hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 958k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 2
classes | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f72b7f5a198735854caf644778be99b784ac4157 | 19,981 | py | Python | Lib/distutils/sysconfig.py | zgrge/cpython | 0e59d247457dde747d84c899e96423647b3da149 | [
"PSF-2.0"
] | null | null | null | Lib/distutils/sysconfig.py | zgrge/cpython | 0e59d247457dde747d84c899e96423647b3da149 | [
"PSF-2.0"
] | null | null | null | Lib/distutils/sysconfig.py | zgrge/cpython | 0e59d247457dde747d84c899e96423647b3da149 | [
"PSF-2.0"
] | 1 | 2021-09-04T13:33:46.000Z | 2021-09-04T13:33:46.000Z | """Provide access to Python's configuration information. The specific
configuration variables available depend heavily on the platform and
configuration. The values may be retrieved using
get_config_var(name), and the list of variables is available via
get_config_vars().keys(). Additional convenience functions are also
available.
Written by: Fred L. Drake, Jr.
Email: <fdrake@acm.org>
"""
import _imp
import os
import re
import sys
from .errors import DistutilsPlatformError
# These are needed in a couple of spots, so just compute them once.
PREFIX = os.path.normpath(sys.prefix)
EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
BASE_PREFIX = os.path.normpath(sys.base_prefix)
BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
# Path to the base directory of the project. On Windows the binary may
# live in project/PCBuild/win32 or project/PCBuild/amd64.
# set for cross builds
if "_PYTHON_PROJECT_BASE" in os.environ:
project_base = os.path.abspath(os.environ["_PYTHON_PROJECT_BASE"])
else:
project_base = os.path.dirname(os.path.abspath(sys.executable))
if (os.name == 'nt' and
project_base.lower().endswith(('\\pcbuild\\win32', '\\pcbuild\\amd64'))):
project_base = os.path.dirname(os.path.dirname(project_base))
# python_build: (Boolean) if true, we're either building Python or
# building an extension with an un-installed Python, so we use
# different (hard-wired) directories.
# Setup.local is available for Makefile builds including VPATH builds,
# Setup.dist is available on Windows
def _is_python_source_dir(d):
for fn in ("Setup.dist", "Setup.local"):
if os.path.isfile(os.path.join(d, "Modules", fn)):
return True
return False
_sys_home = getattr(sys, '_home', None)
if (_sys_home and os.name == 'nt' and
_sys_home.lower().endswith(('\\pcbuild\\win32', '\\pcbuild\\amd64'))):
_sys_home = os.path.dirname(os.path.dirname(_sys_home))
def _python_build():
if _sys_home:
return _is_python_source_dir(_sys_home)
return _is_python_source_dir(project_base)
python_build = _python_build()
# Calculate the build qualifier flags if they are defined. Adding the flags
# to the include and lib directories only makes sense for an installation, not
# an in-source build.
build_flags = ''
try:
if not python_build:
build_flags = sys.abiflags
except AttributeError:
# It's not a configure-based build, so the sys module doesn't have
# this attribute, which is fine.
pass
def get_python_version():
"""Return a string containing the major and minor Python version,
leaving off the patchlevel. Sample return values could be '1.5'
or '2.2'.
"""
return '%d.%d' % sys.version_info[:2]
def get_python_inc(plat_specific=0, prefix=None):
"""Return the directory containing installed Python header files.
If 'plat_specific' is false (the default), this is the path to the
non-platform-specific header files, i.e. Python.h and so on;
otherwise, this is the path to platform-specific header files
(namely pyconfig.h).
If 'prefix' is supplied, use it instead of sys.base_prefix or
sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
"""
if prefix is None:
prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
if os.name == "posix":
if python_build:
# Assume the executable is in the build directory. The
# pyconfig.h file should be in the same directory. Since
# the build directory may not be the source directory, we
# must use "srcdir" from the makefile to find the "Include"
# directory.
base = _sys_home or project_base
if plat_specific:
return base
if _sys_home:
incdir = os.path.join(_sys_home, get_config_var('AST_H_DIR'))
else:
incdir = os.path.join(get_config_var('srcdir'), 'Include')
return os.path.normpath(incdir)
python_dir = 'python' + get_python_version() + build_flags
return os.path.join(prefix, "include", python_dir)
elif os.name == "nt":
return os.path.join(prefix, "include")
else:
raise DistutilsPlatformError(
"I don't know where Python installs its C header files "
"on platform '%s'" % os.name)
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
"""Return the directory containing the Python library (standard or
site additions).
If 'plat_specific' is true, return the directory containing
platform-specific modules, i.e. any module from a non-pure-Python
module distribution; otherwise, return the platform-shared library
directory. If 'standard_lib' is true, return the directory
containing standard Python library modules; otherwise, return the
directory for site-specific modules.
If 'prefix' is supplied, use it instead of sys.base_prefix or
sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
"""
if prefix is None:
if standard_lib:
prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
else:
prefix = plat_specific and EXEC_PREFIX or PREFIX
if os.name == "posix":
libpython = os.path.join(prefix,
"lib", "python" + get_python_version())
if standard_lib:
return libpython
else:
return os.path.join(libpython, "site-packages")
elif os.name == "nt":
if standard_lib:
return os.path.join(prefix, "Lib")
else:
return os.path.join(prefix, "Lib", "site-packages")
else:
raise DistutilsPlatformError(
"I don't know where Python installs its library "
"on platform '%s'" % os.name)
def customize_compiler(compiler):
"""Do any platform-specific customization of a CCompiler instance.
Mainly needed on Unix, so we can plug in the information that
varies across Unices and is stored in Python's Makefile.
"""
if compiler.compiler_type == "unix":
if sys.platform == "darwin":
# Perform first-time customization of compiler-related
# config vars on OS X now that we know we need a compiler.
# This is primarily to support Pythons from binary
# installers. The kind and paths to build tools on
# the user system may vary significantly from the system
# that Python itself was built on. Also the user OS
# version and build tools may not support the same set
# of CPU architectures for universal builds.
global _config_vars
# Use get_config_var() to ensure _config_vars is initialized.
if not get_config_var('CUSTOMIZED_OSX_COMPILER'):
import _osx_support
_osx_support.customize_compiler(_config_vars)
_config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'
(cc, cxx, opt, cflags, ccshared, ldshared, shlib_suffix, ar, ar_flags) = \
get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
'CCSHARED', 'LDSHARED', 'SHLIB_SUFFIX', 'AR', 'ARFLAGS')
if 'CC' in os.environ:
newcc = os.environ['CC']
if (sys.platform == 'darwin'
and 'LDSHARED' not in os.environ
and ldshared.startswith(cc)):
# On OS X, if CC is overridden, use that as the default
# command for LDSHARED as well
ldshared = newcc + ldshared[len(cc):]
cc = newcc
if 'CXX' in os.environ:
cxx = os.environ['CXX']
if 'LDSHARED' in os.environ:
ldshared = os.environ['LDSHARED']
if 'CPP' in os.environ:
cpp = os.environ['CPP']
else:
cpp = cc + " -E" # not always
if 'LDFLAGS' in os.environ:
ldshared = ldshared + ' ' + os.environ['LDFLAGS']
if 'CFLAGS' in os.environ:
cflags = opt + ' ' + os.environ['CFLAGS']
ldshared = ldshared + ' ' + os.environ['CFLAGS']
if 'CPPFLAGS' in os.environ:
cpp = cpp + ' ' + os.environ['CPPFLAGS']
cflags = cflags + ' ' + os.environ['CPPFLAGS']
ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
if 'AR' in os.environ:
ar = os.environ['AR']
if 'ARFLAGS' in os.environ:
archiver = ar + ' ' + os.environ['ARFLAGS']
else:
archiver = ar + ' ' + ar_flags
cc_cmd = cc + ' ' + cflags
compiler.set_executables(
preprocessor=cpp,
compiler=cc_cmd,
compiler_so=cc_cmd + ' ' + ccshared,
compiler_cxx=cxx,
linker_so=ldshared,
linker_exe=cc,
archiver=archiver)
compiler.shared_lib_extension = shlib_suffix
def get_config_h_filename():
"""Return full pathname of installed pyconfig.h file."""
if python_build:
if os.name == "nt":
inc_dir = os.path.join(_sys_home or project_base, "PC")
else:
inc_dir = _sys_home or project_base
else:
inc_dir = get_python_inc(plat_specific=1)
return os.path.join(inc_dir, 'pyconfig.h')
def get_makefile_filename():
"""Return full pathname of installed Makefile from the Python build."""
if python_build:
return os.path.join(_sys_home or project_base, "Makefile")
lib_dir = get_python_lib(plat_specific=0, standard_lib=1)
config_file = 'config-{}{}'.format(get_python_version(), build_flags)
if hasattr(sys.implementation, '_multiarch'):
config_file += '-%s' % sys.implementation._multiarch
return os.path.join(lib_dir, config_file, 'Makefile')
def parse_config_h(fp, g=None):
"""Parse a config.h-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
if g is None:
g = {}
define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
#
while True:
line = fp.readline()
if not line:
break
m = define_rx.match(line)
if m:
n, v = m.group(1, 2)
try: v = int(v)
except ValueError: pass
g[n] = v
else:
m = undef_rx.match(line)
if m:
g[m.group(1)] = 0
return g
# Regexes needed for parsing Makefile (and similar syntaxes,
# like old-style Setup files).
_variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
_findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
_findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
def parse_makefile(fn, g=None):
"""Parse a Makefile-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
from distutils.text_file import TextFile
fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape")
if g is None:
g = {}
done = {}
notdone = {}
while True:
line = fp.readline()
if line is None: # eof
break
m = _variable_rx.match(line)
if m:
n, v = m.group(1, 2)
v = v.strip()
# `$$' is a literal `$' in make
tmpv = v.replace('$$', '')
if "$" in tmpv:
notdone[n] = v
else:
try:
v = int(v)
except ValueError:
# insert literal `$'
done[n] = v.replace('$$', '$')
else:
done[n] = v
# Variables with a 'PY_' prefix in the makefile. These need to
# be made available without that prefix through sysconfig.
# Special care is needed to ensure that variable expansion works, even
# if the expansion uses the name without a prefix.
renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
# do variable interpolation here
while notdone:
for name in list(notdone):
value = notdone[name]
m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
if m:
n = m.group(1)
found = True
if n in done:
item = str(done[n])
elif n in notdone:
# get it on a subsequent round
found = False
elif n in os.environ:
# do it like make: fall back to environment
item = os.environ[n]
elif n in renamed_variables:
if name.startswith('PY_') and name[3:] in renamed_variables:
item = ""
elif 'PY_' + n in notdone:
found = False
else:
item = str(done['PY_' + n])
else:
done[n] = item = ""
if found:
after = value[m.end():]
value = value[:m.start()] + item + after
if "$" in after:
notdone[name] = value
else:
try: value = int(value)
except ValueError:
done[name] = value.strip()
else:
done[name] = value
del notdone[name]
if name.startswith('PY_') \
and name[3:] in renamed_variables:
name = name[3:]
if name not in done:
done[name] = value
else:
# bogus variable reference; just drop it since we can't deal
del notdone[name]
fp.close()
# strip spurious spaces
for k, v in done.items():
if isinstance(v, str):
done[k] = v.strip()
# save the results in the global dictionary
g.update(done)
return g
def expand_makefile_vars(s, vars):
"""Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
'string' according to 'vars' (a dictionary mapping variable names to
values). Variables not present in 'vars' are silently expanded to the
empty string. The variable values in 'vars' should not contain further
variable expansions; if 'vars' is the output of 'parse_makefile()',
you're fine. Returns a variable-expanded version of 's'.
"""
# This algorithm does multiple expansion, so if vars['foo'] contains
# "${bar}", it will expand ${foo} to ${bar}, and then expand
# ${bar}... and so forth. This is fine as long as 'vars' comes from
# 'parse_makefile()', which takes care of such expansions eagerly,
# according to make's variable expansion semantics.
while True:
m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
if m:
(beg, end) = m.span()
s = s[0:beg] + vars.get(m.group(1)) + s[end:]
else:
break
return s
_config_vars = None
def _init_posix():
"""Initialize the module as appropriate for POSIX systems."""
# _sysconfigdata is generated at build time, see the sysconfig module
name = '_sysconfigdata_' + sys.abiflags
_temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
build_time_vars = _temp.build_time_vars
global _config_vars
_config_vars = {}
_config_vars.update(build_time_vars)
def _init_nt():
"""Initialize the module as appropriate for NT"""
g = {}
# set basic install directories
g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
# XXX hmmm.. a normal install puts include files here
g['INCLUDEPY'] = get_python_inc(plat_specific=0)
g['EXT_SUFFIX'] = _imp.extension_suffixes()[0]
g['EXE'] = ".exe"
g['VERSION'] = get_python_version().replace(".", "")
g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))
global _config_vars
_config_vars = g
def get_config_vars(*args):
"""With no arguments, return a dictionary of all configuration
variables relevant for the current platform. Generally this includes
everything needed to build extensions and install both pure modules and
extensions. On Unix, this means every variable defined in Python's
installed Makefile; on Windows it's a much smaller set.
With arguments, return a list of values that result from looking up
each argument in the configuration variable dictionary.
"""
global _config_vars
if _config_vars is None:
func = globals().get("_init_" + os.name)
if func:
func()
else:
_config_vars = {}
# Normalized versions of prefix and exec_prefix are handy to have;
# in fact, these are the standard versions used most places in the
# Distutils.
_config_vars['prefix'] = PREFIX
_config_vars['exec_prefix'] = EXEC_PREFIX
# For backward compatibility, see issue19555
SO = _config_vars.get('EXT_SUFFIX')
if SO is not None:
_config_vars['SO'] = SO
# Always convert srcdir to an absolute path
srcdir = _config_vars.get('srcdir', project_base)
if os.name == 'posix':
if python_build:
# If srcdir is a relative path (typically '.' or '..')
# then it should be interpreted relative to the directory
# containing Makefile.
base = os.path.dirname(get_makefile_filename())
srcdir = os.path.join(base, srcdir)
else:
# srcdir is not meaningful since the installation is
# spread about the filesystem. We choose the
# directory containing the Makefile since we know it
# exists.
srcdir = os.path.dirname(get_makefile_filename())
_config_vars['srcdir'] = os.path.abspath(os.path.normpath(srcdir))
# Convert srcdir into an absolute path if it appears necessary.
# Normally it is relative to the build directory. However, during
# testing, for example, we might be running a non-installed python
# from a different directory.
if python_build and os.name == "posix":
base = project_base
if (not os.path.isabs(_config_vars['srcdir']) and
base != os.getcwd()):
# srcdir is relative and we are not in the same directory
# as the executable. Assume executable is in the build
# directory and make srcdir absolute.
srcdir = os.path.join(base, _config_vars['srcdir'])
_config_vars['srcdir'] = os.path.normpath(srcdir)
# OS X platforms require special customization to handle
# multi-architecture, multi-os-version installers
if sys.platform == 'darwin':
import _osx_support
_osx_support.customize_config_vars(_config_vars)
if args:
vals = []
for name in args:
vals.append(_config_vars.get(name))
return vals
else:
return _config_vars
def get_config_var(name):
"""Return the value of a single variable using the dictionary
returned by 'get_config_vars()'. Equivalent to
get_config_vars().get(name)
"""
if name == 'SO':
import warnings
warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
return get_config_vars().get(name)
| 37.629002 | 94 | 0.598619 |
import _imp
import os
import re
import sys
from .errors import DistutilsPlatformError
PREFIX = os.path.normpath(sys.prefix)
EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
BASE_PREFIX = os.path.normpath(sys.base_prefix)
BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
if "_PYTHON_PROJECT_BASE" in os.environ:
project_base = os.path.abspath(os.environ["_PYTHON_PROJECT_BASE"])
else:
project_base = os.path.dirname(os.path.abspath(sys.executable))
if (os.name == 'nt' and
project_base.lower().endswith(('\\pcbuild\\win32', '\\pcbuild\\amd64'))):
project_base = os.path.dirname(os.path.dirname(project_base))
# building an extension with an un-installed Python, so we use
# different (hard-wired) directories.
# Setup.local is available for Makefile builds including VPATH builds,
# Setup.dist is available on Windows
def _is_python_source_dir(d):
for fn in ("Setup.dist", "Setup.local"):
if os.path.isfile(os.path.join(d, "Modules", fn)):
return True
return False
_sys_home = getattr(sys, '_home', None)
if (_sys_home and os.name == 'nt' and
_sys_home.lower().endswith(('\\pcbuild\\win32', '\\pcbuild\\amd64'))):
_sys_home = os.path.dirname(os.path.dirname(_sys_home))
def _python_build():
if _sys_home:
return _is_python_source_dir(_sys_home)
return _is_python_source_dir(project_base)
python_build = _python_build()
# Calculate the build qualifier flags if they are defined. Adding the flags
# to the include and lib directories only makes sense for an installation, not
# an in-source build.
build_flags = ''
try:
if not python_build:
build_flags = sys.abiflags
except AttributeError:
# It's not a configure-based build, so the sys module doesn't have
# this attribute, which is fine.
pass
def get_python_version():
return '%d.%d' % sys.version_info[:2]
def get_python_inc(plat_specific=0, prefix=None):
if prefix is None:
prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
if os.name == "posix":
if python_build:
# Assume the executable is in the build directory. The
# pyconfig.h file should be in the same directory. Since
# the build directory may not be the source directory, we
# must use "srcdir" from the makefile to find the "Include"
# directory.
base = _sys_home or project_base
if plat_specific:
return base
if _sys_home:
incdir = os.path.join(_sys_home, get_config_var('AST_H_DIR'))
else:
incdir = os.path.join(get_config_var('srcdir'), 'Include')
return os.path.normpath(incdir)
python_dir = 'python' + get_python_version() + build_flags
return os.path.join(prefix, "include", python_dir)
elif os.name == "nt":
return os.path.join(prefix, "include")
else:
raise DistutilsPlatformError(
"I don't know where Python installs its C header files "
"on platform '%s'" % os.name)
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
if prefix is None:
if standard_lib:
prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
else:
prefix = plat_specific and EXEC_PREFIX or PREFIX
if os.name == "posix":
libpython = os.path.join(prefix,
"lib", "python" + get_python_version())
if standard_lib:
return libpython
else:
return os.path.join(libpython, "site-packages")
elif os.name == "nt":
if standard_lib:
return os.path.join(prefix, "Lib")
else:
return os.path.join(prefix, "Lib", "site-packages")
else:
raise DistutilsPlatformError(
"I don't know where Python installs its library "
"on platform '%s'" % os.name)
def customize_compiler(compiler):
if compiler.compiler_type == "unix":
if sys.platform == "darwin":
# Perform first-time customization of compiler-related
# config vars on OS X now that we know we need a compiler.
# This is primarily to support Pythons from binary
# installers. The kind and paths to build tools on
# the user system may vary significantly from the system
# that Python itself was built on. Also the user OS
# version and build tools may not support the same set
# of CPU architectures for universal builds.
global _config_vars
# Use get_config_var() to ensure _config_vars is initialized.
if not get_config_var('CUSTOMIZED_OSX_COMPILER'):
import _osx_support
_osx_support.customize_compiler(_config_vars)
_config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'
(cc, cxx, opt, cflags, ccshared, ldshared, shlib_suffix, ar, ar_flags) = \
get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
'CCSHARED', 'LDSHARED', 'SHLIB_SUFFIX', 'AR', 'ARFLAGS')
if 'CC' in os.environ:
newcc = os.environ['CC']
if (sys.platform == 'darwin'
and 'LDSHARED' not in os.environ
and ldshared.startswith(cc)):
# On OS X, if CC is overridden, use that as the default
# command for LDSHARED as well
ldshared = newcc + ldshared[len(cc):]
cc = newcc
if 'CXX' in os.environ:
cxx = os.environ['CXX']
if 'LDSHARED' in os.environ:
ldshared = os.environ['LDSHARED']
if 'CPP' in os.environ:
cpp = os.environ['CPP']
else:
cpp = cc + " -E" # not always
if 'LDFLAGS' in os.environ:
ldshared = ldshared + ' ' + os.environ['LDFLAGS']
if 'CFLAGS' in os.environ:
cflags = opt + ' ' + os.environ['CFLAGS']
ldshared = ldshared + ' ' + os.environ['CFLAGS']
if 'CPPFLAGS' in os.environ:
cpp = cpp + ' ' + os.environ['CPPFLAGS']
cflags = cflags + ' ' + os.environ['CPPFLAGS']
ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
if 'AR' in os.environ:
ar = os.environ['AR']
if 'ARFLAGS' in os.environ:
archiver = ar + ' ' + os.environ['ARFLAGS']
else:
archiver = ar + ' ' + ar_flags
cc_cmd = cc + ' ' + cflags
compiler.set_executables(
preprocessor=cpp,
compiler=cc_cmd,
compiler_so=cc_cmd + ' ' + ccshared,
compiler_cxx=cxx,
linker_so=ldshared,
linker_exe=cc,
archiver=archiver)
compiler.shared_lib_extension = shlib_suffix
def get_config_h_filename():
if python_build:
if os.name == "nt":
inc_dir = os.path.join(_sys_home or project_base, "PC")
else:
inc_dir = _sys_home or project_base
else:
inc_dir = get_python_inc(plat_specific=1)
return os.path.join(inc_dir, 'pyconfig.h')
def get_makefile_filename():
if python_build:
return os.path.join(_sys_home or project_base, "Makefile")
lib_dir = get_python_lib(plat_specific=0, standard_lib=1)
config_file = 'config-{}{}'.format(get_python_version(), build_flags)
if hasattr(sys.implementation, '_multiarch'):
config_file += '-%s' % sys.implementation._multiarch
return os.path.join(lib_dir, config_file, 'Makefile')
def parse_config_h(fp, g=None):
if g is None:
g = {}
define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
#
while True:
line = fp.readline()
if not line:
break
m = define_rx.match(line)
if m:
n, v = m.group(1, 2)
try: v = int(v)
except ValueError: pass
g[n] = v
else:
m = undef_rx.match(line)
if m:
g[m.group(1)] = 0
return g
# Regexes needed for parsing Makefile (and similar syntaxes,
# like old-style Setup files).
_variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
_findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
_findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
def parse_makefile(fn, g=None):
from distutils.text_file import TextFile
fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape")
if g is None:
g = {}
done = {}
notdone = {}
while True:
line = fp.readline()
if line is None: # eof
break
m = _variable_rx.match(line)
if m:
n, v = m.group(1, 2)
v = v.strip()
# `$$' is a literal `$' in make
tmpv = v.replace('$$', '')
if "$" in tmpv:
notdone[n] = v
else:
try:
v = int(v)
except ValueError:
# insert literal `$'
done[n] = v.replace('$$', '$')
else:
done[n] = v
renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
while notdone:
for name in list(notdone):
value = notdone[name]
m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
if m:
n = m.group(1)
found = True
if n in done:
item = str(done[n])
elif n in notdone:
found = False
elif n in os.environ:
item = os.environ[n]
elif n in renamed_variables:
if name.startswith('PY_') and name[3:] in renamed_variables:
item = ""
elif 'PY_' + n in notdone:
found = False
else:
item = str(done['PY_' + n])
else:
done[n] = item = ""
if found:
after = value[m.end():]
value = value[:m.start()] + item + after
if "$" in after:
notdone[name] = value
else:
try: value = int(value)
except ValueError:
done[name] = value.strip()
else:
done[name] = value
del notdone[name]
if name.startswith('PY_') \
and name[3:] in renamed_variables:
name = name[3:]
if name not in done:
done[name] = value
else:
del notdone[name]
fp.close()
# strip spurious spaces
for k, v in done.items():
if isinstance(v, str):
done[k] = v.strip()
# save the results in the global dictionary
g.update(done)
return g
def expand_makefile_vars(s, vars):
# This algorithm does multiple expansion, so if vars['foo'] contains
# "${bar}", it will expand ${foo} to ${bar}, and then expand
# ${bar}... and so forth. This is fine as long as 'vars' comes from
# 'parse_makefile()', which takes care of such expansions eagerly,
# according to make's variable expansion semantics.
while True:
m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
if m:
(beg, end) = m.span()
s = s[0:beg] + vars.get(m.group(1)) + s[end:]
else:
break
return s
_config_vars = None
def _init_posix():
name = '_sysconfigdata_' + sys.abiflags
_temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
build_time_vars = _temp.build_time_vars
global _config_vars
_config_vars = {}
_config_vars.update(build_time_vars)
def _init_nt():
g = {}
g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
g['INCLUDEPY'] = get_python_inc(plat_specific=0)
g['EXT_SUFFIX'] = _imp.extension_suffixes()[0]
g['EXE'] = ".exe"
g['VERSION'] = get_python_version().replace(".", "")
g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))
global _config_vars
_config_vars = g
def get_config_vars(*args):
global _config_vars
if _config_vars is None:
func = globals().get("_init_" + os.name)
if func:
func()
else:
_config_vars = {}
_config_vars['prefix'] = PREFIX
_config_vars['exec_prefix'] = EXEC_PREFIX
SO = _config_vars.get('EXT_SUFFIX')
if SO is not None:
_config_vars['SO'] = SO
srcdir = _config_vars.get('srcdir', project_base)
if os.name == 'posix':
if python_build:
base = os.path.dirname(get_makefile_filename())
srcdir = os.path.join(base, srcdir)
else:
srcdir = os.path.dirname(get_makefile_filename())
_config_vars['srcdir'] = os.path.abspath(os.path.normpath(srcdir))
if python_build and os.name == "posix":
base = project_base
if (not os.path.isabs(_config_vars['srcdir']) and
base != os.getcwd()):
srcdir = os.path.join(base, _config_vars['srcdir'])
_config_vars['srcdir'] = os.path.normpath(srcdir)
if sys.platform == 'darwin':
import _osx_support
_osx_support.customize_config_vars(_config_vars)
if args:
vals = []
for name in args:
vals.append(_config_vars.get(name))
return vals
else:
return _config_vars
def get_config_var(name):
if name == 'SO':
import warnings
warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
return get_config_vars().get(name)
| true | true |
f72b80495eb53cc9c695a5f53c6e25c1d550506d | 2,820 | py | Python | tack/commands/Command.py | moxie0/TACKpy | 5cd8ee33b4a6eba4ae9fed3582682e2658e4fee2 | [
"Unlicense"
] | 15 | 2015-04-11T03:51:16.000Z | 2022-02-01T10:37:47.000Z | tack/commands/Command.py | moxie0/TACKpy | 5cd8ee33b4a6eba4ae9fed3582682e2658e4fee2 | [
"Unlicense"
] | null | null | null | tack/commands/Command.py | moxie0/TACKpy | 5cd8ee33b4a6eba4ae9fed3582682e2658e4fee2 | [
"Unlicense"
] | 5 | 2016-09-26T17:50:35.000Z | 2022-02-01T10:37:48.000Z | import getopt
import getpass
import sys
import time
from tack.structures.TackKeyFile import TackKeyFile
from tack.util.Time import Time
from tack.version import __version__
from tack.InvalidPasswordException import InvalidPasswordException
class Command:
def __init__(self, argv, options, flags):
try:
self.argv = argv
self.flags = flags
self.options = ":".join(options) + ":"
self.values, self.remainder = getopt.getopt(argv, self.options + self.flags)
except getopt.GetoptError as e:
self.printError(e)
def isVerbose(self):
return self._containsOption("-v")
def getPassword(self):
return self._getOptionValue("-p")
def getKey(self, password):
keyPemFile = self._getOptionValue("-k")
if not keyPemFile:
self.printError("-k missing (TACK Key)")
if not password:
password = self._promptPassword()
try:
keyPemData = open(keyPemFile, "rU").read()
while True:
try:
inKey = TackKeyFile.createFromPem(keyPemData, password)
return inKey
except InvalidPasswordException, ipe:
sys.stderr.write("Password incorrect!\n")
password = self._promptPassword()
except SyntaxError:
self.printError("Error processing TACK Key File")
except IOError:
self.printError("Error opening TACK Key File: %s" % keyPemFile)
def getOutputFile(self):
output = None
try:
output = self._getOptionValue("-o")
if output is None:
return sys.stdout, None
else:
return open(output, "w"), output
except IOError:
self.printError("Error opening output file: %s" % output)
def addPemComments(self, inStr):
"""Add pre-PEM metadata/comments to PEM strings."""
versionStr = __version__
timeStr = Time.posixTimeToStr(time.time(), True)
outStr = "Created by tack.py %s\nCreated at %s\n%s" %\
(versionStr, timeStr, inStr)
return outStr
def _promptPassword(self):
return getpass.getpass("Enter password for key file: ")
def _getOptionValue(self, flag):
for option, value in self.values:
if option == flag:
return value
return None
def _containsOption(self, flag):
for option, value in self.values:
if option == flag:
return True
def printError(self, error):
"""Print error message and exit"""
sys.stderr.write("ERROR: %s\n" % error)
sys.exit(-1)
| 30 | 88 | 0.569858 | import getopt
import getpass
import sys
import time
from tack.structures.TackKeyFile import TackKeyFile
from tack.util.Time import Time
from tack.version import __version__
from tack.InvalidPasswordException import InvalidPasswordException
class Command:
def __init__(self, argv, options, flags):
try:
self.argv = argv
self.flags = flags
self.options = ":".join(options) + ":"
self.values, self.remainder = getopt.getopt(argv, self.options + self.flags)
except getopt.GetoptError as e:
self.printError(e)
def isVerbose(self):
return self._containsOption("-v")
def getPassword(self):
return self._getOptionValue("-p")
def getKey(self, password):
keyPemFile = self._getOptionValue("-k")
if not keyPemFile:
self.printError("-k missing (TACK Key)")
if not password:
password = self._promptPassword()
try:
keyPemData = open(keyPemFile, "rU").read()
while True:
try:
inKey = TackKeyFile.createFromPem(keyPemData, password)
return inKey
except InvalidPasswordException, ipe:
sys.stderr.write("Password incorrect!\n")
password = self._promptPassword()
except SyntaxError:
self.printError("Error processing TACK Key File")
except IOError:
self.printError("Error opening TACK Key File: %s" % keyPemFile)
def getOutputFile(self):
output = None
try:
output = self._getOptionValue("-o")
if output is None:
return sys.stdout, None
else:
return open(output, "w"), output
except IOError:
self.printError("Error opening output file: %s" % output)
def addPemComments(self, inStr):
"""Add pre-PEM metadata/comments to PEM strings."""
versionStr = __version__
timeStr = Time.posixTimeToStr(time.time(), True)
outStr = "Created by tack.py %s\nCreated at %s\n%s" %\
(versionStr, timeStr, inStr)
return outStr
def _promptPassword(self):
return getpass.getpass("Enter password for key file: ")
def _getOptionValue(self, flag):
for option, value in self.values:
if option == flag:
return value
return None
def _containsOption(self, flag):
for option, value in self.values:
if option == flag:
return True
def printError(self, error):
"""Print error message and exit"""
sys.stderr.write("ERROR: %s\n" % error)
sys.exit(-1)
| false | true |
f72b8091065be3b6530f5a20ec604f2dd1b4fe73 | 5,012 | py | Python | core/routine.py | cybert79/Osmedeus | 684d853144e2f85343c3367440120142455f296b | [
"MIT"
] | 1 | 2019-07-14T20:48:19.000Z | 2019-07-14T20:48:19.000Z | core/routine.py | KbaHaxor/Osmedeus | 0894d52ad5949e9151b0fd05d9746ecafc8057b5 | [
"MIT"
] | null | null | null | core/routine.py | KbaHaxor/Osmedeus | 0894d52ad5949e9151b0fd05d9746ecafc8057b5 | [
"MIT"
] | null | null | null | import sys, time
from core import utils
from pprint import pprint
from modules import initials
from modules import subdomain
from modules import recon
from modules import assetfinding
from modules import takeover
from modules import screenshot
from modules import portscan
from modules import gitscan
from modules import burpstate
from modules import brutethings
from modules import dirbrute
from modules import vulnscan
from modules import cors
from modules import ipspace
from modules import sslscan
from modules import headers
from modules import conclusion
from modules import healcheck
# runnning normal routine if none of module specific
def normal(options):
utils.print_good("Running with {0} speed".format(options['SPEED']))
# Create skeleton json
initials.Initials(options)
# Finding subdomain
subdomain.SubdomainScanning(options)
# waiting for previous module
utils.just_waiting(options, 'SubdomainScanning')
# Scanning for subdomain take over
takeover.TakeOverScanning(options)
# Screen shot the target on common service
screenshot.ScreenShot(options)
# Recon
recon.Recon(options)
# Recon
assetfinding.AssetFinding(options)
# Scanning for CorsScan
cors.CorsScan(options)
# Discovery IP space
ipspace.IPSpace(options)
# SSL Scan
sslscan.SSLScan(options)
# Headers Scan
headers.HeadersScan(options)
# Note: From here the module gonna take really long time
# for scanning service and stuff like that
utils.print_info('This gonna take a while')
# Scanning all port using result from subdomain scanning
# and also checking vulnerable service based on version
portscan.PortScan(options)
# Directory scan
dirbrute.DirBrute(options)
# Starting vulnerable scan
vulnscan.VulnScan(options)
# brutethings.BruteThings(options)
conclusion.Conclusion(options)
def specific(options, module):
module = module.lower()
# checking the tool is installed right or not and exit
if 'health' in module:
health = healcheck.Healcheck(options)
if health.checking():
utils.print_good("All things look fine")
else:
utils.print_bad("Installing Osmedeus not correctly done")
utils.just_shutdown_flask(options)
sys.exit(0)
initials.Initials(options)
if 'sub' in module or 'subdomain' in module:
subdomain.SubdomainScanning(options)
takeover.TakeOverScanning(options)
screenshot.ScreenShot(options)
cors.CorsScan(options)
recon.Recon(options)
assetfinding.AssetFinding(options)
if 'ip' in module:
# Discovery IP space
ipspace.IPSpace(options)
if 'screen' in module:
# Discovery IP space
screenshot.ScreenShot(options)
if 'portscan' in module:
# scanning port, service and vuln with masscan and nmap
portscan.PortScan(options)
if 'headers' in module:
headers.HeadersScan(options)
if 'asset' in module:
assetfinding.AssetFinding(options)
if 'vuln' in module:
# scanning vulnerable service based on version
vulnscan.VulnScan(options)
if 'dir' in module:
# run blind directory brute force directly
dirbrute.DirBrute(options)
if 'brute' in module or 'force' in module:
# running brute force things based on scanning result
brutethings.BruteThings(options)
if 'git' in module:
gitscan.GitScan(options)
# if 'burp' in module:
# burpstate.BurpState(options)
conclusion.Conclusion(options)
# just for debug purpose
def debug(options):
utils.print_good("Debug routine")
utils.print_good("Running with {0} speed".format(options['SPEED']))
# Create skeleton json
pprint(options)
initials.Initials(options)
# ##Finding subdomain
subdomain.SubdomainScanning(options)
# ####waiting for previous module
# utils.just_waiting(options, 'SubdomainScanning')
# recon.Recon(options)
# ###Screen shot the target on common service
screenshot.ScreenShot(options)
# ###Scanning for subdomain take over
# takeover.TakeOverScanning(options)
# ##Discovery IP space
# ipspace.IPSpace(options)
# # # ##Scanning for CorsScan
# cors.CorsScan(options)
# ### SSL Scan
# sslscan.SSLScan(options)
# ##Headers Scan
# headers.HeadersScan(options)
# ##### Note: From here the module gonna take really long time for scanning service and stuff like that
# utils.print_info('This gonna take a while')
# dirbrute.DirBrute(options)
# #Scanning all port using result from subdomain scanning and also checking vulnerable service based on version
# portscan.PortScan(options)
# # #Starting vulnerable scan
# vulnscan.VulnScan(options)
# # #Brute force service from port scan result
# # brutethings.BruteThings(options)
# conclusion.Conclusion(options)
| 25.441624 | 115 | 0.70012 | import sys, time
from core import utils
from pprint import pprint
from modules import initials
from modules import subdomain
from modules import recon
from modules import assetfinding
from modules import takeover
from modules import screenshot
from modules import portscan
from modules import gitscan
from modules import burpstate
from modules import brutethings
from modules import dirbrute
from modules import vulnscan
from modules import cors
from modules import ipspace
from modules import sslscan
from modules import headers
from modules import conclusion
from modules import healcheck
def normal(options):
utils.print_good("Running with {0} speed".format(options['SPEED']))
initials.Initials(options)
subdomain.SubdomainScanning(options)
utils.just_waiting(options, 'SubdomainScanning')
takeover.TakeOverScanning(options)
screenshot.ScreenShot(options)
recon.Recon(options)
assetfinding.AssetFinding(options)
cors.CorsScan(options)
ipspace.IPSpace(options)
sslscan.SSLScan(options)
headers.HeadersScan(options)
utils.print_info('This gonna take a while')
portscan.PortScan(options)
dirbrute.DirBrute(options)
vulnscan.VulnScan(options)
conclusion.Conclusion(options)
def specific(options, module):
module = module.lower()
if 'health' in module:
health = healcheck.Healcheck(options)
if health.checking():
utils.print_good("All things look fine")
else:
utils.print_bad("Installing Osmedeus not correctly done")
utils.just_shutdown_flask(options)
sys.exit(0)
initials.Initials(options)
if 'sub' in module or 'subdomain' in module:
subdomain.SubdomainScanning(options)
takeover.TakeOverScanning(options)
screenshot.ScreenShot(options)
cors.CorsScan(options)
recon.Recon(options)
assetfinding.AssetFinding(options)
if 'ip' in module:
ipspace.IPSpace(options)
if 'screen' in module:
screenshot.ScreenShot(options)
if 'portscan' in module:
portscan.PortScan(options)
if 'headers' in module:
headers.HeadersScan(options)
if 'asset' in module:
assetfinding.AssetFinding(options)
if 'vuln' in module:
vulnscan.VulnScan(options)
if 'dir' in module:
dirbrute.DirBrute(options)
if 'brute' in module or 'force' in module:
brutethings.BruteThings(options)
if 'git' in module:
gitscan.GitScan(options)
conclusion.Conclusion(options)
def debug(options):
utils.print_good("Debug routine")
utils.print_good("Running with {0} speed".format(options['SPEED']))
pprint(options)
initials.Initials(options)
ons)
| true | true |
f72b81d4193fded68a3f2f0d2fc449f357b11230 | 108,819 | py | Python | synapse/handlers/federation.py | V02460/synapse | 782dd72037cf71fb3f9e4922b07c56df2f59de75 | [
"Apache-2.0"
] | null | null | null | synapse/handlers/federation.py | V02460/synapse | 782dd72037cf71fb3f9e4922b07c56df2f59de75 | [
"Apache-2.0"
] | null | null | null | synapse/handlers/federation.py | V02460/synapse | 782dd72037cf71fb3f9e4922b07c56df2f59de75 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2017-2018 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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.
"""Contains handlers for federation events."""
import itertools
import logging
import six
from six import iteritems, itervalues
from six.moves import http_client, zip
from signedjson.key import decode_verify_key_bytes
from signedjson.sign import verify_signed_json
from unpaddedbase64 import decode_base64
from twisted.internet import defer
from synapse.api.constants import EventTypes, Membership, RejectedReason
from synapse.api.errors import (
AuthError,
CodeMessageException,
Codes,
FederationDeniedError,
FederationError,
RequestSendFailed,
StoreError,
SynapseError,
)
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersions
from synapse.crypto.event_signing import compute_event_signature
from synapse.event_auth import auth_types_for_event
from synapse.events.validator import EventValidator
from synapse.logging.context import (
make_deferred_yieldable,
nested_logging_context,
preserve_fn,
run_in_background,
)
from synapse.logging.utils import log_function
from synapse.replication.http.federation import (
ReplicationCleanRoomRestServlet,
ReplicationFederationSendEventsRestServlet,
)
from synapse.replication.http.membership import ReplicationUserJoinedLeftRoomRestServlet
from synapse.state import StateResolutionStore, resolve_events_with_store
from synapse.types import UserID, get_domain_from_id
from synapse.util import unwrapFirstError
from synapse.util.async_helpers import Linearizer
from synapse.util.distributor import user_joined_room
from synapse.util.retryutils import NotRetryingDestination
from synapse.visibility import filter_events_for_server
from ._base import BaseHandler
logger = logging.getLogger(__name__)
def shortstr(iterable, maxitems=5):
"""If iterable has maxitems or fewer, return the stringification of a list
containing those items.
Otherwise, return the stringification of a a list with the first maxitems items,
followed by "...".
Args:
iterable (Iterable): iterable to truncate
maxitems (int): number of items to return before truncating
Returns:
unicode
"""
items = list(itertools.islice(iterable, maxitems + 1))
if len(items) <= maxitems:
return str(items)
return "[" + ", ".join(repr(r) for r in items[:maxitems]) + ", ...]"
class FederationHandler(BaseHandler):
"""Handles events that originated from federation.
Responsible for:
a) handling received Pdus before handing them on as Events to the rest
of the home server (including auth and state conflict resoultion)
b) converting events that were produced by local clients that may need
to be sent to remote home servers.
c) doing the necessary dances to invite remote users and join remote
rooms.
"""
def __init__(self, hs):
super(FederationHandler, self).__init__(hs)
self.hs = hs
self.store = hs.get_datastore()
self.federation_client = hs.get_federation_client()
self.state_handler = hs.get_state_handler()
self.server_name = hs.hostname
self.keyring = hs.get_keyring()
self.action_generator = hs.get_action_generator()
self.is_mine_id = hs.is_mine_id
self.pusher_pool = hs.get_pusherpool()
self.spam_checker = hs.get_spam_checker()
self.event_creation_handler = hs.get_event_creation_handler()
self._server_notices_mxid = hs.config.server_notices_mxid
self.config = hs.config
self.http_client = hs.get_simple_http_client()
self._send_events_to_master = ReplicationFederationSendEventsRestServlet.make_client(
hs
)
self._notify_user_membership_change = ReplicationUserJoinedLeftRoomRestServlet.make_client(
hs
)
self._clean_room_for_join_client = ReplicationCleanRoomRestServlet.make_client(
hs
)
# When joining a room we need to queue any events for that room up
self.room_queues = {}
self._room_pdu_linearizer = Linearizer("fed_room_pdu")
self.third_party_event_rules = hs.get_third_party_event_rules()
@defer.inlineCallbacks
def on_receive_pdu(self, origin, pdu, sent_to_us_directly=False):
""" Process a PDU received via a federation /send/ transaction, or
via backfill of missing prev_events
Args:
origin (str): server which initiated the /send/ transaction. Will
be used to fetch missing events or state.
pdu (FrozenEvent): received PDU
sent_to_us_directly (bool): True if this event was pushed to us; False if
we pulled it as the result of a missing prev_event.
Returns (Deferred): completes with None
"""
room_id = pdu.room_id
event_id = pdu.event_id
logger.info("[%s %s] handling received PDU: %s", room_id, event_id, pdu)
# We reprocess pdus when we have seen them only as outliers
existing = yield self.store.get_event(
event_id, allow_none=True, allow_rejected=True
)
# FIXME: Currently we fetch an event again when we already have it
# if it has been marked as an outlier.
already_seen = existing and (
not existing.internal_metadata.is_outlier()
or pdu.internal_metadata.is_outlier()
)
if already_seen:
logger.debug("[%s %s]: Already seen pdu", room_id, event_id)
return
# do some initial sanity-checking of the event. In particular, make
# sure it doesn't have hundreds of prev_events or auth_events, which
# could cause a huge state resolution or cascade of event fetches.
try:
self._sanity_check_event(pdu)
except SynapseError as err:
logger.warn(
"[%s %s] Received event failed sanity checks", room_id, event_id
)
raise FederationError("ERROR", err.code, err.msg, affected=pdu.event_id)
# If we are currently in the process of joining this room, then we
# queue up events for later processing.
if room_id in self.room_queues:
logger.info(
"[%s %s] Queuing PDU from %s for now: join in progress",
room_id,
event_id,
origin,
)
self.room_queues[room_id].append((pdu, origin))
return
# If we're not in the room just ditch the event entirely. This is
# probably an old server that has come back and thinks we're still in
# the room (or we've been rejoined to the room by a state reset).
#
# Note that if we were never in the room then we would have already
# dropped the event, since we wouldn't know the room version.
is_in_room = yield self.auth.check_host_in_room(room_id, self.server_name)
if not is_in_room:
logger.info(
"[%s %s] Ignoring PDU from %s as we're not in the room",
room_id,
event_id,
origin,
)
return None
state = None
auth_chain = []
# Get missing pdus if necessary.
if not pdu.internal_metadata.is_outlier():
# We only backfill backwards to the min depth.
min_depth = yield self.get_min_depth_for_context(pdu.room_id)
logger.debug("[%s %s] min_depth: %d", room_id, event_id, min_depth)
prevs = set(pdu.prev_event_ids())
seen = yield self.store.have_seen_events(prevs)
if min_depth and pdu.depth < min_depth:
# This is so that we don't notify the user about this
# message, to work around the fact that some events will
# reference really really old events we really don't want to
# send to the clients.
pdu.internal_metadata.outlier = True
elif min_depth and pdu.depth > min_depth:
missing_prevs = prevs - seen
if sent_to_us_directly and missing_prevs:
# If we're missing stuff, ensure we only fetch stuff one
# at a time.
logger.info(
"[%s %s] Acquiring room lock to fetch %d missing prev_events: %s",
room_id,
event_id,
len(missing_prevs),
shortstr(missing_prevs),
)
with (yield self._room_pdu_linearizer.queue(pdu.room_id)):
logger.info(
"[%s %s] Acquired room lock to fetch %d missing prev_events",
room_id,
event_id,
len(missing_prevs),
)
yield self._get_missing_events_for_pdu(
origin, pdu, prevs, min_depth
)
# Update the set of things we've seen after trying to
# fetch the missing stuff
seen = yield self.store.have_seen_events(prevs)
if not prevs - seen:
logger.info(
"[%s %s] Found all missing prev_events",
room_id,
event_id,
)
elif missing_prevs:
logger.info(
"[%s %s] Not recursively fetching %d missing prev_events: %s",
room_id,
event_id,
len(missing_prevs),
shortstr(missing_prevs),
)
if prevs - seen:
# We've still not been able to get all of the prev_events for this event.
#
# In this case, we need to fall back to asking another server in the
# federation for the state at this event. That's ok provided we then
# resolve the state against other bits of the DAG before using it (which
# will ensure that you can't just take over a room by sending an event,
# withholding its prev_events, and declaring yourself to be an admin in
# the subsequent state request).
#
# Now, if we're pulling this event as a missing prev_event, then clearly
# this event is not going to become the only forward-extremity and we are
# guaranteed to resolve its state against our existing forward
# extremities, so that should be fine.
#
# On the other hand, if this event was pushed to us, it is possible for
# it to become the only forward-extremity in the room, and we would then
# trust its state to be the state for the whole room. This is very bad.
# Further, if the event was pushed to us, there is no excuse for us not to
# have all the prev_events. We therefore reject any such events.
#
# XXX this really feels like it could/should be merged with the above,
# but there is an interaction with min_depth that I'm not really
# following.
if sent_to_us_directly:
logger.warn(
"[%s %s] Rejecting: failed to fetch %d prev events: %s",
room_id,
event_id,
len(prevs - seen),
shortstr(prevs - seen),
)
raise FederationError(
"ERROR",
403,
(
"Your server isn't divulging details about prev_events "
"referenced in this event."
),
affected=pdu.event_id,
)
# Calculate the state after each of the previous events, and
# resolve them to find the correct state at the current event.
auth_chains = set()
event_map = {event_id: pdu}
try:
# Get the state of the events we know about
ours = yield self.store.get_state_groups_ids(room_id, seen)
# state_maps is a list of mappings from (type, state_key) to event_id
state_maps = list(
ours.values()
) # type: list[dict[tuple[str, str], str]]
# we don't need this any more, let's delete it.
del ours
# Ask the remote server for the states we don't
# know about
for p in prevs - seen:
logger.info(
"[%s %s] Requesting state at missing prev_event %s",
room_id,
event_id,
p,
)
room_version = yield self.store.get_room_version(room_id)
with nested_logging_context(p):
# note that if any of the missing prevs share missing state or
# auth events, the requests to fetch those events are deduped
# by the get_pdu_cache in federation_client.
remote_state, got_auth_chain = (
yield self.federation_client.get_state_for_room(
origin, room_id, p
)
)
# we want the state *after* p; get_state_for_room returns the
# state *before* p.
remote_event = yield self.federation_client.get_pdu(
[origin], p, room_version, outlier=True
)
if remote_event is None:
raise Exception(
"Unable to get missing prev_event %s" % (p,)
)
if remote_event.is_state():
remote_state.append(remote_event)
# XXX hrm I'm not convinced that duplicate events will compare
# for equality, so I'm not sure this does what the author
# hoped.
auth_chains.update(got_auth_chain)
remote_state_map = {
(x.type, x.state_key): x.event_id for x in remote_state
}
state_maps.append(remote_state_map)
for x in remote_state:
event_map[x.event_id] = x
state_map = yield resolve_events_with_store(
room_version,
state_maps,
event_map,
state_res_store=StateResolutionStore(self.store),
)
# We need to give _process_received_pdu the actual state events
# rather than event ids, so generate that now.
# First though we need to fetch all the events that are in
# state_map, so we can build up the state below.
evs = yield self.store.get_events(
list(state_map.values()),
get_prev_content=False,
check_redacted=False,
)
event_map.update(evs)
state = [event_map[e] for e in six.itervalues(state_map)]
auth_chain = list(auth_chains)
except Exception:
logger.warn(
"[%s %s] Error attempting to resolve state at missing "
"prev_events",
room_id,
event_id,
exc_info=True,
)
raise FederationError(
"ERROR",
403,
"We can't get valid state history.",
affected=event_id,
)
yield self._process_received_pdu(
origin, pdu, state=state, auth_chain=auth_chain
)
@defer.inlineCallbacks
def _get_missing_events_for_pdu(self, origin, pdu, prevs, min_depth):
"""
Args:
origin (str): Origin of the pdu. Will be called to get the missing events
pdu: received pdu
prevs (set(str)): List of event ids which we are missing
min_depth (int): Minimum depth of events to return.
"""
room_id = pdu.room_id
event_id = pdu.event_id
seen = yield self.store.have_seen_events(prevs)
if not prevs - seen:
return
latest = yield self.store.get_latest_event_ids_in_room(room_id)
# We add the prev events that we have seen to the latest
# list to ensure the remote server doesn't give them to us
latest = set(latest)
latest |= seen
logger.info(
"[%s %s]: Requesting missing events between %s and %s",
room_id,
event_id,
shortstr(latest),
event_id,
)
# XXX: we set timeout to 10s to help workaround
# https://github.com/matrix-org/synapse/issues/1733.
# The reason is to avoid holding the linearizer lock
# whilst processing inbound /send transactions, causing
# FDs to stack up and block other inbound transactions
# which empirically can currently take up to 30 minutes.
#
# N.B. this explicitly disables retry attempts.
#
# N.B. this also increases our chances of falling back to
# fetching fresh state for the room if the missing event
# can't be found, which slightly reduces our security.
# it may also increase our DAG extremity count for the room,
# causing additional state resolution? See #1760.
# However, fetching state doesn't hold the linearizer lock
# apparently.
#
# see https://github.com/matrix-org/synapse/pull/1744
#
# ----
#
# Update richvdh 2018/09/18: There are a number of problems with timing this
# request out agressively on the client side:
#
# - it plays badly with the server-side rate-limiter, which starts tarpitting you
# if you send too many requests at once, so you end up with the server carefully
# working through the backlog of your requests, which you have already timed
# out.
#
# - for this request in particular, we now (as of
# https://github.com/matrix-org/synapse/pull/3456) reject any PDUs where the
# server can't produce a plausible-looking set of prev_events - so we becone
# much more likely to reject the event.
#
# - contrary to what it says above, we do *not* fall back to fetching fresh state
# for the room if get_missing_events times out. Rather, we give up processing
# the PDU whose prevs we are missing, which then makes it much more likely that
# we'll end up back here for the *next* PDU in the list, which exacerbates the
# problem.
#
# - the agressive 10s timeout was introduced to deal with incoming federation
# requests taking 8 hours to process. It's not entirely clear why that was going
# on; certainly there were other issues causing traffic storms which are now
# resolved, and I think in any case we may be more sensible about our locking
# now. We're *certainly* more sensible about our logging.
#
# All that said: Let's try increasing the timout to 60s and see what happens.
try:
missing_events = yield self.federation_client.get_missing_events(
origin,
room_id,
earliest_events_ids=list(latest),
latest_events=[pdu],
limit=10,
min_depth=min_depth,
timeout=60000,
)
except RequestSendFailed as e:
# We failed to get the missing events, but since we need to handle
# the case of `get_missing_events` not returning the necessary
# events anyway, it is safe to simply log the error and continue.
logger.warn("[%s %s]: Failed to get prev_events: %s", room_id, event_id, e)
return
logger.info(
"[%s %s]: Got %d prev_events: %s",
room_id,
event_id,
len(missing_events),
shortstr(missing_events),
)
# We want to sort these by depth so we process them and
# tell clients about them in order.
missing_events.sort(key=lambda x: x.depth)
for ev in missing_events:
logger.info(
"[%s %s] Handling received prev_event %s",
room_id,
event_id,
ev.event_id,
)
with nested_logging_context(ev.event_id):
try:
yield self.on_receive_pdu(origin, ev, sent_to_us_directly=False)
except FederationError as e:
if e.code == 403:
logger.warn(
"[%s %s] Received prev_event %s failed history check.",
room_id,
event_id,
ev.event_id,
)
else:
raise
@defer.inlineCallbacks
def _process_received_pdu(self, origin, event, state, auth_chain):
""" Called when we have a new pdu. We need to do auth checks and put it
through the StateHandler.
"""
room_id = event.room_id
event_id = event.event_id
logger.debug("[%s %s] Processing event: %s", room_id, event_id, event)
event_ids = set()
if state:
event_ids |= {e.event_id for e in state}
if auth_chain:
event_ids |= {e.event_id for e in auth_chain}
seen_ids = yield self.store.have_seen_events(event_ids)
if state and auth_chain is not None:
# If we have any state or auth_chain given to us by the replication
# layer, then we should handle them (if we haven't before.)
event_infos = []
for e in itertools.chain(auth_chain, state):
if e.event_id in seen_ids:
continue
e.internal_metadata.outlier = True
auth_ids = e.auth_event_ids()
auth = {
(e.type, e.state_key): e
for e in auth_chain
if e.event_id in auth_ids or e.type == EventTypes.Create
}
event_infos.append({"event": e, "auth_events": auth})
seen_ids.add(e.event_id)
logger.info(
"[%s %s] persisting newly-received auth/state events %s",
room_id,
event_id,
[e["event"].event_id for e in event_infos],
)
yield self._handle_new_events(origin, event_infos)
try:
context = yield self._handle_new_event(origin, event, state=state)
except AuthError as e:
raise FederationError("ERROR", e.code, e.msg, affected=event.event_id)
room = yield self.store.get_room(room_id)
if not room:
try:
yield self.store.store_room(
room_id=room_id, room_creator_user_id="", is_public=False
)
except StoreError:
logger.exception("Failed to store room.")
if event.type == EventTypes.Member:
if event.membership == Membership.JOIN:
# Only fire user_joined_room if the user has acutally
# joined the room. Don't bother if the user is just
# changing their profile info.
newly_joined = True
prev_state_ids = yield context.get_prev_state_ids(self.store)
prev_state_id = prev_state_ids.get((event.type, event.state_key))
if prev_state_id:
prev_state = yield self.store.get_event(
prev_state_id, allow_none=True
)
if prev_state and prev_state.membership == Membership.JOIN:
newly_joined = False
if newly_joined:
user = UserID.from_string(event.state_key)
yield self.user_joined_room(user, room_id)
@log_function
@defer.inlineCallbacks
def backfill(self, dest, room_id, limit, extremities):
""" Trigger a backfill request to `dest` for the given `room_id`
This will attempt to get more events from the remote. If the other side
has no new events to offer, this will return an empty list.
As the events are received, we check their signatures, and also do some
sanity-checking on them. If any of the backfilled events are invalid,
this method throws a SynapseError.
TODO: make this more useful to distinguish failures of the remote
server from invalid events (there is probably no point in trying to
re-fetch invalid events from every other HS in the room.)
"""
if dest == self.server_name:
raise SynapseError(400, "Can't backfill from self.")
room_version = yield self.store.get_room_version(room_id)
events = yield self.federation_client.backfill(
dest, room_id, limit=limit, extremities=extremities
)
# ideally we'd sanity check the events here for excess prev_events etc,
# but it's hard to reject events at this point without completely
# breaking backfill in the same way that it is currently broken by
# events whose signature we cannot verify (#3121).
#
# So for now we accept the events anyway. #3124 tracks this.
#
# for ev in events:
# self._sanity_check_event(ev)
# Don't bother processing events we already have.
seen_events = yield self.store.have_events_in_timeline(
set(e.event_id for e in events)
)
events = [e for e in events if e.event_id not in seen_events]
if not events:
return []
event_map = {e.event_id: e for e in events}
event_ids = set(e.event_id for e in events)
edges = [ev.event_id for ev in events if set(ev.prev_event_ids()) - event_ids]
logger.info("backfill: Got %d events with %d edges", len(events), len(edges))
# For each edge get the current state.
auth_events = {}
state_events = {}
events_to_state = {}
for e_id in edges:
state, auth = yield self.federation_client.get_state_for_room(
destination=dest, room_id=room_id, event_id=e_id
)
auth_events.update({a.event_id: a for a in auth})
auth_events.update({s.event_id: s for s in state})
state_events.update({s.event_id: s for s in state})
events_to_state[e_id] = state
required_auth = set(
a_id
for event in events
+ list(state_events.values())
+ list(auth_events.values())
for a_id in event.auth_event_ids()
)
auth_events.update(
{e_id: event_map[e_id] for e_id in required_auth if e_id in event_map}
)
missing_auth = required_auth - set(auth_events)
failed_to_fetch = set()
# Try and fetch any missing auth events from both DB and remote servers.
# We repeatedly do this until we stop finding new auth events.
while missing_auth - failed_to_fetch:
logger.info("Missing auth for backfill: %r", missing_auth)
ret_events = yield self.store.get_events(missing_auth - failed_to_fetch)
auth_events.update(ret_events)
required_auth.update(
a_id for event in ret_events.values() for a_id in event.auth_event_ids()
)
missing_auth = required_auth - set(auth_events)
if missing_auth - failed_to_fetch:
logger.info(
"Fetching missing auth for backfill: %r",
missing_auth - failed_to_fetch,
)
results = yield make_deferred_yieldable(
defer.gatherResults(
[
run_in_background(
self.federation_client.get_pdu,
[dest],
event_id,
room_version=room_version,
outlier=True,
timeout=10000,
)
for event_id in missing_auth - failed_to_fetch
],
consumeErrors=True,
)
).addErrback(unwrapFirstError)
auth_events.update({a.event_id: a for a in results if a})
required_auth.update(
a_id
for event in results
if event
for a_id in event.auth_event_ids()
)
missing_auth = required_auth - set(auth_events)
failed_to_fetch = missing_auth - set(auth_events)
seen_events = yield self.store.have_seen_events(
set(auth_events.keys()) | set(state_events.keys())
)
# We now have a chunk of events plus associated state and auth chain to
# persist. We do the persistence in two steps:
# 1. Auth events and state get persisted as outliers, plus the
# backward extremities get persisted (as non-outliers).
# 2. The rest of the events in the chunk get persisted one by one, as
# each one depends on the previous event for its state.
#
# The important thing is that events in the chunk get persisted as
# non-outliers, including when those events are also in the state or
# auth chain. Caution must therefore be taken to ensure that they are
# not accidentally marked as outliers.
# Step 1a: persist auth events that *don't* appear in the chunk
ev_infos = []
for a in auth_events.values():
# We only want to persist auth events as outliers that we haven't
# seen and aren't about to persist as part of the backfilled chunk.
if a.event_id in seen_events or a.event_id in event_map:
continue
a.internal_metadata.outlier = True
ev_infos.append(
{
"event": a,
"auth_events": {
(
auth_events[a_id].type,
auth_events[a_id].state_key,
): auth_events[a_id]
for a_id in a.auth_event_ids()
if a_id in auth_events
},
}
)
# Step 1b: persist the events in the chunk we fetched state for (i.e.
# the backwards extremities) as non-outliers.
for e_id in events_to_state:
# For paranoia we ensure that these events are marked as
# non-outliers
ev = event_map[e_id]
assert not ev.internal_metadata.is_outlier()
ev_infos.append(
{
"event": ev,
"state": events_to_state[e_id],
"auth_events": {
(
auth_events[a_id].type,
auth_events[a_id].state_key,
): auth_events[a_id]
for a_id in ev.auth_event_ids()
if a_id in auth_events
},
}
)
yield self._handle_new_events(dest, ev_infos, backfilled=True)
# Step 2: Persist the rest of the events in the chunk one by one
events.sort(key=lambda e: e.depth)
for event in events:
if event in events_to_state:
continue
# For paranoia we ensure that these events are marked as
# non-outliers
assert not event.internal_metadata.is_outlier()
# We store these one at a time since each event depends on the
# previous to work out the state.
# TODO: We can probably do something more clever here.
yield self._handle_new_event(dest, event, backfilled=True)
return events
@defer.inlineCallbacks
def maybe_backfill(self, room_id, current_depth):
"""Checks the database to see if we should backfill before paginating,
and if so do.
"""
extremities = yield self.store.get_oldest_events_with_depth_in_room(room_id)
if not extremities:
logger.debug("Not backfilling as no extremeties found.")
return
# We only want to paginate if we can actually see the events we'll get,
# as otherwise we'll just spend a lot of resources to get redacted
# events.
#
# We do this by filtering all the backwards extremities and seeing if
# any remain. Given we don't have the extremity events themselves, we
# need to actually check the events that reference them.
#
# *Note*: the spec wants us to keep backfilling until we reach the start
# of the room in case we are allowed to see some of the history. However
# in practice that causes more issues than its worth, as a) its
# relatively rare for there to be any visible history and b) even when
# there is its often sufficiently long ago that clients would stop
# attempting to paginate before backfill reached the visible history.
#
# TODO: If we do do a backfill then we should filter the backwards
# extremities to only include those that point to visible portions of
# history.
#
# TODO: Correctly handle the case where we are allowed to see the
# forward event but not the backward extremity, e.g. in the case of
# initial join of the server where we are allowed to see the join
# event but not anything before it. This would require looking at the
# state *before* the event, ignoring the special casing certain event
# types have.
forward_events = yield self.store.get_successor_events(list(extremities))
extremities_events = yield self.store.get_events(
forward_events, check_redacted=False, get_prev_content=False
)
# We set `check_history_visibility_only` as we might otherwise get false
# positives from users having been erased.
filtered_extremities = yield filter_events_for_server(
self.store,
self.server_name,
list(extremities_events.values()),
redact=False,
check_history_visibility_only=True,
)
if not filtered_extremities:
return False
# Check if we reached a point where we should start backfilling.
sorted_extremeties_tuple = sorted(extremities.items(), key=lambda e: -int(e[1]))
max_depth = sorted_extremeties_tuple[0][1]
# We don't want to specify too many extremities as it causes the backfill
# request URI to be too long.
extremities = dict(sorted_extremeties_tuple[:5])
if current_depth > max_depth:
logger.debug(
"Not backfilling as we don't need to. %d < %d", max_depth, current_depth
)
return
# Now we need to decide which hosts to hit first.
# First we try hosts that are already in the room
# TODO: HEURISTIC ALERT.
curr_state = yield self.state_handler.get_current_state(room_id)
def get_domains_from_state(state):
"""Get joined domains from state
Args:
state (dict[tuple, FrozenEvent]): State map from type/state
key to event.
Returns:
list[tuple[str, int]]: Returns a list of servers with the
lowest depth of their joins. Sorted by lowest depth first.
"""
joined_users = [
(state_key, int(event.depth))
for (e_type, state_key), event in iteritems(state)
if e_type == EventTypes.Member and event.membership == Membership.JOIN
]
joined_domains = {}
for u, d in joined_users:
try:
dom = get_domain_from_id(u)
old_d = joined_domains.get(dom)
if old_d:
joined_domains[dom] = min(d, old_d)
else:
joined_domains[dom] = d
except Exception:
pass
return sorted(joined_domains.items(), key=lambda d: d[1])
curr_domains = get_domains_from_state(curr_state)
likely_domains = [
domain for domain, depth in curr_domains if domain != self.server_name
]
@defer.inlineCallbacks
def try_backfill(domains):
# TODO: Should we try multiple of these at a time?
for dom in domains:
try:
yield self.backfill(
dom, room_id, limit=100, extremities=extremities
)
# If this succeeded then we probably already have the
# appropriate stuff.
# TODO: We can probably do something more intelligent here.
return True
except SynapseError as e:
logger.info("Failed to backfill from %s because %s", dom, e)
continue
except CodeMessageException as e:
if 400 <= e.code < 500:
raise
logger.info("Failed to backfill from %s because %s", dom, e)
continue
except NotRetryingDestination as e:
logger.info(str(e))
continue
except RequestSendFailed as e:
logger.info("Falied to get backfill from %s because %s", dom, e)
continue
except FederationDeniedError as e:
logger.info(e)
continue
except Exception as e:
logger.exception("Failed to backfill from %s because %s", dom, e)
continue
return False
success = yield try_backfill(likely_domains)
if success:
return True
# Huh, well *those* domains didn't work out. Lets try some domains
# from the time.
tried_domains = set(likely_domains)
tried_domains.add(self.server_name)
event_ids = list(extremities.keys())
logger.debug("calling resolve_state_groups in _maybe_backfill")
resolve = preserve_fn(self.state_handler.resolve_state_groups_for_events)
states = yield make_deferred_yieldable(
defer.gatherResults(
[resolve(room_id, [e]) for e in event_ids], consumeErrors=True
)
)
# dict[str, dict[tuple, str]], a map from event_id to state map of
# event_ids.
states = dict(zip(event_ids, [s.state for s in states]))
state_map = yield self.store.get_events(
[e_id for ids in itervalues(states) for e_id in itervalues(ids)],
get_prev_content=False,
)
states = {
key: {
k: state_map[e_id]
for k, e_id in iteritems(state_dict)
if e_id in state_map
}
for key, state_dict in iteritems(states)
}
for e_id, _ in sorted_extremeties_tuple:
likely_domains = get_domains_from_state(states[e_id])
success = yield try_backfill(
[dom for dom, _ in likely_domains if dom not in tried_domains]
)
if success:
return True
tried_domains.update(dom for dom, _ in likely_domains)
return False
def _sanity_check_event(self, ev):
"""
Do some early sanity checks of a received event
In particular, checks it doesn't have an excessive number of
prev_events or auth_events, which could cause a huge state resolution
or cascade of event fetches.
Args:
ev (synapse.events.EventBase): event to be checked
Returns: None
Raises:
SynapseError if the event does not pass muster
"""
if len(ev.prev_event_ids()) > 20:
logger.warn(
"Rejecting event %s which has %i prev_events",
ev.event_id,
len(ev.prev_event_ids()),
)
raise SynapseError(http_client.BAD_REQUEST, "Too many prev_events")
if len(ev.auth_event_ids()) > 10:
logger.warn(
"Rejecting event %s which has %i auth_events",
ev.event_id,
len(ev.auth_event_ids()),
)
raise SynapseError(http_client.BAD_REQUEST, "Too many auth_events")
@defer.inlineCallbacks
def send_invite(self, target_host, event):
""" Sends the invite to the remote server for signing.
Invites must be signed by the invitee's server before distribution.
"""
pdu = yield self.federation_client.send_invite(
destination=target_host,
room_id=event.room_id,
event_id=event.event_id,
pdu=event,
)
return pdu
@defer.inlineCallbacks
def on_event_auth(self, event_id):
event = yield self.store.get_event(event_id)
auth = yield self.store.get_auth_chain(
[auth_id for auth_id in event.auth_event_ids()], include_given=True
)
return [e for e in auth]
@log_function
@defer.inlineCallbacks
def do_invite_join(self, target_hosts, room_id, joinee, content):
""" Attempts to join the `joinee` to the room `room_id` via the
server `target_host`.
This first triggers a /make_join/ request that returns a partial
event that we can fill out and sign. This is then sent to the
remote server via /send_join/ which responds with the state at that
event and the auth_chains.
We suspend processing of any received events from this room until we
have finished processing the join.
"""
logger.debug("Joining %s to %s", joinee, room_id)
origin, event, event_format_version = yield self._make_and_verify_event(
target_hosts,
room_id,
joinee,
"join",
content,
params={"ver": KNOWN_ROOM_VERSIONS},
)
# This shouldn't happen, because the RoomMemberHandler has a
# linearizer lock which only allows one operation per user per room
# at a time - so this is just paranoia.
assert room_id not in self.room_queues
self.room_queues[room_id] = []
yield self._clean_room_for_join(room_id)
handled_events = set()
try:
# Try the host we successfully got a response to /make_join/
# request first.
try:
target_hosts.remove(origin)
target_hosts.insert(0, origin)
except ValueError:
pass
ret = yield self.federation_client.send_join(
target_hosts, event, event_format_version
)
origin = ret["origin"]
state = ret["state"]
auth_chain = ret["auth_chain"]
auth_chain.sort(key=lambda e: e.depth)
handled_events.update([s.event_id for s in state])
handled_events.update([a.event_id for a in auth_chain])
handled_events.add(event.event_id)
logger.debug("do_invite_join auth_chain: %s", auth_chain)
logger.debug("do_invite_join state: %s", state)
logger.debug("do_invite_join event: %s", event)
try:
yield self.store.store_room(
room_id=room_id, room_creator_user_id="", is_public=False
)
except Exception:
# FIXME
pass
yield self._persist_auth_tree(origin, auth_chain, state, event)
logger.debug("Finished joining %s to %s", joinee, room_id)
finally:
room_queue = self.room_queues[room_id]
del self.room_queues[room_id]
# we don't need to wait for the queued events to be processed -
# it's just a best-effort thing at this point. We do want to do
# them roughly in order, though, otherwise we'll end up making
# lots of requests for missing prev_events which we do actually
# have. Hence we fire off the deferred, but don't wait for it.
run_in_background(self._handle_queued_pdus, room_queue)
return True
@defer.inlineCallbacks
def _handle_queued_pdus(self, room_queue):
"""Process PDUs which got queued up while we were busy send_joining.
Args:
room_queue (list[FrozenEvent, str]): list of PDUs to be processed
and the servers that sent them
"""
for p, origin in room_queue:
try:
logger.info(
"Processing queued PDU %s which was received "
"while we were joining %s",
p.event_id,
p.room_id,
)
with nested_logging_context(p.event_id):
yield self.on_receive_pdu(origin, p, sent_to_us_directly=True)
except Exception as e:
logger.warn(
"Error handling queued PDU %s from %s: %s", p.event_id, origin, e
)
@defer.inlineCallbacks
@log_function
def on_make_join_request(self, origin, room_id, user_id):
""" We've received a /make_join/ request, so we create a partial
join event for the room and return that. We do *not* persist or
process it until the other server has signed it and sent it back.
Args:
origin (str): The (verified) server name of the requesting server.
room_id (str): Room to create join event in
user_id (str): The user to create the join for
Returns:
Deferred[FrozenEvent]
"""
if get_domain_from_id(user_id) != origin:
logger.info(
"Got /make_join request for user %r from different origin %s, ignoring",
user_id,
origin,
)
raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
event_content = {"membership": Membership.JOIN}
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(
room_version,
{
"type": EventTypes.Member,
"content": event_content,
"room_id": room_id,
"sender": user_id,
"state_key": user_id,
},
)
try:
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
except AuthError as e:
logger.warn("Failed to create join %r because %s", event, e)
raise e
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info("Creation of join %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
# The remote hasn't signed it yet, obviously. We'll do the full checks
# when we get the event back in `on_send_join_request`
yield self.auth.check_from_context(
room_version, event, context, do_sig_check=False
)
return event
@defer.inlineCallbacks
@log_function
def on_send_join_request(self, origin, pdu):
""" We have received a join event for a room. Fully process it and
respond with the current state and auth chains.
"""
event = pdu
logger.debug(
"on_send_join_request: Got event: %s, signatures: %s",
event.event_id,
event.signatures,
)
event.internal_metadata.outlier = False
# Send this event on behalf of the origin server.
#
# The reasons we have the destination server rather than the origin
# server send it are slightly mysterious: the origin server should have
# all the neccessary state once it gets the response to the send_join,
# so it could send the event itself if it wanted to. It may be that
# doing it this way reduces failure modes, or avoids certain attacks
# where a new server selectively tells a subset of the federation that
# it has joined.
#
# The fact is that, as of the current writing, Synapse doesn't send out
# the join event over federation after joining, and changing it now
# would introduce the danger of backwards-compatibility problems.
event.internal_metadata.send_on_behalf_of = origin
context = yield self._handle_new_event(origin, event)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info("Sending of join %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
logger.debug(
"on_send_join_request: After _handle_new_event: %s, sigs: %s",
event.event_id,
event.signatures,
)
if event.type == EventTypes.Member:
if event.content["membership"] == Membership.JOIN:
user = UserID.from_string(event.state_key)
yield self.user_joined_room(user, event.room_id)
prev_state_ids = yield context.get_prev_state_ids(self.store)
state_ids = list(prev_state_ids.values())
auth_chain = yield self.store.get_auth_chain(state_ids)
state = yield self.store.get_events(list(prev_state_ids.values()))
return {"state": list(state.values()), "auth_chain": auth_chain}
@defer.inlineCallbacks
def on_invite_request(self, origin, pdu):
""" We've got an invite event. Process and persist it. Sign it.
Respond with the now signed event.
"""
event = pdu
if event.state_key is None:
raise SynapseError(400, "The invite event did not have a state key")
is_blocked = yield self.store.is_room_blocked(event.room_id)
if is_blocked:
raise SynapseError(403, "This room has been blocked on this server")
if self.hs.config.block_non_admin_invites:
raise SynapseError(403, "This server does not accept room invites")
if not self.spam_checker.user_may_invite(
event.sender, event.state_key, event.room_id
):
raise SynapseError(
403, "This user is not permitted to send invites to this server/user"
)
membership = event.content.get("membership")
if event.type != EventTypes.Member or membership != Membership.INVITE:
raise SynapseError(400, "The event was not an m.room.member invite event")
sender_domain = get_domain_from_id(event.sender)
if sender_domain != origin:
raise SynapseError(
400, "The invite event was not from the server sending it"
)
if not self.is_mine_id(event.state_key):
raise SynapseError(400, "The invite event must be for this server")
# block any attempts to invite the server notices mxid
if event.state_key == self._server_notices_mxid:
raise SynapseError(http_client.FORBIDDEN, "Cannot invite this user")
event.internal_metadata.outlier = True
event.internal_metadata.out_of_band_membership = True
event.signatures.update(
compute_event_signature(
event.get_pdu_json(), self.hs.hostname, self.hs.config.signing_key[0]
)
)
context = yield self.state_handler.compute_event_context(event)
yield self.persist_events_and_notify([(event, context)])
return event
@defer.inlineCallbacks
def do_remotely_reject_invite(self, target_hosts, room_id, user_id):
origin, event, event_format_version = yield self._make_and_verify_event(
target_hosts, room_id, user_id, "leave"
)
# Mark as outlier as we don't have any state for this event; we're not
# even in the room.
event.internal_metadata.outlier = True
event.internal_metadata.out_of_band_membership = True
# Try the host that we succesfully called /make_leave/ on first for
# the /send_leave/ request.
try:
target_hosts.remove(origin)
target_hosts.insert(0, origin)
except ValueError:
pass
yield self.federation_client.send_leave(target_hosts, event)
context = yield self.state_handler.compute_event_context(event)
yield self.persist_events_and_notify([(event, context)])
return event
@defer.inlineCallbacks
def _make_and_verify_event(
self, target_hosts, room_id, user_id, membership, content={}, params=None
):
origin, event, format_ver = yield self.federation_client.make_membership_event(
target_hosts, room_id, user_id, membership, content, params=params
)
logger.debug("Got response to make_%s: %s", membership, event)
# We should assert some things.
# FIXME: Do this in a nicer way
assert event.type == EventTypes.Member
assert event.user_id == user_id
assert event.state_key == user_id
assert event.room_id == room_id
return origin, event, format_ver
@defer.inlineCallbacks
@log_function
def on_make_leave_request(self, origin, room_id, user_id):
""" We've received a /make_leave/ request, so we create a partial
leave event for the room and return that. We do *not* persist or
process it until the other server has signed it and sent it back.
Args:
origin (str): The (verified) server name of the requesting server.
room_id (str): Room to create leave event in
user_id (str): The user to create the leave for
Returns:
Deferred[FrozenEvent]
"""
if get_domain_from_id(user_id) != origin:
logger.info(
"Got /make_leave request for user %r from different origin %s, ignoring",
user_id,
origin,
)
raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(
room_version,
{
"type": EventTypes.Member,
"content": {"membership": Membership.LEAVE},
"room_id": room_id,
"sender": user_id,
"state_key": user_id,
},
)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.warning("Creation of leave %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
try:
# The remote hasn't signed it yet, obviously. We'll do the full checks
# when we get the event back in `on_send_leave_request`
yield self.auth.check_from_context(
room_version, event, context, do_sig_check=False
)
except AuthError as e:
logger.warn("Failed to create new leave %r because %s", event, e)
raise e
return event
@defer.inlineCallbacks
@log_function
def on_send_leave_request(self, origin, pdu):
""" We have received a leave event for a room. Fully process it."""
event = pdu
logger.debug(
"on_send_leave_request: Got event: %s, signatures: %s",
event.event_id,
event.signatures,
)
event.internal_metadata.outlier = False
context = yield self._handle_new_event(origin, event)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info("Sending of leave %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
logger.debug(
"on_send_leave_request: After _handle_new_event: %s, sigs: %s",
event.event_id,
event.signatures,
)
return None
@defer.inlineCallbacks
def get_state_for_pdu(self, room_id, event_id):
"""Returns the state at the event. i.e. not including said event.
"""
event = yield self.store.get_event(
event_id, allow_none=False, check_room_id=room_id
)
state_groups = yield self.store.get_state_groups(room_id, [event_id])
if state_groups:
_, state = list(iteritems(state_groups)).pop()
results = {(e.type, e.state_key): e for e in state}
if event.is_state():
# Get previous state
if "replaces_state" in event.unsigned:
prev_id = event.unsigned["replaces_state"]
if prev_id != event.event_id:
prev_event = yield self.store.get_event(prev_id)
results[(event.type, event.state_key)] = prev_event
else:
del results[(event.type, event.state_key)]
res = list(results.values())
return res
else:
return []
@defer.inlineCallbacks
def get_state_ids_for_pdu(self, room_id, event_id):
"""Returns the state at the event. i.e. not including said event.
"""
event = yield self.store.get_event(
event_id, allow_none=False, check_room_id=room_id
)
state_groups = yield self.store.get_state_groups_ids(room_id, [event_id])
if state_groups:
_, state = list(state_groups.items()).pop()
results = state
if event.is_state():
# Get previous state
if "replaces_state" in event.unsigned:
prev_id = event.unsigned["replaces_state"]
if prev_id != event.event_id:
results[(event.type, event.state_key)] = prev_id
else:
results.pop((event.type, event.state_key), None)
return list(results.values())
else:
return []
@defer.inlineCallbacks
@log_function
def on_backfill_request(self, origin, room_id, pdu_list, limit):
in_room = yield self.auth.check_host_in_room(room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
events = yield self.store.get_backfill_events(room_id, pdu_list, limit)
events = yield filter_events_for_server(self.store, origin, events)
return events
@defer.inlineCallbacks
@log_function
def get_persisted_pdu(self, origin, event_id):
"""Get an event from the database for the given server.
Args:
origin [str]: hostname of server which is requesting the event; we
will check that the server is allowed to see it.
event_id [str]: id of the event being requested
Returns:
Deferred[EventBase|None]: None if we know nothing about the event;
otherwise the (possibly-redacted) event.
Raises:
AuthError if the server is not currently in the room
"""
event = yield self.store.get_event(
event_id, allow_none=True, allow_rejected=True
)
if event:
in_room = yield self.auth.check_host_in_room(event.room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
events = yield filter_events_for_server(self.store, origin, [event])
event = events[0]
return event
else:
return None
def get_min_depth_for_context(self, context):
return self.store.get_min_depth(context)
@defer.inlineCallbacks
def _handle_new_event(
self, origin, event, state=None, auth_events=None, backfilled=False
):
context = yield self._prep_event(
origin, event, state=state, auth_events=auth_events, backfilled=backfilled
)
# reraise does not allow inlineCallbacks to preserve the stacktrace, so we
# hack around with a try/finally instead.
success = False
try:
if not event.internal_metadata.is_outlier() and not backfilled:
yield self.action_generator.handle_push_actions_for_event(
event, context
)
yield self.persist_events_and_notify(
[(event, context)], backfilled=backfilled
)
success = True
finally:
if not success:
run_in_background(
self.store.remove_push_actions_from_staging, event.event_id
)
return context
@defer.inlineCallbacks
def _handle_new_events(self, origin, event_infos, backfilled=False):
"""Creates the appropriate contexts and persists events. The events
should not depend on one another, e.g. this should be used to persist
a bunch of outliers, but not a chunk of individual events that depend
on each other for state calculations.
Notifies about the events where appropriate.
"""
@defer.inlineCallbacks
def prep(ev_info):
event = ev_info["event"]
with nested_logging_context(suffix=event.event_id):
res = yield self._prep_event(
origin,
event,
state=ev_info.get("state"),
auth_events=ev_info.get("auth_events"),
backfilled=backfilled,
)
return res
contexts = yield make_deferred_yieldable(
defer.gatherResults(
[run_in_background(prep, ev_info) for ev_info in event_infos],
consumeErrors=True,
)
)
yield self.persist_events_and_notify(
[
(ev_info["event"], context)
for ev_info, context in zip(event_infos, contexts)
],
backfilled=backfilled,
)
@defer.inlineCallbacks
def _persist_auth_tree(self, origin, auth_events, state, event):
"""Checks the auth chain is valid (and passes auth checks) for the
state and event. Then persists the auth chain and state atomically.
Persists the event separately. Notifies about the persisted events
where appropriate.
Will attempt to fetch missing auth events.
Args:
origin (str): Where the events came from
auth_events (list)
state (list)
event (Event)
Returns:
Deferred
"""
events_to_context = {}
for e in itertools.chain(auth_events, state):
e.internal_metadata.outlier = True
ctx = yield self.state_handler.compute_event_context(e)
events_to_context[e.event_id] = ctx
event_map = {
e.event_id: e for e in itertools.chain(auth_events, state, [event])
}
create_event = None
for e in auth_events:
if (e.type, e.state_key) == (EventTypes.Create, ""):
create_event = e
break
if create_event is None:
# If the state doesn't have a create event then the room is
# invalid, and it would fail auth checks anyway.
raise SynapseError(400, "No create event in state")
room_version = create_event.content.get(
"room_version", RoomVersions.V1.identifier
)
missing_auth_events = set()
for e in itertools.chain(auth_events, state, [event]):
for e_id in e.auth_event_ids():
if e_id not in event_map:
missing_auth_events.add(e_id)
for e_id in missing_auth_events:
m_ev = yield self.federation_client.get_pdu(
[origin], e_id, room_version=room_version, outlier=True, timeout=10000
)
if m_ev and m_ev.event_id == e_id:
event_map[e_id] = m_ev
else:
logger.info("Failed to find auth event %r", e_id)
for e in itertools.chain(auth_events, state, [event]):
auth_for_e = {
(event_map[e_id].type, event_map[e_id].state_key): event_map[e_id]
for e_id in e.auth_event_ids()
if e_id in event_map
}
if create_event:
auth_for_e[(EventTypes.Create, "")] = create_event
try:
self.auth.check(room_version, e, auth_events=auth_for_e)
except SynapseError as err:
# we may get SynapseErrors here as well as AuthErrors. For
# instance, there are a couple of (ancient) events in some
# rooms whose senders do not have the correct sigil; these
# cause SynapseErrors in auth.check. We don't want to give up
# the attempt to federate altogether in such cases.
logger.warn("Rejecting %s because %s", e.event_id, err.msg)
if e == event:
raise
events_to_context[e.event_id].rejected = RejectedReason.AUTH_ERROR
yield self.persist_events_and_notify(
[
(e, events_to_context[e.event_id])
for e in itertools.chain(auth_events, state)
]
)
new_event_context = yield self.state_handler.compute_event_context(
event, old_state=state
)
yield self.persist_events_and_notify([(event, new_event_context)])
@defer.inlineCallbacks
def _prep_event(self, origin, event, state, auth_events, backfilled):
"""
Args:
origin:
event:
state:
auth_events:
backfilled (bool)
Returns:
Deferred, which resolves to synapse.events.snapshot.EventContext
"""
context = yield self.state_handler.compute_event_context(event, old_state=state)
if not auth_events:
prev_state_ids = yield context.get_prev_state_ids(self.store)
auth_events_ids = yield self.auth.compute_auth_events(
event, prev_state_ids, for_verification=True
)
auth_events = yield self.store.get_events(auth_events_ids)
auth_events = {(e.type, e.state_key): e for e in auth_events.values()}
# This is a hack to fix some old rooms where the initial join event
# didn't reference the create event in its auth events.
if event.type == EventTypes.Member and not event.auth_event_ids():
if len(event.prev_event_ids()) == 1 and event.depth < 5:
c = yield self.store.get_event(
event.prev_event_ids()[0], allow_none=True
)
if c and c.type == EventTypes.Create:
auth_events[(c.type, c.state_key)] = c
try:
yield self.do_auth(origin, event, context, auth_events=auth_events)
except AuthError as e:
logger.warn("[%s %s] Rejecting: %s", event.room_id, event.event_id, e.msg)
context.rejected = RejectedReason.AUTH_ERROR
if not context.rejected:
yield self._check_for_soft_fail(event, state, backfilled)
if event.type == EventTypes.GuestAccess and not context.rejected:
yield self.maybe_kick_guest_users(event)
return context
@defer.inlineCallbacks
def _check_for_soft_fail(self, event, state, backfilled):
"""Checks if we should soft fail the event, if so marks the event as
such.
Args:
event (FrozenEvent)
state (dict|None): The state at the event if we don't have all the
event's prev events
backfilled (bool): Whether the event is from backfill
Returns:
Deferred
"""
# For new (non-backfilled and non-outlier) events we check if the event
# passes auth based on the current state. If it doesn't then we
# "soft-fail" the event.
do_soft_fail_check = not backfilled and not event.internal_metadata.is_outlier()
if do_soft_fail_check:
extrem_ids = yield self.store.get_latest_event_ids_in_room(event.room_id)
extrem_ids = set(extrem_ids)
prev_event_ids = set(event.prev_event_ids())
if extrem_ids == prev_event_ids:
# If they're the same then the current state is the same as the
# state at the event, so no point rechecking auth for soft fail.
do_soft_fail_check = False
if do_soft_fail_check:
room_version = yield self.store.get_room_version(event.room_id)
# Calculate the "current state".
if state is not None:
# If we're explicitly given the state then we won't have all the
# prev events, and so we have a gap in the graph. In this case
# we want to be a little careful as we might have been down for
# a while and have an incorrect view of the current state,
# however we still want to do checks as gaps are easy to
# maliciously manufacture.
#
# So we use a "current state" that is actually a state
# resolution across the current forward extremities and the
# given state at the event. This should correctly handle cases
# like bans, especially with state res v2.
state_sets = yield self.store.get_state_groups(
event.room_id, extrem_ids
)
state_sets = list(state_sets.values())
state_sets.append(state)
current_state_ids = yield self.state_handler.resolve_events(
room_version, state_sets, event
)
current_state_ids = {
k: e.event_id for k, e in iteritems(current_state_ids)
}
else:
current_state_ids = yield self.state_handler.get_current_state_ids(
event.room_id, latest_event_ids=extrem_ids
)
logger.debug(
"Doing soft-fail check for %s: state %s",
event.event_id,
current_state_ids,
)
# Now check if event pass auth against said current state
auth_types = auth_types_for_event(event)
current_state_ids = [
e for k, e in iteritems(current_state_ids) if k in auth_types
]
current_auth_events = yield self.store.get_events(current_state_ids)
current_auth_events = {
(e.type, e.state_key): e for e in current_auth_events.values()
}
try:
self.auth.check(room_version, event, auth_events=current_auth_events)
except AuthError as e:
logger.warn("Soft-failing %r because %s", event, e)
event.internal_metadata.soft_failed = True
@defer.inlineCallbacks
def on_query_auth(
self, origin, event_id, room_id, remote_auth_chain, rejects, missing
):
in_room = yield self.auth.check_host_in_room(room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
event = yield self.store.get_event(
event_id, allow_none=False, check_room_id=room_id
)
# Just go through and process each event in `remote_auth_chain`. We
# don't want to fall into the trap of `missing` being wrong.
for e in remote_auth_chain:
try:
yield self._handle_new_event(origin, e)
except AuthError:
pass
# Now get the current auth_chain for the event.
local_auth_chain = yield self.store.get_auth_chain(
[auth_id for auth_id in event.auth_event_ids()], include_given=True
)
# TODO: Check if we would now reject event_id. If so we need to tell
# everyone.
ret = yield self.construct_auth_difference(local_auth_chain, remote_auth_chain)
logger.debug("on_query_auth returning: %s", ret)
return ret
@defer.inlineCallbacks
def on_get_missing_events(
self, origin, room_id, earliest_events, latest_events, limit
):
in_room = yield self.auth.check_host_in_room(room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
limit = min(limit, 20)
missing_events = yield self.store.get_missing_events(
room_id=room_id,
earliest_events=earliest_events,
latest_events=latest_events,
limit=limit,
)
missing_events = yield filter_events_for_server(
self.store, origin, missing_events
)
return missing_events
@defer.inlineCallbacks
@log_function
def do_auth(self, origin, event, context, auth_events):
"""
Args:
origin (str):
event (synapse.events.EventBase):
context (synapse.events.snapshot.EventContext):
auth_events (dict[(str, str)->synapse.events.EventBase]):
Map from (event_type, state_key) to event
What we expect the event's auth_events to be, based on the event's
position in the dag. I think? maybe??
Also NB that this function adds entries to it.
Returns:
defer.Deferred[None]
"""
room_version = yield self.store.get_room_version(event.room_id)
try:
yield self._update_auth_events_and_context_for_auth(
origin, event, context, auth_events
)
except Exception:
# We don't really mind if the above fails, so lets not fail
# processing if it does. However, it really shouldn't fail so
# let's still log as an exception since we'll still want to fix
# any bugs.
logger.exception(
"Failed to double check auth events for %s with remote. "
"Ignoring failure and continuing processing of event.",
event.event_id,
)
try:
self.auth.check(room_version, event, auth_events=auth_events)
except AuthError as e:
logger.warn("Failed auth resolution for %r because %s", event, e)
raise e
@defer.inlineCallbacks
def _update_auth_events_and_context_for_auth(
self, origin, event, context, auth_events
):
"""Helper for do_auth. See there for docs.
Checks whether a given event has the expected auth events. If it
doesn't then we talk to the remote server to compare state to see if
we can come to a consensus (e.g. if one server missed some valid
state).
This attempts to resovle any potential divergence of state between
servers, but is not essential and so failures should not block further
processing of the event.
Args:
origin (str):
event (synapse.events.EventBase):
context (synapse.events.snapshot.EventContext):
auth_events (dict[(str, str)->synapse.events.EventBase]):
Returns:
defer.Deferred[None]
"""
event_auth_events = set(event.auth_event_ids())
if event.is_state():
event_key = (event.type, event.state_key)
else:
event_key = None
# if the event's auth_events refers to events which are not in our
# calculated auth_events, we need to fetch those events from somewhere.
#
# we start by fetching them from the store, and then try calling /event_auth/.
missing_auth = event_auth_events.difference(
e.event_id for e in auth_events.values()
)
if missing_auth:
# TODO: can we use store.have_seen_events here instead?
have_events = yield self.store.get_seen_events_with_rejections(missing_auth)
logger.debug("Got events %s from store", have_events)
missing_auth.difference_update(have_events.keys())
else:
have_events = {}
have_events.update({e.event_id: "" for e in auth_events.values()})
if missing_auth:
# If we don't have all the auth events, we need to get them.
logger.info("auth_events contains unknown events: %s", missing_auth)
try:
try:
remote_auth_chain = yield self.federation_client.get_event_auth(
origin, event.room_id, event.event_id
)
except RequestSendFailed as e:
# The other side isn't around or doesn't implement the
# endpoint, so lets just bail out.
logger.info("Failed to get event auth from remote: %s", e)
return
seen_remotes = yield self.store.have_seen_events(
[e.event_id for e in remote_auth_chain]
)
for e in remote_auth_chain:
if e.event_id in seen_remotes:
continue
if e.event_id == event.event_id:
continue
try:
auth_ids = e.auth_event_ids()
auth = {
(e.type, e.state_key): e
for e in remote_auth_chain
if e.event_id in auth_ids or e.type == EventTypes.Create
}
e.internal_metadata.outlier = True
logger.debug(
"do_auth %s missing_auth: %s", event.event_id, e.event_id
)
yield self._handle_new_event(origin, e, auth_events=auth)
if e.event_id in event_auth_events:
auth_events[(e.type, e.state_key)] = e
except AuthError:
pass
have_events = yield self.store.get_seen_events_with_rejections(
event.auth_event_ids()
)
except Exception:
# FIXME:
logger.exception("Failed to get auth chain")
if event.internal_metadata.is_outlier():
logger.info("Skipping auth_event fetch for outlier")
return
# FIXME: Assumes we have and stored all the state for all the
# prev_events
different_auth = event_auth_events.difference(
e.event_id for e in auth_events.values()
)
if not different_auth:
return
logger.info(
"auth_events refers to events which are not in our calculated auth "
"chain: %s",
different_auth,
)
room_version = yield self.store.get_room_version(event.room_id)
different_events = yield make_deferred_yieldable(
defer.gatherResults(
[
run_in_background(
self.store.get_event, d, allow_none=True, allow_rejected=False
)
for d in different_auth
if d in have_events and not have_events[d]
],
consumeErrors=True,
)
).addErrback(unwrapFirstError)
if different_events:
local_view = dict(auth_events)
remote_view = dict(auth_events)
remote_view.update(
{(d.type, d.state_key): d for d in different_events if d}
)
new_state = yield self.state_handler.resolve_events(
room_version,
[list(local_view.values()), list(remote_view.values())],
event,
)
logger.info(
"After state res: updating auth_events with new state %s",
{
(d.type, d.state_key): d.event_id
for d in new_state.values()
if auth_events.get((d.type, d.state_key)) != d
},
)
auth_events.update(new_state)
different_auth = event_auth_events.difference(
e.event_id for e in auth_events.values()
)
yield self._update_context_for_auth_events(
event, context, auth_events, event_key
)
if not different_auth:
# we're done
return
logger.info(
"auth_events still refers to events which are not in the calculated auth "
"chain after state resolution: %s",
different_auth,
)
# Only do auth resolution if we have something new to say.
# We can't prove an auth failure.
do_resolution = False
for e_id in different_auth:
if e_id in have_events:
if have_events[e_id] == RejectedReason.NOT_ANCESTOR:
do_resolution = True
break
if not do_resolution:
logger.info(
"Skipping auth resolution due to lack of provable rejection reasons"
)
return
logger.info("Doing auth resolution")
prev_state_ids = yield context.get_prev_state_ids(self.store)
# 1. Get what we think is the auth chain.
auth_ids = yield self.auth.compute_auth_events(event, prev_state_ids)
local_auth_chain = yield self.store.get_auth_chain(auth_ids, include_given=True)
try:
# 2. Get remote difference.
try:
result = yield self.federation_client.query_auth(
origin, event.room_id, event.event_id, local_auth_chain
)
except RequestSendFailed as e:
# The other side isn't around or doesn't implement the
# endpoint, so lets just bail out.
logger.info("Failed to query auth from remote: %s", e)
return
seen_remotes = yield self.store.have_seen_events(
[e.event_id for e in result["auth_chain"]]
)
# 3. Process any remote auth chain events we haven't seen.
for ev in result["auth_chain"]:
if ev.event_id in seen_remotes:
continue
if ev.event_id == event.event_id:
continue
try:
auth_ids = ev.auth_event_ids()
auth = {
(e.type, e.state_key): e
for e in result["auth_chain"]
if e.event_id in auth_ids or event.type == EventTypes.Create
}
ev.internal_metadata.outlier = True
logger.debug(
"do_auth %s different_auth: %s", event.event_id, e.event_id
)
yield self._handle_new_event(origin, ev, auth_events=auth)
if ev.event_id in event_auth_events:
auth_events[(ev.type, ev.state_key)] = ev
except AuthError:
pass
except Exception:
# FIXME:
logger.exception("Failed to query auth chain")
# 4. Look at rejects and their proofs.
# TODO.
yield self._update_context_for_auth_events(
event, context, auth_events, event_key
)
@defer.inlineCallbacks
def _update_context_for_auth_events(self, event, context, auth_events, event_key):
"""Update the state_ids in an event context after auth event resolution,
storing the changes as a new state group.
Args:
event (Event): The event we're handling the context for
context (synapse.events.snapshot.EventContext): event context
to be updated
auth_events (dict[(str, str)->str]): Events to update in the event
context.
event_key ((str, str)): (type, state_key) for the current event.
this will not be included in the current_state in the context.
"""
state_updates = {
k: a.event_id for k, a in iteritems(auth_events) if k != event_key
}
current_state_ids = yield context.get_current_state_ids(self.store)
current_state_ids = dict(current_state_ids)
current_state_ids.update(state_updates)
prev_state_ids = yield context.get_prev_state_ids(self.store)
prev_state_ids = dict(prev_state_ids)
prev_state_ids.update({k: a.event_id for k, a in iteritems(auth_events)})
# create a new state group as a delta from the existing one.
prev_group = context.state_group
state_group = yield self.store.store_state_group(
event.event_id,
event.room_id,
prev_group=prev_group,
delta_ids=state_updates,
current_state_ids=current_state_ids,
)
yield context.update_state(
state_group=state_group,
current_state_ids=current_state_ids,
prev_state_ids=prev_state_ids,
prev_group=prev_group,
delta_ids=state_updates,
)
@defer.inlineCallbacks
def construct_auth_difference(self, local_auth, remote_auth):
""" Given a local and remote auth chain, find the differences. This
assumes that we have already processed all events in remote_auth
Params:
local_auth (list)
remote_auth (list)
Returns:
dict
"""
logger.debug("construct_auth_difference Start!")
# TODO: Make sure we are OK with local_auth or remote_auth having more
# auth events in them than strictly necessary.
def sort_fun(ev):
return ev.depth, ev.event_id
logger.debug("construct_auth_difference after sort_fun!")
# We find the differences by starting at the "bottom" of each list
# and iterating up on both lists. The lists are ordered by depth and
# then event_id, we iterate up both lists until we find the event ids
# don't match. Then we look at depth/event_id to see which side is
# missing that event, and iterate only up that list. Repeat.
remote_list = list(remote_auth)
remote_list.sort(key=sort_fun)
local_list = list(local_auth)
local_list.sort(key=sort_fun)
local_iter = iter(local_list)
remote_iter = iter(remote_list)
logger.debug("construct_auth_difference before get_next!")
def get_next(it, opt=None):
try:
return next(it)
except Exception:
return opt
current_local = get_next(local_iter)
current_remote = get_next(remote_iter)
logger.debug("construct_auth_difference before while")
missing_remotes = []
missing_locals = []
while current_local or current_remote:
if current_remote is None:
missing_locals.append(current_local)
current_local = get_next(local_iter)
continue
if current_local is None:
missing_remotes.append(current_remote)
current_remote = get_next(remote_iter)
continue
if current_local.event_id == current_remote.event_id:
current_local = get_next(local_iter)
current_remote = get_next(remote_iter)
continue
if current_local.depth < current_remote.depth:
missing_locals.append(current_local)
current_local = get_next(local_iter)
continue
if current_local.depth > current_remote.depth:
missing_remotes.append(current_remote)
current_remote = get_next(remote_iter)
continue
# They have the same depth, so we fall back to the event_id order
if current_local.event_id < current_remote.event_id:
missing_locals.append(current_local)
current_local = get_next(local_iter)
if current_local.event_id > current_remote.event_id:
missing_remotes.append(current_remote)
current_remote = get_next(remote_iter)
continue
logger.debug("construct_auth_difference after while")
# missing locals should be sent to the server
# We should find why we are missing remotes, as they will have been
# rejected.
# Remove events from missing_remotes if they are referencing a missing
# remote. We only care about the "root" rejected ones.
missing_remote_ids = [e.event_id for e in missing_remotes]
base_remote_rejected = list(missing_remotes)
for e in missing_remotes:
for e_id in e.auth_event_ids():
if e_id in missing_remote_ids:
try:
base_remote_rejected.remove(e)
except ValueError:
pass
reason_map = {}
for e in base_remote_rejected:
reason = yield self.store.get_rejection_reason(e.event_id)
if reason is None:
# TODO: e is not in the current state, so we should
# construct some proof of that.
continue
reason_map[e.event_id] = reason
if reason == RejectedReason.AUTH_ERROR:
pass
elif reason == RejectedReason.REPLACED:
# TODO: Get proof
pass
elif reason == RejectedReason.NOT_ANCESTOR:
# TODO: Get proof.
pass
logger.debug("construct_auth_difference returning")
return {
"auth_chain": local_auth,
"rejects": {
e.event_id: {"reason": reason_map[e.event_id], "proof": None}
for e in base_remote_rejected
},
"missing": [e.event_id for e in missing_locals],
}
@defer.inlineCallbacks
@log_function
def exchange_third_party_invite(
self, sender_user_id, target_user_id, room_id, signed
):
third_party_invite = {"signed": signed}
event_dict = {
"type": EventTypes.Member,
"content": {
"membership": Membership.INVITE,
"third_party_invite": third_party_invite,
},
"room_id": room_id,
"sender": sender_user_id,
"state_key": target_user_id,
}
if (yield self.auth.check_host_in_room(room_id, self.hs.hostname)):
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(room_version, event_dict)
EventValidator().validate_builder(builder)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info(
"Creation of threepid invite %s forbidden by third-party rules",
event,
)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
event, context = yield self.add_display_name_to_third_party_invite(
room_version, event_dict, event, context
)
EventValidator().validate_new(event)
# We need to tell the transaction queue to send this out, even
# though the sender isn't a local user.
event.internal_metadata.send_on_behalf_of = self.hs.hostname
try:
yield self.auth.check_from_context(room_version, event, context)
except AuthError as e:
logger.warn("Denying new third party invite %r because %s", event, e)
raise e
yield self._check_signature(event, context)
member_handler = self.hs.get_room_member_handler()
yield member_handler.send_membership_event(None, event, context)
else:
destinations = set(x.split(":", 1)[-1] for x in (sender_user_id, room_id))
yield self.federation_client.forward_third_party_invite(
destinations, room_id, event_dict
)
@defer.inlineCallbacks
@log_function
def on_exchange_third_party_invite_request(self, room_id, event_dict):
"""Handle an exchange_third_party_invite request from a remote server
The remote server will call this when it wants to turn a 3pid invite
into a normal m.room.member invite.
Args:
room_id (str): The ID of the room.
event_dict (dict[str, Any]): Dictionary containing the event body.
Returns:
Deferred: resolves (to None)
"""
room_version = yield self.store.get_room_version(room_id)
# NB: event_dict has a particular specced format we might need to fudge
# if we change event formats too much.
builder = self.event_builder_factory.new(room_version, event_dict)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.warning(
"Exchange of threepid invite %s forbidden by third-party rules", event
)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
event, context = yield self.add_display_name_to_third_party_invite(
room_version, event_dict, event, context
)
try:
self.auth.check_from_context(room_version, event, context)
except AuthError as e:
logger.warn("Denying third party invite %r because %s", event, e)
raise e
yield self._check_signature(event, context)
# We need to tell the transaction queue to send this out, even
# though the sender isn't a local user.
event.internal_metadata.send_on_behalf_of = get_domain_from_id(event.sender)
member_handler = self.hs.get_room_member_handler()
yield member_handler.send_membership_event(None, event, context)
@defer.inlineCallbacks
def add_display_name_to_third_party_invite(
self, room_version, event_dict, event, context
):
key = (
EventTypes.ThirdPartyInvite,
event.content["third_party_invite"]["signed"]["token"],
)
original_invite = None
prev_state_ids = yield context.get_prev_state_ids(self.store)
original_invite_id = prev_state_ids.get(key)
if original_invite_id:
original_invite = yield self.store.get_event(
original_invite_id, allow_none=True
)
if original_invite:
display_name = original_invite.content["display_name"]
event_dict["content"]["third_party_invite"]["display_name"] = display_name
else:
logger.info(
"Could not find invite event for third_party_invite: %r", event_dict
)
# We don't discard here as this is not the appropriate place to do
# auth checks. If we need the invite and don't have it then the
# auth check code will explode appropriately.
builder = self.event_builder_factory.new(room_version, event_dict)
EventValidator().validate_builder(builder)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
EventValidator().validate_new(event)
return (event, context)
@defer.inlineCallbacks
def _check_signature(self, event, context):
"""
Checks that the signature in the event is consistent with its invite.
Args:
event (Event): The m.room.member event to check
context (EventContext):
Raises:
AuthError: if signature didn't match any keys, or key has been
revoked,
SynapseError: if a transient error meant a key couldn't be checked
for revocation.
"""
signed = event.content["third_party_invite"]["signed"]
token = signed["token"]
prev_state_ids = yield context.get_prev_state_ids(self.store)
invite_event_id = prev_state_ids.get((EventTypes.ThirdPartyInvite, token))
invite_event = None
if invite_event_id:
invite_event = yield self.store.get_event(invite_event_id, allow_none=True)
if not invite_event:
raise AuthError(403, "Could not find invite")
logger.debug("Checking auth on event %r", event.content)
last_exception = None
# for each public key in the 3pid invite event
for public_key_object in self.hs.get_auth().get_public_keys(invite_event):
try:
# for each sig on the third_party_invite block of the actual invite
for server, signature_block in signed["signatures"].items():
for key_name, encoded_signature in signature_block.items():
if not key_name.startswith("ed25519:"):
continue
logger.debug(
"Attempting to verify sig with key %s from %r "
"against pubkey %r",
key_name,
server,
public_key_object,
)
try:
public_key = public_key_object["public_key"]
verify_key = decode_verify_key_bytes(
key_name, decode_base64(public_key)
)
verify_signed_json(signed, server, verify_key)
logger.debug(
"Successfully verified sig with key %s from %r "
"against pubkey %r",
key_name,
server,
public_key_object,
)
except Exception:
logger.info(
"Failed to verify sig with key %s from %r "
"against pubkey %r",
key_name,
server,
public_key_object,
)
raise
try:
if "key_validity_url" in public_key_object:
yield self._check_key_revocation(
public_key, public_key_object["key_validity_url"]
)
except Exception:
logger.info(
"Failed to query key_validity_url %s",
public_key_object["key_validity_url"],
)
raise
return
except Exception as e:
last_exception = e
raise last_exception
@defer.inlineCallbacks
def _check_key_revocation(self, public_key, url):
"""
Checks whether public_key has been revoked.
Args:
public_key (str): base-64 encoded public key.
url (str): Key revocation URL.
Raises:
AuthError: if they key has been revoked.
SynapseError: if a transient error meant a key couldn't be checked
for revocation.
"""
try:
response = yield self.http_client.get_json(url, {"public_key": public_key})
except Exception:
raise SynapseError(502, "Third party certificate could not be checked")
if "valid" not in response or not response["valid"]:
raise AuthError(403, "Third party certificate was invalid")
@defer.inlineCallbacks
def persist_events_and_notify(self, event_and_contexts, backfilled=False):
"""Persists events and tells the notifier/pushers about them, if
necessary.
Args:
event_and_contexts(list[tuple[FrozenEvent, EventContext]])
backfilled (bool): Whether these events are a result of
backfilling or not
Returns:
Deferred
"""
if self.config.worker_app:
yield self._send_events_to_master(
store=self.store,
event_and_contexts=event_and_contexts,
backfilled=backfilled,
)
else:
max_stream_id = yield self.store.persist_events(
event_and_contexts, backfilled=backfilled
)
if not backfilled: # Never notify for backfilled events
for event, _ in event_and_contexts:
yield self._notify_persisted_event(event, max_stream_id)
def _notify_persisted_event(self, event, max_stream_id):
"""Checks to see if notifier/pushers should be notified about the
event or not.
Args:
event (FrozenEvent)
max_stream_id (int): The max_stream_id returned by persist_events
"""
extra_users = []
if event.type == EventTypes.Member:
target_user_id = event.state_key
# We notify for memberships if its an invite for one of our
# users
if event.internal_metadata.is_outlier():
if event.membership != Membership.INVITE:
if not self.is_mine_id(target_user_id):
return
target_user = UserID.from_string(target_user_id)
extra_users.append(target_user)
elif event.internal_metadata.is_outlier():
return
event_stream_id = event.internal_metadata.stream_ordering
self.notifier.on_new_room_event(
event, event_stream_id, max_stream_id, extra_users=extra_users
)
return self.pusher_pool.on_new_notifications(event_stream_id, max_stream_id)
def _clean_room_for_join(self, room_id):
"""Called to clean up any data in DB for a given room, ready for the
server to join the room.
Args:
room_id (str)
"""
if self.config.worker_app:
return self._clean_room_for_join_client(room_id)
else:
return self.store.clean_room_for_join(room_id)
def user_joined_room(self, user, room_id):
"""Called when a new user has joined the room
"""
if self.config.worker_app:
return self._notify_user_membership_change(
room_id=room_id, user_id=user.to_string(), change="joined"
)
else:
return user_joined_room(self.distributor, user, room_id)
@defer.inlineCallbacks
def get_room_complexity(self, remote_room_hosts, room_id):
"""
Fetch the complexity of a remote room over federation.
Args:
remote_room_hosts (list[str]): The remote servers to ask.
room_id (str): The room ID to ask about.
Returns:
Deferred[dict] or Deferred[None]: Dict contains the complexity
metric versions, while None means we could not fetch the complexity.
"""
for host in remote_room_hosts:
res = yield self.federation_client.get_room_complexity(host, room_id)
# We got a result, return it.
if res:
defer.returnValue(res)
# We fell off the bottom, couldn't get the complexity from anyone. Oh
# well.
defer.returnValue(None)
| 38.411225 | 99 | 0.5732 |
import itertools
import logging
import six
from six import iteritems, itervalues
from six.moves import http_client, zip
from signedjson.key import decode_verify_key_bytes
from signedjson.sign import verify_signed_json
from unpaddedbase64 import decode_base64
from twisted.internet import defer
from synapse.api.constants import EventTypes, Membership, RejectedReason
from synapse.api.errors import (
AuthError,
CodeMessageException,
Codes,
FederationDeniedError,
FederationError,
RequestSendFailed,
StoreError,
SynapseError,
)
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersions
from synapse.crypto.event_signing import compute_event_signature
from synapse.event_auth import auth_types_for_event
from synapse.events.validator import EventValidator
from synapse.logging.context import (
make_deferred_yieldable,
nested_logging_context,
preserve_fn,
run_in_background,
)
from synapse.logging.utils import log_function
from synapse.replication.http.federation import (
ReplicationCleanRoomRestServlet,
ReplicationFederationSendEventsRestServlet,
)
from synapse.replication.http.membership import ReplicationUserJoinedLeftRoomRestServlet
from synapse.state import StateResolutionStore, resolve_events_with_store
from synapse.types import UserID, get_domain_from_id
from synapse.util import unwrapFirstError
from synapse.util.async_helpers import Linearizer
from synapse.util.distributor import user_joined_room
from synapse.util.retryutils import NotRetryingDestination
from synapse.visibility import filter_events_for_server
from ._base import BaseHandler
logger = logging.getLogger(__name__)
def shortstr(iterable, maxitems=5):
items = list(itertools.islice(iterable, maxitems + 1))
if len(items) <= maxitems:
return str(items)
return "[" + ", ".join(repr(r) for r in items[:maxitems]) + ", ...]"
class FederationHandler(BaseHandler):
def __init__(self, hs):
super(FederationHandler, self).__init__(hs)
self.hs = hs
self.store = hs.get_datastore()
self.federation_client = hs.get_federation_client()
self.state_handler = hs.get_state_handler()
self.server_name = hs.hostname
self.keyring = hs.get_keyring()
self.action_generator = hs.get_action_generator()
self.is_mine_id = hs.is_mine_id
self.pusher_pool = hs.get_pusherpool()
self.spam_checker = hs.get_spam_checker()
self.event_creation_handler = hs.get_event_creation_handler()
self._server_notices_mxid = hs.config.server_notices_mxid
self.config = hs.config
self.http_client = hs.get_simple_http_client()
self._send_events_to_master = ReplicationFederationSendEventsRestServlet.make_client(
hs
)
self._notify_user_membership_change = ReplicationUserJoinedLeftRoomRestServlet.make_client(
hs
)
self._clean_room_for_join_client = ReplicationCleanRoomRestServlet.make_client(
hs
)
self.room_queues = {}
self._room_pdu_linearizer = Linearizer("fed_room_pdu")
self.third_party_event_rules = hs.get_third_party_event_rules()
@defer.inlineCallbacks
def on_receive_pdu(self, origin, pdu, sent_to_us_directly=False):
room_id = pdu.room_id
event_id = pdu.event_id
logger.info("[%s %s] handling received PDU: %s", room_id, event_id, pdu)
existing = yield self.store.get_event(
event_id, allow_none=True, allow_rejected=True
)
already_seen = existing and (
not existing.internal_metadata.is_outlier()
or pdu.internal_metadata.is_outlier()
)
if already_seen:
logger.debug("[%s %s]: Already seen pdu", room_id, event_id)
return
# could cause a huge state resolution or cascade of event fetches.
try:
self._sanity_check_event(pdu)
except SynapseError as err:
logger.warn(
"[%s %s] Received event failed sanity checks", room_id, event_id
)
raise FederationError("ERROR", err.code, err.msg, affected=pdu.event_id)
# If we are currently in the process of joining this room, then we
# queue up events for later processing.
if room_id in self.room_queues:
logger.info(
"[%s %s] Queuing PDU from %s for now: join in progress",
room_id,
event_id,
origin,
)
self.room_queues[room_id].append((pdu, origin))
return
# If we're not in the room just ditch the event entirely. This is
# the room (or we've been rejoined to the room by a state reset).
is_in_room = yield self.auth.check_host_in_room(room_id, self.server_name)
if not is_in_room:
logger.info(
"[%s %s] Ignoring PDU from %s as we're not in the room",
room_id,
event_id,
origin,
)
return None
state = None
auth_chain = []
if not pdu.internal_metadata.is_outlier():
min_depth = yield self.get_min_depth_for_context(pdu.room_id)
logger.debug("[%s %s] min_depth: %d", room_id, event_id, min_depth)
prevs = set(pdu.prev_event_ids())
seen = yield self.store.have_seen_events(prevs)
if min_depth and pdu.depth < min_depth:
# message, to work around the fact that some events will
# reference really really old events we really don't want to
pdu.internal_metadata.outlier = True
elif min_depth and pdu.depth > min_depth:
missing_prevs = prevs - seen
if sent_to_us_directly and missing_prevs:
# at a time.
logger.info(
"[%s %s] Acquiring room lock to fetch %d missing prev_events: %s",
room_id,
event_id,
len(missing_prevs),
shortstr(missing_prevs),
)
with (yield self._room_pdu_linearizer.queue(pdu.room_id)):
logger.info(
"[%s %s] Acquired room lock to fetch %d missing prev_events",
room_id,
event_id,
len(missing_prevs),
)
yield self._get_missing_events_for_pdu(
origin, pdu, prevs, min_depth
)
# Update the set of things we've seen after trying to
seen = yield self.store.have_seen_events(prevs)
if not prevs - seen:
logger.info(
"[%s %s] Found all missing prev_events",
room_id,
event_id,
)
elif missing_prevs:
logger.info(
"[%s %s] Not recursively fetching %d missing prev_events: %s",
room_id,
event_id,
len(missing_prevs),
shortstr(missing_prevs),
)
if prevs - seen:
#
# In this case, we need to fall back to asking another server in the
# federation for the state at this event. That's ok provided we then
# withholding its prev_events, and declaring yourself to be an admin in
# the subsequent state request).
#
# Now, if we're pulling this event as a missing prev_event, then clearly
# following.
if sent_to_us_directly:
logger.warn(
"[%s %s] Rejecting: failed to fetch %d prev events: %s",
room_id,
event_id,
len(prevs - seen),
shortstr(prevs - seen),
)
raise FederationError(
"ERROR",
403,
(
"Your server isn't divulging details about prev_events "
"referenced in this event."
),
affected=pdu.event_id,
)
auth_chains = set()
event_map = {event_id: pdu}
try:
ours = yield self.store.get_state_groups_ids(room_id, seen)
state_maps = list(
ours.values()
)
del ours
# know about
for p in prevs - seen:
logger.info(
"[%s %s] Requesting state at missing prev_event %s",
room_id,
event_id,
p,
)
room_version = yield self.store.get_room_version(room_id)
with nested_logging_context(p):
# note that if any of the missing prevs share missing state or
# auth events, the requests to fetch those events are deduped
# by the get_pdu_cache in federation_client.
remote_state, got_auth_chain = (
yield self.federation_client.get_state_for_room(
origin, room_id, p
)
)
# we want the state *after* p; get_state_for_room returns the
# state *before* p.
remote_event = yield self.federation_client.get_pdu(
[origin], p, room_version, outlier=True
)
if remote_event is None:
raise Exception(
"Unable to get missing prev_event %s" % (p,)
)
if remote_event.is_state():
remote_state.append(remote_event)
# XXX hrm I'm not convinced that duplicate events will compare
# hoped.
auth_chains.update(got_auth_chain)
remote_state_map = {
(x.type, x.state_key): x.event_id for x in remote_state
}
state_maps.append(remote_state_map)
for x in remote_state:
event_map[x.event_id] = x
state_map = yield resolve_events_with_store(
room_version,
state_maps,
event_map,
state_res_store=StateResolutionStore(self.store),
)
# We need to give _process_received_pdu the actual state events
# rather than event ids, so generate that now.
# First though we need to fetch all the events that are in
# state_map, so we can build up the state below.
evs = yield self.store.get_events(
list(state_map.values()),
get_prev_content=False,
check_redacted=False,
)
event_map.update(evs)
state = [event_map[e] for e in six.itervalues(state_map)]
auth_chain = list(auth_chains)
except Exception:
logger.warn(
"[%s %s] Error attempting to resolve state at missing "
"prev_events",
room_id,
event_id,
exc_info=True,
)
raise FederationError(
"ERROR",
403,
"We can't get valid state history.",
affected=event_id,
)
yield self._process_received_pdu(
origin, pdu, state=state, auth_chain=auth_chain
)
@defer.inlineCallbacks
def _get_missing_events_for_pdu(self, origin, pdu, prevs, min_depth):
room_id = pdu.room_id
event_id = pdu.event_id
seen = yield self.store.have_seen_events(prevs)
if not prevs - seen:
return
latest = yield self.store.get_latest_event_ids_in_room(room_id)
latest = set(latest)
latest |= seen
logger.info(
"[%s %s]: Requesting missing events between %s and %s",
room_id,
event_id,
shortstr(latest),
event_id,
)
# XXX: we set timeout to 10s to help workaround
# https://github.com/matrix-org/synapse/issues/1733.
# The reason is to avoid holding the linearizer lock
# whilst processing inbound /send transactions, causing
# FDs to stack up and block other inbound transactions
# which empirically can currently take up to 30 minutes.
#
# N.B. this explicitly disables retry attempts.
#
# N.B. this also increases our chances of falling back to
# fetching fresh state for the room if the missing event
# can't be found, which slightly reduces our security.
# apparently.
#
# see https://github.com/matrix-org/synapse/pull/1744
#
# ----
#
# Update richvdh 2018/09/18: There are a number of problems with timing this
# request out agressively on the client side:
#
# - it plays badly with the server-side rate-limiter, which starts tarpitting you
# if you send too many requests at once, so you end up with the server carefully
# working through the backlog of your requests, which you have already timed
# out.
#
# - for this request in particular, we now (as of
# https://github.com/matrix-org/synapse/pull/3456) reject any PDUs where the
# server can't produce a plausible-looking set of prev_events - so we becone
# problem.
#
# - the agressive 10s timeout was introduced to deal with incoming federation
# requests taking 8 hours to process. It's not entirely clear why that was going
#
# All that said: Let's try increasing the timout to 60s and see what happens.
try:
missing_events = yield self.federation_client.get_missing_events(
origin,
room_id,
earliest_events_ids=list(latest),
latest_events=[pdu],
limit=10,
min_depth=min_depth,
timeout=60000,
)
except RequestSendFailed as e:
logger.warn("[%s %s]: Failed to get prev_events: %s", room_id, event_id, e)
return
logger.info(
"[%s %s]: Got %d prev_events: %s",
room_id,
event_id,
len(missing_events),
shortstr(missing_events),
)
missing_events.sort(key=lambda x: x.depth)
for ev in missing_events:
logger.info(
"[%s %s] Handling received prev_event %s",
room_id,
event_id,
ev.event_id,
)
with nested_logging_context(ev.event_id):
try:
yield self.on_receive_pdu(origin, ev, sent_to_us_directly=False)
except FederationError as e:
if e.code == 403:
logger.warn(
"[%s %s] Received prev_event %s failed history check.",
room_id,
event_id,
ev.event_id,
)
else:
raise
@defer.inlineCallbacks
def _process_received_pdu(self, origin, event, state, auth_chain):
room_id = event.room_id
event_id = event.event_id
logger.debug("[%s %s] Processing event: %s", room_id, event_id, event)
event_ids = set()
if state:
event_ids |= {e.event_id for e in state}
if auth_chain:
event_ids |= {e.event_id for e in auth_chain}
seen_ids = yield self.store.have_seen_events(event_ids)
if state and auth_chain is not None:
event_infos = []
for e in itertools.chain(auth_chain, state):
if e.event_id in seen_ids:
continue
e.internal_metadata.outlier = True
auth_ids = e.auth_event_ids()
auth = {
(e.type, e.state_key): e
for e in auth_chain
if e.event_id in auth_ids or e.type == EventTypes.Create
}
event_infos.append({"event": e, "auth_events": auth})
seen_ids.add(e.event_id)
logger.info(
"[%s %s] persisting newly-received auth/state events %s",
room_id,
event_id,
[e["event"].event_id for e in event_infos],
)
yield self._handle_new_events(origin, event_infos)
try:
context = yield self._handle_new_event(origin, event, state=state)
except AuthError as e:
raise FederationError("ERROR", e.code, e.msg, affected=event.event_id)
room = yield self.store.get_room(room_id)
if not room:
try:
yield self.store.store_room(
room_id=room_id, room_creator_user_id="", is_public=False
)
except StoreError:
logger.exception("Failed to store room.")
if event.type == EventTypes.Member:
if event.membership == Membership.JOIN:
# Only fire user_joined_room if the user has acutally
# joined the room. Don't bother if the user is just
newly_joined = True
prev_state_ids = yield context.get_prev_state_ids(self.store)
prev_state_id = prev_state_ids.get((event.type, event.state_key))
if prev_state_id:
prev_state = yield self.store.get_event(
prev_state_id, allow_none=True
)
if prev_state and prev_state.membership == Membership.JOIN:
newly_joined = False
if newly_joined:
user = UserID.from_string(event.state_key)
yield self.user_joined_room(user, room_id)
@log_function
@defer.inlineCallbacks
def backfill(self, dest, room_id, limit, extremities):
if dest == self.server_name:
raise SynapseError(400, "Can't backfill from self.")
room_version = yield self.store.get_room_version(room_id)
events = yield self.federation_client.backfill(
dest, room_id, limit=limit, extremities=extremities
)
# ideally we'd sanity check the events here for excess prev_events etc,
# breaking backfill in the same way that it is currently broken by
# events whose signature we cannot verify (#3121).
#
# So for now we accept the events anyway. #3124 tracks this.
#
# for ev in events:
# self._sanity_check_event(ev)
# Don't bother processing events we already have.
seen_events = yield self.store.have_events_in_timeline(
set(e.event_id for e in events)
)
events = [e for e in events if e.event_id not in seen_events]
if not events:
return []
event_map = {e.event_id: e for e in events}
event_ids = set(e.event_id for e in events)
edges = [ev.event_id for ev in events if set(ev.prev_event_ids()) - event_ids]
logger.info("backfill: Got %d events with %d edges", len(events), len(edges))
auth_events = {}
state_events = {}
events_to_state = {}
for e_id in edges:
state, auth = yield self.federation_client.get_state_for_room(
destination=dest, room_id=room_id, event_id=e_id
)
auth_events.update({a.event_id: a for a in auth})
auth_events.update({s.event_id: s for s in state})
state_events.update({s.event_id: s for s in state})
events_to_state[e_id] = state
required_auth = set(
a_id
for event in events
+ list(state_events.values())
+ list(auth_events.values())
for a_id in event.auth_event_ids()
)
auth_events.update(
{e_id: event_map[e_id] for e_id in required_auth if e_id in event_map}
)
missing_auth = required_auth - set(auth_events)
failed_to_fetch = set()
while missing_auth - failed_to_fetch:
logger.info("Missing auth for backfill: %r", missing_auth)
ret_events = yield self.store.get_events(missing_auth - failed_to_fetch)
auth_events.update(ret_events)
required_auth.update(
a_id for event in ret_events.values() for a_id in event.auth_event_ids()
)
missing_auth = required_auth - set(auth_events)
if missing_auth - failed_to_fetch:
logger.info(
"Fetching missing auth for backfill: %r",
missing_auth - failed_to_fetch,
)
results = yield make_deferred_yieldable(
defer.gatherResults(
[
run_in_background(
self.federation_client.get_pdu,
[dest],
event_id,
room_version=room_version,
outlier=True,
timeout=10000,
)
for event_id in missing_auth - failed_to_fetch
],
consumeErrors=True,
)
).addErrback(unwrapFirstError)
auth_events.update({a.event_id: a for a in results if a})
required_auth.update(
a_id
for event in results
if event
for a_id in event.auth_event_ids()
)
missing_auth = required_auth - set(auth_events)
failed_to_fetch = missing_auth - set(auth_events)
seen_events = yield self.store.have_seen_events(
set(auth_events.keys()) | set(state_events.keys())
)
ev_infos = []
for a in auth_events.values():
# We only want to persist auth events as outliers that we haven't
if a.event_id in seen_events or a.event_id in event_map:
continue
a.internal_metadata.outlier = True
ev_infos.append(
{
"event": a,
"auth_events": {
(
auth_events[a_id].type,
auth_events[a_id].state_key,
): auth_events[a_id]
for a_id in a.auth_event_ids()
if a_id in auth_events
},
}
)
# Step 1b: persist the events in the chunk we fetched state for (i.e.
# the backwards extremities) as non-outliers.
for e_id in events_to_state:
# For paranoia we ensure that these events are marked as
# non-outliers
ev = event_map[e_id]
assert not ev.internal_metadata.is_outlier()
ev_infos.append(
{
"event": ev,
"state": events_to_state[e_id],
"auth_events": {
(
auth_events[a_id].type,
auth_events[a_id].state_key,
): auth_events[a_id]
for a_id in ev.auth_event_ids()
if a_id in auth_events
},
}
)
yield self._handle_new_events(dest, ev_infos, backfilled=True)
# Step 2: Persist the rest of the events in the chunk one by one
events.sort(key=lambda e: e.depth)
for event in events:
if event in events_to_state:
continue
# For paranoia we ensure that these events are marked as
# non-outliers
assert not event.internal_metadata.is_outlier()
# We store these one at a time since each event depends on the
# previous to work out the state.
# TODO: We can probably do something more clever here.
yield self._handle_new_event(dest, event, backfilled=True)
return events
@defer.inlineCallbacks
def maybe_backfill(self, room_id, current_depth):
extremities = yield self.store.get_oldest_events_with_depth_in_room(room_id)
if not extremities:
logger.debug("Not backfilling as no extremeties found.")
return
# We only want to paginate if we can actually see the events we'll get,
# events.
#
# We do this by filtering all the backwards extremities and seeing if
# any remain. Given we don't have the extremity events themselves, we
forward_events = yield self.store.get_successor_events(list(extremities))
extremities_events = yield self.store.get_events(
forward_events, check_redacted=False, get_prev_content=False
)
filtered_extremities = yield filter_events_for_server(
self.store,
self.server_name,
list(extremities_events.values()),
redact=False,
check_history_visibility_only=True,
)
if not filtered_extremities:
return False
sorted_extremeties_tuple = sorted(extremities.items(), key=lambda e: -int(e[1]))
max_depth = sorted_extremeties_tuple[0][1]
# request URI to be too long.
extremities = dict(sorted_extremeties_tuple[:5])
if current_depth > max_depth:
logger.debug(
"Not backfilling as we don't need to. %d < %d", max_depth, current_depth
)
return
curr_state = yield self.state_handler.get_current_state(room_id)
def get_domains_from_state(state):
joined_users = [
(state_key, int(event.depth))
for (e_type, state_key), event in iteritems(state)
if e_type == EventTypes.Member and event.membership == Membership.JOIN
]
joined_domains = {}
for u, d in joined_users:
try:
dom = get_domain_from_id(u)
old_d = joined_domains.get(dom)
if old_d:
joined_domains[dom] = min(d, old_d)
else:
joined_domains[dom] = d
except Exception:
pass
return sorted(joined_domains.items(), key=lambda d: d[1])
curr_domains = get_domains_from_state(curr_state)
likely_domains = [
domain for domain, depth in curr_domains if domain != self.server_name
]
@defer.inlineCallbacks
def try_backfill(domains):
for dom in domains:
try:
yield self.backfill(
dom, room_id, limit=100, extremities=extremities
)
return True
except SynapseError as e:
logger.info("Failed to backfill from %s because %s", dom, e)
continue
except CodeMessageException as e:
if 400 <= e.code < 500:
raise
logger.info("Failed to backfill from %s because %s", dom, e)
continue
except NotRetryingDestination as e:
logger.info(str(e))
continue
except RequestSendFailed as e:
logger.info("Falied to get backfill from %s because %s", dom, e)
continue
except FederationDeniedError as e:
logger.info(e)
continue
except Exception as e:
logger.exception("Failed to backfill from %s because %s", dom, e)
continue
return False
success = yield try_backfill(likely_domains)
if success:
return True
# from the time.
tried_domains = set(likely_domains)
tried_domains.add(self.server_name)
event_ids = list(extremities.keys())
logger.debug("calling resolve_state_groups in _maybe_backfill")
resolve = preserve_fn(self.state_handler.resolve_state_groups_for_events)
states = yield make_deferred_yieldable(
defer.gatherResults(
[resolve(room_id, [e]) for e in event_ids], consumeErrors=True
)
)
# dict[str, dict[tuple, str]], a map from event_id to state map of
# event_ids.
states = dict(zip(event_ids, [s.state for s in states]))
state_map = yield self.store.get_events(
[e_id for ids in itervalues(states) for e_id in itervalues(ids)],
get_prev_content=False,
)
states = {
key: {
k: state_map[e_id]
for k, e_id in iteritems(state_dict)
if e_id in state_map
}
for key, state_dict in iteritems(states)
}
for e_id, _ in sorted_extremeties_tuple:
likely_domains = get_domains_from_state(states[e_id])
success = yield try_backfill(
[dom for dom, _ in likely_domains if dom not in tried_domains]
)
if success:
return True
tried_domains.update(dom for dom, _ in likely_domains)
return False
def _sanity_check_event(self, ev):
if len(ev.prev_event_ids()) > 20:
logger.warn(
"Rejecting event %s which has %i prev_events",
ev.event_id,
len(ev.prev_event_ids()),
)
raise SynapseError(http_client.BAD_REQUEST, "Too many prev_events")
if len(ev.auth_event_ids()) > 10:
logger.warn(
"Rejecting event %s which has %i auth_events",
ev.event_id,
len(ev.auth_event_ids()),
)
raise SynapseError(http_client.BAD_REQUEST, "Too many auth_events")
@defer.inlineCallbacks
def send_invite(self, target_host, event):
pdu = yield self.federation_client.send_invite(
destination=target_host,
room_id=event.room_id,
event_id=event.event_id,
pdu=event,
)
return pdu
@defer.inlineCallbacks
def on_event_auth(self, event_id):
event = yield self.store.get_event(event_id)
auth = yield self.store.get_auth_chain(
[auth_id for auth_id in event.auth_event_ids()], include_given=True
)
return [e for e in auth]
@log_function
@defer.inlineCallbacks
def do_invite_join(self, target_hosts, room_id, joinee, content):
logger.debug("Joining %s to %s", joinee, room_id)
origin, event, event_format_version = yield self._make_and_verify_event(
target_hosts,
room_id,
joinee,
"join",
content,
params={"ver": KNOWN_ROOM_VERSIONS},
)
# This shouldn't happen, because the RoomMemberHandler has a
assert room_id not in self.room_queues
self.room_queues[room_id] = []
yield self._clean_room_for_join(room_id)
handled_events = set()
try:
try:
target_hosts.remove(origin)
target_hosts.insert(0, origin)
except ValueError:
pass
ret = yield self.federation_client.send_join(
target_hosts, event, event_format_version
)
origin = ret["origin"]
state = ret["state"]
auth_chain = ret["auth_chain"]
auth_chain.sort(key=lambda e: e.depth)
handled_events.update([s.event_id for s in state])
handled_events.update([a.event_id for a in auth_chain])
handled_events.add(event.event_id)
logger.debug("do_invite_join auth_chain: %s", auth_chain)
logger.debug("do_invite_join state: %s", state)
logger.debug("do_invite_join event: %s", event)
try:
yield self.store.store_room(
room_id=room_id, room_creator_user_id="", is_public=False
)
except Exception:
pass
yield self._persist_auth_tree(origin, auth_chain, state, event)
logger.debug("Finished joining %s to %s", joinee, room_id)
finally:
room_queue = self.room_queues[room_id]
del self.room_queues[room_id]
# it's just a best-effort thing at this point. We do want to do
# lots of requests for missing prev_events which we do actually
# have. Hence we fire off the deferred, but don't wait for it.
run_in_background(self._handle_queued_pdus, room_queue)
return True
@defer.inlineCallbacks
def _handle_queued_pdus(self, room_queue):
for p, origin in room_queue:
try:
logger.info(
"Processing queued PDU %s which was received "
"while we were joining %s",
p.event_id,
p.room_id,
)
with nested_logging_context(p.event_id):
yield self.on_receive_pdu(origin, p, sent_to_us_directly=True)
except Exception as e:
logger.warn(
"Error handling queued PDU %s from %s: %s", p.event_id, origin, e
)
@defer.inlineCallbacks
@log_function
def on_make_join_request(self, origin, room_id, user_id):
if get_domain_from_id(user_id) != origin:
logger.info(
"Got /make_join request for user %r from different origin %s, ignoring",
user_id,
origin,
)
raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
event_content = {"membership": Membership.JOIN}
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(
room_version,
{
"type": EventTypes.Member,
"content": event_content,
"room_id": room_id,
"sender": user_id,
"state_key": user_id,
},
)
try:
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
except AuthError as e:
logger.warn("Failed to create join %r because %s", event, e)
raise e
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info("Creation of join %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
yield self.auth.check_from_context(
room_version, event, context, do_sig_check=False
)
return event
@defer.inlineCallbacks
@log_function
def on_send_join_request(self, origin, pdu):
event = pdu
logger.debug(
"on_send_join_request: Got event: %s, signatures: %s",
event.event_id,
event.signatures,
)
event.internal_metadata.outlier = False
# the join event over federation after joining, and changing it now
# would introduce the danger of backwards-compatibility problems.
event.internal_metadata.send_on_behalf_of = origin
context = yield self._handle_new_event(origin, event)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info("Sending of join %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
logger.debug(
"on_send_join_request: After _handle_new_event: %s, sigs: %s",
event.event_id,
event.signatures,
)
if event.type == EventTypes.Member:
if event.content["membership"] == Membership.JOIN:
user = UserID.from_string(event.state_key)
yield self.user_joined_room(user, event.room_id)
prev_state_ids = yield context.get_prev_state_ids(self.store)
state_ids = list(prev_state_ids.values())
auth_chain = yield self.store.get_auth_chain(state_ids)
state = yield self.store.get_events(list(prev_state_ids.values()))
return {"state": list(state.values()), "auth_chain": auth_chain}
@defer.inlineCallbacks
def on_invite_request(self, origin, pdu):
event = pdu
if event.state_key is None:
raise SynapseError(400, "The invite event did not have a state key")
is_blocked = yield self.store.is_room_blocked(event.room_id)
if is_blocked:
raise SynapseError(403, "This room has been blocked on this server")
if self.hs.config.block_non_admin_invites:
raise SynapseError(403, "This server does not accept room invites")
if not self.spam_checker.user_may_invite(
event.sender, event.state_key, event.room_id
):
raise SynapseError(
403, "This user is not permitted to send invites to this server/user"
)
membership = event.content.get("membership")
if event.type != EventTypes.Member or membership != Membership.INVITE:
raise SynapseError(400, "The event was not an m.room.member invite event")
sender_domain = get_domain_from_id(event.sender)
if sender_domain != origin:
raise SynapseError(
400, "The invite event was not from the server sending it"
)
if not self.is_mine_id(event.state_key):
raise SynapseError(400, "The invite event must be for this server")
# block any attempts to invite the server notices mxid
if event.state_key == self._server_notices_mxid:
raise SynapseError(http_client.FORBIDDEN, "Cannot invite this user")
event.internal_metadata.outlier = True
event.internal_metadata.out_of_band_membership = True
event.signatures.update(
compute_event_signature(
event.get_pdu_json(), self.hs.hostname, self.hs.config.signing_key[0]
)
)
context = yield self.state_handler.compute_event_context(event)
yield self.persist_events_and_notify([(event, context)])
return event
@defer.inlineCallbacks
def do_remotely_reject_invite(self, target_hosts, room_id, user_id):
origin, event, event_format_version = yield self._make_and_verify_event(
target_hosts, room_id, user_id, "leave"
)
# Mark as outlier as we don't have any state for this event; we're not
# even in the room.
event.internal_metadata.outlier = True
event.internal_metadata.out_of_band_membership = True
# Try the host that we succesfully called /make_leave/ on first for
# the /send_leave/ request.
try:
target_hosts.remove(origin)
target_hosts.insert(0, origin)
except ValueError:
pass
yield self.federation_client.send_leave(target_hosts, event)
context = yield self.state_handler.compute_event_context(event)
yield self.persist_events_and_notify([(event, context)])
return event
@defer.inlineCallbacks
def _make_and_verify_event(
self, target_hosts, room_id, user_id, membership, content={}, params=None
):
origin, event, format_ver = yield self.federation_client.make_membership_event(
target_hosts, room_id, user_id, membership, content, params=params
)
logger.debug("Got response to make_%s: %s", membership, event)
# We should assert some things.
# FIXME: Do this in a nicer way
assert event.type == EventTypes.Member
assert event.user_id == user_id
assert event.state_key == user_id
assert event.room_id == room_id
return origin, event, format_ver
@defer.inlineCallbacks
@log_function
def on_make_leave_request(self, origin, room_id, user_id):
if get_domain_from_id(user_id) != origin:
logger.info(
"Got /make_leave request for user %r from different origin %s, ignoring",
user_id,
origin,
)
raise SynapseError(403, "User not from origin", Codes.FORBIDDEN)
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(
room_version,
{
"type": EventTypes.Member,
"content": {"membership": Membership.LEAVE},
"room_id": room_id,
"sender": user_id,
"state_key": user_id,
},
)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.warning("Creation of leave %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
try:
# The remote hasn't signed it yet, obviously. We'll do the full checks
# when we get the event back in `on_send_leave_request`
yield self.auth.check_from_context(
room_version, event, context, do_sig_check=False
)
except AuthError as e:
logger.warn("Failed to create new leave %r because %s", event, e)
raise e
return event
@defer.inlineCallbacks
@log_function
def on_send_leave_request(self, origin, pdu):
event = pdu
logger.debug(
"on_send_leave_request: Got event: %s, signatures: %s",
event.event_id,
event.signatures,
)
event.internal_metadata.outlier = False
context = yield self._handle_new_event(origin, event)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info("Sending of leave %s forbidden by third-party rules", event)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
logger.debug(
"on_send_leave_request: After _handle_new_event: %s, sigs: %s",
event.event_id,
event.signatures,
)
return None
@defer.inlineCallbacks
def get_state_for_pdu(self, room_id, event_id):
event = yield self.store.get_event(
event_id, allow_none=False, check_room_id=room_id
)
state_groups = yield self.store.get_state_groups(room_id, [event_id])
if state_groups:
_, state = list(iteritems(state_groups)).pop()
results = {(e.type, e.state_key): e for e in state}
if event.is_state():
# Get previous state
if "replaces_state" in event.unsigned:
prev_id = event.unsigned["replaces_state"]
if prev_id != event.event_id:
prev_event = yield self.store.get_event(prev_id)
results[(event.type, event.state_key)] = prev_event
else:
del results[(event.type, event.state_key)]
res = list(results.values())
return res
else:
return []
@defer.inlineCallbacks
def get_state_ids_for_pdu(self, room_id, event_id):
event = yield self.store.get_event(
event_id, allow_none=False, check_room_id=room_id
)
state_groups = yield self.store.get_state_groups_ids(room_id, [event_id])
if state_groups:
_, state = list(state_groups.items()).pop()
results = state
if event.is_state():
# Get previous state
if "replaces_state" in event.unsigned:
prev_id = event.unsigned["replaces_state"]
if prev_id != event.event_id:
results[(event.type, event.state_key)] = prev_id
else:
results.pop((event.type, event.state_key), None)
return list(results.values())
else:
return []
@defer.inlineCallbacks
@log_function
def on_backfill_request(self, origin, room_id, pdu_list, limit):
in_room = yield self.auth.check_host_in_room(room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
events = yield self.store.get_backfill_events(room_id, pdu_list, limit)
events = yield filter_events_for_server(self.store, origin, events)
return events
@defer.inlineCallbacks
@log_function
def get_persisted_pdu(self, origin, event_id):
event = yield self.store.get_event(
event_id, allow_none=True, allow_rejected=True
)
if event:
in_room = yield self.auth.check_host_in_room(event.room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
events = yield filter_events_for_server(self.store, origin, [event])
event = events[0]
return event
else:
return None
def get_min_depth_for_context(self, context):
return self.store.get_min_depth(context)
@defer.inlineCallbacks
def _handle_new_event(
self, origin, event, state=None, auth_events=None, backfilled=False
):
context = yield self._prep_event(
origin, event, state=state, auth_events=auth_events, backfilled=backfilled
)
# reraise does not allow inlineCallbacks to preserve the stacktrace, so we
# hack around with a try/finally instead.
success = False
try:
if not event.internal_metadata.is_outlier() and not backfilled:
yield self.action_generator.handle_push_actions_for_event(
event, context
)
yield self.persist_events_and_notify(
[(event, context)], backfilled=backfilled
)
success = True
finally:
if not success:
run_in_background(
self.store.remove_push_actions_from_staging, event.event_id
)
return context
@defer.inlineCallbacks
def _handle_new_events(self, origin, event_infos, backfilled=False):
@defer.inlineCallbacks
def prep(ev_info):
event = ev_info["event"]
with nested_logging_context(suffix=event.event_id):
res = yield self._prep_event(
origin,
event,
state=ev_info.get("state"),
auth_events=ev_info.get("auth_events"),
backfilled=backfilled,
)
return res
contexts = yield make_deferred_yieldable(
defer.gatherResults(
[run_in_background(prep, ev_info) for ev_info in event_infos],
consumeErrors=True,
)
)
yield self.persist_events_and_notify(
[
(ev_info["event"], context)
for ev_info, context in zip(event_infos, contexts)
],
backfilled=backfilled,
)
@defer.inlineCallbacks
def _persist_auth_tree(self, origin, auth_events, state, event):
events_to_context = {}
for e in itertools.chain(auth_events, state):
e.internal_metadata.outlier = True
ctx = yield self.state_handler.compute_event_context(e)
events_to_context[e.event_id] = ctx
event_map = {
e.event_id: e for e in itertools.chain(auth_events, state, [event])
}
create_event = None
for e in auth_events:
if (e.type, e.state_key) == (EventTypes.Create, ""):
create_event = e
break
if create_event is None:
# If the state doesn't have a create event then the room is
raise SynapseError(400, "No create event in state")
room_version = create_event.content.get(
"room_version", RoomVersions.V1.identifier
)
missing_auth_events = set()
for e in itertools.chain(auth_events, state, [event]):
for e_id in e.auth_event_ids():
if e_id not in event_map:
missing_auth_events.add(e_id)
for e_id in missing_auth_events:
m_ev = yield self.federation_client.get_pdu(
[origin], e_id, room_version=room_version, outlier=True, timeout=10000
)
if m_ev and m_ev.event_id == e_id:
event_map[e_id] = m_ev
else:
logger.info("Failed to find auth event %r", e_id)
for e in itertools.chain(auth_events, state, [event]):
auth_for_e = {
(event_map[e_id].type, event_map[e_id].state_key): event_map[e_id]
for e_id in e.auth_event_ids()
if e_id in event_map
}
if create_event:
auth_for_e[(EventTypes.Create, "")] = create_event
try:
self.auth.check(room_version, e, auth_events=auth_for_e)
except SynapseError as err:
# the attempt to federate altogether in such cases.
logger.warn("Rejecting %s because %s", e.event_id, err.msg)
if e == event:
raise
events_to_context[e.event_id].rejected = RejectedReason.AUTH_ERROR
yield self.persist_events_and_notify(
[
(e, events_to_context[e.event_id])
for e in itertools.chain(auth_events, state)
]
)
new_event_context = yield self.state_handler.compute_event_context(
event, old_state=state
)
yield self.persist_events_and_notify([(event, new_event_context)])
@defer.inlineCallbacks
def _prep_event(self, origin, event, state, auth_events, backfilled):
context = yield self.state_handler.compute_event_context(event, old_state=state)
if not auth_events:
prev_state_ids = yield context.get_prev_state_ids(self.store)
auth_events_ids = yield self.auth.compute_auth_events(
event, prev_state_ids, for_verification=True
)
auth_events = yield self.store.get_events(auth_events_ids)
auth_events = {(e.type, e.state_key): e for e in auth_events.values()}
# This is a hack to fix some old rooms where the initial join event
# didn't reference the create event in its auth events.
if event.type == EventTypes.Member and not event.auth_event_ids():
if len(event.prev_event_ids()) == 1 and event.depth < 5:
c = yield self.store.get_event(
event.prev_event_ids()[0], allow_none=True
)
if c and c.type == EventTypes.Create:
auth_events[(c.type, c.state_key)] = c
try:
yield self.do_auth(origin, event, context, auth_events=auth_events)
except AuthError as e:
logger.warn("[%s %s] Rejecting: %s", event.room_id, event.event_id, e.msg)
context.rejected = RejectedReason.AUTH_ERROR
if not context.rejected:
yield self._check_for_soft_fail(event, state, backfilled)
if event.type == EventTypes.GuestAccess and not context.rejected:
yield self.maybe_kick_guest_users(event)
return context
@defer.inlineCallbacks
def _check_for_soft_fail(self, event, state, backfilled):
# "soft-fail" the event.
do_soft_fail_check = not backfilled and not event.internal_metadata.is_outlier()
if do_soft_fail_check:
extrem_ids = yield self.store.get_latest_event_ids_in_room(event.room_id)
extrem_ids = set(extrem_ids)
prev_event_ids = set(event.prev_event_ids())
if extrem_ids == prev_event_ids:
# If they're the same then the current state is the same as the
do_soft_fail_check = False
if do_soft_fail_check:
room_version = yield self.store.get_room_version(event.room_id)
if state is not None:
state_sets = yield self.store.get_state_groups(
event.room_id, extrem_ids
)
state_sets = list(state_sets.values())
state_sets.append(state)
current_state_ids = yield self.state_handler.resolve_events(
room_version, state_sets, event
)
current_state_ids = {
k: e.event_id for k, e in iteritems(current_state_ids)
}
else:
current_state_ids = yield self.state_handler.get_current_state_ids(
event.room_id, latest_event_ids=extrem_ids
)
logger.debug(
"Doing soft-fail check for %s: state %s",
event.event_id,
current_state_ids,
)
auth_types = auth_types_for_event(event)
current_state_ids = [
e for k, e in iteritems(current_state_ids) if k in auth_types
]
current_auth_events = yield self.store.get_events(current_state_ids)
current_auth_events = {
(e.type, e.state_key): e for e in current_auth_events.values()
}
try:
self.auth.check(room_version, event, auth_events=current_auth_events)
except AuthError as e:
logger.warn("Soft-failing %r because %s", event, e)
event.internal_metadata.soft_failed = True
@defer.inlineCallbacks
def on_query_auth(
self, origin, event_id, room_id, remote_auth_chain, rejects, missing
):
in_room = yield self.auth.check_host_in_room(room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
event = yield self.store.get_event(
event_id, allow_none=False, check_room_id=room_id
)
for e in remote_auth_chain:
try:
yield self._handle_new_event(origin, e)
except AuthError:
pass
# Now get the current auth_chain for the event.
local_auth_chain = yield self.store.get_auth_chain(
[auth_id for auth_id in event.auth_event_ids()], include_given=True
)
# TODO: Check if we would now reject event_id. If so we need to tell
# everyone.
ret = yield self.construct_auth_difference(local_auth_chain, remote_auth_chain)
logger.debug("on_query_auth returning: %s", ret)
return ret
@defer.inlineCallbacks
def on_get_missing_events(
self, origin, room_id, earliest_events, latest_events, limit
):
in_room = yield self.auth.check_host_in_room(room_id, origin)
if not in_room:
raise AuthError(403, "Host not in room.")
limit = min(limit, 20)
missing_events = yield self.store.get_missing_events(
room_id=room_id,
earliest_events=earliest_events,
latest_events=latest_events,
limit=limit,
)
missing_events = yield filter_events_for_server(
self.store, origin, missing_events
)
return missing_events
@defer.inlineCallbacks
@log_function
def do_auth(self, origin, event, context, auth_events):
room_version = yield self.store.get_room_version(event.room_id)
try:
yield self._update_auth_events_and_context_for_auth(
origin, event, context, auth_events
)
except Exception:
# We don't really mind if the above fails, so lets not fail
# let's still log as an exception since we'll still want to fix
# any bugs.
logger.exception(
"Failed to double check auth events for %s with remote. "
"Ignoring failure and continuing processing of event.",
event.event_id,
)
try:
self.auth.check(room_version, event, auth_events=auth_events)
except AuthError as e:
logger.warn("Failed auth resolution for %r because %s", event, e)
raise e
@defer.inlineCallbacks
def _update_auth_events_and_context_for_auth(
self, origin, event, context, auth_events
):
event_auth_events = set(event.auth_event_ids())
if event.is_state():
event_key = (event.type, event.state_key)
else:
event_key = None
# if the event's auth_events refers to events which are not in our
missing_auth = event_auth_events.difference(
e.event_id for e in auth_events.values()
)
if missing_auth:
have_events = yield self.store.get_seen_events_with_rejections(missing_auth)
logger.debug("Got events %s from store", have_events)
missing_auth.difference_update(have_events.keys())
else:
have_events = {}
have_events.update({e.event_id: "" for e in auth_events.values()})
if missing_auth:
logger.info("auth_events contains unknown events: %s", missing_auth)
try:
try:
remote_auth_chain = yield self.federation_client.get_event_auth(
origin, event.room_id, event.event_id
)
except RequestSendFailed as e:
# The other side isn't around or doesn't implement the
# endpoint, so lets just bail out.
logger.info("Failed to get event auth from remote: %s", e)
return
seen_remotes = yield self.store.have_seen_events(
[e.event_id for e in remote_auth_chain]
)
for e in remote_auth_chain:
if e.event_id in seen_remotes:
continue
if e.event_id == event.event_id:
continue
try:
auth_ids = e.auth_event_ids()
auth = {
(e.type, e.state_key): e
for e in remote_auth_chain
if e.event_id in auth_ids or e.type == EventTypes.Create
}
e.internal_metadata.outlier = True
logger.debug(
"do_auth %s missing_auth: %s", event.event_id, e.event_id
)
yield self._handle_new_event(origin, e, auth_events=auth)
if e.event_id in event_auth_events:
auth_events[(e.type, e.state_key)] = e
except AuthError:
pass
have_events = yield self.store.get_seen_events_with_rejections(
event.auth_event_ids()
)
except Exception:
# FIXME:
logger.exception("Failed to get auth chain")
if event.internal_metadata.is_outlier():
logger.info("Skipping auth_event fetch for outlier")
return
# FIXME: Assumes we have and stored all the state for all the
# prev_events
different_auth = event_auth_events.difference(
e.event_id for e in auth_events.values()
)
if not different_auth:
return
logger.info(
"auth_events refers to events which are not in our calculated auth "
"chain: %s",
different_auth,
)
room_version = yield self.store.get_room_version(event.room_id)
different_events = yield make_deferred_yieldable(
defer.gatherResults(
[
run_in_background(
self.store.get_event, d, allow_none=True, allow_rejected=False
)
for d in different_auth
if d in have_events and not have_events[d]
],
consumeErrors=True,
)
).addErrback(unwrapFirstError)
if different_events:
local_view = dict(auth_events)
remote_view = dict(auth_events)
remote_view.update(
{(d.type, d.state_key): d for d in different_events if d}
)
new_state = yield self.state_handler.resolve_events(
room_version,
[list(local_view.values()), list(remote_view.values())],
event,
)
logger.info(
"After state res: updating auth_events with new state %s",
{
(d.type, d.state_key): d.event_id
for d in new_state.values()
if auth_events.get((d.type, d.state_key)) != d
},
)
auth_events.update(new_state)
different_auth = event_auth_events.difference(
e.event_id for e in auth_events.values()
)
yield self._update_context_for_auth_events(
event, context, auth_events, event_key
)
if not different_auth:
# we're done
return
logger.info(
"auth_events still refers to events which are not in the calculated auth "
"chain after state resolution: %s",
different_auth,
)
do_resolution = False
for e_id in different_auth:
if e_id in have_events:
if have_events[e_id] == RejectedReason.NOT_ANCESTOR:
do_resolution = True
break
if not do_resolution:
logger.info(
"Skipping auth resolution due to lack of provable rejection reasons"
)
return
logger.info("Doing auth resolution")
prev_state_ids = yield context.get_prev_state_ids(self.store)
# 1. Get what we think is the auth chain.
auth_ids = yield self.auth.compute_auth_events(event, prev_state_ids)
local_auth_chain = yield self.store.get_auth_chain(auth_ids, include_given=True)
try:
# 2. Get remote difference.
try:
result = yield self.federation_client.query_auth(
origin, event.room_id, event.event_id, local_auth_chain
)
except RequestSendFailed as e:
# The other side isn't around or doesn't implement the
# endpoint, so lets just bail out.
logger.info("Failed to query auth from remote: %s", e)
return
seen_remotes = yield self.store.have_seen_events(
[e.event_id for e in result["auth_chain"]]
)
# 3. Process any remote auth chain events we haven't seen.
for ev in result["auth_chain"]:
if ev.event_id in seen_remotes:
continue
if ev.event_id == event.event_id:
continue
try:
auth_ids = ev.auth_event_ids()
auth = {
(e.type, e.state_key): e
for e in result["auth_chain"]
if e.event_id in auth_ids or event.type == EventTypes.Create
}
ev.internal_metadata.outlier = True
logger.debug(
"do_auth %s different_auth: %s", event.event_id, e.event_id
)
yield self._handle_new_event(origin, ev, auth_events=auth)
if ev.event_id in event_auth_events:
auth_events[(ev.type, ev.state_key)] = ev
except AuthError:
pass
except Exception:
logger.exception("Failed to query auth chain")
yield self._update_context_for_auth_events(
event, context, auth_events, event_key
)
@defer.inlineCallbacks
def _update_context_for_auth_events(self, event, context, auth_events, event_key):
state_updates = {
k: a.event_id for k, a in iteritems(auth_events) if k != event_key
}
current_state_ids = yield context.get_current_state_ids(self.store)
current_state_ids = dict(current_state_ids)
current_state_ids.update(state_updates)
prev_state_ids = yield context.get_prev_state_ids(self.store)
prev_state_ids = dict(prev_state_ids)
prev_state_ids.update({k: a.event_id for k, a in iteritems(auth_events)})
prev_group = context.state_group
state_group = yield self.store.store_state_group(
event.event_id,
event.room_id,
prev_group=prev_group,
delta_ids=state_updates,
current_state_ids=current_state_ids,
)
yield context.update_state(
state_group=state_group,
current_state_ids=current_state_ids,
prev_state_ids=prev_state_ids,
prev_group=prev_group,
delta_ids=state_updates,
)
@defer.inlineCallbacks
def construct_auth_difference(self, local_auth, remote_auth):
logger.debug("construct_auth_difference Start!")
def sort_fun(ev):
return ev.depth, ev.event_id
logger.debug("construct_auth_difference after sort_fun!")
# missing that event, and iterate only up that list. Repeat.
remote_list = list(remote_auth)
remote_list.sort(key=sort_fun)
local_list = list(local_auth)
local_list.sort(key=sort_fun)
local_iter = iter(local_list)
remote_iter = iter(remote_list)
logger.debug("construct_auth_difference before get_next!")
def get_next(it, opt=None):
try:
return next(it)
except Exception:
return opt
current_local = get_next(local_iter)
current_remote = get_next(remote_iter)
logger.debug("construct_auth_difference before while")
missing_remotes = []
missing_locals = []
while current_local or current_remote:
if current_remote is None:
missing_locals.append(current_local)
current_local = get_next(local_iter)
continue
if current_local is None:
missing_remotes.append(current_remote)
current_remote = get_next(remote_iter)
continue
if current_local.event_id == current_remote.event_id:
current_local = get_next(local_iter)
current_remote = get_next(remote_iter)
continue
if current_local.depth < current_remote.depth:
missing_locals.append(current_local)
current_local = get_next(local_iter)
continue
if current_local.depth > current_remote.depth:
missing_remotes.append(current_remote)
current_remote = get_next(remote_iter)
continue
# They have the same depth, so we fall back to the event_id order
if current_local.event_id < current_remote.event_id:
missing_locals.append(current_local)
current_local = get_next(local_iter)
if current_local.event_id > current_remote.event_id:
missing_remotes.append(current_remote)
current_remote = get_next(remote_iter)
continue
logger.debug("construct_auth_difference after while")
# missing locals should be sent to the server
# We should find why we are missing remotes, as they will have been
# rejected.
# Remove events from missing_remotes if they are referencing a missing
# remote. We only care about the "root" rejected ones.
missing_remote_ids = [e.event_id for e in missing_remotes]
base_remote_rejected = list(missing_remotes)
for e in missing_remotes:
for e_id in e.auth_event_ids():
if e_id in missing_remote_ids:
try:
base_remote_rejected.remove(e)
except ValueError:
pass
reason_map = {}
for e in base_remote_rejected:
reason = yield self.store.get_rejection_reason(e.event_id)
if reason is None:
# TODO: e is not in the current state, so we should
# construct some proof of that.
continue
reason_map[e.event_id] = reason
if reason == RejectedReason.AUTH_ERROR:
pass
elif reason == RejectedReason.REPLACED:
# TODO: Get proof
pass
elif reason == RejectedReason.NOT_ANCESTOR:
# TODO: Get proof.
pass
logger.debug("construct_auth_difference returning")
return {
"auth_chain": local_auth,
"rejects": {
e.event_id: {"reason": reason_map[e.event_id], "proof": None}
for e in base_remote_rejected
},
"missing": [e.event_id for e in missing_locals],
}
@defer.inlineCallbacks
@log_function
def exchange_third_party_invite(
self, sender_user_id, target_user_id, room_id, signed
):
third_party_invite = {"signed": signed}
event_dict = {
"type": EventTypes.Member,
"content": {
"membership": Membership.INVITE,
"third_party_invite": third_party_invite,
},
"room_id": room_id,
"sender": sender_user_id,
"state_key": target_user_id,
}
if (yield self.auth.check_host_in_room(room_id, self.hs.hostname)):
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(room_version, event_dict)
EventValidator().validate_builder(builder)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.info(
"Creation of threepid invite %s forbidden by third-party rules",
event,
)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
event, context = yield self.add_display_name_to_third_party_invite(
room_version, event_dict, event, context
)
EventValidator().validate_new(event)
# We need to tell the transaction queue to send this out, even
# though the sender isn't a local user.
event.internal_metadata.send_on_behalf_of = self.hs.hostname
try:
yield self.auth.check_from_context(room_version, event, context)
except AuthError as e:
logger.warn("Denying new third party invite %r because %s", event, e)
raise e
yield self._check_signature(event, context)
member_handler = self.hs.get_room_member_handler()
yield member_handler.send_membership_event(None, event, context)
else:
destinations = set(x.split(":", 1)[-1] for x in (sender_user_id, room_id))
yield self.federation_client.forward_third_party_invite(
destinations, room_id, event_dict
)
@defer.inlineCallbacks
@log_function
def on_exchange_third_party_invite_request(self, room_id, event_dict):
room_version = yield self.store.get_room_version(room_id)
builder = self.event_builder_factory.new(room_version, event_dict)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
event_allowed = yield self.third_party_event_rules.check_event_allowed(
event, context
)
if not event_allowed:
logger.warning(
"Exchange of threepid invite %s forbidden by third-party rules", event
)
raise SynapseError(
403, "This event is not allowed in this context", Codes.FORBIDDEN
)
event, context = yield self.add_display_name_to_third_party_invite(
room_version, event_dict, event, context
)
try:
self.auth.check_from_context(room_version, event, context)
except AuthError as e:
logger.warn("Denying third party invite %r because %s", event, e)
raise e
yield self._check_signature(event, context)
event.internal_metadata.send_on_behalf_of = get_domain_from_id(event.sender)
member_handler = self.hs.get_room_member_handler()
yield member_handler.send_membership_event(None, event, context)
@defer.inlineCallbacks
def add_display_name_to_third_party_invite(
self, room_version, event_dict, event, context
):
key = (
EventTypes.ThirdPartyInvite,
event.content["third_party_invite"]["signed"]["token"],
)
original_invite = None
prev_state_ids = yield context.get_prev_state_ids(self.store)
original_invite_id = prev_state_ids.get(key)
if original_invite_id:
original_invite = yield self.store.get_event(
original_invite_id, allow_none=True
)
if original_invite:
display_name = original_invite.content["display_name"]
event_dict["content"]["third_party_invite"]["display_name"] = display_name
else:
logger.info(
"Could not find invite event for third_party_invite: %r", event_dict
)
# We don't discard here as this is not the appropriate place to do
# auth check code will explode appropriately.
builder = self.event_builder_factory.new(room_version, event_dict)
EventValidator().validate_builder(builder)
event, context = yield self.event_creation_handler.create_new_client_event(
builder=builder
)
EventValidator().validate_new(event)
return (event, context)
@defer.inlineCallbacks
def _check_signature(self, event, context):
signed = event.content["third_party_invite"]["signed"]
token = signed["token"]
prev_state_ids = yield context.get_prev_state_ids(self.store)
invite_event_id = prev_state_ids.get((EventTypes.ThirdPartyInvite, token))
invite_event = None
if invite_event_id:
invite_event = yield self.store.get_event(invite_event_id, allow_none=True)
if not invite_event:
raise AuthError(403, "Could not find invite")
logger.debug("Checking auth on event %r", event.content)
last_exception = None
# for each public key in the 3pid invite event
for public_key_object in self.hs.get_auth().get_public_keys(invite_event):
try:
# for each sig on the third_party_invite block of the actual invite
for server, signature_block in signed["signatures"].items():
for key_name, encoded_signature in signature_block.items():
if not key_name.startswith("ed25519:"):
continue
logger.debug(
"Attempting to verify sig with key %s from %r "
"against pubkey %r",
key_name,
server,
public_key_object,
)
try:
public_key = public_key_object["public_key"]
verify_key = decode_verify_key_bytes(
key_name, decode_base64(public_key)
)
verify_signed_json(signed, server, verify_key)
logger.debug(
"Successfully verified sig with key %s from %r "
"against pubkey %r",
key_name,
server,
public_key_object,
)
except Exception:
logger.info(
"Failed to verify sig with key %s from %r "
"against pubkey %r",
key_name,
server,
public_key_object,
)
raise
try:
if "key_validity_url" in public_key_object:
yield self._check_key_revocation(
public_key, public_key_object["key_validity_url"]
)
except Exception:
logger.info(
"Failed to query key_validity_url %s",
public_key_object["key_validity_url"],
)
raise
return
except Exception as e:
last_exception = e
raise last_exception
@defer.inlineCallbacks
def _check_key_revocation(self, public_key, url):
try:
response = yield self.http_client.get_json(url, {"public_key": public_key})
except Exception:
raise SynapseError(502, "Third party certificate could not be checked")
if "valid" not in response or not response["valid"]:
raise AuthError(403, "Third party certificate was invalid")
@defer.inlineCallbacks
def persist_events_and_notify(self, event_and_contexts, backfilled=False):
if self.config.worker_app:
yield self._send_events_to_master(
store=self.store,
event_and_contexts=event_and_contexts,
backfilled=backfilled,
)
else:
max_stream_id = yield self.store.persist_events(
event_and_contexts, backfilled=backfilled
)
if not backfilled: # Never notify for backfilled events
for event, _ in event_and_contexts:
yield self._notify_persisted_event(event, max_stream_id)
def _notify_persisted_event(self, event, max_stream_id):
extra_users = []
if event.type == EventTypes.Member:
target_user_id = event.state_key
# We notify for memberships if its an invite for one of our
# users
if event.internal_metadata.is_outlier():
if event.membership != Membership.INVITE:
if not self.is_mine_id(target_user_id):
return
target_user = UserID.from_string(target_user_id)
extra_users.append(target_user)
elif event.internal_metadata.is_outlier():
return
event_stream_id = event.internal_metadata.stream_ordering
self.notifier.on_new_room_event(
event, event_stream_id, max_stream_id, extra_users=extra_users
)
return self.pusher_pool.on_new_notifications(event_stream_id, max_stream_id)
def _clean_room_for_join(self, room_id):
if self.config.worker_app:
return self._clean_room_for_join_client(room_id)
else:
return self.store.clean_room_for_join(room_id)
def user_joined_room(self, user, room_id):
if self.config.worker_app:
return self._notify_user_membership_change(
room_id=room_id, user_id=user.to_string(), change="joined"
)
else:
return user_joined_room(self.distributor, user, room_id)
@defer.inlineCallbacks
def get_room_complexity(self, remote_room_hosts, room_id):
for host in remote_room_hosts:
res = yield self.federation_client.get_room_complexity(host, room_id)
# We got a result, return it.
if res:
defer.returnValue(res)
# We fell off the bottom, couldn't get the complexity from anyone. Oh
defer.returnValue(None)
| true | true |
f72b820782f5de6dce810345423aa0c625f54b34 | 53,798 | py | Python | mysql-utilities-1.6.0/mysql/utilities/common/rpl_sync.py | bopopescu/mysql-dbcompare | 1e912fd87282be3b3bed48487e6beb0ecb1de339 | [
"Apache-2.0"
] | 2 | 2018-03-20T07:42:58.000Z | 2018-03-20T07:43:49.000Z | mysql-utilities-1.6.0/mysql/utilities/common/rpl_sync.py | bopopescu/mysql-dbcompare | 1e912fd87282be3b3bed48487e6beb0ecb1de339 | [
"Apache-2.0"
] | null | null | null | mysql-utilities-1.6.0/mysql/utilities/common/rpl_sync.py | bopopescu/mysql-dbcompare | 1e912fd87282be3b3bed48487e6beb0ecb1de339 | [
"Apache-2.0"
] | 1 | 2020-07-23T23:07:08.000Z | 2020-07-23T23:07:08.000Z | #
# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
"""
This file contains features to check the data consistency in a replication
topology (i.e., between the master and its slaves, or only slaves), providing
synchronization features to perform the check over the (supposed) same data of
a system with replication active (running).
"""
import re
import sys
from multiprocessing.pool import ThreadPool
from mysql.utilities.command.dbcompare import diff_objects, get_common_objects
from mysql.utilities.common.database import Database
from mysql.utilities.common.messages import ERROR_USER_WITHOUT_PRIVILEGES
from mysql.utilities.common.pattern_matching import convertSQL_LIKE2REGEXP
from mysql.utilities.common.replication import (get_last_server_gtid,
gtid_set_cardinality,
gtid_set_union)
from mysql.utilities.common.sql_transform import quote_with_backticks
from mysql.utilities.common.topology import Topology
from mysql.utilities.common.user import User
from mysql.utilities.exception import UtilError
# Regular expression to handle the server version format.
_RE_VERSION_FORMAT = r'^(\d+\.\d+(\.\d+)*).*$'
class RPLSynchronizer(object):
"""Class to manage the features of the replication synchronization checker.
The RPLSynchronizer class is used to manage synchronization check between
servers of a replication topology, namely between the master and its
slaves or only between slaves. It provides functions to determine the
slaves missing transactions (i.e., missing GTIDs) and check data
consistency.
"""
def __init__(self, master_cnx_dic, slaves_cnx_dic_lst, options):
"""Constructor.
options[in] dictionary of options (e.g., discover, timeouts,
verbosity).
"""
self._verbosity = options.get('verbosity')
self._rpl_timeout = options.get('rpl_timeout')
self._checksum_timeout = options.get('checksum_timeout')
self._interval = options.get('interval')
self._rpl_topology = Topology(master_cnx_dic, slaves_cnx_dic_lst,
options)
self._slaves = self._rpl_topology.get_slaves_dict()
# Set base server used as reference for comparisons.
self._base_server = None
self._base_server_key = None
self._set_base_server()
# Check user permissions to perform the consistency check.
self._check_privileges()
# Check usage of replication filters.
self._master_rpl_filters = {}
self._slaves_rpl_filters = {}
self._check_rpl_filters()
def _set_base_server(self):
"""Set the base server used for comparison in the internal state.
Set the master if used or the first slave from the topology as the
base server. The base server is the one used as a reference for
comparison with the others. This method sets two instance variables:
_base_server with the Server instance, and _base_server_key with the
string identifying the server (format: 'host@port').
Note: base server might need to be changed (set again) if it is
removed from the topology for some reason (e.g. GTID disabled).
"""
master = self._get_master()
self._base_server = master if master \
else self._rpl_topology.slaves[0]['instance']
self._base_server_key = "{0}@{1}".format(self._base_server.host,
self._base_server.port)
def _get_slave(self, slave_key):
"""Get the slave server instance for the specified key 'host@port'.
This function retrieves the Server instance of for a slave from the
internal state by specifying the key that uniquely identifies it,
i.e. 'host@port'.
slave_key[in] String with the format 'host@port' that uniquely
identifies a server.
Returns a Server instance of the slave with the specified key value
(i.e., 'host@port').
"""
slave_dict = self._slaves[slave_key]
return slave_dict['instance']
def _get_master(self):
"""Get the master server instance.
This function retrieves the Server instance of the master (in the
replication topology).
Returns a Server instance of the master.
"""
return self._rpl_topology.master
def _check_privileges(self):
"""Check required privileges to perform the synchronization check.
This method check if the used users for the master and slaves possess
the required privileges to perform the synchronization check. More
specifically, the following privileges are required:
- on the master: SUPER or REPLICATION CLIENT, LOCK TABLES and
SELECT;
- on slaves: SUPER and SELECT.
An exception is thrown if users doesn't have enough privileges.
"""
if self._verbosity:
print("# Checking users permission to perform consistency check.\n"
"#")
# Check privileges for master.
master_priv = [('SUPER', 'REPLICATION CLIENT'), ('LOCK TABLES',),
('SELECT',)]
master_priv_str = "SUPER or REPLICATION CLIENT, LOCK TABLES and SELECT"
if self._get_master():
server = self._get_master()
user_obj = User(server, "{0}@{1}".format(server.user, server.host))
for any_priv_tuple in master_priv:
has_privilege = any(
[user_obj.has_privilege('*', '*', priv)
for priv in any_priv_tuple]
)
if not has_privilege:
raise UtilError(ERROR_USER_WITHOUT_PRIVILEGES.format(
user=server.user, host=server.host, port=server.port,
operation='perform the synchronization check',
req_privileges=master_priv_str
))
# Check privileges for slaves.
slave_priv = [('SUPER',), ('SELECT',)]
slave_priv_str = "SUPER and SELECT"
for slave_key in self._slaves:
server = self._get_slave(slave_key)
user_obj = User(server, "{0}@{1}".format(server.user, server.host))
for any_priv_tuple in slave_priv:
has_privilege = any(
[user_obj.has_privilege('*', '*', priv)
for priv in any_priv_tuple]
)
if not has_privilege:
raise UtilError(
"User '{0}' on '{1}@{2}' does not have sufficient "
"privileges to perform the synchronization check "
"(required: {3}).".format(server.user, server.host,
server.port, slave_priv_str)
)
def _check_rpl_filters(self):
"""Check usage of replication filters.
Check the usage of replication filtering option on the master (if
defined) and slaves, and set the internal state with the found options
(to check later).
"""
# Get binlog filtering option for the master.
if self._get_master():
m_filters = self._get_master().get_binlog_exceptions()
if m_filters:
# Set filtering option for master.
self._master_rpl_filters['binlog_do_db'] = \
m_filters[0][1].split(',') if m_filters[0][1] else None
self._master_rpl_filters['binlog_ignore_db'] = \
m_filters[0][2].split(',') if m_filters[0][2] else None
# Get replication filtering options for each slave.
for slave_key in self._slaves:
slave = self._get_slave(slave_key)
s_filters = slave.get_slave_rpl_filters()
if s_filters:
# Handle known server issues with some replication filters,
# leading to inconsistent GTID sets. Sync not supported for
# server with those issues.
issues = [(0, 'replicate_do_db'), (1, 'replicate_ignore_db'),
(4, 'replicate_wild_do_table')]
for index, rpl_opt in issues:
if s_filters[index]:
raise UtilError(
"Use of {0} option is not supported. There is a "
"known issue with the use this replication filter "
"and GTID for some server versions. Issue "
"detected for '{1}'.".format(rpl_opt, slave_key))
# Set map (dictionary) with the slave filtering options.
filters_map = {
'replicate_do_db':
s_filters[0].split(',') if s_filters[0] else None,
'replicate_ignore_db':
s_filters[1].split(',') if s_filters[1] else None,
'replicate_do_table':
s_filters[2].split(',') if s_filters[2] else None,
'replicate_ignore_table':
s_filters[3].split(',') if s_filters[3] else None,
}
# Handle wild-*-table filters differently to create
# corresponding regexp.
if s_filters[4]:
wild_list = s_filters[4].split(',')
filters_map['replicate_wild_do_table'] = wild_list
# Create auxiliary list with compiled regexp to match.
regexp_list = []
for wild in wild_list:
regexp = re.compile(convertSQL_LIKE2REGEXP(wild))
regexp_list.append(regexp)
filters_map['regexp_do_table'] = regexp_list
else:
filters_map['replicate_wild_do_table'] = None
filters_map['regexp_do_table'] = None
if s_filters[5]:
wild_list = s_filters[5].split(',')
filters_map['replicate_wild_ignore_table'] = wild_list
# Create auxiliary list with compiled regexp to match.
regexp_list = []
for wild in wild_list:
regexp = re.compile(convertSQL_LIKE2REGEXP(wild))
regexp_list.append(regexp)
filters_map['regexp_ignore_table'] = regexp_list
else:
filters_map['replicate_wild_ignore_table'] = None
filters_map['regexp_ignore_table'] = None
# Set filtering options for the slave.
self._slaves_rpl_filters[slave_key] = filters_map
# Print warning if filters are found.
if self._master_rpl_filters or self._slaves_rpl_filters:
print("# WARNING: Replication filters found on checked "
"servers. This can lead data consistency issues "
"depending on how statements are evaluated.\n"
"# More information: "
"http://dev.mysql.com/doc/en/replication-rules.html")
if self._verbosity:
# Print filter options in verbose mode.
if self._master_rpl_filters:
print("# Master '{0}@{1}':".format(
self._get_master().host, self._get_master().port
))
for rpl_filter in self._master_rpl_filters:
if self._master_rpl_filters[rpl_filter]:
print("# - {0}: {1}".format(
rpl_filter,
', '.join(
self._master_rpl_filters[rpl_filter]
)
))
if self._slaves_rpl_filters:
for slave_key in self._slaves_rpl_filters:
print("# Slave '{0}':".format(slave_key))
filters_map = self._slaves_rpl_filters[slave_key]
for rpl_filter in filters_map:
if (rpl_filter.startswith('replicate')
and filters_map[rpl_filter]):
print("# - {0}: {1}".format(
rpl_filter,
', '.join(filters_map[rpl_filter])
))
def _is_rpl_filtered(self, db_name, tbl_name=None, slave=None):
""" Check if the given object is to be filtered by replication.
This method checks if the given database or table name is
supposed to be filtered by replication (i.e., not replicated),
according to the defined replication filters for the master or
the specified slave.
db_name[in] Name of the database to check (not backtick quoted) or
associated to the table to check..
tbl_name[in] Name of the table to check (not backtick quoted).
Table level filtering rules are only checked if this
value is not None. By default None, meaning that only
the database level rules are checked.
slave[in] Identification of the slave in the format 'host@port'
to check, determining which filtering rules will be
checked. If None only the master filtering rules are
checked, otherwise the rule of the specified slaves
are used. By default: None.
Returns a boolean value indicating if the given database or table is
supposed to be filtered by the replication or not. More precisely,
if True then updates associated to the object are (supposedly) not
replicated, otherwise they are replicated.
"""
def match_regexp(name, regex_list):
""" Check if 'name' matches one of the regex in the given list.
"""
for regex in regex_list:
if regex.match(name):
return True
return False
# Determine object to check and set full qualified name.
is_db = tbl_name is None
obj_name = db_name if is_db else '{0}.{1}'.format(db_name, tbl_name)
# Match replication filter for Master.
if not slave and is_db and self._master_rpl_filters:
if self._master_rpl_filters['binlog_do_db']:
if obj_name in self._master_rpl_filters['binlog_do_db']:
return False
else:
return True
elif self._master_rpl_filters['binlog_ignore_db']:
if obj_name in self._master_rpl_filters['binlog_ignore_db']:
return True
# Match replication filters for the specified slave.
if slave and slave in self._slaves_rpl_filters:
rpl_filter = self._slaves_rpl_filters[slave]
if is_db:
if rpl_filter['replicate_do_db']:
if obj_name in rpl_filter['replicate_do_db']:
return False
else:
return True
elif (rpl_filter['replicate_ignore_db']
and obj_name in rpl_filter['replicate_ignore_db']):
return True
else:
if (rpl_filter['replicate_do_table']
and obj_name in rpl_filter['replicate_do_table']):
return False
if (rpl_filter['replicate_ignore_table']
and obj_name in rpl_filter['replicate_ignore_table']):
return True
if (rpl_filter['replicate_wild_do_table']
and match_regexp(obj_name,
rpl_filter['regexp_do_table'])):
return False
if (rpl_filter['replicate_wild_ignore_table']
and match_regexp(obj_name,
rpl_filter['regexp_ignore_table'])):
return True
if (rpl_filter['replicate_do_table']
or rpl_filter['replicate_wild_do_table']):
return True
# Do not filter replication for object (if no filter rule matched).
return False
def _apply_for_all_slaves(self, slaves, function, args=(), kwargs=None,
multithreading=False):
"""Apply specified function to all given slaves.
This function allow the execution (concurrently or not) of the
specified function with the given arguments on all the specified
slaves.
slaves[in] List of slaves to apply the function. It is assumed
that the list is composed by strings with the
format 'host@port', identifying each slave.
function[in] Name of the function (string) to apply on all
slaves.
args[in] Tuple with all the function arguments (except
keyword arguments).
kwargs[in] Dictionary with all the function keyword arguments.
multithreading[in] Boolean value indicating if the function will be
applied concurrently on all slaves. By default
False, no concurrency.
Return a list of tuples composed by two elements: a string identifying
the slave ('host@port') and the result of the execution of the target
function for the corresponding slave.
"""
if kwargs is None:
kwargs = {}
if multithreading:
# Create a pool of threads to execute the method for each slave.
pool = ThreadPool(processes=len(slaves))
thread_res_lst = []
for slave_key in slaves:
slave = self._get_slave(slave_key)
thread_res = pool.apply_async(getattr(slave, function), args,
kwargs)
thread_res_lst.append((slave_key, thread_res))
pool.close()
# Wait for all threads to finish here to avoid RuntimeErrors when
# waiting for the result of a thread that is already dead.
pool.join()
# Get the result from each slave and return the results.
res = []
for slave_key, thread_res in thread_res_lst:
res.append((slave_key, thread_res.get()))
return res
else:
res = []
for slave_key in slaves:
slave = self._get_slave(slave_key)
slave_res = getattr(slave, function)(*args, **kwargs)
res.append((slave_key, slave_res))
return res
def check_server_versions(self):
"""Check server versions.
Check all server versions and report version differences.
"""
srv_versions = {}
# Get the server version of the master if used.
master = self._get_master()
if master:
master_version = master.get_version()
match = re.match(_RE_VERSION_FORMAT, master_version.strip())
if match:
# Add .0 as release version if not provided.
if not match.group(2):
master_version = "{0}.0".format(match.group(1))
else:
master_version = match.group(1)
master_id = '{0}@{1}'.format(master.host, master.port)
# Store the master version.
srv_versions[master_version] = [master_id]
# Get the server version for all slaves.
for slave_key in self._slaves:
slave = self._get_slave(slave_key)
version = slave.get_version()
match = re.match(_RE_VERSION_FORMAT, version.strip())
if match:
# Add .0 as release version if not provided.
if not match.group(2):
version = "{0}.0".format(match.group(1))
else:
version = match.group(1)
# Store the slave version.
if version in srv_versions:
srv_versions[version].append(slave_key)
else:
srv_versions[version] = [slave_key]
# Check the servers versions and issue a warning if different.
if len(srv_versions) > 1:
print("# WARNING: Servers using different versions:")
for version in srv_versions:
servers_str = ",".join(srv_versions[version])
print("# - {0} for {1}.".format(version, servers_str))
print("#")
def check_gtid_sync(self):
"""Check GTIDs synchronization.
Perform several GTID checks (enabled and errant transactions). If the
master is available (was specified) then it also checks if GTIDs are
in sync between master and its slaves and report the amount of
transaction (i.e., GTIDs) behind the master for each slave.
GTID differences might be an indicator of the existence of data
consistency issues.
Note: The master may not be specified, its use is not mandatory.
"""
# Check if GTIDs are enabled on the topology.
if self._get_master(): # Use of Master is not mandatory.
# GTIDs must be enabled on the master.
if self._get_master().supports_gtid().upper() != 'ON':
raise UtilError(
"Master must support GTIDs and have GTID_MODE=ON."
)
# Skip slaves without GTID enabled and warn user.
reset_base_srv = False
for slave_key, slave_dict in self._slaves.items():
slave = slave_dict['instance']
support_gtid = slave.supports_gtid().upper()
if support_gtid != 'ON':
reason = "GTID_MODE=OFF" if support_gtid == 'OFF' \
else "not support GTIDs"
print("# WARNING: Slave '{0}' will be skipped - "
"{1}.".format(slave_key, reason))
print("#")
del self._slaves[slave_key]
self._rpl_topology.remove_slave(slave_dict)
if slave_key == self._base_server_key:
reset_base_srv = True
# At least on slave must have GTIDs enabled.
if len(self._slaves) == 0:
raise UtilError("No slaves found with GTID support and "
"GTID_MODE=ON.")
# Reset base server if needed (it must have GTID_MODE=ON).
if reset_base_srv:
self._set_base_server()
# Check the set of executed GTIDs and report differences, only if the
# master is specified.
if self._get_master():
master_gtids = self._get_master().get_gtid_executed()
slaves_gtids_data = \
self._rpl_topology.slaves_gtid_subtract_executed(
master_gtids, multithreading=True
)
print("#\n# GTID differences between Master and Slaves:")
for host, port, gtids_missing in slaves_gtids_data:
slave_key = '{0}@{1}'.format(host, port)
gtid_size = gtid_set_cardinality(gtids_missing)
if gtid_size:
plural = 's' if gtid_size > 1 else ''
print("# - Slave '{0}' is {1} transaction{2} behind "
"Master.".format(slave_key, gtid_size, plural))
if self._verbosity:
print("# Missing GTIDs: "
"{0}".format(gtids_missing))
else:
print("# - Slave '{0}' is up-to-date.".format(slave_key))
print("#")
@staticmethod
def _exist_in_obj_list(obj_name, obj_type, obj_list):
"""Check if object (name and type) exists in the given list.
This function checks if the database object for the specified name and
type exists in the specified list of database objects.
obj_name[in] Name of the object to check.
obj_type[in] Type of the object to check.
obj_list[in] List of objects to check. It is assumed that the list
has the format of the ones returned by the function
mysql.utilities.command.dbcompare.get_common_objects().
More precisely with the format:
[(obj_type1, (obj_name1,))..(obj_typeN, (obj_nameN,))]
Returns a boolean value indicating if object with the specified name
and type exists in the specified list of objects.
"""
for obj_row in obj_list:
if obj_row[0] == obj_type and obj_row[1][0] == obj_name:
return True
return False
def _split_active_slaves(self, slaves):
"""Get the list of slaves with replication running and not.
This method separates the list of given slaves into active (with the
IO and SQL thread running) and non active slaves (with one of the
threads stopped).
slaves[in] List of target slaves to separate.
Returns a tuple with two elements, first with the list of active slaves
and the second with the list of not active ones.
"""
# Get slaves status.
slaves_state = self._apply_for_all_slaves(slaves, 'get_slaves_errors',
multithreading=True)
# Store IO and SQL thread status.
active_slaves = []
not_active_slaves = []
for slave_key, state in slaves_state:
# Locally store IO and SQL threads status.
io_running = state[3].upper() == 'YES'
self._slaves[slave_key]['IO_Running'] = io_running
sql_running = state[4].upper() == 'YES'
self._slaves[slave_key]['SQL_Running'] = sql_running
if io_running and sql_running:
active_slaves.append(slave_key)
else:
not_active_slaves.append(slave_key)
print("# WARNING: Slave not active '{0}' - "
"Sync skipped.".format(slave_key))
if self._verbosity:
# Print warning if slave is stopped due to an error.
if not io_running and state[2]:
print("# - IO thread stopped: ERROR {0} - "
"{1}".format(state[1], state[2]))
if not sql_running and state[6]:
print("# - SQL thread stopped: ERROR {0} - "
"{1}".format(state[5], state[6]))
# Return separated list of active and non active replication slaves.
return active_slaves, not_active_slaves
def _compute_sync_point(self, active_slaves=None):
"""Compute the GTID synchronization point.
This method computes the GTID synchronization point based based on the
GTID_EXECUTED set. If a master is available for synchronization the
last GTID from the GTID_EXECUTED set is used as sync point If no
master is available the union of the GTID_EXECUTED sets among all
active slaves is used as the sync point.
active_slaves[in] List of active slaves to consider. Only required
if the master is not available. It is assumed
that the list is composed by strings with the
format 'host@port', identifying each slave.
Return a GTID set representing to synchronization point (to wait for
slaves to catch up and stop).
"""
if self._get_master():
gtid_set = self._get_master().get_gtid_executed()
master_uuid = self._get_master().get_server_uuid()
return get_last_server_gtid(gtid_set, master_uuid)
else:
# Get GTID_EXECUTED on all slaves.
all_gtid_executed = self._apply_for_all_slaves(
active_slaves, 'get_gtid_executed', multithreading=True
)
# Compute the union of all GTID sets for each UUID among slaves.
gtid_sets_by_uuid = {}
for _, gtid_executed in all_gtid_executed:
gtids_list = gtid_executed.split("\n")
for gtid in gtids_list:
gtid_set = gtid.rstrip(', ')
uuid = gtid_set.split(':')[0]
if uuid not in gtid_sets_by_uuid:
gtid_sets_by_uuid[uuid] = gtid_set
else:
union_set = gtid_set_union(gtid_sets_by_uuid[uuid],
gtid_set)
gtid_sets_by_uuid[uuid] = union_set
# Return union of all know executed GTID.
return ",".join(gtid_sets_by_uuid.itervalues())
def _sync_slaves(self, slaves, gtid):
"""Set synchronization point (specified GTID set) for the given slaves.
The method set the synchronization point for the given slaves by
(concurrently) stopping and immediately executing START SLAVE UNTIL
on all given slaves in order to stop upon reaching the given GTID set
(i.e., committing all corresponding transactions for the given GTID
sync point).
slaves[in] List of target slaves to synchronize (i.e., instruct
to stop upon reaching the synchronization point).
gtid[in] GTID set used as the synchronization point.
"""
# Make running slaves stop until sync point (GTID) is reached.
if self._verbosity:
print("# Setting data synchronization point for slaves.")
# STOP slave (only SQL thread).
self._apply_for_all_slaves(slaves, 'stop_sql_thread',
multithreading=True)
# START slave UNTIL sync point is reached.
# Note: Only the SQL thread is stopped when the condition is reached.
until_ops = {'until_gtid_set': gtid, 'sql_after_gtid': True,
'only_sql_thread': True}
self._apply_for_all_slaves(slaves, 'start', (), until_ops,
multithreading=True)
def _checksum_and_resume_rpl(self, not_sync_slaves, sync_slave, table):
"""Checksum table and resume replication on slaves.
This method computes (concurrently) the table checksum of the given
slaves lists (those synced and not synced). For the list of not synced
slaves the table checksum is immediately computed. For the list of
synced slaves, first it waits for them to catch up and the sync point
and only then compute the table checksum and resume replication.
not_sync_slaves[in] List of not synced slaves.
sync_slave[in] List of (previously) synced slaves.
table[in] Target table to compute the checksum.
Returns a list of tuples, each tuple containing the identification of
the server and the corresponding checksum result.
"""
if self._verbosity:
print("# Compute checksum on slaves (wait to catch up and resume"
" replication).")
sys.stdout.flush()
not_sync_checksum = []
if not_sync_slaves:
not_sync_checksum = self._apply_for_all_slaves(
not_sync_slaves, 'checksum_table', (table,),
{'exec_timeout': self._checksum_timeout},
multithreading=True
)
sync_checksum = []
if sync_slave:
sync_checksum = self._apply_for_all_slaves(
sync_slave, 'wait_checksum_and_start', (table,),
{'wait_timeout': self._rpl_timeout,
'wait_interval': self._interval,
'checksum_timeout': self._checksum_timeout},
multithreading=True
)
return not_sync_checksum + sync_checksum
def _check_table_data_sync(self, table, slaves):
"""Check table data synchronization for specified slaves.
This method check the data consistency for the specified table between
the base server (master or slave) and the specified salves. This
operation requires the definition of a "synchronization point" in order
to ensure that the "supposed" same data is compared between servers.
This coordination process is based on GTIDs (checking that all data
until a given GTID has been processed on the slaves). A different
algorithm is used to set the "synchronization point" depending if the
master is used or not. The data consistency is checked relying on the
CHECKSUM TABLE query.
If an error occur during this process, any locked table must be
unlocked and both master and slaves should resume their previous
activity.
Important note: this method assumes that the table exists on the base
server and all specified slaves, therefore checking the existence of
the table as well as other integrity checks (server versions, GTID
definitions, etc.) need to be performed outside the scope of this
method.
table[in] Qualified name of the table to check (quoted with
backticks).
slaves[in] List of slaves to check. Each element of the list must
be a string with the format 'host@port'.
Returns the number of data consistency found.
"""
success = False
checksum_issues = 0
# If no master used then add base server (slave) to slaves to sync.
if not self._get_master():
slaves = slaves + [self._base_server_key]
# Separate active from non active slaves.
active_slaves, not_active_slaves = self._split_active_slaves(slaves)
if self._get_master():
# Lock the table on the master to get GTID synchronization point
# and perform the table checksum.
try:
self._get_master().exec_query(
"LOCK TABLES {0} READ".format(table)
)
last_exec_gtid = self._compute_sync_point()
if self._verbosity > 2:
print("# Sync point GTID: {0}".format(last_exec_gtid))
# Immediately instruct active slaves to stop on sync point.
if active_slaves:
self._sync_slaves(active_slaves, last_exec_gtid)
# Perform table checksum on master.
base_server_checksum = self._get_master().checksum_table(
table, self._checksum_timeout
)
if base_server_checksum[0]:
success = True # Successful checksum for base server.
if self._verbosity > 2:
print("# Checksum on base server (Master): "
"{0}".format(base_server_checksum[0][1]))
else:
print("# [SKIP] {0} checksum on base server (Master) - "
"{1}".format(table, base_server_checksum[1]))
finally:
# Unlock table.
self._get_master().exec_query("UNLOCK TABLES")
elif active_slaves:
# Perform sync without master, only based on active slave (if any).
try:
# Stop all active slaves to get the GTID synchronization point.
self._apply_for_all_slaves(
active_slaves, 'stop_sql_thread', multithreading=True
)
sync_gtids = self._compute_sync_point(active_slaves)
if self._verbosity > 2:
print("# Sync point GTID: {0}".format(sync_gtids))
# Instruct active slaves to stop on sync point.
self._sync_slaves(active_slaves, sync_gtids)
except UtilError:
# Try to restart the slaves in case an error occurs.
self._apply_for_all_slaves(
active_slaves, 'star_sql_thread', multithreading=True
)
# Compute checksum on all slaves and return to previous state.
slaves_checksum = self._checksum_and_resume_rpl(not_active_slaves,
active_slaves, table)
# Check if checksum for base server was successfully computed.
if not self._get_master():
for slave_key, checksum in slaves_checksum:
if slave_key == self._base_server_key:
if checksum[0]:
success = True # Successful checksum for base server.
base_server_checksum = checksum
slaves_checksum.remove((slave_key, checksum))
if self._verbosity > 2:
print("# Checksum on base server: "
"{0}".format(base_server_checksum[0][1]))
else:
print("# [SKIP] {0} checksum on base server - "
"{1}".format(table, checksum[1]))
break
# Compare checksum and report results.
if success and slaves_checksum:
for slave_key, checksum_res in slaves_checksum:
if checksum_res[0] is None:
print("# [SKIP] {0} checksum for Slave '{1}' - "
"{2}.".format(table, slave_key, checksum_res[1]))
else:
if self._verbosity > 2:
checksum_val = ': {0}'.format(checksum_res[0][1])
else:
checksum_val = ''
if checksum_res[0] != base_server_checksum[0]:
print("# [DIFF] {0} checksum for server '{1}'"
"{2}.".format(table, slave_key, checksum_val))
checksum_issues += 1
else:
print("# [OK] {0} checksum for server '{1}'"
"{2}.".format(table, slave_key, checksum_val))
return checksum_issues
def check_data_sync(self, options, data_to_include, data_to_exclude):
"""Check data synchronization.
Check if the data (in all tables) is in sync between the checked
servers (master and its slaves, or only slaves). It reports structure
difference database/tables missing or with a different definition and
data differences between a base server and the others.
Note: A different algorithm is applied to perform the synchronization,
depending if the master is specified (available) or not.
options[in] Dictionary of options.
data_to_include[in] Dictionary of data (set of tables) by database to
check.
data_to_exclude[in] Dictionary of data (set of tables) by database to
exclude from check.
Returns the number of consistency issues found (comparing database
definitions and data).
"""
issues_count = 0
# Skip all database objects, except tables.
options['skip_views'] = True
options['skip_triggers'] = True
options['skip_procs'] = True
options['skip_funcs'] = True
options['skip_events'] = True
options['skip_grants'] = True
diff_options = {}
diff_options.update(options)
diff_options['quiet'] = True # Do not print messages.
diff_options['suppress_sql'] = True # Do not print SQL statements.
diff_options['skip_table_opts'] = True # Ignore AUTO_INCREMENT diffs.
# Check the server version requirement to support sync features.
# Slave servers of version >= 5.6.14 are required due to a known issue
# for START SLAVE UNTIL with the SQL_AFTER_GTIDS option. More info:
# https://dev.mysql.com/doc/refman/5.6/en/start-slave.html
for slave_key in self._slaves:
if not self._get_slave(slave_key).check_version_compat(5, 6, 14):
raise UtilError(
"Server '{0}' version must be 5.6.14 or greater. Sync is "
"not supported for versions prior to 5.6.14 due to a "
"known issue with START SLAVE UNTIL and the "
"SQL_AFTER_GTIDS option.".format(slave_key))
print("# Checking data consistency.\n#")
base_srv_type = 'Master' if self._get_master() else 'Slave'
print("# Using {0} '{1}' as base server for comparison."
"".format(base_srv_type, self._base_server_key))
# Get all databases from the base server.
db_rows = self._base_server.get_all_databases()
base_server_dbs = set([row[0] for row in db_rows])
# Process databases to include/exclude from check.
db_to_include = set()
if data_to_include:
db_to_include = set([db for db in data_to_include])
base_server_dbs = base_server_dbs & db_to_include
not_exist_db = db_to_include - base_server_dbs
if not_exist_db:
plurals = ('s', '') if len(not_exist_db) > 1 else ('', 'es')
print('# WARNING: specified database{0} to check do{1} not '
'exist on base server and will be skipped: '
'{2}.'.format(plurals[0], plurals[1],
", ".join(not_exist_db)))
db_to_exclude = set()
if data_to_exclude:
db_to_exclude = set(
[db for db in data_to_exclude if not data_to_exclude[db]]
)
base_server_dbs = base_server_dbs - db_to_exclude
# Check databases on slaves (except the base server).
slaves_except_base = [key for key in self._slaves
if key != self._base_server_key]
for slave_key in slaves_except_base:
slave = self._get_slave(slave_key)
db_rows = slave.get_all_databases()
slave_dbs = set([row[0] for row in db_rows])
# Process databases to include/exclude.
if db_to_include:
slave_dbs = slave_dbs & db_to_include
if db_to_exclude:
slave_dbs = slave_dbs - db_to_exclude
# Add slave databases set to internal state.
self._slaves[slave_key]['databases'] = slave_dbs
# Report databases not on base server and filtered by replication.
dbs_not_in_base_srv = slave_dbs - base_server_dbs
filtered_dbs = set(
[db for db in dbs_not_in_base_srv
if self._is_rpl_filtered(db, slave=self._base_server_key)]
)
dbs_not_in_base_srv -= filtered_dbs
for db in filtered_dbs:
print("# [SKIP] Database '{0}' - filtered by replication "
"rule on base server.".format(db))
if dbs_not_in_base_srv:
issues_count += len(dbs_not_in_base_srv)
plural = 's' if len(dbs_not_in_base_srv) > 1 else ''
print("# [DIFF] Database{0} NOT on base server but found on "
"'{1}': {2}".format(plural, slave_key,
",".join(dbs_not_in_base_srv)))
# Determine server to check base replication filtering options.
filter_srv = None if self._get_master() else self._base_server_key
# Check data consistency for each table on the base server.
for db_name in base_server_dbs:
# Skip database if filtered by defined replication rules.
if self._is_rpl_filtered(db_name, slave=filter_srv):
print("# [SKIP] Database '{0}' check - filtered by "
"replication rule.".format(db_name))
continue
print("# Checking '{0}' database...".format(db_name))
slaves_to_check = {}
# Check if database exists on slaves (except the base server).
for slave_key in slaves_except_base:
# Skip database if filtered by defined replication rules.
if self._is_rpl_filtered(db_name, slave=slave_key):
print("# [SKIP] Database '{0}' check for '{1}' - filtered "
"by replication rule.".format(db_name, slave_key))
continue
if db_name in self._slaves[slave_key]['databases']:
# Store slave database instance and common objects.
slave_db = Database(self._get_slave(slave_key), db_name,
options)
slave_db.init()
slave_dic = {'db': slave_db}
in_both, in_basesrv, not_in_basesrv = get_common_objects(
self._base_server, self._get_slave(slave_key),
db_name, db_name, False, options)
# Process tables to include/exclude from check (on slaves).
if (data_to_include and db_name in data_to_include
and data_to_include[db_name]):
in_both = [
obj_row for obj_row in in_both
if obj_row[1][0] in data_to_include[db_name]
]
in_basesrv = [
obj_row for obj_row in in_basesrv
if obj_row[1][0] in data_to_include[db_name]
]
not_in_basesrv = [
obj_row for obj_row in not_in_basesrv
if obj_row[1][0] in data_to_include[db_name]
]
if (data_to_exclude and db_name in data_to_exclude
and data_to_exclude[db_name]):
in_both = [
obj_row for obj_row in in_both
if obj_row[1][0] not in data_to_exclude[db_name]
]
in_basesrv = [
obj_row for obj_row in in_basesrv
if obj_row[1][0] not in data_to_exclude[db_name]
]
not_in_basesrv = [
obj_row for obj_row in not_in_basesrv
if obj_row[1][0] not in data_to_exclude[db_name]
]
slave_dic['in_both'] = in_both
slave_dic['in_basesrv'] = in_basesrv
slaves_to_check[slave_key] = slave_dic
# Report tables not on base server and filtered by
# replication.
tbls_not_in = set(
[obj_row[1][0] for obj_row in not_in_basesrv
if obj_row[0] == 'TABLE']
)
filtered_tbls = set(
[tbl for tbl in tbls_not_in if self._is_rpl_filtered(
db_name, tbl_name=tbl, slave=self._base_server_key
)]
)
tbls_not_in -= filtered_tbls
for tbl in filtered_tbls:
print("# [SKIP] Table '{0}' - filtered by replication "
"rule on base server.".format(tbl))
if tbls_not_in:
plural = 's' if len(tbls_not_in) > 1 else ''
print("# [DIFF] Table{0} NOT on base server but "
"found on '{1}': "
"{2}".format(plural, slave_key,
", ".join(tbls_not_in)))
issues_count += len(tbls_not_in)
else:
print("# [DIFF] Database '{0}' NOT on server "
"'{1}'.".format(db_name, slave_key))
issues_count += 1
# Only check database if at least one slave has it.
if slaves_to_check:
db = Database(self._base_server, db_name, options)
db.init()
for db_obj in db.get_next_object():
obj_type = db_obj[0]
obj_name = db_obj[1][0]
# Process tables to include/exclude from check (on base
# server).
if (data_to_include and data_to_include[db_name]
and obj_name not in data_to_include[db_name]):
# Skip to the next object if not in data to include.
continue
if (data_to_exclude and data_to_exclude[db_name]
and obj_name in data_to_exclude[db_name]):
# Skip to the next object if in data to exclude.
continue
checksum_task = []
# Check object data on all valid slaves.
for slave_key in slaves_to_check:
# Skip table if filtered by defined replication rules.
if (obj_type == 'TABLE'
and self._is_rpl_filtered(db_name, obj_name,
slave=slave_key)):
print("# [SKIP] Table '{0}' check for '{1}' - "
"filtered by replication rule."
"".format(obj_name, slave_key))
continue
slave_dic = slaves_to_check[slave_key]
# Check if object does not exist on Slave.
if self._exist_in_obj_list(obj_name, obj_type,
slave_dic['in_basesrv']):
print("# [DIFF] {0} '{1}.{2}' NOT on server "
"'{3}'.".format(obj_type.capitalize(),
db_name, obj_name,
slave_key))
issues_count += 1
continue
# Quote object name with backticks.
q_obj = '{0}.{1}'.format(
quote_with_backticks(db_name),
quote_with_backticks(obj_name)
)
# Check object definition.
def_diff = diff_objects(
self._base_server, self._get_slave(slave_key),
q_obj, q_obj, diff_options, obj_type
)
if def_diff:
print("# [DIFF] {0} {1} definition is "
"different on '{2}'."
"".format(obj_type.capitalize(), q_obj,
slave_key))
issues_count += 1
if self._verbosity:
for diff in def_diff[3:]:
print("# {0}".format(diff))
continue
# Add slave to table checksum task.
checksum_task.append(slave_key)
# Perform table checksum on valid slaves.
if checksum_task and obj_type == 'TABLE':
print("# - Checking '{0}' table data..."
"".format(obj_name))
num_issues = self._check_table_data_sync(q_obj,
checksum_task)
issues_count += num_issues
print("#\n#...done.\n#")
str_issues_count = 'No' if issues_count == 0 else str(issues_count)
plural = 's' if issues_count > 1 else ''
print("# SUMMARY: {0} data consistency issue{1} found.\n"
"#".format(str_issues_count, plural))
return issues_count
| 48.379496 | 79 | 0.549686 |
import re
import sys
from multiprocessing.pool import ThreadPool
from mysql.utilities.command.dbcompare import diff_objects, get_common_objects
from mysql.utilities.common.database import Database
from mysql.utilities.common.messages import ERROR_USER_WITHOUT_PRIVILEGES
from mysql.utilities.common.pattern_matching import convertSQL_LIKE2REGEXP
from mysql.utilities.common.replication import (get_last_server_gtid,
gtid_set_cardinality,
gtid_set_union)
from mysql.utilities.common.sql_transform import quote_with_backticks
from mysql.utilities.common.topology import Topology
from mysql.utilities.common.user import User
from mysql.utilities.exception import UtilError
_RE_VERSION_FORMAT = r'^(\d+\.\d+(\.\d+)*).*$'
class RPLSynchronizer(object):
def __init__(self, master_cnx_dic, slaves_cnx_dic_lst, options):
self._verbosity = options.get('verbosity')
self._rpl_timeout = options.get('rpl_timeout')
self._checksum_timeout = options.get('checksum_timeout')
self._interval = options.get('interval')
self._rpl_topology = Topology(master_cnx_dic, slaves_cnx_dic_lst,
options)
self._slaves = self._rpl_topology.get_slaves_dict()
self._base_server = None
self._base_server_key = None
self._set_base_server()
self._check_privileges()
self._master_rpl_filters = {}
self._slaves_rpl_filters = {}
self._check_rpl_filters()
def _set_base_server(self):
master = self._get_master()
self._base_server = master if master \
else self._rpl_topology.slaves[0]['instance']
self._base_server_key = "{0}@{1}".format(self._base_server.host,
self._base_server.port)
def _get_slave(self, slave_key):
slave_dict = self._slaves[slave_key]
return slave_dict['instance']
def _get_master(self):
return self._rpl_topology.master
def _check_privileges(self):
if self._verbosity:
print("# Checking users permission to perform consistency check.\n"
"#")
master_priv = [('SUPER', 'REPLICATION CLIENT'), ('LOCK TABLES',),
('SELECT',)]
master_priv_str = "SUPER or REPLICATION CLIENT, LOCK TABLES and SELECT"
if self._get_master():
server = self._get_master()
user_obj = User(server, "{0}@{1}".format(server.user, server.host))
for any_priv_tuple in master_priv:
has_privilege = any(
[user_obj.has_privilege('*', '*', priv)
for priv in any_priv_tuple]
)
if not has_privilege:
raise UtilError(ERROR_USER_WITHOUT_PRIVILEGES.format(
user=server.user, host=server.host, port=server.port,
operation='perform the synchronization check',
req_privileges=master_priv_str
))
slave_priv = [('SUPER',), ('SELECT',)]
slave_priv_str = "SUPER and SELECT"
for slave_key in self._slaves:
server = self._get_slave(slave_key)
user_obj = User(server, "{0}@{1}".format(server.user, server.host))
for any_priv_tuple in slave_priv:
has_privilege = any(
[user_obj.has_privilege('*', '*', priv)
for priv in any_priv_tuple]
)
if not has_privilege:
raise UtilError(
"User '{0}' on '{1}@{2}' does not have sufficient "
"privileges to perform the synchronization check "
"(required: {3}).".format(server.user, server.host,
server.port, slave_priv_str)
)
def _check_rpl_filters(self):
if self._get_master():
m_filters = self._get_master().get_binlog_exceptions()
if m_filters:
self._master_rpl_filters['binlog_do_db'] = \
m_filters[0][1].split(',') if m_filters[0][1] else None
self._master_rpl_filters['binlog_ignore_db'] = \
m_filters[0][2].split(',') if m_filters[0][2] else None
for slave_key in self._slaves:
slave = self._get_slave(slave_key)
s_filters = slave.get_slave_rpl_filters()
if s_filters:
issues = [(0, 'replicate_do_db'), (1, 'replicate_ignore_db'),
(4, 'replicate_wild_do_table')]
for index, rpl_opt in issues:
if s_filters[index]:
raise UtilError(
"Use of {0} option is not supported. There is a "
"known issue with the use this replication filter "
"and GTID for some server versions. Issue "
"detected for '{1}'.".format(rpl_opt, slave_key))
filters_map = {
'replicate_do_db':
s_filters[0].split(',') if s_filters[0] else None,
'replicate_ignore_db':
s_filters[1].split(',') if s_filters[1] else None,
'replicate_do_table':
s_filters[2].split(',') if s_filters[2] else None,
'replicate_ignore_table':
s_filters[3].split(',') if s_filters[3] else None,
}
if s_filters[4]:
wild_list = s_filters[4].split(',')
filters_map['replicate_wild_do_table'] = wild_list
regexp_list = []
for wild in wild_list:
regexp = re.compile(convertSQL_LIKE2REGEXP(wild))
regexp_list.append(regexp)
filters_map['regexp_do_table'] = regexp_list
else:
filters_map['replicate_wild_do_table'] = None
filters_map['regexp_do_table'] = None
if s_filters[5]:
wild_list = s_filters[5].split(',')
filters_map['replicate_wild_ignore_table'] = wild_list
regexp_list = []
for wild in wild_list:
regexp = re.compile(convertSQL_LIKE2REGEXP(wild))
regexp_list.append(regexp)
filters_map['regexp_ignore_table'] = regexp_list
else:
filters_map['replicate_wild_ignore_table'] = None
filters_map['regexp_ignore_table'] = None
self._slaves_rpl_filters[slave_key] = filters_map
if self._master_rpl_filters or self._slaves_rpl_filters:
print("# WARNING: Replication filters found on checked "
"servers. This can lead data consistency issues "
"depending on how statements are evaluated.\n"
"# More information: "
"http://dev.mysql.com/doc/en/replication-rules.html")
if self._verbosity:
if self._master_rpl_filters:
print("# Master '{0}@{1}':".format(
self._get_master().host, self._get_master().port
))
for rpl_filter in self._master_rpl_filters:
if self._master_rpl_filters[rpl_filter]:
print("# - {0}: {1}".format(
rpl_filter,
', '.join(
self._master_rpl_filters[rpl_filter]
)
))
if self._slaves_rpl_filters:
for slave_key in self._slaves_rpl_filters:
print("# Slave '{0}':".format(slave_key))
filters_map = self._slaves_rpl_filters[slave_key]
for rpl_filter in filters_map:
if (rpl_filter.startswith('replicate')
and filters_map[rpl_filter]):
print("# - {0}: {1}".format(
rpl_filter,
', '.join(filters_map[rpl_filter])
))
def _is_rpl_filtered(self, db_name, tbl_name=None, slave=None):
def match_regexp(name, regex_list):
for regex in regex_list:
if regex.match(name):
return True
return False
is_db = tbl_name is None
obj_name = db_name if is_db else '{0}.{1}'.format(db_name, tbl_name)
if not slave and is_db and self._master_rpl_filters:
if self._master_rpl_filters['binlog_do_db']:
if obj_name in self._master_rpl_filters['binlog_do_db']:
return False
else:
return True
elif self._master_rpl_filters['binlog_ignore_db']:
if obj_name in self._master_rpl_filters['binlog_ignore_db']:
return True
if slave and slave in self._slaves_rpl_filters:
rpl_filter = self._slaves_rpl_filters[slave]
if is_db:
if rpl_filter['replicate_do_db']:
if obj_name in rpl_filter['replicate_do_db']:
return False
else:
return True
elif (rpl_filter['replicate_ignore_db']
and obj_name in rpl_filter['replicate_ignore_db']):
return True
else:
if (rpl_filter['replicate_do_table']
and obj_name in rpl_filter['replicate_do_table']):
return False
if (rpl_filter['replicate_ignore_table']
and obj_name in rpl_filter['replicate_ignore_table']):
return True
if (rpl_filter['replicate_wild_do_table']
and match_regexp(obj_name,
rpl_filter['regexp_do_table'])):
return False
if (rpl_filter['replicate_wild_ignore_table']
and match_regexp(obj_name,
rpl_filter['regexp_ignore_table'])):
return True
if (rpl_filter['replicate_do_table']
or rpl_filter['replicate_wild_do_table']):
return True
return False
def _apply_for_all_slaves(self, slaves, function, args=(), kwargs=None,
multithreading=False):
if kwargs is None:
kwargs = {}
if multithreading:
pool = ThreadPool(processes=len(slaves))
thread_res_lst = []
for slave_key in slaves:
slave = self._get_slave(slave_key)
thread_res = pool.apply_async(getattr(slave, function), args,
kwargs)
thread_res_lst.append((slave_key, thread_res))
pool.close()
pool.join()
res = []
for slave_key, thread_res in thread_res_lst:
res.append((slave_key, thread_res.get()))
return res
else:
res = []
for slave_key in slaves:
slave = self._get_slave(slave_key)
slave_res = getattr(slave, function)(*args, **kwargs)
res.append((slave_key, slave_res))
return res
def check_server_versions(self):
srv_versions = {}
master = self._get_master()
if master:
master_version = master.get_version()
match = re.match(_RE_VERSION_FORMAT, master_version.strip())
if match:
if not match.group(2):
master_version = "{0}.0".format(match.group(1))
else:
master_version = match.group(1)
master_id = '{0}@{1}'.format(master.host, master.port)
srv_versions[master_version] = [master_id]
for slave_key in self._slaves:
slave = self._get_slave(slave_key)
version = slave.get_version()
match = re.match(_RE_VERSION_FORMAT, version.strip())
if match:
if not match.group(2):
version = "{0}.0".format(match.group(1))
else:
version = match.group(1)
if version in srv_versions:
srv_versions[version].append(slave_key)
else:
srv_versions[version] = [slave_key]
if len(srv_versions) > 1:
print("# WARNING: Servers using different versions:")
for version in srv_versions:
servers_str = ",".join(srv_versions[version])
print("# - {0} for {1}.".format(version, servers_str))
print("#")
def check_gtid_sync(self):
if self._get_master():
if self._get_master().supports_gtid().upper() != 'ON':
raise UtilError(
"Master must support GTIDs and have GTID_MODE=ON."
)
reset_base_srv = False
for slave_key, slave_dict in self._slaves.items():
slave = slave_dict['instance']
support_gtid = slave.supports_gtid().upper()
if support_gtid != 'ON':
reason = "GTID_MODE=OFF" if support_gtid == 'OFF' \
else "not support GTIDs"
print("# WARNING: Slave '{0}' will be skipped - "
"{1}.".format(slave_key, reason))
print("#")
del self._slaves[slave_key]
self._rpl_topology.remove_slave(slave_dict)
if slave_key == self._base_server_key:
reset_base_srv = True
if len(self._slaves) == 0:
raise UtilError("No slaves found with GTID support and "
"GTID_MODE=ON.")
if reset_base_srv:
self._set_base_server()
if self._get_master():
master_gtids = self._get_master().get_gtid_executed()
slaves_gtids_data = \
self._rpl_topology.slaves_gtid_subtract_executed(
master_gtids, multithreading=True
)
print("#\n# GTID differences between Master and Slaves:")
for host, port, gtids_missing in slaves_gtids_data:
slave_key = '{0}@{1}'.format(host, port)
gtid_size = gtid_set_cardinality(gtids_missing)
if gtid_size:
plural = 's' if gtid_size > 1 else ''
print("# - Slave '{0}' is {1} transaction{2} behind "
"Master.".format(slave_key, gtid_size, plural))
if self._verbosity:
print("# Missing GTIDs: "
"{0}".format(gtids_missing))
else:
print("# - Slave '{0}' is up-to-date.".format(slave_key))
print("#")
@staticmethod
def _exist_in_obj_list(obj_name, obj_type, obj_list):
for obj_row in obj_list:
if obj_row[0] == obj_type and obj_row[1][0] == obj_name:
return True
return False
def _split_active_slaves(self, slaves):
slaves_state = self._apply_for_all_slaves(slaves, 'get_slaves_errors',
multithreading=True)
active_slaves = []
not_active_slaves = []
for slave_key, state in slaves_state:
io_running = state[3].upper() == 'YES'
self._slaves[slave_key]['IO_Running'] = io_running
sql_running = state[4].upper() == 'YES'
self._slaves[slave_key]['SQL_Running'] = sql_running
if io_running and sql_running:
active_slaves.append(slave_key)
else:
not_active_slaves.append(slave_key)
print("# WARNING: Slave not active '{0}' - "
"Sync skipped.".format(slave_key))
if self._verbosity:
if not io_running and state[2]:
print("# - IO thread stopped: ERROR {0} - "
"{1}".format(state[1], state[2]))
if not sql_running and state[6]:
print("# - SQL thread stopped: ERROR {0} - "
"{1}".format(state[5], state[6]))
return active_slaves, not_active_slaves
def _compute_sync_point(self, active_slaves=None):
if self._get_master():
gtid_set = self._get_master().get_gtid_executed()
master_uuid = self._get_master().get_server_uuid()
return get_last_server_gtid(gtid_set, master_uuid)
else:
all_gtid_executed = self._apply_for_all_slaves(
active_slaves, 'get_gtid_executed', multithreading=True
)
gtid_sets_by_uuid = {}
for _, gtid_executed in all_gtid_executed:
gtids_list = gtid_executed.split("\n")
for gtid in gtids_list:
gtid_set = gtid.rstrip(', ')
uuid = gtid_set.split(':')[0]
if uuid not in gtid_sets_by_uuid:
gtid_sets_by_uuid[uuid] = gtid_set
else:
union_set = gtid_set_union(gtid_sets_by_uuid[uuid],
gtid_set)
gtid_sets_by_uuid[uuid] = union_set
return ",".join(gtid_sets_by_uuid.itervalues())
def _sync_slaves(self, slaves, gtid):
if self._verbosity:
print("# Setting data synchronization point for slaves.")
self._apply_for_all_slaves(slaves, 'stop_sql_thread',
multithreading=True)
until_ops = {'until_gtid_set': gtid, 'sql_after_gtid': True,
'only_sql_thread': True}
self._apply_for_all_slaves(slaves, 'start', (), until_ops,
multithreading=True)
def _checksum_and_resume_rpl(self, not_sync_slaves, sync_slave, table):
if self._verbosity:
print("# Compute checksum on slaves (wait to catch up and resume"
" replication).")
sys.stdout.flush()
not_sync_checksum = []
if not_sync_slaves:
not_sync_checksum = self._apply_for_all_slaves(
not_sync_slaves, 'checksum_table', (table,),
{'exec_timeout': self._checksum_timeout},
multithreading=True
)
sync_checksum = []
if sync_slave:
sync_checksum = self._apply_for_all_slaves(
sync_slave, 'wait_checksum_and_start', (table,),
{'wait_timeout': self._rpl_timeout,
'wait_interval': self._interval,
'checksum_timeout': self._checksum_timeout},
multithreading=True
)
return not_sync_checksum + sync_checksum
def _check_table_data_sync(self, table, slaves):
success = False
checksum_issues = 0
if not self._get_master():
slaves = slaves + [self._base_server_key]
active_slaves, not_active_slaves = self._split_active_slaves(slaves)
if self._get_master():
try:
self._get_master().exec_query(
"LOCK TABLES {0} READ".format(table)
)
last_exec_gtid = self._compute_sync_point()
if self._verbosity > 2:
print("# Sync point GTID: {0}".format(last_exec_gtid))
if active_slaves:
self._sync_slaves(active_slaves, last_exec_gtid)
base_server_checksum = self._get_master().checksum_table(
table, self._checksum_timeout
)
if base_server_checksum[0]:
success = True
if self._verbosity > 2:
print("# Checksum on base server (Master): "
"{0}".format(base_server_checksum[0][1]))
else:
print("# [SKIP] {0} checksum on base server (Master) - "
"{1}".format(table, base_server_checksum[1]))
finally:
self._get_master().exec_query("UNLOCK TABLES")
elif active_slaves:
try:
self._apply_for_all_slaves(
active_slaves, 'stop_sql_thread', multithreading=True
)
sync_gtids = self._compute_sync_point(active_slaves)
if self._verbosity > 2:
print("# Sync point GTID: {0}".format(sync_gtids))
self._sync_slaves(active_slaves, sync_gtids)
except UtilError:
self._apply_for_all_slaves(
active_slaves, 'star_sql_thread', multithreading=True
)
slaves_checksum = self._checksum_and_resume_rpl(not_active_slaves,
active_slaves, table)
if not self._get_master():
for slave_key, checksum in slaves_checksum:
if slave_key == self._base_server_key:
if checksum[0]:
success = True
base_server_checksum = checksum
slaves_checksum.remove((slave_key, checksum))
if self._verbosity > 2:
print("# Checksum on base server: "
"{0}".format(base_server_checksum[0][1]))
else:
print("# [SKIP] {0} checksum on base server - "
"{1}".format(table, checksum[1]))
break
if success and slaves_checksum:
for slave_key, checksum_res in slaves_checksum:
if checksum_res[0] is None:
print("# [SKIP] {0} checksum for Slave '{1}' - "
"{2}.".format(table, slave_key, checksum_res[1]))
else:
if self._verbosity > 2:
checksum_val = ': {0}'.format(checksum_res[0][1])
else:
checksum_val = ''
if checksum_res[0] != base_server_checksum[0]:
print("# [DIFF] {0} checksum for server '{1}'"
"{2}.".format(table, slave_key, checksum_val))
checksum_issues += 1
else:
print("# [OK] {0} checksum for server '{1}'"
"{2}.".format(table, slave_key, checksum_val))
return checksum_issues
def check_data_sync(self, options, data_to_include, data_to_exclude):
issues_count = 0
options['skip_views'] = True
options['skip_triggers'] = True
options['skip_procs'] = True
options['skip_funcs'] = True
options['skip_events'] = True
options['skip_grants'] = True
diff_options = {}
diff_options.update(options)
diff_options['quiet'] = True
diff_options['suppress_sql'] = True
diff_options['skip_table_opts'] = True
for slave_key in self._slaves:
if not self._get_slave(slave_key).check_version_compat(5, 6, 14):
raise UtilError(
"Server '{0}' version must be 5.6.14 or greater. Sync is "
"not supported for versions prior to 5.6.14 due to a "
"known issue with START SLAVE UNTIL and the "
"SQL_AFTER_GTIDS option.".format(slave_key))
print("# Checking data consistency.\n#")
base_srv_type = 'Master' if self._get_master() else 'Slave'
print("# Using {0} '{1}' as base server for comparison."
"".format(base_srv_type, self._base_server_key))
db_rows = self._base_server.get_all_databases()
base_server_dbs = set([row[0] for row in db_rows])
db_to_include = set()
if data_to_include:
db_to_include = set([db for db in data_to_include])
base_server_dbs = base_server_dbs & db_to_include
not_exist_db = db_to_include - base_server_dbs
if not_exist_db:
plurals = ('s', '') if len(not_exist_db) > 1 else ('', 'es')
print('# WARNING: specified database{0} to check do{1} not '
'exist on base server and will be skipped: '
'{2}.'.format(plurals[0], plurals[1],
", ".join(not_exist_db)))
db_to_exclude = set()
if data_to_exclude:
db_to_exclude = set(
[db for db in data_to_exclude if not data_to_exclude[db]]
)
base_server_dbs = base_server_dbs - db_to_exclude
slaves_except_base = [key for key in self._slaves
if key != self._base_server_key]
for slave_key in slaves_except_base:
slave = self._get_slave(slave_key)
db_rows = slave.get_all_databases()
slave_dbs = set([row[0] for row in db_rows])
if db_to_include:
slave_dbs = slave_dbs & db_to_include
if db_to_exclude:
slave_dbs = slave_dbs - db_to_exclude
self._slaves[slave_key]['databases'] = slave_dbs
dbs_not_in_base_srv = slave_dbs - base_server_dbs
filtered_dbs = set(
[db for db in dbs_not_in_base_srv
if self._is_rpl_filtered(db, slave=self._base_server_key)]
)
dbs_not_in_base_srv -= filtered_dbs
for db in filtered_dbs:
print("# [SKIP] Database '{0}' - filtered by replication "
"rule on base server.".format(db))
if dbs_not_in_base_srv:
issues_count += len(dbs_not_in_base_srv)
plural = 's' if len(dbs_not_in_base_srv) > 1 else ''
print("# [DIFF] Database{0} NOT on base server but found on "
"'{1}': {2}".format(plural, slave_key,
",".join(dbs_not_in_base_srv)))
filter_srv = None if self._get_master() else self._base_server_key
for db_name in base_server_dbs:
if self._is_rpl_filtered(db_name, slave=filter_srv):
print("# [SKIP] Database '{0}' check - filtered by "
"replication rule.".format(db_name))
continue
print("# Checking '{0}' database...".format(db_name))
slaves_to_check = {}
for slave_key in slaves_except_base:
if self._is_rpl_filtered(db_name, slave=slave_key):
print("# [SKIP] Database '{0}' check for '{1}' - filtered "
"by replication rule.".format(db_name, slave_key))
continue
if db_name in self._slaves[slave_key]['databases']:
slave_db = Database(self._get_slave(slave_key), db_name,
options)
slave_db.init()
slave_dic = {'db': slave_db}
in_both, in_basesrv, not_in_basesrv = get_common_objects(
self._base_server, self._get_slave(slave_key),
db_name, db_name, False, options)
if (data_to_include and db_name in data_to_include
and data_to_include[db_name]):
in_both = [
obj_row for obj_row in in_both
if obj_row[1][0] in data_to_include[db_name]
]
in_basesrv = [
obj_row for obj_row in in_basesrv
if obj_row[1][0] in data_to_include[db_name]
]
not_in_basesrv = [
obj_row for obj_row in not_in_basesrv
if obj_row[1][0] in data_to_include[db_name]
]
if (data_to_exclude and db_name in data_to_exclude
and data_to_exclude[db_name]):
in_both = [
obj_row for obj_row in in_both
if obj_row[1][0] not in data_to_exclude[db_name]
]
in_basesrv = [
obj_row for obj_row in in_basesrv
if obj_row[1][0] not in data_to_exclude[db_name]
]
not_in_basesrv = [
obj_row for obj_row in not_in_basesrv
if obj_row[1][0] not in data_to_exclude[db_name]
]
slave_dic['in_both'] = in_both
slave_dic['in_basesrv'] = in_basesrv
slaves_to_check[slave_key] = slave_dic
tbls_not_in = set(
[obj_row[1][0] for obj_row in not_in_basesrv
if obj_row[0] == 'TABLE']
)
filtered_tbls = set(
[tbl for tbl in tbls_not_in if self._is_rpl_filtered(
db_name, tbl_name=tbl, slave=self._base_server_key
)]
)
tbls_not_in -= filtered_tbls
for tbl in filtered_tbls:
print("# [SKIP] Table '{0}' - filtered by replication "
"rule on base server.".format(tbl))
if tbls_not_in:
plural = 's' if len(tbls_not_in) > 1 else ''
print("# [DIFF] Table{0} NOT on base server but "
"found on '{1}': "
"{2}".format(plural, slave_key,
", ".join(tbls_not_in)))
issues_count += len(tbls_not_in)
else:
print("# [DIFF] Database '{0}' NOT on server "
"'{1}'.".format(db_name, slave_key))
issues_count += 1
if slaves_to_check:
db = Database(self._base_server, db_name, options)
db.init()
for db_obj in db.get_next_object():
obj_type = db_obj[0]
obj_name = db_obj[1][0]
if (data_to_include and data_to_include[db_name]
and obj_name not in data_to_include[db_name]):
continue
if (data_to_exclude and data_to_exclude[db_name]
and obj_name in data_to_exclude[db_name]):
continue
checksum_task = []
for slave_key in slaves_to_check:
if (obj_type == 'TABLE'
and self._is_rpl_filtered(db_name, obj_name,
slave=slave_key)):
print("# [SKIP] Table '{0}' check for '{1}' - "
"filtered by replication rule."
"".format(obj_name, slave_key))
continue
slave_dic = slaves_to_check[slave_key]
if self._exist_in_obj_list(obj_name, obj_type,
slave_dic['in_basesrv']):
print("# [DIFF] {0} '{1}.{2}' NOT on server "
"'{3}'.".format(obj_type.capitalize(),
db_name, obj_name,
slave_key))
issues_count += 1
continue
q_obj = '{0}.{1}'.format(
quote_with_backticks(db_name),
quote_with_backticks(obj_name)
)
def_diff = diff_objects(
self._base_server, self._get_slave(slave_key),
q_obj, q_obj, diff_options, obj_type
)
if def_diff:
print("# [DIFF] {0} {1} definition is "
"different on '{2}'."
"".format(obj_type.capitalize(), q_obj,
slave_key))
issues_count += 1
if self._verbosity:
for diff in def_diff[3:]:
print("# {0}".format(diff))
continue
checksum_task.append(slave_key)
if checksum_task and obj_type == 'TABLE':
print("# - Checking '{0}' table data..."
"".format(obj_name))
num_issues = self._check_table_data_sync(q_obj,
checksum_task)
issues_count += num_issues
print("#\n#...done.\n#")
str_issues_count = 'No' if issues_count == 0 else str(issues_count)
plural = 's' if issues_count > 1 else ''
print("# SUMMARY: {0} data consistency issue{1} found.\n"
"#".format(str_issues_count, plural))
return issues_count
| true | true |
f72b84523234516e230f5570be8f20af24029148 | 29,913 | py | Python | rbc/remotejit.py | guilhermeleobas/rbc | 4b568b91c6ce3ef7727fee001169302c3803c4fd | [
"BSD-3-Clause"
] | null | null | null | rbc/remotejit.py | guilhermeleobas/rbc | 4b568b91c6ce3ef7727fee001169302c3803c4fd | [
"BSD-3-Clause"
] | null | null | null | rbc/remotejit.py | guilhermeleobas/rbc | 4b568b91c6ce3ef7727fee001169302c3803c4fd | [
"BSD-3-Clause"
] | null | null | null | """RemoteJIT client/server config functions
"""
__all__ = ['RemoteJIT', 'Signature', 'Caller']
import os
import inspect
import warnings
import ctypes
from contextlib import nullcontext
from . import irtools
from .typesystem import Type, get_signature
from .thrift import Server, Dispatcher, dispatchermethod, Data, Client
from .utils import get_local_ip
from .targetinfo import TargetInfo
from .rbclib import tracing_allocator
# XXX WIP: the OmnisciCompilerPipeline is no longer omnisci-specific because
# we support Arrays even without omnisci, so it must be renamed and moved
# somewhere elsef
from .omnisci_backend import OmnisciCompilerPipeline
def isfunctionlike(obj):
"""Return True if object is function alike.
"""
if obj is None or isinstance(obj, (Signature, list, tuple, str, Caller)):
return False
return True
def extract_templates(options):
"""Extract templates mapping data from options dictionary.
If options does not contain "templates", it will be constructed
from all unknown options that have list values. Otherwise, the
corresponding value is returned with no further processing of
options content.
Parameters
----------
options : dict
Returns
-------
options : dict
A copy of input without templates mapping data.
templates : dict
Templates mapping which is a collections of pairs of template
name and a list of concrete types. Template name cannot
correspond to a concrete type.
"""
known_options = ['devices', 'local']
new_options = {}
templates = options.get('templates')
if templates is not None:
new_options.update(options)
del new_options['templates']
else:
templates = {}
for k, v in options.items():
if (isinstance(k, str) and isinstance(v, list) and k not in known_options):
templates[k] = v
else:
new_options[k] = v
return new_options, templates
class Signature(object):
"""Signature decorator for Python functions.
A Signature decorator may contain many signature objects
representing the prototypes of functions.
Signature decorators are re-usable and composeable. For example:
.. highlight:: python
.. code-block:: python
rjit = RemoteJIT(host='localhost' port=6274)
# remotebinaryfunc is Signature instance
remotebinaryfunc = rjit('int32(int32, int32)',
'float32(float32, float32)', ...)
# add will be Caller instance
@remotebinaryfunc
def add(a, b):
return a + b
# sub will be Caller instance
@remotebinaryfunc
def sub(a, b):
return a - b
add(1, 2) # returns 3
sub(1.0, 2.0) # returns -1.0
"""
def __init__(self, remotejit):
assert isinstance(remotejit, RemoteJIT), type(remotejit)
self.remotejit = remotejit
self.signatures = []
self.signature_devices = {}
self.signature_templates = {}
@property
def debug(self):
return self.remotejit.debug
@property
def local(self):
sig = Signature(self.remotejit.local)
sig.signatures.extend(self.signatures)
assert not self.signature_devices
assert not self.signature_templates
return sig
def __str__(self):
lst = ["'%s'" % (s,) for s in self.signatures]
return '%s(%s)' % (self.__class__.__name__, ', '.join(lst))
def __call__(self, obj, **options):
"""Decorate signatures or a function.
Parameters
----------
obj : {str, Signature, function, ...}
Specify object that represents a function type.
Keyword parameters
------------------
devices : list
Specify device names for the given set of signatures.
templates : dict
Specify template types mapping.
Returns
-------
result : {Signature, Caller}
If obj is a function, return Caller. Otherwise return self
that is extended with new signatures from obj.
Note
----
The validity of the input argument is not checked here. This
is because the bit-size of certain C types (e.g. size_t, long,
etc) depend on the target device which information will be
available at the compile stage. The target dependent
signatures can be retrieved using
`signature.get_signatures()`.
"""
if obj is None:
return self
options, templates = extract_templates(options)
devices = options.get('devices')
if isinstance(obj, Signature):
self.signatures.extend(obj.signatures)
self.signature_devices.update(obj.signature_devices)
self.remotejit.discard_last_compile()
if devices is not None:
for s in obj.signatures:
self.signature_devices[s] = devices
assert not templates
for s in obj.signatures:
t = obj.signature_templates.get(s)
if t is not None:
self.signature_templates[s] = t
return self
if isinstance(obj, Caller):
# return new Caller with extended signatures set
assert obj.remotejit is self.remotejit
final = Signature(self.remotejit)
final(self) # copies the signatures from self to final
final(obj.signature) # copies the signatures from obj to final
assert devices is None
assert not templates
return Caller(obj.func, final)
if isfunctionlike(obj):
final = Signature(self.remotejit)
final(self) # copies the signatures from self to final
assert devices is None
assert not templates
return Caller(obj, final)
self.signatures.append(obj)
self.remotejit.discard_last_compile()
if devices is not None:
self.signature_devices[obj] = devices
if templates:
self.signature_templates[obj] = templates
return self
def best_match(self, func, atypes: tuple) -> Type:
"""Return function type from signatures that matches best with given
argument types.
If no match is found, raise TypeError.
Parameters
----------
atypes : Type-tuple
Specify a tuple of argument types.
Returns
-------
ftype : Type
Function type that arguments match best with given argument
types.
"""
ftype = None
match_penalty = None
available_types = self.normalized(func).signatures
for typ in available_types:
penalty = typ.match(atypes)
if penalty is not None:
if ftype is None or penalty < match_penalty:
ftype = typ
match_penalty = penalty
if ftype is None:
satypes = ', '.join(map(str, atypes))
available = '; '.join(map(str, available_types))
raise TypeError(
f'found no matching function type to given argument types'
f' `{satypes}`. Available function types: {available}')
return ftype
def normalized(self, func=None):
"""Return a copy of Signature object where all signatures are
normalized to Type instances using the current target device
information.
Parameters
----------
func : {None, callable}
Python function that annotations are attached to signature.
Returns
-------
signature : Signature
"""
signature = Signature(self.remotejit)
fsig = Type.fromcallable(func) if func is not None else None
nargs = fsig.arity if func is not None else None
target_info = TargetInfo()
for sig in self.signatures:
devices = self.signature_devices.get(sig)
if not target_info.check_enabled(devices):
if self.debug:
print(f'{type(self).__name__}.normalized: skipping {sig} as'
f' not supported by devices: {devices}')
continue
templates = self.signature_templates.get(sig, {})
sig = Type.fromobject(sig)
if not sig.is_complete:
warnings.warn(f'Incomplete signature {sig} will be ignored')
continue
if not sig.is_function:
raise ValueError(
'expected signature representing function type,'
f' got `{sig}`')
if nargs is None:
nargs = sig.arity
elif sig.arity != nargs:
raise ValueError(f'signature `{sig}` must have arity {nargs}'
f' but got {len(sig[1])}')
if fsig is not None:
sig.inherit_annotations(fsig)
if not sig.is_concrete:
for csig in sig.apply_templates(templates):
assert isinstance(csig, Type), (sig, csig, type(csig))
if csig not in signature.signatures:
signature.signatures.append(csig)
else:
if sig not in signature.signatures:
signature.signatures.append(sig)
if fsig is not None and fsig.is_complete:
if fsig not in signature.signatures:
signature.signatures.append(fsig)
return signature
class Caller(object):
"""Remote JIT caller, holds the decorated function that can be
executed remotely.
"""
def __init__(self, func, signature: Signature):
"""Construct remote JIT caller instance.
Parameters
----------
func : callable
Specify a Python function that is used as a template to
remotely JIT compiled functions.
signature : Signature
Specify a collection of signatures.
local : bool
When True, local process will be interpreted as
remote. Useful for debugging.
"""
self.remotejit = signature.remotejit
self.signature = signature
func = self.remotejit.preprocess_callable(func)
self.func = func
self.nargs = len(get_signature(func).parameters)
# Attributes used in RBC user-interface
self._is_compiled = set() # items are (fname, ftype)
self._client = None
self.remotejit.add_caller(self)
@property
def local(self):
"""Return Caller instance that executes function calls on the local
host. Useful for debugging.
"""
return Caller(self.func, self.signature.local)
def __repr__(self):
return '%s(%s, %s, local=%s)' % (type(self).__name__, self.func,
self.signature, self.local)
def __str__(self):
return self.describe()
def describe(self):
"""Return LLVM IRs of all target devices.
"""
lst = ['']
fid = 0
for device, target_info in self.remotejit.targets.items():
with Type.alias(**self.remotejit.typesystem_aliases):
with target_info:
lst.append(f'{device:-^80}')
signatures = self.get_signatures()
signatures_map = {}
for sig in signatures:
fid += 1
signatures_map[fid] = sig
llvm_module, succesful_fids = irtools.compile_to_LLVM(
[(self.func, signatures_map)],
target_info,
pipeline_class=OmnisciCompilerPipeline,
debug=self.remotejit.debug)
lst.append(str(llvm_module))
lst.append(f'{"":-^80}')
return '\n'.join(lst)
def get_signatures(self):
"""Return a list of normalized signatures for given target device.
"""
return self.signature.normalized(self.func).signatures
# RBC user-interface
def __call__(self, *arguments, **options):
"""Return the result of a remote JIT compiled function call.
"""
device = options.get('device')
targets = self.remotejit.targets
if device is None:
if len(targets) > 1:
raise TypeError(
f'specifying device is required when target has more than'
f' one device. Available devices: {", ".join(targets)}')
device = tuple(targets)[0]
target_info = targets[device]
with target_info:
atypes = tuple(map(Type.fromvalue, arguments))
ftype = self.signature.best_match(self.func, atypes)
key = self.func.__name__, ftype
if key not in self._is_compiled:
self.remotejit.remote_compile(self.func, ftype, target_info)
self._is_compiled.add(key)
return self.remotejit.remote_call(self.func, ftype, arguments)
class RemoteJIT(object):
"""RemoteJIT is a decorator generator for user functions to be
remotely JIT compiled.
To use, define
.. highlight:: python
.. code-block:: python
rjit = RemoteJIT(host='localhost', port=6274)
@rjit
def foo(a: int, b: int) -> int:
return a + b
@rjit('double(double, double)',
'int64(int64, int64)')
def bar(a, b):
return a + b
# Finally, call
c = foo(1, 2) # c = 3
b = bar(7.0, 1.0) # b = 8.0
The sum will be evaluated in the remote host.
"""
multiplexed = True
thrift_content = None
typesystem_aliases = dict()
def __init__(self, host='localhost', port=11532,
local=False, debug=False, use_tracing_allocator=False):
"""Construct remote JIT function decorator.
The decorator is re-usable for different functions.
Parameters
----------
host : str
Specify the host name of IP of JIT server
port : {int, str}
Specify the service port of the JIT server
local : bool
When True, use local client. Useful for debugging.
debug : bool
When True, output debug messages.
use_tracing_allocator : bool
When True, enable the automatic detection of memory leaks.
"""
if host == 'localhost':
host = get_local_ip()
if use_tracing_allocator and not local:
raise ValueError('use_tracing_allocator=True can be used only with local=True')
self.debug = debug
self.use_tracing_allocator = use_tracing_allocator
self.host = host
self.port = int(port)
self.server_process = None
# A collection of Caller instances. Each represents a function
# that have many argument type dependent implementations.
self._callers = []
self._last_compile = None
self._targets = None
if local:
self._client = LocalClient(debug=debug,
use_tracing_allocator=use_tracing_allocator)
else:
self._client = None
@property
def local(self):
localjit = type(self)(local=True, debug=self.debug)
localjit._callers.extend(self._callers)
return localjit
def add_caller(self, caller):
self._callers.append(caller)
self.discard_last_compile()
def get_callers(self):
return self._callers
def reset(self):
"""Drop all callers definitions and compilation results.
"""
self._callers.clear()
self.discard_last_compile()
@property
def have_last_compile(self):
"""Check if compile data exists.
See `set_last_compile` method for more information.
"""
return self._last_compile is not None
def discard_last_compile(self):
"""Discard compile data.
See `set_last_compile` method for more information.
"""
self._last_compile = None
def set_last_compile(self, compile_data):
"""Save compile data.
The caller is responsible for discarding previous compiler
data by calling `discard_last_compile` method.
Parameters
----------
compile_data : object
Compile data can be any Python object. When None, it is
interpreted as no compile data is available.
Notes
-----
The have/discard/set_last_compile methods provide a way to
avoid unnecessary compilations when the remote server supports
registration of compiled functions. The corresponding
`register` method is expected to use the following pattern:
.. code-block:: python
def register(self):
if self.have_last_compile:
return
<compile defined functions>
self.set_last_compile(<compilation results>)
The `discard_last_compile()` method is called when the compile
data becomes obsolete or needs to be discarded. For instance,
the compile data will be discarded when calling the following
methods: `reset`, `add_caller`. Note that the `add_caller`
call is triggered when applying the remotejit decorator to a
Python function to be compiled.
"""
assert self._last_compile is None
self._last_compile = compile_data
def get_pending_names(self):
"""Return the names of functions that have not been registered to the
remote server.
"""
names = set()
if not self.have_last_compile:
for caller in reversed(self.get_callers()):
names.add(caller.func.__name__)
return names
def retrieve_targets(self):
"""Retrieve target device information from remote client.
Redefine this method if remote client is not native.
Returns
-------
targets : dict
Map of target device names and informations.
"""
# TODO: rename thrift API targets to get_device_parameters?
response = self.client(remotejit=dict(targets=()))
targets = {}
for device, data in response['remotejit']['targets'].items():
targets[device] = TargetInfo.fromjson(data)
return targets
@property
def targets(self):
"""Return device-target_info mapping of the remote server.
"""
if self._targets is None:
self._targets = self.retrieve_targets()
return self._targets
def __call__(self, *signatures, **options):
"""Define a remote JIT function signatures and template.
Parameters
----------
signatures : tuple
Specify signatures of a remote JIT function, or a Python
function as a template from which the remote JIT function
will be compiled.
Keyword parameters
------------------
local : bool
devices : list
Specify device names for the given set of signatures.
templates : dict
Specify template types mapping.
Returns
-------
sig: {Signature, Caller}
Signature decorator or Caller
Notes
-----
The signatures can be strings in the following form:
"<return type>(<argument type 1>, <argument type 2>, ...)"
or any other object that can be converted to function type,
see `Type.fromobject` for more information.
"""
if options.get('local'):
s = Signature(self.local)
else:
s = Signature(self)
devices = options.get('devices')
options, templates = extract_templates(options)
for sig in signatures:
s = s(sig, devices=devices, templates=templates)
return s
def start_server(self, background=False):
"""Start remotejit server from client.
"""
thrift_file = os.path.join(os.path.dirname(__file__),
'remotejit.thrift')
print('staring rpc.thrift server: %s' % (thrift_file), end='',
flush=True)
if self.debug:
print(flush=True)
dispatcher = DebugDispatcherRJIT
else:
dispatcher = DispatcherRJIT
if background:
ps = Server.run_bg(dispatcher, thrift_file,
dict(host=self.host, port=self.port,
debug=self.debug))
self.server_process = ps
else:
Server.run(dispatcher, thrift_file,
dict(host=self.host, port=self.port,
debug=self.debug))
print('... rpc.thrift server stopped', flush=True)
def stop_server(self):
"""Stop remotejit server from client.
"""
if self.server_process is not None and self.server_process.is_alive():
print('... stopping rpc.thrift server')
self.server_process.terminate()
self.server_process = None
@property
def client(self):
"""Return remote host connection as Client instance.
"""
if self._client is None:
self._client = Client(
host=self.host,
port=self.port,
multiplexed=self.multiplexed,
thrift_content=self.thrift_content,
socket_timeout=60000)
return self._client
def remote_compile(self, func, ftype: Type, target_info: TargetInfo):
"""Remote compile function and signatures to machine code.
The input function `func` is compiled to LLVM IR module, the
LLVM IR module is sent to remote host where the remote host is
expected to complete the compilation process.
Return the corresponding LLVM IR module instance which may be
useful for debugging.
"""
if self.debug:
print(f'remote_compile({func}, {ftype})')
llvm_module, succesful_fids = irtools.compile_to_LLVM(
[(func, {0: ftype})],
target_info,
pipeline_class=OmnisciCompilerPipeline,
debug=self.debug)
ir = str(llvm_module)
mangled_signatures = ';'.join([s.mangle() for s in [ftype]])
response = self.client(remotejit=dict(
compile=(func.__name__, mangled_signatures, ir)))
assert response['remotejit']['compile'], response
return llvm_module
def remote_call(self, func, ftype: Type, arguments: tuple):
"""Call function remotely on given arguments.
The input function `func` is called remotely by sending the
arguments data to remote host where the previously compiled
function (see `remote_compile` method) is applied to the
arguments, and the result is returned to local process.
"""
if self.debug:
print(f'remote_call({func}, {ftype}, {arguments})')
fullname = func.__name__ + ftype.mangle()
response = self.client(remotejit=dict(call=(fullname, arguments)))
return response['remotejit']['call']
def python(self, statement):
"""Execute Python statement remotely.
"""
response = self.client(remotejit=dict(python=(statement,)))
return response['remotejit']['python']
def preprocess_callable(self, func):
"""Preprocess func to be used as a remotejit function definition.
Parameters
----------
func : callable
Returns
-------
func : callable
Preprocessed func.
"""
return func
class DispatcherRJIT(Dispatcher):
"""Implements remotejit service methods.
"""
def __init__(self, server, debug=False, use_tracing_allocator=False):
super().__init__(server, debug=debug)
self.use_tracing_allocator = use_tracing_allocator
self.compiled_functions = dict()
self.engines = dict()
self.python_globals = dict()
self.python_locals = dict()
@dispatchermethod
def targets(self) -> dict:
"""Retrieve target device information.
Returns
-------
info : dict
Map of target devices and their properties.
"""
if self.use_tracing_allocator:
target_info = TargetInfo.host(name='host_cpu_tracing_allocator',
use_tracing_allocator=True)
else:
target_info = TargetInfo.host()
target_info.set('has_numba', True)
target_info.set('has_cpython', True)
return dict(cpu=target_info.tojson())
@dispatchermethod
def compile(self, name: str, signatures: str, ir: str) -> int:
"""JIT compile function.
Parameters
----------
name : str
Specify the function name.
signatures : str
Specify semi-colon separated list of mangled signatures.
ir : str
Specify LLVM IR representation of the function.
"""
engine = irtools.compile_IR(ir)
for msig in signatures.split(';'):
sig = Type.demangle(msig)
ctypes_sig = sig.toctypes()
assert sig.is_function
if sig[0].is_aggregate:
raise RuntimeError(
f'Functions with aggregate return type values are not supported,'
f' got function `{name}` with `{sig}` signature')
fullname = name + msig
addr = engine.get_function_address(fullname)
if self.debug:
print(f'compile({name}, {sig}) -> {hex(addr)}')
# storing engine as the owner of function addresses
if addr:
self.compiled_functions[fullname] = engine, ctypes_sig(addr), sig, ctypes_sig
else:
warnings.warn('No compilation result for {name}|{sig=}')
return True
@dispatchermethod
def call(self, fullname: str, arguments: tuple) -> Data:
"""Call JIT compiled function
Parameters
----------
fullname : str
Specify the full name of the function that is in form
"<name><mangled signature>"
arguments : tuple
Specify the arguments to the function.
"""
# if we are using a tracing allocator, automatically detect memory leaks
# at each call.
if self.use_tracing_allocator:
leak_detector = tracing_allocator.new_leak_detector()
else:
leak_detector = nullcontext()
with leak_detector:
return self._do_call(fullname, arguments)
def _do_call(self, fullname, arguments):
if self.debug:
print(f'call({fullname}, {arguments})')
ef = self.compiled_functions.get(fullname)
if ef is None:
raise RuntimeError(
f'no such compiled function `{fullname}`. Available functions:\n'
f' {"; ".join(list(self.compiled_functions))}\n.')
sig = ef[2]
ctypes_sig = ef[3]
if len(arguments) == 0:
assert sig.arity == 1 and sig[1][0].is_void, sig
else:
assert len(arguments) == sig.arity, (len(arguments), sig.arity)
ctypes_arguments = []
for typ, ctypes_typ, value in zip(sig[1], ctypes_sig._argtypes_, arguments):
if typ.is_custom:
typ = typ.get_struct_type()
if typ.is_struct:
if isinstance(value, tuple):
member_values = [t.toctypes()(value[i]) for i, t in enumerate(typ)]
else:
member_values = [t.toctypes()(getattr(value, t.name)) for t in typ]
ctypes_arguments.extend(member_values)
elif typ.is_pointer:
if isinstance(value, ctypes.c_void_p):
value = ctypes.cast(value, ctypes_typ)
else:
value = ctypes.cast(value, ctypes_typ)
ctypes_arguments.append(value)
else:
ctypes_arguments.append(value)
r = ef[1](*ctypes_arguments)
if sig[0].is_pointer and sig[0][0].is_void and isinstance(r, int):
r = ctypes.c_void_p(r)
if self.debug:
print(f'-> {r}')
if hasattr(r, 'topython'):
return r.topython()
return r
@dispatchermethod
def python(self, statement: str) -> int:
"""Execute Python statement.
"""
if self.debug:
print(f'python({statement!r})')
exec(statement, self.python_globals, self.python_locals)
return True
class DebugDispatcherRJIT(DispatcherRJIT):
"""
Enables debug messages.
"""
debug = True
class LocalClient(object):
"""Pretender of thrift.Client.
All calls will be made in a local process. Useful for debbuging.
"""
def __init__(self, debug=False, use_tracing_allocator=False):
self.dispatcher = DispatcherRJIT(None, debug=debug,
use_tracing_allocator=use_tracing_allocator)
def __call__(self, **services):
results = {}
for service_name, query_dict in services.items():
results[service_name] = {}
for mthname, args in query_dict.items():
mth = getattr(self.dispatcher, mthname)
mth = inspect.unwrap(mth)
results[service_name][mthname] = mth(self.dispatcher, *args)
return results
| 34.2254 | 93 | 0.585063 |
__all__ = ['RemoteJIT', 'Signature', 'Caller']
import os
import inspect
import warnings
import ctypes
from contextlib import nullcontext
from . import irtools
from .typesystem import Type, get_signature
from .thrift import Server, Dispatcher, dispatchermethod, Data, Client
from .utils import get_local_ip
from .targetinfo import TargetInfo
from .rbclib import tracing_allocator
from .omnisci_backend import OmnisciCompilerPipeline
def isfunctionlike(obj):
if obj is None or isinstance(obj, (Signature, list, tuple, str, Caller)):
return False
return True
def extract_templates(options):
known_options = ['devices', 'local']
new_options = {}
templates = options.get('templates')
if templates is not None:
new_options.update(options)
del new_options['templates']
else:
templates = {}
for k, v in options.items():
if (isinstance(k, str) and isinstance(v, list) and k not in known_options):
templates[k] = v
else:
new_options[k] = v
return new_options, templates
class Signature(object):
def __init__(self, remotejit):
assert isinstance(remotejit, RemoteJIT), type(remotejit)
self.remotejit = remotejit
self.signatures = []
self.signature_devices = {}
self.signature_templates = {}
@property
def debug(self):
return self.remotejit.debug
@property
def local(self):
sig = Signature(self.remotejit.local)
sig.signatures.extend(self.signatures)
assert not self.signature_devices
assert not self.signature_templates
return sig
def __str__(self):
lst = ["'%s'" % (s,) for s in self.signatures]
return '%s(%s)' % (self.__class__.__name__, ', '.join(lst))
def __call__(self, obj, **options):
if obj is None:
return self
options, templates = extract_templates(options)
devices = options.get('devices')
if isinstance(obj, Signature):
self.signatures.extend(obj.signatures)
self.signature_devices.update(obj.signature_devices)
self.remotejit.discard_last_compile()
if devices is not None:
for s in obj.signatures:
self.signature_devices[s] = devices
assert not templates
for s in obj.signatures:
t = obj.signature_templates.get(s)
if t is not None:
self.signature_templates[s] = t
return self
if isinstance(obj, Caller):
assert obj.remotejit is self.remotejit
final = Signature(self.remotejit)
final(self)
final(obj.signature)
assert devices is None
assert not templates
return Caller(obj.func, final)
if isfunctionlike(obj):
final = Signature(self.remotejit)
final(self)
assert devices is None
assert not templates
return Caller(obj, final)
self.signatures.append(obj)
self.remotejit.discard_last_compile()
if devices is not None:
self.signature_devices[obj] = devices
if templates:
self.signature_templates[obj] = templates
return self
def best_match(self, func, atypes: tuple) -> Type:
ftype = None
match_penalty = None
available_types = self.normalized(func).signatures
for typ in available_types:
penalty = typ.match(atypes)
if penalty is not None:
if ftype is None or penalty < match_penalty:
ftype = typ
match_penalty = penalty
if ftype is None:
satypes = ', '.join(map(str, atypes))
available = '; '.join(map(str, available_types))
raise TypeError(
f'found no matching function type to given argument types'
f' `{satypes}`. Available function types: {available}')
return ftype
def normalized(self, func=None):
signature = Signature(self.remotejit)
fsig = Type.fromcallable(func) if func is not None else None
nargs = fsig.arity if func is not None else None
target_info = TargetInfo()
for sig in self.signatures:
devices = self.signature_devices.get(sig)
if not target_info.check_enabled(devices):
if self.debug:
print(f'{type(self).__name__}.normalized: skipping {sig} as'
f' not supported by devices: {devices}')
continue
templates = self.signature_templates.get(sig, {})
sig = Type.fromobject(sig)
if not sig.is_complete:
warnings.warn(f'Incomplete signature {sig} will be ignored')
continue
if not sig.is_function:
raise ValueError(
'expected signature representing function type,'
f' got `{sig}`')
if nargs is None:
nargs = sig.arity
elif sig.arity != nargs:
raise ValueError(f'signature `{sig}` must have arity {nargs}'
f' but got {len(sig[1])}')
if fsig is not None:
sig.inherit_annotations(fsig)
if not sig.is_concrete:
for csig in sig.apply_templates(templates):
assert isinstance(csig, Type), (sig, csig, type(csig))
if csig not in signature.signatures:
signature.signatures.append(csig)
else:
if sig not in signature.signatures:
signature.signatures.append(sig)
if fsig is not None and fsig.is_complete:
if fsig not in signature.signatures:
signature.signatures.append(fsig)
return signature
class Caller(object):
def __init__(self, func, signature: Signature):
self.remotejit = signature.remotejit
self.signature = signature
func = self.remotejit.preprocess_callable(func)
self.func = func
self.nargs = len(get_signature(func).parameters)
self._is_compiled = set()
self._client = None
self.remotejit.add_caller(self)
@property
def local(self):
return Caller(self.func, self.signature.local)
def __repr__(self):
return '%s(%s, %s, local=%s)' % (type(self).__name__, self.func,
self.signature, self.local)
def __str__(self):
return self.describe()
def describe(self):
lst = ['']
fid = 0
for device, target_info in self.remotejit.targets.items():
with Type.alias(**self.remotejit.typesystem_aliases):
with target_info:
lst.append(f'{device:-^80}')
signatures = self.get_signatures()
signatures_map = {}
for sig in signatures:
fid += 1
signatures_map[fid] = sig
llvm_module, succesful_fids = irtools.compile_to_LLVM(
[(self.func, signatures_map)],
target_info,
pipeline_class=OmnisciCompilerPipeline,
debug=self.remotejit.debug)
lst.append(str(llvm_module))
lst.append(f'{"":-^80}')
return '\n'.join(lst)
def get_signatures(self):
return self.signature.normalized(self.func).signatures
def __call__(self, *arguments, **options):
device = options.get('device')
targets = self.remotejit.targets
if device is None:
if len(targets) > 1:
raise TypeError(
f'specifying device is required when target has more than'
f' one device. Available devices: {", ".join(targets)}')
device = tuple(targets)[0]
target_info = targets[device]
with target_info:
atypes = tuple(map(Type.fromvalue, arguments))
ftype = self.signature.best_match(self.func, atypes)
key = self.func.__name__, ftype
if key not in self._is_compiled:
self.remotejit.remote_compile(self.func, ftype, target_info)
self._is_compiled.add(key)
return self.remotejit.remote_call(self.func, ftype, arguments)
class RemoteJIT(object):
multiplexed = True
thrift_content = None
typesystem_aliases = dict()
def __init__(self, host='localhost', port=11532,
local=False, debug=False, use_tracing_allocator=False):
if host == 'localhost':
host = get_local_ip()
if use_tracing_allocator and not local:
raise ValueError('use_tracing_allocator=True can be used only with local=True')
self.debug = debug
self.use_tracing_allocator = use_tracing_allocator
self.host = host
self.port = int(port)
self.server_process = None
self._callers = []
self._last_compile = None
self._targets = None
if local:
self._client = LocalClient(debug=debug,
use_tracing_allocator=use_tracing_allocator)
else:
self._client = None
@property
def local(self):
localjit = type(self)(local=True, debug=self.debug)
localjit._callers.extend(self._callers)
return localjit
def add_caller(self, caller):
self._callers.append(caller)
self.discard_last_compile()
def get_callers(self):
return self._callers
def reset(self):
self._callers.clear()
self.discard_last_compile()
@property
def have_last_compile(self):
return self._last_compile is not None
def discard_last_compile(self):
self._last_compile = None
def set_last_compile(self, compile_data):
assert self._last_compile is None
self._last_compile = compile_data
def get_pending_names(self):
names = set()
if not self.have_last_compile:
for caller in reversed(self.get_callers()):
names.add(caller.func.__name__)
return names
def retrieve_targets(self):
response = self.client(remotejit=dict(targets=()))
targets = {}
for device, data in response['remotejit']['targets'].items():
targets[device] = TargetInfo.fromjson(data)
return targets
@property
def targets(self):
if self._targets is None:
self._targets = self.retrieve_targets()
return self._targets
def __call__(self, *signatures, **options):
if options.get('local'):
s = Signature(self.local)
else:
s = Signature(self)
devices = options.get('devices')
options, templates = extract_templates(options)
for sig in signatures:
s = s(sig, devices=devices, templates=templates)
return s
def start_server(self, background=False):
thrift_file = os.path.join(os.path.dirname(__file__),
'remotejit.thrift')
print('staring rpc.thrift server: %s' % (thrift_file), end='',
flush=True)
if self.debug:
print(flush=True)
dispatcher = DebugDispatcherRJIT
else:
dispatcher = DispatcherRJIT
if background:
ps = Server.run_bg(dispatcher, thrift_file,
dict(host=self.host, port=self.port,
debug=self.debug))
self.server_process = ps
else:
Server.run(dispatcher, thrift_file,
dict(host=self.host, port=self.port,
debug=self.debug))
print('... rpc.thrift server stopped', flush=True)
def stop_server(self):
if self.server_process is not None and self.server_process.is_alive():
print('... stopping rpc.thrift server')
self.server_process.terminate()
self.server_process = None
@property
def client(self):
if self._client is None:
self._client = Client(
host=self.host,
port=self.port,
multiplexed=self.multiplexed,
thrift_content=self.thrift_content,
socket_timeout=60000)
return self._client
def remote_compile(self, func, ftype: Type, target_info: TargetInfo):
if self.debug:
print(f'remote_compile({func}, {ftype})')
llvm_module, succesful_fids = irtools.compile_to_LLVM(
[(func, {0: ftype})],
target_info,
pipeline_class=OmnisciCompilerPipeline,
debug=self.debug)
ir = str(llvm_module)
mangled_signatures = ';'.join([s.mangle() for s in [ftype]])
response = self.client(remotejit=dict(
compile=(func.__name__, mangled_signatures, ir)))
assert response['remotejit']['compile'], response
return llvm_module
def remote_call(self, func, ftype: Type, arguments: tuple):
if self.debug:
print(f'remote_call({func}, {ftype}, {arguments})')
fullname = func.__name__ + ftype.mangle()
response = self.client(remotejit=dict(call=(fullname, arguments)))
return response['remotejit']['call']
def python(self, statement):
response = self.client(remotejit=dict(python=(statement,)))
return response['remotejit']['python']
def preprocess_callable(self, func):
return func
class DispatcherRJIT(Dispatcher):
def __init__(self, server, debug=False, use_tracing_allocator=False):
super().__init__(server, debug=debug)
self.use_tracing_allocator = use_tracing_allocator
self.compiled_functions = dict()
self.engines = dict()
self.python_globals = dict()
self.python_locals = dict()
@dispatchermethod
def targets(self) -> dict:
if self.use_tracing_allocator:
target_info = TargetInfo.host(name='host_cpu_tracing_allocator',
use_tracing_allocator=True)
else:
target_info = TargetInfo.host()
target_info.set('has_numba', True)
target_info.set('has_cpython', True)
return dict(cpu=target_info.tojson())
@dispatchermethod
def compile(self, name: str, signatures: str, ir: str) -> int:
engine = irtools.compile_IR(ir)
for msig in signatures.split(';'):
sig = Type.demangle(msig)
ctypes_sig = sig.toctypes()
assert sig.is_function
if sig[0].is_aggregate:
raise RuntimeError(
f'Functions with aggregate return type values are not supported,'
f' got function `{name}` with `{sig}` signature')
fullname = name + msig
addr = engine.get_function_address(fullname)
if self.debug:
print(f'compile({name}, {sig}) -> {hex(addr)}')
if addr:
self.compiled_functions[fullname] = engine, ctypes_sig(addr), sig, ctypes_sig
else:
warnings.warn('No compilation result for {name}|{sig=}')
return True
@dispatchermethod
def call(self, fullname: str, arguments: tuple) -> Data:
if self.use_tracing_allocator:
leak_detector = tracing_allocator.new_leak_detector()
else:
leak_detector = nullcontext()
with leak_detector:
return self._do_call(fullname, arguments)
def _do_call(self, fullname, arguments):
if self.debug:
print(f'call({fullname}, {arguments})')
ef = self.compiled_functions.get(fullname)
if ef is None:
raise RuntimeError(
f'no such compiled function `{fullname}`. Available functions:\n'
f' {"; ".join(list(self.compiled_functions))}\n.')
sig = ef[2]
ctypes_sig = ef[3]
if len(arguments) == 0:
assert sig.arity == 1 and sig[1][0].is_void, sig
else:
assert len(arguments) == sig.arity, (len(arguments), sig.arity)
ctypes_arguments = []
for typ, ctypes_typ, value in zip(sig[1], ctypes_sig._argtypes_, arguments):
if typ.is_custom:
typ = typ.get_struct_type()
if typ.is_struct:
if isinstance(value, tuple):
member_values = [t.toctypes()(value[i]) for i, t in enumerate(typ)]
else:
member_values = [t.toctypes()(getattr(value, t.name)) for t in typ]
ctypes_arguments.extend(member_values)
elif typ.is_pointer:
if isinstance(value, ctypes.c_void_p):
value = ctypes.cast(value, ctypes_typ)
else:
value = ctypes.cast(value, ctypes_typ)
ctypes_arguments.append(value)
else:
ctypes_arguments.append(value)
r = ef[1](*ctypes_arguments)
if sig[0].is_pointer and sig[0][0].is_void and isinstance(r, int):
r = ctypes.c_void_p(r)
if self.debug:
print(f'-> {r}')
if hasattr(r, 'topython'):
return r.topython()
return r
@dispatchermethod
def python(self, statement: str) -> int:
if self.debug:
print(f'python({statement!r})')
exec(statement, self.python_globals, self.python_locals)
return True
class DebugDispatcherRJIT(DispatcherRJIT):
debug = True
class LocalClient(object):
def __init__(self, debug=False, use_tracing_allocator=False):
self.dispatcher = DispatcherRJIT(None, debug=debug,
use_tracing_allocator=use_tracing_allocator)
def __call__(self, **services):
results = {}
for service_name, query_dict in services.items():
results[service_name] = {}
for mthname, args in query_dict.items():
mth = getattr(self.dispatcher, mthname)
mth = inspect.unwrap(mth)
results[service_name][mthname] = mth(self.dispatcher, *args)
return results
| true | true |
f72b8471d48e46d56ffa1ffa9f9a1797ba37c49a | 521 | py | Python | objectivec/test/testdata/single_add_gen.py | kimjungwow/onnxruntime-riscv | 3c21abef03190648fe68a6633ac026725e6dfc58 | [
"MIT"
] | 18 | 2020-05-19T12:48:07.000Z | 2021-04-28T06:41:57.000Z | objectivec/test/testdata/single_add_gen.py | kimjungwow/onnxruntime-riscv | 3c21abef03190648fe68a6633ac026725e6dfc58 | [
"MIT"
] | 61 | 2021-05-31T05:15:41.000Z | 2022-03-29T22:34:33.000Z | objectivec/test/testdata/single_add_gen.py | ekmixon/onnxruntime | 1ab8a95eb6675afb6d0ad9d93600ef0022e2ddb5 | [
"MIT"
] | 9 | 2021-05-14T20:17:26.000Z | 2022-03-20T11:44:29.000Z | import onnx
from onnx import helper
from onnx import TensorProto
graph = helper.make_graph(
[ # nodes
helper.make_node("Add", ["A", "B"], ["C"], "Add"),
],
"SingleAdd", # name
[ # inputs
helper.make_tensor_value_info('A', TensorProto.FLOAT, [1]),
helper.make_tensor_value_info('B', TensorProto.FLOAT, [1]),
],
[ # outputs
helper.make_tensor_value_info('C', TensorProto.FLOAT, [1]),
])
model = helper.make_model(graph)
onnx.save(model, r'single_add.onnx')
| 26.05 | 67 | 0.619962 | import onnx
from onnx import helper
from onnx import TensorProto
graph = helper.make_graph(
[
helper.make_node("Add", ["A", "B"], ["C"], "Add"),
],
"SingleAdd",
[
helper.make_tensor_value_info('A', TensorProto.FLOAT, [1]),
helper.make_tensor_value_info('B', TensorProto.FLOAT, [1]),
],
[
helper.make_tensor_value_info('C', TensorProto.FLOAT, [1]),
])
model = helper.make_model(graph)
onnx.save(model, r'single_add.onnx')
| true | true |
f72b855250840e726278906521e0e8944c433f43 | 426 | py | Python | src/ploomber/sources/__init__.py | MarcoJHB/ploomber | 4849ef6915572f7934392443b4faf138172b9596 | [
"Apache-2.0"
] | 2,141 | 2020-02-14T02:34:34.000Z | 2022-03-31T22:43:20.000Z | src/ploomber/sources/__init__.py | MarcoJHB/ploomber | 4849ef6915572f7934392443b4faf138172b9596 | [
"Apache-2.0"
] | 660 | 2020-02-06T16:15:57.000Z | 2022-03-31T22:55:01.000Z | src/ploomber/sources/__init__.py | MarcoJHB/ploomber | 4849ef6915572f7934392443b4faf138172b9596 | [
"Apache-2.0"
] | 122 | 2020-02-14T18:53:05.000Z | 2022-03-27T22:33:24.000Z | from ploomber.sources.sources import (SQLScriptSource, SQLQuerySource,
GenericSource, FileSource, EmptySource)
from ploomber.sources.notebooksource import NotebookSource
from ploomber.sources.pythoncallablesource import PythonCallableSource
__all__ = [
'PythonCallableSource', 'SQLScriptSource', 'SQLQuerySource',
'GenericSource', 'FileSource', 'NotebookSource', 'EmptySource'
]
| 42.6 | 77 | 0.744131 | from ploomber.sources.sources import (SQLScriptSource, SQLQuerySource,
GenericSource, FileSource, EmptySource)
from ploomber.sources.notebooksource import NotebookSource
from ploomber.sources.pythoncallablesource import PythonCallableSource
__all__ = [
'PythonCallableSource', 'SQLScriptSource', 'SQLQuerySource',
'GenericSource', 'FileSource', 'NotebookSource', 'EmptySource'
]
| true | true |
f72b86570c3337610eec48f13a1fb108a1bdff30 | 21,794 | py | Python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_08_01/operations/_vpn_connections_operations.py | beltr0n/azure-sdk-for-python | 2f7fb8bee881b0fc0386a0ad5385755ceedd0453 | [
"MIT"
] | 2 | 2021-03-24T06:26:11.000Z | 2021-04-18T15:55:59.000Z | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_08_01/operations/_vpn_connections_operations.py | beltr0n/azure-sdk-for-python | 2f7fb8bee881b0fc0386a0ad5385755ceedd0453 | [
"MIT"
] | 4 | 2019-04-17T17:57:49.000Z | 2020-04-24T21:11:22.000Z | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_08_01/operations/_vpn_connections_operations.py | beltr0n/azure-sdk-for-python | 2f7fb8bee881b0fc0386a0ad5385755ceedd0453 | [
"MIT"
] | 2 | 2021-05-23T16:46:31.000Z | 2021-05-26T23:51:09.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class VpnConnectionsOperations(object):
"""VpnConnectionsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2019_08_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def get(
self,
resource_group_name, # type: str
gateway_name, # type: str
connection_name, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.VpnConnection"
"""Retrieves the details of a vpn connection.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param connection_name: The name of the vpn connection.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: VpnConnection, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2019_08_01.models.VpnConnection
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
def _create_or_update_initial(
self,
resource_group_name, # type: str
gateway_name, # type: str
connection_name, # type: str
vpn_connection_parameters, # type: "_models.VpnConnection"
**kwargs # type: Any
):
# type: (...) -> "_models.VpnConnection"
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(vpn_connection_parameters, 'VpnConnection')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('VpnConnection', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
def begin_create_or_update(
self,
resource_group_name, # type: str
gateway_name, # type: str
connection_name, # type: str
vpn_connection_parameters, # type: "_models.VpnConnection"
**kwargs # type: Any
):
# type: (...) -> LROPoller["_models.VpnConnection"]
"""Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the
existing connection.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param connection_name: The name of the connection.
:type connection_name: str
:param vpn_connection_parameters: Parameters supplied to create or Update a VPN Connection.
:type vpn_connection_parameters: ~azure.mgmt.network.v2019_08_01.models.VpnConnection
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either VpnConnection or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2019_08_01.models.VpnConnection]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_or_update_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
connection_name=connection_name,
vpn_connection_parameters=vpn_connection_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
def _delete_initial(
self,
resource_group_name, # type: str
gateway_name, # type: str
connection_name, # type: str
**kwargs # type: Any
):
# type: (...) -> None
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
def begin_delete(
self,
resource_group_name, # type: str
gateway_name, # type: str
connection_name, # type: str
**kwargs # type: Any
):
# type: (...) -> LROPoller[None]
"""Deletes a vpn connection.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:param connection_name: The name of the connection.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
connection_name=connection_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore
def list_by_vpn_gateway(
self,
resource_group_name, # type: str
gateway_name, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.ListVpnConnectionsResult"]
"""Retrieves all vpn connections for a particular virtual wan vpn gateway.
:param resource_group_name: The resource group name of the VpnGateway.
:type resource_group_name: str
:param gateway_name: The name of the gateway.
:type gateway_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ListVpnConnectionsResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_08_01.models.ListVpnConnectionsResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVpnConnectionsResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_vpn_gateway.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('ListVpnConnectionsResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_vpn_gateway.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections'} # type: ignore
| 49.307692 | 220 | 0.663944 |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling
from .. import models as _models
if TYPE_CHECKING:
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class VpnConnectionsOperations(object):
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def get(
self,
resource_group_name,
gateway_name,
connection_name,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
accept = "application/json"
url = self.get.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
def _create_or_update_initial(
self,
resource_group_name,
gateway_name,
connection_name,
vpn_connection_parameters,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
url = self._create_or_update_initial.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {}
body_content = self._serialize.body(vpn_connection_parameters, 'VpnConnection')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('VpnConnection', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
def begin_create_or_update(
self,
resource_group_name,
gateway_name,
connection_name,
vpn_connection_parameters,
**kwargs
):
polling = kwargs.pop('polling', True)
cls = kwargs.pop('cls', None)
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None)
if cont_token is None:
raw_result = self._create_or_update_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
connection_name=connection_name,
vpn_connection_parameters=vpn_connection_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VpnConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
def _delete_initial(
self,
resource_group_name,
gateway_name,
connection_name,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
accept = "application/json"
url = self._delete_initial.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
def begin_delete(
self,
resource_group_name,
gateway_name,
connection_name,
**kwargs
):
polling = kwargs.pop('polling', True)
cls = kwargs.pop('cls', None)
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None)
if cont_token is None:
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
gateway_name=gateway_name,
connection_name=connection_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'}
def list_by_vpn_gateway(
self,
resource_group_name,
gateway_name,
**kwargs
):
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-08-01"
accept = "application/json"
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
url = self.list_by_vpn_gateway.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('ListVpnConnectionsResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_vpn_gateway.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections'}
| true | true |
f72b87aee4ad934ef97feead34023c03afde9798 | 1,084 | py | Python | cloudfunc/client.py | jadbin/cloudfunc | 6d54bd993a784d20baba34e8ff897401efb12a22 | [
"MIT"
] | 2 | 2020-08-03T11:39:29.000Z | 2020-08-05T07:09:17.000Z | cloudfunc/client.py | jadbin/cloudfunc | 6d54bd993a784d20baba34e8ff897401efb12a22 | [
"MIT"
] | null | null | null | cloudfunc/client.py | jadbin/cloudfunc | 6d54bd993a784d20baba34e8ff897401efb12a22 | [
"MIT"
] | null | null | null | # coding=utf-8
import os
import pickle
import requests
from .errors import CloudFuncError
class CloudFuncClient:
def __init__(self, serve_address: str = None):
if serve_address is None:
serve_address = os.environ['CLOUDFUNC_SERVE_ADDRESS']
assert serve_address is not None, 'cloudfunc-serve address is not given'
self.serve_address = serve_address
self.session = requests.Session()
def run(self, cloud_func_name: str, *args, **kwargs):
data = pickle.dumps((args, kwargs))
try:
resp = self.session.post(
f'http://{self.serve_address}/cloud-funcs/run',
params={'name': cloud_func_name},
data=data,
headers={'Content-Type': 'application/octet-stream'}
)
except Exception as e:
raise CloudFuncError(e)
else:
try:
resp.raise_for_status()
except requests.HTTPError:
raise CloudFuncError(resp.text)
return pickle.loads(resp.content)
| 30.111111 | 80 | 0.595941 |
import os
import pickle
import requests
from .errors import CloudFuncError
class CloudFuncClient:
def __init__(self, serve_address: str = None):
if serve_address is None:
serve_address = os.environ['CLOUDFUNC_SERVE_ADDRESS']
assert serve_address is not None, 'cloudfunc-serve address is not given'
self.serve_address = serve_address
self.session = requests.Session()
def run(self, cloud_func_name: str, *args, **kwargs):
data = pickle.dumps((args, kwargs))
try:
resp = self.session.post(
f'http://{self.serve_address}/cloud-funcs/run',
params={'name': cloud_func_name},
data=data,
headers={'Content-Type': 'application/octet-stream'}
)
except Exception as e:
raise CloudFuncError(e)
else:
try:
resp.raise_for_status()
except requests.HTTPError:
raise CloudFuncError(resp.text)
return pickle.loads(resp.content)
| true | true |
f72b87c6dad7aa35765c68a88cffd6f561ea82e6 | 3,138 | py | Python | tests/beta_tests/test_shorted_ipv6_address.py | the-zebulan/CodeWars | 1eafd1247d60955a5dfb63e4882e8ce86019f43a | [
"MIT"
] | 40 | 2016-03-09T12:26:20.000Z | 2022-03-23T08:44:51.000Z | tests/beta_tests/test_shorted_ipv6_address.py | akalynych/CodeWars | 1eafd1247d60955a5dfb63e4882e8ce86019f43a | [
"MIT"
] | null | null | null | tests/beta_tests/test_shorted_ipv6_address.py | akalynych/CodeWars | 1eafd1247d60955a5dfb63e4882e8ce86019f43a | [
"MIT"
] | 36 | 2016-11-07T19:59:58.000Z | 2022-03-31T11:18:27.000Z | import unittest
from katas.beta.shorten_ipv6_address import shorten
class ShortenIPv6TestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(shorten('2642:0006:0006:0000:0000:0000:0000:9147'),
'2642:6:6::9147')
def test_equal_2(self):
self.assertEqual(shorten('1234:0000:5678:0000:0000:90AB:0000:CDEF'),
'1234:0:5678::90AB:0:CDEF')
def test_equal_3(self):
self.assertEqual(shorten('1111:0000:0000:2222:0000:0000:3333:4444'),
'1111::2222:0:0:3333:4444')
def test_equal_4(self):
self.assertEqual(shorten('A43B:1CF6:541C:98AA:CC43:1092:E932:90AD'),
'A43B:1CF6:541C:98AA:CC43:1092:E932:90AD')
def test_equal_5(self):
self.assertEqual(shorten('9000:B004:C13A:594C:19CD:102D:394F:FCD1'),
'9000:B004:C13A:594C:19CD:102D:394F:FCD1')
def test_equal_6(self):
self.assertEqual(shorten('043B:00F6:541C:08AA:0003:1092:000D:90AD'),
'43B:F6:541C:8AA:3:1092:D:90AD')
def test_equal_7(self):
self.assertEqual(shorten('9000:0004:000A:094C:00CD:102D:394F:0001'),
'9000:4:A:94C:CD:102D:394F:1')
def test_equal_8(self):
self.assertEqual(shorten('3BDF:000E:0004:0ECD:0000:0009:3C7F:734F'),
'3BDF:E:4:ECD::9:3C7F:734F')
def test_equal_9(self):
self.assertEqual(shorten('0388:0B7B:004D:0000:00D3:FDC1:E0E8:08D7'),
'388:B7B:4D::D3:FDC1:E0E8:8D7')
def test_equal_10(self):
self.assertEqual(shorten('0018:000A:0F0C:10B2:668D:0000:0000:009B'),
'18:A:F0C:10B2:668D::9B')
def test_equal_11(self):
self.assertEqual(shorten('00AF:0000:0000:0000:0000:704E:EC20:3DAA'),
'AF::704E:EC20:3DAA')
def test_equal_12(self):
self.assertEqual(shorten('A2A5:03DB:0000:60A5:0000:0005:BD22:0000'),
'A2A5:3DB::60A5:0:5:BD22:0')
def test_equal_13(self):
self.assertEqual(shorten('0000:0FBA:0000:0000:0000:0000:057E:AFFD'),
'0:FBA::57E:AFFD')
def test_equal_14(self):
self.assertEqual(shorten('0000:0000:0000:0000:0000:0C30:00DA:29CB'),
'::C30:DA:29CB')
def test_equal_15(self):
self.assertEqual(shorten('97CA:4C84:B62B:C3A8:00F4:0000:0000:0000'),
'97CA:4C84:B62B:C3A8:F4::')
def test_equal_16(self):
self.assertEqual(shorten('0000:0391:F08E:0F28:0000:0003:0037:0006'),
'::391:F08E:F28:0:3:37:6')
def test_equal_17(self):
self.assertEqual(shorten('00C8:0000:0243:0050:ED26:008F:0000:0000'),
'C8:0:243:50:ED26:8F::')
def test_equal_18(self):
self.assertEqual(shorten('0000:0000:0001:0007:0F63:0000:4FF7:0000'),
'::1:7:F63:0:4FF7:0')
def test_equal_19(self):
self.assertEqual(shorten('0000:0000:6B6F:63B3:0000:0001:0000:0000'),
'::6B6F:63B3:0:1:0:0')
| 38.268293 | 76 | 0.581899 | import unittest
from katas.beta.shorten_ipv6_address import shorten
class ShortenIPv6TestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(shorten('2642:0006:0006:0000:0000:0000:0000:9147'),
'2642:6:6::9147')
def test_equal_2(self):
self.assertEqual(shorten('1234:0000:5678:0000:0000:90AB:0000:CDEF'),
'1234:0:5678::90AB:0:CDEF')
def test_equal_3(self):
self.assertEqual(shorten('1111:0000:0000:2222:0000:0000:3333:4444'),
'1111::2222:0:0:3333:4444')
def test_equal_4(self):
self.assertEqual(shorten('A43B:1CF6:541C:98AA:CC43:1092:E932:90AD'),
'A43B:1CF6:541C:98AA:CC43:1092:E932:90AD')
def test_equal_5(self):
self.assertEqual(shorten('9000:B004:C13A:594C:19CD:102D:394F:FCD1'),
'9000:B004:C13A:594C:19CD:102D:394F:FCD1')
def test_equal_6(self):
self.assertEqual(shorten('043B:00F6:541C:08AA:0003:1092:000D:90AD'),
'43B:F6:541C:8AA:3:1092:D:90AD')
def test_equal_7(self):
self.assertEqual(shorten('9000:0004:000A:094C:00CD:102D:394F:0001'),
'9000:4:A:94C:CD:102D:394F:1')
def test_equal_8(self):
self.assertEqual(shorten('3BDF:000E:0004:0ECD:0000:0009:3C7F:734F'),
'3BDF:E:4:ECD::9:3C7F:734F')
def test_equal_9(self):
self.assertEqual(shorten('0388:0B7B:004D:0000:00D3:FDC1:E0E8:08D7'),
'388:B7B:4D::D3:FDC1:E0E8:8D7')
def test_equal_10(self):
self.assertEqual(shorten('0018:000A:0F0C:10B2:668D:0000:0000:009B'),
'18:A:F0C:10B2:668D::9B')
def test_equal_11(self):
self.assertEqual(shorten('00AF:0000:0000:0000:0000:704E:EC20:3DAA'),
'AF::704E:EC20:3DAA')
def test_equal_12(self):
self.assertEqual(shorten('A2A5:03DB:0000:60A5:0000:0005:BD22:0000'),
'A2A5:3DB::60A5:0:5:BD22:0')
def test_equal_13(self):
self.assertEqual(shorten('0000:0FBA:0000:0000:0000:0000:057E:AFFD'),
'0:FBA::57E:AFFD')
def test_equal_14(self):
self.assertEqual(shorten('0000:0000:0000:0000:0000:0C30:00DA:29CB'),
'::C30:DA:29CB')
def test_equal_15(self):
self.assertEqual(shorten('97CA:4C84:B62B:C3A8:00F4:0000:0000:0000'),
'97CA:4C84:B62B:C3A8:F4::')
def test_equal_16(self):
self.assertEqual(shorten('0000:0391:F08E:0F28:0000:0003:0037:0006'),
'::391:F08E:F28:0:3:37:6')
def test_equal_17(self):
self.assertEqual(shorten('00C8:0000:0243:0050:ED26:008F:0000:0000'),
'C8:0:243:50:ED26:8F::')
def test_equal_18(self):
self.assertEqual(shorten('0000:0000:0001:0007:0F63:0000:4FF7:0000'),
'::1:7:F63:0:4FF7:0')
def test_equal_19(self):
self.assertEqual(shorten('0000:0000:6B6F:63B3:0000:0001:0000:0000'),
'::6B6F:63B3:0:1:0:0')
| true | true |
f72b8813889944a82a8a131828595a1454d68cd2 | 116,092 | py | Python | electrum/lnworker.py | vhn0912/electrum | a65b97d25c3e37c0e77484f1846e537f9d5be274 | [
"MIT"
] | 1 | 2022-02-24T14:05:49.000Z | 2022-02-24T14:05:49.000Z | electrum/lnworker.py | vhn0912/electrum | a65b97d25c3e37c0e77484f1846e537f9d5be274 | [
"MIT"
] | null | null | null | electrum/lnworker.py | vhn0912/electrum | a65b97d25c3e37c0e77484f1846e537f9d5be274 | [
"MIT"
] | null | null | null | # Copyright (C) 2018 The Electrum developers
# Distributed under the MIT software license, see the accompanying
# file LICENCE or http://www.opensource.org/licenses/mit-license.php
import asyncio
import os
from decimal import Decimal
import random
import time
from typing import (Optional, Sequence, Tuple, List, Set, Dict, TYPE_CHECKING,
NamedTuple, Union, Mapping, Any, Iterable, AsyncGenerator, DefaultDict)
import threading
import socket
import aiohttp
import json
from datetime import datetime, timezone
from functools import partial
from collections import defaultdict
import concurrent
from concurrent import futures
import urllib.parse
import dns.resolver
import dns.exception
from aiorpcx import run_in_thread, NetAddress, ignore_after
from . import constants, util
from . import keystore
from .util import profiler, chunks, OldTaskGroup
from .invoices import PR_TYPE_LN, PR_UNPAID, PR_EXPIRED, PR_PAID, PR_INFLIGHT, PR_FAILED, PR_ROUTING, LNInvoice, LN_EXPIRY_NEVER
from .util import NetworkRetryManager, JsonRPCClient
from .lnutil import LN_MAX_FUNDING_SAT
from .keystore import BIP32_KeyStore
from .bitcoin import COIN
from .bitcoin import opcodes, make_op_return, address_to_scripthash
from .transaction import Transaction
from .transaction import get_script_type_from_output_script
from .crypto import sha256
from .bip32 import BIP32Node
from .util import bh2u, bfh, InvoiceError, resolve_dns_srv, is_ip_address, log_exceptions
from .crypto import chacha20_encrypt, chacha20_decrypt
from .util import ignore_exceptions, make_aiohttp_session
from .util import timestamp_to_datetime, random_shuffled_copy
from .util import MyEncoder, is_private_netaddress, UnrelatedTransactionException
from .logging import Logger
from .lntransport import LNTransport, LNResponderTransport, LNTransportBase
from .lnpeer import Peer, LN_P2P_NETWORK_TIMEOUT
from .lnaddr import lnencode, LnAddr, lndecode
from .ecc import der_sig_from_sig_string
from .lnchannel import Channel, AbstractChannel
from .lnchannel import ChannelState, PeerState, HTLCWithStatus
from .lnrater import LNRater
from . import lnutil
from .lnutil import funding_output_script
from .bitcoin import redeem_script_to_address
from .lnutil import (Outpoint, LNPeerAddr,
get_compressed_pubkey_from_bech32, extract_nodeid,
PaymentFailure, split_host_port, ConnStringFormatError,
generate_keypair, LnKeyFamily, LOCAL, REMOTE,
MIN_FINAL_CLTV_EXPIRY_FOR_INVOICE,
NUM_MAX_EDGES_IN_PAYMENT_PATH, SENT, RECEIVED, HTLCOwner,
UpdateAddHtlc, Direction, LnFeatures, ShortChannelID,
HtlcLog, derive_payment_secret_from_payment_preimage,
NoPathFound, InvalidGossipMsg)
from .lnutil import ln_dummy_address, ln_compare_features, IncompatibleLightningFeatures
from .transaction import PartialTxOutput, PartialTransaction, PartialTxInput
from .lnonion import OnionFailureCode, OnionRoutingFailure
from .lnmsg import decode_msg
from .i18n import _
from .lnrouter import (RouteEdge, LNPaymentRoute, LNPaymentPath, is_route_sane_to_use,
NoChannelPolicy, LNPathInconsistent)
from .address_synchronizer import TX_HEIGHT_LOCAL
from . import lnsweep
from .lnwatcher import LNWalletWatcher
from .crypto import pw_encode_with_version_and_mac, pw_decode_with_version_and_mac
from .lnutil import ImportedChannelBackupStorage, OnchainChannelBackupStorage
from .lnchannel import ChannelBackup
from .channel_db import UpdateStatus
from .channel_db import get_mychannel_info, get_mychannel_policy
from .submarine_swaps import SwapManager
from .channel_db import ChannelInfo, Policy
from .mpp_split import suggest_splits
from .trampoline import create_trampoline_route_and_onion, TRAMPOLINE_FEES, is_legacy_relay
if TYPE_CHECKING:
from .network import Network
from .wallet import Abstract_Wallet
from .channel_db import ChannelDB
from .simple_config import SimpleConfig
SAVED_PR_STATUS = [PR_PAID, PR_UNPAID] # status that are persisted
NUM_PEERS_TARGET = 4
# onchain channel backup data
CB_VERSION = 0
CB_MAGIC_BYTES = bytes([0, 0, 0, CB_VERSION])
FALLBACK_NODE_LIST_TESTNET = (
LNPeerAddr(host='203.132.95.10', port=9735, pubkey=bfh('038863cf8ab91046230f561cd5b386cbff8309fa02e3f0c3ed161a3aeb64a643b9')),
LNPeerAddr(host='2401:d002:4402:0:bf1d:986a:7598:6d49', port=9735, pubkey=bfh('038863cf8ab91046230f561cd5b386cbff8309fa02e3f0c3ed161a3aeb64a643b9')),
LNPeerAddr(host='50.116.3.223', port=9734, pubkey=bfh('03236a685d30096b26692dce0cf0fa7c8528bdf61dbf5363a3ef6d5c92733a3016')),
LNPeerAddr(host='3.16.119.191', port=9735, pubkey=bfh('03d5e17a3c213fe490e1b0c389f8cfcfcea08a29717d50a9f453735e0ab2a7c003')),
LNPeerAddr(host='34.250.234.192', port=9735, pubkey=bfh('03933884aaf1d6b108397e5efe5c86bcf2d8ca8d2f700eda99db9214fc2712b134')),
LNPeerAddr(host='88.99.209.230', port=9735, pubkey=bfh('0260d9119979caedc570ada883ff614c6efb93f7f7382e25d73ecbeba0b62df2d7')),
LNPeerAddr(host='160.16.233.215', port=9735, pubkey=bfh('023ea0a53af875580899da0ab0a21455d9c19160c4ea1b7774c9d4be6810b02d2c')),
LNPeerAddr(host='197.155.6.173', port=9735, pubkey=bfh('0269a94e8b32c005e4336bfb743c08a6e9beb13d940d57c479d95c8e687ccbdb9f')),
LNPeerAddr(host='2c0f:fb18:406::4', port=9735, pubkey=bfh('0269a94e8b32c005e4336bfb743c08a6e9beb13d940d57c479d95c8e687ccbdb9f')),
LNPeerAddr(host='163.172.94.64', port=9735, pubkey=bfh('030f0bf260acdbd3edcad84d7588ec7c5df4711e87e6a23016f989b8d3a4147230')),
LNPeerAddr(host='23.237.77.12', port=9735, pubkey=bfh('02312627fdf07fbdd7e5ddb136611bdde9b00d26821d14d94891395452f67af248')),
LNPeerAddr(host='197.155.6.172', port=9735, pubkey=bfh('02ae2f22b02375e3e9b4b4a2db4f12e1b50752b4062dbefd6e01332acdaf680379')),
LNPeerAddr(host='2c0f:fb18:406::3', port=9735, pubkey=bfh('02ae2f22b02375e3e9b4b4a2db4f12e1b50752b4062dbefd6e01332acdaf680379')),
LNPeerAddr(host='23.239.23.44', port=9740, pubkey=bfh('034fe52e98a0e9d3c21b767e1b371881265d8c7578c21f5afd6d6438da10348b36')),
LNPeerAddr(host='2600:3c01::f03c:91ff:fe05:349c', port=9740, pubkey=bfh('034fe52e98a0e9d3c21b767e1b371881265d8c7578c21f5afd6d6438da10348b36')),
)
FALLBACK_NODE_LIST_MAINNET = [
LNPeerAddr(host='172.81.181.3', port=9735, pubkey=bfh('0214382bdce7750dfcb8126df8e2b12de38536902dc36abcebdaeefdeca1df8284')),
LNPeerAddr(host='35.230.100.60', port=9735, pubkey=bfh('023f5e3582716bed96f6f26cfcd8037e07474d7b4743afdc8b07e692df63464d7e')),
LNPeerAddr(host='40.69.71.114', port=9735, pubkey=bfh('028303182c9885da93b3b25c9621d22cf34475e63c123942e402ab530c0556e675')),
LNPeerAddr(host='94.177.171.73', port=9735, pubkey=bfh('0276e09a267592e7451a939c932cf685f0754de382a3ca85d2fb3a864d4c365ad5')),
LNPeerAddr(host='34.236.113.58', port=9735, pubkey=bfh('02fa50c72ee1e2eb5f1b6d9c3032080c4c864373c4201dfa2966aa34eee1051f97')),
LNPeerAddr(host='52.50.244.44', port=9735, pubkey=bfh('030c3f19d742ca294a55c00376b3b355c3c90d61c6b6b39554dbc7ac19b141c14f')),
LNPeerAddr(host='157.245.68.47', port=9735, pubkey=bfh('03c2abfa93eacec04721c019644584424aab2ba4dff3ac9bdab4e9c97007491dda')),
LNPeerAddr(host='18.221.23.28', port=9735, pubkey=bfh('03abf6f44c355dec0d5aa155bdbdd6e0c8fefe318eff402de65c6eb2e1be55dc3e')),
LNPeerAddr(host='52.224.178.244', port=9735, pubkey=bfh('026b105ac13212c48714c6be9b11577a9ce10f10e1c88a45ce217e6331209faf8b')),
LNPeerAddr(host='34.239.230.56', port=9735, pubkey=bfh('03864ef025fde8fb587d989186ce6a4a186895ee44a926bfc370e2c366597a3f8f')),
LNPeerAddr(host='46.229.165.136', port=9735, pubkey=bfh('0390b5d4492dc2f5318e5233ab2cebf6d48914881a33ef6a9c6bcdbb433ad986d0')),
LNPeerAddr(host='157.230.28.160', port=9735, pubkey=bfh('0279c22ed7a068d10dc1a38ae66d2d6461e269226c60258c021b1ddcdfe4b00bc4')),
LNPeerAddr(host='74.108.13.152', port=9735, pubkey=bfh('0331f80652fb840239df8dc99205792bba2e559a05469915804c08420230e23c7c')),
LNPeerAddr(host='167.172.44.148', port=9735, pubkey=bfh('0395033b252c6f40e3756984162d68174e2bd8060a129c0d3462a9370471c6d28f')),
LNPeerAddr(host='138.68.14.104', port=9735, pubkey=bfh('03bb88ccc444534da7b5b64b4f7b15e1eccb18e102db0e400d4b9cfe93763aa26d')),
LNPeerAddr(host='3.124.63.44', port=9735, pubkey=bfh('0242a4ae0c5bef18048fbecf995094b74bfb0f7391418d71ed394784373f41e4f3')),
LNPeerAddr(host='2001:470:8:2e1::43', port=9735, pubkey=bfh('03baa70886d9200af0ffbd3f9e18d96008331c858456b16e3a9b41e735c6208fef')),
LNPeerAddr(host='2601:186:c100:6bcd:219:d1ff:fe75:dc2f', port=9735, pubkey=bfh('0298f6074a454a1f5345cb2a7c6f9fce206cd0bf675d177cdbf0ca7508dd28852f')),
LNPeerAddr(host='2001:41d0:e:734::1', port=9735, pubkey=bfh('03a503d8e30f2ff407096d235b5db63b4fcf3f89a653acb6f43d3fc492a7674019')),
LNPeerAddr(host='2a01:4f9:2b:2254::2', port=9735, pubkey=bfh('02f3069a342ae2883a6f29e275f06f28a56a6ea2e2d96f5888a3266444dcf542b6')),
LNPeerAddr(host='2a02:8070:24c1:100:528c:2997:6dbc:a054', port=9735, pubkey=bfh('02a45def9ae014fdd2603dd7033d157faa3a55a72b06a63ae22ef46d9fafdc6e8d')),
LNPeerAddr(host='2600:3c01::f03c:91ff:fe05:349c', port=9736, pubkey=bfh('02731b798b39a09f9f14e90ee601afb6ebb796d6e5797de14582a978770b33700f')),
LNPeerAddr(host='2a00:8a60:e012:a00::21', port=9735, pubkey=bfh('027ce055380348d7812d2ae7745701c9f93e70c1adeb2657f053f91df4f2843c71')),
LNPeerAddr(host='2604:a880:400:d1::8bd:1001', port=9735, pubkey=bfh('03649c72a4816f0cd546f84aafbd657e92a30ab474de7ab795e8b5650a427611f7')),
LNPeerAddr(host='2a01:4f8:c0c:7b31::1', port=9735, pubkey=bfh('02c16cca44562b590dd279c942200bdccfd4f990c3a69fad620c10ef2f8228eaff')),
LNPeerAddr(host='2001:41d0:1:b40d::1', port=9735, pubkey=bfh('026726a4b043d413b45b334876d17b8a98848129604429ec65532ba286a42efeac')),
]
from .trampoline import trampolines_by_id, hardcoded_trampoline_nodes, is_hardcoded_trampoline
class PaymentInfo(NamedTuple):
payment_hash: bytes
amount_msat: Optional[int]
direction: int
status: int
class ErrorAddingPeer(Exception): pass
# set some feature flags as baseline for both LNWallet and LNGossip
# note that e.g. DATA_LOSS_PROTECT is needed for LNGossip as many peers require it
BASE_FEATURES = LnFeatures(0)\
| LnFeatures.OPTION_DATA_LOSS_PROTECT_OPT\
| LnFeatures.OPTION_STATIC_REMOTEKEY_OPT\
| LnFeatures.VAR_ONION_OPT\
| LnFeatures.PAYMENT_SECRET_OPT\
| LnFeatures.OPTION_UPFRONT_SHUTDOWN_SCRIPT_OPT\
# we do not want to receive unrequested gossip (see lnpeer.maybe_save_remote_update)
LNWALLET_FEATURES = BASE_FEATURES\
| LnFeatures.OPTION_DATA_LOSS_PROTECT_REQ\
| LnFeatures.OPTION_STATIC_REMOTEKEY_REQ\
| LnFeatures.GOSSIP_QUERIES_REQ\
| LnFeatures.BASIC_MPP_OPT\
| LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT\
| LnFeatures.OPTION_SHUTDOWN_ANYSEGWIT_OPT\
| LnFeatures.OPTION_CHANNEL_TYPE_OPT\
LNGOSSIP_FEATURES = BASE_FEATURES\
| LnFeatures.GOSSIP_QUERIES_OPT\
| LnFeatures.GOSSIP_QUERIES_REQ\
class LNWorker(Logger, NetworkRetryManager[LNPeerAddr]):
INITIAL_TRAMPOLINE_FEE_LEVEL = 1 # only used for trampoline payments. set to 0 in tests.
def __init__(self, xprv, features: LnFeatures):
Logger.__init__(self)
NetworkRetryManager.__init__(
self,
max_retry_delay_normal=3600,
init_retry_delay_normal=600,
max_retry_delay_urgent=300,
init_retry_delay_urgent=4,
)
self.lock = threading.RLock()
self.node_keypair = generate_keypair(BIP32Node.from_xkey(xprv), LnKeyFamily.NODE_KEY)
self.backup_key = generate_keypair(BIP32Node.from_xkey(xprv), LnKeyFamily.BACKUP_CIPHER).privkey
self._peers = {} # type: Dict[bytes, Peer] # pubkey -> Peer # needs self.lock
self.taskgroup = OldTaskGroup()
self.listen_server = None # type: Optional[asyncio.AbstractServer]
self.features = features
self.network = None # type: Optional[Network]
self.config = None # type: Optional[SimpleConfig]
self.stopping_soon = False # whether we are being shut down
util.register_callback(self.on_proxy_changed, ['proxy_set'])
@property
def channel_db(self):
return self.network.channel_db if self.network else None
@property
def peers(self) -> Mapping[bytes, Peer]:
"""Returns a read-only copy of peers."""
with self.lock:
return self._peers.copy()
def channels_for_peer(self, node_id: bytes) -> Dict[bytes, Channel]:
return {}
def get_node_alias(self, node_id: bytes) -> Optional[str]:
"""Returns the alias of the node, or None if unknown."""
node_alias = None
if self.channel_db:
node_info = self.channel_db.get_node_info_for_node_id(node_id)
if node_info:
node_alias = node_info.alias
else:
for k, v in hardcoded_trampoline_nodes().items():
if v.pubkey == node_id:
node_alias = k
break
return node_alias
async def maybe_listen(self):
# FIXME: only one LNWorker can listen at a time (single port)
listen_addr = self.config.get('lightning_listen')
if listen_addr:
self.logger.info(f'lightning_listen enabled. will try to bind: {listen_addr!r}')
try:
netaddr = NetAddress.from_string(listen_addr)
except Exception as e:
self.logger.error(f"failed to parse config key 'lightning_listen'. got: {e!r}")
return
addr = str(netaddr.host)
async def cb(reader, writer):
transport = LNResponderTransport(self.node_keypair.privkey, reader, writer)
try:
node_id = await transport.handshake()
except Exception as e:
self.logger.info(f'handshake failure from incoming connection: {e!r}')
return
await self._add_peer_from_transport(node_id=node_id, transport=transport)
try:
self.listen_server = await asyncio.start_server(cb, addr, netaddr.port)
except OSError as e:
self.logger.error(f"cannot listen for lightning p2p. error: {e!r}")
@ignore_exceptions # don't kill outer taskgroup
async def main_loop(self):
self.logger.info("starting taskgroup.")
try:
async with self.taskgroup as group:
await group.spawn(self._maintain_connectivity())
except Exception as e:
self.logger.exception("taskgroup died.")
finally:
self.logger.info("taskgroup stopped.")
async def _maintain_connectivity(self):
while True:
await asyncio.sleep(1)
if self.stopping_soon:
return
now = time.time()
if len(self._peers) >= NUM_PEERS_TARGET:
continue
peers = await self._get_next_peers_to_try()
for peer in peers:
if self._can_retry_addr(peer, now=now):
try:
await self._add_peer(peer.host, peer.port, peer.pubkey)
except ErrorAddingPeer as e:
self.logger.info(f"failed to add peer: {peer}. exc: {e!r}")
async def _add_peer(self, host: str, port: int, node_id: bytes) -> Peer:
if node_id in self._peers:
return self._peers[node_id]
port = int(port)
peer_addr = LNPeerAddr(host, port, node_id)
self._trying_addr_now(peer_addr)
self.logger.info(f"adding peer {peer_addr}")
if node_id == self.node_keypair.pubkey:
raise ErrorAddingPeer("cannot connect to self")
transport = LNTransport(self.node_keypair.privkey, peer_addr,
proxy=self.network.proxy)
peer = await self._add_peer_from_transport(node_id=node_id, transport=transport)
return peer
async def _add_peer_from_transport(self, *, node_id: bytes, transport: LNTransportBase) -> Peer:
peer = Peer(self, node_id, transport)
with self.lock:
existing_peer = self._peers.get(node_id)
if existing_peer:
existing_peer.close_and_cleanup()
assert node_id not in self._peers
self._peers[node_id] = peer
await self.taskgroup.spawn(peer.main_loop())
return peer
def peer_closed(self, peer: Peer) -> None:
with self.lock:
peer2 = self._peers.get(peer.pubkey)
if peer2 is peer:
self._peers.pop(peer.pubkey)
def num_peers(self) -> int:
return sum([p.is_initialized() for p in self.peers.values()])
def start_network(self, network: 'Network'):
assert network
self.network = network
self.config = network.config
self._add_peers_from_config()
asyncio.run_coroutine_threadsafe(self.main_loop(), self.network.asyncio_loop)
async def stop(self):
if self.listen_server:
self.listen_server.close()
util.unregister_callback(self.on_proxy_changed)
await self.taskgroup.cancel_remaining()
def _add_peers_from_config(self):
peer_list = self.config.get('lightning_peers', [])
for host, port, pubkey in peer_list:
asyncio.run_coroutine_threadsafe(
self._add_peer(host, int(port), bfh(pubkey)),
self.network.asyncio_loop)
def is_good_peer(self, peer: LNPeerAddr) -> bool:
# the purpose of this method is to filter peers that advertise the desired feature bits
# it is disabled for now, because feature bits published in node announcements seem to be unreliable
return True
node_id = peer.pubkey
node = self.channel_db._nodes.get(node_id)
if not node:
return False
try:
ln_compare_features(self.features, node.features)
except IncompatibleLightningFeatures:
return False
#self.logger.info(f'is_good {peer.host}')
return True
def on_peer_successfully_established(self, peer: Peer) -> None:
if isinstance(peer.transport, LNTransport):
peer_addr = peer.transport.peer_addr
# reset connection attempt count
self._on_connection_successfully_established(peer_addr)
# add into channel db
if self.channel_db:
self.channel_db.add_recent_peer(peer_addr)
# save network address into channels we might have with peer
for chan in peer.channels.values():
chan.add_or_update_peer_addr(peer_addr)
async def _get_next_peers_to_try(self) -> Sequence[LNPeerAddr]:
now = time.time()
await self.channel_db.data_loaded.wait()
# first try from recent peers
recent_peers = self.channel_db.get_recent_peers()
for peer in recent_peers:
if not peer:
continue
if peer.pubkey in self._peers:
continue
if not self._can_retry_addr(peer, now=now):
continue
if not self.is_good_peer(peer):
continue
return [peer]
# try random peer from graph
unconnected_nodes = self.channel_db.get_200_randomly_sorted_nodes_not_in(self.peers.keys())
if unconnected_nodes:
for node_id in unconnected_nodes:
addrs = self.channel_db.get_node_addresses(node_id)
if not addrs:
continue
host, port, timestamp = self.choose_preferred_address(list(addrs))
try:
peer = LNPeerAddr(host, port, node_id)
except ValueError:
continue
if not self._can_retry_addr(peer, now=now):
continue
if not self.is_good_peer(peer):
continue
#self.logger.info('taking random ln peer from our channel db')
return [peer]
# getting desperate... let's try hardcoded fallback list of peers
if constants.net in (constants.BitcoinTestnet,):
fallback_list = FALLBACK_NODE_LIST_TESTNET
elif constants.net in (constants.BitcoinMainnet,):
fallback_list = FALLBACK_NODE_LIST_MAINNET
else:
return [] # regtest??
fallback_list = [peer for peer in fallback_list if self._can_retry_addr(peer, now=now)]
if fallback_list:
return [random.choice(fallback_list)]
# last resort: try dns seeds (BOLT-10)
return await run_in_thread(self._get_peers_from_dns_seeds)
def _get_peers_from_dns_seeds(self) -> Sequence[LNPeerAddr]:
# NOTE: potentially long blocking call, do not run directly on asyncio event loop.
# Return several peers to reduce the number of dns queries.
if not constants.net.LN_DNS_SEEDS:
return []
dns_seed = random.choice(constants.net.LN_DNS_SEEDS)
self.logger.info('asking dns seed "{}" for ln peers'.format(dns_seed))
try:
# note: this might block for several seconds
# this will include bech32-encoded-pubkeys and ports
srv_answers = resolve_dns_srv('r{}.{}'.format(
constants.net.LN_REALM_BYTE, dns_seed))
except dns.exception.DNSException as e:
self.logger.info(f'failed querying (1) dns seed "{dns_seed}" for ln peers: {repr(e)}')
return []
random.shuffle(srv_answers)
num_peers = 2 * NUM_PEERS_TARGET
srv_answers = srv_answers[:num_peers]
# we now have pubkeys and ports but host is still needed
peers = []
for srv_ans in srv_answers:
try:
# note: this might block for several seconds
answers = dns.resolver.resolve(srv_ans['host'])
except dns.exception.DNSException as e:
self.logger.info(f'failed querying (2) dns seed "{dns_seed}" for ln peers: {repr(e)}')
continue
try:
ln_host = str(answers[0])
port = int(srv_ans['port'])
bech32_pubkey = srv_ans['host'].split('.')[0]
pubkey = get_compressed_pubkey_from_bech32(bech32_pubkey)
peers.append(LNPeerAddr(ln_host, port, pubkey))
except Exception as e:
self.logger.info(f'error with parsing peer from dns seed: {repr(e)}')
continue
self.logger.info(f'got {len(peers)} ln peers from dns seed')
return peers
@staticmethod
def choose_preferred_address(addr_list: Sequence[Tuple[str, int, int]]) -> Tuple[str, int, int]:
assert len(addr_list) >= 1
# choose first one that is an IP
for host, port, timestamp in addr_list:
if is_ip_address(host):
return host, port, timestamp
# otherwise choose one at random
# TODO maybe filter out onion if not on tor?
choice = random.choice(addr_list)
return choice
def on_proxy_changed(self, event, *args):
for peer in self.peers.values():
peer.close_and_cleanup()
self._clear_addr_retry_times()
@log_exceptions
async def add_peer(self, connect_str: str) -> Peer:
node_id, rest = extract_nodeid(connect_str)
peer = self._peers.get(node_id)
if not peer:
if rest is not None:
host, port = split_host_port(rest)
else:
if not self.channel_db:
addr = trampolines_by_id().get(node_id)
if not addr:
raise ConnStringFormatError(_('Address unknown for node:') + ' ' + bh2u(node_id))
host, port = addr.host, addr.port
else:
addrs = self.channel_db.get_node_addresses(node_id)
if not addrs:
raise ConnStringFormatError(_('Don\'t know any addresses for node:') + ' ' + bh2u(node_id))
host, port, timestamp = self.choose_preferred_address(list(addrs))
port = int(port)
# Try DNS-resolving the host (if needed). This is simply so that
# the caller gets a nice exception if it cannot be resolved.
try:
await asyncio.get_event_loop().getaddrinfo(host, port)
except socket.gaierror:
raise ConnStringFormatError(_('Hostname does not resolve (getaddrinfo failed)'))
# add peer
peer = await self._add_peer(host, port, node_id)
return peer
class LNGossip(LNWorker):
max_age = 14*24*3600
LOGGING_SHORTCUT = 'g'
def __init__(self):
seed = os.urandom(32)
node = BIP32Node.from_rootseed(seed, xtype='standard')
xprv = node.to_xprv()
super().__init__(xprv, LNGOSSIP_FEATURES)
self.unknown_ids = set()
def start_network(self, network: 'Network'):
assert network
super().start_network(network)
asyncio.run_coroutine_threadsafe(self.taskgroup.spawn(self.maintain_db()), self.network.asyncio_loop)
async def maintain_db(self):
await self.channel_db.data_loaded.wait()
while True:
if len(self.unknown_ids) == 0:
self.channel_db.prune_old_policies(self.max_age)
self.channel_db.prune_orphaned_channels()
await asyncio.sleep(120)
async def add_new_ids(self, ids: Iterable[bytes]):
known = self.channel_db.get_channel_ids()
new = set(ids) - set(known)
self.unknown_ids.update(new)
util.trigger_callback('unknown_channels', len(self.unknown_ids))
util.trigger_callback('gossip_peers', self.num_peers())
util.trigger_callback('ln_gossip_sync_progress')
def get_ids_to_query(self) -> Sequence[bytes]:
N = 500
l = list(self.unknown_ids)
self.unknown_ids = set(l[N:])
util.trigger_callback('unknown_channels', len(self.unknown_ids))
util.trigger_callback('ln_gossip_sync_progress')
return l[0:N]
def get_sync_progress_estimate(self) -> Tuple[Optional[int], Optional[int], Optional[int]]:
"""Estimates the gossip synchronization process and returns the number
of synchronized channels, the total channels in the network and a
rescaled percentage of the synchronization process."""
if self.num_peers() == 0:
return None, None, None
nchans_with_0p, nchans_with_1p, nchans_with_2p = self.channel_db.get_num_channels_partitioned_by_policy_count()
num_db_channels = nchans_with_0p + nchans_with_1p + nchans_with_2p
# some channels will never have two policies (only one is in gossip?...)
# so if we have at least 1 policy for a channel, we consider that channel "complete" here
current_est = num_db_channels - nchans_with_0p
total_est = len(self.unknown_ids) + num_db_channels
progress = current_est / total_est if total_est and current_est else 0
progress_percent = (1.0 / 0.95 * progress) * 100
progress_percent = min(progress_percent, 100)
progress_percent = round(progress_percent)
# take a minimal number of synchronized channels to get a more accurate
# percentage estimate
if current_est < 200:
progress_percent = 0
return current_est, total_est, progress_percent
async def process_gossip(self, chan_anns, node_anns, chan_upds):
# note: we run in the originating peer's TaskGroup, so we can safely raise here
# and disconnect only from that peer
await self.channel_db.data_loaded.wait()
self.logger.debug(f'process_gossip {len(chan_anns)} {len(node_anns)} {len(chan_upds)}')
# channel announcements
def process_chan_anns():
for payload in chan_anns:
self.channel_db.verify_channel_announcement(payload)
self.channel_db.add_channel_announcements(chan_anns)
await run_in_thread(process_chan_anns)
# node announcements
def process_node_anns():
for payload in node_anns:
self.channel_db.verify_node_announcement(payload)
self.channel_db.add_node_announcements(node_anns)
await run_in_thread(process_node_anns)
# channel updates
categorized_chan_upds = await run_in_thread(partial(
self.channel_db.add_channel_updates,
chan_upds,
max_age=self.max_age))
orphaned = categorized_chan_upds.orphaned
if orphaned:
self.logger.info(f'adding {len(orphaned)} unknown channel ids')
orphaned_ids = [c['short_channel_id'] for c in orphaned]
await self.add_new_ids(orphaned_ids)
if categorized_chan_upds.good:
self.logger.debug(f'on_channel_update: {len(categorized_chan_upds.good)}/{len(chan_upds)}')
class LNWallet(LNWorker):
lnwatcher: Optional['LNWalletWatcher']
MPP_EXPIRY = 120
TIMEOUT_SHUTDOWN_FAIL_PENDING_HTLCS = 3 # seconds
def __init__(self, wallet: 'Abstract_Wallet', xprv):
self.wallet = wallet
self.db = wallet.db
Logger.__init__(self)
LNWorker.__init__(self, xprv, LNWALLET_FEATURES)
self.config = wallet.config
self.lnwatcher = None
self.lnrater: LNRater = None
self.payments = self.db.get_dict('lightning_payments') # RHASH -> amount, direction, is_paid
self.preimages = self.db.get_dict('lightning_preimages') # RHASH -> preimage
# note: this sweep_address is only used as fallback; as it might result in address-reuse
self.sweep_address = wallet.get_new_sweep_address_for_channel()
self.logs = defaultdict(list) # type: Dict[str, List[HtlcLog]] # key is RHASH # (not persisted)
# used in tests
self.enable_htlc_settle = True
self.enable_htlc_forwarding = True
# note: accessing channels (besides simple lookup) needs self.lock!
self._channels = {} # type: Dict[bytes, Channel]
channels = self.db.get_dict("channels")
for channel_id, c in random_shuffled_copy(channels.items()):
self._channels[bfh(channel_id)] = Channel(c, sweep_address=self.sweep_address, lnworker=self)
self._channel_backups = {} # type: Dict[bytes, ChannelBackup]
# order is important: imported should overwrite onchain
for name in ["onchain_channel_backups", "imported_channel_backups"]:
channel_backups = self.db.get_dict(name)
for channel_id, storage in channel_backups.items():
self._channel_backups[bfh(channel_id)] = ChannelBackup(storage, sweep_address=self.sweep_address, lnworker=self)
self.sent_htlcs = defaultdict(asyncio.Queue) # type: Dict[bytes, asyncio.Queue[HtlcLog]]
self.sent_htlcs_info = dict() # (RHASH, scid, htlc_id) -> route, payment_secret, amount_msat, bucket_msat, trampoline_fee_level
self.sent_buckets = dict() # payment_secret -> (amount_sent, amount_failed)
self.received_mpp_htlcs = dict() # RHASH -> mpp_status, htlc_set
self.swap_manager = SwapManager(wallet=self.wallet, lnworker=self)
# detect inflight payments
self.inflight_payments = set() # (not persisted) keys of invoices that are in PR_INFLIGHT state
for payment_hash in self.get_payments(status='inflight').keys():
self.set_invoice_status(payment_hash.hex(), PR_INFLIGHT)
self.trampoline_forwarding_failures = {} # todo: should be persisted
# map forwarded htlcs (fw_info=(scid_hex, htlc_id)) to originating peer pubkeys
self.downstream_htlc_to_upstream_peer_map = {} # type: Dict[Tuple[str, int], bytes]
def has_deterministic_node_id(self) -> bool:
return bool(self.db.get('lightning_xprv'))
def can_have_recoverable_channels(self) -> bool:
return (self.has_deterministic_node_id()
and not (self.config.get('lightning_listen')))
def has_recoverable_channels(self) -> bool:
"""Whether *future* channels opened by this wallet would be recoverable
from seed (via putting OP_RETURN outputs into funding txs).
"""
return (self.can_have_recoverable_channels()
and self.config.get('use_recoverable_channels', True))
@property
def channels(self) -> Mapping[bytes, Channel]:
"""Returns a read-only copy of channels."""
with self.lock:
return self._channels.copy()
@property
def channel_backups(self) -> Mapping[bytes, ChannelBackup]:
"""Returns a read-only copy of channels."""
with self.lock:
return self._channel_backups.copy()
def get_channel_by_id(self, channel_id: bytes) -> Optional[Channel]:
return self._channels.get(channel_id, None)
def diagnostic_name(self):
return self.wallet.diagnostic_name()
@ignore_exceptions
@log_exceptions
async def sync_with_local_watchtower(self):
watchtower = self.network.local_watchtower
if watchtower:
while True:
for chan in self.channels.values():
await self.sync_channel_with_watchtower(chan, watchtower.sweepstore)
await asyncio.sleep(5)
@ignore_exceptions
@log_exceptions
async def sync_with_remote_watchtower(self):
while True:
# periodically poll if the user updated 'watchtower_url'
await asyncio.sleep(5)
watchtower_url = self.config.get('watchtower_url')
if not watchtower_url:
continue
parsed_url = urllib.parse.urlparse(watchtower_url)
if not (parsed_url.scheme == 'https' or is_private_netaddress(parsed_url.hostname)):
self.logger.warning(f"got watchtower URL for remote tower but we won't use it! "
f"can only use HTTPS (except if private IP): not using {watchtower_url!r}")
continue
# try to sync with the remote watchtower
try:
async with make_aiohttp_session(proxy=self.network.proxy) as session:
watchtower = JsonRPCClient(session, watchtower_url)
watchtower.add_method('get_ctn')
watchtower.add_method('add_sweep_tx')
for chan in self.channels.values():
await self.sync_channel_with_watchtower(chan, watchtower)
except aiohttp.client_exceptions.ClientConnectorError:
self.logger.info(f'could not contact remote watchtower {watchtower_url}')
async def sync_channel_with_watchtower(self, chan: Channel, watchtower):
outpoint = chan.funding_outpoint.to_str()
addr = chan.get_funding_address()
current_ctn = chan.get_oldest_unrevoked_ctn(REMOTE)
watchtower_ctn = await watchtower.get_ctn(outpoint, addr)
for ctn in range(watchtower_ctn + 1, current_ctn):
sweeptxs = chan.create_sweeptxs(ctn)
for tx in sweeptxs:
await watchtower.add_sweep_tx(outpoint, ctn, tx.inputs()[0].prevout.to_str(), tx.serialize())
def start_network(self, network: 'Network'):
assert network
self.network = network
self.config = network.config
self.lnwatcher = LNWalletWatcher(self, network)
self.lnwatcher.start_network(network)
self.swap_manager.start_network(network=network, lnwatcher=self.lnwatcher)
self.lnrater = LNRater(self, network)
for chan in self.channels.values():
self.lnwatcher.add_channel(chan.funding_outpoint.to_str(), chan.get_funding_address())
for cb in self.channel_backups.values():
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
for coro in [
self.maybe_listen(),
self.lnwatcher.on_network_update('network_updated'), # shortcut (don't block) if funding tx locked and verified
self.reestablish_peers_and_channels(),
self.sync_with_local_watchtower(),
self.sync_with_remote_watchtower(),
]:
tg_coro = self.taskgroup.spawn(coro)
asyncio.run_coroutine_threadsafe(tg_coro, self.network.asyncio_loop)
async def stop(self):
self.stopping_soon = True
if self.listen_server: # stop accepting new peers
self.listen_server.close()
async with ignore_after(self.TIMEOUT_SHUTDOWN_FAIL_PENDING_HTLCS):
await self.wait_for_received_pending_htlcs_to_get_removed()
await LNWorker.stop(self)
if self.lnwatcher:
await self.lnwatcher.stop()
self.lnwatcher = None
async def wait_for_received_pending_htlcs_to_get_removed(self):
assert self.stopping_soon is True
# We try to fail pending MPP HTLCs, and wait a bit for them to get removed.
# Note: even without MPP, if we just failed/fulfilled an HTLC, it is good
# to wait a bit for it to become irrevocably removed.
# Note: we don't wait for *all htlcs* to get removed, only for those
# that we can already fail/fulfill. e.g. forwarded htlcs cannot be removed
async with OldTaskGroup() as group:
for peer in self.peers.values():
await group.spawn(peer.wait_one_htlc_switch_iteration())
while True:
if all(not peer.received_htlcs_pending_removal for peer in self.peers.values()):
break
async with OldTaskGroup(wait=any) as group:
for peer in self.peers.values():
await group.spawn(peer.received_htlc_removed_event.wait())
def peer_closed(self, peer):
for chan in self.channels_for_peer(peer.pubkey).values():
chan.peer_state = PeerState.DISCONNECTED
util.trigger_callback('channel', self.wallet, chan)
super().peer_closed(peer)
def get_payments(self, *, status=None) -> Mapping[bytes, List[HTLCWithStatus]]:
out = defaultdict(list)
for chan in self.channels.values():
d = chan.get_payments(status=status)
for payment_hash, plist in d.items():
out[payment_hash] += plist
return out
def get_payment_value(
self, info: Optional['PaymentInfo'], plist: List[HTLCWithStatus],
) -> Tuple[int, int, int]:
assert plist
amount_msat = 0
fee_msat = None
for htlc_with_status in plist:
htlc = htlc_with_status.htlc
_direction = htlc_with_status.direction
amount_msat += int(_direction) * htlc.amount_msat
if _direction == SENT and info and info.amount_msat:
fee_msat = (fee_msat or 0) - info.amount_msat - amount_msat
timestamp = min([htlc_with_status.htlc.timestamp for htlc_with_status in plist])
return amount_msat, fee_msat, timestamp
def get_lightning_history(self):
out = {}
for payment_hash, plist in self.get_payments(status='settled').items():
if len(plist) == 0:
continue
key = payment_hash.hex()
info = self.get_payment_info(payment_hash)
amount_msat, fee_msat, timestamp = self.get_payment_value(info, plist)
if info is not None:
label = self.wallet.get_label(key)
direction = ('sent' if info.direction == SENT else 'received') if len(plist)==1 else 'self-payment'
else:
direction = 'forwarding'
label = _('Forwarding')
preimage = self.get_preimage(payment_hash).hex()
item = {
'type': 'payment',
'label': label,
'timestamp': timestamp or 0,
'date': timestamp_to_datetime(timestamp),
'direction': direction,
'amount_msat': amount_msat,
'fee_msat': fee_msat,
'payment_hash': key,
'preimage': preimage,
}
# add group_id to swap transactions
swap = self.swap_manager.get_swap(payment_hash)
if swap:
if swap.is_reverse:
item['group_id'] = swap.spending_txid
item['group_label'] = 'Reverse swap' + ' ' + self.config.format_amount_and_units(swap.lightning_amount)
else:
item['group_id'] = swap.funding_txid
item['group_label'] = 'Forward swap' + ' ' + self.config.format_amount_and_units(swap.onchain_amount)
# done
out[payment_hash] = item
return out
def get_onchain_history(self):
current_height = self.wallet.get_local_height()
out = {}
# add funding events
for chan in self.channels.values():
item = chan.get_funding_height()
if item is None:
continue
if not self.lnwatcher:
continue # lnwatcher not available with --offline (its data is not persisted)
funding_txid, funding_height, funding_timestamp = item
tx_height = self.lnwatcher.get_tx_height(funding_txid)
item = {
'channel_id': bh2u(chan.channel_id),
'type': 'channel_opening',
'label': self.wallet.get_label_for_txid(funding_txid) or (_('Open channel') + ' ' + chan.get_id_for_log()),
'txid': funding_txid,
'amount_msat': chan.balance(LOCAL, ctn=0),
'direction': 'received',
'timestamp': tx_height.timestamp,
'date': timestamp_to_datetime(tx_height.timestamp),
'fee_sat': None,
'fee_msat': None,
'height': tx_height.height,
'confirmations': tx_height.conf,
}
out[funding_txid] = item
item = chan.get_closing_height()
if item is None:
continue
closing_txid, closing_height, closing_timestamp = item
tx_height = self.lnwatcher.get_tx_height(closing_txid)
item = {
'channel_id': bh2u(chan.channel_id),
'txid': closing_txid,
'label': self.wallet.get_label_for_txid(closing_txid) or (_('Close channel') + ' ' + chan.get_id_for_log()),
'type': 'channel_closure',
'amount_msat': -chan.balance_minus_outgoing_htlcs(LOCAL),
'direction': 'sent',
'timestamp': tx_height.timestamp,
'date': timestamp_to_datetime(tx_height.timestamp),
'fee_sat': None,
'fee_msat': None,
'height': tx_height.height,
'confirmations': tx_height.conf,
}
out[closing_txid] = item
# add info about submarine swaps
settled_payments = self.get_payments(status='settled')
for payment_hash_hex, swap in self.swap_manager.swaps.items():
txid = swap.spending_txid if swap.is_reverse else swap.funding_txid
if txid is None:
continue
payment_hash = bytes.fromhex(payment_hash_hex)
if payment_hash in settled_payments:
plist = settled_payments[payment_hash]
info = self.get_payment_info(payment_hash)
amount_msat, fee_msat, timestamp = self.get_payment_value(info, plist)
else:
amount_msat = 0
label = 'Reverse swap' if swap.is_reverse else 'Forward swap'
delta = current_height - swap.locktime
if not swap.is_redeemed and swap.spending_txid is None and delta < 0:
label += f' (refundable in {-delta} blocks)' # fixme: only if unspent
out[txid] = {
'txid': txid,
'group_id': txid,
'amount_msat': 0,
#'amount_msat': amount_msat, # must not be added
'type': 'swap',
'label': self.wallet.get_label_for_txid(txid) or label,
}
return out
def get_history(self):
out = list(self.get_lightning_history().values()) + list(self.get_onchain_history().values())
# sort by timestamp
out.sort(key=lambda x: (x.get('timestamp') or float("inf")))
balance_msat = 0
for item in out:
balance_msat += item['amount_msat']
item['balance_msat'] = balance_msat
return out
def channel_peers(self) -> List[bytes]:
node_ids = [chan.node_id for chan in self.channels.values() if not chan.is_closed()]
return node_ids
def channels_for_peer(self, node_id):
assert type(node_id) is bytes
return {chan_id: chan for (chan_id, chan) in self.channels.items()
if chan.node_id == node_id}
def channel_state_changed(self, chan: Channel):
if type(chan) is Channel:
self.save_channel(chan)
util.trigger_callback('channel', self.wallet, chan)
def save_channel(self, chan: Channel):
assert type(chan) is Channel
if chan.config[REMOTE].next_per_commitment_point == chan.config[REMOTE].current_per_commitment_point:
raise Exception("Tried to save channel with next_point == current_point, this should not happen")
self.wallet.save_db()
util.trigger_callback('channel', self.wallet, chan)
def channel_by_txo(self, txo: str) -> Optional[AbstractChannel]:
for chan in self.channels.values():
if chan.funding_outpoint.to_str() == txo:
return chan
for chan in self.channel_backups.values():
if chan.funding_outpoint.to_str() == txo:
return chan
async def on_channel_update(self, chan: Channel):
if type(chan) is ChannelBackup:
util.trigger_callback('channel', self.wallet, chan)
return
if chan.get_state() == ChannelState.OPEN and chan.should_be_closed_due_to_expiring_htlcs(self.network.get_local_height()):
self.logger.info(f"force-closing due to expiring htlcs")
await self.schedule_force_closing(chan.channel_id)
elif chan.get_state() == ChannelState.FUNDED:
peer = self._peers.get(chan.node_id)
if peer and peer.is_initialized():
peer.send_funding_locked(chan)
elif chan.get_state() == ChannelState.OPEN:
peer = self._peers.get(chan.node_id)
if peer:
await peer.maybe_update_fee(chan)
conf = self.lnwatcher.get_tx_height(chan.funding_outpoint.txid).conf
peer.on_network_update(chan, conf)
elif chan.get_state() == ChannelState.FORCE_CLOSING:
force_close_tx = chan.force_close_tx()
txid = force_close_tx.txid()
height = self.lnwatcher.get_tx_height(txid).height
if height == TX_HEIGHT_LOCAL:
self.logger.info('REBROADCASTING CLOSING TX')
await self.network.try_broadcasting(force_close_tx, 'force-close')
@log_exceptions
async def _open_channel_coroutine(
self, *,
connect_str: str,
funding_tx: PartialTransaction,
funding_sat: int,
push_sat: int,
password: Optional[str]) -> Tuple[Channel, PartialTransaction]:
peer = await self.add_peer(connect_str)
coro = peer.channel_establishment_flow(
funding_tx=funding_tx,
funding_sat=funding_sat,
push_msat=push_sat * 1000,
temp_channel_id=os.urandom(32))
chan, funding_tx = await asyncio.wait_for(coro, LN_P2P_NETWORK_TIMEOUT)
util.trigger_callback('channels_updated', self.wallet)
self.wallet.add_transaction(funding_tx) # save tx as local into the wallet
self.wallet.sign_transaction(funding_tx, password)
self.wallet.set_label(funding_tx.txid(), _('Open channel'))
if funding_tx.is_complete():
await self.network.try_broadcasting(funding_tx, 'open_channel')
return chan, funding_tx
def add_channel(self, chan: Channel):
with self.lock:
self._channels[chan.channel_id] = chan
self.lnwatcher.add_channel(chan.funding_outpoint.to_str(), chan.get_funding_address())
def add_new_channel(self, chan: Channel):
self.add_channel(chan)
channels_db = self.db.get_dict('channels')
channels_db[chan.channel_id.hex()] = chan.storage
for addr in chan.get_wallet_addresses_channel_might_want_reserved():
self.wallet.set_reserved_state_of_address(addr, reserved=True)
try:
self.save_channel(chan)
backup_dir = self.config.get_backup_dir()
if backup_dir is not None:
self.wallet.save_backup(backup_dir)
except:
chan.set_state(ChannelState.REDEEMED)
self.remove_channel(chan.channel_id)
raise
def cb_data(self, node_id):
return CB_MAGIC_BYTES + node_id[0:16]
def decrypt_cb_data(self, encrypted_data, funding_address):
funding_scripthash = bytes.fromhex(address_to_scripthash(funding_address))
nonce = funding_scripthash[0:12]
return chacha20_decrypt(key=self.backup_key, data=encrypted_data, nonce=nonce)
def encrypt_cb_data(self, data, funding_address):
funding_scripthash = bytes.fromhex(address_to_scripthash(funding_address))
nonce = funding_scripthash[0:12]
return chacha20_encrypt(key=self.backup_key, data=data, nonce=nonce)
def mktx_for_open_channel(
self, *,
coins: Sequence[PartialTxInput],
funding_sat: int,
node_id: bytes,
fee_est=None) -> PartialTransaction:
outputs = [PartialTxOutput.from_address_and_value(ln_dummy_address(), funding_sat)]
if self.has_recoverable_channels():
dummy_scriptpubkey = make_op_return(self.cb_data(node_id))
outputs.append(PartialTxOutput(scriptpubkey=dummy_scriptpubkey, value=0))
tx = self.wallet.make_unsigned_transaction(
coins=coins,
outputs=outputs,
fee=fee_est)
tx.set_rbf(False)
return tx
def open_channel(self, *, connect_str: str, funding_tx: PartialTransaction,
funding_sat: int, push_amt_sat: int, password: str = None) -> Tuple[Channel, PartialTransaction]:
if funding_sat > LN_MAX_FUNDING_SAT:
raise Exception(_("Requested channel capacity is over protocol allowed maximum."))
coro = self._open_channel_coroutine(
connect_str=connect_str, funding_tx=funding_tx, funding_sat=funding_sat,
push_sat=push_amt_sat, password=password)
fut = asyncio.run_coroutine_threadsafe(coro, self.network.asyncio_loop)
try:
chan, funding_tx = fut.result()
except concurrent.futures.TimeoutError:
raise Exception(_("open_channel timed out"))
return chan, funding_tx
def get_channel_by_short_id(self, short_channel_id: bytes) -> Optional[Channel]:
for chan in self.channels.values():
if chan.short_channel_id == short_channel_id:
return chan
@log_exceptions
async def pay_invoice(
self, invoice: str, *,
amount_msat: int = None,
attempts: int = 1,
full_path: LNPaymentPath = None) -> Tuple[bool, List[HtlcLog]]:
lnaddr = self._check_invoice(invoice, amount_msat=amount_msat)
min_cltv_expiry = lnaddr.get_min_final_cltv_expiry()
payment_hash = lnaddr.paymenthash
key = payment_hash.hex()
payment_secret = lnaddr.payment_secret
invoice_pubkey = lnaddr.pubkey.serialize()
invoice_features = lnaddr.get_features()
r_tags = lnaddr.get_routing_info('r')
amount_to_pay = lnaddr.get_amount_msat()
status = self.get_payment_status(payment_hash)
if status == PR_PAID:
raise PaymentFailure(_("This invoice has been paid already"))
if status == PR_INFLIGHT:
raise PaymentFailure(_("A payment was already initiated for this invoice"))
if payment_hash in self.get_payments(status='inflight'):
raise PaymentFailure(_("A previous attempt to pay this invoice did not clear"))
info = PaymentInfo(payment_hash, amount_to_pay, SENT, PR_UNPAID)
self.save_payment_info(info)
self.wallet.set_label(key, lnaddr.get_description())
self.set_invoice_status(key, PR_INFLIGHT)
try:
await self.pay_to_node(
node_pubkey=invoice_pubkey,
payment_hash=payment_hash,
payment_secret=payment_secret,
amount_to_pay=amount_to_pay,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
attempts=attempts,
full_path=full_path)
success = True
except PaymentFailure as e:
self.logger.info(f'payment failure: {e!r}')
success = False
reason = str(e)
if success:
self.set_invoice_status(key, PR_PAID)
util.trigger_callback('payment_succeeded', self.wallet, key)
else:
self.set_invoice_status(key, PR_UNPAID)
util.trigger_callback('payment_failed', self.wallet, key, reason)
log = self.logs[key]
return success, log
async def pay_to_node(
self, *,
node_pubkey: bytes,
payment_hash: bytes,
payment_secret: Optional[bytes],
amount_to_pay: int, # in msat
min_cltv_expiry: int,
r_tags,
invoice_features: int,
attempts: int = 1,
full_path: LNPaymentPath = None,
fwd_trampoline_onion=None,
fwd_trampoline_fee=None,
fwd_trampoline_cltv_delta=None) -> None:
if fwd_trampoline_onion:
# todo: compare to the fee of the actual route we found
if fwd_trampoline_fee < 1000:
raise OnionRoutingFailure(code=OnionFailureCode.TRAMPOLINE_FEE_INSUFFICIENT, data=b'')
if fwd_trampoline_cltv_delta < 576:
raise OnionRoutingFailure(code=OnionFailureCode.TRAMPOLINE_EXPIRY_TOO_SOON, data=b'')
self.logs[payment_hash.hex()] = log = []
# when encountering trampoline forwarding difficulties in the legacy case, we
# sometimes need to fall back to a single trampoline forwarder, at the expense
# of privacy
use_two_trampolines = True
trampoline_fee_level = self.INITIAL_TRAMPOLINE_FEE_LEVEL
amount_inflight = 0 # what we sent in htlcs (that receiver gets, without fees)
while True:
amount_to_send = amount_to_pay - amount_inflight
if amount_to_send > 0:
# 1. create a set of routes for remaining amount.
# note: path-finding runs in a separate thread so that we don't block the asyncio loop
# graph updates might occur during the computation
routes = self.create_routes_for_payment(
amount_msat=amount_to_send,
final_total_msat=amount_to_pay,
invoice_pubkey=node_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
full_path=full_path,
payment_hash=payment_hash,
payment_secret=payment_secret,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines,
fwd_trampoline_onion=fwd_trampoline_onion
)
# 2. send htlcs
async for route, amount_msat, total_msat, amount_receiver_msat, cltv_delta, bucket_payment_secret, trampoline_onion in routes:
amount_inflight += amount_receiver_msat
if amount_inflight > amount_to_pay: # safety belts
raise Exception(f"amount_inflight={amount_inflight} > amount_to_pay={amount_to_pay}")
await self.pay_to_route(
route=route,
amount_msat=amount_msat,
total_msat=total_msat,
amount_receiver_msat=amount_receiver_msat,
payment_hash=payment_hash,
payment_secret=bucket_payment_secret,
min_cltv_expiry=cltv_delta,
trampoline_onion=trampoline_onion,
trampoline_fee_level=trampoline_fee_level)
util.trigger_callback('invoice_status', self.wallet, payment_hash.hex())
# 3. await a queue
self.logger.info(f"amount inflight {amount_inflight}")
htlc_log = await self.sent_htlcs[payment_hash].get()
amount_inflight -= htlc_log.amount_msat
if amount_inflight < 0:
raise Exception(f"amount_inflight={amount_inflight} < 0")
log.append(htlc_log)
if htlc_log.success:
if self.network.path_finder:
# TODO: report every route to liquidity hints for mpp
# in the case of success, we report channels of the
# route as being able to send the same amount in the future,
# as we assume to not know the capacity
self.network.path_finder.update_liquidity_hints(htlc_log.route, htlc_log.amount_msat)
# remove inflight htlcs from liquidity hints
self.network.path_finder.update_inflight_htlcs(htlc_log.route, add_htlcs=False)
return
# htlc failed
if len(log) >= attempts:
raise PaymentFailure('Giving up after %d attempts'%len(log))
# if we get a tmp channel failure, it might work to split the amount and try more routes
# if we get a channel update, we might retry the same route and amount
route = htlc_log.route
sender_idx = htlc_log.sender_idx
erring_node_id = route[sender_idx].node_id
failure_msg = htlc_log.failure_msg
code, data = failure_msg.code, failure_msg.data
self.logger.info(f"UPDATE_FAIL_HTLC. code={repr(code)}. "
f"decoded_data={failure_msg.decode_data()}. data={data.hex()!r}")
self.logger.info(f"error reported by {bh2u(erring_node_id)}")
if code == OnionFailureCode.MPP_TIMEOUT:
raise PaymentFailure(failure_msg.code_name())
# trampoline
if not self.channel_db:
# FIXME The trampoline nodes in the path are chosen randomly.
# Some of the errors might depend on how we have chosen them.
# Having more attempts is currently useful in part because of the randomness,
# instead we should give feedback to create_routes_for_payment.
if code in (OnionFailureCode.TRAMPOLINE_FEE_INSUFFICIENT,
OnionFailureCode.TRAMPOLINE_EXPIRY_TOO_SOON):
# TODO: parse the node policy here (not returned by eclair yet)
# TODO: erring node is always the first trampoline even if second
# trampoline demands more fees, we can't influence this
if htlc_log.trampoline_fee_level == trampoline_fee_level:
trampoline_fee_level += 1
self.logger.info(f'raising trampoline fee level {trampoline_fee_level}')
else:
self.logger.info(f'NOT raising trampoline fee level, already at {trampoline_fee_level}')
continue
elif use_two_trampolines:
use_two_trampolines = False
elif code in (OnionFailureCode.UNKNOWN_NEXT_PEER,
OnionFailureCode.TEMPORARY_NODE_FAILURE):
continue
else:
raise PaymentFailure(failure_msg.code_name())
else:
self.handle_error_code_from_failed_htlc(
route=route, sender_idx=sender_idx, failure_msg=failure_msg, amount=htlc_log.amount_msat)
async def pay_to_route(
self, *,
route: LNPaymentRoute,
amount_msat: int,
total_msat: int,
amount_receiver_msat:int,
payment_hash: bytes,
payment_secret: Optional[bytes],
min_cltv_expiry: int,
trampoline_onion: bytes = None,
trampoline_fee_level: int) -> None:
# send a single htlc
short_channel_id = route[0].short_channel_id
chan = self.get_channel_by_short_id(short_channel_id)
peer = self._peers.get(route[0].node_id)
if not peer:
raise PaymentFailure('Dropped peer')
await peer.initialized
htlc = peer.pay(
route=route,
chan=chan,
amount_msat=amount_msat,
total_msat=total_msat,
payment_hash=payment_hash,
min_final_cltv_expiry=min_cltv_expiry,
payment_secret=payment_secret,
trampoline_onion=trampoline_onion)
key = (payment_hash, short_channel_id, htlc.htlc_id)
self.sent_htlcs_info[key] = route, payment_secret, amount_msat, total_msat, amount_receiver_msat, trampoline_fee_level
# if we sent MPP to a trampoline, add item to sent_buckets
if not self.channel_db and amount_msat != total_msat:
if payment_secret not in self.sent_buckets:
self.sent_buckets[payment_secret] = (0, 0)
amount_sent, amount_failed = self.sent_buckets[payment_secret]
amount_sent += amount_receiver_msat
self.sent_buckets[payment_secret] = amount_sent, amount_failed
if self.network.path_finder:
# add inflight htlcs to liquidity hints
self.network.path_finder.update_inflight_htlcs(route, add_htlcs=True)
util.trigger_callback('htlc_added', chan, htlc, SENT)
def handle_error_code_from_failed_htlc(
self,
*,
route: LNPaymentRoute,
sender_idx: int,
failure_msg: OnionRoutingFailure,
amount: int) -> None:
assert self.channel_db # cannot be in trampoline mode
assert self.network.path_finder
# remove inflight htlcs from liquidity hints
self.network.path_finder.update_inflight_htlcs(route, add_htlcs=False)
code, data = failure_msg.code, failure_msg.data
# TODO can we use lnmsg.OnionWireSerializer here?
# TODO update onion_wire.csv
# handle some specific error codes
failure_codes = {
OnionFailureCode.TEMPORARY_CHANNEL_FAILURE: 0,
OnionFailureCode.AMOUNT_BELOW_MINIMUM: 8,
OnionFailureCode.FEE_INSUFFICIENT: 8,
OnionFailureCode.INCORRECT_CLTV_EXPIRY: 4,
OnionFailureCode.EXPIRY_TOO_SOON: 0,
OnionFailureCode.CHANNEL_DISABLED: 2,
}
# determine a fallback channel to blacklist if we don't get the erring
# channel via the payload
if sender_idx is None:
raise PaymentFailure(failure_msg.code_name())
try:
fallback_channel = route[sender_idx + 1].short_channel_id
except IndexError:
raise PaymentFailure(f'payment destination reported error: {failure_msg.code_name()}') from None
# TODO: handle unknown next peer?
# handle failure codes that include a channel update
if code in failure_codes:
offset = failure_codes[code]
channel_update_len = int.from_bytes(data[offset:offset+2], byteorder="big")
channel_update_as_received = data[offset+2: offset+2+channel_update_len]
payload = self._decode_channel_update_msg(channel_update_as_received)
if payload is None:
self.logger.info(f'could not decode channel_update for failed htlc: '
f'{channel_update_as_received.hex()}')
self.network.path_finder.liquidity_hints.add_to_blacklist(fallback_channel)
else:
# apply the channel update or get blacklisted
blacklist, update = self._handle_chanupd_from_failed_htlc(
payload, route=route, sender_idx=sender_idx)
# we interpret a temporary channel failure as a liquidity issue
# in the channel and update our liquidity hints accordingly
if code == OnionFailureCode.TEMPORARY_CHANNEL_FAILURE:
self.network.path_finder.update_liquidity_hints(
route,
amount,
failing_channel=ShortChannelID(payload['short_channel_id']))
elif blacklist:
self.network.path_finder.liquidity_hints.add_to_blacklist(
payload['short_channel_id'])
# if we can't decide on some action, we are stuck
if not (blacklist or update):
raise PaymentFailure(failure_msg.code_name())
# for errors that do not include a channel update
else:
self.network.path_finder.liquidity_hints.add_to_blacklist(fallback_channel)
def _handle_chanupd_from_failed_htlc(self, payload, *, route, sender_idx) -> Tuple[bool, bool]:
blacklist = False
update = False
try:
r = self.channel_db.add_channel_update(payload, verify=True)
except InvalidGossipMsg:
return True, False # blacklist
short_channel_id = ShortChannelID(payload['short_channel_id'])
if r == UpdateStatus.GOOD:
self.logger.info(f"applied channel update to {short_channel_id}")
# TODO: add test for this
# FIXME: this does not work for our own unannounced channels.
for chan in self.channels.values():
if chan.short_channel_id == short_channel_id:
chan.set_remote_update(payload)
update = True
elif r == UpdateStatus.ORPHANED:
# maybe it is a private channel (and data in invoice was outdated)
self.logger.info(f"Could not find {short_channel_id}. maybe update is for private channel?")
start_node_id = route[sender_idx].node_id
update = self.channel_db.add_channel_update_for_private_channel(payload, start_node_id)
blacklist = not update
elif r == UpdateStatus.EXPIRED:
blacklist = True
elif r == UpdateStatus.DEPRECATED:
self.logger.info(f'channel update is not more recent.')
blacklist = True
elif r == UpdateStatus.UNCHANGED:
blacklist = True
return blacklist, update
@classmethod
def _decode_channel_update_msg(cls, chan_upd_msg: bytes) -> Optional[Dict[str, Any]]:
channel_update_as_received = chan_upd_msg
channel_update_typed = (258).to_bytes(length=2, byteorder="big") + channel_update_as_received
# note: some nodes put channel updates in error msgs with the leading msg_type already there.
# we try decoding both ways here.
try:
message_type, payload = decode_msg(channel_update_typed)
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_typed
return payload
except: # FIXME: too broad
try:
message_type, payload = decode_msg(channel_update_as_received)
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_as_received
return payload
except:
return None
@staticmethod
def _check_invoice(invoice: str, *, amount_msat: int = None) -> LnAddr:
addr = lndecode(invoice)
if addr.is_expired():
raise InvoiceError(_("This invoice has expired"))
if amount_msat: # replace amt in invoice. main usecase is paying zero amt invoices
existing_amt_msat = addr.get_amount_msat()
if existing_amt_msat and amount_msat < existing_amt_msat:
raise Exception("cannot pay lower amt than what is originally in LN invoice")
addr.amount = Decimal(amount_msat) / COIN / 1000
if addr.amount is None:
raise InvoiceError(_("Missing amount"))
if addr.get_min_final_cltv_expiry() > lnutil.NBLOCK_CLTV_EXPIRY_TOO_FAR_INTO_FUTURE:
raise InvoiceError("{}\n{}".format(
_("Invoice wants us to risk locking funds for unreasonably long."),
f"min_final_cltv_expiry: {addr.get_min_final_cltv_expiry()}"))
return addr
def is_trampoline_peer(self, node_id: bytes) -> bool:
# until trampoline is advertised in lnfeatures, check against hardcoded list
if is_hardcoded_trampoline(node_id):
return True
peer = self._peers.get(node_id)
if peer and peer.their_features.supports(LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT):
return True
return False
def suggest_peer(self) -> Optional[bytes]:
if self.channel_db:
return self.lnrater.suggest_peer()
else:
return random.choice(list(hardcoded_trampoline_nodes().values())).pubkey
async def create_routes_for_payment(
self, *,
amount_msat: int, # part of payment amount we want routes for now
final_total_msat: int, # total payment amount final receiver will get
invoice_pubkey,
min_cltv_expiry,
r_tags,
invoice_features: int,
payment_hash,
payment_secret,
trampoline_fee_level: int,
use_two_trampolines: bool,
fwd_trampoline_onion=None,
full_path: LNPaymentPath = None) -> AsyncGenerator[Tuple[LNPaymentRoute, int], None]:
"""Creates multiple routes for splitting a payment over the available
private channels.
We first try to conduct the payment over a single channel. If that fails
and mpp is supported by the receiver, we will split the payment."""
invoice_features = LnFeatures(invoice_features)
trampoline_features = LnFeatures.VAR_ONION_OPT
local_height = self.network.get_local_height()
my_active_channels = [chan for chan in self.channels.values() if
chan.is_active() and not chan.is_frozen_for_sending()]
try:
self.logger.info("trying single-part payment")
# try to send over a single channel
if not self.channel_db:
for chan in my_active_channels:
if not self.is_trampoline_peer(chan.node_id):
continue
if chan.node_id == invoice_pubkey:
trampoline_onion = None
trampoline_payment_secret = payment_secret
trampoline_total_msat = final_total_msat
amount_with_fees = amount_msat
cltv_delta = min_cltv_expiry
else:
trampoline_onion, amount_with_fees, cltv_delta = create_trampoline_route_and_onion(
amount_msat=amount_msat,
total_msat=final_total_msat,
min_cltv_expiry=min_cltv_expiry,
my_pubkey=self.node_keypair.pubkey,
invoice_pubkey=invoice_pubkey,
invoice_features=invoice_features,
node_id=chan.node_id,
r_tags=r_tags,
payment_hash=payment_hash,
payment_secret=payment_secret,
local_height=local_height,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines)
trampoline_payment_secret = os.urandom(32)
trampoline_total_msat = amount_with_fees
if chan.available_to_spend(LOCAL, strict=True) < amount_with_fees:
continue
route = [
RouteEdge(
start_node=self.node_keypair.pubkey,
end_node=chan.node_id,
short_channel_id=chan.short_channel_id,
fee_base_msat=0,
fee_proportional_millionths=0,
cltv_expiry_delta=0,
node_features=trampoline_features)
]
yield route, amount_with_fees, trampoline_total_msat, amount_msat, cltv_delta, trampoline_payment_secret, trampoline_onion
break
else:
raise NoPathFound()
else: # local single-part route computation
route = await run_in_thread(
partial(
self.create_route_for_payment,
amount_msat=amount_msat,
invoice_pubkey=invoice_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
my_sending_channels=my_active_channels,
full_path=full_path
)
)
yield route, amount_msat, final_total_msat, amount_msat, min_cltv_expiry, payment_secret, fwd_trampoline_onion
except NoPathFound: # fall back to payment splitting
self.logger.info("no path found, trying multi-part payment")
if not invoice_features.supports(LnFeatures.BASIC_MPP_OPT):
raise
channels_with_funds = {(chan.channel_id, chan.node_id): int(chan.available_to_spend(HTLCOwner.LOCAL))
for chan in my_active_channels}
self.logger.info(f"channels_with_funds: {channels_with_funds}")
if not self.channel_db:
# in the case of a legacy payment, we don't allow splitting via different
# trampoline nodes, as currently no forwarder supports this
use_single_node, _ = is_legacy_relay(invoice_features, r_tags)
split_configurations = suggest_splits(
amount_msat,
channels_with_funds,
exclude_multinode_payments=use_single_node,
exclude_single_part_payments=True,
# we don't split within a channel when sending to a trampoline node,
# the trampoline node will split for us
exclude_single_channel_splits=True,
)
self.logger.info(f'suggest_split {amount_msat} returned {len(split_configurations)} configurations')
for sc in split_configurations:
try:
self.logger.info(f"trying split configuration: {sc.config.values()} rating: {sc.rating}")
per_trampoline_channel_amounts = defaultdict(list)
# categorize by trampoline nodes for trampolin mpp construction
for (chan_id, _), part_amounts_msat in sc.config.items():
chan = self.channels[chan_id]
for part_amount_msat in part_amounts_msat:
per_trampoline_channel_amounts[chan.node_id].append((chan_id, part_amount_msat))
# for each trampoline forwarder, construct mpp trampoline
routes = []
for trampoline_node_id, trampoline_parts in per_trampoline_channel_amounts.items():
per_trampoline_amount = sum([x[1] for x in trampoline_parts])
trampoline_onion, per_trampoline_amount_with_fees, per_trampoline_cltv_delta = create_trampoline_route_and_onion(
amount_msat=per_trampoline_amount,
total_msat=final_total_msat,
min_cltv_expiry=min_cltv_expiry,
my_pubkey=self.node_keypair.pubkey,
invoice_pubkey=invoice_pubkey,
invoice_features=invoice_features,
node_id=trampoline_node_id,
r_tags=r_tags,
payment_hash=payment_hash,
payment_secret=payment_secret,
local_height=local_height,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines)
# node_features is only used to determine is_tlv
per_trampoline_secret = os.urandom(32)
per_trampoline_fees = per_trampoline_amount_with_fees - per_trampoline_amount
self.logger.info(f'per trampoline fees: {per_trampoline_fees}')
for chan_id, part_amount_msat in trampoline_parts:
chan = self.channels[chan_id]
margin = chan.available_to_spend(LOCAL, strict=True) - part_amount_msat
delta_fee = min(per_trampoline_fees, margin)
# TODO: distribute trampoline fee over several channels?
part_amount_msat_with_fees = part_amount_msat + delta_fee
per_trampoline_fees -= delta_fee
route = [
RouteEdge(
start_node=self.node_keypair.pubkey,
end_node=trampoline_node_id,
short_channel_id=chan.short_channel_id,
fee_base_msat=0,
fee_proportional_millionths=0,
cltv_expiry_delta=0,
node_features=trampoline_features)
]
self.logger.info(f'adding route {part_amount_msat} {delta_fee} {margin}')
routes.append((route, part_amount_msat_with_fees, per_trampoline_amount_with_fees, part_amount_msat, per_trampoline_cltv_delta, per_trampoline_secret, trampoline_onion))
if per_trampoline_fees != 0:
self.logger.info('not enough margin to pay trampoline fee')
raise NoPathFound()
for route in routes:
yield route
return
except NoPathFound:
continue
else:
split_configurations = suggest_splits(
amount_msat,
channels_with_funds,
exclude_single_part_payments=True,
)
# We atomically loop through a split configuration. If there was
# a failure to find a path for a single part, we give back control
# after exhausting the split configuration.
yielded_from_split_configuration = False
self.logger.info(f'suggest_split {amount_msat} returned {len(split_configurations)} configurations')
for sc in split_configurations:
self.logger.info(f"trying split configuration: {list(sc.config.values())} rating: {sc.rating}")
for (chan_id, _), part_amounts_msat in sc.config.items():
for part_amount_msat in part_amounts_msat:
channel = self.channels[chan_id]
try:
route = await run_in_thread(
partial(
self.create_route_for_payment,
amount_msat=part_amount_msat,
invoice_pubkey=invoice_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
my_sending_channels=[channel],
full_path=None
)
)
yield route, part_amount_msat, final_total_msat, part_amount_msat, min_cltv_expiry, payment_secret, fwd_trampoline_onion
yielded_from_split_configuration = True
except NoPathFound:
continue
if yielded_from_split_configuration:
return
raise NoPathFound()
@profiler
def create_route_for_payment(
self, *,
amount_msat: int,
invoice_pubkey: bytes,
min_cltv_expiry: int,
r_tags,
invoice_features: int,
my_sending_channels: List[Channel],
full_path: Optional[LNPaymentPath]) -> LNPaymentRoute:
my_sending_channels = {chan.short_channel_id: chan for chan in my_sending_channels
if chan.short_channel_id is not None}
# Collect all private edges from route hints.
# Note: if some route hints are multiple edges long, and these paths cross each other,
# we allow our path finding to cross the paths; i.e. the route hints are not isolated.
private_route_edges = {} # type: Dict[ShortChannelID, RouteEdge]
for private_path in r_tags:
# we need to shift the node pubkey by one towards the destination:
private_path_nodes = [edge[0] for edge in private_path][1:] + [invoice_pubkey]
private_path_rest = [edge[1:] for edge in private_path]
start_node = private_path[0][0]
for end_node, edge_rest in zip(private_path_nodes, private_path_rest):
short_channel_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta = edge_rest
short_channel_id = ShortChannelID(short_channel_id)
# if we have a routing policy for this edge in the db, that takes precedence,
# as it is likely from a previous failure
channel_policy = self.channel_db.get_policy_for_node(
short_channel_id=short_channel_id,
node_id=start_node,
my_channels=my_sending_channels)
if channel_policy:
fee_base_msat = channel_policy.fee_base_msat
fee_proportional_millionths = channel_policy.fee_proportional_millionths
cltv_expiry_delta = channel_policy.cltv_expiry_delta
node_info = self.channel_db.get_node_info_for_node_id(node_id=end_node)
route_edge = RouteEdge(
start_node=start_node,
end_node=end_node,
short_channel_id=short_channel_id,
fee_base_msat=fee_base_msat,
fee_proportional_millionths=fee_proportional_millionths,
cltv_expiry_delta=cltv_expiry_delta,
node_features=node_info.features if node_info else 0)
private_route_edges[route_edge.short_channel_id] = route_edge
start_node = end_node
# now find a route, end to end: between us and the recipient
try:
route = self.network.path_finder.find_route(
nodeA=self.node_keypair.pubkey,
nodeB=invoice_pubkey,
invoice_amount_msat=amount_msat,
path=full_path,
my_sending_channels=my_sending_channels,
private_route_edges=private_route_edges)
except NoChannelPolicy as e:
raise NoPathFound() from e
if not route:
raise NoPathFound()
# test sanity
if not is_route_sane_to_use(route, amount_msat, min_cltv_expiry):
self.logger.info(f"rejecting insane route {route}")
raise NoPathFound()
assert len(route) > 0
if route[-1].end_node != invoice_pubkey:
raise LNPathInconsistent("last node_id != invoice pubkey")
# add features from invoice
route[-1].node_features |= invoice_features
return route
def add_request(self, amount_sat, message, expiry) -> str:
coro = self._add_request_coro(amount_sat, message, expiry)
fut = asyncio.run_coroutine_threadsafe(coro, self.network.asyncio_loop)
try:
return fut.result(timeout=5)
except concurrent.futures.TimeoutError:
raise Exception(_("add invoice timed out"))
@log_exceptions
async def create_invoice(
self, *,
amount_msat: Optional[int],
message: str,
expiry: int,
write_to_disk: bool = True,
) -> Tuple[LnAddr, str]:
timestamp = int(time.time())
routing_hints = await self._calc_routing_hints_for_invoice(amount_msat)
if not routing_hints:
self.logger.info(
"Warning. No routing hints added to invoice. "
"Other clients will likely not be able to send to us.")
# if not all hints are trampoline, do not create trampoline invoice
invoice_features = self.features.for_invoice()
trampoline_hints = []
for r in routing_hints:
node_id, short_channel_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta = r[1][0]
if len(r[1])== 1 and self.is_trampoline_peer(node_id):
trampoline_hints.append(('t', (node_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta)))
payment_preimage = os.urandom(32)
payment_hash = sha256(payment_preimage)
info = PaymentInfo(payment_hash, amount_msat, RECEIVED, PR_UNPAID)
amount_btc = amount_msat/Decimal(COIN*1000) if amount_msat else None
if expiry == 0:
expiry = LN_EXPIRY_NEVER
lnaddr = LnAddr(
paymenthash=payment_hash,
amount=amount_btc,
tags=[
('d', message),
('c', MIN_FINAL_CLTV_EXPIRY_FOR_INVOICE),
('x', expiry),
('9', invoice_features)]
+ routing_hints
+ trampoline_hints,
date=timestamp,
payment_secret=derive_payment_secret_from_payment_preimage(payment_preimage))
invoice = lnencode(lnaddr, self.node_keypair.privkey)
self.save_preimage(payment_hash, payment_preimage, write_to_disk=False)
self.save_payment_info(info, write_to_disk=False)
if write_to_disk:
self.wallet.save_db()
return lnaddr, invoice
async def _add_request_coro(self, amount_sat: Optional[int], message, expiry: int) -> str:
amount_msat = amount_sat * 1000 if amount_sat is not None else None
lnaddr, invoice = await self.create_invoice(
amount_msat=amount_msat,
message=message,
expiry=expiry,
write_to_disk=False,
)
key = bh2u(lnaddr.paymenthash)
req = LNInvoice.from_bech32(invoice)
self.wallet.add_payment_request(req, write_to_disk=False)
self.wallet.set_label(key, message)
self.wallet.save_db()
return key
def save_preimage(self, payment_hash: bytes, preimage: bytes, *, write_to_disk: bool = True):
assert sha256(preimage) == payment_hash
self.preimages[bh2u(payment_hash)] = bh2u(preimage)
if write_to_disk:
self.wallet.save_db()
def get_preimage(self, payment_hash: bytes) -> Optional[bytes]:
r = self.preimages.get(bh2u(payment_hash))
return bfh(r) if r else None
def get_payment_info(self, payment_hash: bytes) -> Optional[PaymentInfo]:
"""returns None if payment_hash is a payment we are forwarding"""
key = payment_hash.hex()
with self.lock:
if key in self.payments:
amount_msat, direction, status = self.payments[key]
return PaymentInfo(payment_hash, amount_msat, direction, status)
def save_payment_info(self, info: PaymentInfo, *, write_to_disk: bool = True) -> None:
key = info.payment_hash.hex()
assert info.status in SAVED_PR_STATUS
with self.lock:
self.payments[key] = info.amount_msat, info.direction, info.status
if write_to_disk:
self.wallet.save_db()
def check_received_mpp_htlc(self, payment_secret, short_channel_id, htlc: UpdateAddHtlc, expected_msat: int) -> Optional[bool]:
""" return MPP status: True (accepted), False (expired) or None """
payment_hash = htlc.payment_hash
is_expired, is_accepted, htlc_set = self.received_mpp_htlcs.get(payment_secret, (False, False, set()))
if self.get_payment_status(payment_hash) == PR_PAID:
# payment_status is persisted
is_accepted = True
is_expired = False
key = (short_channel_id, htlc)
if key not in htlc_set:
htlc_set.add(key)
if not is_accepted and not is_expired:
total = sum([_htlc.amount_msat for scid, _htlc in htlc_set])
first_timestamp = min([_htlc.timestamp for scid, _htlc in htlc_set])
if self.stopping_soon:
is_expired = True # try to time out pending HTLCs before shutting down
elif time.time() - first_timestamp > self.MPP_EXPIRY:
is_expired = True
elif total == expected_msat:
is_accepted = True
if is_accepted or is_expired:
htlc_set.remove(key)
if len(htlc_set) > 0:
self.received_mpp_htlcs[payment_secret] = is_expired, is_accepted, htlc_set
elif payment_secret in self.received_mpp_htlcs:
self.received_mpp_htlcs.pop(payment_secret)
return True if is_accepted else (False if is_expired else None)
def get_payment_status(self, payment_hash: bytes) -> int:
info = self.get_payment_info(payment_hash)
return info.status if info else PR_UNPAID
def get_invoice_status(self, invoice: LNInvoice) -> int:
key = invoice.rhash
log = self.logs[key]
if key in self.inflight_payments:
return PR_INFLIGHT
# status may be PR_FAILED
status = self.get_payment_status(bfh(key))
if status == PR_UNPAID and log:
status = PR_FAILED
return status
def set_invoice_status(self, key: str, status: int) -> None:
if status == PR_INFLIGHT:
self.inflight_payments.add(key)
elif key in self.inflight_payments:
self.inflight_payments.remove(key)
if status in SAVED_PR_STATUS:
self.set_payment_status(bfh(key), status)
util.trigger_callback('invoice_status', self.wallet, key)
def set_request_status(self, payment_hash: bytes, status: int) -> None:
if self.get_payment_status(payment_hash) != status:
self.set_payment_status(payment_hash, status)
util.trigger_callback('request_status', self.wallet, payment_hash.hex(), status)
def set_payment_status(self, payment_hash: bytes, status: int) -> None:
info = self.get_payment_info(payment_hash)
if info is None:
# if we are forwarding
return
info = info._replace(status=status)
self.save_payment_info(info)
def _on_maybe_forwarded_htlc_resolved(self, chan: Channel, htlc_id: int) -> None:
"""Called when an HTLC we offered on chan gets irrevocably fulfilled or failed.
If we find this was a forwarded HTLC, the upstream peer is notified.
"""
fw_info = chan.short_channel_id.hex(), htlc_id
upstream_peer_pubkey = self.downstream_htlc_to_upstream_peer_map.get(fw_info)
if not upstream_peer_pubkey:
return
upstream_peer = self.peers.get(upstream_peer_pubkey)
if not upstream_peer:
return
upstream_peer.downstream_htlc_resolved_event.set()
upstream_peer.downstream_htlc_resolved_event.clear()
def htlc_fulfilled(self, chan: Channel, payment_hash: bytes, htlc_id: int):
util.trigger_callback('htlc_fulfilled', payment_hash, chan, htlc_id)
self._on_maybe_forwarded_htlc_resolved(chan=chan, htlc_id=htlc_id)
q = self.sent_htlcs.get(payment_hash)
if q:
route, payment_secret, amount_msat, bucket_msat, amount_receiver_msat, trampoline_fee_level = self.sent_htlcs_info[(payment_hash, chan.short_channel_id, htlc_id)]
htlc_log = HtlcLog(
success=True,
route=route,
amount_msat=amount_receiver_msat,
trampoline_fee_level=trampoline_fee_level)
q.put_nowait(htlc_log)
else:
key = payment_hash.hex()
self.set_invoice_status(key, PR_PAID)
util.trigger_callback('payment_succeeded', self.wallet, key)
def htlc_failed(
self,
chan: Channel,
payment_hash: bytes,
htlc_id: int,
error_bytes: Optional[bytes],
failure_message: Optional['OnionRoutingFailure']):
util.trigger_callback('htlc_failed', payment_hash, chan, htlc_id)
self._on_maybe_forwarded_htlc_resolved(chan=chan, htlc_id=htlc_id)
q = self.sent_htlcs.get(payment_hash)
if q:
# detect if it is part of a bucket
# if yes, wait until the bucket completely failed
key = (payment_hash, chan.short_channel_id, htlc_id)
route, payment_secret, amount_msat, bucket_msat, amount_receiver_msat, trampoline_fee_level = self.sent_htlcs_info[key]
if error_bytes:
# TODO "decode_onion_error" might raise, catch and maybe blacklist/penalise someone?
try:
failure_message, sender_idx = chan.decode_onion_error(error_bytes, route, htlc_id)
except Exception as e:
sender_idx = None
failure_message = OnionRoutingFailure(-1, str(e))
else:
# probably got "update_fail_malformed_htlc". well... who to penalise now?
assert failure_message is not None
sender_idx = None
self.logger.info(f"htlc_failed {failure_message}")
# check sent_buckets if we use trampoline
if not self.channel_db and payment_secret in self.sent_buckets:
amount_sent, amount_failed = self.sent_buckets[payment_secret]
amount_failed += amount_receiver_msat
self.sent_buckets[payment_secret] = amount_sent, amount_failed
if amount_sent != amount_failed:
self.logger.info('bucket still active...')
return
self.logger.info('bucket failed')
amount_receiver_msat = amount_sent
htlc_log = HtlcLog(
success=False,
route=route,
amount_msat=amount_receiver_msat,
error_bytes=error_bytes,
failure_msg=failure_message,
sender_idx=sender_idx,
trampoline_fee_level=trampoline_fee_level)
q.put_nowait(htlc_log)
else:
self.logger.info(f"received unknown htlc_failed, probably from previous session")
key = payment_hash.hex()
self.set_invoice_status(key, PR_UNPAID)
util.trigger_callback('payment_failed', self.wallet, key, '')
async def _calc_routing_hints_for_invoice(self, amount_msat: Optional[int]):
"""calculate routing hints (BOLT-11 'r' field)"""
routing_hints = []
channels = list(self.channels.values())
# do minimal filtering of channels.
# we include channels that cannot *right now* receive (e.g. peer disconnected or balance insufficient)
channels = [chan for chan in channels
if (chan.is_open() and not chan.is_frozen_for_receiving())]
# Filter out channels that have very low receive capacity compared to invoice amt.
# Even with MPP, below a certain threshold, including these channels probably
# hurts more than help, as they lead to many failed attempts for the sender.
channels = [chan for chan in channels
if chan.available_to_spend(REMOTE) > (amount_msat or 0) * 0.05]
# cap max channels to include to keep QR code reasonably scannable
channels = sorted(channels, key=lambda chan: (not chan.is_active(), -chan.available_to_spend(REMOTE)))
channels = channels[:15]
random.shuffle(channels) # let's not leak channel order
scid_to_my_channels = {chan.short_channel_id: chan for chan in channels
if chan.short_channel_id is not None}
for chan in channels:
chan_id = chan.short_channel_id
assert isinstance(chan_id, bytes), chan_id
channel_info = get_mychannel_info(chan_id, scid_to_my_channels)
# note: as a fallback, if we don't have a channel update for the
# incoming direction of our private channel, we fill the invoice with garbage.
# the sender should still be able to pay us, but will incur an extra round trip
# (they will get the channel update from the onion error)
# at least, that's the theory. https://github.com/lightningnetwork/lnd/issues/2066
fee_base_msat = fee_proportional_millionths = 0
cltv_expiry_delta = 1 # lnd won't even try with zero
missing_info = True
if channel_info:
policy = get_mychannel_policy(channel_info.short_channel_id, chan.node_id, scid_to_my_channels)
if policy:
fee_base_msat = policy.fee_base_msat
fee_proportional_millionths = policy.fee_proportional_millionths
cltv_expiry_delta = policy.cltv_expiry_delta
missing_info = False
if missing_info:
self.logger.info(
f"Warning. Missing channel update for our channel {chan_id}; "
f"filling invoice with incorrect data.")
routing_hints.append(('r', [(
chan.node_id,
chan_id,
fee_base_msat,
fee_proportional_millionths,
cltv_expiry_delta)]))
return routing_hints
def delete_payment(self, payment_hash_hex: str):
try:
with self.lock:
del self.payments[payment_hash_hex]
except KeyError:
return
self.wallet.save_db()
def get_balance(self):
with self.lock:
return Decimal(sum(
chan.balance(LOCAL) if not chan.is_closed() else 0
for chan in self.channels.values())) / 1000
def num_sats_can_send(self) -> Decimal:
can_send = 0
with self.lock:
if self.channels:
for c in self.channels.values():
if c.is_active() and not c.is_frozen_for_sending():
can_send += c.available_to_spend(LOCAL)
# Here we have to guess a fee, because some callers (submarine swaps)
# use this method to initiate a payment, which would otherwise fail.
fee_base_msat = TRAMPOLINE_FEES[3]['fee_base_msat']
fee_proportional_millionths = TRAMPOLINE_FEES[3]['fee_proportional_millionths']
# inverse of fee_for_edge_msat
can_send_minus_fees = (can_send - fee_base_msat) * 1_000_000 // ( 1_000_000 + fee_proportional_millionths)
can_send_minus_fees = max(0, can_send_minus_fees)
return Decimal(can_send_minus_fees) / 1000
def num_sats_can_receive(self) -> Decimal:
with self.lock:
channels = [
c for c in self.channels.values()
if c.is_active() and not c.is_frozen_for_receiving()
]
can_receive = sum([c.available_to_spend(REMOTE) for c in channels]) if channels else 0
return Decimal(can_receive) / 1000
def num_sats_can_receive_no_mpp(self) -> Decimal:
with self.lock:
channels = [
c for c in self.channels.values()
if c.is_active() and not c.is_frozen_for_receiving()
]
can_receive = max([c.available_to_spend(REMOTE) for c in channels]) if channels else 0
return Decimal(can_receive) / 1000
def can_pay_invoice(self, invoice: LNInvoice) -> bool:
return invoice.get_amount_sat() <= self.num_sats_can_send()
def can_receive_invoice(self, invoice: LNInvoice) -> bool:
return invoice.get_amount_sat() <= self.num_sats_can_receive()
async def close_channel(self, chan_id):
chan = self._channels[chan_id]
peer = self._peers[chan.node_id]
return await peer.close_channel(chan_id)
def _force_close_channel(self, chan_id: bytes) -> Transaction:
chan = self._channels[chan_id]
tx = chan.force_close_tx()
# We set the channel state to make sure we won't sign new commitment txs.
# We expect the caller to try to broadcast this tx, after which it is
# not safe to keep using the channel even if the broadcast errors (server could be lying).
# Until the tx is seen in the mempool, there will be automatic rebroadcasts.
chan.set_state(ChannelState.FORCE_CLOSING)
# Add local tx to wallet to also allow manual rebroadcasts.
try:
self.wallet.add_transaction(tx)
except UnrelatedTransactionException:
pass # this can happen if (~all the balance goes to REMOTE)
return tx
async def force_close_channel(self, chan_id: bytes) -> str:
"""Force-close the channel. Network-related exceptions are propagated to the caller.
(automatic rebroadcasts will be scheduled)
"""
# note: as we are async, it can take a few event loop iterations between the caller
# "calling us" and us getting to run, and we only set the channel state now:
tx = self._force_close_channel(chan_id)
await self.network.broadcast_transaction(tx)
return tx.txid()
def schedule_force_closing(self, chan_id: bytes) -> 'asyncio.Task[None]':
"""Schedules a task to force-close the channel and returns it.
Network-related exceptions are suppressed.
(automatic rebroadcasts will be scheduled)
Note: this method is intentionally not async so that callers have a guarantee
that the channel state is set immediately.
"""
tx = self._force_close_channel(chan_id)
return asyncio.create_task(self.network.try_broadcasting(tx, 'force-close'))
def remove_channel(self, chan_id):
chan = self.channels[chan_id]
assert chan.can_be_deleted()
with self.lock:
self._channels.pop(chan_id)
self.db.get('channels').pop(chan_id.hex())
for addr in chan.get_wallet_addresses_channel_might_want_reserved():
self.wallet.set_reserved_state_of_address(addr, reserved=False)
util.trigger_callback('channels_updated', self.wallet)
util.trigger_callback('wallet_updated', self.wallet)
@ignore_exceptions
@log_exceptions
async def reestablish_peer_for_given_channel(self, chan: Channel) -> None:
now = time.time()
peer_addresses = []
if not self.channel_db:
addr = trampolines_by_id().get(chan.node_id)
if addr:
peer_addresses.append(addr)
else:
# will try last good address first, from gossip
last_good_addr = self.channel_db.get_last_good_address(chan.node_id)
if last_good_addr:
peer_addresses.append(last_good_addr)
# will try addresses for node_id from gossip
addrs_from_gossip = self.channel_db.get_node_addresses(chan.node_id) or []
for host, port, ts in addrs_from_gossip:
peer_addresses.append(LNPeerAddr(host, port, chan.node_id))
# will try addresses stored in channel storage
peer_addresses += list(chan.get_peer_addresses())
# Done gathering addresses.
# Now select first one that has not failed recently.
for peer in peer_addresses:
if self._can_retry_addr(peer, urgent=True, now=now):
await self._add_peer(peer.host, peer.port, peer.pubkey)
return
async def reestablish_peers_and_channels(self):
while True:
await asyncio.sleep(1)
if self.stopping_soon:
return
for chan in self.channels.values():
if chan.is_closed():
continue
# reestablish
if not chan.should_try_to_reestablish_peer():
continue
peer = self._peers.get(chan.node_id, None)
if peer:
await peer.taskgroup.spawn(peer.reestablish_channel(chan))
else:
await self.taskgroup.spawn(self.reestablish_peer_for_given_channel(chan))
def current_feerate_per_kw(self):
from .simple_config import FEE_LN_ETA_TARGET, FEERATE_FALLBACK_STATIC_FEE, FEERATE_REGTEST_HARDCODED
from .simple_config import FEERATE_PER_KW_MIN_RELAY_LIGHTNING
if constants.net is constants.BitcoinRegtest:
return FEERATE_REGTEST_HARDCODED // 4
feerate_per_kvbyte = self.network.config.eta_target_to_fee(FEE_LN_ETA_TARGET)
if feerate_per_kvbyte is None:
feerate_per_kvbyte = FEERATE_FALLBACK_STATIC_FEE
return max(FEERATE_PER_KW_MIN_RELAY_LIGHTNING, feerate_per_kvbyte // 4)
def create_channel_backup(self, channel_id):
chan = self._channels[channel_id]
# do not backup old-style channels
assert chan.is_static_remotekey_enabled()
peer_addresses = list(chan.get_peer_addresses())
peer_addr = peer_addresses[0]
return ImportedChannelBackupStorage(
node_id = chan.node_id,
privkey = self.node_keypair.privkey,
funding_txid = chan.funding_outpoint.txid,
funding_index = chan.funding_outpoint.output_index,
funding_address = chan.get_funding_address(),
host = peer_addr.host,
port = peer_addr.port,
is_initiator = chan.constraints.is_initiator,
channel_seed = chan.config[LOCAL].channel_seed,
local_delay = chan.config[LOCAL].to_self_delay,
remote_delay = chan.config[REMOTE].to_self_delay,
remote_revocation_pubkey = chan.config[REMOTE].revocation_basepoint.pubkey,
remote_payment_pubkey = chan.config[REMOTE].payment_basepoint.pubkey)
def export_channel_backup(self, channel_id):
xpub = self.wallet.get_fingerprint()
backup_bytes = self.create_channel_backup(channel_id).to_bytes()
assert backup_bytes == ImportedChannelBackupStorage.from_bytes(backup_bytes).to_bytes(), "roundtrip failed"
encrypted = pw_encode_with_version_and_mac(backup_bytes, xpub)
assert backup_bytes == pw_decode_with_version_and_mac(encrypted, xpub), "encrypt failed"
return 'channel_backup:' + encrypted
async def request_force_close(self, channel_id: bytes, *, connect_str=None) -> None:
if channel_id in self.channels:
chan = self.channels[channel_id]
peer = self._peers.get(chan.node_id)
if not peer:
raise Exception('Peer not found')
chan.should_request_force_close = True
peer.close_and_cleanup()
elif connect_str:
peer = await self.add_peer(connect_str)
await peer.trigger_force_close(channel_id)
elif channel_id in self.channel_backups:
await self._request_force_close_from_backup(channel_id)
else:
raise Exception(f'Unknown channel {channel_id.hex()}')
def import_channel_backup(self, data):
assert data.startswith('channel_backup:')
encrypted = data[15:]
xpub = self.wallet.get_fingerprint()
decrypted = pw_decode_with_version_and_mac(encrypted, xpub)
cb_storage = ImportedChannelBackupStorage.from_bytes(decrypted)
channel_id = cb_storage.channel_id()
if channel_id.hex() in self.db.get_dict("channels"):
raise Exception('Channel already in wallet')
self.logger.info(f'importing channel backup: {channel_id.hex()}')
d = self.db.get_dict("imported_channel_backups")
d[channel_id.hex()] = cb_storage
with self.lock:
cb = ChannelBackup(cb_storage, sweep_address=self.sweep_address, lnworker=self)
self._channel_backups[channel_id] = cb
self.wallet.save_db()
util.trigger_callback('channels_updated', self.wallet)
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
def has_conflicting_backup_with(self, remote_node_id: bytes):
""" Returns whether we have an active channel with this node on another device, using same local node id. """
channel_backup_peers = [
cb.node_id for cb in self.channel_backups.values()
if (not cb.is_closed() and cb.get_local_pubkey() == self.node_keypair.pubkey)]
return any(remote_node_id.startswith(cb_peer_nodeid) for cb_peer_nodeid in channel_backup_peers)
def remove_channel_backup(self, channel_id):
chan = self.channel_backups[channel_id]
assert chan.can_be_deleted()
onchain_backups = self.db.get_dict("onchain_channel_backups")
imported_backups = self.db.get_dict("imported_channel_backups")
if channel_id.hex() in onchain_backups:
onchain_backups.pop(channel_id.hex())
elif channel_id.hex() in imported_backups:
imported_backups.pop(channel_id.hex())
else:
raise Exception('Channel not found')
with self.lock:
self._channel_backups.pop(channel_id)
self.wallet.save_db()
util.trigger_callback('channels_updated', self.wallet)
@log_exceptions
async def _request_force_close_from_backup(self, channel_id: bytes):
cb = self.channel_backups.get(channel_id)
if not cb:
raise Exception(f'channel backup not found {self.channel_backups}')
cb = cb.cb # storage
self.logger.info(f'requesting channel force close: {channel_id.hex()}')
if isinstance(cb, ImportedChannelBackupStorage):
node_id = cb.node_id
privkey = cb.privkey
addresses = [(cb.host, cb.port, 0)]
# TODO also try network addresses from gossip db (as it might have changed)
else:
assert isinstance(cb, OnchainChannelBackupStorage)
if not self.channel_db:
raise Exception('Enable gossip first')
node_id = self.network.channel_db.get_node_by_prefix(cb.node_id_prefix)
privkey = self.node_keypair.privkey
addresses = self.network.channel_db.get_node_addresses(node_id)
if not addresses:
raise Exception('Peer not found in gossip database')
for host, port, timestamp in addresses:
peer_addr = LNPeerAddr(host, port, node_id)
transport = LNTransport(privkey, peer_addr, proxy=self.network.proxy)
peer = Peer(self, node_id, transport, is_channel_backup=True)
try:
async with OldTaskGroup(wait=any) as group:
await group.spawn(peer._message_loop())
await group.spawn(peer.trigger_force_close(channel_id))
return
except Exception as e:
self.logger.info(f'failed to connect {host} {e}')
continue
else:
raise Exception('failed to connect')
def maybe_add_backup_from_tx(self, tx):
funding_address = None
node_id_prefix = None
for i, o in enumerate(tx.outputs()):
script_type = get_script_type_from_output_script(o.scriptpubkey)
if script_type == 'p2wsh':
funding_index = i
funding_address = o.address
for o2 in tx.outputs():
if o2.scriptpubkey.startswith(bytes([opcodes.OP_RETURN])):
encrypted_data = o2.scriptpubkey[2:]
data = self.decrypt_cb_data(encrypted_data, funding_address)
if data.startswith(CB_MAGIC_BYTES):
node_id_prefix = data[4:]
if node_id_prefix is None:
return
funding_txid = tx.txid()
cb_storage = OnchainChannelBackupStorage(
node_id_prefix = node_id_prefix,
funding_txid = funding_txid,
funding_index = funding_index,
funding_address = funding_address,
is_initiator = True)
channel_id = cb_storage.channel_id().hex()
if channel_id in self.db.get_dict("channels"):
return
self.logger.info(f"adding backup from tx")
d = self.db.get_dict("onchain_channel_backups")
d[channel_id] = cb_storage
cb = ChannelBackup(cb_storage, sweep_address=self.sweep_address, lnworker=self)
self.wallet.save_db()
with self.lock:
self._channel_backups[bfh(channel_id)] = cb
util.trigger_callback('channels_updated', self.wallet)
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
| 49.358844 | 201 | 0.631671 |
import asyncio
import os
from decimal import Decimal
import random
import time
from typing import (Optional, Sequence, Tuple, List, Set, Dict, TYPE_CHECKING,
NamedTuple, Union, Mapping, Any, Iterable, AsyncGenerator, DefaultDict)
import threading
import socket
import aiohttp
import json
from datetime import datetime, timezone
from functools import partial
from collections import defaultdict
import concurrent
from concurrent import futures
import urllib.parse
import dns.resolver
import dns.exception
from aiorpcx import run_in_thread, NetAddress, ignore_after
from . import constants, util
from . import keystore
from .util import profiler, chunks, OldTaskGroup
from .invoices import PR_TYPE_LN, PR_UNPAID, PR_EXPIRED, PR_PAID, PR_INFLIGHT, PR_FAILED, PR_ROUTING, LNInvoice, LN_EXPIRY_NEVER
from .util import NetworkRetryManager, JsonRPCClient
from .lnutil import LN_MAX_FUNDING_SAT
from .keystore import BIP32_KeyStore
from .bitcoin import COIN
from .bitcoin import opcodes, make_op_return, address_to_scripthash
from .transaction import Transaction
from .transaction import get_script_type_from_output_script
from .crypto import sha256
from .bip32 import BIP32Node
from .util import bh2u, bfh, InvoiceError, resolve_dns_srv, is_ip_address, log_exceptions
from .crypto import chacha20_encrypt, chacha20_decrypt
from .util import ignore_exceptions, make_aiohttp_session
from .util import timestamp_to_datetime, random_shuffled_copy
from .util import MyEncoder, is_private_netaddress, UnrelatedTransactionException
from .logging import Logger
from .lntransport import LNTransport, LNResponderTransport, LNTransportBase
from .lnpeer import Peer, LN_P2P_NETWORK_TIMEOUT
from .lnaddr import lnencode, LnAddr, lndecode
from .ecc import der_sig_from_sig_string
from .lnchannel import Channel, AbstractChannel
from .lnchannel import ChannelState, PeerState, HTLCWithStatus
from .lnrater import LNRater
from . import lnutil
from .lnutil import funding_output_script
from .bitcoin import redeem_script_to_address
from .lnutil import (Outpoint, LNPeerAddr,
get_compressed_pubkey_from_bech32, extract_nodeid,
PaymentFailure, split_host_port, ConnStringFormatError,
generate_keypair, LnKeyFamily, LOCAL, REMOTE,
MIN_FINAL_CLTV_EXPIRY_FOR_INVOICE,
NUM_MAX_EDGES_IN_PAYMENT_PATH, SENT, RECEIVED, HTLCOwner,
UpdateAddHtlc, Direction, LnFeatures, ShortChannelID,
HtlcLog, derive_payment_secret_from_payment_preimage,
NoPathFound, InvalidGossipMsg)
from .lnutil import ln_dummy_address, ln_compare_features, IncompatibleLightningFeatures
from .transaction import PartialTxOutput, PartialTransaction, PartialTxInput
from .lnonion import OnionFailureCode, OnionRoutingFailure
from .lnmsg import decode_msg
from .i18n import _
from .lnrouter import (RouteEdge, LNPaymentRoute, LNPaymentPath, is_route_sane_to_use,
NoChannelPolicy, LNPathInconsistent)
from .address_synchronizer import TX_HEIGHT_LOCAL
from . import lnsweep
from .lnwatcher import LNWalletWatcher
from .crypto import pw_encode_with_version_and_mac, pw_decode_with_version_and_mac
from .lnutil import ImportedChannelBackupStorage, OnchainChannelBackupStorage
from .lnchannel import ChannelBackup
from .channel_db import UpdateStatus
from .channel_db import get_mychannel_info, get_mychannel_policy
from .submarine_swaps import SwapManager
from .channel_db import ChannelInfo, Policy
from .mpp_split import suggest_splits
from .trampoline import create_trampoline_route_and_onion, TRAMPOLINE_FEES, is_legacy_relay
if TYPE_CHECKING:
from .network import Network
from .wallet import Abstract_Wallet
from .channel_db import ChannelDB
from .simple_config import SimpleConfig
SAVED_PR_STATUS = [PR_PAID, PR_UNPAID]
NUM_PEERS_TARGET = 4
CB_VERSION = 0
CB_MAGIC_BYTES = bytes([0, 0, 0, CB_VERSION])
FALLBACK_NODE_LIST_TESTNET = (
LNPeerAddr(host='203.132.95.10', port=9735, pubkey=bfh('038863cf8ab91046230f561cd5b386cbff8309fa02e3f0c3ed161a3aeb64a643b9')),
LNPeerAddr(host='2401:d002:4402:0:bf1d:986a:7598:6d49', port=9735, pubkey=bfh('038863cf8ab91046230f561cd5b386cbff8309fa02e3f0c3ed161a3aeb64a643b9')),
LNPeerAddr(host='50.116.3.223', port=9734, pubkey=bfh('03236a685d30096b26692dce0cf0fa7c8528bdf61dbf5363a3ef6d5c92733a3016')),
LNPeerAddr(host='3.16.119.191', port=9735, pubkey=bfh('03d5e17a3c213fe490e1b0c389f8cfcfcea08a29717d50a9f453735e0ab2a7c003')),
LNPeerAddr(host='34.250.234.192', port=9735, pubkey=bfh('03933884aaf1d6b108397e5efe5c86bcf2d8ca8d2f700eda99db9214fc2712b134')),
LNPeerAddr(host='88.99.209.230', port=9735, pubkey=bfh('0260d9119979caedc570ada883ff614c6efb93f7f7382e25d73ecbeba0b62df2d7')),
LNPeerAddr(host='160.16.233.215', port=9735, pubkey=bfh('023ea0a53af875580899da0ab0a21455d9c19160c4ea1b7774c9d4be6810b02d2c')),
LNPeerAddr(host='197.155.6.173', port=9735, pubkey=bfh('0269a94e8b32c005e4336bfb743c08a6e9beb13d940d57c479d95c8e687ccbdb9f')),
LNPeerAddr(host='2c0f:fb18:406::4', port=9735, pubkey=bfh('0269a94e8b32c005e4336bfb743c08a6e9beb13d940d57c479d95c8e687ccbdb9f')),
LNPeerAddr(host='163.172.94.64', port=9735, pubkey=bfh('030f0bf260acdbd3edcad84d7588ec7c5df4711e87e6a23016f989b8d3a4147230')),
LNPeerAddr(host='23.237.77.12', port=9735, pubkey=bfh('02312627fdf07fbdd7e5ddb136611bdde9b00d26821d14d94891395452f67af248')),
LNPeerAddr(host='197.155.6.172', port=9735, pubkey=bfh('02ae2f22b02375e3e9b4b4a2db4f12e1b50752b4062dbefd6e01332acdaf680379')),
LNPeerAddr(host='2c0f:fb18:406::3', port=9735, pubkey=bfh('02ae2f22b02375e3e9b4b4a2db4f12e1b50752b4062dbefd6e01332acdaf680379')),
LNPeerAddr(host='23.239.23.44', port=9740, pubkey=bfh('034fe52e98a0e9d3c21b767e1b371881265d8c7578c21f5afd6d6438da10348b36')),
LNPeerAddr(host='2600:3c01::f03c:91ff:fe05:349c', port=9740, pubkey=bfh('034fe52e98a0e9d3c21b767e1b371881265d8c7578c21f5afd6d6438da10348b36')),
)
FALLBACK_NODE_LIST_MAINNET = [
LNPeerAddr(host='172.81.181.3', port=9735, pubkey=bfh('0214382bdce7750dfcb8126df8e2b12de38536902dc36abcebdaeefdeca1df8284')),
LNPeerAddr(host='35.230.100.60', port=9735, pubkey=bfh('023f5e3582716bed96f6f26cfcd8037e07474d7b4743afdc8b07e692df63464d7e')),
LNPeerAddr(host='40.69.71.114', port=9735, pubkey=bfh('028303182c9885da93b3b25c9621d22cf34475e63c123942e402ab530c0556e675')),
LNPeerAddr(host='94.177.171.73', port=9735, pubkey=bfh('0276e09a267592e7451a939c932cf685f0754de382a3ca85d2fb3a864d4c365ad5')),
LNPeerAddr(host='34.236.113.58', port=9735, pubkey=bfh('02fa50c72ee1e2eb5f1b6d9c3032080c4c864373c4201dfa2966aa34eee1051f97')),
LNPeerAddr(host='52.50.244.44', port=9735, pubkey=bfh('030c3f19d742ca294a55c00376b3b355c3c90d61c6b6b39554dbc7ac19b141c14f')),
LNPeerAddr(host='157.245.68.47', port=9735, pubkey=bfh('03c2abfa93eacec04721c019644584424aab2ba4dff3ac9bdab4e9c97007491dda')),
LNPeerAddr(host='18.221.23.28', port=9735, pubkey=bfh('03abf6f44c355dec0d5aa155bdbdd6e0c8fefe318eff402de65c6eb2e1be55dc3e')),
LNPeerAddr(host='52.224.178.244', port=9735, pubkey=bfh('026b105ac13212c48714c6be9b11577a9ce10f10e1c88a45ce217e6331209faf8b')),
LNPeerAddr(host='34.239.230.56', port=9735, pubkey=bfh('03864ef025fde8fb587d989186ce6a4a186895ee44a926bfc370e2c366597a3f8f')),
LNPeerAddr(host='46.229.165.136', port=9735, pubkey=bfh('0390b5d4492dc2f5318e5233ab2cebf6d48914881a33ef6a9c6bcdbb433ad986d0')),
LNPeerAddr(host='157.230.28.160', port=9735, pubkey=bfh('0279c22ed7a068d10dc1a38ae66d2d6461e269226c60258c021b1ddcdfe4b00bc4')),
LNPeerAddr(host='74.108.13.152', port=9735, pubkey=bfh('0331f80652fb840239df8dc99205792bba2e559a05469915804c08420230e23c7c')),
LNPeerAddr(host='167.172.44.148', port=9735, pubkey=bfh('0395033b252c6f40e3756984162d68174e2bd8060a129c0d3462a9370471c6d28f')),
LNPeerAddr(host='138.68.14.104', port=9735, pubkey=bfh('03bb88ccc444534da7b5b64b4f7b15e1eccb18e102db0e400d4b9cfe93763aa26d')),
LNPeerAddr(host='3.124.63.44', port=9735, pubkey=bfh('0242a4ae0c5bef18048fbecf995094b74bfb0f7391418d71ed394784373f41e4f3')),
LNPeerAddr(host='2001:470:8:2e1::43', port=9735, pubkey=bfh('03baa70886d9200af0ffbd3f9e18d96008331c858456b16e3a9b41e735c6208fef')),
LNPeerAddr(host='2601:186:c100:6bcd:219:d1ff:fe75:dc2f', port=9735, pubkey=bfh('0298f6074a454a1f5345cb2a7c6f9fce206cd0bf675d177cdbf0ca7508dd28852f')),
LNPeerAddr(host='2001:41d0:e:734::1', port=9735, pubkey=bfh('03a503d8e30f2ff407096d235b5db63b4fcf3f89a653acb6f43d3fc492a7674019')),
LNPeerAddr(host='2a01:4f9:2b:2254::2', port=9735, pubkey=bfh('02f3069a342ae2883a6f29e275f06f28a56a6ea2e2d96f5888a3266444dcf542b6')),
LNPeerAddr(host='2a02:8070:24c1:100:528c:2997:6dbc:a054', port=9735, pubkey=bfh('02a45def9ae014fdd2603dd7033d157faa3a55a72b06a63ae22ef46d9fafdc6e8d')),
LNPeerAddr(host='2600:3c01::f03c:91ff:fe05:349c', port=9736, pubkey=bfh('02731b798b39a09f9f14e90ee601afb6ebb796d6e5797de14582a978770b33700f')),
LNPeerAddr(host='2a00:8a60:e012:a00::21', port=9735, pubkey=bfh('027ce055380348d7812d2ae7745701c9f93e70c1adeb2657f053f91df4f2843c71')),
LNPeerAddr(host='2604:a880:400:d1::8bd:1001', port=9735, pubkey=bfh('03649c72a4816f0cd546f84aafbd657e92a30ab474de7ab795e8b5650a427611f7')),
LNPeerAddr(host='2a01:4f8:c0c:7b31::1', port=9735, pubkey=bfh('02c16cca44562b590dd279c942200bdccfd4f990c3a69fad620c10ef2f8228eaff')),
LNPeerAddr(host='2001:41d0:1:b40d::1', port=9735, pubkey=bfh('026726a4b043d413b45b334876d17b8a98848129604429ec65532ba286a42efeac')),
]
from .trampoline import trampolines_by_id, hardcoded_trampoline_nodes, is_hardcoded_trampoline
class PaymentInfo(NamedTuple):
payment_hash: bytes
amount_msat: Optional[int]
direction: int
status: int
class ErrorAddingPeer(Exception): pass
BASE_FEATURES = LnFeatures(0)\
| LnFeatures.OPTION_DATA_LOSS_PROTECT_OPT\
| LnFeatures.OPTION_STATIC_REMOTEKEY_OPT\
| LnFeatures.VAR_ONION_OPT\
| LnFeatures.PAYMENT_SECRET_OPT\
| LnFeatures.OPTION_UPFRONT_SHUTDOWN_SCRIPT_OPT\
LNWALLET_FEATURES = BASE_FEATURES\
| LnFeatures.OPTION_DATA_LOSS_PROTECT_REQ\
| LnFeatures.OPTION_STATIC_REMOTEKEY_REQ\
| LnFeatures.GOSSIP_QUERIES_REQ\
| LnFeatures.BASIC_MPP_OPT\
| LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT\
| LnFeatures.OPTION_SHUTDOWN_ANYSEGWIT_OPT\
| LnFeatures.OPTION_CHANNEL_TYPE_OPT\
LNGOSSIP_FEATURES = BASE_FEATURES\
| LnFeatures.GOSSIP_QUERIES_OPT\
| LnFeatures.GOSSIP_QUERIES_REQ\
class LNWorker(Logger, NetworkRetryManager[LNPeerAddr]):
INITIAL_TRAMPOLINE_FEE_LEVEL = 1
def __init__(self, xprv, features: LnFeatures):
Logger.__init__(self)
NetworkRetryManager.__init__(
self,
max_retry_delay_normal=3600,
init_retry_delay_normal=600,
max_retry_delay_urgent=300,
init_retry_delay_urgent=4,
)
self.lock = threading.RLock()
self.node_keypair = generate_keypair(BIP32Node.from_xkey(xprv), LnKeyFamily.NODE_KEY)
self.backup_key = generate_keypair(BIP32Node.from_xkey(xprv), LnKeyFamily.BACKUP_CIPHER).privkey
self._peers = {} f.listen_server = None
self.features = features
self.network = None
self.config = None
self.stopping_soon = False
util.register_callback(self.on_proxy_changed, ['proxy_set'])
@property
def channel_db(self):
return self.network.channel_db if self.network else None
@property
def peers(self) -> Mapping[bytes, Peer]:
with self.lock:
return self._peers.copy()
def channels_for_peer(self, node_id: bytes) -> Dict[bytes, Channel]:
return {}
def get_node_alias(self, node_id: bytes) -> Optional[str]:
node_alias = None
if self.channel_db:
node_info = self.channel_db.get_node_info_for_node_id(node_id)
if node_info:
node_alias = node_info.alias
else:
for k, v in hardcoded_trampoline_nodes().items():
if v.pubkey == node_id:
node_alias = k
break
return node_alias
async def maybe_listen(self):
listen_addr = self.config.get('lightning_listen')
if listen_addr:
self.logger.info(f'lightning_listen enabled. will try to bind: {listen_addr!r}')
try:
netaddr = NetAddress.from_string(listen_addr)
except Exception as e:
self.logger.error(f"failed to parse config key 'lightning_listen'. got: {e!r}")
return
addr = str(netaddr.host)
async def cb(reader, writer):
transport = LNResponderTransport(self.node_keypair.privkey, reader, writer)
try:
node_id = await transport.handshake()
except Exception as e:
self.logger.info(f'handshake failure from incoming connection: {e!r}')
return
await self._add_peer_from_transport(node_id=node_id, transport=transport)
try:
self.listen_server = await asyncio.start_server(cb, addr, netaddr.port)
except OSError as e:
self.logger.error(f"cannot listen for lightning p2p. error: {e!r}")
@ignore_exceptions
async def main_loop(self):
self.logger.info("starting taskgroup.")
try:
async with self.taskgroup as group:
await group.spawn(self._maintain_connectivity())
except Exception as e:
self.logger.exception("taskgroup died.")
finally:
self.logger.info("taskgroup stopped.")
async def _maintain_connectivity(self):
while True:
await asyncio.sleep(1)
if self.stopping_soon:
return
now = time.time()
if len(self._peers) >= NUM_PEERS_TARGET:
continue
peers = await self._get_next_peers_to_try()
for peer in peers:
if self._can_retry_addr(peer, now=now):
try:
await self._add_peer(peer.host, peer.port, peer.pubkey)
except ErrorAddingPeer as e:
self.logger.info(f"failed to add peer: {peer}. exc: {e!r}")
async def _add_peer(self, host: str, port: int, node_id: bytes) -> Peer:
if node_id in self._peers:
return self._peers[node_id]
port = int(port)
peer_addr = LNPeerAddr(host, port, node_id)
self._trying_addr_now(peer_addr)
self.logger.info(f"adding peer {peer_addr}")
if node_id == self.node_keypair.pubkey:
raise ErrorAddingPeer("cannot connect to self")
transport = LNTransport(self.node_keypair.privkey, peer_addr,
proxy=self.network.proxy)
peer = await self._add_peer_from_transport(node_id=node_id, transport=transport)
return peer
async def _add_peer_from_transport(self, *, node_id: bytes, transport: LNTransportBase) -> Peer:
peer = Peer(self, node_id, transport)
with self.lock:
existing_peer = self._peers.get(node_id)
if existing_peer:
existing_peer.close_and_cleanup()
assert node_id not in self._peers
self._peers[node_id] = peer
await self.taskgroup.spawn(peer.main_loop())
return peer
def peer_closed(self, peer: Peer) -> None:
with self.lock:
peer2 = self._peers.get(peer.pubkey)
if peer2 is peer:
self._peers.pop(peer.pubkey)
def num_peers(self) -> int:
return sum([p.is_initialized() for p in self.peers.values()])
def start_network(self, network: 'Network'):
assert network
self.network = network
self.config = network.config
self._add_peers_from_config()
asyncio.run_coroutine_threadsafe(self.main_loop(), self.network.asyncio_loop)
async def stop(self):
if self.listen_server:
self.listen_server.close()
util.unregister_callback(self.on_proxy_changed)
await self.taskgroup.cancel_remaining()
def _add_peers_from_config(self):
peer_list = self.config.get('lightning_peers', [])
for host, port, pubkey in peer_list:
asyncio.run_coroutine_threadsafe(
self._add_peer(host, int(port), bfh(pubkey)),
self.network.asyncio_loop)
def is_good_peer(self, peer: LNPeerAddr) -> bool:
# the purpose of this method is to filter peers that advertise the desired feature bits
# it is disabled for now, because feature bits published in node announcements seem to be unreliable
return True
node_id = peer.pubkey
node = self.channel_db._nodes.get(node_id)
if not node:
return False
try:
ln_compare_features(self.features, node.features)
except IncompatibleLightningFeatures:
return False
#self.logger.info(f'is_good {peer.host}')
return True
def on_peer_successfully_established(self, peer: Peer) -> None:
if isinstance(peer.transport, LNTransport):
peer_addr = peer.transport.peer_addr
# reset connection attempt count
self._on_connection_successfully_established(peer_addr)
# add into channel db
if self.channel_db:
self.channel_db.add_recent_peer(peer_addr)
# save network address into channels we might have with peer
for chan in peer.channels.values():
chan.add_or_update_peer_addr(peer_addr)
async def _get_next_peers_to_try(self) -> Sequence[LNPeerAddr]:
now = time.time()
await self.channel_db.data_loaded.wait()
# first try from recent peers
recent_peers = self.channel_db.get_recent_peers()
for peer in recent_peers:
if not peer:
continue
if peer.pubkey in self._peers:
continue
if not self._can_retry_addr(peer, now=now):
continue
if not self.is_good_peer(peer):
continue
return [peer]
# try random peer from graph
unconnected_nodes = self.channel_db.get_200_randomly_sorted_nodes_not_in(self.peers.keys())
if unconnected_nodes:
for node_id in unconnected_nodes:
addrs = self.channel_db.get_node_addresses(node_id)
if not addrs:
continue
host, port, timestamp = self.choose_preferred_address(list(addrs))
try:
peer = LNPeerAddr(host, port, node_id)
except ValueError:
continue
if not self._can_retry_addr(peer, now=now):
continue
if not self.is_good_peer(peer):
continue
#self.logger.info('taking random ln peer from our channel db')
return [peer]
# getting desperate... let's try hardcoded fallback list of peers
if constants.net in (constants.BitcoinTestnet,):
fallback_list = FALLBACK_NODE_LIST_TESTNET
elif constants.net in (constants.BitcoinMainnet,):
fallback_list = FALLBACK_NODE_LIST_MAINNET
else:
return []
fallback_list = [peer for peer in fallback_list if self._can_retry_addr(peer, now=now)]
if fallback_list:
return [random.choice(fallback_list)]
return await run_in_thread(self._get_peers_from_dns_seeds)
def _get_peers_from_dns_seeds(self) -> Sequence[LNPeerAddr]:
if not constants.net.LN_DNS_SEEDS:
return []
dns_seed = random.choice(constants.net.LN_DNS_SEEDS)
self.logger.info('asking dns seed "{}" for ln peers'.format(dns_seed))
try:
srv_answers = resolve_dns_srv('r{}.{}'.format(
constants.net.LN_REALM_BYTE, dns_seed))
except dns.exception.DNSException as e:
self.logger.info(f'failed querying (1) dns seed "{dns_seed}" for ln peers: {repr(e)}')
return []
random.shuffle(srv_answers)
num_peers = 2 * NUM_PEERS_TARGET
srv_answers = srv_answers[:num_peers]
peers = []
for srv_ans in srv_answers:
try:
answers = dns.resolver.resolve(srv_ans['host'])
except dns.exception.DNSException as e:
self.logger.info(f'failed querying (2) dns seed "{dns_seed}" for ln peers: {repr(e)}')
continue
try:
ln_host = str(answers[0])
port = int(srv_ans['port'])
bech32_pubkey = srv_ans['host'].split('.')[0]
pubkey = get_compressed_pubkey_from_bech32(bech32_pubkey)
peers.append(LNPeerAddr(ln_host, port, pubkey))
except Exception as e:
self.logger.info(f'error with parsing peer from dns seed: {repr(e)}')
continue
self.logger.info(f'got {len(peers)} ln peers from dns seed')
return peers
@staticmethod
def choose_preferred_address(addr_list: Sequence[Tuple[str, int, int]]) -> Tuple[str, int, int]:
assert len(addr_list) >= 1
for host, port, timestamp in addr_list:
if is_ip_address(host):
return host, port, timestamp
choice = random.choice(addr_list)
return choice
def on_proxy_changed(self, event, *args):
for peer in self.peers.values():
peer.close_and_cleanup()
self._clear_addr_retry_times()
@log_exceptions
async def add_peer(self, connect_str: str) -> Peer:
node_id, rest = extract_nodeid(connect_str)
peer = self._peers.get(node_id)
if not peer:
if rest is not None:
host, port = split_host_port(rest)
else:
if not self.channel_db:
addr = trampolines_by_id().get(node_id)
if not addr:
raise ConnStringFormatError(_('Address unknown for node:') + ' ' + bh2u(node_id))
host, port = addr.host, addr.port
else:
addrs = self.channel_db.get_node_addresses(node_id)
if not addrs:
raise ConnStringFormatError(_('Don\'t know any addresses for node:') + ' ' + bh2u(node_id))
host, port, timestamp = self.choose_preferred_address(list(addrs))
port = int(port)
# Try DNS-resolving the host (if needed). This is simply so that
# the caller gets a nice exception if it cannot be resolved.
try:
await asyncio.get_event_loop().getaddrinfo(host, port)
except socket.gaierror:
raise ConnStringFormatError(_('Hostname does not resolve (getaddrinfo failed)'))
# add peer
peer = await self._add_peer(host, port, node_id)
return peer
class LNGossip(LNWorker):
max_age = 14*24*3600
LOGGING_SHORTCUT = 'g'
def __init__(self):
seed = os.urandom(32)
node = BIP32Node.from_rootseed(seed, xtype='standard')
xprv = node.to_xprv()
super().__init__(xprv, LNGOSSIP_FEATURES)
self.unknown_ids = set()
def start_network(self, network: 'Network'):
assert network
super().start_network(network)
asyncio.run_coroutine_threadsafe(self.taskgroup.spawn(self.maintain_db()), self.network.asyncio_loop)
async def maintain_db(self):
await self.channel_db.data_loaded.wait()
while True:
if len(self.unknown_ids) == 0:
self.channel_db.prune_old_policies(self.max_age)
self.channel_db.prune_orphaned_channels()
await asyncio.sleep(120)
async def add_new_ids(self, ids: Iterable[bytes]):
known = self.channel_db.get_channel_ids()
new = set(ids) - set(known)
self.unknown_ids.update(new)
util.trigger_callback('unknown_channels', len(self.unknown_ids))
util.trigger_callback('gossip_peers', self.num_peers())
util.trigger_callback('ln_gossip_sync_progress')
def get_ids_to_query(self) -> Sequence[bytes]:
N = 500
l = list(self.unknown_ids)
self.unknown_ids = set(l[N:])
util.trigger_callback('unknown_channels', len(self.unknown_ids))
util.trigger_callback('ln_gossip_sync_progress')
return l[0:N]
def get_sync_progress_estimate(self) -> Tuple[Optional[int], Optional[int], Optional[int]]:
if self.num_peers() == 0:
return None, None, None
nchans_with_0p, nchans_with_1p, nchans_with_2p = self.channel_db.get_num_channels_partitioned_by_policy_count()
num_db_channels = nchans_with_0p + nchans_with_1p + nchans_with_2p
# some channels will never have two policies (only one is in gossip?...)
# so if we have at least 1 policy for a channel, we consider that channel "complete" here
current_est = num_db_channels - nchans_with_0p
total_est = len(self.unknown_ids) + num_db_channels
progress = current_est / total_est if total_est and current_est else 0
progress_percent = (1.0 / 0.95 * progress) * 100
progress_percent = min(progress_percent, 100)
progress_percent = round(progress_percent)
# take a minimal number of synchronized channels to get a more accurate
# percentage estimate
if current_est < 200:
progress_percent = 0
return current_est, total_est, progress_percent
async def process_gossip(self, chan_anns, node_anns, chan_upds):
# note: we run in the originating peer's TaskGroup, so we can safely raise here
await self.channel_db.data_loaded.wait()
self.logger.debug(f'process_gossip {len(chan_anns)} {len(node_anns)} {len(chan_upds)}')
def process_chan_anns():
for payload in chan_anns:
self.channel_db.verify_channel_announcement(payload)
self.channel_db.add_channel_announcements(chan_anns)
await run_in_thread(process_chan_anns)
def process_node_anns():
for payload in node_anns:
self.channel_db.verify_node_announcement(payload)
self.channel_db.add_node_announcements(node_anns)
await run_in_thread(process_node_anns)
categorized_chan_upds = await run_in_thread(partial(
self.channel_db.add_channel_updates,
chan_upds,
max_age=self.max_age))
orphaned = categorized_chan_upds.orphaned
if orphaned:
self.logger.info(f'adding {len(orphaned)} unknown channel ids')
orphaned_ids = [c['short_channel_id'] for c in orphaned]
await self.add_new_ids(orphaned_ids)
if categorized_chan_upds.good:
self.logger.debug(f'on_channel_update: {len(categorized_chan_upds.good)}/{len(chan_upds)}')
class LNWallet(LNWorker):
lnwatcher: Optional['LNWalletWatcher']
MPP_EXPIRY = 120
TIMEOUT_SHUTDOWN_FAIL_PENDING_HTLCS = 3
def __init__(self, wallet: 'Abstract_Wallet', xprv):
self.wallet = wallet
self.db = wallet.db
Logger.__init__(self)
LNWorker.__init__(self, xprv, LNWALLET_FEATURES)
self.config = wallet.config
self.lnwatcher = None
self.lnrater: LNRater = None
self.payments = self.db.get_dict('lightning_payments')
self.preimages = self.db.get_dict('lightning_preimages')
self.sweep_address = wallet.get_new_sweep_address_for_channel()
self.logs = defaultdict(list) self.enable_htlc_forwarding = True
self._channels = {}
channels = self.db.get_dict("channels")
for channel_id, c in random_shuffled_copy(channels.items()):
self._channels[bfh(channel_id)] = Channel(c, sweep_address=self.sweep_address, lnworker=self)
self._channel_backups = {}
for name in ["onchain_channel_backups", "imported_channel_backups"]:
channel_backups = self.db.get_dict(name)
for channel_id, storage in channel_backups.items():
self._channel_backups[bfh(channel_id)] = ChannelBackup(storage, sweep_address=self.sweep_address, lnworker=self)
self.sent_htlcs = defaultdict(asyncio.Queue)
self.sent_htlcs_info = dict()
self.sent_buckets = dict()
self.received_mpp_htlcs = dict()
self.swap_manager = SwapManager(wallet=self.wallet, lnworker=self)
self.inflight_payments = set()
for payment_hash in self.get_payments(status='inflight').keys():
self.set_invoice_status(payment_hash.hex(), PR_INFLIGHT)
self.trampoline_forwarding_failures = {}
self.downstream_htlc_to_upstream_peer_map = {}
def has_deterministic_node_id(self) -> bool:
return bool(self.db.get('lightning_xprv'))
def can_have_recoverable_channels(self) -> bool:
return (self.has_deterministic_node_id()
and not (self.config.get('lightning_listen')))
def has_recoverable_channels(self) -> bool:
return (self.can_have_recoverable_channels()
and self.config.get('use_recoverable_channels', True))
@property
def channels(self) -> Mapping[bytes, Channel]:
with self.lock:
return self._channels.copy()
@property
def channel_backups(self) -> Mapping[bytes, ChannelBackup]:
with self.lock:
return self._channel_backups.copy()
def get_channel_by_id(self, channel_id: bytes) -> Optional[Channel]:
return self._channels.get(channel_id, None)
def diagnostic_name(self):
return self.wallet.diagnostic_name()
@ignore_exceptions
@log_exceptions
async def sync_with_local_watchtower(self):
watchtower = self.network.local_watchtower
if watchtower:
while True:
for chan in self.channels.values():
await self.sync_channel_with_watchtower(chan, watchtower.sweepstore)
await asyncio.sleep(5)
@ignore_exceptions
@log_exceptions
async def sync_with_remote_watchtower(self):
while True:
await asyncio.sleep(5)
watchtower_url = self.config.get('watchtower_url')
if not watchtower_url:
continue
parsed_url = urllib.parse.urlparse(watchtower_url)
if not (parsed_url.scheme == 'https' or is_private_netaddress(parsed_url.hostname)):
self.logger.warning(f"got watchtower URL for remote tower but we won't use it! "
f"can only use HTTPS (except if private IP): not using {watchtower_url!r}")
continue
# try to sync with the remote watchtower
try:
async with make_aiohttp_session(proxy=self.network.proxy) as session:
watchtower = JsonRPCClient(session, watchtower_url)
watchtower.add_method('get_ctn')
watchtower.add_method('add_sweep_tx')
for chan in self.channels.values():
await self.sync_channel_with_watchtower(chan, watchtower)
except aiohttp.client_exceptions.ClientConnectorError:
self.logger.info(f'could not contact remote watchtower {watchtower_url}')
async def sync_channel_with_watchtower(self, chan: Channel, watchtower):
outpoint = chan.funding_outpoint.to_str()
addr = chan.get_funding_address()
current_ctn = chan.get_oldest_unrevoked_ctn(REMOTE)
watchtower_ctn = await watchtower.get_ctn(outpoint, addr)
for ctn in range(watchtower_ctn + 1, current_ctn):
sweeptxs = chan.create_sweeptxs(ctn)
for tx in sweeptxs:
await watchtower.add_sweep_tx(outpoint, ctn, tx.inputs()[0].prevout.to_str(), tx.serialize())
def start_network(self, network: 'Network'):
assert network
self.network = network
self.config = network.config
self.lnwatcher = LNWalletWatcher(self, network)
self.lnwatcher.start_network(network)
self.swap_manager.start_network(network=network, lnwatcher=self.lnwatcher)
self.lnrater = LNRater(self, network)
for chan in self.channels.values():
self.lnwatcher.add_channel(chan.funding_outpoint.to_str(), chan.get_funding_address())
for cb in self.channel_backups.values():
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
for coro in [
self.maybe_listen(),
self.lnwatcher.on_network_update('network_updated'), # shortcut (don't block) if funding tx locked and verified
self.reestablish_peers_and_channels(),
self.sync_with_local_watchtower(),
self.sync_with_remote_watchtower(),
]:
tg_coro = self.taskgroup.spawn(coro)
asyncio.run_coroutine_threadsafe(tg_coro, self.network.asyncio_loop)
async def stop(self):
self.stopping_soon = True
if self.listen_server:
self.listen_server.close()
async with ignore_after(self.TIMEOUT_SHUTDOWN_FAIL_PENDING_HTLCS):
await self.wait_for_received_pending_htlcs_to_get_removed()
await LNWorker.stop(self)
if self.lnwatcher:
await self.lnwatcher.stop()
self.lnwatcher = None
async def wait_for_received_pending_htlcs_to_get_removed(self):
assert self.stopping_soon is True
# that we can already fail/fulfill. e.g. forwarded htlcs cannot be removed
async with OldTaskGroup() as group:
for peer in self.peers.values():
await group.spawn(peer.wait_one_htlc_switch_iteration())
while True:
if all(not peer.received_htlcs_pending_removal for peer in self.peers.values()):
break
async with OldTaskGroup(wait=any) as group:
for peer in self.peers.values():
await group.spawn(peer.received_htlc_removed_event.wait())
def peer_closed(self, peer):
for chan in self.channels_for_peer(peer.pubkey).values():
chan.peer_state = PeerState.DISCONNECTED
util.trigger_callback('channel', self.wallet, chan)
super().peer_closed(peer)
def get_payments(self, *, status=None) -> Mapping[bytes, List[HTLCWithStatus]]:
out = defaultdict(list)
for chan in self.channels.values():
d = chan.get_payments(status=status)
for payment_hash, plist in d.items():
out[payment_hash] += plist
return out
def get_payment_value(
self, info: Optional['PaymentInfo'], plist: List[HTLCWithStatus],
) -> Tuple[int, int, int]:
assert plist
amount_msat = 0
fee_msat = None
for htlc_with_status in plist:
htlc = htlc_with_status.htlc
_direction = htlc_with_status.direction
amount_msat += int(_direction) * htlc.amount_msat
if _direction == SENT and info and info.amount_msat:
fee_msat = (fee_msat or 0) - info.amount_msat - amount_msat
timestamp = min([htlc_with_status.htlc.timestamp for htlc_with_status in plist])
return amount_msat, fee_msat, timestamp
def get_lightning_history(self):
out = {}
for payment_hash, plist in self.get_payments(status='settled').items():
if len(plist) == 0:
continue
key = payment_hash.hex()
info = self.get_payment_info(payment_hash)
amount_msat, fee_msat, timestamp = self.get_payment_value(info, plist)
if info is not None:
label = self.wallet.get_label(key)
direction = ('sent' if info.direction == SENT else 'received') if len(plist)==1 else 'self-payment'
else:
direction = 'forwarding'
label = _('Forwarding')
preimage = self.get_preimage(payment_hash).hex()
item = {
'type': 'payment',
'label': label,
'timestamp': timestamp or 0,
'date': timestamp_to_datetime(timestamp),
'direction': direction,
'amount_msat': amount_msat,
'fee_msat': fee_msat,
'payment_hash': key,
'preimage': preimage,
}
# add group_id to swap transactions
swap = self.swap_manager.get_swap(payment_hash)
if swap:
if swap.is_reverse:
item['group_id'] = swap.spending_txid
item['group_label'] = 'Reverse swap' + ' ' + self.config.format_amount_and_units(swap.lightning_amount)
else:
item['group_id'] = swap.funding_txid
item['group_label'] = 'Forward swap' + ' ' + self.config.format_amount_and_units(swap.onchain_amount)
# done
out[payment_hash] = item
return out
def get_onchain_history(self):
current_height = self.wallet.get_local_height()
out = {}
# add funding events
for chan in self.channels.values():
item = chan.get_funding_height()
if item is None:
continue
if not self.lnwatcher:
continue # lnwatcher not available with --offline (its data is not persisted)
funding_txid, funding_height, funding_timestamp = item
tx_height = self.lnwatcher.get_tx_height(funding_txid)
item = {
'channel_id': bh2u(chan.channel_id),
'type': 'channel_opening',
'label': self.wallet.get_label_for_txid(funding_txid) or (_('Open channel') + ' ' + chan.get_id_for_log()),
'txid': funding_txid,
'amount_msat': chan.balance(LOCAL, ctn=0),
'direction': 'received',
'timestamp': tx_height.timestamp,
'date': timestamp_to_datetime(tx_height.timestamp),
'fee_sat': None,
'fee_msat': None,
'height': tx_height.height,
'confirmations': tx_height.conf,
}
out[funding_txid] = item
item = chan.get_closing_height()
if item is None:
continue
closing_txid, closing_height, closing_timestamp = item
tx_height = self.lnwatcher.get_tx_height(closing_txid)
item = {
'channel_id': bh2u(chan.channel_id),
'txid': closing_txid,
'label': self.wallet.get_label_for_txid(closing_txid) or (_('Close channel') + ' ' + chan.get_id_for_log()),
'type': 'channel_closure',
'amount_msat': -chan.balance_minus_outgoing_htlcs(LOCAL),
'direction': 'sent',
'timestamp': tx_height.timestamp,
'date': timestamp_to_datetime(tx_height.timestamp),
'fee_sat': None,
'fee_msat': None,
'height': tx_height.height,
'confirmations': tx_height.conf,
}
out[closing_txid] = item
# add info about submarine swaps
settled_payments = self.get_payments(status='settled')
for payment_hash_hex, swap in self.swap_manager.swaps.items():
txid = swap.spending_txid if swap.is_reverse else swap.funding_txid
if txid is None:
continue
payment_hash = bytes.fromhex(payment_hash_hex)
if payment_hash in settled_payments:
plist = settled_payments[payment_hash]
info = self.get_payment_info(payment_hash)
amount_msat, fee_msat, timestamp = self.get_payment_value(info, plist)
else:
amount_msat = 0
label = 'Reverse swap' if swap.is_reverse else 'Forward swap'
delta = current_height - swap.locktime
if not swap.is_redeemed and swap.spending_txid is None and delta < 0:
label += f' (refundable in {-delta} blocks)' # fixme: only if unspent
out[txid] = {
'txid': txid,
'group_id': txid,
'amount_msat': 0,
#'amount_msat': amount_msat, # must not be added
'type': 'swap',
'label': self.wallet.get_label_for_txid(txid) or label,
}
return out
def get_history(self):
out = list(self.get_lightning_history().values()) + list(self.get_onchain_history().values())
# sort by timestamp
out.sort(key=lambda x: (x.get('timestamp') or float("inf")))
balance_msat = 0
for item in out:
balance_msat += item['amount_msat']
item['balance_msat'] = balance_msat
return out
def channel_peers(self) -> List[bytes]:
node_ids = [chan.node_id for chan in self.channels.values() if not chan.is_closed()]
return node_ids
def channels_for_peer(self, node_id):
assert type(node_id) is bytes
return {chan_id: chan for (chan_id, chan) in self.channels.items()
if chan.node_id == node_id}
def channel_state_changed(self, chan: Channel):
if type(chan) is Channel:
self.save_channel(chan)
util.trigger_callback('channel', self.wallet, chan)
def save_channel(self, chan: Channel):
assert type(chan) is Channel
if chan.config[REMOTE].next_per_commitment_point == chan.config[REMOTE].current_per_commitment_point:
raise Exception("Tried to save channel with next_point == current_point, this should not happen")
self.wallet.save_db()
util.trigger_callback('channel', self.wallet, chan)
def channel_by_txo(self, txo: str) -> Optional[AbstractChannel]:
for chan in self.channels.values():
if chan.funding_outpoint.to_str() == txo:
return chan
for chan in self.channel_backups.values():
if chan.funding_outpoint.to_str() == txo:
return chan
async def on_channel_update(self, chan: Channel):
if type(chan) is ChannelBackup:
util.trigger_callback('channel', self.wallet, chan)
return
if chan.get_state() == ChannelState.OPEN and chan.should_be_closed_due_to_expiring_htlcs(self.network.get_local_height()):
self.logger.info(f"force-closing due to expiring htlcs")
await self.schedule_force_closing(chan.channel_id)
elif chan.get_state() == ChannelState.FUNDED:
peer = self._peers.get(chan.node_id)
if peer and peer.is_initialized():
peer.send_funding_locked(chan)
elif chan.get_state() == ChannelState.OPEN:
peer = self._peers.get(chan.node_id)
if peer:
await peer.maybe_update_fee(chan)
conf = self.lnwatcher.get_tx_height(chan.funding_outpoint.txid).conf
peer.on_network_update(chan, conf)
elif chan.get_state() == ChannelState.FORCE_CLOSING:
force_close_tx = chan.force_close_tx()
txid = force_close_tx.txid()
height = self.lnwatcher.get_tx_height(txid).height
if height == TX_HEIGHT_LOCAL:
self.logger.info('REBROADCASTING CLOSING TX')
await self.network.try_broadcasting(force_close_tx, 'force-close')
@log_exceptions
async def _open_channel_coroutine(
self, *,
connect_str: str,
funding_tx: PartialTransaction,
funding_sat: int,
push_sat: int,
password: Optional[str]) -> Tuple[Channel, PartialTransaction]:
peer = await self.add_peer(connect_str)
coro = peer.channel_establishment_flow(
funding_tx=funding_tx,
funding_sat=funding_sat,
push_msat=push_sat * 1000,
temp_channel_id=os.urandom(32))
chan, funding_tx = await asyncio.wait_for(coro, LN_P2P_NETWORK_TIMEOUT)
util.trigger_callback('channels_updated', self.wallet)
self.wallet.add_transaction(funding_tx) # save tx as local into the wallet
self.wallet.sign_transaction(funding_tx, password)
self.wallet.set_label(funding_tx.txid(), _('Open channel'))
if funding_tx.is_complete():
await self.network.try_broadcasting(funding_tx, 'open_channel')
return chan, funding_tx
def add_channel(self, chan: Channel):
with self.lock:
self._channels[chan.channel_id] = chan
self.lnwatcher.add_channel(chan.funding_outpoint.to_str(), chan.get_funding_address())
def add_new_channel(self, chan: Channel):
self.add_channel(chan)
channels_db = self.db.get_dict('channels')
channels_db[chan.channel_id.hex()] = chan.storage
for addr in chan.get_wallet_addresses_channel_might_want_reserved():
self.wallet.set_reserved_state_of_address(addr, reserved=True)
try:
self.save_channel(chan)
backup_dir = self.config.get_backup_dir()
if backup_dir is not None:
self.wallet.save_backup(backup_dir)
except:
chan.set_state(ChannelState.REDEEMED)
self.remove_channel(chan.channel_id)
raise
def cb_data(self, node_id):
return CB_MAGIC_BYTES + node_id[0:16]
def decrypt_cb_data(self, encrypted_data, funding_address):
funding_scripthash = bytes.fromhex(address_to_scripthash(funding_address))
nonce = funding_scripthash[0:12]
return chacha20_decrypt(key=self.backup_key, data=encrypted_data, nonce=nonce)
def encrypt_cb_data(self, data, funding_address):
funding_scripthash = bytes.fromhex(address_to_scripthash(funding_address))
nonce = funding_scripthash[0:12]
return chacha20_encrypt(key=self.backup_key, data=data, nonce=nonce)
def mktx_for_open_channel(
self, *,
coins: Sequence[PartialTxInput],
funding_sat: int,
node_id: bytes,
fee_est=None) -> PartialTransaction:
outputs = [PartialTxOutput.from_address_and_value(ln_dummy_address(), funding_sat)]
if self.has_recoverable_channels():
dummy_scriptpubkey = make_op_return(self.cb_data(node_id))
outputs.append(PartialTxOutput(scriptpubkey=dummy_scriptpubkey, value=0))
tx = self.wallet.make_unsigned_transaction(
coins=coins,
outputs=outputs,
fee=fee_est)
tx.set_rbf(False)
return tx
def open_channel(self, *, connect_str: str, funding_tx: PartialTransaction,
funding_sat: int, push_amt_sat: int, password: str = None) -> Tuple[Channel, PartialTransaction]:
if funding_sat > LN_MAX_FUNDING_SAT:
raise Exception(_("Requested channel capacity is over protocol allowed maximum."))
coro = self._open_channel_coroutine(
connect_str=connect_str, funding_tx=funding_tx, funding_sat=funding_sat,
push_sat=push_amt_sat, password=password)
fut = asyncio.run_coroutine_threadsafe(coro, self.network.asyncio_loop)
try:
chan, funding_tx = fut.result()
except concurrent.futures.TimeoutError:
raise Exception(_("open_channel timed out"))
return chan, funding_tx
def get_channel_by_short_id(self, short_channel_id: bytes) -> Optional[Channel]:
for chan in self.channels.values():
if chan.short_channel_id == short_channel_id:
return chan
@log_exceptions
async def pay_invoice(
self, invoice: str, *,
amount_msat: int = None,
attempts: int = 1,
full_path: LNPaymentPath = None) -> Tuple[bool, List[HtlcLog]]:
lnaddr = self._check_invoice(invoice, amount_msat=amount_msat)
min_cltv_expiry = lnaddr.get_min_final_cltv_expiry()
payment_hash = lnaddr.paymenthash
key = payment_hash.hex()
payment_secret = lnaddr.payment_secret
invoice_pubkey = lnaddr.pubkey.serialize()
invoice_features = lnaddr.get_features()
r_tags = lnaddr.get_routing_info('r')
amount_to_pay = lnaddr.get_amount_msat()
status = self.get_payment_status(payment_hash)
if status == PR_PAID:
raise PaymentFailure(_("This invoice has been paid already"))
if status == PR_INFLIGHT:
raise PaymentFailure(_("A payment was already initiated for this invoice"))
if payment_hash in self.get_payments(status='inflight'):
raise PaymentFailure(_("A previous attempt to pay this invoice did not clear"))
info = PaymentInfo(payment_hash, amount_to_pay, SENT, PR_UNPAID)
self.save_payment_info(info)
self.wallet.set_label(key, lnaddr.get_description())
self.set_invoice_status(key, PR_INFLIGHT)
try:
await self.pay_to_node(
node_pubkey=invoice_pubkey,
payment_hash=payment_hash,
payment_secret=payment_secret,
amount_to_pay=amount_to_pay,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
attempts=attempts,
full_path=full_path)
success = True
except PaymentFailure as e:
self.logger.info(f'payment failure: {e!r}')
success = False
reason = str(e)
if success:
self.set_invoice_status(key, PR_PAID)
util.trigger_callback('payment_succeeded', self.wallet, key)
else:
self.set_invoice_status(key, PR_UNPAID)
util.trigger_callback('payment_failed', self.wallet, key, reason)
log = self.logs[key]
return success, log
async def pay_to_node(
self, *,
node_pubkey: bytes,
payment_hash: bytes,
payment_secret: Optional[bytes],
amount_to_pay: int, # in msat
min_cltv_expiry: int,
r_tags,
invoice_features: int,
attempts: int = 1,
full_path: LNPaymentPath = None,
fwd_trampoline_onion=None,
fwd_trampoline_fee=None,
fwd_trampoline_cltv_delta=None) -> None:
if fwd_trampoline_onion:
# todo: compare to the fee of the actual route we found
if fwd_trampoline_fee < 1000:
raise OnionRoutingFailure(code=OnionFailureCode.TRAMPOLINE_FEE_INSUFFICIENT, data=b'')
if fwd_trampoline_cltv_delta < 576:
raise OnionRoutingFailure(code=OnionFailureCode.TRAMPOLINE_EXPIRY_TOO_SOON, data=b'')
self.logs[payment_hash.hex()] = log = []
# when encountering trampoline forwarding difficulties in the legacy case, we
# sometimes need to fall back to a single trampoline forwarder, at the expense
# of privacy
use_two_trampolines = True
trampoline_fee_level = self.INITIAL_TRAMPOLINE_FEE_LEVEL
amount_inflight = 0 # what we sent in htlcs (that receiver gets, without fees)
while True:
amount_to_send = amount_to_pay - amount_inflight
if amount_to_send > 0:
# 1. create a set of routes for remaining amount.
# note: path-finding runs in a separate thread so that we don't block the asyncio loop
routes = self.create_routes_for_payment(
amount_msat=amount_to_send,
final_total_msat=amount_to_pay,
invoice_pubkey=node_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
full_path=full_path,
payment_hash=payment_hash,
payment_secret=payment_secret,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines,
fwd_trampoline_onion=fwd_trampoline_onion
)
async for route, amount_msat, total_msat, amount_receiver_msat, cltv_delta, bucket_payment_secret, trampoline_onion in routes:
amount_inflight += amount_receiver_msat
if amount_inflight > amount_to_pay:
raise Exception(f"amount_inflight={amount_inflight} > amount_to_pay={amount_to_pay}")
await self.pay_to_route(
route=route,
amount_msat=amount_msat,
total_msat=total_msat,
amount_receiver_msat=amount_receiver_msat,
payment_hash=payment_hash,
payment_secret=bucket_payment_secret,
min_cltv_expiry=cltv_delta,
trampoline_onion=trampoline_onion,
trampoline_fee_level=trampoline_fee_level)
util.trigger_callback('invoice_status', self.wallet, payment_hash.hex())
self.logger.info(f"amount inflight {amount_inflight}")
htlc_log = await self.sent_htlcs[payment_hash].get()
amount_inflight -= htlc_log.amount_msat
if amount_inflight < 0:
raise Exception(f"amount_inflight={amount_inflight} < 0")
log.append(htlc_log)
if htlc_log.success:
if self.network.path_finder:
self.network.path_finder.update_liquidity_hints(htlc_log.route, htlc_log.amount_msat)
self.network.path_finder.update_inflight_htlcs(htlc_log.route, add_htlcs=False)
return
if len(log) >= attempts:
raise PaymentFailure('Giving up after %d attempts'%len(log))
route = htlc_log.route
sender_idx = htlc_log.sender_idx
erring_node_id = route[sender_idx].node_id
failure_msg = htlc_log.failure_msg
code, data = failure_msg.code, failure_msg.data
self.logger.info(f"UPDATE_FAIL_HTLC. code={repr(code)}. "
f"decoded_data={failure_msg.decode_data()}. data={data.hex()!r}")
self.logger.info(f"error reported by {bh2u(erring_node_id)}")
if code == OnionFailureCode.MPP_TIMEOUT:
raise PaymentFailure(failure_msg.code_name())
if not self.channel_db:
if code in (OnionFailureCode.TRAMPOLINE_FEE_INSUFFICIENT,
OnionFailureCode.TRAMPOLINE_EXPIRY_TOO_SOON):
if htlc_log.trampoline_fee_level == trampoline_fee_level:
trampoline_fee_level += 1
self.logger.info(f'raising trampoline fee level {trampoline_fee_level}')
else:
self.logger.info(f'NOT raising trampoline fee level, already at {trampoline_fee_level}')
continue
elif use_two_trampolines:
use_two_trampolines = False
elif code in (OnionFailureCode.UNKNOWN_NEXT_PEER,
OnionFailureCode.TEMPORARY_NODE_FAILURE):
continue
else:
raise PaymentFailure(failure_msg.code_name())
else:
self.handle_error_code_from_failed_htlc(
route=route, sender_idx=sender_idx, failure_msg=failure_msg, amount=htlc_log.amount_msat)
async def pay_to_route(
self, *,
route: LNPaymentRoute,
amount_msat: int,
total_msat: int,
amount_receiver_msat:int,
payment_hash: bytes,
payment_secret: Optional[bytes],
min_cltv_expiry: int,
trampoline_onion: bytes = None,
trampoline_fee_level: int) -> None:
# send a single htlc
short_channel_id = route[0].short_channel_id
chan = self.get_channel_by_short_id(short_channel_id)
peer = self._peers.get(route[0].node_id)
if not peer:
raise PaymentFailure('Dropped peer')
await peer.initialized
htlc = peer.pay(
route=route,
chan=chan,
amount_msat=amount_msat,
total_msat=total_msat,
payment_hash=payment_hash,
min_final_cltv_expiry=min_cltv_expiry,
payment_secret=payment_secret,
trampoline_onion=trampoline_onion)
key = (payment_hash, short_channel_id, htlc.htlc_id)
self.sent_htlcs_info[key] = route, payment_secret, amount_msat, total_msat, amount_receiver_msat, trampoline_fee_level
# if we sent MPP to a trampoline, add item to sent_buckets
if not self.channel_db and amount_msat != total_msat:
if payment_secret not in self.sent_buckets:
self.sent_buckets[payment_secret] = (0, 0)
amount_sent, amount_failed = self.sent_buckets[payment_secret]
amount_sent += amount_receiver_msat
self.sent_buckets[payment_secret] = amount_sent, amount_failed
if self.network.path_finder:
# add inflight htlcs to liquidity hints
self.network.path_finder.update_inflight_htlcs(route, add_htlcs=True)
util.trigger_callback('htlc_added', chan, htlc, SENT)
def handle_error_code_from_failed_htlc(
self,
*,
route: LNPaymentRoute,
sender_idx: int,
failure_msg: OnionRoutingFailure,
amount: int) -> None:
assert self.channel_db # cannot be in trampoline mode
assert self.network.path_finder
# remove inflight htlcs from liquidity hints
self.network.path_finder.update_inflight_htlcs(route, add_htlcs=False)
code, data = failure_msg.code, failure_msg.data
# TODO can we use lnmsg.OnionWireSerializer here?
# TODO update onion_wire.csv
# handle some specific error codes
failure_codes = {
OnionFailureCode.TEMPORARY_CHANNEL_FAILURE: 0,
OnionFailureCode.AMOUNT_BELOW_MINIMUM: 8,
OnionFailureCode.FEE_INSUFFICIENT: 8,
OnionFailureCode.INCORRECT_CLTV_EXPIRY: 4,
OnionFailureCode.EXPIRY_TOO_SOON: 0,
OnionFailureCode.CHANNEL_DISABLED: 2,
}
# determine a fallback channel to blacklist if we don't get the erring
if sender_idx is None:
raise PaymentFailure(failure_msg.code_name())
try:
fallback_channel = route[sender_idx + 1].short_channel_id
except IndexError:
raise PaymentFailure(f'payment destination reported error: {failure_msg.code_name()}') from None
if code in failure_codes:
offset = failure_codes[code]
channel_update_len = int.from_bytes(data[offset:offset+2], byteorder="big")
channel_update_as_received = data[offset+2: offset+2+channel_update_len]
payload = self._decode_channel_update_msg(channel_update_as_received)
if payload is None:
self.logger.info(f'could not decode channel_update for failed htlc: '
f'{channel_update_as_received.hex()}')
self.network.path_finder.liquidity_hints.add_to_blacklist(fallback_channel)
else:
blacklist, update = self._handle_chanupd_from_failed_htlc(
payload, route=route, sender_idx=sender_idx)
if code == OnionFailureCode.TEMPORARY_CHANNEL_FAILURE:
self.network.path_finder.update_liquidity_hints(
route,
amount,
failing_channel=ShortChannelID(payload['short_channel_id']))
elif blacklist:
self.network.path_finder.liquidity_hints.add_to_blacklist(
payload['short_channel_id'])
if not (blacklist or update):
raise PaymentFailure(failure_msg.code_name())
# for errors that do not include a channel update
else:
self.network.path_finder.liquidity_hints.add_to_blacklist(fallback_channel)
def _handle_chanupd_from_failed_htlc(self, payload, *, route, sender_idx) -> Tuple[bool, bool]:
blacklist = False
update = False
try:
r = self.channel_db.add_channel_update(payload, verify=True)
except InvalidGossipMsg:
return True, False # blacklist
short_channel_id = ShortChannelID(payload['short_channel_id'])
if r == UpdateStatus.GOOD:
self.logger.info(f"applied channel update to {short_channel_id}")
# TODO: add test for this
# FIXME: this does not work for our own unannounced channels.
for chan in self.channels.values():
if chan.short_channel_id == short_channel_id:
chan.set_remote_update(payload)
update = True
elif r == UpdateStatus.ORPHANED:
# maybe it is a private channel (and data in invoice was outdated)
self.logger.info(f"Could not find {short_channel_id}. maybe update is for private channel?")
start_node_id = route[sender_idx].node_id
update = self.channel_db.add_channel_update_for_private_channel(payload, start_node_id)
blacklist = not update
elif r == UpdateStatus.EXPIRED:
blacklist = True
elif r == UpdateStatus.DEPRECATED:
self.logger.info(f'channel update is not more recent.')
blacklist = True
elif r == UpdateStatus.UNCHANGED:
blacklist = True
return blacklist, update
@classmethod
def _decode_channel_update_msg(cls, chan_upd_msg: bytes) -> Optional[Dict[str, Any]]:
channel_update_as_received = chan_upd_msg
channel_update_typed = (258).to_bytes(length=2, byteorder="big") + channel_update_as_received
# note: some nodes put channel updates in error msgs with the leading msg_type already there.
# we try decoding both ways here.
try:
message_type, payload = decode_msg(channel_update_typed)
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_typed
return payload
except: # FIXME: too broad
try:
message_type, payload = decode_msg(channel_update_as_received)
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_as_received
return payload
except:
return None
@staticmethod
def _check_invoice(invoice: str, *, amount_msat: int = None) -> LnAddr:
addr = lndecode(invoice)
if addr.is_expired():
raise InvoiceError(_("This invoice has expired"))
if amount_msat: # replace amt in invoice. main usecase is paying zero amt invoices
existing_amt_msat = addr.get_amount_msat()
if existing_amt_msat and amount_msat < existing_amt_msat:
raise Exception("cannot pay lower amt than what is originally in LN invoice")
addr.amount = Decimal(amount_msat) / COIN / 1000
if addr.amount is None:
raise InvoiceError(_("Missing amount"))
if addr.get_min_final_cltv_expiry() > lnutil.NBLOCK_CLTV_EXPIRY_TOO_FAR_INTO_FUTURE:
raise InvoiceError("{}\n{}".format(
_("Invoice wants us to risk locking funds for unreasonably long."),
f"min_final_cltv_expiry: {addr.get_min_final_cltv_expiry()}"))
return addr
def is_trampoline_peer(self, node_id: bytes) -> bool:
# until trampoline is advertised in lnfeatures, check against hardcoded list
if is_hardcoded_trampoline(node_id):
return True
peer = self._peers.get(node_id)
if peer and peer.their_features.supports(LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT):
return True
return False
def suggest_peer(self) -> Optional[bytes]:
if self.channel_db:
return self.lnrater.suggest_peer()
else:
return random.choice(list(hardcoded_trampoline_nodes().values())).pubkey
async def create_routes_for_payment(
self, *,
amount_msat: int, # part of payment amount we want routes for now
final_total_msat: int, # total payment amount final receiver will get
invoice_pubkey,
min_cltv_expiry,
r_tags,
invoice_features: int,
payment_hash,
payment_secret,
trampoline_fee_level: int,
use_two_trampolines: bool,
fwd_trampoline_onion=None,
full_path: LNPaymentPath = None) -> AsyncGenerator[Tuple[LNPaymentRoute, int], None]:
invoice_features = LnFeatures(invoice_features)
trampoline_features = LnFeatures.VAR_ONION_OPT
local_height = self.network.get_local_height()
my_active_channels = [chan for chan in self.channels.values() if
chan.is_active() and not chan.is_frozen_for_sending()]
try:
self.logger.info("trying single-part payment")
# try to send over a single channel
if not self.channel_db:
for chan in my_active_channels:
if not self.is_trampoline_peer(chan.node_id):
continue
if chan.node_id == invoice_pubkey:
trampoline_onion = None
trampoline_payment_secret = payment_secret
trampoline_total_msat = final_total_msat
amount_with_fees = amount_msat
cltv_delta = min_cltv_expiry
else:
trampoline_onion, amount_with_fees, cltv_delta = create_trampoline_route_and_onion(
amount_msat=amount_msat,
total_msat=final_total_msat,
min_cltv_expiry=min_cltv_expiry,
my_pubkey=self.node_keypair.pubkey,
invoice_pubkey=invoice_pubkey,
invoice_features=invoice_features,
node_id=chan.node_id,
r_tags=r_tags,
payment_hash=payment_hash,
payment_secret=payment_secret,
local_height=local_height,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines)
trampoline_payment_secret = os.urandom(32)
trampoline_total_msat = amount_with_fees
if chan.available_to_spend(LOCAL, strict=True) < amount_with_fees:
continue
route = [
RouteEdge(
start_node=self.node_keypair.pubkey,
end_node=chan.node_id,
short_channel_id=chan.short_channel_id,
fee_base_msat=0,
fee_proportional_millionths=0,
cltv_expiry_delta=0,
node_features=trampoline_features)
]
yield route, amount_with_fees, trampoline_total_msat, amount_msat, cltv_delta, trampoline_payment_secret, trampoline_onion
break
else:
raise NoPathFound()
else: # local single-part route computation
route = await run_in_thread(
partial(
self.create_route_for_payment,
amount_msat=amount_msat,
invoice_pubkey=invoice_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
my_sending_channels=my_active_channels,
full_path=full_path
)
)
yield route, amount_msat, final_total_msat, amount_msat, min_cltv_expiry, payment_secret, fwd_trampoline_onion
except NoPathFound: # fall back to payment splitting
self.logger.info("no path found, trying multi-part payment")
if not invoice_features.supports(LnFeatures.BASIC_MPP_OPT):
raise
channels_with_funds = {(chan.channel_id, chan.node_id): int(chan.available_to_spend(HTLCOwner.LOCAL))
for chan in my_active_channels}
self.logger.info(f"channels_with_funds: {channels_with_funds}")
if not self.channel_db:
# in the case of a legacy payment, we don't allow splitting via different
use_single_node, _ = is_legacy_relay(invoice_features, r_tags)
split_configurations = suggest_splits(
amount_msat,
channels_with_funds,
exclude_multinode_payments=use_single_node,
exclude_single_part_payments=True,
# the trampoline node will split for us
exclude_single_channel_splits=True,
)
self.logger.info(f'suggest_split {amount_msat} returned {len(split_configurations)} configurations')
for sc in split_configurations:
try:
self.logger.info(f"trying split configuration: {sc.config.values()} rating: {sc.rating}")
per_trampoline_channel_amounts = defaultdict(list)
# categorize by trampoline nodes for trampolin mpp construction
for (chan_id, _), part_amounts_msat in sc.config.items():
chan = self.channels[chan_id]
for part_amount_msat in part_amounts_msat:
per_trampoline_channel_amounts[chan.node_id].append((chan_id, part_amount_msat))
# for each trampoline forwarder, construct mpp trampoline
routes = []
for trampoline_node_id, trampoline_parts in per_trampoline_channel_amounts.items():
per_trampoline_amount = sum([x[1] for x in trampoline_parts])
trampoline_onion, per_trampoline_amount_with_fees, per_trampoline_cltv_delta = create_trampoline_route_and_onion(
amount_msat=per_trampoline_amount,
total_msat=final_total_msat,
min_cltv_expiry=min_cltv_expiry,
my_pubkey=self.node_keypair.pubkey,
invoice_pubkey=invoice_pubkey,
invoice_features=invoice_features,
node_id=trampoline_node_id,
r_tags=r_tags,
payment_hash=payment_hash,
payment_secret=payment_secret,
local_height=local_height,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines)
# node_features is only used to determine is_tlv
per_trampoline_secret = os.urandom(32)
per_trampoline_fees = per_trampoline_amount_with_fees - per_trampoline_amount
self.logger.info(f'per trampoline fees: {per_trampoline_fees}')
for chan_id, part_amount_msat in trampoline_parts:
chan = self.channels[chan_id]
margin = chan.available_to_spend(LOCAL, strict=True) - part_amount_msat
delta_fee = min(per_trampoline_fees, margin)
# TODO: distribute trampoline fee over several channels?
part_amount_msat_with_fees = part_amount_msat + delta_fee
per_trampoline_fees -= delta_fee
route = [
RouteEdge(
start_node=self.node_keypair.pubkey,
end_node=trampoline_node_id,
short_channel_id=chan.short_channel_id,
fee_base_msat=0,
fee_proportional_millionths=0,
cltv_expiry_delta=0,
node_features=trampoline_features)
]
self.logger.info(f'adding route {part_amount_msat} {delta_fee} {margin}')
routes.append((route, part_amount_msat_with_fees, per_trampoline_amount_with_fees, part_amount_msat, per_trampoline_cltv_delta, per_trampoline_secret, trampoline_onion))
if per_trampoline_fees != 0:
self.logger.info('not enough margin to pay trampoline fee')
raise NoPathFound()
for route in routes:
yield route
return
except NoPathFound:
continue
else:
split_configurations = suggest_splits(
amount_msat,
channels_with_funds,
exclude_single_part_payments=True,
)
# We atomically loop through a split configuration. If there was
# a failure to find a path for a single part, we give back control
# after exhausting the split configuration.
yielded_from_split_configuration = False
self.logger.info(f'suggest_split {amount_msat} returned {len(split_configurations)} configurations')
for sc in split_configurations:
self.logger.info(f"trying split configuration: {list(sc.config.values())} rating: {sc.rating}")
for (chan_id, _), part_amounts_msat in sc.config.items():
for part_amount_msat in part_amounts_msat:
channel = self.channels[chan_id]
try:
route = await run_in_thread(
partial(
self.create_route_for_payment,
amount_msat=part_amount_msat,
invoice_pubkey=invoice_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
my_sending_channels=[channel],
full_path=None
)
)
yield route, part_amount_msat, final_total_msat, part_amount_msat, min_cltv_expiry, payment_secret, fwd_trampoline_onion
yielded_from_split_configuration = True
except NoPathFound:
continue
if yielded_from_split_configuration:
return
raise NoPathFound()
@profiler
def create_route_for_payment(
self, *,
amount_msat: int,
invoice_pubkey: bytes,
min_cltv_expiry: int,
r_tags,
invoice_features: int,
my_sending_channels: List[Channel],
full_path: Optional[LNPaymentPath]) -> LNPaymentRoute:
my_sending_channels = {chan.short_channel_id: chan for chan in my_sending_channels
if chan.short_channel_id is not None}
# Collect all private edges from route hints.
# Note: if some route hints are multiple edges long, and these paths cross each other,
# we allow our path finding to cross the paths; i.e. the route hints are not isolated.
private_route_edges = {} # type: Dict[ShortChannelID, RouteEdge]
for private_path in r_tags:
# we need to shift the node pubkey by one towards the destination:
private_path_nodes = [edge[0] for edge in private_path][1:] + [invoice_pubkey]
private_path_rest = [edge[1:] for edge in private_path]
start_node = private_path[0][0]
for end_node, edge_rest in zip(private_path_nodes, private_path_rest):
short_channel_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta = edge_rest
short_channel_id = ShortChannelID(short_channel_id)
# if we have a routing policy for this edge in the db, that takes precedence,
# as it is likely from a previous failure
channel_policy = self.channel_db.get_policy_for_node(
short_channel_id=short_channel_id,
node_id=start_node,
my_channels=my_sending_channels)
if channel_policy:
fee_base_msat = channel_policy.fee_base_msat
fee_proportional_millionths = channel_policy.fee_proportional_millionths
cltv_expiry_delta = channel_policy.cltv_expiry_delta
node_info = self.channel_db.get_node_info_for_node_id(node_id=end_node)
route_edge = RouteEdge(
start_node=start_node,
end_node=end_node,
short_channel_id=short_channel_id,
fee_base_msat=fee_base_msat,
fee_proportional_millionths=fee_proportional_millionths,
cltv_expiry_delta=cltv_expiry_delta,
node_features=node_info.features if node_info else 0)
private_route_edges[route_edge.short_channel_id] = route_edge
start_node = end_node
# now find a route, end to end: between us and the recipient
try:
route = self.network.path_finder.find_route(
nodeA=self.node_keypair.pubkey,
nodeB=invoice_pubkey,
invoice_amount_msat=amount_msat,
path=full_path,
my_sending_channels=my_sending_channels,
private_route_edges=private_route_edges)
except NoChannelPolicy as e:
raise NoPathFound() from e
if not route:
raise NoPathFound()
# test sanity
if not is_route_sane_to_use(route, amount_msat, min_cltv_expiry):
self.logger.info(f"rejecting insane route {route}")
raise NoPathFound()
assert len(route) > 0
if route[-1].end_node != invoice_pubkey:
raise LNPathInconsistent("last node_id != invoice pubkey")
# add features from invoice
route[-1].node_features |= invoice_features
return route
def add_request(self, amount_sat, message, expiry) -> str:
coro = self._add_request_coro(amount_sat, message, expiry)
fut = asyncio.run_coroutine_threadsafe(coro, self.network.asyncio_loop)
try:
return fut.result(timeout=5)
except concurrent.futures.TimeoutError:
raise Exception(_("add invoice timed out"))
@log_exceptions
async def create_invoice(
self, *,
amount_msat: Optional[int],
message: str,
expiry: int,
write_to_disk: bool = True,
) -> Tuple[LnAddr, str]:
timestamp = int(time.time())
routing_hints = await self._calc_routing_hints_for_invoice(amount_msat)
if not routing_hints:
self.logger.info(
"Warning. No routing hints added to invoice. "
"Other clients will likely not be able to send to us.")
# if not all hints are trampoline, do not create trampoline invoice
invoice_features = self.features.for_invoice()
trampoline_hints = []
for r in routing_hints:
node_id, short_channel_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta = r[1][0]
if len(r[1])== 1 and self.is_trampoline_peer(node_id):
trampoline_hints.append(('t', (node_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta)))
payment_preimage = os.urandom(32)
payment_hash = sha256(payment_preimage)
info = PaymentInfo(payment_hash, amount_msat, RECEIVED, PR_UNPAID)
amount_btc = amount_msat/Decimal(COIN*1000) if amount_msat else None
if expiry == 0:
expiry = LN_EXPIRY_NEVER
lnaddr = LnAddr(
paymenthash=payment_hash,
amount=amount_btc,
tags=[
('d', message),
('c', MIN_FINAL_CLTV_EXPIRY_FOR_INVOICE),
('x', expiry),
('9', invoice_features)]
+ routing_hints
+ trampoline_hints,
date=timestamp,
payment_secret=derive_payment_secret_from_payment_preimage(payment_preimage))
invoice = lnencode(lnaddr, self.node_keypair.privkey)
self.save_preimage(payment_hash, payment_preimage, write_to_disk=False)
self.save_payment_info(info, write_to_disk=False)
if write_to_disk:
self.wallet.save_db()
return lnaddr, invoice
async def _add_request_coro(self, amount_sat: Optional[int], message, expiry: int) -> str:
amount_msat = amount_sat * 1000 if amount_sat is not None else None
lnaddr, invoice = await self.create_invoice(
amount_msat=amount_msat,
message=message,
expiry=expiry,
write_to_disk=False,
)
key = bh2u(lnaddr.paymenthash)
req = LNInvoice.from_bech32(invoice)
self.wallet.add_payment_request(req, write_to_disk=False)
self.wallet.set_label(key, message)
self.wallet.save_db()
return key
def save_preimage(self, payment_hash: bytes, preimage: bytes, *, write_to_disk: bool = True):
assert sha256(preimage) == payment_hash
self.preimages[bh2u(payment_hash)] = bh2u(preimage)
if write_to_disk:
self.wallet.save_db()
def get_preimage(self, payment_hash: bytes) -> Optional[bytes]:
r = self.preimages.get(bh2u(payment_hash))
return bfh(r) if r else None
def get_payment_info(self, payment_hash: bytes) -> Optional[PaymentInfo]:
key = payment_hash.hex()
with self.lock:
if key in self.payments:
amount_msat, direction, status = self.payments[key]
return PaymentInfo(payment_hash, amount_msat, direction, status)
def save_payment_info(self, info: PaymentInfo, *, write_to_disk: bool = True) -> None:
key = info.payment_hash.hex()
assert info.status in SAVED_PR_STATUS
with self.lock:
self.payments[key] = info.amount_msat, info.direction, info.status
if write_to_disk:
self.wallet.save_db()
def check_received_mpp_htlc(self, payment_secret, short_channel_id, htlc: UpdateAddHtlc, expected_msat: int) -> Optional[bool]:
payment_hash = htlc.payment_hash
is_expired, is_accepted, htlc_set = self.received_mpp_htlcs.get(payment_secret, (False, False, set()))
if self.get_payment_status(payment_hash) == PR_PAID:
# payment_status is persisted
is_accepted = True
is_expired = False
key = (short_channel_id, htlc)
if key not in htlc_set:
htlc_set.add(key)
if not is_accepted and not is_expired:
total = sum([_htlc.amount_msat for scid, _htlc in htlc_set])
first_timestamp = min([_htlc.timestamp for scid, _htlc in htlc_set])
if self.stopping_soon:
is_expired = True # try to time out pending HTLCs before shutting down
elif time.time() - first_timestamp > self.MPP_EXPIRY:
is_expired = True
elif total == expected_msat:
is_accepted = True
if is_accepted or is_expired:
htlc_set.remove(key)
if len(htlc_set) > 0:
self.received_mpp_htlcs[payment_secret] = is_expired, is_accepted, htlc_set
elif payment_secret in self.received_mpp_htlcs:
self.received_mpp_htlcs.pop(payment_secret)
return True if is_accepted else (False if is_expired else None)
def get_payment_status(self, payment_hash: bytes) -> int:
info = self.get_payment_info(payment_hash)
return info.status if info else PR_UNPAID
def get_invoice_status(self, invoice: LNInvoice) -> int:
key = invoice.rhash
log = self.logs[key]
if key in self.inflight_payments:
return PR_INFLIGHT
# status may be PR_FAILED
status = self.get_payment_status(bfh(key))
if status == PR_UNPAID and log:
status = PR_FAILED
return status
def set_invoice_status(self, key: str, status: int) -> None:
if status == PR_INFLIGHT:
self.inflight_payments.add(key)
elif key in self.inflight_payments:
self.inflight_payments.remove(key)
if status in SAVED_PR_STATUS:
self.set_payment_status(bfh(key), status)
util.trigger_callback('invoice_status', self.wallet, key)
def set_request_status(self, payment_hash: bytes, status: int) -> None:
if self.get_payment_status(payment_hash) != status:
self.set_payment_status(payment_hash, status)
util.trigger_callback('request_status', self.wallet, payment_hash.hex(), status)
def set_payment_status(self, payment_hash: bytes, status: int) -> None:
info = self.get_payment_info(payment_hash)
if info is None:
# if we are forwarding
return
info = info._replace(status=status)
self.save_payment_info(info)
def _on_maybe_forwarded_htlc_resolved(self, chan: Channel, htlc_id: int) -> None:
fw_info = chan.short_channel_id.hex(), htlc_id
upstream_peer_pubkey = self.downstream_htlc_to_upstream_peer_map.get(fw_info)
if not upstream_peer_pubkey:
return
upstream_peer = self.peers.get(upstream_peer_pubkey)
if not upstream_peer:
return
upstream_peer.downstream_htlc_resolved_event.set()
upstream_peer.downstream_htlc_resolved_event.clear()
def htlc_fulfilled(self, chan: Channel, payment_hash: bytes, htlc_id: int):
util.trigger_callback('htlc_fulfilled', payment_hash, chan, htlc_id)
self._on_maybe_forwarded_htlc_resolved(chan=chan, htlc_id=htlc_id)
q = self.sent_htlcs.get(payment_hash)
if q:
route, payment_secret, amount_msat, bucket_msat, amount_receiver_msat, trampoline_fee_level = self.sent_htlcs_info[(payment_hash, chan.short_channel_id, htlc_id)]
htlc_log = HtlcLog(
success=True,
route=route,
amount_msat=amount_receiver_msat,
trampoline_fee_level=trampoline_fee_level)
q.put_nowait(htlc_log)
else:
key = payment_hash.hex()
self.set_invoice_status(key, PR_PAID)
util.trigger_callback('payment_succeeded', self.wallet, key)
def htlc_failed(
self,
chan: Channel,
payment_hash: bytes,
htlc_id: int,
error_bytes: Optional[bytes],
failure_message: Optional['OnionRoutingFailure']):
util.trigger_callback('htlc_failed', payment_hash, chan, htlc_id)
self._on_maybe_forwarded_htlc_resolved(chan=chan, htlc_id=htlc_id)
q = self.sent_htlcs.get(payment_hash)
if q:
# detect if it is part of a bucket
# if yes, wait until the bucket completely failed
key = (payment_hash, chan.short_channel_id, htlc_id)
route, payment_secret, amount_msat, bucket_msat, amount_receiver_msat, trampoline_fee_level = self.sent_htlcs_info[key]
if error_bytes:
# TODO "decode_onion_error" might raise, catch and maybe blacklist/penalise someone?
try:
failure_message, sender_idx = chan.decode_onion_error(error_bytes, route, htlc_id)
except Exception as e:
sender_idx = None
failure_message = OnionRoutingFailure(-1, str(e))
else:
# probably got "update_fail_malformed_htlc". well... who to penalise now?
assert failure_message is not None
sender_idx = None
self.logger.info(f"htlc_failed {failure_message}")
# check sent_buckets if we use trampoline
if not self.channel_db and payment_secret in self.sent_buckets:
amount_sent, amount_failed = self.sent_buckets[payment_secret]
amount_failed += amount_receiver_msat
self.sent_buckets[payment_secret] = amount_sent, amount_failed
if amount_sent != amount_failed:
self.logger.info('bucket still active...')
return
self.logger.info('bucket failed')
amount_receiver_msat = amount_sent
htlc_log = HtlcLog(
success=False,
route=route,
amount_msat=amount_receiver_msat,
error_bytes=error_bytes,
failure_msg=failure_message,
sender_idx=sender_idx,
trampoline_fee_level=trampoline_fee_level)
q.put_nowait(htlc_log)
else:
self.logger.info(f"received unknown htlc_failed, probably from previous session")
key = payment_hash.hex()
self.set_invoice_status(key, PR_UNPAID)
util.trigger_callback('payment_failed', self.wallet, key, '')
async def _calc_routing_hints_for_invoice(self, amount_msat: Optional[int]):
routing_hints = []
channels = list(self.channels.values())
# do minimal filtering of channels.
# we include channels that cannot *right now* receive (e.g. peer disconnected or balance insufficient)
channels = [chan for chan in channels
if (chan.is_open() and not chan.is_frozen_for_receiving())]
# Filter out channels that have very low receive capacity compared to invoice amt.
# Even with MPP, below a certain threshold, including these channels probably
# hurts more than help, as they lead to many failed attempts for the sender.
channels = [chan for chan in channels
if chan.available_to_spend(REMOTE) > (amount_msat or 0) * 0.05]
# cap max channels to include to keep QR code reasonably scannable
channels = sorted(channels, key=lambda chan: (not chan.is_active(), -chan.available_to_spend(REMOTE)))
channels = channels[:15]
random.shuffle(channels) # let's not leak channel order
scid_to_my_channels = {chan.short_channel_id: chan for chan in channels
if chan.short_channel_id is not None}
for chan in channels:
chan_id = chan.short_channel_id
assert isinstance(chan_id, bytes), chan_id
channel_info = get_mychannel_info(chan_id, scid_to_my_channels)
# incoming direction of our private channel, we fill the invoice with garbage.
# the sender should still be able to pay us, but will incur an extra round trip
# (they will get the channel update from the onion error)
# at least, that's the theory. https://github.com/lightningnetwork/lnd/issues/2066
fee_base_msat = fee_proportional_millionths = 0
cltv_expiry_delta = 1
missing_info = True
if channel_info:
policy = get_mychannel_policy(channel_info.short_channel_id, chan.node_id, scid_to_my_channels)
if policy:
fee_base_msat = policy.fee_base_msat
fee_proportional_millionths = policy.fee_proportional_millionths
cltv_expiry_delta = policy.cltv_expiry_delta
missing_info = False
if missing_info:
self.logger.info(
f"Warning. Missing channel update for our channel {chan_id}; "
f"filling invoice with incorrect data.")
routing_hints.append(('r', [(
chan.node_id,
chan_id,
fee_base_msat,
fee_proportional_millionths,
cltv_expiry_delta)]))
return routing_hints
def delete_payment(self, payment_hash_hex: str):
try:
with self.lock:
del self.payments[payment_hash_hex]
except KeyError:
return
self.wallet.save_db()
def get_balance(self):
with self.lock:
return Decimal(sum(
chan.balance(LOCAL) if not chan.is_closed() else 0
for chan in self.channels.values())) / 1000
def num_sats_can_send(self) -> Decimal:
can_send = 0
with self.lock:
if self.channels:
for c in self.channels.values():
if c.is_active() and not c.is_frozen_for_sending():
can_send += c.available_to_spend(LOCAL)
# Here we have to guess a fee, because some callers (submarine swaps)
# use this method to initiate a payment, which would otherwise fail.
fee_base_msat = TRAMPOLINE_FEES[3]['fee_base_msat']
fee_proportional_millionths = TRAMPOLINE_FEES[3]['fee_proportional_millionths']
# inverse of fee_for_edge_msat
can_send_minus_fees = (can_send - fee_base_msat) * 1_000_000 // ( 1_000_000 + fee_proportional_millionths)
can_send_minus_fees = max(0, can_send_minus_fees)
return Decimal(can_send_minus_fees) / 1000
def num_sats_can_receive(self) -> Decimal:
with self.lock:
channels = [
c for c in self.channels.values()
if c.is_active() and not c.is_frozen_for_receiving()
]
can_receive = sum([c.available_to_spend(REMOTE) for c in channels]) if channels else 0
return Decimal(can_receive) / 1000
def num_sats_can_receive_no_mpp(self) -> Decimal:
with self.lock:
channels = [
c for c in self.channels.values()
if c.is_active() and not c.is_frozen_for_receiving()
]
can_receive = max([c.available_to_spend(REMOTE) for c in channels]) if channels else 0
return Decimal(can_receive) / 1000
def can_pay_invoice(self, invoice: LNInvoice) -> bool:
return invoice.get_amount_sat() <= self.num_sats_can_send()
def can_receive_invoice(self, invoice: LNInvoice) -> bool:
return invoice.get_amount_sat() <= self.num_sats_can_receive()
async def close_channel(self, chan_id):
chan = self._channels[chan_id]
peer = self._peers[chan.node_id]
return await peer.close_channel(chan_id)
def _force_close_channel(self, chan_id: bytes) -> Transaction:
chan = self._channels[chan_id]
tx = chan.force_close_tx()
# We set the channel state to make sure we won't sign new commitment txs.
chan.set_state(ChannelState.FORCE_CLOSING)
try:
self.wallet.add_transaction(tx)
except UnrelatedTransactionException:
pass
return tx
async def force_close_channel(self, chan_id: bytes) -> str:
tx = self._force_close_channel(chan_id)
await self.network.broadcast_transaction(tx)
return tx.txid()
def schedule_force_closing(self, chan_id: bytes) -> 'asyncio.Task[None]':
tx = self._force_close_channel(chan_id)
return asyncio.create_task(self.network.try_broadcasting(tx, 'force-close'))
def remove_channel(self, chan_id):
chan = self.channels[chan_id]
assert chan.can_be_deleted()
with self.lock:
self._channels.pop(chan_id)
self.db.get('channels').pop(chan_id.hex())
for addr in chan.get_wallet_addresses_channel_might_want_reserved():
self.wallet.set_reserved_state_of_address(addr, reserved=False)
util.trigger_callback('channels_updated', self.wallet)
util.trigger_callback('wallet_updated', self.wallet)
@ignore_exceptions
@log_exceptions
async def reestablish_peer_for_given_channel(self, chan: Channel) -> None:
now = time.time()
peer_addresses = []
if not self.channel_db:
addr = trampolines_by_id().get(chan.node_id)
if addr:
peer_addresses.append(addr)
else:
last_good_addr = self.channel_db.get_last_good_address(chan.node_id)
if last_good_addr:
peer_addresses.append(last_good_addr)
addrs_from_gossip = self.channel_db.get_node_addresses(chan.node_id) or []
for host, port, ts in addrs_from_gossip:
peer_addresses.append(LNPeerAddr(host, port, chan.node_id))
peer_addresses += list(chan.get_peer_addresses())
for peer in peer_addresses:
if self._can_retry_addr(peer, urgent=True, now=now):
await self._add_peer(peer.host, peer.port, peer.pubkey)
return
async def reestablish_peers_and_channels(self):
while True:
await asyncio.sleep(1)
if self.stopping_soon:
return
for chan in self.channels.values():
if chan.is_closed():
continue
if not chan.should_try_to_reestablish_peer():
continue
peer = self._peers.get(chan.node_id, None)
if peer:
await peer.taskgroup.spawn(peer.reestablish_channel(chan))
else:
await self.taskgroup.spawn(self.reestablish_peer_for_given_channel(chan))
def current_feerate_per_kw(self):
from .simple_config import FEE_LN_ETA_TARGET, FEERATE_FALLBACK_STATIC_FEE, FEERATE_REGTEST_HARDCODED
from .simple_config import FEERATE_PER_KW_MIN_RELAY_LIGHTNING
if constants.net is constants.BitcoinRegtest:
return FEERATE_REGTEST_HARDCODED // 4
feerate_per_kvbyte = self.network.config.eta_target_to_fee(FEE_LN_ETA_TARGET)
if feerate_per_kvbyte is None:
feerate_per_kvbyte = FEERATE_FALLBACK_STATIC_FEE
return max(FEERATE_PER_KW_MIN_RELAY_LIGHTNING, feerate_per_kvbyte // 4)
def create_channel_backup(self, channel_id):
chan = self._channels[channel_id]
assert chan.is_static_remotekey_enabled()
peer_addresses = list(chan.get_peer_addresses())
peer_addr = peer_addresses[0]
return ImportedChannelBackupStorage(
node_id = chan.node_id,
privkey = self.node_keypair.privkey,
funding_txid = chan.funding_outpoint.txid,
funding_index = chan.funding_outpoint.output_index,
funding_address = chan.get_funding_address(),
host = peer_addr.host,
port = peer_addr.port,
is_initiator = chan.constraints.is_initiator,
channel_seed = chan.config[LOCAL].channel_seed,
local_delay = chan.config[LOCAL].to_self_delay,
remote_delay = chan.config[REMOTE].to_self_delay,
remote_revocation_pubkey = chan.config[REMOTE].revocation_basepoint.pubkey,
remote_payment_pubkey = chan.config[REMOTE].payment_basepoint.pubkey)
def export_channel_backup(self, channel_id):
xpub = self.wallet.get_fingerprint()
backup_bytes = self.create_channel_backup(channel_id).to_bytes()
assert backup_bytes == ImportedChannelBackupStorage.from_bytes(backup_bytes).to_bytes(), "roundtrip failed"
encrypted = pw_encode_with_version_and_mac(backup_bytes, xpub)
assert backup_bytes == pw_decode_with_version_and_mac(encrypted, xpub), "encrypt failed"
return 'channel_backup:' + encrypted
async def request_force_close(self, channel_id: bytes, *, connect_str=None) -> None:
if channel_id in self.channels:
chan = self.channels[channel_id]
peer = self._peers.get(chan.node_id)
if not peer:
raise Exception('Peer not found')
chan.should_request_force_close = True
peer.close_and_cleanup()
elif connect_str:
peer = await self.add_peer(connect_str)
await peer.trigger_force_close(channel_id)
elif channel_id in self.channel_backups:
await self._request_force_close_from_backup(channel_id)
else:
raise Exception(f'Unknown channel {channel_id.hex()}')
def import_channel_backup(self, data):
assert data.startswith('channel_backup:')
encrypted = data[15:]
xpub = self.wallet.get_fingerprint()
decrypted = pw_decode_with_version_and_mac(encrypted, xpub)
cb_storage = ImportedChannelBackupStorage.from_bytes(decrypted)
channel_id = cb_storage.channel_id()
if channel_id.hex() in self.db.get_dict("channels"):
raise Exception('Channel already in wallet')
self.logger.info(f'importing channel backup: {channel_id.hex()}')
d = self.db.get_dict("imported_channel_backups")
d[channel_id.hex()] = cb_storage
with self.lock:
cb = ChannelBackup(cb_storage, sweep_address=self.sweep_address, lnworker=self)
self._channel_backups[channel_id] = cb
self.wallet.save_db()
util.trigger_callback('channels_updated', self.wallet)
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
def has_conflicting_backup_with(self, remote_node_id: bytes):
channel_backup_peers = [
cb.node_id for cb in self.channel_backups.values()
if (not cb.is_closed() and cb.get_local_pubkey() == self.node_keypair.pubkey)]
return any(remote_node_id.startswith(cb_peer_nodeid) for cb_peer_nodeid in channel_backup_peers)
def remove_channel_backup(self, channel_id):
chan = self.channel_backups[channel_id]
assert chan.can_be_deleted()
onchain_backups = self.db.get_dict("onchain_channel_backups")
imported_backups = self.db.get_dict("imported_channel_backups")
if channel_id.hex() in onchain_backups:
onchain_backups.pop(channel_id.hex())
elif channel_id.hex() in imported_backups:
imported_backups.pop(channel_id.hex())
else:
raise Exception('Channel not found')
with self.lock:
self._channel_backups.pop(channel_id)
self.wallet.save_db()
util.trigger_callback('channels_updated', self.wallet)
@log_exceptions
async def _request_force_close_from_backup(self, channel_id: bytes):
cb = self.channel_backups.get(channel_id)
if not cb:
raise Exception(f'channel backup not found {self.channel_backups}')
cb = cb.cb
self.logger.info(f'requesting channel force close: {channel_id.hex()}')
if isinstance(cb, ImportedChannelBackupStorage):
node_id = cb.node_id
privkey = cb.privkey
addresses = [(cb.host, cb.port, 0)]
else:
assert isinstance(cb, OnchainChannelBackupStorage)
if not self.channel_db:
raise Exception('Enable gossip first')
node_id = self.network.channel_db.get_node_by_prefix(cb.node_id_prefix)
privkey = self.node_keypair.privkey
addresses = self.network.channel_db.get_node_addresses(node_id)
if not addresses:
raise Exception('Peer not found in gossip database')
for host, port, timestamp in addresses:
peer_addr = LNPeerAddr(host, port, node_id)
transport = LNTransport(privkey, peer_addr, proxy=self.network.proxy)
peer = Peer(self, node_id, transport, is_channel_backup=True)
try:
async with OldTaskGroup(wait=any) as group:
await group.spawn(peer._message_loop())
await group.spawn(peer.trigger_force_close(channel_id))
return
except Exception as e:
self.logger.info(f'failed to connect {host} {e}')
continue
else:
raise Exception('failed to connect')
def maybe_add_backup_from_tx(self, tx):
funding_address = None
node_id_prefix = None
for i, o in enumerate(tx.outputs()):
script_type = get_script_type_from_output_script(o.scriptpubkey)
if script_type == 'p2wsh':
funding_index = i
funding_address = o.address
for o2 in tx.outputs():
if o2.scriptpubkey.startswith(bytes([opcodes.OP_RETURN])):
encrypted_data = o2.scriptpubkey[2:]
data = self.decrypt_cb_data(encrypted_data, funding_address)
if data.startswith(CB_MAGIC_BYTES):
node_id_prefix = data[4:]
if node_id_prefix is None:
return
funding_txid = tx.txid()
cb_storage = OnchainChannelBackupStorage(
node_id_prefix = node_id_prefix,
funding_txid = funding_txid,
funding_index = funding_index,
funding_address = funding_address,
is_initiator = True)
channel_id = cb_storage.channel_id().hex()
if channel_id in self.db.get_dict("channels"):
return
self.logger.info(f"adding backup from tx")
d = self.db.get_dict("onchain_channel_backups")
d[channel_id] = cb_storage
cb = ChannelBackup(cb_storage, sweep_address=self.sweep_address, lnworker=self)
self.wallet.save_db()
with self.lock:
self._channel_backups[bfh(channel_id)] = cb
util.trigger_callback('channels_updated', self.wallet)
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
| true | true |
f72b88a082eaa6db2a20df009f1b14a4cabb69cb | 355 | py | Python | unified_api/utils/utils.py | campos537/deep-fashion-system | 1de31dd6260cc967e1832cff63ae7e537a3a4e9d | [
"Unlicense"
] | 1 | 2021-04-06T00:43:26.000Z | 2021-04-06T00:43:26.000Z | unified_api/utils/utils.py | campos537/deep-fashion-system | 1de31dd6260cc967e1832cff63ae7e537a3a4e9d | [
"Unlicense"
] | null | null | null | unified_api/utils/utils.py | campos537/deep-fashion-system | 1de31dd6260cc967e1832cff63ae7e537a3a4e9d | [
"Unlicense"
] | null | null | null | def valid_pubsub(config):
if (config.get("topic_id") is not None and config.get("project_id") is not None
and config.get("subscription_id") is not None):
return True
return False
def valid_kafka(config):
if config.get("bootstrap_server") is not None and config.get("port") is not None:
return True
return False | 35.5 | 85 | 0.673239 | def valid_pubsub(config):
if (config.get("topic_id") is not None and config.get("project_id") is not None
and config.get("subscription_id") is not None):
return True
return False
def valid_kafka(config):
if config.get("bootstrap_server") is not None and config.get("port") is not None:
return True
return False | true | true |
f72b8a6bcb330314847fdb6f9ab7b88b743e3aa1 | 3,094 | py | Python | sdk/python/kfp/cli/diagnose_me/kubernetes_cluster_test.py | ConverJens/pipelines | a1d453af214ec9eebad73fb05845dd3499d60d00 | [
"Apache-2.0"
] | 6 | 2020-05-19T02:35:11.000Z | 2020-05-29T17:58:42.000Z | sdk/python/kfp/cli/diagnose_me/kubernetes_cluster_test.py | ConverJens/pipelines | a1d453af214ec9eebad73fb05845dd3499d60d00 | [
"Apache-2.0"
] | 1,932 | 2021-01-25T11:23:37.000Z | 2022-03-31T17:10:18.000Z | sdk/python/kfp/cli/diagnose_me/kubernetes_cluster_test.py | ConverJens/pipelines | a1d453af214ec9eebad73fb05845dd3499d60d00 | [
"Apache-2.0"
] | 11 | 2020-05-19T22:26:41.000Z | 2021-01-25T09:56:21.000Z | # Lint as: python3
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License,Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for diagnose_me.kubernetes_cluster."""
from typing import Text
import unittest
from unittest import mock
from . import kubernetes_cluster as dkc
from . import utility
class KubernetesClusterTest(unittest.TestCase):
@mock.patch.object(dkc, 'execute_kubectl_command', autospec=True)
def test_project_configuration_gcloud(self, mock_execute_kubectl_command):
"""Tests gcloud commands."""
dkc.get_kubectl_configuration(dkc.Commands.GET_PODS)
mock_execute_kubectl_command.assert_called_once_with(
['get', 'pods', '--all-namespaces'], human_readable=False)
dkc.get_kubectl_configuration(dkc.Commands.GET_CONFIGURED_CONTEXT)
mock_execute_kubectl_command.assert_called_with(['config', 'view'],
human_readable=False)
dkc.get_kubectl_configuration(dkc.Commands.GET_KUBECTL_VERSION)
mock_execute_kubectl_command.assert_called_with(['version'],
human_readable=False)
dkc.get_kubectl_configuration(
dkc.Commands.GET_PODS, kubernetes_context='test_context')
mock_execute_kubectl_command.assert_called_with(
['get', 'pods', '--context', 'test_context', '--all-namespaces'],
human_readable=False)
dkc.get_kubectl_configuration(
dkc.Commands.GET_PODS, kubernetes_context='test_context')
mock_execute_kubectl_command.assert_called_with(
['get', 'pods', '--context', 'test_context', '--all-namespaces'],
human_readable=False)
def test_Commands(self):
"""Verify commands are formaated properly."""
for command in dkc.Commands:
self.assertIsInstance(dkc._command_string[command], Text)
self.assertNotIn('\t', dkc._command_string[command])
self.assertNotIn('\n', dkc._command_string[command])
@mock.patch.object(utility, 'ExecutorResponse', autospec=True)
def test_execute_kubectl_command(self, mock_executor_response):
"""Test execute_gsutil_command."""
dkc.execute_kubectl_command(
[dkc._command_string[dkc.Commands.GET_KUBECTL_VERSION]])
mock_executor_response().execute_command.assert_called_once_with(
['kubectl', 'version', '-o', 'json'])
dkc.execute_kubectl_command(
[dkc._command_string[dkc.Commands.GET_KUBECTL_VERSION]],
human_readable=True)
mock_executor_response().execute_command.assert_called_with(
['kubectl', 'version'])
if __name__ == '__main__':
unittest.main()
| 40.181818 | 76 | 0.724952 |
from typing import Text
import unittest
from unittest import mock
from . import kubernetes_cluster as dkc
from . import utility
class KubernetesClusterTest(unittest.TestCase):
@mock.patch.object(dkc, 'execute_kubectl_command', autospec=True)
def test_project_configuration_gcloud(self, mock_execute_kubectl_command):
dkc.get_kubectl_configuration(dkc.Commands.GET_PODS)
mock_execute_kubectl_command.assert_called_once_with(
['get', 'pods', '--all-namespaces'], human_readable=False)
dkc.get_kubectl_configuration(dkc.Commands.GET_CONFIGURED_CONTEXT)
mock_execute_kubectl_command.assert_called_with(['config', 'view'],
human_readable=False)
dkc.get_kubectl_configuration(dkc.Commands.GET_KUBECTL_VERSION)
mock_execute_kubectl_command.assert_called_with(['version'],
human_readable=False)
dkc.get_kubectl_configuration(
dkc.Commands.GET_PODS, kubernetes_context='test_context')
mock_execute_kubectl_command.assert_called_with(
['get', 'pods', '--context', 'test_context', '--all-namespaces'],
human_readable=False)
dkc.get_kubectl_configuration(
dkc.Commands.GET_PODS, kubernetes_context='test_context')
mock_execute_kubectl_command.assert_called_with(
['get', 'pods', '--context', 'test_context', '--all-namespaces'],
human_readable=False)
def test_Commands(self):
for command in dkc.Commands:
self.assertIsInstance(dkc._command_string[command], Text)
self.assertNotIn('\t', dkc._command_string[command])
self.assertNotIn('\n', dkc._command_string[command])
@mock.patch.object(utility, 'ExecutorResponse', autospec=True)
def test_execute_kubectl_command(self, mock_executor_response):
dkc.execute_kubectl_command(
[dkc._command_string[dkc.Commands.GET_KUBECTL_VERSION]])
mock_executor_response().execute_command.assert_called_once_with(
['kubectl', 'version', '-o', 'json'])
dkc.execute_kubectl_command(
[dkc._command_string[dkc.Commands.GET_KUBECTL_VERSION]],
human_readable=True)
mock_executor_response().execute_command.assert_called_with(
['kubectl', 'version'])
if __name__ == '__main__':
unittest.main()
| true | true |
f72b8a7bda68abbe8202a4c1804acb456c64dc74 | 1,096 | py | Python | synth.py | athakor/java-monitoring | 6c013839c5b349e4402a3fa87245930d8d1cc20b | [
"Apache-2.0"
] | null | null | null | synth.py | athakor/java-monitoring | 6c013839c5b349e4402a3fa87245930d8d1cc20b | [
"Apache-2.0"
] | null | null | null | synth.py | athakor/java-monitoring | 6c013839c5b349e4402a3fa87245930d8d1cc20b | [
"Apache-2.0"
] | null | null | null | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This script is used to synthesize generated parts of this library."""
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.java as java
gapic = gcp.GAPICGenerator()
service = 'monitoring'
versions = ['v3']
config_pattern = '/google/monitoring/artman_monitoring.yaml'
for version in versions:
java.gapic_library(
service=service,
version=version,
config_pattern=config_pattern,
package_pattern='com.google.{service}.{version}',
gapic=gapic
)
java.common_templates()
| 29.621622 | 74 | 0.756387 |
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.java as java
gapic = gcp.GAPICGenerator()
service = 'monitoring'
versions = ['v3']
config_pattern = '/google/monitoring/artman_monitoring.yaml'
for version in versions:
java.gapic_library(
service=service,
version=version,
config_pattern=config_pattern,
package_pattern='com.google.{service}.{version}',
gapic=gapic
)
java.common_templates()
| true | true |
f72b8af740fb1cc78203d79551f725c340162fdf | 49 | py | Python | typings/bl_rna_utils/__init__.py | Argmaster/PyR3 | 6786bcb6a101fe4bd4cc50fe43767b8178504b15 | [
"MIT"
] | 2 | 2021-12-12T18:51:52.000Z | 2022-02-23T09:49:16.000Z | typings/bl_rna_utils/__init__.py | Argmaster/PyR3 | 6786bcb6a101fe4bd4cc50fe43767b8178504b15 | [
"MIT"
] | 2 | 2021-11-08T12:09:02.000Z | 2021-12-12T23:01:12.000Z | typings/bl_rna_utils/__init__.py | Argmaster/PyR3 | 6786bcb6a101fe4bd4cc50fe43767b8178504b15 | [
"MIT"
] | null | null | null | import sys
import typing
from . import data_path
| 12.25 | 23 | 0.816327 | import sys
import typing
from . import data_path
| true | true |
f72b8b472726026675a7b89a1c670dce52cfa9b7 | 2,274 | py | Python | tests/model/model_discovery_test.py | nickgaya/bravado-core | 16e752963bfceb4adfa43724085bc4127eefcd59 | [
"BSD-3-Clause"
] | 122 | 2015-04-22T17:31:18.000Z | 2021-11-08T10:29:57.000Z | tests/model/model_discovery_test.py | nickgaya/bravado-core | 16e752963bfceb4adfa43724085bc4127eefcd59 | [
"BSD-3-Clause"
] | 364 | 2015-04-10T22:19:23.000Z | 2022-02-25T08:55:10.000Z | tests/model/model_discovery_test.py | nickgaya/bravado-core | 16e752963bfceb4adfa43724085bc4127eefcd59 | [
"BSD-3-Clause"
] | 118 | 2015-04-20T15:11:53.000Z | 2021-12-09T10:03:34.000Z | # -*- coding: utf-8 -*-
import mock
import pytest
from bravado_core.model import _run_post_processing
from bravado_core.model import model_discovery
from bravado_core.spec import Spec
@pytest.fixture
def wrap__run_post_processing():
with mock.patch(
'bravado_core.model._run_post_processing',
wraps=_run_post_processing,
) as _wrap__run_post_processing:
yield _wrap__run_post_processing
def test_model_discovery_flow_no_ref_dereference(wrap__run_post_processing, minimal_swagger_dict):
spec = Spec(
spec_dict=minimal_swagger_dict,
config={
'internally_dereference_refs': False,
},
)
model_discovery(swagger_spec=spec)
wrap__run_post_processing.assert_called_once_with(spec)
def test_model_discovery_flow_with_ref_dereference(wrap__run_post_processing, minimal_swagger_dict):
spec = Spec(
spec_dict=dict(minimal_swagger_dict, definitions={'model': {'type': 'object'}}),
config={
'internally_dereference_refs': True,
},
origin_url='',
)
model_discovery(swagger_spec=spec)
# _run_post_processing is called 3 times
# 1. post processing on initial specs
# 2. post processing on on bravado_core.spec_flattening.flattened_spec
# 3. post processing to rebuild definitions to remove possible references in the model specs
assert wrap__run_post_processing.call_count == 3
@pytest.mark.parametrize(
'model_dict',
[
{
'properties': {
'allOf': {
'type': 'string',
},
'title': {'type': 'string'},
'type': {'type': 'string'},
},
'type': 'object',
},
],
)
def test_model_discovery_for_models_with_not_string_title_x_model(minimal_swagger_dict, model_dict):
# This test case has been extracted from the Kubernetes Swagger specs
# https://raw.githubusercontent.com/kubernetes/kubernetes/release-1.15/api/openapi-spec/swagger.json#/definitions/io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.JSONSchemaProps
spec = Spec.from_dict(spec_dict=dict(minimal_swagger_dict, definitions={'Model': model_dict}))
assert set(spec.definitions) == {'Model'}
| 33.940299 | 195 | 0.690413 |
import mock
import pytest
from bravado_core.model import _run_post_processing
from bravado_core.model import model_discovery
from bravado_core.spec import Spec
@pytest.fixture
def wrap__run_post_processing():
with mock.patch(
'bravado_core.model._run_post_processing',
wraps=_run_post_processing,
) as _wrap__run_post_processing:
yield _wrap__run_post_processing
def test_model_discovery_flow_no_ref_dereference(wrap__run_post_processing, minimal_swagger_dict):
spec = Spec(
spec_dict=minimal_swagger_dict,
config={
'internally_dereference_refs': False,
},
)
model_discovery(swagger_spec=spec)
wrap__run_post_processing.assert_called_once_with(spec)
def test_model_discovery_flow_with_ref_dereference(wrap__run_post_processing, minimal_swagger_dict):
spec = Spec(
spec_dict=dict(minimal_swagger_dict, definitions={'model': {'type': 'object'}}),
config={
'internally_dereference_refs': True,
},
origin_url='',
)
model_discovery(swagger_spec=spec)
assert wrap__run_post_processing.call_count == 3
@pytest.mark.parametrize(
'model_dict',
[
{
'properties': {
'allOf': {
'type': 'string',
},
'title': {'type': 'string'},
'type': {'type': 'string'},
},
'type': 'object',
},
],
)
def test_model_discovery_for_models_with_not_string_title_x_model(minimal_swagger_dict, model_dict):
_dict}))
assert set(spec.definitions) == {'Model'}
| true | true |
f72b8df9aa69d2cc28657e451f4a61aca75b3217 | 2,091 | py | Python | toys/sqlalchemy_bakery.py | mikegreen7892003/PythonToy | e9218cdee4a38835fdbebad0e429ddf52bb444b4 | [
"MIT"
] | null | null | null | toys/sqlalchemy_bakery.py | mikegreen7892003/PythonToy | e9218cdee4a38835fdbebad0e429ddf52bb444b4 | [
"MIT"
] | null | null | null | toys/sqlalchemy_bakery.py | mikegreen7892003/PythonToy | e9218cdee4a38835fdbebad0e429ddf52bb444b4 | [
"MIT"
] | null | null | null | """
Just for Python 3
"""
import logging
import pprint
import tornado.web
import tornado.httpserver
from tornado.options import define, options, parse_command_line
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext import baked
from sqlalchemy.orm import Session
# models
BAKERY = baked.bakery()
Base = declarative_base()
ENGINE = create_engine('sqlite:///:memory:', echo=False)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (
self.name, self.fullname, self.password)
# request
class MainHandler(tornado.web.RequestHandler):
@property
def session(self):
return Session(bind=ENGINE)
def get(self):
uid = self.get_argument("uid")
def fn(session):
logging.warn("call fn %s", fn)
return session.query(User).filter(User.id == uid)
baked_query = BAKERY(fn)
logging.info("fn %s", fn.__code__)
logging.warn("baked_query _cache_key: %s", baked_query._cache_key)
user_list = baked_query(self.session).all()
self.write("user_list:\n{}\n".format(pprint.pformat(user_list)))
def main():
Base.metadata.create_all(ENGINE)
# add test user
session = Session(bind=ENGINE)
for uid in range(20):
user = User(name='ed {}'.format(uid), fullname='Ed Jones {}'.format(uid), password='edspassword')
session.add(user)
session.commit()
# start application
application = tornado.web.Application([
(r"/", MainHandler),
], )
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
define("port", default=8888, help="run on the given port", type=int)
parse_command_line()
main()
| 23.761364 | 105 | 0.659971 |
import logging
import pprint
import tornado.web
import tornado.httpserver
from tornado.options import define, options, parse_command_line
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext import baked
from sqlalchemy.orm import Session
BAKERY = baked.bakery()
Base = declarative_base()
ENGINE = create_engine('sqlite:///:memory:', echo=False)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (
self.name, self.fullname, self.password)
class MainHandler(tornado.web.RequestHandler):
@property
def session(self):
return Session(bind=ENGINE)
def get(self):
uid = self.get_argument("uid")
def fn(session):
logging.warn("call fn %s", fn)
return session.query(User).filter(User.id == uid)
baked_query = BAKERY(fn)
logging.info("fn %s", fn.__code__)
logging.warn("baked_query _cache_key: %s", baked_query._cache_key)
user_list = baked_query(self.session).all()
self.write("user_list:\n{}\n".format(pprint.pformat(user_list)))
def main():
Base.metadata.create_all(ENGINE)
session = Session(bind=ENGINE)
for uid in range(20):
user = User(name='ed {}'.format(uid), fullname='Ed Jones {}'.format(uid), password='edspassword')
session.add(user)
session.commit()
application = tornado.web.Application([
(r"/", MainHandler),
], )
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
define("port", default=8888, help="run on the given port", type=int)
parse_command_line()
main()
| true | true |
f72b8dfa12eefecf24dc259425f0b7961d8f210a | 28,498 | py | Python | tests/gce_virtual_machine_test.py | mikeweng/PerfKitBenchmarker | e929a69f04e2f91a0fed7da8db8a321edf58f403 | [
"Apache-2.0"
] | null | null | null | tests/gce_virtual_machine_test.py | mikeweng/PerfKitBenchmarker | e929a69f04e2f91a0fed7da8db8a321edf58f403 | [
"Apache-2.0"
] | null | null | null | tests/gce_virtual_machine_test.py | mikeweng/PerfKitBenchmarker | e929a69f04e2f91a0fed7da8db8a321edf58f403 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 PerfKitBenchmarker 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 perfkitbenchmarker.providers.gcp.gce_virtual_machine."""
import contextlib
import copy
import json
import re
import unittest
from absl import flags
import builtins
import mock
from perfkitbenchmarker import benchmark_spec
from perfkitbenchmarker import context
from perfkitbenchmarker import errors
from perfkitbenchmarker import os_types
from perfkitbenchmarker import providers
from perfkitbenchmarker import virtual_machine
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.configs import benchmark_config_spec
from perfkitbenchmarker.providers.gcp import gce_network
from perfkitbenchmarker.providers.gcp import gce_virtual_machine
from perfkitbenchmarker.providers.gcp import util
from tests import pkb_common_test_case
FLAGS = flags.FLAGS
_BENCHMARK_NAME = 'name'
_BENCHMARK_UID = 'benchmark_uid'
_COMPONENT = 'test_component'
_FLAGS = None
_FAKE_INSTANCE_METADATA = {
'id': '123456',
'networkInterfaces': [
{
'accessConfigs': [
{
'natIP': '1.2.3.4'
}
],
'networkIP': '1.2.3.4'
}
]
}
_FAKE_DISK_METADATA = {
'id': '123456',
'kind': 'compute#disk',
'name': 'fakedisk',
'sizeGb': '10',
'sourceImage': '',
'type': 'pd-standard'
}
@contextlib.contextmanager
def PatchCriticalObjects(retvals=None):
"""A context manager that patches a few critical objects with mocks."""
def ReturnVal(*unused_arg, **unused_kwargs):
del unused_arg
del unused_kwargs
return ('', '', 0) if retvals is None else retvals.pop(0)
with mock.patch(
vm_util.__name__ + '.IssueCommand',
side_effect=ReturnVal) as issue_command, mock.patch(
builtins.__name__ + '.open'), mock.patch(
vm_util.__name__ +
'.NamedTemporaryFile'), mock.patch(util.__name__ +
'.GetDefaultProject'):
yield issue_command
class GceVmSpecTestCase(pkb_common_test_case.PkbCommonTestCase):
def testStringMachineType(self):
result = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='n1-standard-8')
self.assertEqual(result.machine_type, 'n1-standard-8')
self.assertEqual(result.cpus, None)
self.assertEqual(result.memory, None)
def testStringMachineTypeWithGpus(self):
gpu_count = 2
gpu_type = 'k80'
result = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='n1-standard-8',
gpu_count=gpu_count,
gpu_type=gpu_type)
self.assertEqual(result.machine_type, 'n1-standard-8')
self.assertEqual(result.gpu_type, 'k80')
self.assertEqual(result.gpu_count, 2)
def testCustomMachineType(self):
result = gce_virtual_machine.GceVmSpec(_COMPONENT, machine_type={
'cpus': 1, 'memory': '7.5GiB'})
self.assertEqual(result.machine_type, None)
self.assertEqual(result.cpus, 1)
self.assertEqual(result.memory, 7680)
def testCustomMachineTypeWithGpus(self):
gpu_count = 2
gpu_type = 'k80'
result = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type={
'cpus': 1,
'memory': '7.5GiB'
},
gpu_count=gpu_count,
gpu_type=gpu_type)
self.assertEqual(result.cpus, 1)
self.assertEqual(result.memory, 7680)
self.assertEqual(result.gpu_type, 'k80')
self.assertEqual(result.gpu_count, 2)
def testStringMachineTypeFlagOverride(self):
FLAGS['machine_type'].parse('n1-standard-8')
result = gce_virtual_machine.GceVmSpec(
_COMPONENT,
flag_values=FLAGS,
machine_type={
'cpus': 1,
'memory': '7.5GiB'
})
self.assertEqual(result.machine_type, 'n1-standard-8')
self.assertEqual(result.cpus, None)
self.assertEqual(result.memory, None)
def testCustomMachineTypeFlagOverride(self):
FLAGS['machine_type'].parse('{cpus: 1, memory: 7.5GiB}')
result = gce_virtual_machine.GceVmSpec(
_COMPONENT, flag_values=FLAGS, machine_type='n1-standard-8')
self.assertEqual(result.machine_type, None)
self.assertEqual(result.cpus, 1)
self.assertEqual(result.memory, 7680)
class GceVirtualMachineTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GceVirtualMachineTestCase, self).setUp()
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceNetwork.GetNetwork')
self.mock_get_network = p.start()
self.addCleanup(p.stop)
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceFirewall.GetFirewall')
self.mock_get_firewall = p.start()
self.addCleanup(p.stop)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
def testVmWithMachineTypeNonPreemptible(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type='test_machine_type', project='p')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset(
{'dedicated_host': False, 'machine_type': 'test_machine_type',
'project': 'p'},
vm.GetResourceMetadata()
)
def testVmWithMachineTypePreemptible(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type='test_machine_type', preemptible=True,
project='p')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset(
{'dedicated_host': False, 'machine_type': 'test_machine_type',
'preemptible': True, 'project': 'p'},
vm.GetResourceMetadata()
)
def testCustomVmNonPreemptible(self):
spec = gce_virtual_machine.GceVmSpec(_COMPONENT, machine_type={
'cpus': 1, 'memory': '1.0GiB'}, project='p')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset(
{'cpus': 1, 'memory_mib': 1024, 'project': 'p',
'dedicated_host': False},
vm.GetResourceMetadata())
def testCustomVmPreemptible(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={'cpus': 1, 'memory': '1.0GiB'},
preemptible=True,
project='fakeproject')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset({
'cpus': 1, 'memory_mib': 1024, 'project': 'fakeproject',
'dedicated_host': False, 'preemptible': True}, vm.GetResourceMetadata())
def testCustomVmWithGpus(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT,
machine_type={'cpus': 1, 'memory': '1.0GiB'},
gpu_count=2,
gpu_type='k80',
project='fakeproject')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset({
'cpus': 1, 'memory_mib': 1024, 'project': 'fakeproject',
'dedicated_host': False, 'gpu_count': 2, 'gpu_type': 'k80'
}, vm.GetResourceMetadata())
def _CreateFakeDiskMetadata(image):
fake_disk = copy.copy(_FAKE_DISK_METADATA)
fake_disk['sourceImage'] = image
return fake_disk
class GceVirtualMachineOsTypesTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GceVirtualMachineOsTypesTestCase, self).setUp()
FLAGS.gcp_instance_metadata_from_file = ''
FLAGS.gcp_instance_metadata = ''
FLAGS.gcloud_path = 'gcloud'
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceNetwork.GetNetwork')
self.mock_get_network = p.start()
self.addCleanup(p.stop)
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceFirewall.GetFirewall')
self.mock_get_firewall = p.start()
self.addCleanup(p.stop)
self.spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type')
p = mock.patch(gce_virtual_machine.__name__ +
'.linux_vm.BaseLinuxMixin._GetNumCpus')
self.mock_get_num_cpus = p.start()
self.addCleanup(p.stop)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
def _CreateFakeReturnValues(self, fake_image=''):
fake_rets = [('', '', 0), (json.dumps(_FAKE_INSTANCE_METADATA), '', 0)]
if fake_image:
fake_rets.append((json.dumps(_CreateFakeDiskMetadata(fake_image)), '', 0))
return fake_rets
def testCreateUbuntu1604(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1604)
fake_image = 'fake-ubuntu1604'
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(self.spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn(
'--image-family ubuntu-1604-lts --image-project ubuntu-os-cloud',
command_string)
self.assertNotIn('--boot-disk-size', command_string)
self.assertNotIn('--boot-disk-type', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
self.assertDictContainsSubset({'image': fake_image,
'image_family': 'ubuntu-1604-lts',
'image_project': 'ubuntu-os-cloud',
'boot_disk_size': '10',
'boot_disk_type': 'pd-standard'},
vm.GetResourceMetadata())
def testCreateUbuntuInCustomProject(self):
"""Test simulating passing --image and --image_project."""
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1604)
fake_image = 'fake-ubuntu1604'
fake_image_project = 'fake-project'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image,
image_project=fake_image_project)
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn(
'--image fake-ubuntu1604 --image-project fake-project',
command_string)
self.assertNotIn('--image-family', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'fake-project'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
def testCreateUbuntuInCustomDisk(self):
"""Test simulating passing --image and --image_project."""
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1604)
fake_image = 'fake-ubuntu1604'
fake_image_project = 'fake-project'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image,
image_project=fake_image_project,
boot_disk_size=20,
boot_disk_type='fake-disk-type')
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn('--boot-disk-size 20', command_string)
self.assertIn('--boot-disk-type fake-disk-type', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 2)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'fake-project',
'boot_disk_size': 20,
'boot_disk_type': 'fake-disk-type'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
def testCreateUbuntu1804(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1804)
fake_image = 'fake-ubuntu1804'
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(self.spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn(
'--image-family ubuntu-1804-lts --image-project ubuntu-os-cloud',
command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
self.assertDictContainsSubset({'image': fake_image,
'image_family': 'ubuntu-1804-lts',
'image_project': 'ubuntu-os-cloud'},
vm.GetResourceMetadata())
def testCreateRhel7CustomImage(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.RHEL7)
fake_image = 'fake-custom-rhel-image'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image)
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn('--image ' + fake_image, command_string)
self.assertIn('--image-project rhel-cloud', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'rhel-cloud'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
def testCreateCentOs7CustomImage(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.CENTOS7)
fake_image = 'fake-custom-centos7-image'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image)
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn('--image ' + fake_image, command_string)
self.assertIn('--image-project centos-cloud', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'centos-cloud'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
class GCEVMFlagsTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GCEVMFlagsTestCase, self).setUp()
FLAGS.cloud = providers.GCP
FLAGS.gcloud_path = 'test_gcloud'
FLAGS.run_uri = 'aaaaaa'
FLAGS.gcp_instance_metadata = []
FLAGS.gcp_instance_metadata_from_file = []
# Creating a VM object causes network objects to be added to the current
# thread's benchmark spec. Create such a benchmark spec for these tests.
self.addCleanup(context.SetThreadBenchmarkSpec, None)
config_spec = benchmark_config_spec.BenchmarkConfigSpec(
_BENCHMARK_NAME, flag_values=FLAGS, vm_groups={})
self._benchmark_spec = benchmark_spec.BenchmarkSpec(
mock.MagicMock(), config_spec, _BENCHMARK_UID)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
def _CreateVmCommand(self, **flag_kwargs):
with PatchCriticalObjects() as issue_command:
for key, value in flag_kwargs.items():
FLAGS[key].parse(value)
vm_spec = gce_virtual_machine.GceVmSpec(
'test_vm_spec.GCP',
FLAGS,
image='image',
machine_type='test_machine_type')
vm = pkb_common_test_case.TestGceVirtualMachine(vm_spec)
vm._Create()
return ' '.join(issue_command.call_args[0][0]), issue_command.call_count
def testPreemptibleVMFlag(self):
cmd, call_count = self._CreateVmCommand(gce_preemptible_vms=True)
self.assertEqual(call_count, 1)
self.assertIn('--preemptible', cmd)
def testMigrateOnMaintenanceFlagTrueWithGpus(self):
with self.assertRaises(errors.Config.InvalidValue) as cm:
self._CreateVmCommand(
gce_migrate_on_maintenance=True, gpu_count=1, gpu_type='k80')
self.assertEqual(str(cm.exception), (
'Cannot set flag gce_migrate_on_maintenance on '
'instances with GPUs, as it is not supported by GCP.'))
def testMigrateOnMaintenanceFlagFalseWithGpus(self):
_, call_count = self._CreateVmCommand(
gce_migrate_on_maintenance=False, gpu_count=1, gpu_type='k80')
self.assertEqual(call_count, 1)
def testAcceleratorTypeOverrideFlag(self):
cmd, call_count = self._CreateVmCommand(
gce_accelerator_type_override='fake_type', gpu_count=1, gpu_type='k80')
self.assertEqual(call_count, 1)
self.assertIn('--accelerator', cmd)
self.assertIn('type=fake_type,count=1', cmd)
def testImageProjectFlag(self):
"""Tests that custom image_project flag is supported."""
cmd, call_count = self._CreateVmCommand(image_project='bar')
self.assertEqual(call_count, 1)
self.assertIn('--image-project bar', cmd)
def testNetworkTierFlagPremium(self):
"""Tests that the premium network tier flag is supported."""
cmd, call_count = self._CreateVmCommand(gce_network_tier='premium')
self.assertEqual(call_count, 1)
self.assertIn('--network-tier PREMIUM', cmd)
def testNetworkTierFlagStandard(self):
"""Tests that the standard network tier flag is supported."""
cmd, call_count = self._CreateVmCommand(gce_network_tier='standard')
self.assertEqual(call_count, 1)
self.assertIn('--network-tier STANDARD', cmd)
def testGcpInstanceMetadataFlag(self):
cmd, call_count = self._CreateVmCommand(
gcp_instance_metadata=['k1:v1', 'k2:v2,k3:v3'], owner='test-owner')
self.assertEqual(call_count, 1)
actual_metadata = re.compile(
r'--metadata\s+(.*)(\s+--)?').search(cmd).group(1)
self.assertIn('k1=v1', actual_metadata)
self.assertIn('k2=v2', actual_metadata)
self.assertIn('k3=v3', actual_metadata)
# Assert that FLAGS.owner is honored and added to instance metadata.
self.assertIn('owner=test-owner', actual_metadata)
def testGcpInstanceMetadataFromFileFlag(self):
cmd, call_count = self._CreateVmCommand(
gcp_instance_metadata_from_file=['k1:p1', 'k2:p2,k3:p3'])
self.assertEqual(call_count, 1)
actual_metadata_from_file = re.compile(
r'--metadata-from-file\s+(.*)(\s+--)?').search(cmd).group(1)
self.assertIn('k1=p1', actual_metadata_from_file)
self.assertIn('k2=p2', actual_metadata_from_file)
self.assertIn('k3=p3', actual_metadata_from_file)
def testGceTags(self):
self.assertIn('--tags perfkitbenchmarker', self._CreateVmCommand()[0])
self.assertIn('--tags perfkitbenchmarker,testtag',
self._CreateVmCommand(gce_tags=['testtag'])[0])
def testShieldedSecureBootFlag(self):
"""Tests that the custom shielded secure boot flag is supported."""
cmd, call_count = self._CreateVmCommand(
gce_shielded_secure_boot=True)
self.assertEqual(call_count, 1)
self.assertIn('--shielded-secure-boot', cmd)
class GCEVMCreateTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GCEVMCreateTestCase, self).setUp()
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceNetwork.GetNetwork')
self.mock_get_network = p.start()
self.addCleanup(p.stop)
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceFirewall.GetFirewall')
self.mock_get_firewall = p.start()
self.addCleanup(p.stop)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testCreateRateLimitedMachineCreated(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'The resource already exists', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm._Create() # No error should be thrown.
self.assertEqual(issue_command.call_count, 5)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testCreateRateLimitedMachineCreatedFailure(self, mock_cmd):
fake_rets = []
for _ in range(0, 100):
fake_rets.append(('stdout', 'Rate Limit Exceeded', 1))
with PatchCriticalObjects(fake_rets) as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
with self.assertRaises(
errors.Benchmarks.QuotaFailure.RateLimitExceededError):
vm._Create()
self.assertEqual(issue_command.call_count,
util.RATE_LIMITED_MAX_RETRIES + 1)
def testCreateVMAlreadyExists(self):
fake_rets = [('stdout', 'The resource already exists', 1)]
with PatchCriticalObjects(fake_rets):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
with self.assertRaises(errors.Resource.CreationError):
vm._Create()
def testVmWithoutGpu(self):
with PatchCriticalObjects() as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm._Create()
self.assertEqual(issue_command.call_count, 1)
self.assertNotIn('--accelerator', issue_command.call_args[0][0])
def testVmWithGpu(self):
with PatchCriticalObjects() as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT,
machine_type='n1-standard-8',
gpu_count=2,
gpu_type='k80')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm._Create()
self.assertEqual(issue_command.call_count, 1)
self.assertIn('--accelerator', issue_command.call_args[0][0])
self.assertIn('type=nvidia-tesla-k80,count=2',
issue_command.call_args[0][0])
self.assertIn('--maintenance-policy', issue_command.call_args[0][0])
self.assertIn('TERMINATE', issue_command.call_args[0][0])
class GceFirewallRuleTest(pkb_common_test_case.PkbCommonTestCase):
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleSuccessfulAfterRateLimited(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'some warning perhaps', 0)]
with PatchCriticalObjects(fake_rets) as issue_command:
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 2)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleGenericErrorAfterRateLimited(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'some random firewall error', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
with self.assertRaises(errors.VmUtil.IssueCommandError):
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 3)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleAlreadyExistsAfterRateLimited(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'firewall already exists', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 3)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleGenericError(self, mock_cmd):
fake_rets = [('stdout', 'some random firewall error', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
with self.assertRaises(errors.VmUtil.IssueCommandError):
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 1)
class GceNetworkTest(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GceNetworkTest, self).setUp()
# need a benchmarkspec in the context to run
config_spec = benchmark_config_spec.BenchmarkConfigSpec(
'cluster_boot', flag_values=FLAGS)
benchmark_spec.BenchmarkSpec(mock.Mock(), config_spec, 'uid')
def testGetNetwork(self):
project = 'myproject'
zone = 'us-east1-a'
vm = mock.Mock(zone=zone, project=project, cidr=None)
net = gce_network.GceNetwork.GetNetwork(vm)
self.assertEqual(project, net.project)
self.assertEqual(zone, net.zone)
if __name__ == '__main__':
unittest.main()
| 40.422695 | 80 | 0.65573 |
import contextlib
import copy
import json
import re
import unittest
from absl import flags
import builtins
import mock
from perfkitbenchmarker import benchmark_spec
from perfkitbenchmarker import context
from perfkitbenchmarker import errors
from perfkitbenchmarker import os_types
from perfkitbenchmarker import providers
from perfkitbenchmarker import virtual_machine
from perfkitbenchmarker import vm_util
from perfkitbenchmarker.configs import benchmark_config_spec
from perfkitbenchmarker.providers.gcp import gce_network
from perfkitbenchmarker.providers.gcp import gce_virtual_machine
from perfkitbenchmarker.providers.gcp import util
from tests import pkb_common_test_case
FLAGS = flags.FLAGS
_BENCHMARK_NAME = 'name'
_BENCHMARK_UID = 'benchmark_uid'
_COMPONENT = 'test_component'
_FLAGS = None
_FAKE_INSTANCE_METADATA = {
'id': '123456',
'networkInterfaces': [
{
'accessConfigs': [
{
'natIP': '1.2.3.4'
}
],
'networkIP': '1.2.3.4'
}
]
}
_FAKE_DISK_METADATA = {
'id': '123456',
'kind': 'compute#disk',
'name': 'fakedisk',
'sizeGb': '10',
'sourceImage': '',
'type': 'pd-standard'
}
@contextlib.contextmanager
def PatchCriticalObjects(retvals=None):
def ReturnVal(*unused_arg, **unused_kwargs):
del unused_arg
del unused_kwargs
return ('', '', 0) if retvals is None else retvals.pop(0)
with mock.patch(
vm_util.__name__ + '.IssueCommand',
side_effect=ReturnVal) as issue_command, mock.patch(
builtins.__name__ + '.open'), mock.patch(
vm_util.__name__ +
'.NamedTemporaryFile'), mock.patch(util.__name__ +
'.GetDefaultProject'):
yield issue_command
class GceVmSpecTestCase(pkb_common_test_case.PkbCommonTestCase):
def testStringMachineType(self):
result = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='n1-standard-8')
self.assertEqual(result.machine_type, 'n1-standard-8')
self.assertEqual(result.cpus, None)
self.assertEqual(result.memory, None)
def testStringMachineTypeWithGpus(self):
gpu_count = 2
gpu_type = 'k80'
result = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='n1-standard-8',
gpu_count=gpu_count,
gpu_type=gpu_type)
self.assertEqual(result.machine_type, 'n1-standard-8')
self.assertEqual(result.gpu_type, 'k80')
self.assertEqual(result.gpu_count, 2)
def testCustomMachineType(self):
result = gce_virtual_machine.GceVmSpec(_COMPONENT, machine_type={
'cpus': 1, 'memory': '7.5GiB'})
self.assertEqual(result.machine_type, None)
self.assertEqual(result.cpus, 1)
self.assertEqual(result.memory, 7680)
def testCustomMachineTypeWithGpus(self):
gpu_count = 2
gpu_type = 'k80'
result = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type={
'cpus': 1,
'memory': '7.5GiB'
},
gpu_count=gpu_count,
gpu_type=gpu_type)
self.assertEqual(result.cpus, 1)
self.assertEqual(result.memory, 7680)
self.assertEqual(result.gpu_type, 'k80')
self.assertEqual(result.gpu_count, 2)
def testStringMachineTypeFlagOverride(self):
FLAGS['machine_type'].parse('n1-standard-8')
result = gce_virtual_machine.GceVmSpec(
_COMPONENT,
flag_values=FLAGS,
machine_type={
'cpus': 1,
'memory': '7.5GiB'
})
self.assertEqual(result.machine_type, 'n1-standard-8')
self.assertEqual(result.cpus, None)
self.assertEqual(result.memory, None)
def testCustomMachineTypeFlagOverride(self):
FLAGS['machine_type'].parse('{cpus: 1, memory: 7.5GiB}')
result = gce_virtual_machine.GceVmSpec(
_COMPONENT, flag_values=FLAGS, machine_type='n1-standard-8')
self.assertEqual(result.machine_type, None)
self.assertEqual(result.cpus, 1)
self.assertEqual(result.memory, 7680)
class GceVirtualMachineTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GceVirtualMachineTestCase, self).setUp()
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceNetwork.GetNetwork')
self.mock_get_network = p.start()
self.addCleanup(p.stop)
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceFirewall.GetFirewall')
self.mock_get_firewall = p.start()
self.addCleanup(p.stop)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
def testVmWithMachineTypeNonPreemptible(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type='test_machine_type', project='p')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset(
{'dedicated_host': False, 'machine_type': 'test_machine_type',
'project': 'p'},
vm.GetResourceMetadata()
)
def testVmWithMachineTypePreemptible(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type='test_machine_type', preemptible=True,
project='p')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset(
{'dedicated_host': False, 'machine_type': 'test_machine_type',
'preemptible': True, 'project': 'p'},
vm.GetResourceMetadata()
)
def testCustomVmNonPreemptible(self):
spec = gce_virtual_machine.GceVmSpec(_COMPONENT, machine_type={
'cpus': 1, 'memory': '1.0GiB'}, project='p')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset(
{'cpus': 1, 'memory_mib': 1024, 'project': 'p',
'dedicated_host': False},
vm.GetResourceMetadata())
def testCustomVmPreemptible(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={'cpus': 1, 'memory': '1.0GiB'},
preemptible=True,
project='fakeproject')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset({
'cpus': 1, 'memory_mib': 1024, 'project': 'fakeproject',
'dedicated_host': False, 'preemptible': True}, vm.GetResourceMetadata())
def testCustomVmWithGpus(self):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT,
machine_type={'cpus': 1, 'memory': '1.0GiB'},
gpu_count=2,
gpu_type='k80',
project='fakeproject')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm.created = True
self.assertDictContainsSubset({
'cpus': 1, 'memory_mib': 1024, 'project': 'fakeproject',
'dedicated_host': False, 'gpu_count': 2, 'gpu_type': 'k80'
}, vm.GetResourceMetadata())
def _CreateFakeDiskMetadata(image):
fake_disk = copy.copy(_FAKE_DISK_METADATA)
fake_disk['sourceImage'] = image
return fake_disk
class GceVirtualMachineOsTypesTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GceVirtualMachineOsTypesTestCase, self).setUp()
FLAGS.gcp_instance_metadata_from_file = ''
FLAGS.gcp_instance_metadata = ''
FLAGS.gcloud_path = 'gcloud'
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceNetwork.GetNetwork')
self.mock_get_network = p.start()
self.addCleanup(p.stop)
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceFirewall.GetFirewall')
self.mock_get_firewall = p.start()
self.addCleanup(p.stop)
self.spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type')
p = mock.patch(gce_virtual_machine.__name__ +
'.linux_vm.BaseLinuxMixin._GetNumCpus')
self.mock_get_num_cpus = p.start()
self.addCleanup(p.stop)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
def _CreateFakeReturnValues(self, fake_image=''):
fake_rets = [('', '', 0), (json.dumps(_FAKE_INSTANCE_METADATA), '', 0)]
if fake_image:
fake_rets.append((json.dumps(_CreateFakeDiskMetadata(fake_image)), '', 0))
return fake_rets
def testCreateUbuntu1604(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1604)
fake_image = 'fake-ubuntu1604'
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(self.spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn(
'--image-family ubuntu-1604-lts --image-project ubuntu-os-cloud',
command_string)
self.assertNotIn('--boot-disk-size', command_string)
self.assertNotIn('--boot-disk-type', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
self.assertDictContainsSubset({'image': fake_image,
'image_family': 'ubuntu-1604-lts',
'image_project': 'ubuntu-os-cloud',
'boot_disk_size': '10',
'boot_disk_type': 'pd-standard'},
vm.GetResourceMetadata())
def testCreateUbuntuInCustomProject(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1604)
fake_image = 'fake-ubuntu1604'
fake_image_project = 'fake-project'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image,
image_project=fake_image_project)
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn(
'--image fake-ubuntu1604 --image-project fake-project',
command_string)
self.assertNotIn('--image-family', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'fake-project'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
def testCreateUbuntuInCustomDisk(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1604)
fake_image = 'fake-ubuntu1604'
fake_image_project = 'fake-project'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image,
image_project=fake_image_project,
boot_disk_size=20,
boot_disk_type='fake-disk-type')
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn('--boot-disk-size 20', command_string)
self.assertIn('--boot-disk-type fake-disk-type', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 2)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'fake-project',
'boot_disk_size': 20,
'boot_disk_type': 'fake-disk-type'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
def testCreateUbuntu1804(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.UBUNTU1804)
fake_image = 'fake-ubuntu1804'
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(self.spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn(
'--image-family ubuntu-1804-lts --image-project ubuntu-os-cloud',
command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
self.assertDictContainsSubset({'image': fake_image,
'image_family': 'ubuntu-1804-lts',
'image_project': 'ubuntu-os-cloud'},
vm.GetResourceMetadata())
def testCreateRhel7CustomImage(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.RHEL7)
fake_image = 'fake-custom-rhel-image'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image)
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn('--image ' + fake_image, command_string)
self.assertIn('--image-project rhel-cloud', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'rhel-cloud'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
def testCreateCentOs7CustomImage(self):
vm_class = virtual_machine.GetVmClass(providers.GCP, os_types.CENTOS7)
fake_image = 'fake-custom-centos7-image'
spec = gce_virtual_machine.GceVmSpec(_COMPONENT,
machine_type='fake-machine-type',
image=fake_image)
with PatchCriticalObjects(
self._CreateFakeReturnValues(fake_image)) as issue_command:
vm = vm_class(spec)
vm._Create()
vm.created = True
command_string = ' '.join(issue_command.call_args[0][0])
self.assertEqual(issue_command.call_count, 1)
self.assertIn('gcloud compute instances create', command_string)
self.assertIn('--image ' + fake_image, command_string)
self.assertIn('--image-project centos-cloud', command_string)
vm._PostCreate()
self.assertEqual(issue_command.call_count, 3)
vm_metadata = vm.GetResourceMetadata()
self.assertDictContainsSubset({'image': fake_image,
'image_project': 'centos-cloud'},
vm_metadata)
self.assertNotIn('image_family', vm_metadata)
class GCEVMFlagsTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GCEVMFlagsTestCase, self).setUp()
FLAGS.cloud = providers.GCP
FLAGS.gcloud_path = 'test_gcloud'
FLAGS.run_uri = 'aaaaaa'
FLAGS.gcp_instance_metadata = []
FLAGS.gcp_instance_metadata_from_file = []
self.addCleanup(context.SetThreadBenchmarkSpec, None)
config_spec = benchmark_config_spec.BenchmarkConfigSpec(
_BENCHMARK_NAME, flag_values=FLAGS, vm_groups={})
self._benchmark_spec = benchmark_spec.BenchmarkSpec(
mock.MagicMock(), config_spec, _BENCHMARK_UID)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
def _CreateVmCommand(self, **flag_kwargs):
with PatchCriticalObjects() as issue_command:
for key, value in flag_kwargs.items():
FLAGS[key].parse(value)
vm_spec = gce_virtual_machine.GceVmSpec(
'test_vm_spec.GCP',
FLAGS,
image='image',
machine_type='test_machine_type')
vm = pkb_common_test_case.TestGceVirtualMachine(vm_spec)
vm._Create()
return ' '.join(issue_command.call_args[0][0]), issue_command.call_count
def testPreemptibleVMFlag(self):
cmd, call_count = self._CreateVmCommand(gce_preemptible_vms=True)
self.assertEqual(call_count, 1)
self.assertIn('--preemptible', cmd)
def testMigrateOnMaintenanceFlagTrueWithGpus(self):
with self.assertRaises(errors.Config.InvalidValue) as cm:
self._CreateVmCommand(
gce_migrate_on_maintenance=True, gpu_count=1, gpu_type='k80')
self.assertEqual(str(cm.exception), (
'Cannot set flag gce_migrate_on_maintenance on '
'instances with GPUs, as it is not supported by GCP.'))
def testMigrateOnMaintenanceFlagFalseWithGpus(self):
_, call_count = self._CreateVmCommand(
gce_migrate_on_maintenance=False, gpu_count=1, gpu_type='k80')
self.assertEqual(call_count, 1)
def testAcceleratorTypeOverrideFlag(self):
cmd, call_count = self._CreateVmCommand(
gce_accelerator_type_override='fake_type', gpu_count=1, gpu_type='k80')
self.assertEqual(call_count, 1)
self.assertIn('--accelerator', cmd)
self.assertIn('type=fake_type,count=1', cmd)
def testImageProjectFlag(self):
cmd, call_count = self._CreateVmCommand(image_project='bar')
self.assertEqual(call_count, 1)
self.assertIn('--image-project bar', cmd)
def testNetworkTierFlagPremium(self):
cmd, call_count = self._CreateVmCommand(gce_network_tier='premium')
self.assertEqual(call_count, 1)
self.assertIn('--network-tier PREMIUM', cmd)
def testNetworkTierFlagStandard(self):
cmd, call_count = self._CreateVmCommand(gce_network_tier='standard')
self.assertEqual(call_count, 1)
self.assertIn('--network-tier STANDARD', cmd)
def testGcpInstanceMetadataFlag(self):
cmd, call_count = self._CreateVmCommand(
gcp_instance_metadata=['k1:v1', 'k2:v2,k3:v3'], owner='test-owner')
self.assertEqual(call_count, 1)
actual_metadata = re.compile(
r'--metadata\s+(.*)(\s+--)?').search(cmd).group(1)
self.assertIn('k1=v1', actual_metadata)
self.assertIn('k2=v2', actual_metadata)
self.assertIn('k3=v3', actual_metadata)
# Assert that FLAGS.owner is honored and added to instance metadata.
self.assertIn('owner=test-owner', actual_metadata)
def testGcpInstanceMetadataFromFileFlag(self):
cmd, call_count = self._CreateVmCommand(
gcp_instance_metadata_from_file=['k1:p1', 'k2:p2,k3:p3'])
self.assertEqual(call_count, 1)
actual_metadata_from_file = re.compile(
r'--metadata-from-file\s+(.*)(\s+--)?').search(cmd).group(1)
self.assertIn('k1=p1', actual_metadata_from_file)
self.assertIn('k2=p2', actual_metadata_from_file)
self.assertIn('k3=p3', actual_metadata_from_file)
def testGceTags(self):
self.assertIn('--tags perfkitbenchmarker', self._CreateVmCommand()[0])
self.assertIn('--tags perfkitbenchmarker,testtag',
self._CreateVmCommand(gce_tags=['testtag'])[0])
def testShieldedSecureBootFlag(self):
cmd, call_count = self._CreateVmCommand(
gce_shielded_secure_boot=True)
self.assertEqual(call_count, 1)
self.assertIn('--shielded-secure-boot', cmd)
class GCEVMCreateTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GCEVMCreateTestCase, self).setUp()
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceNetwork.GetNetwork')
self.mock_get_network = p.start()
self.addCleanup(p.stop)
p = mock.patch(gce_virtual_machine.__name__ +
'.gce_network.GceFirewall.GetFirewall')
self.mock_get_firewall = p.start()
self.addCleanup(p.stop)
get_tmp_dir_mock = mock.patch(
vm_util.__name__ + '.GetTempDir', return_value='TempDir')
get_tmp_dir_mock.start()
self.addCleanup(get_tmp_dir_mock.stop)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testCreateRateLimitedMachineCreated(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'The resource already exists', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm._Create() # No error should be thrown.
self.assertEqual(issue_command.call_count, 5)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testCreateRateLimitedMachineCreatedFailure(self, mock_cmd):
fake_rets = []
for _ in range(0, 100):
fake_rets.append(('stdout', 'Rate Limit Exceeded', 1))
with PatchCriticalObjects(fake_rets) as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
with self.assertRaises(
errors.Benchmarks.QuotaFailure.RateLimitExceededError):
vm._Create()
self.assertEqual(issue_command.call_count,
util.RATE_LIMITED_MAX_RETRIES + 1)
def testCreateVMAlreadyExists(self):
fake_rets = [('stdout', 'The resource already exists', 1)]
with PatchCriticalObjects(fake_rets):
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
with self.assertRaises(errors.Resource.CreationError):
vm._Create()
def testVmWithoutGpu(self):
with PatchCriticalObjects() as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT, machine_type={
'cpus': 1,
'memory': '1.0GiB',
})
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm._Create()
self.assertEqual(issue_command.call_count, 1)
self.assertNotIn('--accelerator', issue_command.call_args[0][0])
def testVmWithGpu(self):
with PatchCriticalObjects() as issue_command:
spec = gce_virtual_machine.GceVmSpec(
_COMPONENT,
machine_type='n1-standard-8',
gpu_count=2,
gpu_type='k80')
vm = pkb_common_test_case.TestGceVirtualMachine(spec)
vm._Create()
self.assertEqual(issue_command.call_count, 1)
self.assertIn('--accelerator', issue_command.call_args[0][0])
self.assertIn('type=nvidia-tesla-k80,count=2',
issue_command.call_args[0][0])
self.assertIn('--maintenance-policy', issue_command.call_args[0][0])
self.assertIn('TERMINATE', issue_command.call_args[0][0])
class GceFirewallRuleTest(pkb_common_test_case.PkbCommonTestCase):
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleSuccessfulAfterRateLimited(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'some warning perhaps', 0)]
with PatchCriticalObjects(fake_rets) as issue_command:
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 2)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleGenericErrorAfterRateLimited(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'some random firewall error', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
with self.assertRaises(errors.VmUtil.IssueCommandError):
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 3)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleAlreadyExistsAfterRateLimited(self, mock_cmd):
fake_rets = [('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'Rate Limit Exceeded', 1),
('stdout', 'firewall already exists', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 3)
@mock.patch('time.sleep', side_effect=lambda _: None)
def testGceFirewallRuleGenericError(self, mock_cmd):
fake_rets = [('stdout', 'some random firewall error', 1)]
with PatchCriticalObjects(fake_rets) as issue_command:
with self.assertRaises(errors.VmUtil.IssueCommandError):
fr = gce_network.GceFirewallRule('name', 'project', 'allow',
'network_name')
fr._Create()
self.assertEqual(issue_command.call_count, 1)
class GceNetworkTest(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(GceNetworkTest, self).setUp()
# need a benchmarkspec in the context to run
config_spec = benchmark_config_spec.BenchmarkConfigSpec(
'cluster_boot', flag_values=FLAGS)
benchmark_spec.BenchmarkSpec(mock.Mock(), config_spec, 'uid')
def testGetNetwork(self):
project = 'myproject'
zone = 'us-east1-a'
vm = mock.Mock(zone=zone, project=project, cidr=None)
net = gce_network.GceNetwork.GetNetwork(vm)
self.assertEqual(project, net.project)
self.assertEqual(zone, net.zone)
if __name__ == '__main__':
unittest.main()
| true | true |
f72b8e84fb1e9a3b3bd3404c7c3d64a53cc6b63f | 4,233 | py | Python | Chapter 05/enc_dec/model.py | bpbpublications/Time-Series-Forecasting-using-Deep-Learning | fd84553d33e912edb4a1400af0f9374e72747457 | [
"MIT"
] | 7 | 2021-12-13T20:00:05.000Z | 2022-03-11T08:44:43.000Z | Chapter 05/enc_dec/model.py | bpbpublications/Time-Series-Forecasting-using-Deep-Learning | fd84553d33e912edb4a1400af0f9374e72747457 | [
"MIT"
] | 1 | 2022-02-22T10:39:12.000Z | 2022-02-22T10:39:12.000Z | Chapter 05/enc_dec/model.py | bpbpublications/Time-Series-Forecasting-using-Deep-Learning | fd84553d33e912edb4a1400af0f9374e72747457 | [
"MIT"
] | null | null | null | import numpy as np
import random
import torch
import torch.nn as nn
from torch import optim
class Encoder(nn.Module):
def __init__(self, input_size, hidden_size, num_layers = 1):
super(Encoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size = input_size, hidden_size = hidden_size, num_layers = num_layers)
def forward(self, x):
flat = x.view(x.shape[0], x.shape[1], self.input_size)
out, h = self.lstm(flat)
return out, h
class Decoder(nn.Module):
def __init__(self, input_size, hidden_size, output_size = 1, num_layers = 1):
super(Decoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.output_size = output_size
self.lstm = nn.LSTM(input_size = input_size, hidden_size = hidden_size, num_layers = num_layers)
self.linear = nn.Linear(hidden_size, output_size)
def forward(self, x, h):
out, h = self.lstm(x.unsqueeze(0), h)
y = self.linear(out.squeeze(0))
return y, h
class EncoderDecoder(nn.Module):
def __init__(self, hidden_size, input_size = 1, output_size = 1):
super(EncoderDecoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.encoder = Encoder(input_size = input_size, hidden_size = hidden_size)
self.decoder = Decoder(input_size = input_size, hidden_size = hidden_size, output_size = output_size)
def train_model(
self, train, target, epochs, target_len, method = 'recursive',
tfr = 0.5, lr = 0.01, dynamic_tf = False
):
losses = np.full(epochs, np.nan)
optimizer = optim.Adam(self.parameters(), lr = lr)
criterion = nn.MSELoss()
for e in range(epochs):
predicted = torch.zeros(target_len, train.shape[1], train.shape[2])
optimizer.zero_grad()
_, enc_h = self.encoder(train)
dec_in = train[-1, :, :]
dec_h = enc_h
if method == 'recursive':
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
dec_in = dec_out
if method == 'teacher_forcing':
# use teacher forcing
if random.random() < tfr:
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
dec_in = target[t, :, :]
# predict recursively
else:
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
dec_in = dec_out
if method == 'mixed_teacher_forcing':
# predict using mixed teacher forcing
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
# predict with teacher forcing
if random.random() < tfr:
dec_in = target[t, :, :]
# predict recursively
else:
dec_in = dec_out
loss = criterion(predicted, target)
loss.backward()
optimizer.step()
losses[e] = loss.item()
if e % 10 == 0:
print(f'Epoch {e}/{epochs}: {round(loss.item(), 4)}')
# dynamic teacher forcing
if dynamic_tf and tfr > 0:
tfr = tfr - 0.02
return losses
def predict(self, x, target_len):
y = torch.zeros(target_len, x.shape[1], x.shape[2])
_, enc_h = self.encoder(x)
dec_in = x[-1, :, :]
dec_h = enc_h
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
y[t] = dec_out
dec_in = dec_out
return y
| 33.070313 | 109 | 0.541932 | import numpy as np
import random
import torch
import torch.nn as nn
from torch import optim
class Encoder(nn.Module):
def __init__(self, input_size, hidden_size, num_layers = 1):
super(Encoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size = input_size, hidden_size = hidden_size, num_layers = num_layers)
def forward(self, x):
flat = x.view(x.shape[0], x.shape[1], self.input_size)
out, h = self.lstm(flat)
return out, h
class Decoder(nn.Module):
def __init__(self, input_size, hidden_size, output_size = 1, num_layers = 1):
super(Decoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.output_size = output_size
self.lstm = nn.LSTM(input_size = input_size, hidden_size = hidden_size, num_layers = num_layers)
self.linear = nn.Linear(hidden_size, output_size)
def forward(self, x, h):
out, h = self.lstm(x.unsqueeze(0), h)
y = self.linear(out.squeeze(0))
return y, h
class EncoderDecoder(nn.Module):
def __init__(self, hidden_size, input_size = 1, output_size = 1):
super(EncoderDecoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.encoder = Encoder(input_size = input_size, hidden_size = hidden_size)
self.decoder = Decoder(input_size = input_size, hidden_size = hidden_size, output_size = output_size)
def train_model(
self, train, target, epochs, target_len, method = 'recursive',
tfr = 0.5, lr = 0.01, dynamic_tf = False
):
losses = np.full(epochs, np.nan)
optimizer = optim.Adam(self.parameters(), lr = lr)
criterion = nn.MSELoss()
for e in range(epochs):
predicted = torch.zeros(target_len, train.shape[1], train.shape[2])
optimizer.zero_grad()
_, enc_h = self.encoder(train)
dec_in = train[-1, :, :]
dec_h = enc_h
if method == 'recursive':
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
dec_in = dec_out
if method == 'teacher_forcing':
if random.random() < tfr:
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
dec_in = target[t, :, :]
else:
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
dec_in = dec_out
if method == 'mixed_teacher_forcing':
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
predicted[t] = dec_out
if random.random() < tfr:
dec_in = target[t, :, :]
else:
dec_in = dec_out
loss = criterion(predicted, target)
loss.backward()
optimizer.step()
losses[e] = loss.item()
if e % 10 == 0:
print(f'Epoch {e}/{epochs}: {round(loss.item(), 4)}')
if dynamic_tf and tfr > 0:
tfr = tfr - 0.02
return losses
def predict(self, x, target_len):
y = torch.zeros(target_len, x.shape[1], x.shape[2])
_, enc_h = self.encoder(x)
dec_in = x[-1, :, :]
dec_h = enc_h
for t in range(target_len):
dec_out, dec_h = self.decoder(dec_in, dec_h)
y[t] = dec_out
dec_in = dec_out
return y
| true | true |
f72b917ba1bfdb505c6c57281ee679daa562ced3 | 4,564 | py | Python | galaxy/tools/deps/__init__.py | jmchilton/pulsar | 783b90cf0bce893a11c347fcaf6778b98e0bb062 | [
"Apache-2.0"
] | null | null | null | galaxy/tools/deps/__init__.py | jmchilton/pulsar | 783b90cf0bce893a11c347fcaf6778b98e0bb062 | [
"Apache-2.0"
] | 1 | 2015-02-21T18:48:19.000Z | 2015-02-27T15:50:32.000Z | galaxy/tools/deps/__init__.py | jmchilton/pulsar | 783b90cf0bce893a11c347fcaf6778b98e0bb062 | [
"Apache-2.0"
] | 3 | 2015-02-22T13:34:16.000Z | 2020-10-01T01:28:04.000Z | """
Dependency management for tools.
"""
import os.path
import logging
log = logging.getLogger( __name__ )
from .resolvers import INDETERMINATE_DEPENDENCY
from .resolvers.galaxy_packages import GalaxyPackageDependencyResolver
from .resolvers.tool_shed_packages import ToolShedPackageDependencyResolver
from galaxy.util import plugin_config
def build_dependency_manager( config ):
if getattr( config, "use_tool_dependencies", False ):
dependency_manager_kwds = {
'default_base_path': config.tool_dependency_dir,
'conf_file': config.dependency_resolvers_config_file,
}
dependency_manager = DependencyManager( **dependency_manager_kwds )
else:
dependency_manager = NullDependencyManager()
return dependency_manager
class NullDependencyManager( object ):
def uses_tool_shed_dependencies(self):
return False
def dependency_shell_commands( self, requirements, **kwds ):
return []
def find_dep( self, name, version=None, type='package', **kwds ):
return INDETERMINATE_DEPENDENCY
class DependencyManager( object ):
"""
A DependencyManager attempts to resolve named and versioned dependencies by
searching for them under a list of directories. Directories should be
of the form:
$BASE/name/version/...
and should each contain a file 'env.sh' which can be sourced to make the
dependency available in the current shell environment.
"""
def __init__( self, default_base_path, conf_file=None ):
"""
Create a new dependency manager looking for packages under the paths listed
in `base_paths`. The default base path is app.config.tool_dependency_dir.
"""
if not os.path.exists( default_base_path ):
log.warn( "Path '%s' does not exist, ignoring", default_base_path )
if not os.path.isdir( default_base_path ):
log.warn( "Path '%s' is not directory, ignoring", default_base_path )
self.default_base_path = os.path.abspath( default_base_path )
self.resolver_classes = self.__resolvers_dict()
self.dependency_resolvers = self.__build_dependency_resolvers( conf_file )
def dependency_shell_commands( self, requirements, **kwds ):
commands = []
for requirement in requirements:
log.debug( "Building dependency shell command for dependency '%s'", requirement.name )
dependency = INDETERMINATE_DEPENDENCY
if requirement.type in [ 'package', 'set_environment' ]:
dependency = self.find_dep( name=requirement.name,
version=requirement.version,
type=requirement.type,
**kwds )
dependency_commands = dependency.shell_commands( requirement )
if not dependency_commands:
log.warn( "Failed to resolve dependency on '%s', ignoring", requirement.name )
else:
commands.append( dependency_commands )
return commands
def uses_tool_shed_dependencies(self):
return any( map( lambda r: isinstance( r, ToolShedPackageDependencyResolver ), self.dependency_resolvers ) )
def find_dep( self, name, version=None, type='package', **kwds ):
for resolver in self.dependency_resolvers:
dependency = resolver.resolve( name, version, type, **kwds )
if dependency != INDETERMINATE_DEPENDENCY:
return dependency
return INDETERMINATE_DEPENDENCY
def __build_dependency_resolvers( self, conf_file ):
if not conf_file or not os.path.exists( conf_file ):
return self.__default_dependency_resolvers()
plugin_source = plugin_config.plugin_source_from_path( conf_file )
return self.__parse_resolver_conf_xml( plugin_source )
def __default_dependency_resolvers( self ):
return [
ToolShedPackageDependencyResolver(self),
GalaxyPackageDependencyResolver(self),
GalaxyPackageDependencyResolver(self, versionless=True),
]
def __parse_resolver_conf_xml(self, plugin_source):
"""
"""
extra_kwds = dict( dependency_manager=self )
return plugin_config.load_plugins( self.resolver_classes, plugin_source, extra_kwds )
def __resolvers_dict( self ):
import galaxy.tools.deps.resolvers
return plugin_config.plugins_dict( galaxy.tools.deps.resolvers, 'resolver_type' )
| 40.035088 | 116 | 0.675066 |
import os.path
import logging
log = logging.getLogger( __name__ )
from .resolvers import INDETERMINATE_DEPENDENCY
from .resolvers.galaxy_packages import GalaxyPackageDependencyResolver
from .resolvers.tool_shed_packages import ToolShedPackageDependencyResolver
from galaxy.util import plugin_config
def build_dependency_manager( config ):
if getattr( config, "use_tool_dependencies", False ):
dependency_manager_kwds = {
'default_base_path': config.tool_dependency_dir,
'conf_file': config.dependency_resolvers_config_file,
}
dependency_manager = DependencyManager( **dependency_manager_kwds )
else:
dependency_manager = NullDependencyManager()
return dependency_manager
class NullDependencyManager( object ):
def uses_tool_shed_dependencies(self):
return False
def dependency_shell_commands( self, requirements, **kwds ):
return []
def find_dep( self, name, version=None, type='package', **kwds ):
return INDETERMINATE_DEPENDENCY
class DependencyManager( object ):
def __init__( self, default_base_path, conf_file=None ):
if not os.path.exists( default_base_path ):
log.warn( "Path '%s' does not exist, ignoring", default_base_path )
if not os.path.isdir( default_base_path ):
log.warn( "Path '%s' is not directory, ignoring", default_base_path )
self.default_base_path = os.path.abspath( default_base_path )
self.resolver_classes = self.__resolvers_dict()
self.dependency_resolvers = self.__build_dependency_resolvers( conf_file )
def dependency_shell_commands( self, requirements, **kwds ):
commands = []
for requirement in requirements:
log.debug( "Building dependency shell command for dependency '%s'", requirement.name )
dependency = INDETERMINATE_DEPENDENCY
if requirement.type in [ 'package', 'set_environment' ]:
dependency = self.find_dep( name=requirement.name,
version=requirement.version,
type=requirement.type,
**kwds )
dependency_commands = dependency.shell_commands( requirement )
if not dependency_commands:
log.warn( "Failed to resolve dependency on '%s', ignoring", requirement.name )
else:
commands.append( dependency_commands )
return commands
def uses_tool_shed_dependencies(self):
return any( map( lambda r: isinstance( r, ToolShedPackageDependencyResolver ), self.dependency_resolvers ) )
def find_dep( self, name, version=None, type='package', **kwds ):
for resolver in self.dependency_resolvers:
dependency = resolver.resolve( name, version, type, **kwds )
if dependency != INDETERMINATE_DEPENDENCY:
return dependency
return INDETERMINATE_DEPENDENCY
def __build_dependency_resolvers( self, conf_file ):
if not conf_file or not os.path.exists( conf_file ):
return self.__default_dependency_resolvers()
plugin_source = plugin_config.plugin_source_from_path( conf_file )
return self.__parse_resolver_conf_xml( plugin_source )
def __default_dependency_resolvers( self ):
return [
ToolShedPackageDependencyResolver(self),
GalaxyPackageDependencyResolver(self),
GalaxyPackageDependencyResolver(self, versionless=True),
]
def __parse_resolver_conf_xml(self, plugin_source):
extra_kwds = dict( dependency_manager=self )
return plugin_config.load_plugins( self.resolver_classes, plugin_source, extra_kwds )
def __resolvers_dict( self ):
import galaxy.tools.deps.resolvers
return plugin_config.plugins_dict( galaxy.tools.deps.resolvers, 'resolver_type' )
| true | true |
f72b91de3aa8e38ef7f1435603855433b8cce9c5 | 6,254 | py | Python | python/fate_arch/protobuf/python/model_service_pb2_grpc.py | hubert-he/FATE | 6758e150bd7ca7d6f788f9a7a8c8aea7e6500363 | [
"Apache-2.0"
] | 3,787 | 2019-08-30T04:55:10.000Z | 2022-03-31T23:30:07.000Z | python/fate_arch/protobuf/python/model_service_pb2_grpc.py | JavaGreenHands/FATE | ea1e94b6be50c70c354d1861093187e523af32f2 | [
"Apache-2.0"
] | 1,439 | 2019-08-29T16:35:52.000Z | 2022-03-31T11:55:31.000Z | python/fate_arch/protobuf/python/model_service_pb2_grpc.py | JavaGreenHands/FATE | ea1e94b6be50c70c354d1861093187e523af32f2 | [
"Apache-2.0"
] | 1,179 | 2019-08-29T16:18:32.000Z | 2022-03-31T12:55:38.000Z | #
# Copyright 2019 The FATE 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.
#
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import model_service_pb2 as model__service__pb2
class ModelServiceStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.publishLoad = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/publishLoad',
request_serializer=model__service__pb2.PublishRequest.SerializeToString,
response_deserializer=model__service__pb2.PublishResponse.FromString,
)
self.publishBind = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/publishBind',
request_serializer=model__service__pb2.PublishRequest.SerializeToString,
response_deserializer=model__service__pb2.PublishResponse.FromString,
)
self.publishOnline = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/publishOnline',
request_serializer=model__service__pb2.PublishRequest.SerializeToString,
response_deserializer=model__service__pb2.PublishResponse.FromString,
)
self.queryModel = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/queryModel',
request_serializer=model__service__pb2.QueryModelRequest.SerializeToString,
response_deserializer=model__service__pb2.QueryModelResponse.FromString,
)
self.unload = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/unload',
request_serializer=model__service__pb2.UnloadRequest.SerializeToString,
response_deserializer=model__service__pb2.UnloadResponse.FromString,
)
self.unbind = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/unbind',
request_serializer=model__service__pb2.UnbindRequest.SerializeToString,
response_deserializer=model__service__pb2.UnbindResponse.FromString,
)
class ModelServiceServicer(object):
# missing associated documentation comment in .proto file
pass
def publishLoad(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def publishBind(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def publishOnline(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def queryModel(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def unload(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def unbind(self, request, context):
# missing associated documentation comment in .proto file
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ModelServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'publishLoad': grpc.unary_unary_rpc_method_handler(
servicer.publishLoad,
request_deserializer=model__service__pb2.PublishRequest.FromString,
response_serializer=model__service__pb2.PublishResponse.SerializeToString,
),
'publishBind': grpc.unary_unary_rpc_method_handler(
servicer.publishBind,
request_deserializer=model__service__pb2.PublishRequest.FromString,
response_serializer=model__service__pb2.PublishResponse.SerializeToString,
),
'publishOnline': grpc.unary_unary_rpc_method_handler(
servicer.publishOnline,
request_deserializer=model__service__pb2.PublishRequest.FromString,
response_serializer=model__service__pb2.PublishResponse.SerializeToString,
),
'queryModel': grpc.unary_unary_rpc_method_handler(
servicer.queryModel,
request_deserializer=model__service__pb2.QueryModelRequest.FromString,
response_serializer=model__service__pb2.QueryModelResponse.SerializeToString,
),
'unload': grpc.unary_unary_rpc_method_handler(
servicer.unload,
request_deserializer=model__service__pb2.UnloadRequest.FromString,
response_serializer=model__service__pb2.UnloadResponse.SerializeToString,
),
'unbind': grpc.unary_unary_rpc_method_handler(
servicer.unbind,
request_deserializer=model__service__pb2.UnbindRequest.FromString,
response_serializer=model__service__pb2.UnbindResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'com.webank.ai.fate.api.mlmodel.manager.ModelService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
| 42.544218 | 87 | 0.756316 |
import grpc
import model_service_pb2 as model__service__pb2
class ModelServiceStub(object):
pass
def __init__(self, channel):
self.publishLoad = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/publishLoad',
request_serializer=model__service__pb2.PublishRequest.SerializeToString,
response_deserializer=model__service__pb2.PublishResponse.FromString,
)
self.publishBind = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/publishBind',
request_serializer=model__service__pb2.PublishRequest.SerializeToString,
response_deserializer=model__service__pb2.PublishResponse.FromString,
)
self.publishOnline = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/publishOnline',
request_serializer=model__service__pb2.PublishRequest.SerializeToString,
response_deserializer=model__service__pb2.PublishResponse.FromString,
)
self.queryModel = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/queryModel',
request_serializer=model__service__pb2.QueryModelRequest.SerializeToString,
response_deserializer=model__service__pb2.QueryModelResponse.FromString,
)
self.unload = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/unload',
request_serializer=model__service__pb2.UnloadRequest.SerializeToString,
response_deserializer=model__service__pb2.UnloadResponse.FromString,
)
self.unbind = channel.unary_unary(
'/com.webank.ai.fate.api.mlmodel.manager.ModelService/unbind',
request_serializer=model__service__pb2.UnbindRequest.SerializeToString,
response_deserializer=model__service__pb2.UnbindResponse.FromString,
)
class ModelServiceServicer(object):
pass
def publishLoad(self, request, context):
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def publishBind(self, request, context):
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def publishOnline(self, request, context):
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def queryModel(self, request, context):
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def unload(self, request, context):
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def unbind(self, request, context):
pass
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_ModelServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'publishLoad': grpc.unary_unary_rpc_method_handler(
servicer.publishLoad,
request_deserializer=model__service__pb2.PublishRequest.FromString,
response_serializer=model__service__pb2.PublishResponse.SerializeToString,
),
'publishBind': grpc.unary_unary_rpc_method_handler(
servicer.publishBind,
request_deserializer=model__service__pb2.PublishRequest.FromString,
response_serializer=model__service__pb2.PublishResponse.SerializeToString,
),
'publishOnline': grpc.unary_unary_rpc_method_handler(
servicer.publishOnline,
request_deserializer=model__service__pb2.PublishRequest.FromString,
response_serializer=model__service__pb2.PublishResponse.SerializeToString,
),
'queryModel': grpc.unary_unary_rpc_method_handler(
servicer.queryModel,
request_deserializer=model__service__pb2.QueryModelRequest.FromString,
response_serializer=model__service__pb2.QueryModelResponse.SerializeToString,
),
'unload': grpc.unary_unary_rpc_method_handler(
servicer.unload,
request_deserializer=model__service__pb2.UnloadRequest.FromString,
response_serializer=model__service__pb2.UnloadResponse.SerializeToString,
),
'unbind': grpc.unary_unary_rpc_method_handler(
servicer.unbind,
request_deserializer=model__service__pb2.UnbindRequest.FromString,
response_serializer=model__service__pb2.UnbindResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'com.webank.ai.fate.api.mlmodel.manager.ModelService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
| true | true |
f72b929b8804ad874d618eb5b43b2fb64fdfe7ad | 123 | py | Python | app/api/__init__.py | oyasr/mudawen | 6f0161ab783536d7c5d695225ef28ce4947a46e3 | [
"MIT"
] | null | null | null | app/api/__init__.py | oyasr/mudawen | 6f0161ab783536d7c5d695225ef28ce4947a46e3 | [
"MIT"
] | null | null | null | app/api/__init__.py | oyasr/mudawen | 6f0161ab783536d7c5d695225ef28ce4947a46e3 | [
"MIT"
] | null | null | null | from flask import Blueprint
api = Blueprint('api', __name__)
from . import authentication, comments, errors, posts, users | 24.6 | 60 | 0.772358 | from flask import Blueprint
api = Blueprint('api', __name__)
from . import authentication, comments, errors, posts, users | true | true |
f72b92ac89e1858b89e04e9891a5197b9c3b4cbe | 112,673 | py | Python | youtube_dl/YoutubeDL.py | hylinktree/youtube-dl | e4cc49f0c0cd9939c4d7992ba54ab0737fdaa9b0 | [
"Unlicense"
] | null | null | null | youtube_dl/YoutubeDL.py | hylinktree/youtube-dl | e4cc49f0c0cd9939c4d7992ba54ab0737fdaa9b0 | [
"Unlicense"
] | null | null | null | youtube_dl/YoutubeDL.py | hylinktree/youtube-dl | e4cc49f0c0cd9939c4d7992ba54ab0737fdaa9b0 | [
"Unlicense"
] | null | null | null | #!/usr/bin/env python
# coding: utf-8
from __future__ import absolute_import, unicode_literals
import collections
import contextlib
import copy
import datetime
import errno
import fileinput
import io
import itertools
import json
import locale
import operator
import os
import platform
import re
import shutil
import subprocess
import socket
import sys
import time
import tokenize
import traceback
import random
from string import ascii_letters
from .compat import (
compat_basestring,
compat_cookiejar,
compat_get_terminal_size,
compat_http_client,
compat_kwargs,
compat_numeric_types,
compat_os_name,
compat_str,
compat_tokenize_tokenize,
compat_urllib_error,
compat_urllib_request,
compat_urllib_request_DataHandler,
)
from .utils import (
age_restricted,
args_to_str,
ContentTooShortError,
date_from_str,
DateRange,
DEFAULT_OUTTMPL,
determine_ext,
determine_protocol,
DownloadError,
encode_compat_str,
encodeFilename,
error_to_compat_str,
expand_path,
ExtractorError,
format_bytes,
formatSeconds,
GeoRestrictedError,
int_or_none,
ISO3166Utils,
locked_file,
make_HTTPS_handler,
MaxDownloadsReached,
orderedSet,
PagedList,
parse_filesize,
PerRequestProxyHandler,
platform_name,
PostProcessingError,
preferredencoding,
prepend_extension,
register_socks_protocols,
render_table,
replace_extension,
SameFileError,
sanitize_filename,
sanitize_path,
sanitize_url,
sanitized_Request,
std_headers,
str_or_none,
subtitles_filename,
UnavailableVideoError,
url_basename,
version_tuple,
write_json_file,
write_string,
YoutubeDLCookieJar,
YoutubeDLCookieProcessor,
YoutubeDLHandler,
YoutubeDLRedirectHandler,
)
from .cache import Cache
from .extractor import get_info_extractor, gen_extractor_classes, _LAZY_LOADER
from .extractor.openload import PhantomJSwrapper
from .downloader import get_suitable_downloader
from .downloader.rtmp import rtmpdump_version
from .postprocessor import (
FFmpegFixupM3u8PP,
FFmpegFixupM4aPP,
FFmpegFixupStretchedPP,
FFmpegMergerPP,
FFmpegPostProcessor,
get_postprocessor,
)
from .version import __version__
if compat_os_name == 'nt':
import ctypes
class YoutubeDL(object):
"""YoutubeDL class.
YoutubeDL objects are the ones responsible of downloading the
actual video file and writing it to disk if the user has requested
it, among some other tasks. In most cases there should be one per
program. As, given a video URL, the downloader doesn't know how to
extract all the needed information, task that InfoExtractors do, it
has to pass the URL to one of them.
For this, YoutubeDL objects have a method that allows
InfoExtractors to be registered in a given order. When it is passed
a URL, the YoutubeDL object handles it to the first InfoExtractor it
finds that reports being able to handle it. The InfoExtractor extracts
all the information about the video or videos the URL refers to, and
YoutubeDL process the extracted information, possibly using a File
Downloader to download the video.
YoutubeDL objects accept a lot of parameters. In order not to saturate
the object constructor with arguments, it receives a dictionary of
options instead. These options are available through the params
attribute for the InfoExtractors to use. The YoutubeDL also
registers itself as the downloader in charge for the InfoExtractors
that are added to it, so this is a "mutual registration".
Available options:
username: Username for authentication purposes.
password: Password for authentication purposes.
videopassword: Password for accessing a video.
ap_mso: Adobe Pass multiple-system operator identifier.
ap_username: Multiple-system operator account username.
ap_password: Multiple-system operator account password.
usenetrc: Use netrc for authentication instead.
verbose: Print additional info to stdout.
quiet: Do not print messages to stdout.
no_warnings: Do not print out anything for warnings.
forceurl: Force printing final URL.
forcetitle: Force printing title.
forceid: Force printing ID.
forcethumbnail: Force printing thumbnail URL.
forcedescription: Force printing description.
forcefilename: Force printing final filename.
forceduration: Force printing duration.
forcejson: Force printing info_dict as JSON.
dump_single_json: Force printing the info_dict of the whole playlist
(or video) as a single JSON line.
simulate: Do not download the video files.
format: Video format code. See options.py for more information.
outtmpl: Template for output names.
outtmpl_na_placeholder: Placeholder for unavailable meta fields.
restrictfilenames: Do not allow "&" and spaces in file names
ignoreerrors: Do not stop on download errors.
force_generic_extractor: Force downloader to use the generic extractor
nooverwrites: Prevent overwriting files.
playliststart: Playlist item to start at.
playlistend: Playlist item to end at.
playlist_items: Specific indices of playlist to download.
playlistreverse: Download playlist items in reverse order.
playlistrandom: Download playlist items in random order.
matchtitle: Download only matching titles.
rejecttitle: Reject downloads for matching titles.
logger: Log messages to a logging.Logger instance.
logtostderr: Log messages to stderr instead of stdout.
writedescription: Write the video description to a .description file
writeinfojson: Write the video description to a .info.json file
writeannotations: Write the video annotations to a .annotations.xml file
writethumbnail: Write the thumbnail image to a file
write_all_thumbnails: Write all thumbnail formats to files
writesubtitles: Write the video subtitles to a file
writeautomaticsub: Write the automatically generated subtitles to a file
allsubtitles: Downloads all the subtitles of the video
(requires writesubtitles or writeautomaticsub)
listsubtitles: Lists all available subtitles for the video
subtitlesformat: The format code for subtitles
subtitleslangs: List of languages of the subtitles to download
keepvideo: Keep the video file after post-processing
daterange: A DateRange object, download only if the upload_date is in the range.
skip_download: Skip the actual download of the video file
cachedir: Location of the cache files in the filesystem.
False to disable filesystem cache.
noplaylist: Download single video instead of a playlist if in doubt.
age_limit: An integer representing the user's age in years.
Unsuitable videos for the given age are skipped.
min_views: An integer representing the minimum view count the video
must have in order to not be skipped.
Videos without view count information are always
downloaded. None for no limit.
max_views: An integer representing the maximum view count.
Videos that are more popular than that are not
downloaded.
Videos without view count information are always
downloaded. None for no limit.
download_archive: File name of a file where all downloads are recorded.
Videos already present in the file are not downloaded
again.
cookiefile: File name where cookies should be read from and dumped to.
nocheckcertificate:Do not verify SSL certificates
prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
At the moment, this is only supported by YouTube.
proxy: URL of the proxy server to use
geo_verification_proxy: URL of the proxy to use for IP address verification
on geo-restricted sites.
socket_timeout: Time to wait for unresponsive hosts, in seconds
bidi_workaround: Work around buggy terminals without bidirectional text
support, using fridibi
debug_printtraffic:Print out sent and received HTTP traffic
include_ads: Download ads as well
default_search: Prepend this string if an input url is not valid.
'auto' for elaborate guessing
encoding: Use this encoding instead of the system-specified.
extract_flat: Do not resolve URLs, return the immediate result.
Pass in 'in_playlist' to only show this behavior for
playlist items.
postprocessors: A list of dictionaries, each with an entry
* key: The name of the postprocessor. See
youtube_dl/postprocessor/__init__.py for a list.
as well as any further keyword arguments for the
postprocessor.
progress_hooks: A list of functions that get called on download
progress, with a dictionary with the entries
* status: One of "downloading", "error", or "finished".
Check this first and ignore unknown values.
If status is one of "downloading", or "finished", the
following properties may also be present:
* filename: The final filename (always present)
* tmpfilename: The filename we're currently writing to
* downloaded_bytes: Bytes on disk
* total_bytes: Size of the whole file, None if unknown
* total_bytes_estimate: Guess of the eventual file size,
None if unavailable.
* elapsed: The number of seconds since download started.
* eta: The estimated time in seconds, None if unknown
* speed: The download speed in bytes/second, None if
unknown
* fragment_index: The counter of the currently
downloaded video fragment.
* fragment_count: The number of fragments (= individual
files that will be merged)
Progress hooks are guaranteed to be called at least once
(with status "finished") if the download is successful.
merge_output_format: Extension to use when merging formats.
fixup: Automatically correct known faults of the file.
One of:
- "never": do nothing
- "warn": only emit a warning
- "detect_or_warn": check whether we can do anything
about it, warn otherwise (default)
source_address: Client-side IP address to bind to.
call_home: Boolean, true iff we are allowed to contact the
youtube-dl servers for debugging.
sleep_interval: Number of seconds to sleep before each download when
used alone or a lower bound of a range for randomized
sleep before each download (minimum possible number
of seconds to sleep) when used along with
max_sleep_interval.
max_sleep_interval:Upper bound of a range for randomized sleep before each
download (maximum possible number of seconds to sleep).
Must only be used along with sleep_interval.
Actual sleep time will be a random float from range
[sleep_interval; max_sleep_interval].
listformats: Print an overview of available video formats and exit.
list_thumbnails: Print a table of all thumbnails and exit.
match_filter: A function that gets called with the info_dict of
every video.
If it returns a message, the video is ignored.
If it returns None, the video is downloaded.
match_filter_func in utils.py is one example for this.
no_color: Do not emit color codes in output.
geo_bypass: Bypass geographic restriction via faking X-Forwarded-For
HTTP header
geo_bypass_country:
Two-letter ISO 3166-2 country code that will be used for
explicit geographic restriction bypassing via faking
X-Forwarded-For HTTP header
geo_bypass_ip_block:
IP range in CIDR notation that will be used similarly to
geo_bypass_country
The following options determine which downloader is picked:
external_downloader: Executable of the external downloader to call.
None or unset for standard (built-in) downloader.
hls_prefer_native: Use the native HLS downloader instead of ffmpeg/avconv
if True, otherwise use ffmpeg/avconv if False, otherwise
use downloader suggested by extractor if None.
The following parameters are not used by YoutubeDL itself, they are used by
the downloader (see youtube_dl/downloader/common.py):
nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
noresizebuffer, retries, continuedl, noprogress, consoletitle,
xattr_set_filesize, external_downloader_args, hls_use_mpegts,
http_chunk_size.
The following options are used by the post processors:
prefer_ffmpeg: If False, use avconv instead of ffmpeg if both are available,
otherwise prefer ffmpeg.
ffmpeg_location: Location of the ffmpeg/avconv binary; either the path
to the binary or its containing directory.
postprocessor_args: A list of additional command-line arguments for the
postprocessor.
The following options are used by the Youtube extractor:
youtube_include_dash_manifest: If True (default), DASH manifests and related
data will be downloaded and processed by extractor.
You can reduce network I/O by disabling it if you don't
care about DASH.
"""
_NUMERIC_FIELDS = set((
'width', 'height', 'tbr', 'abr', 'asr', 'vbr', 'fps', 'filesize', 'filesize_approx',
'timestamp', 'upload_year', 'upload_month', 'upload_day',
'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
'average_rating', 'comment_count', 'age_limit',
'start_time', 'end_time',
'chapter_number', 'season_number', 'episode_number',
'track_number', 'disc_number', 'release_year',
'playlist_index',
))
params = None
_ies = []
_pps = []
_download_retcode = None
_num_downloads = None
_playlist_level = 0
_playlist_urls = set()
_screen_file = None
def __init__(self, params=None, auto_init=True):
"""Create a FileDownloader object with the given options."""
if params is None:
params = {}
self._ies = []
self._ies_instances = {}
self._pps = []
self._progress_hooks = []
self._download_retcode = 0
self._num_downloads = 0
self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
self._err_file = sys.stderr
self.params = {
# Default parameters
'nocheckcertificate': False,
}
self.params.update(params)
self.cache = Cache(self)
def check_deprecated(param, option, suggestion):
if self.params.get(param) is not None:
self.report_warning(
'%s is deprecated. Use %s instead.' % (option, suggestion))
return True
return False
if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
if self.params.get('geo_verification_proxy') is None:
self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
check_deprecated('autonumber_size', '--autonumber-size', 'output template with %(autonumber)0Nd, where N in the number of digits')
check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
if params.get('bidi_workaround', False):
try:
import pty
master, slave = pty.openpty()
width = compat_get_terminal_size().columns
if width is None:
width_args = []
else:
width_args = ['-w', str(width)]
sp_kwargs = dict(
stdin=subprocess.PIPE,
stdout=slave,
stderr=self._err_file)
try:
self._output_process = subprocess.Popen(
['bidiv'] + width_args, **sp_kwargs
)
except OSError:
self._output_process = subprocess.Popen(
['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
self._output_channel = os.fdopen(master, 'rb')
except OSError as ose:
if ose.errno == errno.ENOENT:
self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
else:
raise
if (sys.platform != 'win32'
and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
and not params.get('restrictfilenames', False)):
# Unicode filesystem API will throw errors (#1474, #13027)
self.report_warning(
'Assuming --restrict-filenames since file system encoding '
'cannot encode all characters. '
'Set the LC_ALL environment variable to fix this.')
self.params['restrictfilenames'] = True
if isinstance(params.get('outtmpl'), bytes):
self.report_warning(
'Parameter outtmpl is bytes, but should be a unicode string. '
'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
self._setup_opener()
if auto_init:
self.print_debug_header()
self.add_default_info_extractors()
for pp_def_raw in self.params.get('postprocessors', []):
pp_class = get_postprocessor(pp_def_raw['key'])
pp_def = dict(pp_def_raw)
del pp_def['key']
pp = pp_class(self, **compat_kwargs(pp_def))
self.add_post_processor(pp)
for ph in self.params.get('progress_hooks', []):
self.add_progress_hook(ph)
register_socks_protocols()
def warn_if_short_id(self, argv):
# short YouTube ID starting with dash?
idxs = [
i for i, a in enumerate(argv)
if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
if idxs:
correct_argv = (
['youtube-dl']
+ [a for i, a in enumerate(argv) if i not in idxs]
+ ['--'] + [argv[i] for i in idxs]
)
self.report_warning(
'Long argument string detected. '
'Use -- to separate parameters and URLs, like this:\n%s\n' %
args_to_str(correct_argv))
def add_info_extractor(self, ie):
"""Add an InfoExtractor object to the end of the list."""
self._ies.append(ie)
if not isinstance(ie, type):
self._ies_instances[ie.ie_key()] = ie
ie.set_downloader(self)
def get_info_extractor(self, ie_key):
"""
Get an instance of an IE with name ie_key, it will try to get one from
the _ies list, if there's no instance it will create a new one and add
it to the extractor list.
"""
ie = self._ies_instances.get(ie_key)
if ie is None:
ie = get_info_extractor(ie_key)()
self.add_info_extractor(ie)
return ie
def add_default_info_extractors(self):
"""
Add the InfoExtractors returned by gen_extractors to the end of the list
"""
for ie in gen_extractor_classes():
self.add_info_extractor(ie)
def add_post_processor(self, pp):
"""Add a PostProcessor object to the end of the chain."""
self._pps.append(pp)
pp.set_downloader(self)
def add_progress_hook(self, ph):
"""Add the progress hook (currently only for the file downloader)"""
self._progress_hooks.append(ph)
def _bidi_workaround(self, message):
if not hasattr(self, '_output_channel'):
return message
assert hasattr(self, '_output_process')
assert isinstance(message, compat_str)
line_count = message.count('\n') + 1
self._output_process.stdin.write((message + '\n').encode('utf-8'))
self._output_process.stdin.flush()
res = ''.join(self._output_channel.readline().decode('utf-8')
for _ in range(line_count))
return res[:-len('\n')]
def to_screen(self, message, skip_eol=False):
"""Print message to stdout if not in quiet mode."""
return self.to_stdout(message, skip_eol, check_quiet=True)
def _write_string(self, s, out=None):
write_string(s, out=out, encoding=self.params.get('encoding'))
def to_stdout(self, message, skip_eol=False, check_quiet=False):
"""Print message to stdout if not in quiet mode."""
if self.params.get('logger'):
self.params['logger'].debug(message)
elif not check_quiet or not self.params.get('quiet', False):
message = self._bidi_workaround(message)
terminator = ['\n', ''][skip_eol]
output = message + terminator
self._write_string(output, self._screen_file)
def to_stderr(self, message):
"""Print message to stderr."""
assert isinstance(message, compat_str)
if self.params.get('logger'):
self.params['logger'].error(message)
else:
message = self._bidi_workaround(message)
output = message + '\n'
self._write_string(output, self._err_file)
def to_console_title(self, message):
if not self.params.get('consoletitle', False):
return
if compat_os_name == 'nt':
if ctypes.windll.kernel32.GetConsoleWindow():
# c_wchar_p() might not be necessary if `message` is
# already of type unicode()
ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
elif 'TERM' in os.environ:
self._write_string('\033]0;%s\007' % message, self._screen_file)
def save_console_title(self):
if not self.params.get('consoletitle', False):
return
if self.params.get('simulate', False):
return
if compat_os_name != 'nt' and 'TERM' in os.environ:
# Save the title on stack
self._write_string('\033[22;0t', self._screen_file)
def restore_console_title(self):
if not self.params.get('consoletitle', False):
return
if self.params.get('simulate', False):
return
if compat_os_name != 'nt' and 'TERM' in os.environ:
# Restore the title from stack
self._write_string('\033[23;0t', self._screen_file)
def __enter__(self):
self.save_console_title()
return self
def __exit__(self, *args):
self.restore_console_title()
if self.params.get('cookiefile') is not None:
self.cookiejar.save(ignore_discard=True, ignore_expires=True)
def trouble(self, message=None, tb=None):
"""Determine action to take when a download problem appears.
Depending on if the downloader has been configured to ignore
download errors or not, this method may throw an exception or
not when errors are found, after printing the message.
tb, if given, is additional traceback information.
"""
if message is not None:
self.to_stderr(message)
if self.params.get('verbose'):
if tb is None:
if sys.exc_info()[0]: # if .trouble has been called from an except block
tb = ''
if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
tb += encode_compat_str(traceback.format_exc())
else:
tb_data = traceback.format_list(traceback.extract_stack())
tb = ''.join(tb_data)
self.to_stderr(tb)
if not self.params.get('ignoreerrors', False):
if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
exc_info = sys.exc_info()[1].exc_info
else:
exc_info = sys.exc_info()
raise DownloadError(message, exc_info)
self._download_retcode = 1
def report_warning(self, message):
'''
Print the message to stderr, it will be prefixed with 'WARNING:'
If stderr is a tty file the 'WARNING:' will be colored
'''
if self.params.get('logger') is not None:
self.params['logger'].warning(message)
else:
if self.params.get('no_warnings'):
return
if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
_msg_header = '\033[0;33mWARNING:\033[0m'
else:
_msg_header = 'WARNING:'
warning_message = '%s %s' % (_msg_header, message)
self.to_stderr(warning_message)
def report_error(self, message, tb=None):
'''
Do the same as trouble, but prefixes the message with 'ERROR:', colored
in red if stderr is a tty file.
'''
if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
_msg_header = '\033[0;31mERROR:\033[0m'
else:
_msg_header = 'ERROR:'
error_message = '%s %s' % (_msg_header, message)
self.trouble(error_message, tb)
def report_file_already_downloaded(self, file_name):
"""Report file has already been fully downloaded."""
try:
self.to_screen('[download] %s has already been downloaded' % file_name)
except UnicodeEncodeError:
self.to_screen('[download] The file has already been downloaded')
def prepare_filename(self, info_dict):
"""Generate the output filename."""
try:
template_dict = dict(info_dict)
template_dict['epoch'] = int(time.time())
autonumber_size = self.params.get('autonumber_size')
if autonumber_size is None:
autonumber_size = 5
template_dict['autonumber'] = self.params.get('autonumber_start', 1) - 1 + self._num_downloads
if template_dict.get('resolution') is None:
if template_dict.get('width') and template_dict.get('height'):
template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
elif template_dict.get('height'):
template_dict['resolution'] = '%sp' % template_dict['height']
elif template_dict.get('width'):
template_dict['resolution'] = '%dx?' % template_dict['width']
sanitize = lambda k, v: sanitize_filename(
compat_str(v),
restricted=self.params.get('restrictfilenames'),
is_id=(k == 'id' or k.endswith('_id')))
template_dict = dict((k, v if isinstance(v, compat_numeric_types) else sanitize(k, v))
for k, v in template_dict.items()
if v is not None and not isinstance(v, (list, tuple, dict)))
template_dict = collections.defaultdict(lambda: self.params.get('outtmpl_na_placeholder', 'NA'), template_dict)
outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
# For fields playlist_index and autonumber convert all occurrences
# of %(field)s to %(field)0Nd for backward compatibility
field_size_compat_map = {
'playlist_index': len(str(template_dict['n_entries'])),
'autonumber': autonumber_size,
}
FIELD_SIZE_COMPAT_RE = r'(?<!%)%\((?P<field>autonumber|playlist_index)\)s'
mobj = re.search(FIELD_SIZE_COMPAT_RE, outtmpl)
if mobj:
outtmpl = re.sub(
FIELD_SIZE_COMPAT_RE,
r'%%(\1)0%dd' % field_size_compat_map[mobj.group('field')],
outtmpl)
# Missing numeric fields used together with integer presentation types
# in format specification will break the argument substitution since
# string NA placeholder is returned for missing fields. We will patch
# output template for missing fields to meet string presentation type.
for numeric_field in self._NUMERIC_FIELDS:
if numeric_field not in template_dict:
# As of [1] format syntax is:
# %[mapping_key][conversion_flags][minimum_width][.precision][length_modifier]type
# 1. https://docs.python.org/2/library/stdtypes.html#string-formatting
FORMAT_RE = r'''(?x)
(?<!%)
%
\({0}\) # mapping key
(?:[#0\-+ ]+)? # conversion flags (optional)
(?:\d+)? # minimum field width (optional)
(?:\.\d+)? # precision (optional)
[hlL]? # length modifier (optional)
[diouxXeEfFgGcrs%] # conversion type
'''
outtmpl = re.sub(
FORMAT_RE.format(numeric_field),
r'%({0})s'.format(numeric_field), outtmpl)
# expand_path translates '%%' into '%' and '$$' into '$'
# correspondingly that is not what we want since we need to keep
# '%%' intact for template dict substitution step. Working around
# with boundary-alike separator hack.
sep = ''.join([random.choice(ascii_letters) for _ in range(32)])
# print('hychu, {%s}' % outtmpl)
outtmpl = outtmpl.replace('%%', '%{0}%'.format(sep)).replace('$$', '${0}$'.format(sep))
# outtmpl should be expand_path'ed before template dict substitution
# because meta fields may contain env variables we don't want to
# be expanded. For example, for outtmpl "%(title)s.%(ext)s" and
# title "Hello $PATH", we don't want `$PATH` to be expanded.
filename = expand_path(outtmpl).replace(sep, '') % template_dict
# filename = os.path.join('out', filename)
# print('hychu, The filename is {%s}.{%s}' % (outtmpl, filename))
# Temporary fix for #4787
# 'Treat' all problem characters by passing filename through preferredencoding
# to workaround encoding issues with subprocess on python2 @ Windows
if sys.version_info < (3, 0) and sys.platform == 'win32':
filename = encodeFilename(filename, True).decode(preferredencoding())
return sanitize_path(filename)
except ValueError as err:
self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
return None
def _match_entry(self, info_dict, incomplete):
""" Returns None iff the file should be downloaded """
video_title = info_dict.get('title', info_dict.get('id', 'video'))
if 'title' in info_dict:
# This can happen when we're just evaluating the playlist
title = info_dict['title']
matchtitle = self.params.get('matchtitle', False)
if matchtitle:
if not re.search(matchtitle, title, re.IGNORECASE):
return '"' + title + '" title did not match pattern "' + matchtitle + '"'
rejecttitle = self.params.get('rejecttitle', False)
if rejecttitle:
if re.search(rejecttitle, title, re.IGNORECASE):
return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
date = info_dict.get('upload_date')
if date is not None:
dateRange = self.params.get('daterange', DateRange())
if date not in dateRange:
return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
view_count = info_dict.get('view_count')
if view_count is not None:
min_views = self.params.get('min_views')
if min_views is not None and view_count < min_views:
return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
max_views = self.params.get('max_views')
if max_views is not None and view_count > max_views:
return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
return 'Skipping "%s" because it is age restricted' % video_title
if self.in_download_archive(info_dict):
return '%s has already been recorded in archive' % video_title
if not incomplete:
match_filter = self.params.get('match_filter')
if match_filter is not None:
ret = match_filter(info_dict)
if ret is not None:
return ret
return None
@staticmethod
def add_extra_info(info_dict, extra_info):
'''Set the keys from extra_info in info dict if they are missing'''
for key, value in extra_info.items():
info_dict.setdefault(key, value)
def extract_info(self, url, download=True, ie_key=None, extra_info={},
process=True, force_generic_extractor=False):
'''
Returns a list with a dictionary for each video we find.
If 'download', also downloads the videos.
extra_info is a dict containing the extra values to add to each result
'''
if not ie_key and force_generic_extractor:
ie_key = 'Generic'
if ie_key:
ies = [self.get_info_extractor(ie_key)]
else:
ies = self._ies
for ie in ies:
if not ie.suitable(url):
continue
ie = self.get_info_extractor(ie.ie_key())
if not ie.working():
self.report_warning('The program functionality for this site has been marked as broken, '
'and will probably not work.')
return self.__extract_info(url, ie, download, extra_info, process)
else:
self.report_error('no suitable InfoExtractor for URL %s' % url)
def __handle_extraction_exceptions(func):
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except GeoRestrictedError as e:
msg = e.msg
if e.countries:
msg += '\nThis video is available in %s.' % ', '.join(
map(ISO3166Utils.short2full, e.countries))
msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
self.report_error(msg)
except ExtractorError as e: # An error we somewhat expected
self.report_error(compat_str(e), e.format_traceback())
except MaxDownloadsReached:
raise
except Exception as e:
if self.params.get('ignoreerrors', False):
self.report_error(error_to_compat_str(e), tb=encode_compat_str(traceback.format_exc()))
else:
raise
return wrapper
@__handle_extraction_exceptions
def __extract_info(self, url, ie, download, extra_info, process):
ie_result = ie.extract(url)
if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
return
if isinstance(ie_result, list):
# Backwards compatibility: old IE result format
ie_result = {
'_type': 'compat_list',
'entries': ie_result,
}
self.add_default_extra_info(ie_result, ie, url)
if process:
return self.process_ie_result(ie_result, download, extra_info)
else:
return ie_result
def add_default_extra_info(self, ie_result, ie, url):
self.add_extra_info(ie_result, {
'extractor': ie.IE_NAME,
'webpage_url': url,
'webpage_url_basename': url_basename(url),
'extractor_key': ie.ie_key(),
})
def process_ie_result(self, ie_result, download=True, extra_info={}):
"""
Take the result of the ie(may be modified) and resolve all unresolved
references (URLs, playlist items).
It will also download the videos if 'download'.
Returns the resolved ie_result.
"""
result_type = ie_result.get('_type', 'video')
if result_type in ('url', 'url_transparent'):
ie_result['url'] = sanitize_url(ie_result['url'])
extract_flat = self.params.get('extract_flat', False)
if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
or extract_flat is True):
self.__forced_printings(
ie_result, self.prepare_filename(ie_result),
incomplete=True)
return ie_result
if result_type == 'video':
self.add_extra_info(ie_result, extra_info)
return self.process_video_result(ie_result, download=download)
elif result_type == 'url':
# We have to add extra_info to the results because it may be
# contained in a playlist
return self.extract_info(ie_result['url'],
download,
ie_key=ie_result.get('ie_key'),
extra_info=extra_info)
elif result_type == 'url_transparent':
# Use the information from the embedding page
info = self.extract_info(
ie_result['url'], ie_key=ie_result.get('ie_key'),
extra_info=extra_info, download=False, process=False)
# extract_info may return None when ignoreerrors is enabled and
# extraction failed with an error, don't crash and return early
# in this case
if not info:
return info
force_properties = dict(
(k, v) for k, v in ie_result.items() if v is not None)
for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'):
if f in force_properties:
del force_properties[f]
new_result = info.copy()
new_result.update(force_properties)
# Extracted info may not be a video result (i.e.
# info.get('_type', 'video') != video) but rather an url or
# url_transparent. In such cases outer metadata (from ie_result)
# should be propagated to inner one (info). For this to happen
# _type of info should be overridden with url_transparent. This
# fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
if new_result.get('_type') == 'url':
new_result['_type'] = 'url_transparent'
return self.process_ie_result(
new_result, download=download, extra_info=extra_info)
elif result_type in ('playlist', 'multi_video'):
# Protect from infinite recursion due to recursively nested playlists
# (see https://github.com/ytdl-org/youtube-dl/issues/27833)
webpage_url = ie_result['webpage_url']
if webpage_url in self._playlist_urls:
self.to_screen(
'[download] Skipping already downloaded playlist: %s'
% ie_result.get('title') or ie_result.get('id'))
return
self._playlist_level += 1
self._playlist_urls.add(webpage_url)
try:
return self.__process_playlist(ie_result, download)
finally:
self._playlist_level -= 1
if not self._playlist_level:
self._playlist_urls.clear()
elif result_type == 'compat_list':
self.report_warning(
'Extractor %s returned a compat_list result. '
'It needs to be updated.' % ie_result.get('extractor'))
def _fixup(r):
self.add_extra_info(
r,
{
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
}
)
return r
ie_result['entries'] = [
self.process_ie_result(_fixup(r), download, extra_info)
for r in ie_result['entries']
]
return ie_result
else:
raise Exception('Invalid result type: %s' % result_type)
def __process_playlist(self, ie_result, download):
# We process each entry in the playlist
playlist = ie_result.get('title') or ie_result.get('id')
self.to_screen('[download] Downloading playlist: %s' % playlist)
playlist_results = []
playliststart = self.params.get('playliststart', 1) - 1
playlistend = self.params.get('playlistend')
# For backwards compatibility, interpret -1 as whole list
if playlistend == -1:
playlistend = None
playlistitems_str = self.params.get('playlist_items')
playlistitems = None
if playlistitems_str is not None:
def iter_playlistitems(format):
for string_segment in format.split(','):
if '-' in string_segment:
start, end = string_segment.split('-')
for item in range(int(start), int(end) + 1):
yield int(item)
else:
yield int(string_segment)
playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
ie_entries = ie_result['entries']
def make_playlistitems_entries(list_ie_entries):
num_entries = len(list_ie_entries)
return [
list_ie_entries[i - 1] for i in playlistitems
if -num_entries <= i - 1 < num_entries]
def report_download(num_entries):
self.to_screen(
'[%s] playlist %s: Downloading %d videos' %
(ie_result['extractor'], playlist, num_entries))
if isinstance(ie_entries, list):
n_all_entries = len(ie_entries)
if playlistitems:
entries = make_playlistitems_entries(ie_entries)
else:
entries = ie_entries[playliststart:playlistend]
n_entries = len(entries)
self.to_screen(
'[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
(ie_result['extractor'], playlist, n_all_entries, n_entries))
elif isinstance(ie_entries, PagedList):
if playlistitems:
entries = []
for item in playlistitems:
entries.extend(ie_entries.getslice(
item - 1, item
))
else:
entries = ie_entries.getslice(
playliststart, playlistend)
n_entries = len(entries)
report_download(n_entries)
else: # iterable
if playlistitems:
entries = make_playlistitems_entries(list(itertools.islice(
ie_entries, 0, max(playlistitems))))
else:
entries = list(itertools.islice(
ie_entries, playliststart, playlistend))
n_entries = len(entries)
report_download(n_entries)
if self.params.get('playlistreverse', False):
entries = entries[::-1]
if self.params.get('playlistrandom', False):
random.shuffle(entries)
x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
for i, entry in enumerate(entries, 1):
self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
# This __x_forwarded_for_ip thing is a bit ugly but requires
# minimal changes
if x_forwarded_for:
entry['__x_forwarded_for_ip'] = x_forwarded_for
extra = {
'n_entries': n_entries,
'playlist': playlist,
'playlist_id': ie_result.get('id'),
'playlist_title': ie_result.get('title'),
'playlist_uploader': ie_result.get('uploader'),
'playlist_uploader_id': ie_result.get('uploader_id'),
'playlist_index': playlistitems[i - 1] if playlistitems else i + playliststart,
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
}
reason = self._match_entry(entry, incomplete=True)
if reason is not None:
self.to_screen('[download] ' + reason)
continue
entry_result = self.__process_iterable_entry(entry, download, extra)
# TODO: skip failed (empty) entries?
playlist_results.append(entry_result)
ie_result['entries'] = playlist_results
self.to_screen('[download] Finished downloading playlist: %s' % playlist)
return ie_result
@__handle_extraction_exceptions
def __process_iterable_entry(self, entry, download, extra_info):
return self.process_ie_result(
entry, download=download, extra_info=extra_info)
def _build_format_filter(self, filter_spec):
" Returns a function to filter the formats according to the filter_spec "
OPERATORS = {
'<': operator.lt,
'<=': operator.le,
'>': operator.gt,
'>=': operator.ge,
'=': operator.eq,
'!=': operator.ne,
}
operator_rex = re.compile(r'''(?x)\s*
(?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps)
\s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
(?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
$
''' % '|'.join(map(re.escape, OPERATORS.keys())))
m = operator_rex.search(filter_spec)
if m:
try:
comparison_value = int(m.group('value'))
except ValueError:
comparison_value = parse_filesize(m.group('value'))
if comparison_value is None:
comparison_value = parse_filesize(m.group('value') + 'B')
if comparison_value is None:
raise ValueError(
'Invalid value %r in format specification %r' % (
m.group('value'), filter_spec))
op = OPERATORS[m.group('op')]
if not m:
STR_OPERATORS = {
'=': operator.eq,
'^=': lambda attr, value: attr.startswith(value),
'$=': lambda attr, value: attr.endswith(value),
'*=': lambda attr, value: value in attr,
}
str_operator_rex = re.compile(r'''(?x)
\s*(?P<key>ext|acodec|vcodec|container|protocol|format_id|language)
\s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?
\s*(?P<value>[a-zA-Z0-9._-]+)
\s*$
''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
m = str_operator_rex.search(filter_spec)
if m:
comparison_value = m.group('value')
str_op = STR_OPERATORS[m.group('op')]
if m.group('negation'):
op = lambda attr, value: not str_op(attr, value)
else:
op = str_op
if not m:
raise ValueError('Invalid filter specification %r' % filter_spec)
def _filter(f):
actual_value = f.get(m.group('key'))
if actual_value is None:
return m.group('none_inclusive')
return op(actual_value, comparison_value)
return _filter
def _default_format_spec(self, info_dict, download=True):
def can_merge():
merger = FFmpegMergerPP(self)
return merger.available and merger.can_merge()
def prefer_best():
if self.params.get('simulate', False):
return False
if not download:
return False
if self.params.get('outtmpl', DEFAULT_OUTTMPL) == '-':
return True
if info_dict.get('is_live'):
return True
if not can_merge():
return True
return False
req_format_list = ['bestvideo+bestaudio', 'best']
if prefer_best():
req_format_list.reverse()
return '/'.join(req_format_list)
def build_format_selector(self, format_spec):
def syntax_error(note, start):
message = (
'Invalid format specification: '
'{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
return SyntaxError(message)
PICKFIRST = 'PICKFIRST'
MERGE = 'MERGE'
SINGLE = 'SINGLE'
GROUP = 'GROUP'
FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
def _parse_filter(tokens):
filter_parts = []
for type, string, start, _, _ in tokens:
if type == tokenize.OP and string == ']':
return ''.join(filter_parts)
else:
filter_parts.append(string)
def _remove_unused_ops(tokens):
# Remove operators that we don't use and join them with the surrounding strings
# for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
ALLOWED_OPS = ('/', '+', ',', '(', ')')
last_string, last_start, last_end, last_line = None, None, None, None
for type, string, start, end, line in tokens:
if type == tokenize.OP and string == '[':
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
last_string = None
yield type, string, start, end, line
# everything inside brackets will be handled by _parse_filter
for type, string, start, end, line in tokens:
yield type, string, start, end, line
if type == tokenize.OP and string == ']':
break
elif type == tokenize.OP and string in ALLOWED_OPS:
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
last_string = None
yield type, string, start, end, line
elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
if not last_string:
last_string = string
last_start = start
last_end = end
else:
last_string += string
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
selectors = []
current_selector = None
for type, string, start, _, _ in tokens:
# ENCODING is only defined in python 3.x
if type == getattr(tokenize, 'ENCODING', None):
continue
elif type in [tokenize.NAME, tokenize.NUMBER]:
current_selector = FormatSelector(SINGLE, string, [])
elif type == tokenize.OP:
if string == ')':
if not inside_group:
# ')' will be handled by the parentheses group
tokens.restore_last_token()
break
elif inside_merge and string in ['/', ',']:
tokens.restore_last_token()
break
elif inside_choice and string == ',':
tokens.restore_last_token()
break
elif string == ',':
if not current_selector:
raise syntax_error('"," must follow a format selector', start)
selectors.append(current_selector)
current_selector = None
elif string == '/':
if not current_selector:
raise syntax_error('"/" must follow a format selector', start)
first_choice = current_selector
second_choice = _parse_format_selection(tokens, inside_choice=True)
current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
elif string == '[':
if not current_selector:
current_selector = FormatSelector(SINGLE, 'best', [])
format_filter = _parse_filter(tokens)
current_selector.filters.append(format_filter)
elif string == '(':
if current_selector:
raise syntax_error('Unexpected "("', start)
group = _parse_format_selection(tokens, inside_group=True)
current_selector = FormatSelector(GROUP, group, [])
elif string == '+':
if inside_merge:
raise syntax_error('Unexpected "+"', start)
video_selector = current_selector
audio_selector = _parse_format_selection(tokens, inside_merge=True)
if not video_selector or not audio_selector:
raise syntax_error('"+" must be between two format selectors', start)
current_selector = FormatSelector(MERGE, (video_selector, audio_selector), [])
else:
raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
elif type == tokenize.ENDMARKER:
break
if current_selector:
selectors.append(current_selector)
return selectors
def _build_selector_function(selector):
if isinstance(selector, list):
fs = [_build_selector_function(s) for s in selector]
def selector_function(ctx):
for f in fs:
for format in f(ctx):
yield format
return selector_function
elif selector.type == GROUP:
selector_function = _build_selector_function(selector.selector)
elif selector.type == PICKFIRST:
fs = [_build_selector_function(s) for s in selector.selector]
def selector_function(ctx):
for f in fs:
picked_formats = list(f(ctx))
if picked_formats:
return picked_formats
return []
elif selector.type == SINGLE:
format_spec = selector.selector
def selector_function(ctx):
formats = list(ctx['formats'])
if not formats:
return
if format_spec == 'all':
for f in formats:
yield f
elif format_spec in ['best', 'worst', None]:
format_idx = 0 if format_spec == 'worst' else -1
audiovideo_formats = [
f for f in formats
if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
if audiovideo_formats:
yield audiovideo_formats[format_idx]
# for extractors with incomplete formats (audio only (soundcloud)
# or video only (imgur)) we will fallback to best/worst
# {video,audio}-only format
elif ctx['incomplete_formats']:
yield formats[format_idx]
elif format_spec == 'bestaudio':
audio_formats = [
f for f in formats
if f.get('vcodec') == 'none']
if audio_formats:
yield audio_formats[-1]
elif format_spec == 'worstaudio':
audio_formats = [
f for f in formats
if f.get('vcodec') == 'none']
if audio_formats:
yield audio_formats[0]
elif format_spec == 'bestvideo':
video_formats = [
f for f in formats
if f.get('acodec') == 'none']
if video_formats:
yield video_formats[-1]
elif format_spec == 'worstvideo':
video_formats = [
f for f in formats
if f.get('acodec') == 'none']
if video_formats:
yield video_formats[0]
else:
extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
if format_spec in extensions:
filter_f = lambda f: f['ext'] == format_spec
else:
filter_f = lambda f: f['format_id'] == format_spec
matches = list(filter(filter_f, formats))
if matches:
yield matches[-1]
elif selector.type == MERGE:
def _merge(formats_info):
format_1, format_2 = [f['format_id'] for f in formats_info]
# The first format must contain the video and the
# second the audio
if formats_info[0].get('vcodec') == 'none':
self.report_error('The first format must '
'contain the video, try using '
'"-f %s+%s"' % (format_2, format_1))
return
# Formats must be opposite (video+audio)
if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none':
self.report_error(
'Both formats %s and %s are video-only, you must specify "-f video+audio"'
% (format_1, format_2))
return
output_ext = (
formats_info[0]['ext']
if self.params.get('merge_output_format') is None
else self.params['merge_output_format'])
return {
'requested_formats': formats_info,
'format': '%s+%s' % (formats_info[0].get('format'),
formats_info[1].get('format')),
'format_id': '%s+%s' % (formats_info[0].get('format_id'),
formats_info[1].get('format_id')),
'width': formats_info[0].get('width'),
'height': formats_info[0].get('height'),
'resolution': formats_info[0].get('resolution'),
'fps': formats_info[0].get('fps'),
'vcodec': formats_info[0].get('vcodec'),
'vbr': formats_info[0].get('vbr'),
'stretched_ratio': formats_info[0].get('stretched_ratio'),
'acodec': formats_info[1].get('acodec'),
'abr': formats_info[1].get('abr'),
'ext': output_ext,
}
video_selector, audio_selector = map(_build_selector_function, selector.selector)
def selector_function(ctx):
for pair in itertools.product(
video_selector(copy.deepcopy(ctx)), audio_selector(copy.deepcopy(ctx))):
yield _merge(pair)
filters = [self._build_format_filter(f) for f in selector.filters]
def final_selector(ctx):
ctx_copy = copy.deepcopy(ctx)
for _filter in filters:
ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
return selector_function(ctx_copy)
return final_selector
stream = io.BytesIO(format_spec.encode('utf-8'))
try:
tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
except tokenize.TokenError:
raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
class TokenIterator(object):
def __init__(self, tokens):
self.tokens = tokens
self.counter = 0
def __iter__(self):
return self
def __next__(self):
if self.counter >= len(self.tokens):
raise StopIteration()
value = self.tokens[self.counter]
self.counter += 1
return value
next = __next__
def restore_last_token(self):
self.counter -= 1
parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
return _build_selector_function(parsed_selector)
def _calc_headers(self, info_dict):
res = std_headers.copy()
add_headers = info_dict.get('http_headers')
if add_headers:
res.update(add_headers)
cookies = self._calc_cookies(info_dict)
if cookies:
res['Cookie'] = cookies
if 'X-Forwarded-For' not in res:
x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
if x_forwarded_for_ip:
res['X-Forwarded-For'] = x_forwarded_for_ip
return res
def _calc_cookies(self, info_dict):
pr = sanitized_Request(info_dict['url'])
self.cookiejar.add_cookie_header(pr)
return pr.get_header('Cookie')
def process_video_result(self, info_dict, download=True):
assert info_dict.get('_type', 'video') == 'video'
if 'id' not in info_dict:
raise ExtractorError('Missing "id" field in extractor result')
if 'title' not in info_dict:
raise ExtractorError('Missing "title" field in extractor result')
def report_force_conversion(field, field_not, conversion):
self.report_warning(
'"%s" field is not %s - forcing %s conversion, there is an error in extractor'
% (field, field_not, conversion))
def sanitize_string_field(info, string_field):
field = info.get(string_field)
if field is None or isinstance(field, compat_str):
return
report_force_conversion(string_field, 'a string', 'string')
info[string_field] = compat_str(field)
def sanitize_numeric_fields(info):
for numeric_field in self._NUMERIC_FIELDS:
field = info.get(numeric_field)
if field is None or isinstance(field, compat_numeric_types):
continue
report_force_conversion(numeric_field, 'numeric', 'int')
info[numeric_field] = int_or_none(field)
sanitize_string_field(info_dict, 'id')
sanitize_numeric_fields(info_dict)
if 'playlist' not in info_dict:
# It isn't part of a playlist
info_dict['playlist'] = None
info_dict['playlist_index'] = None
thumbnails = info_dict.get('thumbnails')
if thumbnails is None:
thumbnail = info_dict.get('thumbnail')
if thumbnail:
info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
if thumbnails:
thumbnails.sort(key=lambda t: (
t.get('preference') if t.get('preference') is not None else -1,
t.get('width') if t.get('width') is not None else -1,
t.get('height') if t.get('height') is not None else -1,
t.get('id') if t.get('id') is not None else '', t.get('url')))
for i, t in enumerate(thumbnails):
t['url'] = sanitize_url(t['url'])
if t.get('width') and t.get('height'):
t['resolution'] = '%dx%d' % (t['width'], t['height'])
if t.get('id') is None:
t['id'] = '%d' % i
if self.params.get('list_thumbnails'):
self.list_thumbnails(info_dict)
return
thumbnail = info_dict.get('thumbnail')
if thumbnail:
info_dict['thumbnail'] = sanitize_url(thumbnail)
elif thumbnails:
info_dict['thumbnail'] = thumbnails[-1]['url']
if 'display_id' not in info_dict and 'id' in info_dict:
info_dict['display_id'] = info_dict['id']
for ts_key, date_key in (
('timestamp', 'upload_date'),
('release_timestamp', 'release_date'),
):
if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
# Working around out-of-range timestamp values (e.g. negative ones on Windows,
# see http://bugs.python.org/issue1646728)
try:
upload_date = datetime.datetime.utcfromtimestamp(info_dict[ts_key])
info_dict[date_key] = upload_date.strftime('%Y%m%d')
except (ValueError, OverflowError, OSError):
pass
# Auto generate title fields corresponding to the *_number fields when missing
# in order to always have clean titles. This is very common for TV series.
for field in ('chapter', 'season', 'episode'):
if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
for cc_kind in ('subtitles', 'automatic_captions'):
cc = info_dict.get(cc_kind)
if cc:
for _, subtitle in cc.items():
for subtitle_format in subtitle:
if subtitle_format.get('url'):
subtitle_format['url'] = sanitize_url(subtitle_format['url'])
if subtitle_format.get('ext') is None:
subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
automatic_captions = info_dict.get('automatic_captions')
subtitles = info_dict.get('subtitles')
if self.params.get('listsubtitles', False):
if 'automatic_captions' in info_dict:
self.list_subtitles(
info_dict['id'], automatic_captions, 'automatic captions')
self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
return
info_dict['requested_subtitles'] = self.process_subtitles(
info_dict['id'], subtitles, automatic_captions)
# We now pick which formats have to be downloaded
if info_dict.get('formats') is None:
# There's only one format available
formats = [info_dict]
else:
formats = info_dict['formats']
if not formats:
raise ExtractorError('No video formats found!')
def is_wellformed(f):
url = f.get('url')
if not url:
self.report_warning(
'"url" field is missing or empty - skipping format, '
'there is an error in extractor')
return False
if isinstance(url, bytes):
sanitize_string_field(f, 'url')
return True
# Filter out malformed formats for better extraction robustness
formats = list(filter(is_wellformed, formats))
formats_dict = {}
# We check that all the formats have the format and format_id fields
for i, format in enumerate(formats):
sanitize_string_field(format, 'format_id')
sanitize_numeric_fields(format)
format['url'] = sanitize_url(format['url'])
if not format.get('format_id'):
format['format_id'] = compat_str(i)
else:
# Sanitize format_id from characters used in format selector expression
format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
format_id = format['format_id']
if format_id not in formats_dict:
formats_dict[format_id] = []
formats_dict[format_id].append(format)
# Make sure all formats have unique format_id
for format_id, ambiguous_formats in formats_dict.items():
if len(ambiguous_formats) > 1:
for i, format in enumerate(ambiguous_formats):
format['format_id'] = '%s-%d' % (format_id, i)
for i, format in enumerate(formats):
if format.get('format') is None:
format['format'] = '{id} - {res}{note}'.format(
id=format['format_id'],
res=self.format_resolution(format),
note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
)
# Automatically determine file extension if missing
if format.get('ext') is None:
format['ext'] = determine_ext(format['url']).lower()
# Automatically determine protocol if missing (useful for format
# selection purposes)
if format.get('protocol') is None:
format['protocol'] = determine_protocol(format)
# Add HTTP headers, so that external programs can use them from the
# json output
full_format_info = info_dict.copy()
full_format_info.update(format)
format['http_headers'] = self._calc_headers(full_format_info)
# Remove private housekeeping stuff
if '__x_forwarded_for_ip' in info_dict:
del info_dict['__x_forwarded_for_ip']
# TODO Central sorting goes here
if formats[0] is not info_dict:
# only set the 'formats' fields if the original info_dict list them
# otherwise we end up with a circular reference, the first (and unique)
# element in the 'formats' field in info_dict is info_dict itself,
# which can't be exported to json
info_dict['formats'] = formats
if self.params.get('listformats'):
self.list_formats(info_dict)
return
req_format = self.params.get('format')
if req_format is None:
req_format = self._default_format_spec(info_dict, download=download)
if self.params.get('verbose'):
self._write_string('[debug] Default format spec: %s\n' % req_format)
format_selector = self.build_format_selector(req_format)
# While in format selection we may need to have an access to the original
# format set in order to calculate some metrics or do some processing.
# For now we need to be able to guess whether original formats provided
# by extractor are incomplete or not (i.e. whether extractor provides only
# video-only or audio-only formats) for proper formats selection for
# extractors with such incomplete formats (see
# https://github.com/ytdl-org/youtube-dl/pull/5556).
# Since formats may be filtered during format selection and may not match
# the original formats the results may be incorrect. Thus original formats
# or pre-calculated metrics should be passed to format selection routines
# as well.
# We will pass a context object containing all necessary additional data
# instead of just formats.
# This fixes incorrect format selection issue (see
# https://github.com/ytdl-org/youtube-dl/issues/10083).
incomplete_formats = (
# All formats are video-only or
all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats)
# all formats are audio-only
or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
ctx = {
'formats': formats,
'incomplete_formats': incomplete_formats,
}
formats_to_download = list(format_selector(ctx))
if not formats_to_download:
raise ExtractorError('requested format not available',
expected=True)
if download:
if len(formats_to_download) > 1:
self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
for format in formats_to_download:
new_info = dict(info_dict)
new_info.update(format)
self.process_info(new_info)
# We update the info dict with the best quality format (backwards compatibility)
info_dict.update(formats_to_download[-1])
return info_dict
def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
"""Select the requested subtitles and their format"""
available_subs = {}
if normal_subtitles and self.params.get('writesubtitles'):
available_subs.update(normal_subtitles)
if automatic_captions and self.params.get('writeautomaticsub'):
for lang, cap_info in automatic_captions.items():
if lang not in available_subs:
available_subs[lang] = cap_info
if (not self.params.get('writesubtitles') and not
self.params.get('writeautomaticsub') or not
available_subs):
return None
if self.params.get('allsubtitles', False):
requested_langs = available_subs.keys()
else:
if self.params.get('subtitleslangs', False):
requested_langs = self.params.get('subtitleslangs')
elif 'en' in available_subs:
requested_langs = ['en']
else:
requested_langs = [list(available_subs.keys())[0]]
formats_query = self.params.get('subtitlesformat', 'best')
formats_preference = formats_query.split('/') if formats_query else []
subs = {}
for lang in requested_langs:
formats = available_subs.get(lang)
if formats is None:
self.report_warning('%s subtitles not available for %s' % (lang, video_id))
continue
for ext in formats_preference:
if ext == 'best':
f = formats[-1]
break
matches = list(filter(lambda f: f['ext'] == ext, formats))
if matches:
f = matches[-1]
break
else:
f = formats[-1]
self.report_warning(
'No subtitle format found matching "%s" for language %s, '
'using %s' % (formats_query, lang, f['ext']))
subs[lang] = f
return subs
def __forced_printings(self, info_dict, filename, incomplete):
def print_mandatory(field):
if (self.params.get('force%s' % field, False)
and (not incomplete or info_dict.get(field) is not None)):
self.to_stdout(info_dict[field])
def print_optional(field):
if (self.params.get('force%s' % field, False)
and info_dict.get(field) is not None):
self.to_stdout(info_dict[field])
print_mandatory('title')
print_mandatory('id')
if self.params.get('forceurl', False) and not incomplete:
if info_dict.get('requested_formats') is not None:
for f in info_dict['requested_formats']:
self.to_stdout(f['url'] + f.get('play_path', ''))
else:
# For RTMP URLs, also include the playpath
self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
print_optional('thumbnail')
print_optional('description')
if self.params.get('forcefilename', False) and filename is not None:
self.to_stdout(filename)
if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
self.to_stdout(formatSeconds(info_dict['duration']))
print_mandatory('format')
if self.params.get('forcejson', False):
self.to_stdout(json.dumps(info_dict))
def process_info(self, info_dict):
"""Process a single resolved IE result."""
assert info_dict.get('_type', 'video') == 'video'
max_downloads = self.params.get('max_downloads')
if max_downloads is not None:
if self._num_downloads >= int(max_downloads):
raise MaxDownloadsReached()
# TODO: backward compatibility, to be removed
info_dict['fulltitle'] = info_dict['title']
if 'format' not in info_dict:
info_dict['format'] = info_dict['ext']
reason = self._match_entry(info_dict, incomplete=False)
if reason is not None:
self.to_screen('[download] ' + reason)
return
self._num_downloads += 1
info_dict['_filename'] = filename = self.prepare_filename(info_dict)
# Forced printings
self.__forced_printings(info_dict, filename, incomplete=False)
# Do nothing else if in simulate mode
if self.params.get('simulate', False):
return
if filename is None:
return
def ensure_dir_exists(path):
try:
dn = os.path.dirname(path)
if dn and not os.path.exists(dn):
os.makedirs(dn)
return True
except (OSError, IOError) as err:
if isinstance(err, OSError) and err.errno == errno.EEXIST:
return True
self.report_error('unable to create directory ' + error_to_compat_str(err))
return False
if not ensure_dir_exists(sanitize_path(encodeFilename(filename))):
return
if self.params.get('writedescription', False):
descfn = replace_extension(filename, 'description', info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
self.to_screen('[info] Video description is already present')
elif info_dict.get('description') is None:
self.report_warning('There\'s no description to write.')
else:
try:
self.to_screen('[info] Writing video description to: ' + descfn)
with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
descfile.write(info_dict['description'])
except (OSError, IOError):
self.report_error('Cannot write description file ' + descfn)
return
if self.params.get('writeannotations', False):
annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
self.to_screen('[info] Video annotations are already present')
elif not info_dict.get('annotations'):
self.report_warning('There are no annotations to write.')
else:
try:
self.to_screen('[info] Writing video annotations to: ' + annofn)
with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
annofile.write(info_dict['annotations'])
except (KeyError, TypeError):
self.report_warning('There are no annotations to write.')
except (OSError, IOError):
self.report_error('Cannot write annotations file: ' + annofn)
return
subtitles_are_requested = any([self.params.get('writesubtitles', False),
self.params.get('writeautomaticsub')])
if subtitles_are_requested and info_dict.get('requested_subtitles'):
# subtitles download errors are already managed as troubles in relevant IE
# that way it will silently go on when used with unsupporting IE
subtitles = info_dict['requested_subtitles']
ie = self.get_info_extractor(info_dict['extractor_key'])
for sub_lang, sub_info in subtitles.items():
sub_format = sub_info['ext']
sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
self.to_screen('[info] Video subtitle %s.%s is already present' % (sub_lang, sub_format))
else:
self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
if sub_info.get('data') is not None:
try:
# Use newline='' to prevent conversion of newline characters
# See https://github.com/ytdl-org/youtube-dl/issues/10268
with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8', newline='') as subfile:
subfile.write(sub_info['data'])
except (OSError, IOError):
self.report_error('Cannot write subtitles file ' + sub_filename)
return
else:
try:
sub_data = ie._request_webpage(
sub_info['url'], info_dict['id'], note=False).read()
with io.open(encodeFilename(sub_filename), 'wb') as subfile:
subfile.write(sub_data)
except (ExtractorError, IOError, OSError, ValueError) as err:
self.report_warning('Unable to download subtitle for "%s": %s' %
(sub_lang, error_to_compat_str(err)))
continue
if self.params.get('writeinfojson', False):
infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
self.to_screen('[info] Video description metadata is already present')
else:
self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
try:
write_json_file(self.filter_requested_info(info_dict), infofn)
except (OSError, IOError):
self.report_error('Cannot write metadata to JSON file ' + infofn)
return
self._write_thumbnails(info_dict, filename)
if not self.params.get('skip_download', False):
try:
def dl(name, info):
fd = get_suitable_downloader(info, self.params)(self, self.params)
for ph in self._progress_hooks:
fd.add_progress_hook(ph)
if self.params.get('verbose'):
self.to_screen('[debug] Invoking downloader on %r' % info.get('url'))
return fd.download(name, info)
if info_dict.get('requested_formats') is not None:
downloaded = []
success = True
merger = FFmpegMergerPP(self)
if not merger.available:
postprocessors = []
self.report_warning('You have requested multiple '
'formats but ffmpeg or avconv are not installed.'
' The formats won\'t be merged.')
else:
postprocessors = [merger]
def compatible_formats(formats):
video, audio = formats
# Check extension
video_ext, audio_ext = video.get('ext'), audio.get('ext')
if video_ext and audio_ext:
COMPATIBLE_EXTS = (
('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma'),
('webm')
)
for exts in COMPATIBLE_EXTS:
if video_ext in exts and audio_ext in exts:
return True
# TODO: Check acodec/vcodec
return False
filename_real_ext = os.path.splitext(filename)[1][1:]
filename_wo_ext = (
os.path.splitext(filename)[0]
if filename_real_ext == info_dict['ext']
else filename)
requested_formats = info_dict['requested_formats']
if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
info_dict['ext'] = 'mkv'
self.report_warning(
'Requested formats are incompatible for merge and will be merged into mkv.')
# Ensure filename always has a correct extension for successful merge
filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
if os.path.exists(encodeFilename(filename)):
self.to_screen(
'[download] %s has already been downloaded and '
'merged' % filename)
else:
for f in requested_formats:
new_info = dict(info_dict)
new_info.update(f)
fname = prepend_extension(
self.prepare_filename(new_info),
'f%s' % f['format_id'], new_info['ext'])
if not ensure_dir_exists(fname):
return
downloaded.append(fname)
partial_success = dl(fname, new_info)
success = success and partial_success
info_dict['__postprocessors'] = postprocessors
info_dict['__files_to_merge'] = downloaded
else:
# Just a single file
success = dl(filename, info_dict)
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
self.report_error('unable to download video data: %s' % error_to_compat_str(err))
return
except (OSError, IOError) as err:
raise UnavailableVideoError(err)
except (ContentTooShortError, ) as err:
self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
return
if success and filename != '-':
# Fixup content
fixup_policy = self.params.get('fixup')
if fixup_policy is None:
fixup_policy = 'detect_or_warn'
INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.'
stretched_ratio = info_dict.get('stretched_ratio')
if stretched_ratio is not None and stretched_ratio != 1:
if fixup_policy == 'warn':
self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
info_dict['id'], stretched_ratio))
elif fixup_policy == 'detect_or_warn':
stretched_pp = FFmpegFixupStretchedPP(self)
if stretched_pp.available:
info_dict.setdefault('__postprocessors', [])
info_dict['__postprocessors'].append(stretched_pp)
else:
self.report_warning(
'%s: Non-uniform pixel ratio (%s). %s'
% (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE))
else:
assert fixup_policy in ('ignore', 'never')
if (info_dict.get('requested_formats') is None
and info_dict.get('container') == 'm4a_dash'):
if fixup_policy == 'warn':
self.report_warning(
'%s: writing DASH m4a. '
'Only some players support this container.'
% info_dict['id'])
elif fixup_policy == 'detect_or_warn':
fixup_pp = FFmpegFixupM4aPP(self)
if fixup_pp.available:
info_dict.setdefault('__postprocessors', [])
info_dict['__postprocessors'].append(fixup_pp)
else:
self.report_warning(
'%s: writing DASH m4a. '
'Only some players support this container. %s'
% (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
else:
assert fixup_policy in ('ignore', 'never')
if (info_dict.get('protocol') == 'm3u8_native'
or info_dict.get('protocol') == 'm3u8'
and self.params.get('hls_prefer_native')):
if fixup_policy == 'warn':
self.report_warning('%s: malformed AAC bitstream detected.' % (
info_dict['id']))
elif fixup_policy == 'detect_or_warn':
fixup_pp = FFmpegFixupM3u8PP(self)
if fixup_pp.available:
info_dict.setdefault('__postprocessors', [])
info_dict['__postprocessors'].append(fixup_pp)
else:
self.report_warning(
'%s: malformed AAC bitstream detected. %s'
% (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
else:
assert fixup_policy in ('ignore', 'never')
try:
self.post_process(filename, info_dict)
except (PostProcessingError) as err:
self.report_error('postprocessing: %s' % str(err))
return
self.record_download_archive(info_dict)
def download(self, url_list):
"""Download a given list of URLs."""
outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
if (len(url_list) > 1
and outtmpl != '-'
and '%' not in outtmpl
and self.params.get('max_downloads') != 1):
raise SameFileError(outtmpl)
for url in url_list:
try:
# It also downloads the videos
res = self.extract_info(
url, force_generic_extractor=self.params.get('force_generic_extractor', False))
except UnavailableVideoError:
self.report_error('unable to download video')
except MaxDownloadsReached:
self.to_screen('[info] Maximum number of downloaded files reached.')
raise
else:
if self.params.get('dump_single_json', False):
self.to_stdout(json.dumps(res))
return self._download_retcode
def download_with_info_file(self, info_filename):
with contextlib.closing(fileinput.FileInput(
[info_filename], mode='r',
openhook=fileinput.hook_encoded('utf-8'))) as f:
# FileInput doesn't have a read method, we can't call json.load
info = self.filter_requested_info(json.loads('\n'.join(f)))
try:
self.process_ie_result(info, download=True)
except DownloadError:
webpage_url = info.get('webpage_url')
if webpage_url is not None:
self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
return self.download([webpage_url])
else:
raise
return self._download_retcode
@staticmethod
def filter_requested_info(info_dict):
return dict(
(k, v) for k, v in info_dict.items()
if k not in ['requested_formats', 'requested_subtitles'])
def post_process(self, filename, ie_info):
"""Run all the postprocessors on the given file."""
info = dict(ie_info)
info['filepath'] = filename
pps_chain = []
if ie_info.get('__postprocessors') is not None:
pps_chain.extend(ie_info['__postprocessors'])
pps_chain.extend(self._pps)
for pp in pps_chain:
files_to_delete = []
try:
files_to_delete, info = pp.run(info)
except PostProcessingError as e:
self.report_error(e.msg)
if files_to_delete and not self.params.get('keepvideo', False):
for old_filename in files_to_delete:
self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
try:
os.remove(encodeFilename(old_filename))
except (IOError, OSError):
self.report_warning('Unable to remove downloaded original file')
def _make_archive_id(self, info_dict):
video_id = info_dict.get('id')
if not video_id:
return
# Future-proof against any change in case
# and backwards compatibility with prior versions
extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
if extractor is None:
url = str_or_none(info_dict.get('url'))
if not url:
return
# Try to find matching extractor for the URL and take its ie_key
for ie in self._ies:
if ie.suitable(url):
extractor = ie.ie_key()
break
else:
return
return extractor.lower() + ' ' + video_id
def in_download_archive(self, info_dict):
fn = self.params.get('download_archive')
if fn is None:
return False
vid_id = self._make_archive_id(info_dict)
if not vid_id:
return False # Incomplete video information
try:
with locked_file(fn, 'r', encoding='utf-8') as archive_file:
for line in archive_file:
if line.strip() == vid_id:
return True
except IOError as ioe:
if ioe.errno != errno.ENOENT:
raise
return False
def record_download_archive(self, info_dict):
fn = self.params.get('download_archive')
if fn is None:
return
vid_id = self._make_archive_id(info_dict)
assert vid_id
with locked_file(fn, 'a', encoding='utf-8') as archive_file:
archive_file.write(vid_id + '\n')
@staticmethod
def format_resolution(format, default='unknown'):
if format.get('vcodec') == 'none':
return 'audio only'
if format.get('resolution') is not None:
return format['resolution']
if format.get('height') is not None:
if format.get('width') is not None:
res = '%sx%s' % (format['width'], format['height'])
else:
res = '%sp' % format['height']
elif format.get('width') is not None:
res = '%dx?' % format['width']
else:
res = default
return res
def _format_note(self, fdict):
res = ''
if fdict.get('ext') in ['f4f', 'f4m']:
res += '(unsupported) '
if fdict.get('language'):
if res:
res += ' '
res += '[%s] ' % fdict['language']
if fdict.get('format_note') is not None:
res += fdict['format_note'] + ' '
if fdict.get('tbr') is not None:
res += '%4dk ' % fdict['tbr']
if fdict.get('container') is not None:
if res:
res += ', '
res += '%s container' % fdict['container']
if (fdict.get('vcodec') is not None
and fdict.get('vcodec') != 'none'):
if res:
res += ', '
res += fdict['vcodec']
if fdict.get('vbr') is not None:
res += '@'
elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
res += 'video@'
if fdict.get('vbr') is not None:
res += '%4dk' % fdict['vbr']
if fdict.get('fps') is not None:
if res:
res += ', '
res += '%sfps' % fdict['fps']
if fdict.get('acodec') is not None:
if res:
res += ', '
if fdict['acodec'] == 'none':
res += 'video only'
else:
res += '%-5s' % fdict['acodec']
elif fdict.get('abr') is not None:
if res:
res += ', '
res += 'audio'
if fdict.get('abr') is not None:
res += '@%3dk' % fdict['abr']
if fdict.get('asr') is not None:
res += ' (%5dHz)' % fdict['asr']
if fdict.get('filesize') is not None:
if res:
res += ', '
res += format_bytes(fdict['filesize'])
elif fdict.get('filesize_approx') is not None:
if res:
res += ', '
res += '~' + format_bytes(fdict['filesize_approx'])
return res
def list_formats(self, info_dict):
formats = info_dict.get('formats', [info_dict])
table = [
[f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
for f in formats
if f.get('preference') is None or f['preference'] >= -1000]
if len(formats) > 1:
table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
header_line = ['format code', 'extension', 'resolution', 'note']
self.to_screen(
'[info] Available formats for %s:\n%s' %
(info_dict['id'], render_table(header_line, table)))
def list_thumbnails(self, info_dict):
thumbnails = info_dict.get('thumbnails')
if not thumbnails:
self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
return
self.to_screen(
'[info] Thumbnails for %s:' % info_dict['id'])
self.to_screen(render_table(
['ID', 'width', 'height', 'URL'],
[[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
def list_subtitles(self, video_id, subtitles, name='subtitles'):
if not subtitles:
self.to_screen('%s has no %s' % (video_id, name))
return
self.to_screen(
'Available %s for %s:' % (name, video_id))
self.to_screen(render_table(
['Language', 'formats'],
[[lang, ', '.join(f['ext'] for f in reversed(formats))]
for lang, formats in subtitles.items()]))
def urlopen(self, req):
""" Start an HTTP download """
if isinstance(req, compat_basestring):
req = sanitized_Request(req)
return self._opener.open(req, timeout=self._socket_timeout)
def print_debug_header(self):
if not self.params.get('verbose'):
return
if type('') is not compat_str:
# Python 2.6 on SLES11 SP1 (https://github.com/ytdl-org/youtube-dl/issues/3326)
self.report_warning(
'Your Python is broken! Update to a newer and supported version')
stdout_encoding = getattr(
sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
encoding_str = (
'[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
locale.getpreferredencoding(),
sys.getfilesystemencoding(),
stdout_encoding,
self.get_encoding()))
write_string(encoding_str, encoding=None)
self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
if _LAZY_LOADER:
self._write_string('[debug] Lazy loading extractors enabled' + '\n')
try:
sp = subprocess.Popen(
['git', 'rev-parse', '--short', 'HEAD'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=os.path.dirname(os.path.abspath(__file__)))
out, err = sp.communicate()
out = out.decode().strip()
if re.match('[0-9a-f]+', out):
self._write_string('[debug] Git HEAD: ' + out + '\n')
except Exception:
try:
sys.exc_clear()
except Exception:
pass
def python_implementation():
impl_name = platform.python_implementation()
if impl_name == 'PyPy' and hasattr(sys, 'pypy_version_info'):
return impl_name + ' version %d.%d.%d' % sys.pypy_version_info[:3]
return impl_name
self._write_string('[debug] Python version %s (%s) - %s\n' % (
platform.python_version(), python_implementation(),
platform_name()))
exe_versions = FFmpegPostProcessor.get_versions(self)
exe_versions['rtmpdump'] = rtmpdump_version()
exe_versions['phantomjs'] = PhantomJSwrapper._version()
exe_str = ', '.join(
'%s %s' % (exe, v)
for exe, v in sorted(exe_versions.items())
if v
)
if not exe_str:
exe_str = 'none'
self._write_string('[debug] exe versions: %s\n' % exe_str)
proxy_map = {}
for handler in self._opener.handlers:
if hasattr(handler, 'proxies'):
proxy_map.update(handler.proxies)
self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
if self.params.get('call_home', False):
ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
self._write_string('[debug] Public IP address: %s\n' % ipaddr)
latest_version = self.urlopen(
'https://yt-dl.org/latest/version').read().decode('utf-8')
if version_tuple(latest_version) > version_tuple(__version__):
self.report_warning(
'You are using an outdated version (newest version: %s)! '
'See https://yt-dl.org/update if you need help updating.' %
latest_version)
def _setup_opener(self):
timeout_val = self.params.get('socket_timeout')
self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
opts_cookiefile = self.params.get('cookiefile')
opts_proxy = self.params.get('proxy')
if opts_cookiefile is None:
self.cookiejar = compat_cookiejar.CookieJar()
else:
opts_cookiefile = expand_path(opts_cookiefile)
self.cookiejar = YoutubeDLCookieJar(opts_cookiefile)
if os.access(opts_cookiefile, os.R_OK):
self.cookiejar.load(ignore_discard=True, ignore_expires=True)
cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
if opts_proxy is not None:
if opts_proxy == '':
proxies = {}
else:
proxies = {'http': opts_proxy, 'https': opts_proxy}
else:
proxies = compat_urllib_request.getproxies()
# Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805)
if 'http' in proxies and 'https' not in proxies:
proxies['https'] = proxies['http']
proxy_handler = PerRequestProxyHandler(proxies)
debuglevel = 1 if self.params.get('debug_printtraffic') else 0
https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
redirect_handler = YoutubeDLRedirectHandler()
data_handler = compat_urllib_request_DataHandler()
# When passing our own FileHandler instance, build_opener won't add the
# default FileHandler and allows us to disable the file protocol, which
# can be used for malicious purposes (see
# https://github.com/ytdl-org/youtube-dl/issues/8227)
file_handler = compat_urllib_request.FileHandler()
def file_open(*args, **kwargs):
raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
file_handler.file_open = file_open
opener = compat_urllib_request.build_opener(
proxy_handler, https_handler, cookie_processor, ydlh, redirect_handler, data_handler, file_handler)
# Delete the default user-agent header, which would otherwise apply in
# cases where our custom HTTP handler doesn't come into play
# (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details)
opener.addheaders = []
self._opener = opener
def encode(self, s):
if isinstance(s, bytes):
return s # Already encoded
try:
return s.encode(self.get_encoding())
except UnicodeEncodeError as err:
err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
raise
def get_encoding(self):
encoding = self.params.get('encoding')
if encoding is None:
encoding = preferredencoding()
return encoding
def _write_thumbnails(self, info_dict, filename):
if self.params.get('writethumbnail', False):
thumbnails = info_dict.get('thumbnails')
if thumbnails:
thumbnails = [thumbnails[-1]]
elif self.params.get('write_all_thumbnails', False):
thumbnails = info_dict.get('thumbnails')
else:
return
if not thumbnails:
# No thumbnails present, so return immediately
return
for t in thumbnails:
thumb_ext = determine_ext(t['url'], 'jpg')
suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
t['filename'] = thumb_filename = replace_extension(filename + suffix, thumb_ext, info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
self.to_screen('[%s] %s: Thumbnail %sis already present' %
(info_dict['extractor'], info_dict['id'], thumb_display_id))
else:
self.to_screen('[%s] %s: Downloading thumbnail %s...' %
(info_dict['extractor'], info_dict['id'], thumb_display_id))
try:
uf = self.urlopen(t['url'])
with open(encodeFilename(thumb_filename), 'wb') as thumbf:
shutil.copyfileobj(uf, thumbf)
self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
(info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
self.report_warning('Unable to download thumbnail "%s": %s' %
(t['url'], error_to_compat_str(err)))
| 45.727679 | 194 | 0.557267 |
from __future__ import absolute_import, unicode_literals
import collections
import contextlib
import copy
import datetime
import errno
import fileinput
import io
import itertools
import json
import locale
import operator
import os
import platform
import re
import shutil
import subprocess
import socket
import sys
import time
import tokenize
import traceback
import random
from string import ascii_letters
from .compat import (
compat_basestring,
compat_cookiejar,
compat_get_terminal_size,
compat_http_client,
compat_kwargs,
compat_numeric_types,
compat_os_name,
compat_str,
compat_tokenize_tokenize,
compat_urllib_error,
compat_urllib_request,
compat_urllib_request_DataHandler,
)
from .utils import (
age_restricted,
args_to_str,
ContentTooShortError,
date_from_str,
DateRange,
DEFAULT_OUTTMPL,
determine_ext,
determine_protocol,
DownloadError,
encode_compat_str,
encodeFilename,
error_to_compat_str,
expand_path,
ExtractorError,
format_bytes,
formatSeconds,
GeoRestrictedError,
int_or_none,
ISO3166Utils,
locked_file,
make_HTTPS_handler,
MaxDownloadsReached,
orderedSet,
PagedList,
parse_filesize,
PerRequestProxyHandler,
platform_name,
PostProcessingError,
preferredencoding,
prepend_extension,
register_socks_protocols,
render_table,
replace_extension,
SameFileError,
sanitize_filename,
sanitize_path,
sanitize_url,
sanitized_Request,
std_headers,
str_or_none,
subtitles_filename,
UnavailableVideoError,
url_basename,
version_tuple,
write_json_file,
write_string,
YoutubeDLCookieJar,
YoutubeDLCookieProcessor,
YoutubeDLHandler,
YoutubeDLRedirectHandler,
)
from .cache import Cache
from .extractor import get_info_extractor, gen_extractor_classes, _LAZY_LOADER
from .extractor.openload import PhantomJSwrapper
from .downloader import get_suitable_downloader
from .downloader.rtmp import rtmpdump_version
from .postprocessor import (
FFmpegFixupM3u8PP,
FFmpegFixupM4aPP,
FFmpegFixupStretchedPP,
FFmpegMergerPP,
FFmpegPostProcessor,
get_postprocessor,
)
from .version import __version__
if compat_os_name == 'nt':
import ctypes
class YoutubeDL(object):
_NUMERIC_FIELDS = set((
'width', 'height', 'tbr', 'abr', 'asr', 'vbr', 'fps', 'filesize', 'filesize_approx',
'timestamp', 'upload_year', 'upload_month', 'upload_day',
'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
'average_rating', 'comment_count', 'age_limit',
'start_time', 'end_time',
'chapter_number', 'season_number', 'episode_number',
'track_number', 'disc_number', 'release_year',
'playlist_index',
))
params = None
_ies = []
_pps = []
_download_retcode = None
_num_downloads = None
_playlist_level = 0
_playlist_urls = set()
_screen_file = None
def __init__(self, params=None, auto_init=True):
if params is None:
params = {}
self._ies = []
self._ies_instances = {}
self._pps = []
self._progress_hooks = []
self._download_retcode = 0
self._num_downloads = 0
self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
self._err_file = sys.stderr
self.params = {
'nocheckcertificate': False,
}
self.params.update(params)
self.cache = Cache(self)
def check_deprecated(param, option, suggestion):
if self.params.get(param) is not None:
self.report_warning(
'%s is deprecated. Use %s instead.' % (option, suggestion))
return True
return False
if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
if self.params.get('geo_verification_proxy') is None:
self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
check_deprecated('autonumber_size', '--autonumber-size', 'output template with %(autonumber)0Nd, where N in the number of digits')
check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
if params.get('bidi_workaround', False):
try:
import pty
master, slave = pty.openpty()
width = compat_get_terminal_size().columns
if width is None:
width_args = []
else:
width_args = ['-w', str(width)]
sp_kwargs = dict(
stdin=subprocess.PIPE,
stdout=slave,
stderr=self._err_file)
try:
self._output_process = subprocess.Popen(
['bidiv'] + width_args, **sp_kwargs
)
except OSError:
self._output_process = subprocess.Popen(
['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
self._output_channel = os.fdopen(master, 'rb')
except OSError as ose:
if ose.errno == errno.ENOENT:
self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
else:
raise
if (sys.platform != 'win32'
and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
and not params.get('restrictfilenames', False)):
ort_warning(
'Assuming --restrict-filenames since file system encoding '
'cannot encode all characters. '
'Set the LC_ALL environment variable to fix this.')
self.params['restrictfilenames'] = True
if isinstance(params.get('outtmpl'), bytes):
self.report_warning(
'Parameter outtmpl is bytes, but should be a unicode string. '
'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
self._setup_opener()
if auto_init:
self.print_debug_header()
self.add_default_info_extractors()
for pp_def_raw in self.params.get('postprocessors', []):
pp_class = get_postprocessor(pp_def_raw['key'])
pp_def = dict(pp_def_raw)
del pp_def['key']
pp = pp_class(self, **compat_kwargs(pp_def))
self.add_post_processor(pp)
for ph in self.params.get('progress_hooks', []):
self.add_progress_hook(ph)
register_socks_protocols()
def warn_if_short_id(self, argv):
idxs = [
i for i, a in enumerate(argv)
if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
if idxs:
correct_argv = (
['youtube-dl']
+ [a for i, a in enumerate(argv) if i not in idxs]
+ ['--'] + [argv[i] for i in idxs]
)
self.report_warning(
'Long argument string detected. '
'Use -- to separate parameters and URLs, like this:\n%s\n' %
args_to_str(correct_argv))
def add_info_extractor(self, ie):
self._ies.append(ie)
if not isinstance(ie, type):
self._ies_instances[ie.ie_key()] = ie
ie.set_downloader(self)
def get_info_extractor(self, ie_key):
ie = self._ies_instances.get(ie_key)
if ie is None:
ie = get_info_extractor(ie_key)()
self.add_info_extractor(ie)
return ie
def add_default_info_extractors(self):
for ie in gen_extractor_classes():
self.add_info_extractor(ie)
def add_post_processor(self, pp):
self._pps.append(pp)
pp.set_downloader(self)
def add_progress_hook(self, ph):
self._progress_hooks.append(ph)
def _bidi_workaround(self, message):
if not hasattr(self, '_output_channel'):
return message
assert hasattr(self, '_output_process')
assert isinstance(message, compat_str)
line_count = message.count('\n') + 1
self._output_process.stdin.write((message + '\n').encode('utf-8'))
self._output_process.stdin.flush()
res = ''.join(self._output_channel.readline().decode('utf-8')
for _ in range(line_count))
return res[:-len('\n')]
def to_screen(self, message, skip_eol=False):
return self.to_stdout(message, skip_eol, check_quiet=True)
def _write_string(self, s, out=None):
write_string(s, out=out, encoding=self.params.get('encoding'))
def to_stdout(self, message, skip_eol=False, check_quiet=False):
if self.params.get('logger'):
self.params['logger'].debug(message)
elif not check_quiet or not self.params.get('quiet', False):
message = self._bidi_workaround(message)
terminator = ['\n', ''][skip_eol]
output = message + terminator
self._write_string(output, self._screen_file)
def to_stderr(self, message):
assert isinstance(message, compat_str)
if self.params.get('logger'):
self.params['logger'].error(message)
else:
message = self._bidi_workaround(message)
output = message + '\n'
self._write_string(output, self._err_file)
def to_console_title(self, message):
if not self.params.get('consoletitle', False):
return
if compat_os_name == 'nt':
if ctypes.windll.kernel32.GetConsoleWindow():
ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
elif 'TERM' in os.environ:
self._write_string('\033]0;%s\007' % message, self._screen_file)
def save_console_title(self):
if not self.params.get('consoletitle', False):
return
if self.params.get('simulate', False):
return
if compat_os_name != 'nt' and 'TERM' in os.environ:
self._write_string('\033[22;0t', self._screen_file)
def restore_console_title(self):
if not self.params.get('consoletitle', False):
return
if self.params.get('simulate', False):
return
if compat_os_name != 'nt' and 'TERM' in os.environ:
self._write_string('\033[23;0t', self._screen_file)
def __enter__(self):
self.save_console_title()
return self
def __exit__(self, *args):
self.restore_console_title()
if self.params.get('cookiefile') is not None:
self.cookiejar.save(ignore_discard=True, ignore_expires=True)
def trouble(self, message=None, tb=None):
if message is not None:
self.to_stderr(message)
if self.params.get('verbose'):
if tb is None:
if sys.exc_info()[0]:
tb = ''
if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
tb += encode_compat_str(traceback.format_exc())
else:
tb_data = traceback.format_list(traceback.extract_stack())
tb = ''.join(tb_data)
self.to_stderr(tb)
if not self.params.get('ignoreerrors', False):
if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
exc_info = sys.exc_info()[1].exc_info
else:
exc_info = sys.exc_info()
raise DownloadError(message, exc_info)
self._download_retcode = 1
def report_warning(self, message):
if self.params.get('logger') is not None:
self.params['logger'].warning(message)
else:
if self.params.get('no_warnings'):
return
if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
_msg_header = '\033[0;33mWARNING:\033[0m'
else:
_msg_header = 'WARNING:'
warning_message = '%s %s' % (_msg_header, message)
self.to_stderr(warning_message)
def report_error(self, message, tb=None):
if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
_msg_header = '\033[0;31mERROR:\033[0m'
else:
_msg_header = 'ERROR:'
error_message = '%s %s' % (_msg_header, message)
self.trouble(error_message, tb)
def report_file_already_downloaded(self, file_name):
try:
self.to_screen('[download] %s has already been downloaded' % file_name)
except UnicodeEncodeError:
self.to_screen('[download] The file has already been downloaded')
def prepare_filename(self, info_dict):
try:
template_dict = dict(info_dict)
template_dict['epoch'] = int(time.time())
autonumber_size = self.params.get('autonumber_size')
if autonumber_size is None:
autonumber_size = 5
template_dict['autonumber'] = self.params.get('autonumber_start', 1) - 1 + self._num_downloads
if template_dict.get('resolution') is None:
if template_dict.get('width') and template_dict.get('height'):
template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
elif template_dict.get('height'):
template_dict['resolution'] = '%sp' % template_dict['height']
elif template_dict.get('width'):
template_dict['resolution'] = '%dx?' % template_dict['width']
sanitize = lambda k, v: sanitize_filename(
compat_str(v),
restricted=self.params.get('restrictfilenames'),
is_id=(k == 'id' or k.endswith('_id')))
template_dict = dict((k, v if isinstance(v, compat_numeric_types) else sanitize(k, v))
for k, v in template_dict.items()
if v is not None and not isinstance(v, (list, tuple, dict)))
template_dict = collections.defaultdict(lambda: self.params.get('outtmpl_na_placeholder', 'NA'), template_dict)
outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
field_size_compat_map = {
'playlist_index': len(str(template_dict['n_entries'])),
'autonumber': autonumber_size,
}
FIELD_SIZE_COMPAT_RE = r'(?<!%)%\((?P<field>autonumber|playlist_index)\)s'
mobj = re.search(FIELD_SIZE_COMPAT_RE, outtmpl)
if mobj:
outtmpl = re.sub(
FIELD_SIZE_COMPAT_RE,
r'%%(\1)0%dd' % field_size_compat_map[mobj.group('field')],
outtmpl)
for numeric_field in self._NUMERIC_FIELDS:
if numeric_field not in template_dict:
FORMAT_RE = r'''(?x)
(?<!%)
%
\({0}\) # mapping key
(?:[#0\-+ ]+)? # conversion flags (optional)
(?:\d+)? # minimum field width (optional)
(?:\.\d+)? # precision (optional)
[hlL]? # length modifier (optional)
[diouxXeEfFgGcrs%] # conversion type
'''
outtmpl = re.sub(
FORMAT_RE.format(numeric_field),
r'%({0})s'.format(numeric_field), outtmpl)
sep = ''.join([random.choice(ascii_letters) for _ in range(32)])
outtmpl = outtmpl.replace('%%', '%{0}%'.format(sep)).replace('$$', '${0}$'.format(sep))
# because meta fields may contain env variables we don't want to
filename = expand_path(outtmpl).replace(sep, '') % template_dict
# filename = os.path.join('out', filename)
# print('hychu, The filename is {%s}.{%s}' % (outtmpl, filename))
# Temporary fix for #4787
# 'Treat' all problem characters by passing filename through preferredencoding
# to workaround encoding issues with subprocess on python2 @ Windows
if sys.version_info < (3, 0) and sys.platform == 'win32':
filename = encodeFilename(filename, True).decode(preferredencoding())
return sanitize_path(filename)
except ValueError as err:
self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
return None
def _match_entry(self, info_dict, incomplete):
video_title = info_dict.get('title', info_dict.get('id', 'video'))
if 'title' in info_dict:
# This can happen when we're just evaluating the playlist
title = info_dict['title']
matchtitle = self.params.get('matchtitle', False)
if matchtitle:
if not re.search(matchtitle, title, re.IGNORECASE):
return '"' + title + '" title did not match pattern "' + matchtitle + '"'
rejecttitle = self.params.get('rejecttitle', False)
if rejecttitle:
if re.search(rejecttitle, title, re.IGNORECASE):
return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
date = info_dict.get('upload_date')
if date is not None:
dateRange = self.params.get('daterange', DateRange())
if date not in dateRange:
return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
view_count = info_dict.get('view_count')
if view_count is not None:
min_views = self.params.get('min_views')
if min_views is not None and view_count < min_views:
return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
max_views = self.params.get('max_views')
if max_views is not None and view_count > max_views:
return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
return 'Skipping "%s" because it is age restricted' % video_title
if self.in_download_archive(info_dict):
return '%s has already been recorded in archive' % video_title
if not incomplete:
match_filter = self.params.get('match_filter')
if match_filter is not None:
ret = match_filter(info_dict)
if ret is not None:
return ret
return None
@staticmethod
def add_extra_info(info_dict, extra_info):
for key, value in extra_info.items():
info_dict.setdefault(key, value)
def extract_info(self, url, download=True, ie_key=None, extra_info={},
process=True, force_generic_extractor=False):
if not ie_key and force_generic_extractor:
ie_key = 'Generic'
if ie_key:
ies = [self.get_info_extractor(ie_key)]
else:
ies = self._ies
for ie in ies:
if not ie.suitable(url):
continue
ie = self.get_info_extractor(ie.ie_key())
if not ie.working():
self.report_warning('The program functionality for this site has been marked as broken, '
'and will probably not work.')
return self.__extract_info(url, ie, download, extra_info, process)
else:
self.report_error('no suitable InfoExtractor for URL %s' % url)
def __handle_extraction_exceptions(func):
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except GeoRestrictedError as e:
msg = e.msg
if e.countries:
msg += '\nThis video is available in %s.' % ', '.join(
map(ISO3166Utils.short2full, e.countries))
msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
self.report_error(msg)
except ExtractorError as e:
self.report_error(compat_str(e), e.format_traceback())
except MaxDownloadsReached:
raise
except Exception as e:
if self.params.get('ignoreerrors', False):
self.report_error(error_to_compat_str(e), tb=encode_compat_str(traceback.format_exc()))
else:
raise
return wrapper
@__handle_extraction_exceptions
def __extract_info(self, url, ie, download, extra_info, process):
ie_result = ie.extract(url)
if ie_result is None:
return
if isinstance(ie_result, list):
ie_result = {
'_type': 'compat_list',
'entries': ie_result,
}
self.add_default_extra_info(ie_result, ie, url)
if process:
return self.process_ie_result(ie_result, download, extra_info)
else:
return ie_result
def add_default_extra_info(self, ie_result, ie, url):
self.add_extra_info(ie_result, {
'extractor': ie.IE_NAME,
'webpage_url': url,
'webpage_url_basename': url_basename(url),
'extractor_key': ie.ie_key(),
})
def process_ie_result(self, ie_result, download=True, extra_info={}):
result_type = ie_result.get('_type', 'video')
if result_type in ('url', 'url_transparent'):
ie_result['url'] = sanitize_url(ie_result['url'])
extract_flat = self.params.get('extract_flat', False)
if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
or extract_flat is True):
self.__forced_printings(
ie_result, self.prepare_filename(ie_result),
incomplete=True)
return ie_result
if result_type == 'video':
self.add_extra_info(ie_result, extra_info)
return self.process_video_result(ie_result, download=download)
elif result_type == 'url':
return self.extract_info(ie_result['url'],
download,
ie_key=ie_result.get('ie_key'),
extra_info=extra_info)
elif result_type == 'url_transparent':
info = self.extract_info(
ie_result['url'], ie_key=ie_result.get('ie_key'),
extra_info=extra_info, download=False, process=False)
# in this case
if not info:
return info
force_properties = dict(
(k, v) for k, v in ie_result.items() if v is not None)
for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'):
if f in force_properties:
del force_properties[f]
new_result = info.copy()
new_result.update(force_properties)
# Extracted info may not be a video result (i.e.
# info.get('_type', 'video') != video) but rather an url or
# url_transparent. In such cases outer metadata (from ie_result)
# should be propagated to inner one (info). For this to happen
# _type of info should be overridden with url_transparent. This
# fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
if new_result.get('_type') == 'url':
new_result['_type'] = 'url_transparent'
return self.process_ie_result(
new_result, download=download, extra_info=extra_info)
elif result_type in ('playlist', 'multi_video'):
# Protect from infinite recursion due to recursively nested playlists
# (see https://github.com/ytdl-org/youtube-dl/issues/27833)
webpage_url = ie_result['webpage_url']
if webpage_url in self._playlist_urls:
self.to_screen(
'[download] Skipping already downloaded playlist: %s'
% ie_result.get('title') or ie_result.get('id'))
return
self._playlist_level += 1
self._playlist_urls.add(webpage_url)
try:
return self.__process_playlist(ie_result, download)
finally:
self._playlist_level -= 1
if not self._playlist_level:
self._playlist_urls.clear()
elif result_type == 'compat_list':
self.report_warning(
'Extractor %s returned a compat_list result. '
'It needs to be updated.' % ie_result.get('extractor'))
def _fixup(r):
self.add_extra_info(
r,
{
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
}
)
return r
ie_result['entries'] = [
self.process_ie_result(_fixup(r), download, extra_info)
for r in ie_result['entries']
]
return ie_result
else:
raise Exception('Invalid result type: %s' % result_type)
def __process_playlist(self, ie_result, download):
# We process each entry in the playlist
playlist = ie_result.get('title') or ie_result.get('id')
self.to_screen('[download] Downloading playlist: %s' % playlist)
playlist_results = []
playliststart = self.params.get('playliststart', 1) - 1
playlistend = self.params.get('playlistend')
# For backwards compatibility, interpret -1 as whole list
if playlistend == -1:
playlistend = None
playlistitems_str = self.params.get('playlist_items')
playlistitems = None
if playlistitems_str is not None:
def iter_playlistitems(format):
for string_segment in format.split(','):
if '-' in string_segment:
start, end = string_segment.split('-')
for item in range(int(start), int(end) + 1):
yield int(item)
else:
yield int(string_segment)
playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
ie_entries = ie_result['entries']
def make_playlistitems_entries(list_ie_entries):
num_entries = len(list_ie_entries)
return [
list_ie_entries[i - 1] for i in playlistitems
if -num_entries <= i - 1 < num_entries]
def report_download(num_entries):
self.to_screen(
'[%s] playlist %s: Downloading %d videos' %
(ie_result['extractor'], playlist, num_entries))
if isinstance(ie_entries, list):
n_all_entries = len(ie_entries)
if playlistitems:
entries = make_playlistitems_entries(ie_entries)
else:
entries = ie_entries[playliststart:playlistend]
n_entries = len(entries)
self.to_screen(
'[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
(ie_result['extractor'], playlist, n_all_entries, n_entries))
elif isinstance(ie_entries, PagedList):
if playlistitems:
entries = []
for item in playlistitems:
entries.extend(ie_entries.getslice(
item - 1, item
))
else:
entries = ie_entries.getslice(
playliststart, playlistend)
n_entries = len(entries)
report_download(n_entries)
else: # iterable
if playlistitems:
entries = make_playlistitems_entries(list(itertools.islice(
ie_entries, 0, max(playlistitems))))
else:
entries = list(itertools.islice(
ie_entries, playliststart, playlistend))
n_entries = len(entries)
report_download(n_entries)
if self.params.get('playlistreverse', False):
entries = entries[::-1]
if self.params.get('playlistrandom', False):
random.shuffle(entries)
x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
for i, entry in enumerate(entries, 1):
self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
# This __x_forwarded_for_ip thing is a bit ugly but requires
# minimal changes
if x_forwarded_for:
entry['__x_forwarded_for_ip'] = x_forwarded_for
extra = {
'n_entries': n_entries,
'playlist': playlist,
'playlist_id': ie_result.get('id'),
'playlist_title': ie_result.get('title'),
'playlist_uploader': ie_result.get('uploader'),
'playlist_uploader_id': ie_result.get('uploader_id'),
'playlist_index': playlistitems[i - 1] if playlistitems else i + playliststart,
'extractor': ie_result['extractor'],
'webpage_url': ie_result['webpage_url'],
'webpage_url_basename': url_basename(ie_result['webpage_url']),
'extractor_key': ie_result['extractor_key'],
}
reason = self._match_entry(entry, incomplete=True)
if reason is not None:
self.to_screen('[download] ' + reason)
continue
entry_result = self.__process_iterable_entry(entry, download, extra)
# TODO: skip failed (empty) entries?
playlist_results.append(entry_result)
ie_result['entries'] = playlist_results
self.to_screen('[download] Finished downloading playlist: %s' % playlist)
return ie_result
@__handle_extraction_exceptions
def __process_iterable_entry(self, entry, download, extra_info):
return self.process_ie_result(
entry, download=download, extra_info=extra_info)
def _build_format_filter(self, filter_spec):
OPERATORS = {
'<': operator.lt,
'<=': operator.le,
'>': operator.gt,
'>=': operator.ge,
'=': operator.eq,
'!=': operator.ne,
}
operator_rex = re.compile(r'''(?x)\s*
(?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps)
\s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
(?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
$
''' % '|'.join(map(re.escape, OPERATORS.keys())))
m = operator_rex.search(filter_spec)
if m:
try:
comparison_value = int(m.group('value'))
except ValueError:
comparison_value = parse_filesize(m.group('value'))
if comparison_value is None:
comparison_value = parse_filesize(m.group('value') + 'B')
if comparison_value is None:
raise ValueError(
'Invalid value %r in format specification %r' % (
m.group('value'), filter_spec))
op = OPERATORS[m.group('op')]
if not m:
STR_OPERATORS = {
'=': operator.eq,
'^=': lambda attr, value: attr.startswith(value),
'$=': lambda attr, value: attr.endswith(value),
'*=': lambda attr, value: value in attr,
}
str_operator_rex = re.compile(r'''(?x)
\s*(?P<key>ext|acodec|vcodec|container|protocol|format_id|language)
\s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?
\s*(?P<value>[a-zA-Z0-9._-]+)
\s*$
''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
m = str_operator_rex.search(filter_spec)
if m:
comparison_value = m.group('value')
str_op = STR_OPERATORS[m.group('op')]
if m.group('negation'):
op = lambda attr, value: not str_op(attr, value)
else:
op = str_op
if not m:
raise ValueError('Invalid filter specification %r' % filter_spec)
def _filter(f):
actual_value = f.get(m.group('key'))
if actual_value is None:
return m.group('none_inclusive')
return op(actual_value, comparison_value)
return _filter
def _default_format_spec(self, info_dict, download=True):
def can_merge():
merger = FFmpegMergerPP(self)
return merger.available and merger.can_merge()
def prefer_best():
if self.params.get('simulate', False):
return False
if not download:
return False
if self.params.get('outtmpl', DEFAULT_OUTTMPL) == '-':
return True
if info_dict.get('is_live'):
return True
if not can_merge():
return True
return False
req_format_list = ['bestvideo+bestaudio', 'best']
if prefer_best():
req_format_list.reverse()
return '/'.join(req_format_list)
def build_format_selector(self, format_spec):
def syntax_error(note, start):
message = (
'Invalid format specification: '
'{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
return SyntaxError(message)
PICKFIRST = 'PICKFIRST'
MERGE = 'MERGE'
SINGLE = 'SINGLE'
GROUP = 'GROUP'
FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
def _parse_filter(tokens):
filter_parts = []
for type, string, start, _, _ in tokens:
if type == tokenize.OP and string == ']':
return ''.join(filter_parts)
else:
filter_parts.append(string)
def _remove_unused_ops(tokens):
# Remove operators that we don't use and join them with the surrounding strings
ALLOWED_OPS = ('/', '+', ',', '(', ')')
last_string, last_start, last_end, last_line = None, None, None, None
for type, string, start, end, line in tokens:
if type == tokenize.OP and string == '[':
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
last_string = None
yield type, string, start, end, line
for type, string, start, end, line in tokens:
yield type, string, start, end, line
if type == tokenize.OP and string == ']':
break
elif type == tokenize.OP and string in ALLOWED_OPS:
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
last_string = None
yield type, string, start, end, line
elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
if not last_string:
last_string = string
last_start = start
last_end = end
else:
last_string += string
if last_string:
yield tokenize.NAME, last_string, last_start, last_end, last_line
def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
selectors = []
current_selector = None
for type, string, start, _, _ in tokens:
if type == getattr(tokenize, 'ENCODING', None):
continue
elif type in [tokenize.NAME, tokenize.NUMBER]:
current_selector = FormatSelector(SINGLE, string, [])
elif type == tokenize.OP:
if string == ')':
if not inside_group:
tokens.restore_last_token()
break
elif inside_merge and string in ['/', ',']:
tokens.restore_last_token()
break
elif inside_choice and string == ',':
tokens.restore_last_token()
break
elif string == ',':
if not current_selector:
raise syntax_error('"," must follow a format selector', start)
selectors.append(current_selector)
current_selector = None
elif string == '/':
if not current_selector:
raise syntax_error('"/" must follow a format selector', start)
first_choice = current_selector
second_choice = _parse_format_selection(tokens, inside_choice=True)
current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
elif string == '[':
if not current_selector:
current_selector = FormatSelector(SINGLE, 'best', [])
format_filter = _parse_filter(tokens)
current_selector.filters.append(format_filter)
elif string == '(':
if current_selector:
raise syntax_error('Unexpected "("', start)
group = _parse_format_selection(tokens, inside_group=True)
current_selector = FormatSelector(GROUP, group, [])
elif string == '+':
if inside_merge:
raise syntax_error('Unexpected "+"', start)
video_selector = current_selector
audio_selector = _parse_format_selection(tokens, inside_merge=True)
if not video_selector or not audio_selector:
raise syntax_error('"+" must be between two format selectors', start)
current_selector = FormatSelector(MERGE, (video_selector, audio_selector), [])
else:
raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
elif type == tokenize.ENDMARKER:
break
if current_selector:
selectors.append(current_selector)
return selectors
def _build_selector_function(selector):
if isinstance(selector, list):
fs = [_build_selector_function(s) for s in selector]
def selector_function(ctx):
for f in fs:
for format in f(ctx):
yield format
return selector_function
elif selector.type == GROUP:
selector_function = _build_selector_function(selector.selector)
elif selector.type == PICKFIRST:
fs = [_build_selector_function(s) for s in selector.selector]
def selector_function(ctx):
for f in fs:
picked_formats = list(f(ctx))
if picked_formats:
return picked_formats
return []
elif selector.type == SINGLE:
format_spec = selector.selector
def selector_function(ctx):
formats = list(ctx['formats'])
if not formats:
return
if format_spec == 'all':
for f in formats:
yield f
elif format_spec in ['best', 'worst', None]:
format_idx = 0 if format_spec == 'worst' else -1
audiovideo_formats = [
f for f in formats
if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
if audiovideo_formats:
yield audiovideo_formats[format_idx]
elif ctx['incomplete_formats']:
yield formats[format_idx]
elif format_spec == 'bestaudio':
audio_formats = [
f for f in formats
if f.get('vcodec') == 'none']
if audio_formats:
yield audio_formats[-1]
elif format_spec == 'worstaudio':
audio_formats = [
f for f in formats
if f.get('vcodec') == 'none']
if audio_formats:
yield audio_formats[0]
elif format_spec == 'bestvideo':
video_formats = [
f for f in formats
if f.get('acodec') == 'none']
if video_formats:
yield video_formats[-1]
elif format_spec == 'worstvideo':
video_formats = [
f for f in formats
if f.get('acodec') == 'none']
if video_formats:
yield video_formats[0]
else:
extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
if format_spec in extensions:
filter_f = lambda f: f['ext'] == format_spec
else:
filter_f = lambda f: f['format_id'] == format_spec
matches = list(filter(filter_f, formats))
if matches:
yield matches[-1]
elif selector.type == MERGE:
def _merge(formats_info):
format_1, format_2 = [f['format_id'] for f in formats_info]
if formats_info[0].get('vcodec') == 'none':
self.report_error('The first format must '
'contain the video, try using '
'"-f %s+%s"' % (format_2, format_1))
return
if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none':
self.report_error(
'Both formats %s and %s are video-only, you must specify "-f video+audio"'
% (format_1, format_2))
return
output_ext = (
formats_info[0]['ext']
if self.params.get('merge_output_format') is None
else self.params['merge_output_format'])
return {
'requested_formats': formats_info,
'format': '%s+%s' % (formats_info[0].get('format'),
formats_info[1].get('format')),
'format_id': '%s+%s' % (formats_info[0].get('format_id'),
formats_info[1].get('format_id')),
'width': formats_info[0].get('width'),
'height': formats_info[0].get('height'),
'resolution': formats_info[0].get('resolution'),
'fps': formats_info[0].get('fps'),
'vcodec': formats_info[0].get('vcodec'),
'vbr': formats_info[0].get('vbr'),
'stretched_ratio': formats_info[0].get('stretched_ratio'),
'acodec': formats_info[1].get('acodec'),
'abr': formats_info[1].get('abr'),
'ext': output_ext,
}
video_selector, audio_selector = map(_build_selector_function, selector.selector)
def selector_function(ctx):
for pair in itertools.product(
video_selector(copy.deepcopy(ctx)), audio_selector(copy.deepcopy(ctx))):
yield _merge(pair)
filters = [self._build_format_filter(f) for f in selector.filters]
def final_selector(ctx):
ctx_copy = copy.deepcopy(ctx)
for _filter in filters:
ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
return selector_function(ctx_copy)
return final_selector
stream = io.BytesIO(format_spec.encode('utf-8'))
try:
tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
except tokenize.TokenError:
raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
class TokenIterator(object):
def __init__(self, tokens):
self.tokens = tokens
self.counter = 0
def __iter__(self):
return self
def __next__(self):
if self.counter >= len(self.tokens):
raise StopIteration()
value = self.tokens[self.counter]
self.counter += 1
return value
next = __next__
def restore_last_token(self):
self.counter -= 1
parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
return _build_selector_function(parsed_selector)
def _calc_headers(self, info_dict):
res = std_headers.copy()
add_headers = info_dict.get('http_headers')
if add_headers:
res.update(add_headers)
cookies = self._calc_cookies(info_dict)
if cookies:
res['Cookie'] = cookies
if 'X-Forwarded-For' not in res:
x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
if x_forwarded_for_ip:
res['X-Forwarded-For'] = x_forwarded_for_ip
return res
def _calc_cookies(self, info_dict):
pr = sanitized_Request(info_dict['url'])
self.cookiejar.add_cookie_header(pr)
return pr.get_header('Cookie')
def process_video_result(self, info_dict, download=True):
assert info_dict.get('_type', 'video') == 'video'
if 'id' not in info_dict:
raise ExtractorError('Missing "id" field in extractor result')
if 'title' not in info_dict:
raise ExtractorError('Missing "title" field in extractor result')
def report_force_conversion(field, field_not, conversion):
self.report_warning(
'"%s" field is not %s - forcing %s conversion, there is an error in extractor'
% (field, field_not, conversion))
def sanitize_string_field(info, string_field):
field = info.get(string_field)
if field is None or isinstance(field, compat_str):
return
report_force_conversion(string_field, 'a string', 'string')
info[string_field] = compat_str(field)
def sanitize_numeric_fields(info):
for numeric_field in self._NUMERIC_FIELDS:
field = info.get(numeric_field)
if field is None or isinstance(field, compat_numeric_types):
continue
report_force_conversion(numeric_field, 'numeric', 'int')
info[numeric_field] = int_or_none(field)
sanitize_string_field(info_dict, 'id')
sanitize_numeric_fields(info_dict)
if 'playlist' not in info_dict:
info_dict['playlist'] = None
info_dict['playlist_index'] = None
thumbnails = info_dict.get('thumbnails')
if thumbnails is None:
thumbnail = info_dict.get('thumbnail')
if thumbnail:
info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
if thumbnails:
thumbnails.sort(key=lambda t: (
t.get('preference') if t.get('preference') is not None else -1,
t.get('width') if t.get('width') is not None else -1,
t.get('height') if t.get('height') is not None else -1,
t.get('id') if t.get('id') is not None else '', t.get('url')))
for i, t in enumerate(thumbnails):
t['url'] = sanitize_url(t['url'])
if t.get('width') and t.get('height'):
t['resolution'] = '%dx%d' % (t['width'], t['height'])
if t.get('id') is None:
t['id'] = '%d' % i
if self.params.get('list_thumbnails'):
self.list_thumbnails(info_dict)
return
thumbnail = info_dict.get('thumbnail')
if thumbnail:
info_dict['thumbnail'] = sanitize_url(thumbnail)
elif thumbnails:
info_dict['thumbnail'] = thumbnails[-1]['url']
if 'display_id' not in info_dict and 'id' in info_dict:
info_dict['display_id'] = info_dict['id']
for ts_key, date_key in (
('timestamp', 'upload_date'),
('release_timestamp', 'release_date'),
):
if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
# Working around out-of-range timestamp values (e.g. negative ones on Windows,
# see http://bugs.python.org/issue1646728)
try:
upload_date = datetime.datetime.utcfromtimestamp(info_dict[ts_key])
info_dict[date_key] = upload_date.strftime('%Y%m%d')
except (ValueError, OverflowError, OSError):
pass
# Auto generate title fields corresponding to the *_number fields when missing
# in order to always have clean titles. This is very common for TV series.
for field in ('chapter', 'season', 'episode'):
if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
for cc_kind in ('subtitles', 'automatic_captions'):
cc = info_dict.get(cc_kind)
if cc:
for _, subtitle in cc.items():
for subtitle_format in subtitle:
if subtitle_format.get('url'):
subtitle_format['url'] = sanitize_url(subtitle_format['url'])
if subtitle_format.get('ext') is None:
subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
automatic_captions = info_dict.get('automatic_captions')
subtitles = info_dict.get('subtitles')
if self.params.get('listsubtitles', False):
if 'automatic_captions' in info_dict:
self.list_subtitles(
info_dict['id'], automatic_captions, 'automatic captions')
self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
return
info_dict['requested_subtitles'] = self.process_subtitles(
info_dict['id'], subtitles, automatic_captions)
# We now pick which formats have to be downloaded
if info_dict.get('formats') is None:
# There's only one format available
formats = [info_dict]
else:
formats = info_dict['formats']
if not formats:
raise ExtractorError('No video formats found!')
def is_wellformed(f):
url = f.get('url')
if not url:
self.report_warning(
'"url" field is missing or empty - skipping format, '
'there is an error in extractor')
return False
if isinstance(url, bytes):
sanitize_string_field(f, 'url')
return True
formats = list(filter(is_wellformed, formats))
formats_dict = {}
for i, format in enumerate(formats):
sanitize_string_field(format, 'format_id')
sanitize_numeric_fields(format)
format['url'] = sanitize_url(format['url'])
if not format.get('format_id'):
format['format_id'] = compat_str(i)
else:
format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
format_id = format['format_id']
if format_id not in formats_dict:
formats_dict[format_id] = []
formats_dict[format_id].append(format)
for format_id, ambiguous_formats in formats_dict.items():
if len(ambiguous_formats) > 1:
for i, format in enumerate(ambiguous_formats):
format['format_id'] = '%s-%d' % (format_id, i)
for i, format in enumerate(formats):
if format.get('format') is None:
format['format'] = '{id} - {res}{note}'.format(
id=format['format_id'],
res=self.format_resolution(format),
note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
)
if format.get('ext') is None:
format['ext'] = determine_ext(format['url']).lower()
if format.get('protocol') is None:
format['protocol'] = determine_protocol(format)
full_format_info = info_dict.copy()
full_format_info.update(format)
format['http_headers'] = self._calc_headers(full_format_info)
if '__x_forwarded_for_ip' in info_dict:
del info_dict['__x_forwarded_for_ip']
if formats[0] is not info_dict:
info_dict['formats'] = formats
if self.params.get('listformats'):
self.list_formats(info_dict)
return
req_format = self.params.get('format')
if req_format is None:
req_format = self._default_format_spec(info_dict, download=download)
if self.params.get('verbose'):
self._write_string('[debug] Default format spec: %s\n' % req_format)
format_selector = self.build_format_selector(req_format)
# While in format selection we may need to have an access to the original
# format set in order to calculate some metrics or do some processing.
# For now we need to be able to guess whether original formats provided
# by extractor are incomplete or not (i.e. whether extractor provides only
# video-only or audio-only formats) for proper formats selection for
# extractors with such incomplete formats (see
# https://github.com/ytdl-org/youtube-dl/pull/5556).
# Since formats may be filtered during format selection and may not match
# the original formats the results may be incorrect. Thus original formats
# or pre-calculated metrics should be passed to format selection routines
# as well.
# We will pass a context object containing all necessary additional data
# instead of just formats.
# This fixes incorrect format selection issue (see
# https://github.com/ytdl-org/youtube-dl/issues/10083).
incomplete_formats = (
# All formats are video-only or
all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats)
# all formats are audio-only
or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
ctx = {
'formats': formats,
'incomplete_formats': incomplete_formats,
}
formats_to_download = list(format_selector(ctx))
if not formats_to_download:
raise ExtractorError('requested format not available',
expected=True)
if download:
if len(formats_to_download) > 1:
self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
for format in formats_to_download:
new_info = dict(info_dict)
new_info.update(format)
self.process_info(new_info)
# We update the info dict with the best quality format (backwards compatibility)
info_dict.update(formats_to_download[-1])
return info_dict
def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
available_subs = {}
if normal_subtitles and self.params.get('writesubtitles'):
available_subs.update(normal_subtitles)
if automatic_captions and self.params.get('writeautomaticsub'):
for lang, cap_info in automatic_captions.items():
if lang not in available_subs:
available_subs[lang] = cap_info
if (not self.params.get('writesubtitles') and not
self.params.get('writeautomaticsub') or not
available_subs):
return None
if self.params.get('allsubtitles', False):
requested_langs = available_subs.keys()
else:
if self.params.get('subtitleslangs', False):
requested_langs = self.params.get('subtitleslangs')
elif 'en' in available_subs:
requested_langs = ['en']
else:
requested_langs = [list(available_subs.keys())[0]]
formats_query = self.params.get('subtitlesformat', 'best')
formats_preference = formats_query.split('/') if formats_query else []
subs = {}
for lang in requested_langs:
formats = available_subs.get(lang)
if formats is None:
self.report_warning('%s subtitles not available for %s' % (lang, video_id))
continue
for ext in formats_preference:
if ext == 'best':
f = formats[-1]
break
matches = list(filter(lambda f: f['ext'] == ext, formats))
if matches:
f = matches[-1]
break
else:
f = formats[-1]
self.report_warning(
'No subtitle format found matching "%s" for language %s, '
'using %s' % (formats_query, lang, f['ext']))
subs[lang] = f
return subs
def __forced_printings(self, info_dict, filename, incomplete):
def print_mandatory(field):
if (self.params.get('force%s' % field, False)
and (not incomplete or info_dict.get(field) is not None)):
self.to_stdout(info_dict[field])
def print_optional(field):
if (self.params.get('force%s' % field, False)
and info_dict.get(field) is not None):
self.to_stdout(info_dict[field])
print_mandatory('title')
print_mandatory('id')
if self.params.get('forceurl', False) and not incomplete:
if info_dict.get('requested_formats') is not None:
for f in info_dict['requested_formats']:
self.to_stdout(f['url'] + f.get('play_path', ''))
else:
# For RTMP URLs, also include the playpath
self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
print_optional('thumbnail')
print_optional('description')
if self.params.get('forcefilename', False) and filename is not None:
self.to_stdout(filename)
if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
self.to_stdout(formatSeconds(info_dict['duration']))
print_mandatory('format')
if self.params.get('forcejson', False):
self.to_stdout(json.dumps(info_dict))
def process_info(self, info_dict):
assert info_dict.get('_type', 'video') == 'video'
max_downloads = self.params.get('max_downloads')
if max_downloads is not None:
if self._num_downloads >= int(max_downloads):
raise MaxDownloadsReached()
# TODO: backward compatibility, to be removed
info_dict['fulltitle'] = info_dict['title']
if 'format' not in info_dict:
info_dict['format'] = info_dict['ext']
reason = self._match_entry(info_dict, incomplete=False)
if reason is not None:
self.to_screen('[download] ' + reason)
return
self._num_downloads += 1
info_dict['_filename'] = filename = self.prepare_filename(info_dict)
# Forced printings
self.__forced_printings(info_dict, filename, incomplete=False)
# Do nothing else if in simulate mode
if self.params.get('simulate', False):
return
if filename is None:
return
def ensure_dir_exists(path):
try:
dn = os.path.dirname(path)
if dn and not os.path.exists(dn):
os.makedirs(dn)
return True
except (OSError, IOError) as err:
if isinstance(err, OSError) and err.errno == errno.EEXIST:
return True
self.report_error('unable to create directory ' + error_to_compat_str(err))
return False
if not ensure_dir_exists(sanitize_path(encodeFilename(filename))):
return
if self.params.get('writedescription', False):
descfn = replace_extension(filename, 'description', info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
self.to_screen('[info] Video description is already present')
elif info_dict.get('description') is None:
self.report_warning('There\'s no description to write.')
else:
try:
self.to_screen('[info] Writing video description to: ' + descfn)
with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
descfile.write(info_dict['description'])
except (OSError, IOError):
self.report_error('Cannot write description file ' + descfn)
return
if self.params.get('writeannotations', False):
annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
self.to_screen('[info] Video annotations are already present')
elif not info_dict.get('annotations'):
self.report_warning('There are no annotations to write.')
else:
try:
self.to_screen('[info] Writing video annotations to: ' + annofn)
with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
annofile.write(info_dict['annotations'])
except (KeyError, TypeError):
self.report_warning('There are no annotations to write.')
except (OSError, IOError):
self.report_error('Cannot write annotations file: ' + annofn)
return
subtitles_are_requested = any([self.params.get('writesubtitles', False),
self.params.get('writeautomaticsub')])
if subtitles_are_requested and info_dict.get('requested_subtitles'):
subtitles = info_dict['requested_subtitles']
ie = self.get_info_extractor(info_dict['extractor_key'])
for sub_lang, sub_info in subtitles.items():
sub_format = sub_info['ext']
sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
self.to_screen('[info] Video subtitle %s.%s is already present' % (sub_lang, sub_format))
else:
self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
if sub_info.get('data') is not None:
try:
with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8', newline='') as subfile:
subfile.write(sub_info['data'])
except (OSError, IOError):
self.report_error('Cannot write subtitles file ' + sub_filename)
return
else:
try:
sub_data = ie._request_webpage(
sub_info['url'], info_dict['id'], note=False).read()
with io.open(encodeFilename(sub_filename), 'wb') as subfile:
subfile.write(sub_data)
except (ExtractorError, IOError, OSError, ValueError) as err:
self.report_warning('Unable to download subtitle for "%s": %s' %
(sub_lang, error_to_compat_str(err)))
continue
if self.params.get('writeinfojson', False):
infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
self.to_screen('[info] Video description metadata is already present')
else:
self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
try:
write_json_file(self.filter_requested_info(info_dict), infofn)
except (OSError, IOError):
self.report_error('Cannot write metadata to JSON file ' + infofn)
return
self._write_thumbnails(info_dict, filename)
if not self.params.get('skip_download', False):
try:
def dl(name, info):
fd = get_suitable_downloader(info, self.params)(self, self.params)
for ph in self._progress_hooks:
fd.add_progress_hook(ph)
if self.params.get('verbose'):
self.to_screen('[debug] Invoking downloader on %r' % info.get('url'))
return fd.download(name, info)
if info_dict.get('requested_formats') is not None:
downloaded = []
success = True
merger = FFmpegMergerPP(self)
if not merger.available:
postprocessors = []
self.report_warning('You have requested multiple '
'formats but ffmpeg or avconv are not installed.'
' The formats won\'t be merged.')
else:
postprocessors = [merger]
def compatible_formats(formats):
video, audio = formats
# Check extension
video_ext, audio_ext = video.get('ext'), audio.get('ext')
if video_ext and audio_ext:
COMPATIBLE_EXTS = (
('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma'),
('webm')
)
for exts in COMPATIBLE_EXTS:
if video_ext in exts and audio_ext in exts:
return True
# TODO: Check acodec/vcodec
return False
filename_real_ext = os.path.splitext(filename)[1][1:]
filename_wo_ext = (
os.path.splitext(filename)[0]
if filename_real_ext == info_dict['ext']
else filename)
requested_formats = info_dict['requested_formats']
if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
info_dict['ext'] = 'mkv'
self.report_warning(
'Requested formats are incompatible for merge and will be merged into mkv.')
# Ensure filename always has a correct extension for successful merge
filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
if os.path.exists(encodeFilename(filename)):
self.to_screen(
'[download] %s has already been downloaded and '
'merged' % filename)
else:
for f in requested_formats:
new_info = dict(info_dict)
new_info.update(f)
fname = prepend_extension(
self.prepare_filename(new_info),
'f%s' % f['format_id'], new_info['ext'])
if not ensure_dir_exists(fname):
return
downloaded.append(fname)
partial_success = dl(fname, new_info)
success = success and partial_success
info_dict['__postprocessors'] = postprocessors
info_dict['__files_to_merge'] = downloaded
else:
# Just a single file
success = dl(filename, info_dict)
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
self.report_error('unable to download video data: %s' % error_to_compat_str(err))
return
except (OSError, IOError) as err:
raise UnavailableVideoError(err)
except (ContentTooShortError, ) as err:
self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
return
if success and filename != '-':
# Fixup content
fixup_policy = self.params.get('fixup')
if fixup_policy is None:
fixup_policy = 'detect_or_warn'
INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.'
stretched_ratio = info_dict.get('stretched_ratio')
if stretched_ratio is not None and stretched_ratio != 1:
if fixup_policy == 'warn':
self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
info_dict['id'], stretched_ratio))
elif fixup_policy == 'detect_or_warn':
stretched_pp = FFmpegFixupStretchedPP(self)
if stretched_pp.available:
info_dict.setdefault('__postprocessors', [])
info_dict['__postprocessors'].append(stretched_pp)
else:
self.report_warning(
'%s: Non-uniform pixel ratio (%s). %s'
% (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE))
else:
assert fixup_policy in ('ignore', 'never')
if (info_dict.get('requested_formats') is None
and info_dict.get('container') == 'm4a_dash'):
if fixup_policy == 'warn':
self.report_warning(
'%s: writing DASH m4a. '
'Only some players support this container.'
% info_dict['id'])
elif fixup_policy == 'detect_or_warn':
fixup_pp = FFmpegFixupM4aPP(self)
if fixup_pp.available:
info_dict.setdefault('__postprocessors', [])
info_dict['__postprocessors'].append(fixup_pp)
else:
self.report_warning(
'%s: writing DASH m4a. '
'Only some players support this container. %s'
% (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
else:
assert fixup_policy in ('ignore', 'never')
if (info_dict.get('protocol') == 'm3u8_native'
or info_dict.get('protocol') == 'm3u8'
and self.params.get('hls_prefer_native')):
if fixup_policy == 'warn':
self.report_warning('%s: malformed AAC bitstream detected.' % (
info_dict['id']))
elif fixup_policy == 'detect_or_warn':
fixup_pp = FFmpegFixupM3u8PP(self)
if fixup_pp.available:
info_dict.setdefault('__postprocessors', [])
info_dict['__postprocessors'].append(fixup_pp)
else:
self.report_warning(
'%s: malformed AAC bitstream detected. %s'
% (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
else:
assert fixup_policy in ('ignore', 'never')
try:
self.post_process(filename, info_dict)
except (PostProcessingError) as err:
self.report_error('postprocessing: %s' % str(err))
return
self.record_download_archive(info_dict)
def download(self, url_list):
outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
if (len(url_list) > 1
and outtmpl != '-'
and '%' not in outtmpl
and self.params.get('max_downloads') != 1):
raise SameFileError(outtmpl)
for url in url_list:
try:
# It also downloads the videos
res = self.extract_info(
url, force_generic_extractor=self.params.get('force_generic_extractor', False))
except UnavailableVideoError:
self.report_error('unable to download video')
except MaxDownloadsReached:
self.to_screen('[info] Maximum number of downloaded files reached.')
raise
else:
if self.params.get('dump_single_json', False):
self.to_stdout(json.dumps(res))
return self._download_retcode
def download_with_info_file(self, info_filename):
with contextlib.closing(fileinput.FileInput(
[info_filename], mode='r',
openhook=fileinput.hook_encoded('utf-8'))) as f:
# FileInput doesn't have a read method, we can't call json.load
info = self.filter_requested_info(json.loads('\n'.join(f)))
try:
self.process_ie_result(info, download=True)
except DownloadError:
webpage_url = info.get('webpage_url')
if webpage_url is not None:
self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
return self.download([webpage_url])
else:
raise
return self._download_retcode
@staticmethod
def filter_requested_info(info_dict):
return dict(
(k, v) for k, v in info_dict.items()
if k not in ['requested_formats', 'requested_subtitles'])
def post_process(self, filename, ie_info):
info = dict(ie_info)
info['filepath'] = filename
pps_chain = []
if ie_info.get('__postprocessors') is not None:
pps_chain.extend(ie_info['__postprocessors'])
pps_chain.extend(self._pps)
for pp in pps_chain:
files_to_delete = []
try:
files_to_delete, info = pp.run(info)
except PostProcessingError as e:
self.report_error(e.msg)
if files_to_delete and not self.params.get('keepvideo', False):
for old_filename in files_to_delete:
self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
try:
os.remove(encodeFilename(old_filename))
except (IOError, OSError):
self.report_warning('Unable to remove downloaded original file')
def _make_archive_id(self, info_dict):
video_id = info_dict.get('id')
if not video_id:
return
# Future-proof against any change in case
# and backwards compatibility with prior versions
extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
if extractor is None:
url = str_or_none(info_dict.get('url'))
if not url:
return
# Try to find matching extractor for the URL and take its ie_key
for ie in self._ies:
if ie.suitable(url):
extractor = ie.ie_key()
break
else:
return
return extractor.lower() + ' ' + video_id
def in_download_archive(self, info_dict):
fn = self.params.get('download_archive')
if fn is None:
return False
vid_id = self._make_archive_id(info_dict)
if not vid_id:
return False # Incomplete video information
try:
with locked_file(fn, 'r', encoding='utf-8') as archive_file:
for line in archive_file:
if line.strip() == vid_id:
return True
except IOError as ioe:
if ioe.errno != errno.ENOENT:
raise
return False
def record_download_archive(self, info_dict):
fn = self.params.get('download_archive')
if fn is None:
return
vid_id = self._make_archive_id(info_dict)
assert vid_id
with locked_file(fn, 'a', encoding='utf-8') as archive_file:
archive_file.write(vid_id + '\n')
@staticmethod
def format_resolution(format, default='unknown'):
if format.get('vcodec') == 'none':
return 'audio only'
if format.get('resolution') is not None:
return format['resolution']
if format.get('height') is not None:
if format.get('width') is not None:
res = '%sx%s' % (format['width'], format['height'])
else:
res = '%sp' % format['height']
elif format.get('width') is not None:
res = '%dx?' % format['width']
else:
res = default
return res
def _format_note(self, fdict):
res = ''
if fdict.get('ext') in ['f4f', 'f4m']:
res += '(unsupported) '
if fdict.get('language'):
if res:
res += ' '
res += '[%s] ' % fdict['language']
if fdict.get('format_note') is not None:
res += fdict['format_note'] + ' '
if fdict.get('tbr') is not None:
res += '%4dk ' % fdict['tbr']
if fdict.get('container') is not None:
if res:
res += ', '
res += '%s container' % fdict['container']
if (fdict.get('vcodec') is not None
and fdict.get('vcodec') != 'none'):
if res:
res += ', '
res += fdict['vcodec']
if fdict.get('vbr') is not None:
res += '@'
elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
res += 'video@'
if fdict.get('vbr') is not None:
res += '%4dk' % fdict['vbr']
if fdict.get('fps') is not None:
if res:
res += ', '
res += '%sfps' % fdict['fps']
if fdict.get('acodec') is not None:
if res:
res += ', '
if fdict['acodec'] == 'none':
res += 'video only'
else:
res += '%-5s' % fdict['acodec']
elif fdict.get('abr') is not None:
if res:
res += ', '
res += 'audio'
if fdict.get('abr') is not None:
res += '@%3dk' % fdict['abr']
if fdict.get('asr') is not None:
res += ' (%5dHz)' % fdict['asr']
if fdict.get('filesize') is not None:
if res:
res += ', '
res += format_bytes(fdict['filesize'])
elif fdict.get('filesize_approx') is not None:
if res:
res += ', '
res += '~' + format_bytes(fdict['filesize_approx'])
return res
def list_formats(self, info_dict):
formats = info_dict.get('formats', [info_dict])
table = [
[f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
for f in formats
if f.get('preference') is None or f['preference'] >= -1000]
if len(formats) > 1:
table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
header_line = ['format code', 'extension', 'resolution', 'note']
self.to_screen(
'[info] Available formats for %s:\n%s' %
(info_dict['id'], render_table(header_line, table)))
def list_thumbnails(self, info_dict):
thumbnails = info_dict.get('thumbnails')
if not thumbnails:
self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
return
self.to_screen(
'[info] Thumbnails for %s:' % info_dict['id'])
self.to_screen(render_table(
['ID', 'width', 'height', 'URL'],
[[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
def list_subtitles(self, video_id, subtitles, name='subtitles'):
if not subtitles:
self.to_screen('%s has no %s' % (video_id, name))
return
self.to_screen(
'Available %s for %s:' % (name, video_id))
self.to_screen(render_table(
['Language', 'formats'],
[[lang, ', '.join(f['ext'] for f in reversed(formats))]
for lang, formats in subtitles.items()]))
def urlopen(self, req):
if isinstance(req, compat_basestring):
req = sanitized_Request(req)
return self._opener.open(req, timeout=self._socket_timeout)
def print_debug_header(self):
if not self.params.get('verbose'):
return
if type('') is not compat_str:
# Python 2.6 on SLES11 SP1 (https://github.com/ytdl-org/youtube-dl/issues/3326)
self.report_warning(
'Your Python is broken! Update to a newer and supported version')
stdout_encoding = getattr(
sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
encoding_str = (
'[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
locale.getpreferredencoding(),
sys.getfilesystemencoding(),
stdout_encoding,
self.get_encoding()))
write_string(encoding_str, encoding=None)
self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
if _LAZY_LOADER:
self._write_string('[debug] Lazy loading extractors enabled' + '\n')
try:
sp = subprocess.Popen(
['git', 'rev-parse', '--short', 'HEAD'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=os.path.dirname(os.path.abspath(__file__)))
out, err = sp.communicate()
out = out.decode().strip()
if re.match('[0-9a-f]+', out):
self._write_string('[debug] Git HEAD: ' + out + '\n')
except Exception:
try:
sys.exc_clear()
except Exception:
pass
def python_implementation():
impl_name = platform.python_implementation()
if impl_name == 'PyPy' and hasattr(sys, 'pypy_version_info'):
return impl_name + ' version %d.%d.%d' % sys.pypy_version_info[:3]
return impl_name
self._write_string('[debug] Python version %s (%s) - %s\n' % (
platform.python_version(), python_implementation(),
platform_name()))
exe_versions = FFmpegPostProcessor.get_versions(self)
exe_versions['rtmpdump'] = rtmpdump_version()
exe_versions['phantomjs'] = PhantomJSwrapper._version()
exe_str = ', '.join(
'%s %s' % (exe, v)
for exe, v in sorted(exe_versions.items())
if v
)
if not exe_str:
exe_str = 'none'
self._write_string('[debug] exe versions: %s\n' % exe_str)
proxy_map = {}
for handler in self._opener.handlers:
if hasattr(handler, 'proxies'):
proxy_map.update(handler.proxies)
self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
if self.params.get('call_home', False):
ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
self._write_string('[debug] Public IP address: %s\n' % ipaddr)
latest_version = self.urlopen(
'https://yt-dl.org/latest/version').read().decode('utf-8')
if version_tuple(latest_version) > version_tuple(__version__):
self.report_warning(
'You are using an outdated version (newest version: %s)! '
'See https://yt-dl.org/update if you need help updating.' %
latest_version)
def _setup_opener(self):
timeout_val = self.params.get('socket_timeout')
self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
opts_cookiefile = self.params.get('cookiefile')
opts_proxy = self.params.get('proxy')
if opts_cookiefile is None:
self.cookiejar = compat_cookiejar.CookieJar()
else:
opts_cookiefile = expand_path(opts_cookiefile)
self.cookiejar = YoutubeDLCookieJar(opts_cookiefile)
if os.access(opts_cookiefile, os.R_OK):
self.cookiejar.load(ignore_discard=True, ignore_expires=True)
cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
if opts_proxy is not None:
if opts_proxy == '':
proxies = {}
else:
proxies = {'http': opts_proxy, 'https': opts_proxy}
else:
proxies = compat_urllib_request.getproxies()
# Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805)
if 'http' in proxies and 'https' not in proxies:
proxies['https'] = proxies['http']
proxy_handler = PerRequestProxyHandler(proxies)
debuglevel = 1 if self.params.get('debug_printtraffic') else 0
https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
redirect_handler = YoutubeDLRedirectHandler()
data_handler = compat_urllib_request_DataHandler()
# When passing our own FileHandler instance, build_opener won't add the
file_handler = compat_urllib_request.FileHandler()
def file_open(*args, **kwargs):
raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
file_handler.file_open = file_open
opener = compat_urllib_request.build_opener(
proxy_handler, https_handler, cookie_processor, ydlh, redirect_handler, data_handler, file_handler)
# (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details)
opener.addheaders = []
self._opener = opener
def encode(self, s):
if isinstance(s, bytes):
return s # Already encoded
try:
return s.encode(self.get_encoding())
except UnicodeEncodeError as err:
err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
raise
def get_encoding(self):
encoding = self.params.get('encoding')
if encoding is None:
encoding = preferredencoding()
return encoding
def _write_thumbnails(self, info_dict, filename):
if self.params.get('writethumbnail', False):
thumbnails = info_dict.get('thumbnails')
if thumbnails:
thumbnails = [thumbnails[-1]]
elif self.params.get('write_all_thumbnails', False):
thumbnails = info_dict.get('thumbnails')
else:
return
if not thumbnails:
# No thumbnails present, so return immediately
return
for t in thumbnails:
thumb_ext = determine_ext(t['url'], 'jpg')
suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
t['filename'] = thumb_filename = replace_extension(filename + suffix, thumb_ext, info_dict.get('ext'))
if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
self.to_screen('[%s] %s: Thumbnail %sis already present' %
(info_dict['extractor'], info_dict['id'], thumb_display_id))
else:
self.to_screen('[%s] %s: Downloading thumbnail %s...' %
(info_dict['extractor'], info_dict['id'], thumb_display_id))
try:
uf = self.urlopen(t['url'])
with open(encodeFilename(thumb_filename), 'wb') as thumbf:
shutil.copyfileobj(uf, thumbf)
self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
(info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
self.report_warning('Unable to download thumbnail "%s": %s' %
(t['url'], error_to_compat_str(err)))
| true | true |
f72b941393c5f93b8853905303a2c759da17e1f7 | 9,291 | py | Python | invenio_app_ils/circulation/api.py | topless/invenio-app-ils | 38f5a6b61cdeaf5fa5776613073fa46af28737a9 | [
"MIT"
] | null | null | null | invenio_app_ils/circulation/api.py | topless/invenio-app-ils | 38f5a6b61cdeaf5fa5776613073fa46af28737a9 | [
"MIT"
] | 21 | 2018-11-02T14:19:53.000Z | 2021-06-25T15:16:42.000Z | invenio_app_ils/circulation/api.py | topless/invenio-app-ils | 38f5a6b61cdeaf5fa5776613073fa46af28737a9 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
#
# Copyright (C) 2018-2020 CERN.
#
# invenio-app-ils is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio App ILS Circulation APIs."""
import uuid
from copy import copy, deepcopy
from datetime import date, timedelta
from functools import partial
from elasticsearch import VERSION as ES_VERSION
from flask import current_app
from flask_login import current_user
from invenio_circulation.api import Loan
from invenio_circulation.config import (CIRCULATION_STATES_LOAN_ACTIVE,
CIRCULATION_STATES_LOAN_COMPLETED)
from invenio_circulation.pidstore.pids import CIRCULATION_LOAN_PID_TYPE
from invenio_circulation.proxies import current_circulation
from invenio_circulation.search.api import search_by_patron_item_or_document
from invenio_db import db
from invenio_pidstore.models import PIDStatus
from invenio_pidstore.providers.recordid_v2 import RecordIdProviderV2
from invenio_app_ils.errors import (IlsException, InvalidParameterError,
MissingRequiredParameterError,
PatronHasLoanOnDocumentError,
PatronHasLoanOnItemError,
PatronHasRequestOnDocumentError)
from invenio_app_ils.fetchers import pid_fetcher
from invenio_app_ils.items.api import Item
from invenio_app_ils.minters import pid_minter
from invenio_app_ils.proxies import current_app_ils
lt_es7 = ES_VERSION[0] < 7
# override default `invenio-circulation` minters to use the base32 PIDs
# CIRCULATION_LOAN_PID_TYPE is already defined in `invenio-circulation`
ILS_CIRCULATION_LOAN_MINTER = "ilsloanid"
ILS_CIRCULATION_LOAN_FETCHER = "ilsloanid"
IlsCirculationLoanIdProvider = type(
"IlsCirculationLoanIdProvider",
(RecordIdProviderV2,),
dict(
pid_type=CIRCULATION_LOAN_PID_TYPE, default_status=PIDStatus.REGISTERED
),
)
ils_circulation_loan_pid_minter = partial(
pid_minter, provider_cls=IlsCirculationLoanIdProvider
)
ils_circulation_loan_pid_fetcher = partial(
pid_fetcher, provider_cls=IlsCirculationLoanIdProvider
)
def _validate_delivery(delivery):
"""Validate `delivery` param."""
methods = list(
current_app.config.get("ILS_CIRCULATION_DELIVERY_METHODS", {}).keys()
)
if methods:
if not delivery or delivery["method"] not in methods:
raise MissingRequiredParameterError(
description="A valid 'delivery' is required on loan request"
)
def _set_item_to_can_circulate(item_pid):
"""Change the item status to CAN_CIRCULATE."""
item = Item.get_record_by_pid(item_pid["value"])
if item["status"] != "CAN_CIRCULATE":
item["status"] = "CAN_CIRCULATE"
item.commit()
db.session.commit()
current_app_ils.item_indexer.index(item)
def patron_has_active_loan_or_request_on_document(patron_pid, document_pid):
"""Return True if patron has an active loan/request for given document."""
states = (
current_app.config["CIRCULATION_STATES_LOAN_REQUEST"]
+ current_app.config["CIRCULATION_STATES_LOAN_ACTIVE"]
)
search = search_by_patron_item_or_document(
patron_pid=patron_pid, document_pid=document_pid, filter_states=states
)
search_result = search.execute()
return (
search_result,
search_result.hits.total > 0
if lt_es7
else search_result.hits.total.value > 0,
)
def request_loan(
document_pid,
patron_pid,
transaction_location_pid,
transaction_user_pid=None,
**kwargs
):
"""Create a new loan and trigger the first transition to PENDING."""
search_result, loan_found = patron_has_active_loan_or_request_on_document(
patron_pid, document_pid
)
if loan_found:
if (
search_result.hits[0].state
in current_app.config["CIRCULATION_STATES_LOAN_REQUEST"]
):
raise PatronHasRequestOnDocumentError(patron_pid, document_pid)
raise PatronHasLoanOnDocumentError(patron_pid, document_pid)
_validate_delivery(kwargs.get("delivery"))
transaction_user_pid = transaction_user_pid or str(current_user.id)
# create a new loan
record_uuid = uuid.uuid4()
new_loan = dict(
patron_pid=patron_pid,
transaction_location_pid=transaction_location_pid,
transaction_user_pid=transaction_user_pid,
)
pid = ils_circulation_loan_pid_minter(record_uuid, data=new_loan)
loan = Loan.create(data=new_loan, id_=record_uuid)
params = deepcopy(loan)
params.update(document_pid=document_pid, **kwargs)
# trigger the transition to request
loan = current_circulation.circulation.trigger(
loan, **dict(params, trigger="request")
)
return pid, loan
def patron_has_active_loan_on_item(patron_pid, item_pid):
"""Return True if patron has a active Loan for given item."""
search = search_by_patron_item_or_document(
patron_pid=patron_pid,
item_pid=item_pid,
filter_states=current_app.config["CIRCULATION_STATES_LOAN_ACTIVE"],
)
search_result = search.execute()
return (
search_result.hits.total > 0
if lt_es7
else search_result.hits.total.value > 0
)
def checkout_loan(
item_pid,
patron_pid,
transaction_location_pid,
transaction_user_pid=None,
force=False,
**kwargs
):
"""Create a new loan and trigger the first transition to ITEM_ON_LOAN.
:param item_pid: a dict containing `value` and `type` fields to
uniquely identify the item.
:param patron_pid: the PID value of the patron
:param transaction_location_pid: the PID value of the location where the
checkout is performed
:param transaction_user_pid: the PID value of the user that performed the
checkout
:param force: if True, ignore the current status of the item and do perform
the checkout. If False, the checkout will fail when the item cannot
circulate.
"""
if patron_has_active_loan_on_item(
patron_pid=patron_pid, item_pid=item_pid
):
raise PatronHasLoanOnItemError(patron_pid, item_pid)
optional_delivery = kwargs.get("delivery")
if optional_delivery:
_validate_delivery(optional_delivery)
if force:
_set_item_to_can_circulate(item_pid)
transaction_user_pid = transaction_user_pid or str(current_user.id)
# create a new loan
record_uuid = uuid.uuid4()
new_loan = dict(
patron_pid=patron_pid,
transaction_location_pid=transaction_location_pid,
transaction_user_pid=transaction_user_pid,
)
pid = ils_circulation_loan_pid_minter(record_uuid, data=new_loan)
loan = Loan.create(data=new_loan, id_=record_uuid)
params = deepcopy(loan)
params.update(item_pid=item_pid, **kwargs)
# trigger the transition to request
loan = current_circulation.circulation.trigger(
loan, **dict(params, trigger="checkout")
)
return pid, loan
def update_dates_loan(record, start_date=None, end_date=None, request_start_date=None, request_expire_date=None):
"""Updates the dates of a loan."""
state = record["state"]
is_active_or_completed = state in CIRCULATION_STATES_LOAN_ACTIVE \
or state in CIRCULATION_STATES_LOAN_COMPLETED
data = copy(record)
if is_active_or_completed:
today = date.today().strftime("%Y-%m-%d")
if request_start_date or request_expire_date:
raise IlsException(description="Cannot modify request dates of an active or completed loan.")
if start_date:
if start_date > today:
raise InvalidParameterError(description="Start date cannot be in the future for active loans.")
data["start_date"] = start_date
if end_date:
data["end_date"] = end_date
if data["end_date"] < data["start_date"]:
raise InvalidParameterError(description="Negative date range.")
else: # Pending or cancelled
if start_date or end_date:
raise IlsException(description="Cannot modify dates of a pending or cancelled loan.")
if request_start_date:
data["request_start_date"] = request_start_date
if request_expire_date:
data["request_expire_date"] = request_expire_date
if data["request_expire_date"] < data["request_start_date"]:
raise InvalidParameterError(description="Negative date range.")
record.update(data)
record.commit()
db.session.commit()
current_circulation.loan_indexer().index(record)
return record
def circulation_default_loan_duration_for_item(item):
"""Transform circulation restrictions to timedelta for the given item."""
value = item.get("circulation_restriction", "NO_RESTRICTION")
if value == "ONE_WEEK":
return timedelta(weeks=1)
elif value == "TWO_WEEKS":
return timedelta(weeks=2)
elif value == "THREE_WEEKS":
return timedelta(weeks=3)
elif value == "FOUR_WEEKS":
return timedelta(weeks=4)
else:
# default: NO_RESTRICTION
return timedelta(weeks=4)
| 34.66791 | 113 | 0.708966 |
import uuid
from copy import copy, deepcopy
from datetime import date, timedelta
from functools import partial
from elasticsearch import VERSION as ES_VERSION
from flask import current_app
from flask_login import current_user
from invenio_circulation.api import Loan
from invenio_circulation.config import (CIRCULATION_STATES_LOAN_ACTIVE,
CIRCULATION_STATES_LOAN_COMPLETED)
from invenio_circulation.pidstore.pids import CIRCULATION_LOAN_PID_TYPE
from invenio_circulation.proxies import current_circulation
from invenio_circulation.search.api import search_by_patron_item_or_document
from invenio_db import db
from invenio_pidstore.models import PIDStatus
from invenio_pidstore.providers.recordid_v2 import RecordIdProviderV2
from invenio_app_ils.errors import (IlsException, InvalidParameterError,
MissingRequiredParameterError,
PatronHasLoanOnDocumentError,
PatronHasLoanOnItemError,
PatronHasRequestOnDocumentError)
from invenio_app_ils.fetchers import pid_fetcher
from invenio_app_ils.items.api import Item
from invenio_app_ils.minters import pid_minter
from invenio_app_ils.proxies import current_app_ils
lt_es7 = ES_VERSION[0] < 7
ILS_CIRCULATION_LOAN_MINTER = "ilsloanid"
ILS_CIRCULATION_LOAN_FETCHER = "ilsloanid"
IlsCirculationLoanIdProvider = type(
"IlsCirculationLoanIdProvider",
(RecordIdProviderV2,),
dict(
pid_type=CIRCULATION_LOAN_PID_TYPE, default_status=PIDStatus.REGISTERED
),
)
ils_circulation_loan_pid_minter = partial(
pid_minter, provider_cls=IlsCirculationLoanIdProvider
)
ils_circulation_loan_pid_fetcher = partial(
pid_fetcher, provider_cls=IlsCirculationLoanIdProvider
)
def _validate_delivery(delivery):
methods = list(
current_app.config.get("ILS_CIRCULATION_DELIVERY_METHODS", {}).keys()
)
if methods:
if not delivery or delivery["method"] not in methods:
raise MissingRequiredParameterError(
description="A valid 'delivery' is required on loan request"
)
def _set_item_to_can_circulate(item_pid):
item = Item.get_record_by_pid(item_pid["value"])
if item["status"] != "CAN_CIRCULATE":
item["status"] = "CAN_CIRCULATE"
item.commit()
db.session.commit()
current_app_ils.item_indexer.index(item)
def patron_has_active_loan_or_request_on_document(patron_pid, document_pid):
states = (
current_app.config["CIRCULATION_STATES_LOAN_REQUEST"]
+ current_app.config["CIRCULATION_STATES_LOAN_ACTIVE"]
)
search = search_by_patron_item_or_document(
patron_pid=patron_pid, document_pid=document_pid, filter_states=states
)
search_result = search.execute()
return (
search_result,
search_result.hits.total > 0
if lt_es7
else search_result.hits.total.value > 0,
)
def request_loan(
document_pid,
patron_pid,
transaction_location_pid,
transaction_user_pid=None,
**kwargs
):
search_result, loan_found = patron_has_active_loan_or_request_on_document(
patron_pid, document_pid
)
if loan_found:
if (
search_result.hits[0].state
in current_app.config["CIRCULATION_STATES_LOAN_REQUEST"]
):
raise PatronHasRequestOnDocumentError(patron_pid, document_pid)
raise PatronHasLoanOnDocumentError(patron_pid, document_pid)
_validate_delivery(kwargs.get("delivery"))
transaction_user_pid = transaction_user_pid or str(current_user.id)
record_uuid = uuid.uuid4()
new_loan = dict(
patron_pid=patron_pid,
transaction_location_pid=transaction_location_pid,
transaction_user_pid=transaction_user_pid,
)
pid = ils_circulation_loan_pid_minter(record_uuid, data=new_loan)
loan = Loan.create(data=new_loan, id_=record_uuid)
params = deepcopy(loan)
params.update(document_pid=document_pid, **kwargs)
loan = current_circulation.circulation.trigger(
loan, **dict(params, trigger="request")
)
return pid, loan
def patron_has_active_loan_on_item(patron_pid, item_pid):
search = search_by_patron_item_or_document(
patron_pid=patron_pid,
item_pid=item_pid,
filter_states=current_app.config["CIRCULATION_STATES_LOAN_ACTIVE"],
)
search_result = search.execute()
return (
search_result.hits.total > 0
if lt_es7
else search_result.hits.total.value > 0
)
def checkout_loan(
item_pid,
patron_pid,
transaction_location_pid,
transaction_user_pid=None,
force=False,
**kwargs
):
if patron_has_active_loan_on_item(
patron_pid=patron_pid, item_pid=item_pid
):
raise PatronHasLoanOnItemError(patron_pid, item_pid)
optional_delivery = kwargs.get("delivery")
if optional_delivery:
_validate_delivery(optional_delivery)
if force:
_set_item_to_can_circulate(item_pid)
transaction_user_pid = transaction_user_pid or str(current_user.id)
record_uuid = uuid.uuid4()
new_loan = dict(
patron_pid=patron_pid,
transaction_location_pid=transaction_location_pid,
transaction_user_pid=transaction_user_pid,
)
pid = ils_circulation_loan_pid_minter(record_uuid, data=new_loan)
loan = Loan.create(data=new_loan, id_=record_uuid)
params = deepcopy(loan)
params.update(item_pid=item_pid, **kwargs)
loan = current_circulation.circulation.trigger(
loan, **dict(params, trigger="checkout")
)
return pid, loan
def update_dates_loan(record, start_date=None, end_date=None, request_start_date=None, request_expire_date=None):
state = record["state"]
is_active_or_completed = state in CIRCULATION_STATES_LOAN_ACTIVE \
or state in CIRCULATION_STATES_LOAN_COMPLETED
data = copy(record)
if is_active_or_completed:
today = date.today().strftime("%Y-%m-%d")
if request_start_date or request_expire_date:
raise IlsException(description="Cannot modify request dates of an active or completed loan.")
if start_date:
if start_date > today:
raise InvalidParameterError(description="Start date cannot be in the future for active loans.")
data["start_date"] = start_date
if end_date:
data["end_date"] = end_date
if data["end_date"] < data["start_date"]:
raise InvalidParameterError(description="Negative date range.")
else:
if start_date or end_date:
raise IlsException(description="Cannot modify dates of a pending or cancelled loan.")
if request_start_date:
data["request_start_date"] = request_start_date
if request_expire_date:
data["request_expire_date"] = request_expire_date
if data["request_expire_date"] < data["request_start_date"]:
raise InvalidParameterError(description="Negative date range.")
record.update(data)
record.commit()
db.session.commit()
current_circulation.loan_indexer().index(record)
return record
def circulation_default_loan_duration_for_item(item):
value = item.get("circulation_restriction", "NO_RESTRICTION")
if value == "ONE_WEEK":
return timedelta(weeks=1)
elif value == "TWO_WEEKS":
return timedelta(weeks=2)
elif value == "THREE_WEEKS":
return timedelta(weeks=3)
elif value == "FOUR_WEEKS":
return timedelta(weeks=4)
else:
return timedelta(weeks=4)
| true | true |
f72b9483d7b40b72fb27e1e57c80b24dc691d800 | 6,368 | py | Python | tests/functional/testplan/testing/test_tagging.py | raoyitao/testplan | aae3e9cee597ca3d01b6d64eed2642c421c56cbb | [
"Apache-2.0"
] | 96 | 2018-03-14T13:14:50.000Z | 2021-01-14T08:26:08.000Z | tests/functional/testplan/testing/test_tagging.py | raoyitao/testplan | aae3e9cee597ca3d01b6d64eed2642c421c56cbb | [
"Apache-2.0"
] | 135 | 2018-06-28T02:41:05.000Z | 2021-01-19T02:16:58.000Z | tests/functional/testplan/testing/test_tagging.py | raoyitao/testplan | aae3e9cee597ca3d01b6d64eed2642c421c56cbb | [
"Apache-2.0"
] | 53 | 2018-03-17T14:39:15.000Z | 2021-01-21T10:54:13.000Z | import pytest
from testplan.common.utils.testing import check_report
from testplan.report import TestReport, TestGroupReport, TestCaseReport
from testplan.testing.multitest import MultiTest, testsuite, testcase
@testsuite(tags={"color": ["red", "blue"]})
class AlphaSuite(object):
@testcase
def test_method_0(self, env, result):
pass
@testcase(tags=("foo", "bar"))
def test_method_1(self, env, result):
pass
@testcase(tags={"color": "green"})
def test_method_2(self, env, result):
pass
@testsuite(tags={"color": "yellow"})
class BetaSuite(object):
@testcase
def test_method_0(self, env, result):
pass
@testcase(tags="foo")
def test_method_1(self, env, result):
pass
@testcase(tags={"color": "red"})
def test_method_2(self, env, result):
pass
@testsuite
class GammaSuite(object):
@testcase
def test_method_0(self, env, result):
pass
@testcase(
parameters=("AAA", "BBB"),
tag_func=lambda kwargs: {"symbol": kwargs["value"].lower()},
tags={"speed": "slow"},
)
def test_param(self, env, result, value):
pass
@testcase(parameters=("XXX", "YYY"), tags={"speed": "fast"})
def test_param_2(self, env, result, value):
pass
report_for_multitest_without_tags = TestGroupReport(
name="MyMultitest",
category="multitest",
entries=[
TestGroupReport(
name="AlphaSuite",
category="testsuite",
tags={"color": {"red", "blue"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(
name="test_method_1", tags={"simple": {"foo", "bar"}}
),
TestCaseReport(
name="test_method_2", tags={"color": {"green"}}
),
],
),
TestGroupReport(
name="BetaSuite",
category="testsuite",
tags={"color": {"yellow"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(name="test_method_1", tags={"simple": {"foo"}}),
TestCaseReport(name="test_method_2", tags={"color": {"red"}}),
],
),
TestGroupReport(
name="GammaSuite",
category="testsuite",
entries=[
TestCaseReport(name="test_method_0"),
TestGroupReport(
name="test_param",
category="parametrization",
tags={"speed": {"slow"}},
entries=[
TestCaseReport(
name="test_param <value='AAA'>",
tags={"symbol": {"aaa"}},
),
TestCaseReport(
name="test_param <value='BBB'>",
tags={"symbol": {"bbb"}},
),
],
),
TestGroupReport(
name="test_param_2",
category="parametrization",
tags={"speed": {"fast"}},
entries=[
TestCaseReport(name="test_param_2 <value='XXX'>"),
TestCaseReport(name="test_param_2 <value='YYY'>"),
],
),
],
),
],
)
report_for_multitest_with_tags = TestGroupReport(
name="MyMultitest",
category="multitest",
tags={"color": {"orange"}, "environment": {"server"}},
entries=[
TestGroupReport(
name="AlphaSuite",
category="testsuite",
tags={"color": {"red", "blue"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(
name="test_method_1", tags={"simple": {"foo", "bar"}}
),
TestCaseReport(
name="test_method_2", tags={"color": {"green"}}
),
],
),
TestGroupReport(
name="BetaSuite",
category="testsuite",
tags={"color": {"yellow"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(name="test_method_1", tags={"simple": {"foo"}}),
TestCaseReport(name="test_method_2", tags={"color": {"red"}}),
],
),
TestGroupReport(
name="GammaSuite",
category="testsuite",
entries=[
TestCaseReport(name="test_method_0"),
TestGroupReport(
name="test_param",
category="parametrization",
tags={"speed": {"slow"}},
entries=[
TestCaseReport(
name="test_param <value='AAA'>",
tags={"symbol": {"aaa"}},
),
TestCaseReport(
name="test_param <value='BBB'>",
tags={"symbol": {"bbb"}},
),
],
),
TestGroupReport(
name="test_param_2",
category="parametrization",
tags={"speed": {"fast"}},
entries=[
TestCaseReport(name="test_param_2 <value='XXX'>"),
TestCaseReport(name="test_param_2 <value='YYY'>"),
],
),
],
),
],
)
@pytest.mark.parametrize(
"multitest_tags,expected_report",
(
({}, report_for_multitest_without_tags),
(
{"color": "orange", "environment": "server"},
report_for_multitest_with_tags,
),
),
)
def test_multitest_tagging(mockplan, multitest_tags, expected_report):
multitest = MultiTest(
name="MyMultitest",
suites=[AlphaSuite(), BetaSuite(), GammaSuite()],
tags=multitest_tags,
)
mockplan.add(multitest)
mockplan.run()
check_report(
expected=TestReport(name="plan", entries=[expected_report]),
actual=mockplan.report,
)
| 30.4689 | 79 | 0.468907 | import pytest
from testplan.common.utils.testing import check_report
from testplan.report import TestReport, TestGroupReport, TestCaseReport
from testplan.testing.multitest import MultiTest, testsuite, testcase
@testsuite(tags={"color": ["red", "blue"]})
class AlphaSuite(object):
@testcase
def test_method_0(self, env, result):
pass
@testcase(tags=("foo", "bar"))
def test_method_1(self, env, result):
pass
@testcase(tags={"color": "green"})
def test_method_2(self, env, result):
pass
@testsuite(tags={"color": "yellow"})
class BetaSuite(object):
@testcase
def test_method_0(self, env, result):
pass
@testcase(tags="foo")
def test_method_1(self, env, result):
pass
@testcase(tags={"color": "red"})
def test_method_2(self, env, result):
pass
@testsuite
class GammaSuite(object):
@testcase
def test_method_0(self, env, result):
pass
@testcase(
parameters=("AAA", "BBB"),
tag_func=lambda kwargs: {"symbol": kwargs["value"].lower()},
tags={"speed": "slow"},
)
def test_param(self, env, result, value):
pass
@testcase(parameters=("XXX", "YYY"), tags={"speed": "fast"})
def test_param_2(self, env, result, value):
pass
report_for_multitest_without_tags = TestGroupReport(
name="MyMultitest",
category="multitest",
entries=[
TestGroupReport(
name="AlphaSuite",
category="testsuite",
tags={"color": {"red", "blue"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(
name="test_method_1", tags={"simple": {"foo", "bar"}}
),
TestCaseReport(
name="test_method_2", tags={"color": {"green"}}
),
],
),
TestGroupReport(
name="BetaSuite",
category="testsuite",
tags={"color": {"yellow"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(name="test_method_1", tags={"simple": {"foo"}}),
TestCaseReport(name="test_method_2", tags={"color": {"red"}}),
],
),
TestGroupReport(
name="GammaSuite",
category="testsuite",
entries=[
TestCaseReport(name="test_method_0"),
TestGroupReport(
name="test_param",
category="parametrization",
tags={"speed": {"slow"}},
entries=[
TestCaseReport(
name="test_param <value='AAA'>",
tags={"symbol": {"aaa"}},
),
TestCaseReport(
name="test_param <value='BBB'>",
tags={"symbol": {"bbb"}},
),
],
),
TestGroupReport(
name="test_param_2",
category="parametrization",
tags={"speed": {"fast"}},
entries=[
TestCaseReport(name="test_param_2 <value='XXX'>"),
TestCaseReport(name="test_param_2 <value='YYY'>"),
],
),
],
),
],
)
report_for_multitest_with_tags = TestGroupReport(
name="MyMultitest",
category="multitest",
tags={"color": {"orange"}, "environment": {"server"}},
entries=[
TestGroupReport(
name="AlphaSuite",
category="testsuite",
tags={"color": {"red", "blue"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(
name="test_method_1", tags={"simple": {"foo", "bar"}}
),
TestCaseReport(
name="test_method_2", tags={"color": {"green"}}
),
],
),
TestGroupReport(
name="BetaSuite",
category="testsuite",
tags={"color": {"yellow"}},
entries=[
TestCaseReport(name="test_method_0"),
TestCaseReport(name="test_method_1", tags={"simple": {"foo"}}),
TestCaseReport(name="test_method_2", tags={"color": {"red"}}),
],
),
TestGroupReport(
name="GammaSuite",
category="testsuite",
entries=[
TestCaseReport(name="test_method_0"),
TestGroupReport(
name="test_param",
category="parametrization",
tags={"speed": {"slow"}},
entries=[
TestCaseReport(
name="test_param <value='AAA'>",
tags={"symbol": {"aaa"}},
),
TestCaseReport(
name="test_param <value='BBB'>",
tags={"symbol": {"bbb"}},
),
],
),
TestGroupReport(
name="test_param_2",
category="parametrization",
tags={"speed": {"fast"}},
entries=[
TestCaseReport(name="test_param_2 <value='XXX'>"),
TestCaseReport(name="test_param_2 <value='YYY'>"),
],
),
],
),
],
)
@pytest.mark.parametrize(
"multitest_tags,expected_report",
(
({}, report_for_multitest_without_tags),
(
{"color": "orange", "environment": "server"},
report_for_multitest_with_tags,
),
),
)
def test_multitest_tagging(mockplan, multitest_tags, expected_report):
multitest = MultiTest(
name="MyMultitest",
suites=[AlphaSuite(), BetaSuite(), GammaSuite()],
tags=multitest_tags,
)
mockplan.add(multitest)
mockplan.run()
check_report(
expected=TestReport(name="plan", entries=[expected_report]),
actual=mockplan.report,
)
| true | true |
f72b94a2fc75245f4a10ca168ed20ceaddbee478 | 12,107 | py | Python | test/functional/mining_basic.py | onixcoin-io/onix | 37c158a6229fa98c1a86f8b65e91226e36355fd6 | [
"MIT"
] | 6 | 2021-10-31T04:53:09.000Z | 2021-12-16T08:27:06.000Z | test/functional/mining_basic.py | onixcoin-io/onix | 37c158a6229fa98c1a86f8b65e91226e36355fd6 | [
"MIT"
] | 1 | 2021-11-29T08:45:38.000Z | 2021-11-29T08:45:38.000Z | test/functional/mining_basic.py | onixcoin-io/onix | 37c158a6229fa98c1a86f8b65e91226e36355fd6 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2014-2019 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 mining RPCs
- getmininginfo
- getblocktemplate proposal mode
- submitblock"""
import copy
from decimal import Decimal
from test_framework.blocktools import (
create_coinbase,
TIME_GENESIS_BLOCK,
)
from test_framework.messages import (
CBlock,
CBlockHeader
)
from test_framework.mininode import (
P2PDataStore,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
connect_nodes,
)
from test_framework.script import CScriptNum
BLOCK_HEADER_SIZE = len(CBlockHeader().serialize())
def assert_template(node, block, expect, rehash=True):
if rehash:
block.hashMerkleRoot = block.calc_merkle_root()
rsp = node.getblocktemplate(template_request={'data': block.serialize().hex(), 'mode': 'proposal', 'rules': ['segwit']})
assert_equal(rsp, expect)
class MiningTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.supports_cli = False
def mine_chain(self):
self.log.info('Create some old blocks')
for t in range(TIME_GENESIS_BLOCK, TIME_GENESIS_BLOCK + 600 * 600, 600):
self.nodes[0].setmocktime(t)
self.nodes[0].generate(1)
mining_info = self.nodes[0].getmininginfo()
assert_equal(mining_info['blocks'], 600)
assert_equal(mining_info['currentblocktx'], 0)
assert_equal(mining_info['currentblockweight'], 4000)
self.restart_node(0)
connect_nodes(self.nodes[0], 1)
def run_test(self):
self.mine_chain()
node = self.nodes[0]
def assert_submitblock(block, result_str_1, result_str_2=None):
block.solve()
result_str_2 = result_str_2 or 'duplicate-invalid'
assert_equal(result_str_1, node.submitblock(hexdata=block.serialize().hex()))
assert_equal(result_str_2, node.submitblock(hexdata=block.serialize().hex()))
self.log.info('getmininginfo')
mining_info = node.getmininginfo()
assert_equal(mining_info['blocks'], 600)
assert_equal(mining_info['chain'], self.chain)
assert 'currentblocktx' not in mining_info
assert 'currentblockweight' not in mining_info
assert_equal(mining_info['difficulty']['proof-of-work'], Decimal('4.656542373906925E-10'))
assert_equal(mining_info['networkhashps'], Decimal('0.003333333333333334'))
assert_equal(mining_info['pooledtx'], 0)
# Mine a block to leave initial block download
node.generatetoaddress(1, node.get_deterministic_priv_key().address)
tmpl = node.getblocktemplate({'rules': ['segwit']})
self.log.info("getblocktemplate: Test capability advertised")
assert 'proposal' in tmpl['capabilities']
assert 'coinbasetxn' not in tmpl
coinbase_tx = create_coinbase(height=int(tmpl["height"]))
# sequence numbers must not be max for nLockTime to have effect
coinbase_tx.vin[0].nSequence = 2 ** 32 - 2
coinbase_tx.rehash()
# round-trip the encoded bip34 block height commitment
assert_equal(CScriptNum.decode(coinbase_tx.vin[0].scriptSig), 602)
# round-trip negative and multi-byte CScriptNums to catch python regression
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(1500))), 1500)
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(-1500))), -1500)
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(-1))), -1)
block = CBlock()
block.nVersion = tmpl["version"]
block.hashPrevBlock = int(tmpl["previousblockhash"], 16)
block.nTime = tmpl["curtime"]
block.nBits = int(tmpl["bits"], 16)
block.nNonce = 0
block.vtx = [coinbase_tx]
self.log.info("getblocktemplate: segwit rule must be set")
assert_raises_rpc_error(-8, "getblocktemplate must be called with the segwit rule set", node.getblocktemplate)
self.log.info("getblocktemplate: Test valid block")
assert_template(node, block, None)
self.log.info("submitblock: Test block decode failure")
assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, block.serialize()[:-15].hex())
self.log.info("getblocktemplate: Test bad input hash for coinbase transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx[0].vin[0].prevout.hash += 1
bad_block.vtx[0].rehash()
assert_template(node, bad_block, 'bad-cb-missing')
self.log.info("submitblock: Test invalid coinbase transaction")
assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, bad_block.serialize().hex())
self.log.info("getblocktemplate: Test truncated final transaction")
assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': block.serialize()[:-1].hex(), 'mode': 'proposal', 'rules': ['segwit']})
self.log.info("getblocktemplate: Test duplicate transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx.append(bad_block.vtx[0])
assert_template(node, bad_block, 'bad-txns-duplicate')
assert_submitblock(bad_block, 'bad-txns-duplicate', 'bad-txns-duplicate')
self.log.info("getblocktemplate: Test invalid transaction")
bad_block = copy.deepcopy(block)
bad_tx = copy.deepcopy(bad_block.vtx[0])
bad_tx.vin[0].prevout.hash = 255
bad_tx.rehash()
bad_block.vtx.append(bad_tx)
assert_template(node, bad_block, 'bad-txns-inputs-missingorspent')
assert_submitblock(bad_block, 'bad-txns-inputs-missingorspent')
self.log.info("getblocktemplate: Test nonfinal transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx[0].nLockTime = 2 ** 32 - 1
bad_block.vtx[0].rehash()
assert_template(node, bad_block, 'bad-txns-nonfinal')
assert_submitblock(bad_block, 'bad-txns-nonfinal')
self.log.info("getblocktemplate: Test bad tx count")
# The tx count is immediately after the block header
TX_COUNT_OFFSET = 181
bad_block_sn = bytearray(block.serialize())
assert_equal(bad_block_sn[BLOCK_HEADER_SIZE], 1)
bad_block_sn[BLOCK_HEADER_SIZE] += 1
assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': bad_block_sn.hex(), 'mode': 'proposal', 'rules': ['segwit']})
self.log.info("getblocktemplate: Test bad bits")
bad_block = copy.deepcopy(block)
bad_block.nBits = 469762303 # impossible in the real world
assert_template(node, bad_block, 'bad-diffbits')
self.log.info("getblocktemplate: Test bad merkle root")
bad_block = copy.deepcopy(block)
bad_block.hashMerkleRoot += 1
assert_template(node, bad_block, 'bad-txnmrklroot', False)
assert_submitblock(bad_block, 'bad-txnmrklroot', 'bad-txnmrklroot')
#self.log.info("getblocktemplate: Test bad timestamps")
#bad_block = copy.deepcopy(block)
#bad_block.nTime = 2 ** 31 - 1
#assert_template(node, bad_block, 'time-too-new')
#assert_submitblock(bad_block, 'time-too-new', 'time-too-new')
#bad_block.nTime = 0
#assert_template(node, bad_block, 'time-too-old')
#assert_submitblock(bad_block, 'time-too-old', 'time-too-old')
self.log.info("getblocktemplate: Test not best block")
bad_block = copy.deepcopy(block)
bad_block.hashPrevBlock = 123
assert_template(node, bad_block, 'inconclusive-not-best-prevblk')
assert_submitblock(bad_block, 'prev-blk-not-found', 'prev-blk-not-found')
self.log.info('submitheader tests')
assert_raises_rpc_error(-22, 'Block header decode failed', lambda: node.submitheader(hexdata='xx' * BLOCK_HEADER_SIZE))
assert_raises_rpc_error(-22, 'Block header decode failed', lambda: node.submitheader(hexdata='ff' * (BLOCK_HEADER_SIZE-2)))
assert_raises_rpc_error(-25, 'Must submit previous header', lambda: node.submitheader(hexdata=super(CBlock, bad_block).serialize().hex()))
block.nTime += 1
block.solve()
def chain_tip(b_hash, *, status='headers-only', branchlen=1):
return {'hash': b_hash, 'height': 602, 'branchlen': branchlen, 'status': status}
assert chain_tip(block.hash) not in node.getchaintips()
node.submitheader(hexdata=block.serialize().hex())
assert chain_tip(block.hash) in node.getchaintips()
node.submitheader(hexdata=CBlockHeader(block).serialize().hex()) # Noop
assert chain_tip(block.hash) in node.getchaintips()
bad_block_root = copy.deepcopy(block)
bad_block_root.hashMerkleRoot += 2
bad_block_root.solve()
assert chain_tip(bad_block_root.hash) not in node.getchaintips()
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert chain_tip(bad_block_root.hash) in node.getchaintips()
# Should still reject invalid blocks, even if we have the header:
assert_equal(node.submitblock(hexdata=bad_block_root.serialize().hex()), 'bad-txnmrklroot')
assert_equal(node.submitblock(hexdata=bad_block_root.serialize().hex()), 'bad-txnmrklroot')
assert chain_tip(bad_block_root.hash) in node.getchaintips()
# We know the header for this invalid block, so should just return early without error:
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert chain_tip(bad_block_root.hash) in node.getchaintips()
bad_block_lock = copy.deepcopy(block)
bad_block_lock.vtx[0].nLockTime = 2**32 - 1
bad_block_lock.vtx[0].rehash()
bad_block_lock.hashMerkleRoot = bad_block_lock.calc_merkle_root()
bad_block_lock.solve()
assert_equal(node.submitblock(hexdata=bad_block_lock.serialize().hex()), 'bad-txns-nonfinal')
assert_equal(node.submitblock(hexdata=bad_block_lock.serialize().hex()), 'duplicate-invalid')
# Build a "good" block on top of the submitted bad block
bad_block2 = copy.deepcopy(block)
bad_block2.hashPrevBlock = bad_block_lock.sha256
bad_block2.solve()
assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex()))
# Should reject invalid header right away, only applies to PoS blocks in onix.
#bad_block_time = copy.deepcopy(block)
#bad_block_time.nTime = 1
#bad_block_time.solve()
#assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader(hexdata=CBlockHeader(bad_block_time).serialize().hex()))
# Should ask for the block from a p2p node, if they announce the header as well:
node.add_p2p_connection(P2PDataStore())
node.p2p.wait_for_getheaders(timeout=5) # Drop the first getheaders
node.p2p.send_blocks_and_test(blocks=[block], node=node)
# Must be active now:
assert chain_tip(block.hash, status='active', branchlen=0) in node.getchaintips()
# Building a few blocks should give the same results
node.generatetoaddress(10, node.get_deterministic_priv_key().address)
#assert_raises_rpc_error(-25, 'time-too-old', lambda: node.submitheader(hexdata=CBlockHeader(bad_block_time).serialize().hex()))
assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex()))
node.submitheader(hexdata=CBlockHeader(block).serialize().hex())
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert_equal(node.submitblock(hexdata=block.serialize().hex()), 'duplicate') # valid
if __name__ == '__main__':
MiningTest().main()
| 48.043651 | 163 | 0.690262 |
import copy
from decimal import Decimal
from test_framework.blocktools import (
create_coinbase,
TIME_GENESIS_BLOCK,
)
from test_framework.messages import (
CBlock,
CBlockHeader
)
from test_framework.mininode import (
P2PDataStore,
)
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
connect_nodes,
)
from test_framework.script import CScriptNum
BLOCK_HEADER_SIZE = len(CBlockHeader().serialize())
def assert_template(node, block, expect, rehash=True):
if rehash:
block.hashMerkleRoot = block.calc_merkle_root()
rsp = node.getblocktemplate(template_request={'data': block.serialize().hex(), 'mode': 'proposal', 'rules': ['segwit']})
assert_equal(rsp, expect)
class MiningTest(BitcoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = True
self.supports_cli = False
def mine_chain(self):
self.log.info('Create some old blocks')
for t in range(TIME_GENESIS_BLOCK, TIME_GENESIS_BLOCK + 600 * 600, 600):
self.nodes[0].setmocktime(t)
self.nodes[0].generate(1)
mining_info = self.nodes[0].getmininginfo()
assert_equal(mining_info['blocks'], 600)
assert_equal(mining_info['currentblocktx'], 0)
assert_equal(mining_info['currentblockweight'], 4000)
self.restart_node(0)
connect_nodes(self.nodes[0], 1)
def run_test(self):
self.mine_chain()
node = self.nodes[0]
def assert_submitblock(block, result_str_1, result_str_2=None):
block.solve()
result_str_2 = result_str_2 or 'duplicate-invalid'
assert_equal(result_str_1, node.submitblock(hexdata=block.serialize().hex()))
assert_equal(result_str_2, node.submitblock(hexdata=block.serialize().hex()))
self.log.info('getmininginfo')
mining_info = node.getmininginfo()
assert_equal(mining_info['blocks'], 600)
assert_equal(mining_info['chain'], self.chain)
assert 'currentblocktx' not in mining_info
assert 'currentblockweight' not in mining_info
assert_equal(mining_info['difficulty']['proof-of-work'], Decimal('4.656542373906925E-10'))
assert_equal(mining_info['networkhashps'], Decimal('0.003333333333333334'))
assert_equal(mining_info['pooledtx'], 0)
node.generatetoaddress(1, node.get_deterministic_priv_key().address)
tmpl = node.getblocktemplate({'rules': ['segwit']})
self.log.info("getblocktemplate: Test capability advertised")
assert 'proposal' in tmpl['capabilities']
assert 'coinbasetxn' not in tmpl
coinbase_tx = create_coinbase(height=int(tmpl["height"]))
coinbase_tx.vin[0].nSequence = 2 ** 32 - 2
coinbase_tx.rehash()
assert_equal(CScriptNum.decode(coinbase_tx.vin[0].scriptSig), 602)
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(1500))), 1500)
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(-1500))), -1500)
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(-1))), -1)
block = CBlock()
block.nVersion = tmpl["version"]
block.hashPrevBlock = int(tmpl["previousblockhash"], 16)
block.nTime = tmpl["curtime"]
block.nBits = int(tmpl["bits"], 16)
block.nNonce = 0
block.vtx = [coinbase_tx]
self.log.info("getblocktemplate: segwit rule must be set")
assert_raises_rpc_error(-8, "getblocktemplate must be called with the segwit rule set", node.getblocktemplate)
self.log.info("getblocktemplate: Test valid block")
assert_template(node, block, None)
self.log.info("submitblock: Test block decode failure")
assert_raises_rpc_error(-22, "Block decode failed", node.submitblock, block.serialize()[:-15].hex())
self.log.info("getblocktemplate: Test bad input hash for coinbase transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx[0].vin[0].prevout.hash += 1
bad_block.vtx[0].rehash()
assert_template(node, bad_block, 'bad-cb-missing')
self.log.info("submitblock: Test invalid coinbase transaction")
assert_raises_rpc_error(-22, "Block does not start with a coinbase", node.submitblock, bad_block.serialize().hex())
self.log.info("getblocktemplate: Test truncated final transaction")
assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': block.serialize()[:-1].hex(), 'mode': 'proposal', 'rules': ['segwit']})
self.log.info("getblocktemplate: Test duplicate transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx.append(bad_block.vtx[0])
assert_template(node, bad_block, 'bad-txns-duplicate')
assert_submitblock(bad_block, 'bad-txns-duplicate', 'bad-txns-duplicate')
self.log.info("getblocktemplate: Test invalid transaction")
bad_block = copy.deepcopy(block)
bad_tx = copy.deepcopy(bad_block.vtx[0])
bad_tx.vin[0].prevout.hash = 255
bad_tx.rehash()
bad_block.vtx.append(bad_tx)
assert_template(node, bad_block, 'bad-txns-inputs-missingorspent')
assert_submitblock(bad_block, 'bad-txns-inputs-missingorspent')
self.log.info("getblocktemplate: Test nonfinal transaction")
bad_block = copy.deepcopy(block)
bad_block.vtx[0].nLockTime = 2 ** 32 - 1
bad_block.vtx[0].rehash()
assert_template(node, bad_block, 'bad-txns-nonfinal')
assert_submitblock(bad_block, 'bad-txns-nonfinal')
self.log.info("getblocktemplate: Test bad tx count")
TX_COUNT_OFFSET = 181
bad_block_sn = bytearray(block.serialize())
assert_equal(bad_block_sn[BLOCK_HEADER_SIZE], 1)
bad_block_sn[BLOCK_HEADER_SIZE] += 1
assert_raises_rpc_error(-22, "Block decode failed", node.getblocktemplate, {'data': bad_block_sn.hex(), 'mode': 'proposal', 'rules': ['segwit']})
self.log.info("getblocktemplate: Test bad bits")
bad_block = copy.deepcopy(block)
bad_block.nBits = 469762303
assert_template(node, bad_block, 'bad-diffbits')
self.log.info("getblocktemplate: Test bad merkle root")
bad_block = copy.deepcopy(block)
bad_block.hashMerkleRoot += 1
assert_template(node, bad_block, 'bad-txnmrklroot', False)
assert_submitblock(bad_block, 'bad-txnmrklroot', 'bad-txnmrklroot')
self.log.info("getblocktemplate: Test not best block")
bad_block = copy.deepcopy(block)
bad_block.hashPrevBlock = 123
assert_template(node, bad_block, 'inconclusive-not-best-prevblk')
assert_submitblock(bad_block, 'prev-blk-not-found', 'prev-blk-not-found')
self.log.info('submitheader tests')
assert_raises_rpc_error(-22, 'Block header decode failed', lambda: node.submitheader(hexdata='xx' * BLOCK_HEADER_SIZE))
assert_raises_rpc_error(-22, 'Block header decode failed', lambda: node.submitheader(hexdata='ff' * (BLOCK_HEADER_SIZE-2)))
assert_raises_rpc_error(-25, 'Must submit previous header', lambda: node.submitheader(hexdata=super(CBlock, bad_block).serialize().hex()))
block.nTime += 1
block.solve()
def chain_tip(b_hash, *, status='headers-only', branchlen=1):
return {'hash': b_hash, 'height': 602, 'branchlen': branchlen, 'status': status}
assert chain_tip(block.hash) not in node.getchaintips()
node.submitheader(hexdata=block.serialize().hex())
assert chain_tip(block.hash) in node.getchaintips()
node.submitheader(hexdata=CBlockHeader(block).serialize().hex())
assert chain_tip(block.hash) in node.getchaintips()
bad_block_root = copy.deepcopy(block)
bad_block_root.hashMerkleRoot += 2
bad_block_root.solve()
assert chain_tip(bad_block_root.hash) not in node.getchaintips()
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert chain_tip(bad_block_root.hash) in node.getchaintips()
assert_equal(node.submitblock(hexdata=bad_block_root.serialize().hex()), 'bad-txnmrklroot')
assert_equal(node.submitblock(hexdata=bad_block_root.serialize().hex()), 'bad-txnmrklroot')
assert chain_tip(bad_block_root.hash) in node.getchaintips()
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert chain_tip(bad_block_root.hash) in node.getchaintips()
bad_block_lock = copy.deepcopy(block)
bad_block_lock.vtx[0].nLockTime = 2**32 - 1
bad_block_lock.vtx[0].rehash()
bad_block_lock.hashMerkleRoot = bad_block_lock.calc_merkle_root()
bad_block_lock.solve()
assert_equal(node.submitblock(hexdata=bad_block_lock.serialize().hex()), 'bad-txns-nonfinal')
assert_equal(node.submitblock(hexdata=bad_block_lock.serialize().hex()), 'duplicate-invalid')
bad_block2 = copy.deepcopy(block)
bad_block2.hashPrevBlock = bad_block_lock.sha256
bad_block2.solve()
assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex()))
node.add_p2p_connection(P2PDataStore())
node.p2p.wait_for_getheaders(timeout=5)
node.p2p.send_blocks_and_test(blocks=[block], node=node)
assert chain_tip(block.hash, status='active', branchlen=0) in node.getchaintips()
node.generatetoaddress(10, node.get_deterministic_priv_key().address)
assert_raises_rpc_error(-25, 'bad-prevblk', lambda: node.submitheader(hexdata=CBlockHeader(bad_block2).serialize().hex()))
node.submitheader(hexdata=CBlockHeader(block).serialize().hex())
node.submitheader(hexdata=CBlockHeader(bad_block_root).serialize().hex())
assert_equal(node.submitblock(hexdata=block.serialize().hex()), 'duplicate')
if __name__ == '__main__':
MiningTest().main()
| true | true |
f72b9664774aac869ec7bb4e09b59f25f377508a | 3,245 | py | Python | twikoto3/mainwindow.py | azyobuzin/twikoto3 | 8a4efc4ff7280a559f448234cbc3a0bc740e8388 | [
"Apache-2.0"
] | 1 | 2017-12-27T09:50:47.000Z | 2017-12-27T09:50:47.000Z | twikoto3/mainwindow.py | azyobuzin/twikoto3 | 8a4efc4ff7280a559f448234cbc3a0bc740e8388 | [
"Apache-2.0"
] | null | null | null | twikoto3/mainwindow.py | azyobuzin/twikoto3 | 8a4efc4ff7280a559f448234cbc3a0bc740e8388 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""
twikoto3 - Twitter Client
Copyright (C) 2012 azyobuzin
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from PyQt4 import QtCore, QtGui
import twikoto3
from twikoto3.extension import *
from twikoto3.twittertext import validator
class TweetTextEdit(QtGui.QTextEdit):
def __init__(self, parent = None):
super(TweetTextEdit, self).__init__(parent)
self.tweetaction = None
def keyPressEvent(self, e):
if e.key() == QtCore.Qt.Key_Return and (e.modifiers() and QtCore.Qt.ControlModifier):
self.tweetaction()
else:
super(TweetTextEdit, self).keyPressEvent(e)
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle("ついこと 3")
self.layout = QtGui.QVBoxLayout()
self.textedit_tweet = TweetTextEdit()
self.textedit_tweet.setMinimumHeight(46)
self.textedit_tweet.textChanged.connect(self.textedit_tweet_textChanged)
self.textedit_tweet.tweetaction = self.button_tweet_clicked
self.layout.addWidget(self.textedit_tweet)
self.layout_tweetbutton = QtGui.QHBoxLayout()
self.layout.addLayout(self.layout_tweetbutton)
self.label_textcount = QtGui.QLabel("140")
self.layout_tweetbutton.addWidget(self.label_textcount)
self.button_tweet = QtGui.QPushButton("Tweet")
self.button_tweet.clicked.connect(self.button_tweet_clicked)
self.layout_tweetbutton.addWidget(self.button_tweet)
self.centralWidget = QtGui.QWidget()
self.centralWidget.setLayout(self.layout)
self.setCentralWidget(self.centralWidget)
def button_tweet_clicked(self):
status = self.textedit_tweet.toPlainText()
if status | noneoremptystr():
return
self.button_tweet.setEnabled(False)
thread = twikoto3.twitter.updatestatus(status)
def finished():
self.button_tweet.setEnabled(True)
if thread.response is not None:
self.textedit_tweet.setPlainText("")
else:
QtGui.QMessageBox.critical(self, "投稿失敗", str(thread.exception))
thread.finished.connect(finished)
thread.start()
def textedit_tweet_textChanged(self):
self.label_textcount.setText(str(validator.MAX_TWEET_LENGTH - validator.getTweetLength(self.textedit_tweet.toPlainText())))
instance = None
def getinstance():
if MainWindow.instance is None:
MainWindow.instance = MainWindow()
return MainWindow.instance
| 35.659341 | 131 | 0.693991 |
from PyQt4 import QtCore, QtGui
import twikoto3
from twikoto3.extension import *
from twikoto3.twittertext import validator
class TweetTextEdit(QtGui.QTextEdit):
def __init__(self, parent = None):
super(TweetTextEdit, self).__init__(parent)
self.tweetaction = None
def keyPressEvent(self, e):
if e.key() == QtCore.Qt.Key_Return and (e.modifiers() and QtCore.Qt.ControlModifier):
self.tweetaction()
else:
super(TweetTextEdit, self).keyPressEvent(e)
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle("ついこと 3")
self.layout = QtGui.QVBoxLayout()
self.textedit_tweet = TweetTextEdit()
self.textedit_tweet.setMinimumHeight(46)
self.textedit_tweet.textChanged.connect(self.textedit_tweet_textChanged)
self.textedit_tweet.tweetaction = self.button_tweet_clicked
self.layout.addWidget(self.textedit_tweet)
self.layout_tweetbutton = QtGui.QHBoxLayout()
self.layout.addLayout(self.layout_tweetbutton)
self.label_textcount = QtGui.QLabel("140")
self.layout_tweetbutton.addWidget(self.label_textcount)
self.button_tweet = QtGui.QPushButton("Tweet")
self.button_tweet.clicked.connect(self.button_tweet_clicked)
self.layout_tweetbutton.addWidget(self.button_tweet)
self.centralWidget = QtGui.QWidget()
self.centralWidget.setLayout(self.layout)
self.setCentralWidget(self.centralWidget)
def button_tweet_clicked(self):
status = self.textedit_tweet.toPlainText()
if status | noneoremptystr():
return
self.button_tweet.setEnabled(False)
thread = twikoto3.twitter.updatestatus(status)
def finished():
self.button_tweet.setEnabled(True)
if thread.response is not None:
self.textedit_tweet.setPlainText("")
else:
QtGui.QMessageBox.critical(self, "投稿失敗", str(thread.exception))
thread.finished.connect(finished)
thread.start()
def textedit_tweet_textChanged(self):
self.label_textcount.setText(str(validator.MAX_TWEET_LENGTH - validator.getTweetLength(self.textedit_tweet.toPlainText())))
instance = None
def getinstance():
if MainWindow.instance is None:
MainWindow.instance = MainWindow()
return MainWindow.instance
| true | true |
f72b96bf64c72a7aab50945832a74f43bbe2503a | 517 | py | Python | conclusions/1-intro/Basics.py | balajisomasale/Udacity_Data-Structures-and-algorithms | aa9a58e62c488e32920308ae14faad84e735a0dd | [
"MIT"
] | null | null | null | conclusions/1-intro/Basics.py | balajisomasale/Udacity_Data-Structures-and-algorithms | aa9a58e62c488e32920308ae14faad84e735a0dd | [
"MIT"
] | null | null | null | conclusions/1-intro/Basics.py | balajisomasale/Udacity_Data-Structures-and-algorithms | aa9a58e62c488e32920308ae14faad84e735a0dd | [
"MIT"
] | null | null | null | # Write a function called "show_excitement" where the string
# "I am super excited for this course!" is returned exactly
# 5 times, where each sentence is separated by a single space.
# Return the string with "return".
# You can only have the string once in your code.
# Don't just copy/paste it 5 times into a single variable!
def show_excitement():
# Your code goes here!
here = ''
for i in range(5):
here += "I am super excited for this course! "
return here[:-1]
print show_excitement()s | 34.466667 | 62 | 0.700193 |
def show_excitement():
# Your code goes here!
here = ''
for i in range(5):
here += "I am super excited for this course! "
return here[:-1]
print show_excitement()s | false | true |
f72b96fd84fbba9e15af0f1cd90ccc4befda2a17 | 519 | py | Python | dataset/processes/make_center_points.py | Challenging6/YoloDB | bdc1c4239ec112c21a65df64b9f4dc8447b739fa | [
"MIT"
] | null | null | null | dataset/processes/make_center_points.py | Challenging6/YoloDB | bdc1c4239ec112c21a65df64b9f4dc8447b739fa | [
"MIT"
] | null | null | null | dataset/processes/make_center_points.py | Challenging6/YoloDB | bdc1c4239ec112c21a65df64b9f4dc8447b739fa | [
"MIT"
] | null | null | null | import numpy as np
#from concern.config import State
from .data_process import DataProcess
class MakeCenterPoints(DataProcess):
box_key = 'charboxes'
size = 32
def process(self, data):
shape = data['image'].shape[:2]
points = np.zeros((self.size, 2), dtype=np.float32)
boxes = np.array(data[self.box_key])[:self.size]
size = boxes.shape[0]
points[:size] = boxes.mean(axis=1)
data['points'] = (points / shape[::-1]).astype(np.float32)
return data
| 25.95 | 66 | 0.626204 | import numpy as np
from .data_process import DataProcess
class MakeCenterPoints(DataProcess):
box_key = 'charboxes'
size = 32
def process(self, data):
shape = data['image'].shape[:2]
points = np.zeros((self.size, 2), dtype=np.float32)
boxes = np.array(data[self.box_key])[:self.size]
size = boxes.shape[0]
points[:size] = boxes.mean(axis=1)
data['points'] = (points / shape[::-1]).astype(np.float32)
return data
| true | true |
f72b995a0c976a846d2650b3d530e5ff685e31e0 | 1,456 | py | Python | setup.py | ammurdoch/graphql-core | 03c2b06e4636ed8a89c7a4c7e56d244fd9d00bde | [
"MIT"
] | 1 | 2021-07-27T20:47:34.000Z | 2021-07-27T20:47:34.000Z | setup.py | vpetrovykh/graphql-core | 7af97e22afb27861fc1b7d7ca0292095f8427ecb | [
"MIT"
] | null | null | null | setup.py | vpetrovykh/graphql-core | 7af97e22afb27861fc1b7d7ca0292095f8427ecb | [
"MIT"
] | null | null | null | from re import search
from setuptools import setup, find_packages
with open("src/graphql/version.py") as version_file:
version = search('version = "(.*)"', version_file.read()).group(1)
with open("README.md") as readme_file:
readme = readme_file.read()
setup(
name="graphql-core",
version=version,
description="GraphQL implementation for Python, a port of GraphQL.js,"
" the JavaScript reference implementation for GraphQL.",
long_description=readme,
long_description_content_type="text/markdown",
keywords="graphql",
url="https://github.com/graphql-python/graphql-core",
author="Christoph Zwerschke",
author_email="cito@online.de",
license="MIT license",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
],
install_requires=[],
python_requires=">=3.6,<4",
packages=find_packages("src"),
package_dir={"": "src"},
# PEP-561: https://www.python.org/dev/peps/pep-0561/
package_data={"graphql": ["py.typed"]},
include_package_data=True,
zip_safe=False,
)
| 34.666667 | 74 | 0.651099 | from re import search
from setuptools import setup, find_packages
with open("src/graphql/version.py") as version_file:
version = search('version = "(.*)"', version_file.read()).group(1)
with open("README.md") as readme_file:
readme = readme_file.read()
setup(
name="graphql-core",
version=version,
description="GraphQL implementation for Python, a port of GraphQL.js,"
" the JavaScript reference implementation for GraphQL.",
long_description=readme,
long_description_content_type="text/markdown",
keywords="graphql",
url="https://github.com/graphql-python/graphql-core",
author="Christoph Zwerschke",
author_email="cito@online.de",
license="MIT license",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Topic :: Software Development :: Libraries",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
],
install_requires=[],
python_requires=">=3.6,<4",
packages=find_packages("src"),
package_dir={"": "src"},
package_data={"graphql": ["py.typed"]},
include_package_data=True,
zip_safe=False,
)
| true | true |
f72b99ae1a3457bb9180b67219d05ac2ccfc50cd | 1,200 | py | Python | Noise Elimination/mean_elimination_script.py | BAD-Classifier/Signal-Processing | 8163657fb8b8e1ec32ea299a5b4cda9473b91fd0 | [
"MIT"
] | null | null | null | Noise Elimination/mean_elimination_script.py | BAD-Classifier/Signal-Processing | 8163657fb8b8e1ec32ea299a5b4cda9473b91fd0 | [
"MIT"
] | null | null | null | Noise Elimination/mean_elimination_script.py | BAD-Classifier/Signal-Processing | 8163657fb8b8e1ec32ea299a5b4cda9473b91fd0 | [
"MIT"
] | null | null | null | import numpy
import librosa
import glob
import os
import shutil
full_clips = glob.glob("Full_Clips/*.mp3")
print("Number of full clips: " + str(len(full_clips)))
for clip in full_clips:
clip_name = clip[11:]
print("Current clip: " + clip_name)
signal, fs = librosa.load(clip)
signal_abs = numpy.absolute(signal)
search_name = "Cut_Clips/" + clip_name[:-4] + "*[0-9].*"
cut_clips = glob.glob(search_name)
print("Number of clip segments: " + str(len(cut_clips)))
total_mean = numpy.mean(signal_abs)
print("Signal Total mean: " + str(total_mean))
condition = total_mean*0.25
for record in cut_clips:
signal_segment, sample_rate_segment = librosa.load(record)
mean = numpy.mean(numpy.abs(signal_segment))
if mean < condition:
print(record)
print("Segment mean: " + str(mean))
shutil.move(record,"Rejected_noise/")
rejected_clips = glob.glob("Rejected_noise/*.wav")
print(rejected_clips)
for item in rejected_clips:
name = item[15:]
new_name = "All_MFCCs/" + name[:-3] + "png"
if os.path.isfile(new_name):
shutil.move(new_name, "Rejected_MFCCS/")
| 30.769231 | 66 | 0.643333 | import numpy
import librosa
import glob
import os
import shutil
full_clips = glob.glob("Full_Clips/*.mp3")
print("Number of full clips: " + str(len(full_clips)))
for clip in full_clips:
clip_name = clip[11:]
print("Current clip: " + clip_name)
signal, fs = librosa.load(clip)
signal_abs = numpy.absolute(signal)
search_name = "Cut_Clips/" + clip_name[:-4] + "*[0-9].*"
cut_clips = glob.glob(search_name)
print("Number of clip segments: " + str(len(cut_clips)))
total_mean = numpy.mean(signal_abs)
print("Signal Total mean: " + str(total_mean))
condition = total_mean*0.25
for record in cut_clips:
signal_segment, sample_rate_segment = librosa.load(record)
mean = numpy.mean(numpy.abs(signal_segment))
if mean < condition:
print(record)
print("Segment mean: " + str(mean))
shutil.move(record,"Rejected_noise/")
rejected_clips = glob.glob("Rejected_noise/*.wav")
print(rejected_clips)
for item in rejected_clips:
name = item[15:]
new_name = "All_MFCCs/" + name[:-3] + "png"
if os.path.isfile(new_name):
shutil.move(new_name, "Rejected_MFCCS/")
| true | true |
f72b9a83a149804ec5bf2fd5f521cbb2d63c0d98 | 1,384 | py | Python | tests/parser/syntax/test_functions_call.py | Solexplorer/vyper | 135edd6a91d47c72de105066d6e6c1bdfe9ea66e | [
"MIT"
] | 1 | 2021-04-23T21:48:20.000Z | 2021-04-23T21:48:20.000Z | tests/parser/syntax/test_functions_call.py | Solexplorer/vyper | 135edd6a91d47c72de105066d6e6c1bdfe9ea66e | [
"MIT"
] | null | null | null | tests/parser/syntax/test_functions_call.py | Solexplorer/vyper | 135edd6a91d47c72de105066d6e6c1bdfe9ea66e | [
"MIT"
] | 1 | 2020-01-27T05:21:46.000Z | 2020-01-27T05:21:46.000Z | import pytest
from pytest import (
raises,
)
from vyper import (
compiler,
)
from vyper.exceptions import (
ParserException,
StructureException,
)
fail_list = [
"""
@public
def foo() -> uint256:
doesnotexist(2, uint256)
return convert(2, uint256)
""",
"""
@public
def foo() -> uint256:
convert(2, uint256)
return convert(2, uint256)
""",
("""
@private
def test(a : uint256):
pass
@public
def burn(_value: uint256):
self.test(msg.sender._value)
""", ParserException)
]
@pytest.mark.parametrize('bad_code', fail_list)
def test_functions_call_fail(bad_code):
if isinstance(bad_code, tuple):
with raises(bad_code[1]):
compiler.compile_code(bad_code[0])
else:
with raises(StructureException):
compiler.compile_code(bad_code)
valid_list = [
"""
@public
def foo() -> uint256:
return convert(2, uint256)
""",
"""
from vyper.interfaces import ERC20
contract Factory:
def getExchange(token_addr: address) -> address: constant
token: ERC20
factory: Factory
@public
def setup(token_addr: address):
self.token = ERC20(token_addr)
assert self.factory.getExchange(self.token) == self
"""
]
@pytest.mark.parametrize('good_code', valid_list)
def test_functions_call_success(good_code):
assert compiler.compile_code(good_code) is not None
| 17.74359 | 61 | 0.664017 | import pytest
from pytest import (
raises,
)
from vyper import (
compiler,
)
from vyper.exceptions import (
ParserException,
StructureException,
)
fail_list = [
"""
@public
def foo() -> uint256:
doesnotexist(2, uint256)
return convert(2, uint256)
""",
"""
@public
def foo() -> uint256:
convert(2, uint256)
return convert(2, uint256)
""",
("""
@private
def test(a : uint256):
pass
@public
def burn(_value: uint256):
self.test(msg.sender._value)
""", ParserException)
]
@pytest.mark.parametrize('bad_code', fail_list)
def test_functions_call_fail(bad_code):
if isinstance(bad_code, tuple):
with raises(bad_code[1]):
compiler.compile_code(bad_code[0])
else:
with raises(StructureException):
compiler.compile_code(bad_code)
valid_list = [
"""
@public
def foo() -> uint256:
return convert(2, uint256)
""",
"""
from vyper.interfaces import ERC20
contract Factory:
def getExchange(token_addr: address) -> address: constant
token: ERC20
factory: Factory
@public
def setup(token_addr: address):
self.token = ERC20(token_addr)
assert self.factory.getExchange(self.token) == self
"""
]
@pytest.mark.parametrize('good_code', valid_list)
def test_functions_call_success(good_code):
assert compiler.compile_code(good_code) is not None
| true | true |
f72b9b0270340672ef3e38e9ca7507f43250ba2a | 222 | py | Python | aws_test/testapp/views.py | shivavh123/django | 1f94b50d0f5cf5b0b90dcf86afbc267500a3732b | [
"MIT"
] | null | null | null | aws_test/testapp/views.py | shivavh123/django | 1f94b50d0f5cf5b0b90dcf86afbc267500a3732b | [
"MIT"
] | null | null | null | aws_test/testapp/views.py | shivavh123/django | 1f94b50d0f5cf5b0b90dcf86afbc267500a3732b | [
"MIT"
] | null | null | null | from django.shortcuts import render
from django.http import *
# Create your views here.
def test_view(request,name):
data = "Hi, Welcome {}, this is first view in AWS....".format(name)
return HttpResponse(data) | 22.2 | 71 | 0.711712 | from django.shortcuts import render
from django.http import *
def test_view(request,name):
data = "Hi, Welcome {}, this is first view in AWS....".format(name)
return HttpResponse(data) | true | true |
f72b9b18157277dd97c650ac9b1513b389eba29b | 1,411 | py | Python | channels_graphql_ws/__init__.py | hozblok/DjangoChannelsGraphqlWs | 77b406fb19053fcb9220a5bb23e1349fde4fbda3 | [
"MIT"
] | null | null | null | channels_graphql_ws/__init__.py | hozblok/DjangoChannelsGraphqlWs | 77b406fb19053fcb9220a5bb23e1349fde4fbda3 | [
"MIT"
] | null | null | null | channels_graphql_ws/__init__.py | hozblok/DjangoChannelsGraphqlWs | 77b406fb19053fcb9220a5bb23e1349fde4fbda3 | [
"MIT"
] | null | null | null | #
# coding: utf-8
# Copyright (c) 2019 DATADVANCE
#
# 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.
"""Websocket GraphQL server with subscriptions.
Django Channels based WebSocket GraphQL server with Graphene-like
subscriptions.
"""
from .client import GraphqlWsClient, GraphqlWsResponseError
from .graphql_ws import GraphqlWsConsumer, Subscription
from .transport import GraphqlWsTransportAiohttp
| 41.5 | 72 | 0.79022 |
from .client import GraphqlWsClient, GraphqlWsResponseError
from .graphql_ws import GraphqlWsConsumer, Subscription
from .transport import GraphqlWsTransportAiohttp
| true | true |
f72b9b237c832c25f3a47690b75b5f4398085165 | 4,558 | py | Python | alphazero/mcts.py | bartekx43/AlphaTTT | a01c38833a7f841483146bebeef73323d527d812 | [
"MIT"
] | null | null | null | alphazero/mcts.py | bartekx43/AlphaTTT | a01c38833a7f841483146bebeef73323d527d812 | [
"MIT"
] | null | null | null | alphazero/mcts.py | bartekx43/AlphaTTT | a01c38833a7f841483146bebeef73323d527d812 | [
"MIT"
] | null | null | null | import os
import sys
import math
import random
import numpy as np
from copy import deepcopy
sys.path.append(os.path.join(os.environ["HOME"], "AlphaTTT"))
from environment import Environment
from alphazero.database import prepare_state
np.random.seed(80085)
random.seed(80085)
def PUCT_score(child_value, child_prior, parent_visit_count, child_visit_count, c_puct):
pb_c = child_prior * math.sqrt(parent_visit_count) / (child_visit_count + 1)
return child_value + c_puct * pb_c
class MCTS():
def __init__(self, model, root_state, args):
'''
model - class with predict method that returns a valid policy and value
root_state - board_len x board_len array with the initial state of the game
args:
num_simulations - number of leaf node expansions per search
alpha - mixing constant between policy and dirichlet noise
dirichlet_alpha - dirichlet constant for generating dirichlet distribution
c_puct - exploration constant in PUCT score
'''
self.model = model
self.root = deepcopy(root_state)
self.args = args
self.Qsa = {} # self.Qsa(s, a) = Q value for (s, a)
self.Nsa = {} # self.Nsa(s, a) = (s, a) visit count
self.Ns = {} # self.Ns(s) = s visit count
self.Ps = {} # self.Ps(s) = list of available actions in s and corresponding raw probabilities
self.Es = {} # terminal states, potentially going to do this if not too computationally expensive and dirty
# Add dirichlet noise to initial root node
self.add_dirichlet()
def add_dirichlet(self):
rs = self.root.tobytes()
if rs not in self.Ps:
self.find_leaf(deepcopy(self.root))
if self.Es[rs] == 10:
dirichlet = np.random.dirichlet([self.args["dirichlet_alpha"]]*len(self.Ps[rs]))
for i, (move, prob) in enumerate(self.Ps[rs]):
self.Ps[rs][i] = (move, (1 - self.args["alpha"]) * prob + dirichlet[i] * self.args["alpha"])
def search(self): # builds the search tree from the root node
for i in range(self.args["num_simulations"]):
self.find_leaf(deepcopy(self.root))
return
def find_leaf(self, state):
s = state.tobytes()
if s not in self.Es:
self.Es[s] = Environment.game_over(state)
if self.Es[s] != 10:
# terminal state
return -self.Es[s]
if s not in self.Ps: # expand leaf node
p, v = self.model.predict(prepare_state(state))
availability_mask = (state == 0)
p *= availability_mask
if np.sum(p) > 0.0:
p /= np.sum(p) # re-normalize
move_probs = []
for i, row in enumerate(p):
for j, prob in enumerate(row):
if state[i][j] == 0:
move_probs.append(((i, j), prob))
self.Ps[s] = move_probs
self.Ns[s] = 1
return -v
max_puct = -float('inf')
max_action = None
for move, prob in self.Ps[s]:
(Nc, Qc) = (self.Nsa[(s, move)], self.Qsa[(s, move)]) if (s, move) in self.Nsa else (0, 0.0)
puct = PUCT_score(Qc, prob, self.Ns[s], Nc, self.args["c_puct"])
if puct > max_puct:
max_puct = puct
max_action = move
a = max_action
state[a] = 1
state *= -1
v = self.find_leaf(state)
if (s, a) in self.Nsa:
self.Nsa[(s, a)] += 1
self.Qsa[(s, a)] = (self.Nsa[(s, a)] * self.Qsa[(s, a)] + v) / (self.Nsa[(s, a)] + 1)
else:
self.Nsa[(s, a)] = 1
self.Qsa[(s, a)] = v
self.Ns[s] += 1
return -v
def get_pi(self, tau=1.0, as_prob=True):
move_dist = np.zeros((len(self.root), len(self.root)))
rs = self.root.tobytes()
for move, _ in self.Ps[rs]:
move_dist[move] = self.Nsa[(rs, move)] if (rs, move) in self.Nsa else 0
if as_prob is True:
if tau < 0.1: # protecting from numerical overflow
z = np.zeros(move_dist.shape)
move = np.unravel_index(np.argmax(move_dist), move_dist.shape)
z[move[0]][move[1]] = 1.0
move_dist = z
else:
move_dist = np.power(move_dist, 1.0/tau)
if np.sum(move_dist) > 0.0:
move_dist /= np.sum(move_dist)
return move_dist
def select_move(self, tau=1.0, external_move=None):
if external_move is None:
probas = self.get_pi(tau)
selected_move = int(np.random.choice(len(probas.flatten()), 1, p=probas.flatten()))
selected_move = np.unravel_index(selected_move, probas.shape)
else:
selected_move = external_move
self.root[selected_move] = 1
self.root *= -1
# Add dirichlet noise to new root node:
self.add_dirichlet()
return selected_move
| 31.006803 | 111 | 0.623958 | import os
import sys
import math
import random
import numpy as np
from copy import deepcopy
sys.path.append(os.path.join(os.environ["HOME"], "AlphaTTT"))
from environment import Environment
from alphazero.database import prepare_state
np.random.seed(80085)
random.seed(80085)
def PUCT_score(child_value, child_prior, parent_visit_count, child_visit_count, c_puct):
pb_c = child_prior * math.sqrt(parent_visit_count) / (child_visit_count + 1)
return child_value + c_puct * pb_c
class MCTS():
def __init__(self, model, root_state, args):
self.model = model
self.root = deepcopy(root_state)
self.args = args
self.Qsa = {}
self.Nsa = {}
self.Ns = {}
self.Ps = {}
self.Es = {}
self.add_dirichlet()
def add_dirichlet(self):
rs = self.root.tobytes()
if rs not in self.Ps:
self.find_leaf(deepcopy(self.root))
if self.Es[rs] == 10:
dirichlet = np.random.dirichlet([self.args["dirichlet_alpha"]]*len(self.Ps[rs]))
for i, (move, prob) in enumerate(self.Ps[rs]):
self.Ps[rs][i] = (move, (1 - self.args["alpha"]) * prob + dirichlet[i] * self.args["alpha"])
def search(self):
for i in range(self.args["num_simulations"]):
self.find_leaf(deepcopy(self.root))
return
def find_leaf(self, state):
s = state.tobytes()
if s not in self.Es:
self.Es[s] = Environment.game_over(state)
if self.Es[s] != 10:
return -self.Es[s]
if s not in self.Ps:
p, v = self.model.predict(prepare_state(state))
availability_mask = (state == 0)
p *= availability_mask
if np.sum(p) > 0.0:
p /= np.sum(p)
move_probs = []
for i, row in enumerate(p):
for j, prob in enumerate(row):
if state[i][j] == 0:
move_probs.append(((i, j), prob))
self.Ps[s] = move_probs
self.Ns[s] = 1
return -v
max_puct = -float('inf')
max_action = None
for move, prob in self.Ps[s]:
(Nc, Qc) = (self.Nsa[(s, move)], self.Qsa[(s, move)]) if (s, move) in self.Nsa else (0, 0.0)
puct = PUCT_score(Qc, prob, self.Ns[s], Nc, self.args["c_puct"])
if puct > max_puct:
max_puct = puct
max_action = move
a = max_action
state[a] = 1
state *= -1
v = self.find_leaf(state)
if (s, a) in self.Nsa:
self.Nsa[(s, a)] += 1
self.Qsa[(s, a)] = (self.Nsa[(s, a)] * self.Qsa[(s, a)] + v) / (self.Nsa[(s, a)] + 1)
else:
self.Nsa[(s, a)] = 1
self.Qsa[(s, a)] = v
self.Ns[s] += 1
return -v
def get_pi(self, tau=1.0, as_prob=True):
move_dist = np.zeros((len(self.root), len(self.root)))
rs = self.root.tobytes()
for move, _ in self.Ps[rs]:
move_dist[move] = self.Nsa[(rs, move)] if (rs, move) in self.Nsa else 0
if as_prob is True:
if tau < 0.1:
z = np.zeros(move_dist.shape)
move = np.unravel_index(np.argmax(move_dist), move_dist.shape)
z[move[0]][move[1]] = 1.0
move_dist = z
else:
move_dist = np.power(move_dist, 1.0/tau)
if np.sum(move_dist) > 0.0:
move_dist /= np.sum(move_dist)
return move_dist
def select_move(self, tau=1.0, external_move=None):
if external_move is None:
probas = self.get_pi(tau)
selected_move = int(np.random.choice(len(probas.flatten()), 1, p=probas.flatten()))
selected_move = np.unravel_index(selected_move, probas.shape)
else:
selected_move = external_move
self.root[selected_move] = 1
self.root *= -1
self.add_dirichlet()
return selected_move
| true | true |
f72b9b71cfe4c76f04ff852319ec57e7120fbde7 | 70 | py | Python | tests/test_graph_container.py | harangju/wikinet | 903cf94e30f6dae3de3a3615ce6cd67091f512dc | [
"MIT"
] | 9 | 2020-10-19T12:36:49.000Z | 2021-09-07T02:31:52.000Z | tests/test_graph_container.py | harangju/wikinet | 903cf94e30f6dae3de3a3615ce6cd67091f512dc | [
"MIT"
] | 1 | 2022-03-30T09:34:56.000Z | 2022-03-30T14:08:48.000Z | tests/test_graph_container.py | harangju/wikinet | 903cf94e30f6dae3de3a3615ce6cd67091f512dc | [
"MIT"
] | 5 | 2020-10-20T01:39:14.000Z | 2022-03-30T17:12:30.000Z | import wikinet
print('hello world')
print(wikinet.GraphContainer())
| 11.666667 | 31 | 0.771429 | import wikinet
print('hello world')
print(wikinet.GraphContainer())
| true | true |
f72b9c283b7d0547ed71c29c45e273ec49018748 | 876 | py | Python | paneldata_dash/resources/category.py | clarencejlee/jdp | d3d31db0138ff06f2f5ec592d85317941af4f280 | [
"MIT"
] | null | null | null | paneldata_dash/resources/category.py | clarencejlee/jdp | d3d31db0138ff06f2f5ec592d85317941af4f280 | [
"MIT"
] | null | null | null | paneldata_dash/resources/category.py | clarencejlee/jdp | d3d31db0138ff06f2f5ec592d85317941af4f280 | [
"MIT"
] | null | null | null | from flask import request
from flask_restful import Resource
from models.category import CategoryModel
from schemas.category import CategorySchema
category_schema = CategorySchema()
category_list_schema = CategorySchema(many=True)
class Category(Resource):
@classmethod
def get(cls, name: str):
category = CategoryModel.find_by_name(name)
if category:
return category_schema.dump(category), 200
return {"message": "Category not found"}, 404
class CategoryList(Resource):
@classmethod
def get(cls):
page = 1 if (request.args.get("page") is None or request.args.get("page") == 0) \
else int(request.args.get("page")) + 1
size = 10 if request.args.get("size") is None else int(request.args.get("size"))
return {"categories": category_list_schema.dump(CategoryModel.find_all())}, 200
| 30.206897 | 89 | 0.692922 | from flask import request
from flask_restful import Resource
from models.category import CategoryModel
from schemas.category import CategorySchema
category_schema = CategorySchema()
category_list_schema = CategorySchema(many=True)
class Category(Resource):
@classmethod
def get(cls, name: str):
category = CategoryModel.find_by_name(name)
if category:
return category_schema.dump(category), 200
return {"message": "Category not found"}, 404
class CategoryList(Resource):
@classmethod
def get(cls):
page = 1 if (request.args.get("page") is None or request.args.get("page") == 0) \
else int(request.args.get("page")) + 1
size = 10 if request.args.get("size") is None else int(request.args.get("size"))
return {"categories": category_list_schema.dump(CategoryModel.find_all())}, 200
| true | true |
f72b9e6674fbda39b41025e89556f609b84326ea | 2,699 | py | Python | masonite/drivers/UploadS3Driver.py | w3x10e8/core | d8f0ca29c2bd5e86d199391fa916ce2f5c9b0f49 | [
"MIT"
] | null | null | null | masonite/drivers/UploadS3Driver.py | w3x10e8/core | d8f0ca29c2bd5e86d199391fa916ce2f5c9b0f49 | [
"MIT"
] | null | null | null | masonite/drivers/UploadS3Driver.py | w3x10e8/core | d8f0ca29c2bd5e86d199391fa916ce2f5c9b0f49 | [
"MIT"
] | null | null | null | """ Upload S3 Driver """
from masonite.contracts import UploadContract
from masonite.drivers import BaseUploadDriver
from masonite.exceptions import DriverLibraryNotFound
from masonite.managers import UploadManager
from masonite.app import App
class UploadS3Driver(BaseUploadDriver, UploadContract):
"""
Amazon S3 Upload driver
"""
def __init__(self, upload: UploadManager, app: App):
"""Upload Disk Driver Constructor
Arguments:
UploadManager {masonite.managers.UploadManager} -- The Upload Manager object.
StorageConfig {config.storage} -- Storage configuration.
"""
self.upload = upload
self.config = app.make('StorageConfig')
def store(self, fileitem, location=None):
"""Store the file into Amazon S3 server.
Arguments:
fileitem {cgi.Storage} -- Storage object.
Keyword Arguments:
location {string} -- The location on disk you would like to store the file. (default: {None})
Raises:
DriverLibraryNotFound -- Raises when the boto3 library is not installed.
Returns:
string -- Returns the file name just saved.
"""
driver = self.upload.driver('disk')
driver.store(fileitem, location)
file_location = driver.file_location
# Check if is a valid extension
self.validate_extension(fileitem.filename)
try:
import boto3
except ImportError:
raise DriverLibraryNotFound(
'Could not find the "boto3" library. Please pip install this library by running "pip install boto3"')
session = boto3.Session(
aws_access_key_id=self.config.DRIVERS['s3']['client'],
aws_secret_access_key=self.config.DRIVERS['s3']['secret'],
)
s3 = session.resource('s3')
s3.meta.client.upload_file(
file_location,
self.config.DRIVERS['s3']['bucket'],
fileitem.filename
)
return fileitem.filename
def store_prepend(self, fileitem, prepend, location=None):
"""Store the file onto the Amazon S3 server but with a prepended file name.
Arguments:
fileitem {cgi.Storage} -- Storage object.
prepend {string} -- The prefix you want to prepend to the file name.
Keyword Arguments:
location {string} -- The location on disk you would like to store the file. (default: {None})
Returns:
string -- Returns the file name just saved.
"""
fileitem.filename = prepend + fileitem.filename
return self.store(fileitem, location=location)
| 31.022989 | 117 | 0.632086 |
from masonite.contracts import UploadContract
from masonite.drivers import BaseUploadDriver
from masonite.exceptions import DriverLibraryNotFound
from masonite.managers import UploadManager
from masonite.app import App
class UploadS3Driver(BaseUploadDriver, UploadContract):
def __init__(self, upload: UploadManager, app: App):
self.upload = upload
self.config = app.make('StorageConfig')
def store(self, fileitem, location=None):
driver = self.upload.driver('disk')
driver.store(fileitem, location)
file_location = driver.file_location
self.validate_extension(fileitem.filename)
try:
import boto3
except ImportError:
raise DriverLibraryNotFound(
'Could not find the "boto3" library. Please pip install this library by running "pip install boto3"')
session = boto3.Session(
aws_access_key_id=self.config.DRIVERS['s3']['client'],
aws_secret_access_key=self.config.DRIVERS['s3']['secret'],
)
s3 = session.resource('s3')
s3.meta.client.upload_file(
file_location,
self.config.DRIVERS['s3']['bucket'],
fileitem.filename
)
return fileitem.filename
def store_prepend(self, fileitem, prepend, location=None):
fileitem.filename = prepend + fileitem.filename
return self.store(fileitem, location=location)
| true | true |
f72b9ebf1fe11a999e122be4418851c61b594f29 | 9,487 | py | Python | ensemble/control/operational/TestOperationalLayerEnsembleVissim.py | licit-lab/ensemble | 7a78ef0d69610d4fcfc5e008f931ade15e35acbf | [
"Linux-OpenIB"
] | null | null | null | ensemble/control/operational/TestOperationalLayerEnsembleVissim.py | licit-lab/ensemble | 7a78ef0d69610d4fcfc5e008f931ade15e35acbf | [
"Linux-OpenIB"
] | null | null | null | ensemble/control/operational/TestOperationalLayerEnsembleVissim.py | licit-lab/ensemble | 7a78ef0d69610d4fcfc5e008f931ade15e35acbf | [
"Linux-OpenIB"
] | null | null | null | import os
import sys
import ctypes
import platform
import os
import numpy as np
from random import gauss
import win32com.client as com
def get_acceleration(lead_veh_acceleration,lead_veh_id,lead_veh_rel_velocity,lead_veh_type,timestep,
veh_id,veh_setspeed,veh_type,veh_used_distance_headway,veh_used_rel_vel,veh_velocity,
veh_distance_headway,prev_veh_executed_acceleration,
prev_veh_cc_setpoint,prev_veh_cruisecontrol_acceleration):
if platform.system() == 'Windows':
print('Running on win')
filepath = "L:\\UserData\\Kingsley\\PythonEnsembleTestBed"
file_dll = os.path.join(filepath, 'OperationalDLL.dll')
#file_dll = './OperationalDLL.dll'
elif platform.system() == 'Darwin':
print('Running on mac')
file_dll = 'OperationalDLL.dylib'
else:
print('System not supported')
sys.exit()
# Load operational DLL
lib = None
try:
lib = ctypes.cdll.LoadLibrary(file_dll)
except:
print('Error: DLL file could not be found')
quit()
# Set input values: Write value's for current vehicle, in current timestep
curr_lead_veh_acceleration = ctypes.c_double(lead_veh_acceleration) #2.0
curr_lead_veh_id = ctypes.c_long(lead_veh_id) #40
curr_lead_veh_rel_velocity = ctypes.c_double(lead_veh_rel_velocity ) #-1.0
curr_lead_veh_type = ctypes.c_long(lead_veh_type) #10
curr_timestep = ctypes.c_double(timestep) #55.0
curr_ts_length = ctypes.c_double(0.1)
curr_veh_id = ctypes.c_long(veh_id) #10
curr_veh_setspeed = ctypes.c_double(veh_setspeed) #88/3.6
curr_veh_type = ctypes.c_long(veh_type) #10
curr_veh_controller_in_use = ctypes.c_long(1) # from tactical layer 1=ACC,2=CACC
curr_veh_ACC_h = ctypes.c_double(1.6)
curr_veh_CACC_h = ctypes.c_double(0.6)
curr_veh_used_distance_headway = ctypes.c_double(veh_used_distance_headway)#20.0
curr_veh_used_rel_vel = ctypes.c_double(veh_used_rel_vel) #-1.0
curr_veh_velocity = ctypes.c_double(veh_velocity) #85/3.6
curr_veh_autonomous_operational_warning = ctypes.c_long(10)
curr_veh_platooning_max_acceleration = ctypes.c_double(2.0)
prev_veh_cc_setpoint = ctypes.c_double(prev_veh_cc_setpoint)
prev_veh_cruisecontrol_acceleration = ctypes.c_double(prev_veh_cruisecontrol_acceleration)
prev_veh_distance_headway = ctypes.c_double(veh_distance_headway) #20.0
prev_veh_executed_acceleration = ctypes.c_double(prev_veh_executed_acceleration) #-2.0
# Define variables for return values: These are placeholders, no action required
veh_autonomous_operational_acceleration = ctypes.c_double(1)
veh_autonomous_operational_mixingmode = ctypes.c_long(1)
veh_autonomous_operational_warning = ctypes.c_double(1)
veh_cc_setpoint = ctypes.c_double(1)
veh_cruisecontrol_acceleration = ctypes.c_double(1)
success = ctypes.c_int(0)
print("Now call the OL itself...")
# Call operational controller
lib.operational_controller(
curr_lead_veh_acceleration,
curr_lead_veh_id,
curr_lead_veh_rel_velocity,
curr_lead_veh_type,
curr_timestep,
curr_ts_length,
curr_veh_id,
curr_veh_setspeed,
curr_veh_type,
curr_veh_controller_in_use,
curr_veh_ACC_h,
curr_veh_CACC_h,
curr_veh_used_distance_headway,
curr_veh_used_rel_vel,
curr_veh_velocity,
curr_veh_autonomous_operational_warning,
curr_veh_platooning_max_acceleration,
prev_veh_cc_setpoint,
prev_veh_cruisecontrol_acceleration,
prev_veh_distance_headway,
prev_veh_executed_acceleration,
ctypes.byref(veh_autonomous_operational_acceleration),
ctypes.byref(veh_autonomous_operational_mixingmode),
ctypes.byref(veh_autonomous_operational_warning),
ctypes.byref(veh_cc_setpoint),
ctypes.byref(veh_cruisecontrol_acceleration),
ctypes.byref(success))
# Print the return values
if success.value > 0:
veh_acceleration=veh_autonomous_operational_acceleration.value
#print(veh_autonomous_operational_mixingmode.value)
#print(veh_autonomous_operational_warning.value)
veh_cc_set_point=veh_cc_setpoint.value
veh_cruise_control_acceleration=veh_cruisecontrol_acceleration.value
else:
veh_acceleration=-999
veh_cc_setpoint=-999
veh_cruise_control_acceleration=-999
print('An error occurred while calling DLL')
return veh_acceleration,veh_cc_setpoint,veh_cruise_control_acceleration
Vissim = com.gencache.EnsureDispatch("Vissim.Vissim")
GlosaNetworkPath='D:\\Projects\\ENSEMBLE\\Vissim_networks\\Pipeline'#'L:\\UserData\\Kingsley\\Ensemble'
#'L:\\UserData\\Kingsley\\SafeDriving'
#'L:\\UserData\\Kingsley\\Ensemble'#'C:\\Users\\Public\\Documents\\GLOSA\\GlosaTrafficLight'
Filename= os.path.join(GlosaNetworkPath, 'Pipeline.inpx')
#os.path.join(GlosaNetworkPath, 'KnooppuntZonzeelBackup.inpx') #os.path.join(GlosaNetworkPath, 'GlosaTestNetwork2.inpx')
#os.path.join(GlosaNetworkPath, 'TestNetwork.inpx')
flag_read_additionally = False # you can read network(elements) additionally, in this case set "flag_read_additionally" to true
Vissim.LoadNet(Filename, flag_read_additionally)
## Load a Layout:
Filename = os.path.join(GlosaNetworkPath, 'Pipeline.layx')
#os.path.join(GlosaNetworkPath, 'KnooppuntZonzeelBackup.layx')
#os.path.join(GlosaNetworkPath, 'TestNetwork.layx')
#os.path.join(GlosaNetworkPath, 'KnooppuntZonzeelBackup.layx')#os.path.join(GlosaNetworkPath, 'GlosaTestNetwork2.layx')
Vissim.LoadLayout(Filename)
End_of_simulation = 6000 # simulation second [s]
Simulation_Resolution = 10 # simulation second [s]
Number_Runs=4
Simulation_Period=300
Vissim.Simulation.SetAttValue('SimRes', Simulation_Resolution)
Vissim.Simulation.SetAttValue('NumRuns', Number_Runs)
Vissim.Simulation.SetAttValue('SimPeriod', Simulation_Period)
#UDA6
#Vissim.Net.UserDefinedAttributes.AddUserDefinedDataAttribute(6,'Vehicle','vehAcceleration','vehAcceleration',2,0)
#Vissim.Net.UserDefinedAttributes.ItemByKey(6).SetAttValue('DefValue',-1)
#UDA6
Vissim.Net.UserDefinedAttributes.AddUserDefinedDataAttribute(3,'Vehicle','COM_cruise_control_Ac','COM_cruise_control_Ac',2,0)
Vissim.Net.UserDefinedAttributes.ItemByKey(3).SetAttValue('DefValue',-1)
#UDA
Vissim.Net.UserDefinedAttributes.AddUserDefinedDataAttribute(4,'Vehicle','COM_cc_setpoint','COM_cc_setpoint',2,0)
Vissim.Net.UserDefinedAttributes.ItemByKey(4).SetAttValue('DefValue',-1)
def get_leader_info(Vehicle):
lead_veh_id = Vehicle.AttValue('LeadTargNo')
lead_veh_type = Vehicle.AttValue('LeadTargType')
if lead_veh_type == 'VEHICLE' and lead_veh_id != None:
try:
front_vehicle = Vissim.Net.Vehicles.ItemByKey(lead_veh_id)
except:
front_vehicle = -1
else:
front_vehicle=-1
return front_vehicle
#prev_veh_cc_setpoint = np.zeros(number_of_vehicles)
for i in range(6000):
for Vehicle in Vissim.Net.Vehicles.FilteredBy("[VEHTYPE\\NO]=210"):
lead_veh=get_leader_info(Vehicle)
if lead_veh!=-1 and (Vehicle.AttValue('Lane')==lead_veh.AttValue('Lane')):
#simulation info
timestep=Vehicle.AttValue('SimSec')
#Ego Info
print((Vehicle.AttValue('Lane')))
veh_id=Vehicle.AttValue('No')
veh_setspeed=Vehicle.AttValue('DesSpeed')/3.6
veh_type=Vehicle.AttValue('VehType\\No')
veh_used_distance_headway=Vehicle.AttValue('FollowDistNet')
veh_used_rel_vel=(Vehicle.AttValue('Speed')-lead_veh.AttValue('Speed'))/3.6
veh_velocity=Vehicle.AttValue('Speed')/3.6
veh_distance_headway=Vehicle.AttValue('FollowDistNet')
prev_veh_executed_acceleration = Vehicle.AttValue('COM_Ac')
prev_veh_cc_setpoint = Vehicle.AttValue('COM_cc_setpoint')
prev_veh_cruisecontrol_acceleration=Vehicle.AttValue('COM_cruise_control_Ac')
#veh_executed_acceleration=a_prev[veh_id]
#veh_cc_setpoint=prev_veh_cc_setpoint[veh_id]
# Leader Info
lead_veh_acceleration=lead_veh.AttValue('Acceleration')
lead_veh_id=lead_veh.AttValue('No')
lead_veh_rel_velocity=(Vehicle.AttValue('Speed')-lead_veh.AttValue('Speed'))/3.6
lead_veh_type=lead_veh.AttValue('VehType\\No')
curr_veh_executed_acceleration,curr_veh_cc_set_point,curr_veh_cruisecontrol_acceleration=get_acceleration(lead_veh_acceleration,lead_veh_id,lead_veh_rel_velocity,lead_veh_type,timestep,
veh_id,veh_setspeed,veh_type,veh_used_distance_headway,veh_used_rel_vel,veh_velocity,
veh_distance_headway,prev_veh_executed_acceleration,
prev_veh_cc_setpoint,prev_veh_cruisecontrol_acceleration)
# a=call vehicle_model(curr_veh_executed_acceleration)
write_file('file_variables.txt')
Vehicle.SetAttValue('COM_Ac',curr_veh_executed_acceleration)
#Vehicle.SetAttValue('COM_Ac', a)
Vehicle.SetAttValue('COM_At',3)
Vehicle.SetAttValue('COM_cc_setpoint', curr_veh_cc_set_point)
Vehicle.SetAttValue('COM_cruise_control_Ac', curr_veh_cruisecontrol_acceleration)
else:
continue
Vissim.Simulation.RunSingleStep()
| 47.673367 | 197 | 0.733214 | import os
import sys
import ctypes
import platform
import os
import numpy as np
from random import gauss
import win32com.client as com
def get_acceleration(lead_veh_acceleration,lead_veh_id,lead_veh_rel_velocity,lead_veh_type,timestep,
veh_id,veh_setspeed,veh_type,veh_used_distance_headway,veh_used_rel_vel,veh_velocity,
veh_distance_headway,prev_veh_executed_acceleration,
prev_veh_cc_setpoint,prev_veh_cruisecontrol_acceleration):
if platform.system() == 'Windows':
print('Running on win')
filepath = "L:\\UserData\\Kingsley\\PythonEnsembleTestBed"
file_dll = os.path.join(filepath, 'OperationalDLL.dll')
elif platform.system() == 'Darwin':
print('Running on mac')
file_dll = 'OperationalDLL.dylib'
else:
print('System not supported')
sys.exit()
lib = None
try:
lib = ctypes.cdll.LoadLibrary(file_dll)
except:
print('Error: DLL file could not be found')
quit()
curr_lead_veh_acceleration = ctypes.c_double(lead_veh_acceleration) #2.0
curr_lead_veh_id = ctypes.c_long(lead_veh_id) #40
curr_lead_veh_rel_velocity = ctypes.c_double(lead_veh_rel_velocity ) #-1.0
curr_lead_veh_type = ctypes.c_long(lead_veh_type) #10
curr_timestep = ctypes.c_double(timestep) #55.0
curr_ts_length = ctypes.c_double(0.1)
curr_veh_id = ctypes.c_long(veh_id) #10
curr_veh_setspeed = ctypes.c_double(veh_setspeed) #88/3.6
curr_veh_type = ctypes.c_long(veh_type) #10
curr_veh_controller_in_use = ctypes.c_long(1) # from tactical layer 1=ACC,2=CACC
curr_veh_ACC_h = ctypes.c_double(1.6)
curr_veh_CACC_h = ctypes.c_double(0.6)
curr_veh_used_distance_headway = ctypes.c_double(veh_used_distance_headway)#20.0
curr_veh_used_rel_vel = ctypes.c_double(veh_used_rel_vel) #-1.0
curr_veh_velocity = ctypes.c_double(veh_velocity) #85/3.6
curr_veh_autonomous_operational_warning = ctypes.c_long(10)
curr_veh_platooning_max_acceleration = ctypes.c_double(2.0)
prev_veh_cc_setpoint = ctypes.c_double(prev_veh_cc_setpoint)
prev_veh_cruisecontrol_acceleration = ctypes.c_double(prev_veh_cruisecontrol_acceleration)
prev_veh_distance_headway = ctypes.c_double(veh_distance_headway) #20.0
prev_veh_executed_acceleration = ctypes.c_double(prev_veh_executed_acceleration) #-2.0
# Define variables for return values: These are placeholders, no action required
veh_autonomous_operational_acceleration = ctypes.c_double(1)
veh_autonomous_operational_mixingmode = ctypes.c_long(1)
veh_autonomous_operational_warning = ctypes.c_double(1)
veh_cc_setpoint = ctypes.c_double(1)
veh_cruisecontrol_acceleration = ctypes.c_double(1)
success = ctypes.c_int(0)
print("Now call the OL itself...")
# Call operational controller
lib.operational_controller(
curr_lead_veh_acceleration,
curr_lead_veh_id,
curr_lead_veh_rel_velocity,
curr_lead_veh_type,
curr_timestep,
curr_ts_length,
curr_veh_id,
curr_veh_setspeed,
curr_veh_type,
curr_veh_controller_in_use,
curr_veh_ACC_h,
curr_veh_CACC_h,
curr_veh_used_distance_headway,
curr_veh_used_rel_vel,
curr_veh_velocity,
curr_veh_autonomous_operational_warning,
curr_veh_platooning_max_acceleration,
prev_veh_cc_setpoint,
prev_veh_cruisecontrol_acceleration,
prev_veh_distance_headway,
prev_veh_executed_acceleration,
ctypes.byref(veh_autonomous_operational_acceleration),
ctypes.byref(veh_autonomous_operational_mixingmode),
ctypes.byref(veh_autonomous_operational_warning),
ctypes.byref(veh_cc_setpoint),
ctypes.byref(veh_cruisecontrol_acceleration),
ctypes.byref(success))
# Print the return values
if success.value > 0:
veh_acceleration=veh_autonomous_operational_acceleration.value
#print(veh_autonomous_operational_mixingmode.value)
#print(veh_autonomous_operational_warning.value)
veh_cc_set_point=veh_cc_setpoint.value
veh_cruise_control_acceleration=veh_cruisecontrol_acceleration.value
else:
veh_acceleration=-999
veh_cc_setpoint=-999
veh_cruise_control_acceleration=-999
print('An error occurred while calling DLL')
return veh_acceleration,veh_cc_setpoint,veh_cruise_control_acceleration
Vissim = com.gencache.EnsureDispatch("Vissim.Vissim")
GlosaNetworkPath='D:\\Projects\\ENSEMBLE\\Vissim_networks\\Pipeline'#'L:\\UserData\\Kingsley\\Ensemble'
#'L:\\UserData\\Kingsley\\SafeDriving'
#'L:\\UserData\\Kingsley\\Ensemble'#'C:\\Users\\Public\\Documents\\GLOSA\\GlosaTrafficLight'
Filename= os.path.join(GlosaNetworkPath, 'Pipeline.inpx')
#os.path.join(GlosaNetworkPath, 'KnooppuntZonzeelBackup.inpx') #os.path.join(GlosaNetworkPath, 'GlosaTestNetwork2.inpx')
#os.path.join(GlosaNetworkPath, 'TestNetwork.inpx')
flag_read_additionally = False # you can read network(elements) additionally, in this case set "flag_read_additionally" to true
Vissim.LoadNet(Filename, flag_read_additionally)
## Load a Layout:
Filename = os.path.join(GlosaNetworkPath, 'Pipeline.layx')
#os.path.join(GlosaNetworkPath, 'KnooppuntZonzeelBackup.layx')
#os.path.join(GlosaNetworkPath, 'TestNetwork.layx')
#os.path.join(GlosaNetworkPath, 'KnooppuntZonzeelBackup.layx')#os.path.join(GlosaNetworkPath, 'GlosaTestNetwork2.layx')
Vissim.LoadLayout(Filename)
End_of_simulation = 6000 # simulation second [s]
Simulation_Resolution = 10 # simulation second [s]
Number_Runs=4
Simulation_Period=300
Vissim.Simulation.SetAttValue('SimRes', Simulation_Resolution)
Vissim.Simulation.SetAttValue('NumRuns', Number_Runs)
Vissim.Simulation.SetAttValue('SimPeriod', Simulation_Period)
#UDA6
#Vissim.Net.UserDefinedAttributes.AddUserDefinedDataAttribute(6,'Vehicle','vehAcceleration','vehAcceleration',2,0)
#Vissim.Net.UserDefinedAttributes.ItemByKey(6).SetAttValue('DefValue',-1)
#UDA6
Vissim.Net.UserDefinedAttributes.AddUserDefinedDataAttribute(3,'Vehicle','COM_cruise_control_Ac','COM_cruise_control_Ac',2,0)
Vissim.Net.UserDefinedAttributes.ItemByKey(3).SetAttValue('DefValue',-1)
#UDA
Vissim.Net.UserDefinedAttributes.AddUserDefinedDataAttribute(4,'Vehicle','COM_cc_setpoint','COM_cc_setpoint',2,0)
Vissim.Net.UserDefinedAttributes.ItemByKey(4).SetAttValue('DefValue',-1)
def get_leader_info(Vehicle):
lead_veh_id = Vehicle.AttValue('LeadTargNo')
lead_veh_type = Vehicle.AttValue('LeadTargType')
if lead_veh_type == 'VEHICLE' and lead_veh_id != None:
try:
front_vehicle = Vissim.Net.Vehicles.ItemByKey(lead_veh_id)
except:
front_vehicle = -1
else:
front_vehicle=-1
return front_vehicle
#prev_veh_cc_setpoint = np.zeros(number_of_vehicles)
for i in range(6000):
for Vehicle in Vissim.Net.Vehicles.FilteredBy("[VEHTYPE\\NO]=210"):
lead_veh=get_leader_info(Vehicle)
if lead_veh!=-1 and (Vehicle.AttValue('Lane')==lead_veh.AttValue('Lane')):
#simulation info
timestep=Vehicle.AttValue('SimSec')
#Ego Info
print((Vehicle.AttValue('Lane')))
veh_id=Vehicle.AttValue('No')
veh_setspeed=Vehicle.AttValue('DesSpeed')/3.6
veh_type=Vehicle.AttValue('VehType\\No')
veh_used_distance_headway=Vehicle.AttValue('FollowDistNet')
veh_used_rel_vel=(Vehicle.AttValue('Speed')-lead_veh.AttValue('Speed'))/3.6
veh_velocity=Vehicle.AttValue('Speed')/3.6
veh_distance_headway=Vehicle.AttValue('FollowDistNet')
prev_veh_executed_acceleration = Vehicle.AttValue('COM_Ac')
prev_veh_cc_setpoint = Vehicle.AttValue('COM_cc_setpoint')
prev_veh_cruisecontrol_acceleration=Vehicle.AttValue('COM_cruise_control_Ac')
#veh_executed_acceleration=a_prev[veh_id]
#veh_cc_setpoint=prev_veh_cc_setpoint[veh_id]
# Leader Info
lead_veh_acceleration=lead_veh.AttValue('Acceleration')
lead_veh_id=lead_veh.AttValue('No')
lead_veh_rel_velocity=(Vehicle.AttValue('Speed')-lead_veh.AttValue('Speed'))/3.6
lead_veh_type=lead_veh.AttValue('VehType\\No')
curr_veh_executed_acceleration,curr_veh_cc_set_point,curr_veh_cruisecontrol_acceleration=get_acceleration(lead_veh_acceleration,lead_veh_id,lead_veh_rel_velocity,lead_veh_type,timestep,
veh_id,veh_setspeed,veh_type,veh_used_distance_headway,veh_used_rel_vel,veh_velocity,
veh_distance_headway,prev_veh_executed_acceleration,
prev_veh_cc_setpoint,prev_veh_cruisecontrol_acceleration)
# a=call vehicle_model(curr_veh_executed_acceleration)
write_file('file_variables.txt')
Vehicle.SetAttValue('COM_Ac',curr_veh_executed_acceleration)
#Vehicle.SetAttValue('COM_Ac', a)
Vehicle.SetAttValue('COM_At',3)
Vehicle.SetAttValue('COM_cc_setpoint', curr_veh_cc_set_point)
Vehicle.SetAttValue('COM_cruise_control_Ac', curr_veh_cruisecontrol_acceleration)
else:
continue
Vissim.Simulation.RunSingleStep()
| true | true |
f72b9f3d90e40913efdff7e7d1f1b70359588488 | 15,361 | py | Python | main.py | SultanAbuGhazal/3detr | f9725ae655c6ced290c3ec2c53c07566350270f4 | [
"Apache-2.0"
] | null | null | null | main.py | SultanAbuGhazal/3detr | f9725ae655c6ced290c3ec2c53c07566350270f4 | [
"Apache-2.0"
] | null | null | null | main.py | SultanAbuGhazal/3detr | f9725ae655c6ced290c3ec2c53c07566350270f4 | [
"Apache-2.0"
] | null | null | null | # Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import os
import sys
import pickle
import numpy as np
import torch
from torch.multiprocessing import set_start_method
from torch.utils.data import DataLoader, DistributedSampler
# 3DETR codebase specific imports
from datasets import build_dataset
from engine import evaluate, train_one_epoch
from models import build_model
from optimizer import build_optimizer
from criterion import build_criterion
from utils.dist import init_distributed, is_distributed, is_primary, get_rank, barrier
from utils.misc import my_worker_init_fn
from utils.io import save_checkpoint, resume_if_possible
from utils.logger import Logger
def make_args_parser():
parser = argparse.ArgumentParser("3D Detection Using Transformers", add_help=False)
##### Optimizer #####
parser.add_argument("--base_lr", default=5e-4, type=float)
parser.add_argument("--warm_lr", default=1e-6, type=float)
parser.add_argument("--warm_lr_epochs", default=9, type=int)
parser.add_argument("--final_lr", default=1e-6, type=float)
parser.add_argument("--lr_scheduler", default="cosine", type=str)
parser.add_argument("--weight_decay", default=0.1, type=float)
parser.add_argument("--filter_biases_wd", default=False, action="store_true")
parser.add_argument(
"--clip_gradient", default=0.1, type=float, help="Max L2 norm of the gradient"
)
##### Model #####
parser.add_argument(
"--model_name",
default="3detr",
type=str,
help="Name of the model",
choices=["3detr"],
)
### Encoder
parser.add_argument(
"--enc_type", default="vanilla", choices=["masked", "maskedv2", "vanilla"]
)
# Below options are only valid for vanilla encoder
parser.add_argument("--enc_nlayers", default=3, type=int)
parser.add_argument("--enc_dim", default=256, type=int)
parser.add_argument("--enc_ffn_dim", default=128, type=int)
parser.add_argument("--enc_dropout", default=0.1, type=float)
parser.add_argument("--enc_nhead", default=4, type=int)
parser.add_argument("--enc_pos_embed", default=None, type=str)
parser.add_argument("--enc_activation", default="relu", type=str)
### Decoder
parser.add_argument("--dec_nlayers", default=8, type=int)
parser.add_argument("--dec_dim", default=256, type=int)
parser.add_argument("--dec_ffn_dim", default=256, type=int)
parser.add_argument("--dec_dropout", default=0.1, type=float)
parser.add_argument("--dec_nhead", default=4, type=int)
### MLP heads for predicting bounding boxes
parser.add_argument("--mlp_dropout", default=0.3, type=float)
parser.add_argument(
"--nsemcls",
default=-1,
type=int,
help="Number of semantic object classes. Can be inferred from dataset",
)
### Other model params
parser.add_argument("--preenc_npoints", default=2048, type=int)
parser.add_argument(
"--pos_embed", default="fourier", type=str, choices=["fourier", "sine"]
)
parser.add_argument("--nqueries", default=256, type=int)
parser.add_argument("--use_color", default=False, action="store_true")
##### Set Loss #####
### Matcher
parser.add_argument("--matcher_giou_cost", default=2, type=float)
parser.add_argument("--matcher_cls_cost", default=1, type=float)
parser.add_argument("--matcher_center_cost", default=0, type=float)
parser.add_argument("--matcher_objectness_cost", default=0, type=float)
### Loss Weights
parser.add_argument("--loss_giou_weight", default=0, type=float)
parser.add_argument("--loss_sem_cls_weight", default=1, type=float)
parser.add_argument(
"--loss_no_object_weight", default=0.2, type=float
) # "no object" or "background" class for detection
parser.add_argument("--loss_angle_cls_weight", default=0.1, type=float)
parser.add_argument("--loss_angle_reg_weight", default=0.5, type=float)
parser.add_argument("--loss_center_weight", default=5.0, type=float)
parser.add_argument("--loss_size_weight", default=1.0, type=float)
##### Dataset #####
parser.add_argument(
"--dataset_name", required=True, type=str, choices=["scannet", "sunrgbd"]
)
parser.add_argument(
"--dataset_root_dir",
type=str,
default=None,
help="Root directory containing the dataset files. \
If None, default values from scannet.py/sunrgbd.py are used",
)
# parser.add_argument(
# "--meta_data_dir",
# type=str,
# default=None,
# help="Root directory containing the metadata files. \
# If None, default values from scannet.py/sunrgbd.py are used",
# )
parser.add_argument("--dataset_num_workers", default=4, type=int)
parser.add_argument("--batchsize_per_gpu", default=8, type=int)
##### Training #####
parser.add_argument("--start_epoch", default=-1, type=int)
parser.add_argument("--max_epoch", default=720, type=int)
parser.add_argument("--eval_every_epoch", default=10, type=int)
parser.add_argument("--seed", default=0, type=int)
##### Testing #####
parser.add_argument("--test_only", default=False, action="store_true")
parser.add_argument("--test_ckpt", default=None, type=str)
##### I/O #####
parser.add_argument("--checkpoint_dir", default=None, type=str)
parser.add_argument("--log_every", default=10, type=int)
parser.add_argument("--log_metrics_every", default=20, type=int)
parser.add_argument("--save_separate_checkpoint_every_epoch", default=100, type=int)
##### Distributed Training #####
parser.add_argument("--ngpus", default=1, type=int)
parser.add_argument("--dist_url", default="tcp://localhost:12345", type=str)
return parser
def do_train(
args,
model,
model_no_ddp,
optimizer,
criterion,
dataset_config,
dataloaders,
best_val_metrics,
):
"""
Main training loop.
This trains the model for `args.max_epoch` epochs and tests the model after every `args.eval_every_epoch`.
We always evaluate the final checkpoint and report both the final AP and best AP on the val set.
"""
num_iters_per_epoch = len(dataloaders["train"])
num_iters_per_eval_epoch = len(dataloaders["test"])
print(f"Model is {model}")
print(f"Training started at epoch {args.start_epoch} until {args.max_epoch}.")
print(f"One training epoch = {num_iters_per_epoch} iters.")
print(f"One eval epoch = {num_iters_per_eval_epoch} iters.")
final_eval = os.path.join(args.checkpoint_dir, "final_eval.txt")
final_eval_pkl = os.path.join(args.checkpoint_dir, "final_eval.pkl")
if os.path.isfile(final_eval):
print(f"Found final eval file {final_eval}. Skipping training.")
return
logger = Logger(args.checkpoint_dir)
for epoch in range(args.start_epoch, args.max_epoch):
if is_distributed():
dataloaders["train_sampler"].set_epoch(epoch)
aps = train_one_epoch(
args,
epoch,
model,
optimizer,
criterion,
dataset_config,
dataloaders["train"],
logger,
)
# latest checkpoint is always stored in checkpoint.pth
save_checkpoint(
args.checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
filename="checkpoint.pth",
)
metrics = aps.compute_metrics()
metric_str = aps.metrics_to_str(metrics, per_class=False)
metrics_dict = aps.metrics_to_dict(metrics)
curr_iter = epoch * len(dataloaders["train"])
if is_primary():
print("==" * 10)
print(f"Epoch [{epoch}/{args.max_epoch}]; Metrics {metric_str}")
print("==" * 10)
logger.log_scalars(metrics_dict, curr_iter, prefix="Train/")
if (
epoch > 0
and args.save_separate_checkpoint_every_epoch > 0
and epoch % args.save_separate_checkpoint_every_epoch == 0
):
# separate checkpoints are stored as checkpoint_{epoch}.pth
save_checkpoint(
args.checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
)
if epoch % args.eval_every_epoch == 0 or epoch == (args.max_epoch - 1):
ap_calculator = evaluate(
args,
epoch,
model,
criterion,
dataset_config,
dataloaders["test"],
logger,
curr_iter,
)
metrics = ap_calculator.compute_metrics()
ap25 = metrics[0.25]["mAP"]
metric_str = ap_calculator.metrics_to_str(metrics, per_class=True)
metrics_dict = ap_calculator.metrics_to_dict(metrics)
if is_primary():
print("==" * 10)
print(f"Evaluate Epoch [{epoch}/{args.max_epoch}]; Metrics {metric_str}")
print("==" * 10)
logger.log_scalars(metrics_dict, curr_iter, prefix="Test/")
if is_primary() and (
len(best_val_metrics) == 0 or best_val_metrics[0.25]["mAP"] < ap25
):
best_val_metrics = metrics
filename = "checkpoint_best.pth"
save_checkpoint(
args.checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
filename=filename,
)
print(
f"Epoch [{epoch}/{args.max_epoch}] saved current best val checkpoint at {filename}; ap25 {ap25}"
)
# always evaluate last checkpoint
epoch = args.max_epoch - 1
curr_iter = epoch * len(dataloaders["train"])
ap_calculator = evaluate(
args,
epoch,
model,
criterion,
dataset_config,
dataloaders["test"],
logger,
curr_iter,
)
metrics = ap_calculator.compute_metrics()
metric_str = ap_calculator.metrics_to_str(metrics)
if is_primary():
print("==" * 10)
print(f"Evaluate Final [{epoch}/{args.max_epoch}]; Metrics {metric_str}")
print("==" * 10)
with open(final_eval, "w") as fh:
fh.write("Training Finished.\n")
fh.write("==" * 10)
fh.write("Final Eval Numbers.\n")
fh.write(metric_str)
fh.write("\n")
fh.write("==" * 10)
fh.write("Best Eval Numbers.\n")
fh.write(ap_calculator.metrics_to_str(best_val_metrics))
fh.write("\n")
with open(final_eval_pkl, "wb") as fh:
pickle.dump(metrics, fh)
def test_model(args, model, model_no_ddp, criterion, dataset_config, dataloaders):
if args.test_ckpt is None or not os.path.isfile(args.test_ckpt):
f"Please specify a test checkpoint using --test_ckpt. Found invalid value {args.test_ckpt}"
sys.exit(1)
sd = torch.load(args.test_ckpt, map_location=torch.device("cpu"))
model_no_ddp.load_state_dict(sd["model"])
logger = Logger()
criterion = None # do not compute loss for speed-up; Comment out to see test loss
epoch = -1
curr_iter = 0
ap_calculator = evaluate(
args,
epoch,
model,
criterion,
dataset_config,
dataloaders["test"],
logger,
curr_iter,
)
metrics = ap_calculator.compute_metrics()
metric_str = ap_calculator.metrics_to_str(metrics)
if is_primary():
print("==" * 10)
print(f"Test model; Metrics {metric_str}")
print("==" * 10)
def main(local_rank, args):
if args.ngpus > 1:
print(
"Initializing Distributed Training. This is in BETA mode and hasn't been tested thoroughly. Use at your own risk :)"
)
print("To get the maximum speed-up consider reducing evaluations on val set by setting --eval_every_epoch to greater than 50")
init_distributed(
local_rank,
global_rank=local_rank,
world_size=args.ngpus,
dist_url=args.dist_url,
dist_backend="nccl",
)
print(f"Called with args: {args}")
torch.cuda.set_device(local_rank)
np.random.seed(args.seed + get_rank())
torch.manual_seed(args.seed + get_rank())
if torch.cuda.is_available():
torch.cuda.manual_seed_all(args.seed + get_rank())
datasets, dataset_config = build_dataset(args)
model, _ = build_model(args, dataset_config)
model = model.cuda(local_rank)
model_no_ddp = model
if is_distributed():
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[local_rank]
)
criterion = build_criterion(args, dataset_config)
criterion = criterion.cuda(local_rank)
dataloaders = {}
if args.test_only:
dataset_splits = ["test"]
else:
dataset_splits = ["train", "test"]
for split in dataset_splits:
if split == "train":
shuffle = True
else:
shuffle = False
if is_distributed():
sampler = DistributedSampler(datasets[split], shuffle=shuffle)
elif shuffle:
sampler = torch.utils.data.RandomSampler(datasets[split])
else:
sampler = torch.utils.data.SequentialSampler(datasets[split])
dataloaders[split] = DataLoader(
datasets[split],
sampler=sampler,
batch_size=args.batchsize_per_gpu,
num_workers=args.dataset_num_workers,
worker_init_fn=my_worker_init_fn,
)
dataloaders[split + "_sampler"] = sampler
if args.test_only:
criterion = None # faster evaluation
test_model(args, model, model_no_ddp, criterion, dataset_config, dataloaders)
else:
assert (
args.checkpoint_dir is not None
), f"Please specify a checkpoint dir using --checkpoint_dir"
if is_primary() and not os.path.isdir(args.checkpoint_dir):
os.makedirs(args.checkpoint_dir, exist_ok=True)
optimizer = build_optimizer(args, model_no_ddp)
loaded_epoch, best_val_metrics = resume_if_possible(
args.checkpoint_dir, model_no_ddp, optimizer
)
args.start_epoch = loaded_epoch + 1
do_train(
args,
model,
model_no_ddp,
optimizer,
criterion,
dataset_config,
dataloaders,
best_val_metrics,
)
def launch_distributed(args):
world_size = args.ngpus
if world_size == 1:
main(local_rank=0, args=args)
else:
torch.multiprocessing.spawn(main, nprocs=world_size, args=(args,))
if __name__ == "__main__":
parser = make_args_parser()
args = parser.parse_args()
try:
set_start_method("spawn")
except RuntimeError:
pass
launch_distributed(args)
| 35.312644 | 134 | 0.621639 |
import argparse
import os
import sys
import pickle
import numpy as np
import torch
from torch.multiprocessing import set_start_method
from torch.utils.data import DataLoader, DistributedSampler
from datasets import build_dataset
from engine import evaluate, train_one_epoch
from models import build_model
from optimizer import build_optimizer
from criterion import build_criterion
from utils.dist import init_distributed, is_distributed, is_primary, get_rank, barrier
from utils.misc import my_worker_init_fn
from utils.io import save_checkpoint, resume_if_possible
from utils.logger import Logger
def make_args_parser():
parser = argparse.ArgumentParser("3D Detection Using Transformers", add_help=False)
--warm_lr", default=1e-6, type=float)
parser.add_argument("--warm_lr_epochs", default=9, type=int)
parser.add_argument("--final_lr", default=1e-6, type=float)
parser.add_argument("--lr_scheduler", default="cosine", type=str)
parser.add_argument("--weight_decay", default=0.1, type=float)
parser.add_argument("--filter_biases_wd", default=False, action="store_true")
parser.add_argument(
"--clip_gradient", default=0.1, type=float, help="Max L2 norm of the gradient"
)
,
type=str,
help="Name of the model",
choices=["3detr"],
)
ument(
"--enc_type", default="vanilla", choices=["masked", "maskedv2", "vanilla"]
)
parser.add_argument("--enc_nlayers", default=3, type=int)
parser.add_argument("--enc_dim", default=256, type=int)
parser.add_argument("--enc_ffn_dim", default=128, type=int)
parser.add_argument("--enc_dropout", default=0.1, type=float)
parser.add_argument("--enc_nhead", default=4, type=int)
parser.add_argument("--enc_pos_embed", default=None, type=str)
parser.add_argument("--enc_activation", default="relu", type=str)
ument("--dec_nlayers", default=8, type=int)
parser.add_argument("--dec_dim", default=256, type=int)
parser.add_argument("--dec_ffn_dim", default=256, type=int)
parser.add_argument("--dec_dropout", default=0.1, type=float)
parser.add_argument("--dec_nhead", default=4, type=int)
rgument(
"--nsemcls",
default=-1,
type=int,
help="Number of semantic object classes. Can be inferred from dataset",
)
s", default=2048, type=int)
parser.add_argument(
"--pos_embed", default="fourier", type=str, choices=["fourier", "sine"]
)
parser.add_argument("--nqueries", default=256, type=int)
parser.add_argument("--use_color", default=False, action="store_true")
atcher_cls_cost", default=1, type=float)
parser.add_argument("--matcher_center_cost", default=0, type=float)
parser.add_argument("--matcher_objectness_cost", default=0, type=float)
oss_giou_weight", default=0, type=float)
parser.add_argument("--loss_sem_cls_weight", default=1, type=float)
parser.add_argument(
"--loss_no_object_weight", default=0.2, type=float
)
parser.add_argument("--loss_angle_cls_weight", default=0.1, type=float)
parser.add_argument("--loss_angle_reg_weight", default=0.5, type=float)
parser.add_argument("--loss_center_weight", default=5.0, type=float)
parser.add_argument("--loss_size_weight", default=1.0, type=float)
ces=["scannet", "sunrgbd"]
)
parser.add_argument(
"--dataset_root_dir",
type=str,
default=None,
help="Root directory containing the dataset files. \
If None, default values from scannet.py/sunrgbd.py are used",
)
# If None, default values from scannet.py/sunrgbd.py are used",
parser.add_argument("--dataset_num_workers", default=4, type=int)
parser.add_argument("--batchsize_per_gpu", default=8, type=int)
nt("--max_epoch", default=720, type=int)
parser.add_argument("--eval_every_epoch", default=10, type=int)
parser.add_argument("--seed", default=0, type=int)
arser.add_argument("--test_ckpt", default=None, type=str)
tr)
parser.add_argument("--log_every", default=10, type=int)
parser.add_argument("--log_metrics_every", default=20, type=int)
parser.add_argument("--save_separate_checkpoint_every_epoch", default=100, type=int)
str)
return parser
def do_train(
args,
model,
model_no_ddp,
optimizer,
criterion,
dataset_config,
dataloaders,
best_val_metrics,
):
num_iters_per_epoch = len(dataloaders["train"])
num_iters_per_eval_epoch = len(dataloaders["test"])
print(f"Model is {model}")
print(f"Training started at epoch {args.start_epoch} until {args.max_epoch}.")
print(f"One training epoch = {num_iters_per_epoch} iters.")
print(f"One eval epoch = {num_iters_per_eval_epoch} iters.")
final_eval = os.path.join(args.checkpoint_dir, "final_eval.txt")
final_eval_pkl = os.path.join(args.checkpoint_dir, "final_eval.pkl")
if os.path.isfile(final_eval):
print(f"Found final eval file {final_eval}. Skipping training.")
return
logger = Logger(args.checkpoint_dir)
for epoch in range(args.start_epoch, args.max_epoch):
if is_distributed():
dataloaders["train_sampler"].set_epoch(epoch)
aps = train_one_epoch(
args,
epoch,
model,
optimizer,
criterion,
dataset_config,
dataloaders["train"],
logger,
)
save_checkpoint(
args.checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
filename="checkpoint.pth",
)
metrics = aps.compute_metrics()
metric_str = aps.metrics_to_str(metrics, per_class=False)
metrics_dict = aps.metrics_to_dict(metrics)
curr_iter = epoch * len(dataloaders["train"])
if is_primary():
print("==" * 10)
print(f"Epoch [{epoch}/{args.max_epoch}]; Metrics {metric_str}")
print("==" * 10)
logger.log_scalars(metrics_dict, curr_iter, prefix="Train/")
if (
epoch > 0
and args.save_separate_checkpoint_every_epoch > 0
and epoch % args.save_separate_checkpoint_every_epoch == 0
):
save_checkpoint(
args.checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
)
if epoch % args.eval_every_epoch == 0 or epoch == (args.max_epoch - 1):
ap_calculator = evaluate(
args,
epoch,
model,
criterion,
dataset_config,
dataloaders["test"],
logger,
curr_iter,
)
metrics = ap_calculator.compute_metrics()
ap25 = metrics[0.25]["mAP"]
metric_str = ap_calculator.metrics_to_str(metrics, per_class=True)
metrics_dict = ap_calculator.metrics_to_dict(metrics)
if is_primary():
print("==" * 10)
print(f"Evaluate Epoch [{epoch}/{args.max_epoch}]; Metrics {metric_str}")
print("==" * 10)
logger.log_scalars(metrics_dict, curr_iter, prefix="Test/")
if is_primary() and (
len(best_val_metrics) == 0 or best_val_metrics[0.25]["mAP"] < ap25
):
best_val_metrics = metrics
filename = "checkpoint_best.pth"
save_checkpoint(
args.checkpoint_dir,
model_no_ddp,
optimizer,
epoch,
args,
best_val_metrics,
filename=filename,
)
print(
f"Epoch [{epoch}/{args.max_epoch}] saved current best val checkpoint at {filename}; ap25 {ap25}"
)
epoch = args.max_epoch - 1
curr_iter = epoch * len(dataloaders["train"])
ap_calculator = evaluate(
args,
epoch,
model,
criterion,
dataset_config,
dataloaders["test"],
logger,
curr_iter,
)
metrics = ap_calculator.compute_metrics()
metric_str = ap_calculator.metrics_to_str(metrics)
if is_primary():
print("==" * 10)
print(f"Evaluate Final [{epoch}/{args.max_epoch}]; Metrics {metric_str}")
print("==" * 10)
with open(final_eval, "w") as fh:
fh.write("Training Finished.\n")
fh.write("==" * 10)
fh.write("Final Eval Numbers.\n")
fh.write(metric_str)
fh.write("\n")
fh.write("==" * 10)
fh.write("Best Eval Numbers.\n")
fh.write(ap_calculator.metrics_to_str(best_val_metrics))
fh.write("\n")
with open(final_eval_pkl, "wb") as fh:
pickle.dump(metrics, fh)
def test_model(args, model, model_no_ddp, criterion, dataset_config, dataloaders):
if args.test_ckpt is None or not os.path.isfile(args.test_ckpt):
f"Please specify a test checkpoint using --test_ckpt. Found invalid value {args.test_ckpt}"
sys.exit(1)
sd = torch.load(args.test_ckpt, map_location=torch.device("cpu"))
model_no_ddp.load_state_dict(sd["model"])
logger = Logger()
criterion = None
epoch = -1
curr_iter = 0
ap_calculator = evaluate(
args,
epoch,
model,
criterion,
dataset_config,
dataloaders["test"],
logger,
curr_iter,
)
metrics = ap_calculator.compute_metrics()
metric_str = ap_calculator.metrics_to_str(metrics)
if is_primary():
print("==" * 10)
print(f"Test model; Metrics {metric_str}")
print("==" * 10)
def main(local_rank, args):
if args.ngpus > 1:
print(
"Initializing Distributed Training. This is in BETA mode and hasn't been tested thoroughly. Use at your own risk :)"
)
print("To get the maximum speed-up consider reducing evaluations on val set by setting --eval_every_epoch to greater than 50")
init_distributed(
local_rank,
global_rank=local_rank,
world_size=args.ngpus,
dist_url=args.dist_url,
dist_backend="nccl",
)
print(f"Called with args: {args}")
torch.cuda.set_device(local_rank)
np.random.seed(args.seed + get_rank())
torch.manual_seed(args.seed + get_rank())
if torch.cuda.is_available():
torch.cuda.manual_seed_all(args.seed + get_rank())
datasets, dataset_config = build_dataset(args)
model, _ = build_model(args, dataset_config)
model = model.cuda(local_rank)
model_no_ddp = model
if is_distributed():
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = torch.nn.parallel.DistributedDataParallel(
model, device_ids=[local_rank]
)
criterion = build_criterion(args, dataset_config)
criterion = criterion.cuda(local_rank)
dataloaders = {}
if args.test_only:
dataset_splits = ["test"]
else:
dataset_splits = ["train", "test"]
for split in dataset_splits:
if split == "train":
shuffle = True
else:
shuffle = False
if is_distributed():
sampler = DistributedSampler(datasets[split], shuffle=shuffle)
elif shuffle:
sampler = torch.utils.data.RandomSampler(datasets[split])
else:
sampler = torch.utils.data.SequentialSampler(datasets[split])
dataloaders[split] = DataLoader(
datasets[split],
sampler=sampler,
batch_size=args.batchsize_per_gpu,
num_workers=args.dataset_num_workers,
worker_init_fn=my_worker_init_fn,
)
dataloaders[split + "_sampler"] = sampler
if args.test_only:
criterion = None # faster evaluation
test_model(args, model, model_no_ddp, criterion, dataset_config, dataloaders)
else:
assert (
args.checkpoint_dir is not None
), f"Please specify a checkpoint dir using --checkpoint_dir"
if is_primary() and not os.path.isdir(args.checkpoint_dir):
os.makedirs(args.checkpoint_dir, exist_ok=True)
optimizer = build_optimizer(args, model_no_ddp)
loaded_epoch, best_val_metrics = resume_if_possible(
args.checkpoint_dir, model_no_ddp, optimizer
)
args.start_epoch = loaded_epoch + 1
do_train(
args,
model,
model_no_ddp,
optimizer,
criterion,
dataset_config,
dataloaders,
best_val_metrics,
)
def launch_distributed(args):
world_size = args.ngpus
if world_size == 1:
main(local_rank=0, args=args)
else:
torch.multiprocessing.spawn(main, nprocs=world_size, args=(args,))
if __name__ == "__main__":
parser = make_args_parser()
args = parser.parse_args()
try:
set_start_method("spawn")
except RuntimeError:
pass
launch_distributed(args)
| true | true |
f72ba096355b4c9e07406e66b05f1d1a8c1dce09 | 9,312 | py | Python | metadata-ingestion/src/datahub/ingestion/source/ldap.py | zhongjinhan/datahub | 3bf5ffab5db02bed21d9b04fd65860927fce8088 | [
"Apache-2.0"
] | null | null | null | metadata-ingestion/src/datahub/ingestion/source/ldap.py | zhongjinhan/datahub | 3bf5ffab5db02bed21d9b04fd65860927fce8088 | [
"Apache-2.0"
] | 1 | 2021-03-09T19:40:53.000Z | 2021-03-15T17:36:26.000Z | metadata-ingestion/src/datahub/ingestion/source/ldap.py | zhongjinhan/datahub | 3bf5ffab5db02bed21d9b04fd65860927fce8088 | [
"Apache-2.0"
] | null | null | null | """LDAP Source"""
from dataclasses import dataclass
from typing import Any, Dict, Iterable, List, Optional
import ldap
from ldap.controls import SimplePagedResultsControl
from datahub.configuration.common import ConfigModel, ConfigurationError
from datahub.ingestion.api.common import PipelineContext
from datahub.ingestion.api.source import Source, SourceReport
from datahub.ingestion.source.metadata_common import MetadataWorkUnit
from datahub.metadata.com.linkedin.pegasus2avro.mxe import MetadataChangeEvent
from datahub.metadata.schema_classes import (
CorpGroupInfoClass,
CorpGroupSnapshotClass,
CorpUserInfoClass,
CorpUserSnapshotClass,
)
def create_controls(pagesize: int) -> SimplePagedResultsControl:
"""
Create an LDAP control with a page size of "pagesize".
"""
return SimplePagedResultsControl(True, size=pagesize, cookie="")
def get_pctrls(
serverctrls: List[SimplePagedResultsControl],
) -> List[SimplePagedResultsControl]:
"""
Lookup an LDAP paged control object from the returned controls.
"""
return [
c for c in serverctrls if c.controlType == SimplePagedResultsControl.controlType
]
def set_cookie(
lc_object: SimplePagedResultsControl,
pctrls: List[SimplePagedResultsControl],
) -> bool:
"""
Push latest cookie back into the page control.
"""
cookie = pctrls[0].cookie
lc_object.cookie = cookie
return bool(cookie)
def guess_person_ldap(attrs: Dict[str, Any]) -> Optional[str]:
"""Determine the user's LDAP based on the DN and attributes."""
if "sAMAccountName" in attrs:
return attrs["sAMAccountName"][0].decode()
if "uid" in attrs:
return attrs["uid"][0].decode()
return None
class LDAPSourceConfig(ConfigModel):
"""Config used by the LDAP Source."""
# Server configuration.
ldap_server: str
ldap_user: str
ldap_password: str
# Extraction configuration.
base_dn: str
filter: str = "(objectClass=*)"
page_size: int = 20
@dataclass
class LDAPSource(Source):
"""LDAP Source Class."""
config: LDAPSourceConfig
report: SourceReport
def __init__(self, ctx: PipelineContext, config: LDAPSourceConfig):
"""Constructor."""
super().__init__(ctx)
self.config = config
self.report = SourceReport()
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
ldap.set_option(ldap.OPT_REFERRALS, 0)
self.ldap_client = ldap.initialize(self.config.ldap_server)
self.ldap_client.protocol_version = 3
try:
self.ldap_client.simple_bind_s(
self.config.ldap_user, self.config.ldap_password
)
except ldap.LDAPError as e:
raise ConfigurationError("LDAP connection failed") from e
self.lc = create_controls(self.config.page_size)
@classmethod
def create(cls, config_dict: Dict[str, Any], ctx: PipelineContext) -> "LDAPSource":
"""Factory method."""
config = LDAPSourceConfig.parse_obj(config_dict)
return cls(ctx, config)
def get_workunits(self) -> Iterable[MetadataWorkUnit]:
"""Returns an Iterable containing the workunits to ingest LDAP users or groups."""
cookie = True
while cookie:
try:
msgid = self.ldap_client.search_ext(
self.config.base_dn,
ldap.SCOPE_SUBTREE,
self.config.filter,
serverctrls=[self.lc],
)
_rtype, rdata, _rmsgid, serverctrls = self.ldap_client.result3(msgid)
except ldap.LDAPError as e:
self.report.report_failure(
"ldap-control", "LDAP search failed: {}".format(e)
)
break
for dn, attrs in rdata:
if (
b"inetOrgPerson" in attrs["objectClass"]
or b"posixAccount" in attrs["objectClass"]
):
yield from self.handle_user(dn, attrs)
if (
b"posixGroup" in attrs["objectClass"]
or b"organizationalUnit" in attrs["objectClass"]
):
yield from self.handle_group(dn, attrs)
pctrls = get_pctrls(serverctrls)
if not pctrls:
self.report.report_failure(
"ldap-control", "Server ignores RFC 2696 control."
)
break
cookie = set_cookie(self.lc, pctrls)
def handle_user(self, dn: str, attrs: Dict[str, Any]) -> Iterable[MetadataWorkUnit]:
"""
Handle a DN and attributes by adding manager info and constructing a
work unit based on the information.
"""
manager_ldap = None
if "manager" in attrs:
try:
m_cn = attrs["manager"][0].split(b",")[0]
manager_msgid = self.ldap_client.search_ext(
self.config.base_dn,
ldap.SCOPE_SUBTREE,
f"({m_cn.decode()})",
serverctrls=[self.lc],
)
_m_dn, m_attrs = self.ldap_client.result3(manager_msgid)[1][0]
manager_ldap = guess_person_ldap(m_attrs)
except ldap.LDAPError as e:
self.report.report_warning(
dn, "manager LDAP search failed: {}".format(e)
)
mce = self.build_corp_user_mce(dn, attrs, manager_ldap)
if mce:
wu = MetadataWorkUnit(dn, mce)
self.report.report_workunit(wu)
yield wu
yield from []
def handle_group(
self, dn: str, attrs: Dict[str, Any]
) -> Iterable[MetadataWorkUnit]:
"""Creates a workunit for LDAP groups."""
mce = self.build_corp_group_mce(attrs)
if mce:
wu = MetadataWorkUnit(dn, mce)
self.report.report_workunit(wu)
yield wu
yield from []
def build_corp_user_mce(
self, dn: str, attrs: dict, manager_ldap: Optional[str]
) -> Optional[MetadataChangeEvent]:
"""
Create the MetadataChangeEvent via DN and attributes.
"""
ldap_user = guess_person_ldap(attrs)
full_name = attrs["cn"][0].decode()
first_name = attrs["givenName"][0].decode()
last_name = attrs["sn"][0].decode()
email = (attrs["mail"][0]).decode() if "mail" in attrs else ldap_user
display_name = (
(attrs["displayName"][0]).decode() if "displayName" in attrs else full_name
)
department = (
(attrs["departmentNumber"][0]).decode()
if "departmentNumber" in attrs
else None
)
title = attrs["title"][0].decode() if "title" in attrs else None
manager_urn = f"urn:li:corpuser:{manager_ldap}" if manager_ldap else None
return MetadataChangeEvent(
proposedSnapshot=CorpUserSnapshotClass(
urn=f"urn:li:corpuser:{ldap_user}",
aspects=[
CorpUserInfoClass(
active=True,
email=email,
fullName=full_name,
firstName=first_name,
lastName=last_name,
departmentName=department,
displayName=display_name,
title=title,
managerUrn=manager_urn,
)
],
)
)
def build_corp_group_mce(self, attrs: dict) -> Optional[MetadataChangeEvent]:
"""Creates a MetadataChangeEvent for LDAP groups."""
cn = attrs.get("cn")
if cn:
full_name = cn[0].decode()
owners = parse_from_attrs(attrs, "owner")
members = parse_from_attrs(attrs, "uniqueMember")
email = attrs["mail"][0].decode() if "mail" in attrs else full_name
return MetadataChangeEvent(
proposedSnapshot=CorpGroupSnapshotClass(
urn=f"urn:li:corpGroup:{full_name}",
aspects=[
CorpGroupInfoClass(
email=email,
admins=owners,
members=members,
groups=[],
)
],
)
)
return None
def get_report(self) -> SourceReport:
"""Returns the sourcereport."""
return self.report
def close(self) -> None:
"""Closes the Source."""
self.ldap_client.unbind()
def parse_from_attrs(attrs: Dict[str, Any], filter_key: str) -> List[str]:
"""Converts a list of LDAP formats to Datahub corpuser strings."""
if filter_key in attrs:
return [
f"urn:li:corpuser:{strip_ldap_info(ldap_user)}"
for ldap_user in attrs[filter_key]
]
return []
def strip_ldap_info(input_clean: bytes) -> str:
"""Converts a b'uid=username,ou=Groups,dc=internal,dc=machines'
format to username"""
return input_clean.decode().split(",")[0].lstrip("uid=")
| 33.376344 | 90 | 0.575387 | from dataclasses import dataclass
from typing import Any, Dict, Iterable, List, Optional
import ldap
from ldap.controls import SimplePagedResultsControl
from datahub.configuration.common import ConfigModel, ConfigurationError
from datahub.ingestion.api.common import PipelineContext
from datahub.ingestion.api.source import Source, SourceReport
from datahub.ingestion.source.metadata_common import MetadataWorkUnit
from datahub.metadata.com.linkedin.pegasus2avro.mxe import MetadataChangeEvent
from datahub.metadata.schema_classes import (
CorpGroupInfoClass,
CorpGroupSnapshotClass,
CorpUserInfoClass,
CorpUserSnapshotClass,
)
def create_controls(pagesize: int) -> SimplePagedResultsControl:
return SimplePagedResultsControl(True, size=pagesize, cookie="")
def get_pctrls(
serverctrls: List[SimplePagedResultsControl],
) -> List[SimplePagedResultsControl]:
return [
c for c in serverctrls if c.controlType == SimplePagedResultsControl.controlType
]
def set_cookie(
lc_object: SimplePagedResultsControl,
pctrls: List[SimplePagedResultsControl],
) -> bool:
cookie = pctrls[0].cookie
lc_object.cookie = cookie
return bool(cookie)
def guess_person_ldap(attrs: Dict[str, Any]) -> Optional[str]:
if "sAMAccountName" in attrs:
return attrs["sAMAccountName"][0].decode()
if "uid" in attrs:
return attrs["uid"][0].decode()
return None
class LDAPSourceConfig(ConfigModel):
ldap_server: str
ldap_user: str
ldap_password: str
base_dn: str
filter: str = "(objectClass=*)"
page_size: int = 20
@dataclass
class LDAPSource(Source):
config: LDAPSourceConfig
report: SourceReport
def __init__(self, ctx: PipelineContext, config: LDAPSourceConfig):
super().__init__(ctx)
self.config = config
self.report = SourceReport()
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
ldap.set_option(ldap.OPT_REFERRALS, 0)
self.ldap_client = ldap.initialize(self.config.ldap_server)
self.ldap_client.protocol_version = 3
try:
self.ldap_client.simple_bind_s(
self.config.ldap_user, self.config.ldap_password
)
except ldap.LDAPError as e:
raise ConfigurationError("LDAP connection failed") from e
self.lc = create_controls(self.config.page_size)
@classmethod
def create(cls, config_dict: Dict[str, Any], ctx: PipelineContext) -> "LDAPSource":
config = LDAPSourceConfig.parse_obj(config_dict)
return cls(ctx, config)
def get_workunits(self) -> Iterable[MetadataWorkUnit]:
cookie = True
while cookie:
try:
msgid = self.ldap_client.search_ext(
self.config.base_dn,
ldap.SCOPE_SUBTREE,
self.config.filter,
serverctrls=[self.lc],
)
_rtype, rdata, _rmsgid, serverctrls = self.ldap_client.result3(msgid)
except ldap.LDAPError as e:
self.report.report_failure(
"ldap-control", "LDAP search failed: {}".format(e)
)
break
for dn, attrs in rdata:
if (
b"inetOrgPerson" in attrs["objectClass"]
or b"posixAccount" in attrs["objectClass"]
):
yield from self.handle_user(dn, attrs)
if (
b"posixGroup" in attrs["objectClass"]
or b"organizationalUnit" in attrs["objectClass"]
):
yield from self.handle_group(dn, attrs)
pctrls = get_pctrls(serverctrls)
if not pctrls:
self.report.report_failure(
"ldap-control", "Server ignores RFC 2696 control."
)
break
cookie = set_cookie(self.lc, pctrls)
def handle_user(self, dn: str, attrs: Dict[str, Any]) -> Iterable[MetadataWorkUnit]:
manager_ldap = None
if "manager" in attrs:
try:
m_cn = attrs["manager"][0].split(b",")[0]
manager_msgid = self.ldap_client.search_ext(
self.config.base_dn,
ldap.SCOPE_SUBTREE,
f"({m_cn.decode()})",
serverctrls=[self.lc],
)
_m_dn, m_attrs = self.ldap_client.result3(manager_msgid)[1][0]
manager_ldap = guess_person_ldap(m_attrs)
except ldap.LDAPError as e:
self.report.report_warning(
dn, "manager LDAP search failed: {}".format(e)
)
mce = self.build_corp_user_mce(dn, attrs, manager_ldap)
if mce:
wu = MetadataWorkUnit(dn, mce)
self.report.report_workunit(wu)
yield wu
yield from []
def handle_group(
self, dn: str, attrs: Dict[str, Any]
) -> Iterable[MetadataWorkUnit]:
mce = self.build_corp_group_mce(attrs)
if mce:
wu = MetadataWorkUnit(dn, mce)
self.report.report_workunit(wu)
yield wu
yield from []
def build_corp_user_mce(
self, dn: str, attrs: dict, manager_ldap: Optional[str]
) -> Optional[MetadataChangeEvent]:
ldap_user = guess_person_ldap(attrs)
full_name = attrs["cn"][0].decode()
first_name = attrs["givenName"][0].decode()
last_name = attrs["sn"][0].decode()
email = (attrs["mail"][0]).decode() if "mail" in attrs else ldap_user
display_name = (
(attrs["displayName"][0]).decode() if "displayName" in attrs else full_name
)
department = (
(attrs["departmentNumber"][0]).decode()
if "departmentNumber" in attrs
else None
)
title = attrs["title"][0].decode() if "title" in attrs else None
manager_urn = f"urn:li:corpuser:{manager_ldap}" if manager_ldap else None
return MetadataChangeEvent(
proposedSnapshot=CorpUserSnapshotClass(
urn=f"urn:li:corpuser:{ldap_user}",
aspects=[
CorpUserInfoClass(
active=True,
email=email,
fullName=full_name,
firstName=first_name,
lastName=last_name,
departmentName=department,
displayName=display_name,
title=title,
managerUrn=manager_urn,
)
],
)
)
def build_corp_group_mce(self, attrs: dict) -> Optional[MetadataChangeEvent]:
cn = attrs.get("cn")
if cn:
full_name = cn[0].decode()
owners = parse_from_attrs(attrs, "owner")
members = parse_from_attrs(attrs, "uniqueMember")
email = attrs["mail"][0].decode() if "mail" in attrs else full_name
return MetadataChangeEvent(
proposedSnapshot=CorpGroupSnapshotClass(
urn=f"urn:li:corpGroup:{full_name}",
aspects=[
CorpGroupInfoClass(
email=email,
admins=owners,
members=members,
groups=[],
)
],
)
)
return None
def get_report(self) -> SourceReport:
return self.report
def close(self) -> None:
self.ldap_client.unbind()
def parse_from_attrs(attrs: Dict[str, Any], filter_key: str) -> List[str]:
if filter_key in attrs:
return [
f"urn:li:corpuser:{strip_ldap_info(ldap_user)}"
for ldap_user in attrs[filter_key]
]
return []
def strip_ldap_info(input_clean: bytes) -> str:
return input_clean.decode().split(",")[0].lstrip("uid=")
| true | true |
f72ba1d7778091106a4581741203288c6ae24e0e | 1,378 | py | Python | tests/benchmarks/constructs/LocalVariableAssign.py | Mortal/Nuitka | 5150eeff7ff845ed4993c773449cd81b7f127c6b | [
"Apache-2.0"
] | null | null | null | tests/benchmarks/constructs/LocalVariableAssign.py | Mortal/Nuitka | 5150eeff7ff845ed4993c773449cd81b7f127c6b | [
"Apache-2.0"
] | null | null | null | tests/benchmarks/constructs/LocalVariableAssign.py | Mortal/Nuitka | 5150eeff7ff845ed4993c773449cd81b7f127c6b | [
"Apache-2.0"
] | 1 | 2018-12-16T23:51:18.000Z | 2018-12-16T23:51:18.000Z | # Copyright 2018, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python test originally created or extracted from other peoples work. The
# parts from me are licensed as below. It is at least Free Software where
# it's copied from other people. In these cases, that will normally be
# indicated.
#
# 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.
#
module_value1 = 1000
module_value2 = 50
def calledRepeatedly():
# Force frame and eliminate forward propagation (currently).
module_value1
local_value = module_value1
local_value2 = module_value2
# construct_begin
local_value2 = local_value * 2
# construct_alternative
local_value * 2
# construct_end
local_value2 = local_value * 4
return local_value
import itertools
for x in itertools.repeat(None, 50000):
calledRepeatedly()
print("OK.")
| 30.622222 | 78 | 0.722787 |
# indicated.
#
# 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.
#
module_value1 = 1000
module_value2 = 50
def calledRepeatedly():
# Force frame and eliminate forward propagation (currently).
module_value1
local_value = module_value1
local_value2 = module_value2
# construct_begin
local_value2 = local_value * 2
# construct_alternative
local_value * 2
# construct_end
local_value2 = local_value * 4
return local_value
import itertools
for x in itertools.repeat(None, 50000):
calledRepeatedly()
print("OK.")
| true | true |
f72ba2b63d4ac4e8dc4c0d2dd40a513c05d534df | 3,551 | py | Python | tests/test_graph.py | arky/followthemoney | e6e4f5749aadc51893d131aac9744e1184d12f92 | [
"MIT"
] | 137 | 2017-10-20T09:36:32.000Z | 2022-03-24T18:49:16.000Z | tests/test_graph.py | arky/followthemoney | e6e4f5749aadc51893d131aac9744e1184d12f92 | [
"MIT"
] | 505 | 2017-10-24T13:14:06.000Z | 2022-03-28T20:21:45.000Z | tests/test_graph.py | malteos/followthemoney | 7fde00488b4f2bf6acc69d922bd0ca9d2defbe0f | [
"MIT"
] | 32 | 2017-12-19T15:22:07.000Z | 2022-02-18T11:01:28.000Z | from unittest import TestCase
from followthemoney import model
from followthemoney.types import registry
from followthemoney.graph import Graph, Node
ENTITY = {
"id": "ralph",
"schema": "Person",
"properties": {
"name": ["Ralph Tester"],
"birthDate": ["1972-05-01"],
"idNumber": ["9177171", "8e839023"],
"website": ["https://ralphtester.me"],
"phone": ["+12025557612"],
"email": ["info@ralphtester.me"],
"topics": ["role.spy"],
},
}
ENTITY2 = {
"id": "jodie",
"schema": "Person",
"properties": {"name": ["Jodie Tester"], "birthDate": ["1972-05-01"]},
}
REL = {
"id": "jodie2ralph",
"schema": "Family",
"properties": {"person": ["jodie"], "relative": ["ralph"]},
}
PASS = {
"id": "passpoat",
"schema": "Passport",
"properties": {"holder": ["jodie"], "passportNumber": ["HJSJHAS"]},
}
class GraphTestCase(TestCase):
def test_basic_graph(self):
proxy = model.get_proxy(ENTITY, cleaned=False)
graph = Graph(edge_types=registry.pivots)
graph.add(proxy)
assert len(graph.iternodes()) > 1, graph.to_dict()
assert len(graph.proxies) == 1, graph.proxies
assert len(graph.queued) == 0, graph.proxies
graph.add(None)
assert len(graph.proxies) == 1, graph.proxies
assert len(graph.queued) == 0, graph.proxies
def test_adjacent(self):
graph = Graph(edge_types=registry.pivots)
graph.add(model.get_proxy(ENTITY, cleaned=False))
graph.add(model.get_proxy(ENTITY2, cleaned=False))
graph.add(model.get_proxy(REL, cleaned=False))
graph.add(model.get_proxy(PASS, cleaned=False))
node = Node(registry.entity, "jodie")
adj = list(graph.get_adjacent(node))
assert len(adj) == 3, adj
node = Node(registry.entity, "ralph")
adj = list(graph.get_adjacent(node))
assert len(adj) == 7, adj
node = Node(registry.entity, "passpoat")
adj = list(graph.get_adjacent(node))
assert len(adj) == 2, adj
node = Node(registry.entity, "passpoat")
prop = model.get_qname("Identification:holder")
adj = list(graph.get_adjacent(node, prop))
assert len(adj) == 1, adj
assert adj[0].source_prop == prop, adj[0].source_prop
assert adj[0].target_prop == prop.reverse, adj[0].target_prop
node = Node(registry.entity, "jodie")
prop = model.get_qname("Person:familyPerson")
adj = list(graph.get_adjacent(node, prop))
assert len(adj) == 1, adj
assert adj[0].source_prop == prop, adj[0].source_prop
node = Node(registry.entity, "ralph")
prop = model.get_qname("Person:familyRelative")
adj2 = list(graph.get_adjacent(node, prop))
assert len(adj2) == 1, adj2
assert adj2[0].target_prop == prop, adj2[0].target_prop
assert adj[0] == adj2[0], (adj[0], adj2[0])
assert adj[0].id in repr(adj[0]), repr(adj[0])
def test_to_dict(self):
proxy = model.get_proxy(ENTITY, cleaned=False)
graph = Graph(edge_types=registry.pivots)
graph.add(proxy)
data = graph.to_dict()
assert "nodes" in data, data
assert "edges" in data, data
def test_nodes(self):
node = Node(registry.phone, "+4917778271717")
assert "+49177" in repr(node), repr(node)
assert node == node, repr(node)
assert node.caption == str(node), str(node)
assert hash(node) == hash(node.id), repr(node)
| 33.819048 | 74 | 0.599549 | from unittest import TestCase
from followthemoney import model
from followthemoney.types import registry
from followthemoney.graph import Graph, Node
ENTITY = {
"id": "ralph",
"schema": "Person",
"properties": {
"name": ["Ralph Tester"],
"birthDate": ["1972-05-01"],
"idNumber": ["9177171", "8e839023"],
"website": ["https://ralphtester.me"],
"phone": ["+12025557612"],
"email": ["info@ralphtester.me"],
"topics": ["role.spy"],
},
}
ENTITY2 = {
"id": "jodie",
"schema": "Person",
"properties": {"name": ["Jodie Tester"], "birthDate": ["1972-05-01"]},
}
REL = {
"id": "jodie2ralph",
"schema": "Family",
"properties": {"person": ["jodie"], "relative": ["ralph"]},
}
PASS = {
"id": "passpoat",
"schema": "Passport",
"properties": {"holder": ["jodie"], "passportNumber": ["HJSJHAS"]},
}
class GraphTestCase(TestCase):
def test_basic_graph(self):
proxy = model.get_proxy(ENTITY, cleaned=False)
graph = Graph(edge_types=registry.pivots)
graph.add(proxy)
assert len(graph.iternodes()) > 1, graph.to_dict()
assert len(graph.proxies) == 1, graph.proxies
assert len(graph.queued) == 0, graph.proxies
graph.add(None)
assert len(graph.proxies) == 1, graph.proxies
assert len(graph.queued) == 0, graph.proxies
def test_adjacent(self):
graph = Graph(edge_types=registry.pivots)
graph.add(model.get_proxy(ENTITY, cleaned=False))
graph.add(model.get_proxy(ENTITY2, cleaned=False))
graph.add(model.get_proxy(REL, cleaned=False))
graph.add(model.get_proxy(PASS, cleaned=False))
node = Node(registry.entity, "jodie")
adj = list(graph.get_adjacent(node))
assert len(adj) == 3, adj
node = Node(registry.entity, "ralph")
adj = list(graph.get_adjacent(node))
assert len(adj) == 7, adj
node = Node(registry.entity, "passpoat")
adj = list(graph.get_adjacent(node))
assert len(adj) == 2, adj
node = Node(registry.entity, "passpoat")
prop = model.get_qname("Identification:holder")
adj = list(graph.get_adjacent(node, prop))
assert len(adj) == 1, adj
assert adj[0].source_prop == prop, adj[0].source_prop
assert adj[0].target_prop == prop.reverse, adj[0].target_prop
node = Node(registry.entity, "jodie")
prop = model.get_qname("Person:familyPerson")
adj = list(graph.get_adjacent(node, prop))
assert len(adj) == 1, adj
assert adj[0].source_prop == prop, adj[0].source_prop
node = Node(registry.entity, "ralph")
prop = model.get_qname("Person:familyRelative")
adj2 = list(graph.get_adjacent(node, prop))
assert len(adj2) == 1, adj2
assert adj2[0].target_prop == prop, adj2[0].target_prop
assert adj[0] == adj2[0], (adj[0], adj2[0])
assert adj[0].id in repr(adj[0]), repr(adj[0])
def test_to_dict(self):
proxy = model.get_proxy(ENTITY, cleaned=False)
graph = Graph(edge_types=registry.pivots)
graph.add(proxy)
data = graph.to_dict()
assert "nodes" in data, data
assert "edges" in data, data
def test_nodes(self):
node = Node(registry.phone, "+4917778271717")
assert "+49177" in repr(node), repr(node)
assert node == node, repr(node)
assert node.caption == str(node), str(node)
assert hash(node) == hash(node.id), repr(node)
| true | true |
f72ba3d5f708cc3f9400d201f0cc2f6315f72c8b | 832 | py | Python | tests_no_pytest/test_write.py | jzuhone/xija | 1e423d0c48056cc4ea9e4993d28e34794c1420fa | [
"BSD-3-Clause"
] | 2 | 2016-01-05T19:20:43.000Z | 2021-06-04T08:23:08.000Z | tests_no_pytest/test_write.py | jzuhone/xija | 1e423d0c48056cc4ea9e4993d28e34794c1420fa | [
"BSD-3-Clause"
] | 61 | 2015-02-24T02:27:11.000Z | 2022-03-23T13:52:15.000Z | tests_no_pytest/test_write.py | jzuhone/xija | 1e423d0c48056cc4ea9e4993d28e34794c1420fa | [
"BSD-3-Clause"
] | 1 | 2016-01-04T21:08:17.000Z | 2016-01-04T21:08:17.000Z | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import json
import numpy as np
import xija
mdl = xija.ThermalModel(start='2010:001', stop='2010:004')
tephin = mdl.add(xija.Node, 'tephin')
tcylaft6 = mdl.add(xija.Node, 'tcylaft6', predict=False)
coup_tephin_tcylaft6 = mdl.add(xija.Coupling, tephin, tcylaft6, tau=20)
aosares1 = mdl.add(xija.TelemData, 'aosares1')
tephin_solar = mdl.add(xija.SolarHeat, tephin, aosares1,
Ps=[0.1, 0.5, 1.0, 1.5, 2.0],
dPs=[0.01, 0.02, 0.03, 0.04, 0.05])
tephin_heatsink = mdl.add(xija.HeatSink, tephin, T=0.0, tau=20.0)
mdl.make()
mdl.write('test_write.json')
model_spec = json.load(open('test_write.json'))
mdl2 = xija.ThermalModel(start='2010:001', stop='2010:004', model_spec=model_spec)
os.unlink('test_write.json')
| 30.814815 | 82 | 0.68149 |
import os
import json
import numpy as np
import xija
mdl = xija.ThermalModel(start='2010:001', stop='2010:004')
tephin = mdl.add(xija.Node, 'tephin')
tcylaft6 = mdl.add(xija.Node, 'tcylaft6', predict=False)
coup_tephin_tcylaft6 = mdl.add(xija.Coupling, tephin, tcylaft6, tau=20)
aosares1 = mdl.add(xija.TelemData, 'aosares1')
tephin_solar = mdl.add(xija.SolarHeat, tephin, aosares1,
Ps=[0.1, 0.5, 1.0, 1.5, 2.0],
dPs=[0.01, 0.02, 0.03, 0.04, 0.05])
tephin_heatsink = mdl.add(xija.HeatSink, tephin, T=0.0, tau=20.0)
mdl.make()
mdl.write('test_write.json')
model_spec = json.load(open('test_write.json'))
mdl2 = xija.ThermalModel(start='2010:001', stop='2010:004', model_spec=model_spec)
os.unlink('test_write.json')
| true | true |
f72ba4bad6d7541d57491bf18fb1649b5f900db5 | 17,871 | py | Python | src/tests/test_api_functions.py | ArieLevs/NalkinsCloud-Django | 3fab970e4545db2e0b3e63a4bc8a5a1488a4a2bf | [
"Apache-2.0"
] | 6 | 2019-01-07T15:34:27.000Z | 2020-05-16T14:40:38.000Z | src/tests/test_api_functions.py | ArieLevs/NalkinsCloud-Django | 3fab970e4545db2e0b3e63a4bc8a5a1488a4a2bf | [
"Apache-2.0"
] | 9 | 2019-12-28T12:08:36.000Z | 2021-09-22T17:44:41.000Z | src/tests/test_api_functions.py | ArieLevs/NalkinsCloud-Django-Backend | 3fab970e4545db2e0b3e63a4bc8a5a1488a4a2bf | [
"Apache-2.0"
] | null | null | null |
from django.utils.crypto import get_random_string
from django.urls import reverse
from django.utils import timezone
from rest_framework.test import APITestCase
from oauth2_provider.models import AccessToken
from oauth2_provider.models import Application
from nalkinscloud_mosquitto.models import Device, DeviceType, DeviceModel, CustomerDevice
from django_user_email_extension.models import User
import datetime
import logging
from nalkinscloud_django.settings import PROJECT_NAME
# Define logger
logger = logging.getLogger(PROJECT_NAME)
class APIViewsTestCase(APITestCase):
def setUp(self):
# Create OAuth application
self.oauth_client_id = 'some_client_id'
self.oauth_client_secret = 'some_client_secret'
self.oauth_client = Application.objects.create(client_id=self.oauth_client_id,
client_secret=self.oauth_client_secret)
self.email = "test@nalkins.cloud"
self.password = "nalkinscloud"
# Generate basic test user
self.user = User.objects.create_user(
email=self.email,
password=self.password,
is_active=True
)
# Generate access token (oauth) for test user
expires = timezone.now() + datetime.timedelta(seconds=36000)
self.access_token = AccessToken.objects.create(
user=self.user,
application=self.oauth_client,
scope='',
token=get_random_string(length=32),
expires=expires)
self.access_token.save()
# Generate test device
self.device_id = 'api_test_device_id'
self.device_password = 'nalkinscloud'
self.device_model = 'esp8266'
self.device_type = 'dht'
self.device = Device.objects.create_device(device_id=self.device_id, password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
# Generate users device
self.user_device_id = self.user.email
self.user_device_model = 'application'
self.user_device_type = 'user'
self.user_device = Device.objects.create_device(device_id=self.user_device_id, password=self.device_password,
model=DeviceModel.objects.get(model=self.user_device_model),
type=DeviceType.objects.get(type=self.user_device_type))
# Set current client with a token fot authentication
self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + str(self.access_token))
self.health_check_url = reverse('nalkinscloud_api:health_check')
self.registration_url = reverse('nalkinscloud_api:register')
self.device_activation_url = reverse('nalkinscloud_api:device_activation')
self.device_list_url = reverse('nalkinscloud_api:device_list')
self.forgot_password_url = reverse('nalkinscloud_api:forgot_password')
self.get_device_pass_url = reverse('nalkinscloud_api:get_device_pass')
self.remove_device_url = reverse('nalkinscloud_api:remove_device')
self.reset_password_url = reverse('nalkinscloud_api:reset_password')
self.update_device_pass_url = reverse('nalkinscloud_api:update_device_pass')
def test_registration(self):
"""
Test Registration view
"""
post_body = {
'client_secret': self.oauth_client_secret,
'email': 'arielev@nalkins.cloud',
'password': self.password,
'first_name': 'Arie',
'last_name': 'Lev'
}
response = self.client.post(self.registration_url, data=post_body, format='json')
logger.debug("test_registration response: " + str(response.json()))
self.assertEqual(201, response.status_code, "Should return 201, register new user successfully")
# Perform same registration process again
response = self.client.post(self.registration_url, data=post_body, format='json')
self.assertEqual(409, response.status_code, "Should return 409 conflict, email already exists")
# Change client_secret to non valid value
post_body['client_secret'] = 'some_non_existing_client_id'
response = self.client.post(self.registration_url, data=post_body, format='json')
self.assertEqual(401, response.status_code, "Should return not authorized")
self.assertEqual(User.objects.count(), 2, "Two users should be present in the system by this point")
def test_health_check_view(self):
"""
Test Health Check view
:return:
"""
response = self.client.post(self.health_check_url)
logger.debug('test_health_check_view response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return username")
def test_device_activation_view_204(self):
"""
Test case when trying to attach a device that does not exists
:return:
"""
post_body = {
'device_id': 'non_existing_device',
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
self.assertEqual(204, response.status_code, "Should return 204 since device does not exists")
def test_device_activation_view_400_1(self):
"""
Test case when calling the api with no data
:return:
"""
response = self.client.post(self.device_activation_url)
logger.debug('test_device_activation_view_400_1 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return error 400 since there are missing values")
def test_device_activation_view_400_2(self):
"""
Test case when one of data parameters empty
:return:
"""
post_body = {
'device_id': '',
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_400_2 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400 since 'device_id' is blank")
self.assertEqual(response.json(), {'device_id': ['This field may not be blank.']},
"Should return blank field not allowed")
def test_device_activation_view_409(self):
"""
Test case when a device has an owner and its not the current user
:return:
"""
# Generate another test user
user = User.objects.create_user(
email='device@activate.test',
password=self.password,
is_active=True
)
# Generate another test device
device = Device.objects.create_device(device_id='device_activation_test_id', password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
# Attach just created user and device
CustomerDevice.objects.create(user_id=user, device_id=device)
# Test attaching other users device to current user
post_body = {
'device_id': device,
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_409 response: ' + str(response.json()))
self.assertEqual(409, response.status_code, "Should return 409 conflict, device owned by other user")
def test_device_activation_view_200_1(self):
"""
Test case when all is OK and an non owned device attached to current user
:return:
"""
post_body = {
'device_id': self.device_id,
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_200_1 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, device attached")
def test_device_activation_view_200_2(self):
"""
Test case when trying to attach a device that is already attached
:return:
"""
CustomerDevice.objects.create(user_id=self.user, device_id=self.device)
post_body = {
'device_id': self.device_id,
'device_name': 'test_device_activation_view_200_2'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_200_2 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, device already attached to current user")
CustomerDevice.objects.filter(user_id=self.user, device_id=self.user_device).delete()
def test_device_list_view_204(self):
"""
Test case that should return an empty device list
:return:
"""
response = self.client.post(self.device_list_url)
self.assertEqual(204, response.status_code, "Should return empty list")
def test_device_list_view_200(self):
"""
Test case that should return at least 1 length device list
:return:
"""
CustomerDevice.objects.create(user_id=self.user, device_id=self.device)
response = self.client.post(self.device_list_url)
logger.debug('test_device_list_view_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return devices list")
CustomerDevice.objects.filter(user_id=self.user, device_id=self.user_device).delete()
def test_forgot_password_view_400(self):
"""
Test case when no data provided
:return:
"""
response = self.client.post(self.forgot_password_url)
logger.debug('test_forgot_password_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_forgot_password_view_401(self):
"""
Test case when wrong client secret used
:return:
"""
post_data = {
'client_secret': 'some_non_valid_client_secret',
'email': self.user.email
}
response = self.client.post(self.forgot_password_url, data=post_data)
logger.debug('test_forgot_password_view_401 response: ' + str(response.json()))
self.assertEqual(401, response.status_code, "Should return 401, since client secret not exists")
def test_forgot_password_view_200_1(self):
"""
Test case when non existing email requested forgot password
:return:
"""
post_body = {
'client_secret': self.oauth_client_secret,
'email': 'some@not_existing.email',
}
response = self.client.post(self.forgot_password_url, data=post_body, format='json')
self.assertEqual(200, response.status_code, "Should return 200, although email does not exists")
def test_forgot_password_view_200_2(self):
"""
Test case when process should pass successfully
:return:
"""
post_data = {
'client_secret': self.oauth_client_secret,
'email': self.user.email,
}
response = self.client.post(self.forgot_password_url, data=post_data, format='json')
logger.debug('test_forgot_password_view_200_2 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, process completed")
def test_get_device_pass_view_400(self):
"""
Test case when no data received
:return:
"""
response = self.client.post(self.get_device_pass_url)
logger.debug('test_get_device_pass_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_get_device_pass_view_204(self):
"""
Test case when non existing device id received
:return:
"""
post_data = {
'device_id': 'some_non_existing_device_id'
}
response = self.client.post(self.get_device_pass_url, data=post_data)
self.assertEqual(204, response.status_code, "Should return 204, since device id does not exists")
def test_get_device_pass_view_409(self):
"""
Test case when trying to update password for a device that's owned by another user
:return:
"""
# Generate another test user
user = User.objects.create_user(
email='device@get_pass.test',
password=self.password,
is_active=True
)
# Generate another test device
device = Device.objects.create_device(device_id='get_device_pass_test_id', password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
# Attach just created user and device
CustomerDevice.objects.create(user_id=user, device_id=device)
post_data = {
'device_id': device.device_id
}
response = self.client.post(self.get_device_pass_url, data=post_data)
self.assertEqual(409, response.status_code, "Should return 409, since device belongs to another user")
def test_get_device_pass_view_200(self):
"""
Test case when process should pass successfully
:return:
"""
CustomerDevice.objects.create(user_id=self.user, device_id=self.device)
post_data = {
'device_id': self.device.device_id
}
response = self.client.post(self.get_device_pass_url, data=post_data)
self.assertEqual(200, response.status_code, "Should return 200, process succeeded")
def test_remove_device_view_400(self):
"""
Test case when no data received
:return:
"""
response = self.client.post(self.remove_device_url)
logger.debug('test_remove_device_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_remove_device_view_409_200(self):
"""
Test case when no data received
:return:
"""
# Generate another test device
device = Device.objects.create_device(device_id='remove_device_test_id', password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
post_data = {
'device_id': device.device_id
}
response = self.client.post(self.remove_device_url, data=post_data)
logger.debug('test_remove_device_view_409_200 response: ' + str(response.json()))
self.assertEqual(409, response.status_code, "Should return 409, since device is not owned by current user")
# Attach just created device to current user
CustomerDevice.objects.create(user_id=self.user, device_id=device)
response = self.client.post(self.remove_device_url, data=post_data)
logger.debug('test_remove_device_view_409_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, since device owned by current user")
def test_reset_password_view_400(self):
"""
Test case when no data received
:return:
"""
post_data = {
'current_password': '',
'new_password': self.password
}
response = self.client.post(self.reset_password_url, data=post_data)
logger.debug('test_reset_password_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_reset_password_view_422(self):
"""
Test case when wrong incorrect password received
:return:
"""
post_data = {
'current_password': 'somE_RandOm_PassWorD',
'new_password': self.password
}
response = self.client.post(self.reset_password_url, data=post_data)
logger.debug('test_reset_password_view_422 response: ' + str(response.json()))
self.assertEqual(422, response.status_code, "Should return 422, since current password is incorrect")
def test_reset_password_view_200(self):
"""
Test case when wrong correct password received
:return:
"""
post_data = {
'current_password': self.password,
'new_password': self.password
}
response = self.client.post(self.reset_password_url, data=post_data)
logger.debug('test_reset_password_view_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, since current password is correct")
def test_update_mqtt_user_pass_view_200(self):
"""
Test case when pass updates successfully
:return:
"""
response = self.client.post(self.update_device_pass_url)
logger.debug('test_update_mqtt_user_pass_view_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200")
| 43.587805 | 117 | 0.650607 |
from django.utils.crypto import get_random_string
from django.urls import reverse
from django.utils import timezone
from rest_framework.test import APITestCase
from oauth2_provider.models import AccessToken
from oauth2_provider.models import Application
from nalkinscloud_mosquitto.models import Device, DeviceType, DeviceModel, CustomerDevice
from django_user_email_extension.models import User
import datetime
import logging
from nalkinscloud_django.settings import PROJECT_NAME
logger = logging.getLogger(PROJECT_NAME)
class APIViewsTestCase(APITestCase):
def setUp(self):
self.oauth_client_id = 'some_client_id'
self.oauth_client_secret = 'some_client_secret'
self.oauth_client = Application.objects.create(client_id=self.oauth_client_id,
client_secret=self.oauth_client_secret)
self.email = "test@nalkins.cloud"
self.password = "nalkinscloud"
self.user = User.objects.create_user(
email=self.email,
password=self.password,
is_active=True
)
expires = timezone.now() + datetime.timedelta(seconds=36000)
self.access_token = AccessToken.objects.create(
user=self.user,
application=self.oauth_client,
scope='',
token=get_random_string(length=32),
expires=expires)
self.access_token.save()
self.device_id = 'api_test_device_id'
self.device_password = 'nalkinscloud'
self.device_model = 'esp8266'
self.device_type = 'dht'
self.device = Device.objects.create_device(device_id=self.device_id, password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
self.user_device_id = self.user.email
self.user_device_model = 'application'
self.user_device_type = 'user'
self.user_device = Device.objects.create_device(device_id=self.user_device_id, password=self.device_password,
model=DeviceModel.objects.get(model=self.user_device_model),
type=DeviceType.objects.get(type=self.user_device_type))
self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + str(self.access_token))
self.health_check_url = reverse('nalkinscloud_api:health_check')
self.registration_url = reverse('nalkinscloud_api:register')
self.device_activation_url = reverse('nalkinscloud_api:device_activation')
self.device_list_url = reverse('nalkinscloud_api:device_list')
self.forgot_password_url = reverse('nalkinscloud_api:forgot_password')
self.get_device_pass_url = reverse('nalkinscloud_api:get_device_pass')
self.remove_device_url = reverse('nalkinscloud_api:remove_device')
self.reset_password_url = reverse('nalkinscloud_api:reset_password')
self.update_device_pass_url = reverse('nalkinscloud_api:update_device_pass')
def test_registration(self):
post_body = {
'client_secret': self.oauth_client_secret,
'email': 'arielev@nalkins.cloud',
'password': self.password,
'first_name': 'Arie',
'last_name': 'Lev'
}
response = self.client.post(self.registration_url, data=post_body, format='json')
logger.debug("test_registration response: " + str(response.json()))
self.assertEqual(201, response.status_code, "Should return 201, register new user successfully")
response = self.client.post(self.registration_url, data=post_body, format='json')
self.assertEqual(409, response.status_code, "Should return 409 conflict, email already exists")
post_body['client_secret'] = 'some_non_existing_client_id'
response = self.client.post(self.registration_url, data=post_body, format='json')
self.assertEqual(401, response.status_code, "Should return not authorized")
self.assertEqual(User.objects.count(), 2, "Two users should be present in the system by this point")
def test_health_check_view(self):
response = self.client.post(self.health_check_url)
logger.debug('test_health_check_view response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return username")
def test_device_activation_view_204(self):
post_body = {
'device_id': 'non_existing_device',
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
self.assertEqual(204, response.status_code, "Should return 204 since device does not exists")
def test_device_activation_view_400_1(self):
response = self.client.post(self.device_activation_url)
logger.debug('test_device_activation_view_400_1 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return error 400 since there are missing values")
def test_device_activation_view_400_2(self):
post_body = {
'device_id': '',
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_400_2 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400 since 'device_id' is blank")
self.assertEqual(response.json(), {'device_id': ['This field may not be blank.']},
"Should return blank field not allowed")
def test_device_activation_view_409(self):
user = User.objects.create_user(
email='device@activate.test',
password=self.password,
is_active=True
)
device = Device.objects.create_device(device_id='device_activation_test_id', password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
CustomerDevice.objects.create(user_id=user, device_id=device)
post_body = {
'device_id': device,
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_409 response: ' + str(response.json()))
self.assertEqual(409, response.status_code, "Should return 409 conflict, device owned by other user")
def test_device_activation_view_200_1(self):
post_body = {
'device_id': self.device_id,
'device_name': 'device_activation_test'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_200_1 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, device attached")
def test_device_activation_view_200_2(self):
CustomerDevice.objects.create(user_id=self.user, device_id=self.device)
post_body = {
'device_id': self.device_id,
'device_name': 'test_device_activation_view_200_2'
}
response = self.client.post(self.device_activation_url, data=post_body)
logger.debug('test_device_activation_view_200_2 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, device already attached to current user")
CustomerDevice.objects.filter(user_id=self.user, device_id=self.user_device).delete()
def test_device_list_view_204(self):
response = self.client.post(self.device_list_url)
self.assertEqual(204, response.status_code, "Should return empty list")
def test_device_list_view_200(self):
CustomerDevice.objects.create(user_id=self.user, device_id=self.device)
response = self.client.post(self.device_list_url)
logger.debug('test_device_list_view_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return devices list")
CustomerDevice.objects.filter(user_id=self.user, device_id=self.user_device).delete()
def test_forgot_password_view_400(self):
response = self.client.post(self.forgot_password_url)
logger.debug('test_forgot_password_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_forgot_password_view_401(self):
post_data = {
'client_secret': 'some_non_valid_client_secret',
'email': self.user.email
}
response = self.client.post(self.forgot_password_url, data=post_data)
logger.debug('test_forgot_password_view_401 response: ' + str(response.json()))
self.assertEqual(401, response.status_code, "Should return 401, since client secret not exists")
def test_forgot_password_view_200_1(self):
post_body = {
'client_secret': self.oauth_client_secret,
'email': 'some@not_existing.email',
}
response = self.client.post(self.forgot_password_url, data=post_body, format='json')
self.assertEqual(200, response.status_code, "Should return 200, although email does not exists")
def test_forgot_password_view_200_2(self):
post_data = {
'client_secret': self.oauth_client_secret,
'email': self.user.email,
}
response = self.client.post(self.forgot_password_url, data=post_data, format='json')
logger.debug('test_forgot_password_view_200_2 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, process completed")
def test_get_device_pass_view_400(self):
response = self.client.post(self.get_device_pass_url)
logger.debug('test_get_device_pass_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_get_device_pass_view_204(self):
post_data = {
'device_id': 'some_non_existing_device_id'
}
response = self.client.post(self.get_device_pass_url, data=post_data)
self.assertEqual(204, response.status_code, "Should return 204, since device id does not exists")
def test_get_device_pass_view_409(self):
user = User.objects.create_user(
email='device@get_pass.test',
password=self.password,
is_active=True
)
device = Device.objects.create_device(device_id='get_device_pass_test_id', password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
CustomerDevice.objects.create(user_id=user, device_id=device)
post_data = {
'device_id': device.device_id
}
response = self.client.post(self.get_device_pass_url, data=post_data)
self.assertEqual(409, response.status_code, "Should return 409, since device belongs to another user")
def test_get_device_pass_view_200(self):
CustomerDevice.objects.create(user_id=self.user, device_id=self.device)
post_data = {
'device_id': self.device.device_id
}
response = self.client.post(self.get_device_pass_url, data=post_data)
self.assertEqual(200, response.status_code, "Should return 200, process succeeded")
def test_remove_device_view_400(self):
response = self.client.post(self.remove_device_url)
logger.debug('test_remove_device_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_remove_device_view_409_200(self):
device = Device.objects.create_device(device_id='remove_device_test_id', password=self.device_password,
model=DeviceModel.objects.get(model=self.device_model),
type=DeviceType.objects.get(type=self.device_type))
post_data = {
'device_id': device.device_id
}
response = self.client.post(self.remove_device_url, data=post_data)
logger.debug('test_remove_device_view_409_200 response: ' + str(response.json()))
self.assertEqual(409, response.status_code, "Should return 409, since device is not owned by current user")
CustomerDevice.objects.create(user_id=self.user, device_id=device)
response = self.client.post(self.remove_device_url, data=post_data)
logger.debug('test_remove_device_view_409_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, since device owned by current user")
def test_reset_password_view_400(self):
post_data = {
'current_password': '',
'new_password': self.password
}
response = self.client.post(self.reset_password_url, data=post_data)
logger.debug('test_reset_password_view_400 response: ' + str(response.json()))
self.assertEqual(400, response.status_code, "Should return 400, since missing data")
def test_reset_password_view_422(self):
post_data = {
'current_password': 'somE_RandOm_PassWorD',
'new_password': self.password
}
response = self.client.post(self.reset_password_url, data=post_data)
logger.debug('test_reset_password_view_422 response: ' + str(response.json()))
self.assertEqual(422, response.status_code, "Should return 422, since current password is incorrect")
def test_reset_password_view_200(self):
post_data = {
'current_password': self.password,
'new_password': self.password
}
response = self.client.post(self.reset_password_url, data=post_data)
logger.debug('test_reset_password_view_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200, since current password is correct")
def test_update_mqtt_user_pass_view_200(self):
response = self.client.post(self.update_device_pass_url)
logger.debug('test_update_mqtt_user_pass_view_200 response: ' + str(response.json()))
self.assertEqual(200, response.status_code, "Should return 200")
| true | true |
f72ba7d3fb86b7009f80264071c2ffe104766198 | 4,051 | py | Python | events/desucon2018/migrations/0001_initial.py | darkismus/kompassi | 35dea2c7af2857a69cae5c5982b48f01ba56da1f | [
"CC-BY-3.0"
] | 13 | 2015-11-29T12:19:12.000Z | 2021-02-21T15:42:11.000Z | events/desucon2018/migrations/0001_initial.py | darkismus/kompassi | 35dea2c7af2857a69cae5c5982b48f01ba56da1f | [
"CC-BY-3.0"
] | 23 | 2015-04-29T19:43:34.000Z | 2021-02-10T05:50:17.000Z | events/desucon2018/migrations/0001_initial.py | darkismus/kompassi | 35dea2c7af2857a69cae5c5982b48f01ba56da1f | [
"CC-BY-3.0"
] | 11 | 2015-09-20T18:59:00.000Z | 2020-02-07T08:47:34.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-01-28 15:36
from django.db import migrations, models
import django.db.models.deletion
import labour.models.signup_extras
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0029_auto_20170827_1818'),
]
operations = [
migrations.CreateModel(
name='SignupExtra',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_active', models.BooleanField(default=True)),
('shift_type', models.CharField(choices=[('none', 'Ei väliä'), ('4h', 'Pari pitkää vuoroa'), ('yli4h', 'Useita lyhyitä vuoroja')], help_text='Haluatko tehdä yhden pitkän työvuoron vaiko monta lyhyempää vuoroa?', max_length=15, verbose_name='Toivottu työvuoron pituus')),
('prior_experience', models.TextField(blank=True, help_text='Kerro tässä kentässä, jos sinulla on aiempaa kokemusta vastaavista tehtävistä tai muuta sellaista työkokemusta, josta arvioit olevan hyötyä hakemassasi tehtävässä.', verbose_name='Työkokemus')),
('free_text', models.TextField(blank=True, help_text='Jos haluat sanoa hakemuksesi käsittelijöille jotain sellaista, jolle ei ole omaa kenttää yllä, käytä tätä kenttää. Jos haet valokuvaajaksi, kerro lisäksi millaista kuvauskalustoa sinulla on käytettävissäsi ja listaamuutamia gallerialinkkejä, joista pääsemme ihailemaan ottamiasi kuvia. ', verbose_name='Vapaa alue')),
('special_diet_other', models.TextField(blank=True, help_text='Jos noudatat erikoisruokavaliota, jota ei ole yllä olevassa listassa, ilmoita se tässä. Tapahtuman järjestäjä pyrkii ottamaan erikoisruokavaliot huomioon, mutta kaikkia erikoisruokavalioita ei välttämättä pystytä järjestämään.', verbose_name='Muu erikoisruokavalio')),
('shirt_size', models.CharField(choices=[('NO_SHIRT', 'Ei paitaa'), ('XS', 'XS Unisex'), ('S', 'S Unisex'), ('M', 'M Unisex'), ('L', 'L Unisex'), ('XL', 'XL Unisex'), ('XXL', 'XXL Unisex'), ('3XL', '3XL Unisex'), ('4XL', '4XL Unisex'), ('5XL', '5XL Unisex'), ('LF_XS', 'XS Ladyfit'), ('LF_S', 'S Ladyfit'), ('LF_M', 'M Ladyfit'), ('LF_L', 'L Ladyfit'), ('LF_XL', 'XL Ladyfit')], default='NO_SHIRT', help_text='Ajoissa ilmoittautuneet saavat maksuttoman työvoimapaidan. Kokotaulukot: <a href="http://www.bc-collection.eu/uploads/sizes/TU004.jpg" target="_blank">unisex-paita</a>, <a href="http://www.bc-collection.eu/uploads/sizes/TW040.jpg" target="_blank">ladyfit-paita</a>', max_length=8, verbose_name='Paidan koko')),
('shirt_type', models.CharField(choices=[('STAFF', 'Staff'), ('DESURITY', 'Desurity'), ('KUVAAJA', 'Kuvaaja'), ('VENDOR', 'Myynti'), ('TOOLATE', 'Myöhästyi paitatilauksesta')], default='TOOLATE', max_length=8, verbose_name='Paidan tyyppi')),
('night_work', models.BooleanField(default=False, verbose_name='Olen valmis tekemään yötöitä')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='desucon2018_signup_extras', to='core.Event')),
('person', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='desucon2018_signup_extra', to='core.Person')),
],
options={
'abstract': False,
},
bases=(labour.models.signup_extras.SignupExtraMixin, models.Model),
),
migrations.CreateModel(
name='SpecialDiet',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=63)),
],
),
migrations.AddField(
model_name='signupextra',
name='special_diet',
field=models.ManyToManyField(blank=True, related_name='_signupextra_special_diet_+', to='desucon2018.SpecialDiet', verbose_name='Erikoisruokavalio'),
),
]
| 81.02 | 736 | 0.671933 |
from django.db import migrations, models
import django.db.models.deletion
import labour.models.signup_extras
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0029_auto_20170827_1818'),
]
operations = [
migrations.CreateModel(
name='SignupExtra',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_active', models.BooleanField(default=True)),
('shift_type', models.CharField(choices=[('none', 'Ei väliä'), ('4h', 'Pari pitkää vuoroa'), ('yli4h', 'Useita lyhyitä vuoroja')], help_text='Haluatko tehdä yhden pitkän työvuoron vaiko monta lyhyempää vuoroa?', max_length=15, verbose_name='Toivottu työvuoron pituus')),
('prior_experience', models.TextField(blank=True, help_text='Kerro tässä kentässä, jos sinulla on aiempaa kokemusta vastaavista tehtävistä tai muuta sellaista työkokemusta, josta arvioit olevan hyötyä hakemassasi tehtävässä.', verbose_name='Työkokemus')),
('free_text', models.TextField(blank=True, help_text='Jos haluat sanoa hakemuksesi käsittelijöille jotain sellaista, jolle ei ole omaa kenttää yllä, käytä tätä kenttää. Jos haet valokuvaajaksi, kerro lisäksi millaista kuvauskalustoa sinulla on käytettävissäsi ja listaamuutamia gallerialinkkejä, joista pääsemme ihailemaan ottamiasi kuvia. ', verbose_name='Vapaa alue')),
('special_diet_other', models.TextField(blank=True, help_text='Jos noudatat erikoisruokavaliota, jota ei ole yllä olevassa listassa, ilmoita se tässä. Tapahtuman järjestäjä pyrkii ottamaan erikoisruokavaliot huomioon, mutta kaikkia erikoisruokavalioita ei välttämättä pystytä järjestämään.', verbose_name='Muu erikoisruokavalio')),
('shirt_size', models.CharField(choices=[('NO_SHIRT', 'Ei paitaa'), ('XS', 'XS Unisex'), ('S', 'S Unisex'), ('M', 'M Unisex'), ('L', 'L Unisex'), ('XL', 'XL Unisex'), ('XXL', 'XXL Unisex'), ('3XL', '3XL Unisex'), ('4XL', '4XL Unisex'), ('5XL', '5XL Unisex'), ('LF_XS', 'XS Ladyfit'), ('LF_S', 'S Ladyfit'), ('LF_M', 'M Ladyfit'), ('LF_L', 'L Ladyfit'), ('LF_XL', 'XL Ladyfit')], default='NO_SHIRT', help_text='Ajoissa ilmoittautuneet saavat maksuttoman työvoimapaidan. Kokotaulukot: <a href="http://www.bc-collection.eu/uploads/sizes/TU004.jpg" target="_blank">unisex-paita</a>, <a href="http://www.bc-collection.eu/uploads/sizes/TW040.jpg" target="_blank">ladyfit-paita</a>', max_length=8, verbose_name='Paidan koko')),
('shirt_type', models.CharField(choices=[('STAFF', 'Staff'), ('DESURITY', 'Desurity'), ('KUVAAJA', 'Kuvaaja'), ('VENDOR', 'Myynti'), ('TOOLATE', 'Myöhästyi paitatilauksesta')], default='TOOLATE', max_length=8, verbose_name='Paidan tyyppi')),
('night_work', models.BooleanField(default=False, verbose_name='Olen valmis tekemään yötöitä')),
('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='desucon2018_signup_extras', to='core.Event')),
('person', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='desucon2018_signup_extra', to='core.Person')),
],
options={
'abstract': False,
},
bases=(labour.models.signup_extras.SignupExtraMixin, models.Model),
),
migrations.CreateModel(
name='SpecialDiet',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=63)),
],
),
migrations.AddField(
model_name='signupextra',
name='special_diet',
field=models.ManyToManyField(blank=True, related_name='_signupextra_special_diet_+', to='desucon2018.SpecialDiet', verbose_name='Erikoisruokavalio'),
),
]
| true | true |
f72ba8a9a4446d79a62e8b823b38942abbb5f5f3 | 232 | py | Python | my_awesome_project/users/serializers.py | mikejuliano/drf-react-native | 71d40dd168407096e213157c0141588d474ae3d0 | [
"MIT"
] | null | null | null | my_awesome_project/users/serializers.py | mikejuliano/drf-react-native | 71d40dd168407096e213157c0141588d474ae3d0 | [
"MIT"
] | null | null | null | my_awesome_project/users/serializers.py | mikejuliano/drf-react-native | 71d40dd168407096e213157c0141588d474ae3d0 | [
"MIT"
] | null | null | null | from rest_framework import serializers
# from django.contrib.auth.models import User
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username',)
| 21.090909 | 50 | 0.728448 | from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username',)
| true | true |
f72ba8c520fc112f474edccb7228fd1f7e57e095 | 5,326 | py | Python | PythonAPI/carissma_project/lib/python3.5/site-packages/matplotlib/tri/tripcolor.py | AbdulHoffmann/carla_carissma | 8d382769ffa02a6c61a22c57160285505f5ff0a4 | [
"MIT"
] | 445 | 2019-01-26T13:50:26.000Z | 2022-03-18T05:17:38.000Z | venv/lib/python3.7/site-packages/matplotlib/tri/tripcolor.py | John1001Song/Big-Data-Robo-Adviser | 9444dce96954c546333d5aecc92a06c3bfd19aa5 | [
"MIT"
] | 242 | 2019-01-29T15:48:27.000Z | 2022-03-31T22:09:21.000Z | venv/lib/python3.7/site-packages/matplotlib/tri/tripcolor.py | John1001Song/Big-Data-Robo-Adviser | 9444dce96954c546333d5aecc92a06c3bfd19aa5 | [
"MIT"
] | 64 | 2018-04-25T08:51:57.000Z | 2022-01-29T14:13:57.000Z | import numpy as np
from matplotlib.collections import PolyCollection, TriMesh
from matplotlib.colors import Normalize
from matplotlib.tri.triangulation import Triangulation
def tripcolor(ax, *args, alpha=1.0, norm=None, cmap=None, vmin=None,
vmax=None, shading='flat', facecolors=None, **kwargs):
"""
Create a pseudocolor plot of an unstructured triangular grid.
The triangulation can be specified in one of two ways; either::
tripcolor(triangulation, ...)
where triangulation is a :class:`matplotlib.tri.Triangulation`
object, or
::
tripcolor(x, y, ...)
tripcolor(x, y, triangles, ...)
tripcolor(x, y, triangles=triangles, ...)
tripcolor(x, y, mask=mask, ...)
tripcolor(x, y, triangles, mask=mask, ...)
in which case a Triangulation object will be created. See
:class:`~matplotlib.tri.Triangulation` for a explanation of these
possibilities.
The next argument must be *C*, the array of color values, either
one per point in the triangulation if color values are defined at
points, or one per triangle in the triangulation if color values
are defined at triangles. If there are the same number of points
and triangles in the triangulation it is assumed that color
values are defined at points; to force the use of color values at
triangles use the kwarg ``facecolors=C`` instead of just ``C``.
*shading* may be 'flat' (the default) or 'gouraud'. If *shading*
is 'flat' and C values are defined at points, the color values
used for each triangle are from the mean C of the triangle's
three points. If *shading* is 'gouraud' then color values must be
defined at points.
The remaining kwargs are the same as for
:meth:`~matplotlib.axes.Axes.pcolor`.
"""
if shading not in ['flat', 'gouraud']:
raise ValueError("shading must be one of ['flat', 'gouraud'] "
"not {0}".format(shading))
tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs)
# C is the colors array defined at either points or faces (i.e. triangles).
# If facecolors is None, C are defined at points.
# If facecolors is not None, C are defined at faces.
if facecolors is not None:
C = facecolors
else:
C = np.asarray(args[0])
# If there are a different number of points and triangles in the
# triangulation, can omit facecolors kwarg as it is obvious from
# length of C whether it refers to points or faces.
# Do not do this for gouraud shading.
if (facecolors is None and len(C) == len(tri.triangles) and
len(C) != len(tri.x) and shading != 'gouraud'):
facecolors = C
# Check length of C is OK.
if ((facecolors is None and len(C) != len(tri.x)) or
(facecolors is not None and len(C) != len(tri.triangles))):
raise ValueError('Length of color values array must be the same '
'as either the number of triangulation points '
'or triangles')
# Handling of linewidths, shading, edgecolors and antialiased as
# in Axes.pcolor
linewidths = (0.25,)
if 'linewidth' in kwargs:
kwargs['linewidths'] = kwargs.pop('linewidth')
kwargs.setdefault('linewidths', linewidths)
edgecolors = 'none'
if 'edgecolor' in kwargs:
kwargs['edgecolors'] = kwargs.pop('edgecolor')
ec = kwargs.setdefault('edgecolors', edgecolors)
if 'antialiased' in kwargs:
kwargs['antialiaseds'] = kwargs.pop('antialiased')
if 'antialiaseds' not in kwargs and ec.lower() == "none":
kwargs['antialiaseds'] = False
if shading == 'gouraud':
if facecolors is not None:
raise ValueError('Gouraud shading does not support the use '
'of facecolors kwarg')
if len(C) != len(tri.x):
raise ValueError('For gouraud shading, the length of color '
'values array must be the same as the '
'number of triangulation points')
collection = TriMesh(tri, **kwargs)
else:
# Vertices of triangles.
maskedTris = tri.get_masked_triangles()
verts = np.stack((tri.x[maskedTris], tri.y[maskedTris]), axis=-1)
# Color values.
if facecolors is None:
# One color per triangle, the mean of the 3 vertex color values.
C = C[maskedTris].mean(axis=1)
elif tri.mask is not None:
# Remove color values of masked triangles.
C = C.compress(1-tri.mask)
collection = PolyCollection(verts, **kwargs)
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None and not isinstance(norm, Normalize):
raise ValueError("'norm' must be an instance of 'Normalize'")
collection.set_cmap(cmap)
collection.set_norm(norm)
if vmin is not None or vmax is not None:
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
ax.grid(False)
minx = tri.x.min()
maxx = tri.x.max()
miny = tri.y.min()
maxy = tri.y.max()
corners = (minx, miny), (maxx, maxy)
ax.update_datalim(corners)
ax.autoscale_view()
ax.add_collection(collection)
return collection
| 38.042857 | 79 | 0.639504 | import numpy as np
from matplotlib.collections import PolyCollection, TriMesh
from matplotlib.colors import Normalize
from matplotlib.tri.triangulation import Triangulation
def tripcolor(ax, *args, alpha=1.0, norm=None, cmap=None, vmin=None,
vmax=None, shading='flat', facecolors=None, **kwargs):
if shading not in ['flat', 'gouraud']:
raise ValueError("shading must be one of ['flat', 'gouraud'] "
"not {0}".format(shading))
tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs)
if facecolors is not None:
C = facecolors
else:
C = np.asarray(args[0])
if (facecolors is None and len(C) == len(tri.triangles) and
len(C) != len(tri.x) and shading != 'gouraud'):
facecolors = C
if ((facecolors is None and len(C) != len(tri.x)) or
(facecolors is not None and len(C) != len(tri.triangles))):
raise ValueError('Length of color values array must be the same '
'as either the number of triangulation points '
'or triangles')
linewidths = (0.25,)
if 'linewidth' in kwargs:
kwargs['linewidths'] = kwargs.pop('linewidth')
kwargs.setdefault('linewidths', linewidths)
edgecolors = 'none'
if 'edgecolor' in kwargs:
kwargs['edgecolors'] = kwargs.pop('edgecolor')
ec = kwargs.setdefault('edgecolors', edgecolors)
if 'antialiased' in kwargs:
kwargs['antialiaseds'] = kwargs.pop('antialiased')
if 'antialiaseds' not in kwargs and ec.lower() == "none":
kwargs['antialiaseds'] = False
if shading == 'gouraud':
if facecolors is not None:
raise ValueError('Gouraud shading does not support the use '
'of facecolors kwarg')
if len(C) != len(tri.x):
raise ValueError('For gouraud shading, the length of color '
'values array must be the same as the '
'number of triangulation points')
collection = TriMesh(tri, **kwargs)
else:
maskedTris = tri.get_masked_triangles()
verts = np.stack((tri.x[maskedTris], tri.y[maskedTris]), axis=-1)
if facecolors is None:
C = C[maskedTris].mean(axis=1)
elif tri.mask is not None:
C = C.compress(1-tri.mask)
collection = PolyCollection(verts, **kwargs)
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None and not isinstance(norm, Normalize):
raise ValueError("'norm' must be an instance of 'Normalize'")
collection.set_cmap(cmap)
collection.set_norm(norm)
if vmin is not None or vmax is not None:
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
ax.grid(False)
minx = tri.x.min()
maxx = tri.x.max()
miny = tri.y.min()
maxy = tri.y.max()
corners = (minx, miny), (maxx, maxy)
ax.update_datalim(corners)
ax.autoscale_view()
ax.add_collection(collection)
return collection
| true | true |
f72ba8feede17a2888058de31640869ebe5db2d9 | 1,794 | py | Python | app/features/steps/value_propagation_test.py | muglyon/https-github.com-muglyon-DCOP-Decentralised-Control-of-Intelligent-Devices | 68cb868a0875f5e119ac0dbea024c17d241347ac | [
"MIT"
] | 3 | 2020-04-10T09:13:17.000Z | 2021-04-08T07:14:03.000Z | app/features/steps/value_propagation_test.py | muglyon/https-github.com-muglyon-DCOP-Decentralised-Control-of-Intelligent-Devices | 68cb868a0875f5e119ac0dbea024c17d241347ac | [
"MIT"
] | 8 | 2020-09-26T00:55:30.000Z | 2022-01-13T02:32:04.000Z | app/features/steps/value_propagation_test.py | muglyon/https-github.com-muglyon-DCOP-Decentralised-Control-of-Intelligent-Devices | 68cb868a0875f5e119ac0dbea024c17d241347ac | [
"MIT"
] | 2 | 2020-04-12T10:08:15.000Z | 2022-01-20T09:34:50.000Z | #! python3
# value_propagation_test.py - Test the VALUE Propagation behavior
from behave import *
from hamcrest import *
import numpy
@when('get VALUE from parent after UTIL propagation')
def step_impl(context):
set_up(context)
context.dpop_to_test.util_manager.JOIN = context.util_matrix
@then('should select the optimal assignment')
def step_impl(context):
index = context.dpop_to_test.value_manager.get_index_of_best_value_with(
context.data,
context.dpop_to_test.util_manager.matrix_dimensions_order,
context.dpop_to_test.util_manager.JOIN
)
assert_that(index, equal_to(2))
@when('parent send values to wrong format')
def step_impl(context):
set_up(context)
context.data = 'wrong format'
@when('matrix is Null')
def step_impl(context):
set_up(context)
context.util_matrix = None
@then('should raise an exception')
def step_impl(context):
assert_that(calling(context.dpop_to_test.value_manager.get_index_of_best_value_with)
.with_args(context.data, context.util_matrix), raises(Exception))
@when('matrix has 1 dimension')
def step_impl(context):
set_up(context)
context.dpop_to_test.util_manager.JOIN = numpy.asmatrix([[1], [0], [1]])
@then('should return the min value index')
def step_impl(context):
index = context.dpop_to_test.value_manager.get_index_of_best_value_with(
context.data,
context.dpop_to_test.util_manager.matrix_dimensions_order,
context.dpop_to_test.util_manager.JOIN
)
assert_that(index, equal_to(1))
###
# Privates Methods
###
def set_up(context):
context.dpop_to_test.util_manager.matrix_dimensions_order = [1]
context.util_matrix = numpy.arange(start=11, stop=2, step=-1).reshape(3, 3)
context.data = {"1": 1}
| 26.382353 | 88 | 0.731884 |
from behave import *
from hamcrest import *
import numpy
@when('get VALUE from parent after UTIL propagation')
def step_impl(context):
set_up(context)
context.dpop_to_test.util_manager.JOIN = context.util_matrix
@then('should select the optimal assignment')
def step_impl(context):
index = context.dpop_to_test.value_manager.get_index_of_best_value_with(
context.data,
context.dpop_to_test.util_manager.matrix_dimensions_order,
context.dpop_to_test.util_manager.JOIN
)
assert_that(index, equal_to(2))
@when('parent send values to wrong format')
def step_impl(context):
set_up(context)
context.data = 'wrong format'
@when('matrix is Null')
def step_impl(context):
set_up(context)
context.util_matrix = None
@then('should raise an exception')
def step_impl(context):
assert_that(calling(context.dpop_to_test.value_manager.get_index_of_best_value_with)
.with_args(context.data, context.util_matrix), raises(Exception))
@when('matrix has 1 dimension')
def step_impl(context):
set_up(context)
context.dpop_to_test.util_manager.JOIN = numpy.asmatrix([[1], [0], [1]])
@then('should return the min value index')
def step_impl(context):
index = context.dpop_to_test.value_manager.get_index_of_best_value_with(
context.data,
context.dpop_to_test.util_manager.matrix_dimensions_order,
context.dpop_to_test.util_manager.JOIN
)
assert_that(index, equal_to(1))
ef set_up(context):
context.dpop_to_test.util_manager.matrix_dimensions_order = [1]
context.util_matrix = numpy.arange(start=11, stop=2, step=-1).reshape(3, 3)
context.data = {"1": 1}
| true | true |
f72baab36e3a21c7ba43e643724c016ec8ee0837 | 8,858 | py | Python | cinder/openstack/common/config/generator.py | sombrafam/cinder | 60ffb0eedf41b56f3c6af5b301400ced95762194 | [
"Apache-2.0"
] | null | null | null | cinder/openstack/common/config/generator.py | sombrafam/cinder | 60ffb0eedf41b56f3c6af5b301400ced95762194 | [
"Apache-2.0"
] | null | null | null | cinder/openstack/common/config/generator.py | sombrafam/cinder | 60ffb0eedf41b56f3c6af5b301400ced95762194 | [
"Apache-2.0"
] | null | null | null | # Copyright 2012 SINA Corporation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
"""Extracts OpenStack config option info from module(s)."""
from __future__ import print_function
import imp
import os
import re
import socket
import sys
import textwrap
from oslo.config import cfg
import six
from cinder.openstack.common import gettextutils
from cinder.openstack.common import importutils
gettextutils.install('cinder')
STROPT = "StrOpt"
BOOLOPT = "BoolOpt"
INTOPT = "IntOpt"
FLOATOPT = "FloatOpt"
LISTOPT = "ListOpt"
MULTISTROPT = "MultiStrOpt"
OPT_TYPES = {
STROPT: 'string value',
BOOLOPT: 'boolean value',
INTOPT: 'integer value',
FLOATOPT: 'floating point value',
LISTOPT: 'list value',
MULTISTROPT: 'multi valued',
}
OPTION_REGEX = re.compile(r"(%s)" % "|".join([STROPT, BOOLOPT, INTOPT,
FLOATOPT, LISTOPT,
MULTISTROPT]))
PY_EXT = ".py"
BASEDIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
"../../../../"))
WORDWRAP_WIDTH = 60
def generate(srcfiles):
mods_by_pkg = dict()
for filepath in srcfiles:
pkg_name = filepath.split(os.sep)[1]
mod_str = '.'.join(['.'.join(filepath.split(os.sep)[:-1]),
os.path.basename(filepath).split('.')[0]])
mods_by_pkg.setdefault(pkg_name, list()).append(mod_str)
# NOTE(lzyeval): place top level modules before packages
pkg_names = filter(lambda x: x.endswith(PY_EXT), mods_by_pkg.keys())
pkg_names.sort()
ext_names = filter(lambda x: x not in pkg_names, mods_by_pkg.keys())
ext_names.sort()
pkg_names.extend(ext_names)
# opts_by_group is a mapping of group name to an options list
# The options list is a list of (module, options) tuples
opts_by_group = {'DEFAULT': []}
extra_modules = os.getenv("OSLO_CONFIG_GENERATOR_EXTRA_MODULES", "")
if extra_modules:
for module_name in extra_modules.split(','):
module_name = module_name.strip()
module = _import_module(module_name)
if module:
for group, opts in _list_opts(module):
opts_by_group.setdefault(group, []).append((module_name,
opts))
for pkg_name in pkg_names:
mods = mods_by_pkg.get(pkg_name)
mods.sort()
for mod_str in mods:
if mod_str.endswith('.__init__'):
mod_str = mod_str[:mod_str.rfind(".")]
mod_obj = _import_module(mod_str)
if not mod_obj:
raise RuntimeError("Unable to import module %s" % mod_str)
for group, opts in _list_opts(mod_obj):
opts_by_group.setdefault(group, []).append((mod_str, opts))
print_group_opts('DEFAULT', opts_by_group.pop('DEFAULT', []))
for group, opts in opts_by_group.items():
print_group_opts(group, opts)
def _import_module(mod_str):
try:
if mod_str.startswith('bin.'):
imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:]))
return sys.modules[mod_str[4:]]
else:
return importutils.import_module(mod_str)
except Exception as e:
sys.stderr.write("Error importing module %s: %s\n" % (mod_str, str(e)))
return None
def _is_in_group(opt, group):
"Check if opt is in group."
for key, value in group._opts.items():
if value['opt'] == opt:
return True
return False
def _guess_groups(opt, mod_obj):
# is it in the DEFAULT group?
if _is_in_group(opt, cfg.CONF):
return 'DEFAULT'
# what other groups is it in?
for key, value in cfg.CONF.items():
if isinstance(value, cfg.CONF.GroupAttr):
if _is_in_group(opt, value._group):
return value._group.name
raise RuntimeError(
"Unable to find group for option %s, "
"maybe it's defined twice in the same group?"
% opt.name
)
def _list_opts(obj):
def is_opt(o):
return (isinstance(o, cfg.Opt) and
not isinstance(o, cfg.SubCommandOpt))
opts = list()
for attr_str in dir(obj):
attr_obj = getattr(obj, attr_str)
if is_opt(attr_obj):
opts.append(attr_obj)
elif (isinstance(attr_obj, list) and
all(map(lambda x: is_opt(x), attr_obj))):
opts.extend(attr_obj)
ret = {}
for opt in opts:
ret.setdefault(_guess_groups(opt, obj), []).append(opt)
return ret.items()
def print_group_opts(group, opts_by_module):
print("[%s]" % group)
print('')
for mod, opts in opts_by_module:
print('#')
print('# Options defined in %s' % mod)
print('#')
print('')
for opt in opts:
_print_opt(opt)
print('')
def _get_my_ip():
try:
csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
csock.connect(('8.8.8.8', 80))
(addr, port) = csock.getsockname()
csock.close()
return addr
except socket.error:
return None
def _sanitize_default(name, value):
"""Set up a reasonably sensible default for pybasedir, my_ip and host."""
if value.startswith(sys.prefix):
# NOTE(jd) Don't use os.path.join, because it is likely to think the
# second part is an absolute pathname and therefore drop the first
# part.
value = os.path.normpath("/usr/" + value[len(sys.prefix):])
elif value.startswith(BASEDIR):
return value.replace(BASEDIR, '/usr/lib/python/site-packages')
elif BASEDIR in value:
return value.replace(BASEDIR, '')
elif value == _get_my_ip():
return '10.0.0.1'
elif value == socket.gethostname() and 'host' in name:
return 'cinder'
elif value.strip() != value:
return '"%s"' % value
return value
def _print_opt(opt):
opt_name, opt_default, opt_help = opt.dest, opt.default, opt.help
if not opt_help:
sys.stderr.write('WARNING: "%s" is missing help string.\n' % opt_name)
opt_help = ""
opt_type = None
try:
opt_type = OPTION_REGEX.search(str(type(opt))).group(0)
except (ValueError, AttributeError) as err:
sys.stderr.write("%s\n" % str(err))
sys.exit(1)
opt_help += ' (' + OPT_TYPES[opt_type] + ')'
print('#', "\n# ".join(textwrap.wrap(opt_help, WORDWRAP_WIDTH)))
if opt.deprecated_opts:
for deprecated_opt in opt.deprecated_opts:
if deprecated_opt.name:
deprecated_group = (deprecated_opt.group if
deprecated_opt.group else "DEFAULT")
print('# Deprecated group/name - [%s]/%s' %
(deprecated_group,
deprecated_opt.name))
try:
if opt_default is None:
print('#%s=<None>' % opt_name)
elif opt_type == STROPT:
assert(isinstance(opt_default, six.string_types))
print('#%s=%s' % (opt_name, _sanitize_default(opt_name,
opt_default)))
elif opt_type == BOOLOPT:
assert(isinstance(opt_default, bool))
print('#%s=%s' % (opt_name, str(opt_default).lower()))
elif opt_type == INTOPT:
assert(isinstance(opt_default, int) and
not isinstance(opt_default, bool))
print('#%s=%s' % (opt_name, opt_default))
elif opt_type == FLOATOPT:
assert(isinstance(opt_default, float))
print('#%s=%s' % (opt_name, opt_default))
elif opt_type == LISTOPT:
assert(isinstance(opt_default, list))
print('#%s=%s' % (opt_name, ','.join(opt_default)))
elif opt_type == MULTISTROPT:
assert(isinstance(opt_default, list))
if not opt_default:
opt_default = ['']
for default in opt_default:
print('#%s=%s' % (opt_name, default))
print('')
except Exception:
sys.stderr.write('Error in option "%s"\n' % opt_name)
sys.exit(1)
def main():
generate(sys.argv[1:])
if __name__ == '__main__':
main()
| 32.929368 | 79 | 0.593362 |
from __future__ import print_function
import imp
import os
import re
import socket
import sys
import textwrap
from oslo.config import cfg
import six
from cinder.openstack.common import gettextutils
from cinder.openstack.common import importutils
gettextutils.install('cinder')
STROPT = "StrOpt"
BOOLOPT = "BoolOpt"
INTOPT = "IntOpt"
FLOATOPT = "FloatOpt"
LISTOPT = "ListOpt"
MULTISTROPT = "MultiStrOpt"
OPT_TYPES = {
STROPT: 'string value',
BOOLOPT: 'boolean value',
INTOPT: 'integer value',
FLOATOPT: 'floating point value',
LISTOPT: 'list value',
MULTISTROPT: 'multi valued',
}
OPTION_REGEX = re.compile(r"(%s)" % "|".join([STROPT, BOOLOPT, INTOPT,
FLOATOPT, LISTOPT,
MULTISTROPT]))
PY_EXT = ".py"
BASEDIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
"../../../../"))
WORDWRAP_WIDTH = 60
def generate(srcfiles):
mods_by_pkg = dict()
for filepath in srcfiles:
pkg_name = filepath.split(os.sep)[1]
mod_str = '.'.join(['.'.join(filepath.split(os.sep)[:-1]),
os.path.basename(filepath).split('.')[0]])
mods_by_pkg.setdefault(pkg_name, list()).append(mod_str)
pkg_names = filter(lambda x: x.endswith(PY_EXT), mods_by_pkg.keys())
pkg_names.sort()
ext_names = filter(lambda x: x not in pkg_names, mods_by_pkg.keys())
ext_names.sort()
pkg_names.extend(ext_names)
opts_by_group = {'DEFAULT': []}
extra_modules = os.getenv("OSLO_CONFIG_GENERATOR_EXTRA_MODULES", "")
if extra_modules:
for module_name in extra_modules.split(','):
module_name = module_name.strip()
module = _import_module(module_name)
if module:
for group, opts in _list_opts(module):
opts_by_group.setdefault(group, []).append((module_name,
opts))
for pkg_name in pkg_names:
mods = mods_by_pkg.get(pkg_name)
mods.sort()
for mod_str in mods:
if mod_str.endswith('.__init__'):
mod_str = mod_str[:mod_str.rfind(".")]
mod_obj = _import_module(mod_str)
if not mod_obj:
raise RuntimeError("Unable to import module %s" % mod_str)
for group, opts in _list_opts(mod_obj):
opts_by_group.setdefault(group, []).append((mod_str, opts))
print_group_opts('DEFAULT', opts_by_group.pop('DEFAULT', []))
for group, opts in opts_by_group.items():
print_group_opts(group, opts)
def _import_module(mod_str):
try:
if mod_str.startswith('bin.'):
imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:]))
return sys.modules[mod_str[4:]]
else:
return importutils.import_module(mod_str)
except Exception as e:
sys.stderr.write("Error importing module %s: %s\n" % (mod_str, str(e)))
return None
def _is_in_group(opt, group):
for key, value in group._opts.items():
if value['opt'] == opt:
return True
return False
def _guess_groups(opt, mod_obj):
if _is_in_group(opt, cfg.CONF):
return 'DEFAULT'
for key, value in cfg.CONF.items():
if isinstance(value, cfg.CONF.GroupAttr):
if _is_in_group(opt, value._group):
return value._group.name
raise RuntimeError(
"Unable to find group for option %s, "
"maybe it's defined twice in the same group?"
% opt.name
)
def _list_opts(obj):
def is_opt(o):
return (isinstance(o, cfg.Opt) and
not isinstance(o, cfg.SubCommandOpt))
opts = list()
for attr_str in dir(obj):
attr_obj = getattr(obj, attr_str)
if is_opt(attr_obj):
opts.append(attr_obj)
elif (isinstance(attr_obj, list) and
all(map(lambda x: is_opt(x), attr_obj))):
opts.extend(attr_obj)
ret = {}
for opt in opts:
ret.setdefault(_guess_groups(opt, obj), []).append(opt)
return ret.items()
def print_group_opts(group, opts_by_module):
print("[%s]" % group)
print('')
for mod, opts in opts_by_module:
print('
print('
print('
print('')
for opt in opts:
_print_opt(opt)
print('')
def _get_my_ip():
try:
csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
csock.connect(('8.8.8.8', 80))
(addr, port) = csock.getsockname()
csock.close()
return addr
except socket.error:
return None
def _sanitize_default(name, value):
if value.startswith(sys.prefix):
# NOTE(jd) Don't use os.path.join, because it is likely to think the
value = os.path.normpath("/usr/" + value[len(sys.prefix):])
elif value.startswith(BASEDIR):
return value.replace(BASEDIR, '/usr/lib/python/site-packages')
elif BASEDIR in value:
return value.replace(BASEDIR, '')
elif value == _get_my_ip():
return '10.0.0.1'
elif value == socket.gethostname() and 'host' in name:
return 'cinder'
elif value.strip() != value:
return '"%s"' % value
return value
def _print_opt(opt):
opt_name, opt_default, opt_help = opt.dest, opt.default, opt.help
if not opt_help:
sys.stderr.write('WARNING: "%s" is missing help string.\n' % opt_name)
opt_help = ""
opt_type = None
try:
opt_type = OPTION_REGEX.search(str(type(opt))).group(0)
except (ValueError, AttributeError) as err:
sys.stderr.write("%s\n" % str(err))
sys.exit(1)
opt_help += ' (' + OPT_TYPES[opt_type] + ')'
print('#', "\n# ".join(textwrap.wrap(opt_help, WORDWRAP_WIDTH)))
if opt.deprecated_opts:
for deprecated_opt in opt.deprecated_opts:
if deprecated_opt.name:
deprecated_group = (deprecated_opt.group if
deprecated_opt.group else "DEFAULT")
print('# Deprecated group/name - [%s]/%s' %
(deprecated_group,
deprecated_opt.name))
try:
if opt_default is None:
print('#%s=<None>' % opt_name)
elif opt_type == STROPT:
assert(isinstance(opt_default, six.string_types))
print('#%s=%s' % (opt_name, _sanitize_default(opt_name,
opt_default)))
elif opt_type == BOOLOPT:
assert(isinstance(opt_default, bool))
print('#%s=%s' % (opt_name, str(opt_default).lower()))
elif opt_type == INTOPT:
assert(isinstance(opt_default, int) and
not isinstance(opt_default, bool))
print('#%s=%s' % (opt_name, opt_default))
elif opt_type == FLOATOPT:
assert(isinstance(opt_default, float))
print('#%s=%s' % (opt_name, opt_default))
elif opt_type == LISTOPT:
assert(isinstance(opt_default, list))
print('#%s=%s' % (opt_name, ','.join(opt_default)))
elif opt_type == MULTISTROPT:
assert(isinstance(opt_default, list))
if not opt_default:
opt_default = ['']
for default in opt_default:
print('#%s=%s' % (opt_name, default))
print('')
except Exception:
sys.stderr.write('Error in option "%s"\n' % opt_name)
sys.exit(1)
def main():
generate(sys.argv[1:])
if __name__ == '__main__':
main()
| true | true |
f72bab7ab1bca3789121e05f9da664664eeab617 | 3,732 | py | Python | GitHubUploader.py | ytyaru/GitHub.Uploader.AddFunction.Contributions.201705141424 | 06e44308b0eb132f0ce1e547cedc6b0f6e566c93 | [
"CC0-1.0"
] | null | null | null | GitHubUploader.py | ytyaru/GitHub.Uploader.AddFunction.Contributions.201705141424 | 06e44308b0eb132f0ce1e547cedc6b0f6e566c93 | [
"CC0-1.0"
] | null | null | null | GitHubUploader.py | ytyaru/GitHub.Uploader.AddFunction.Contributions.201705141424 | 06e44308b0eb132f0ce1e547cedc6b0f6e566c93 | [
"CC0-1.0"
] | null | null | null | #!/usr/bin/python3
#!python3
#encoding:utf-8
import sys
import os.path
import subprocess
import configparser
import argparse
import web.service.github.api.v3.AuthenticationsCreator
import web.service.github.api.v3.AuthenticationData
#import web.service.github.api.v3.CurrentUser
import web.service.github.api.v3.CurrentRepository
import web.service.github.api.v3.Client
import database.src.Database
import cui.uploader.Main
import web.log.Log
import database.src.contributions.Main
class Main:
def __init__(self):
pass
def Run(self):
parser = argparse.ArgumentParser(
description='GitHub Repository Uploader.',
)
parser.add_argument('path_dir_pj')
parser.add_argument('-u', '--username')
parser.add_argument('-d', '--description')
parser.add_argument('-l', '--homepage', '--link', '--url')
args = parser.parse_args()
# print(args)
# print('path_dir_pj: {0}'.format(args.path_dir_pj))
# print('-u: {0}'.format(args.username))
# print('-d: {0}'.format(args.description))
# print('-l: {0}'.format(args.homepage))
config = configparser.ConfigParser()
config.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config.ini'))
# path_dir_db = os.path.abspath(config['Path']['DB'])
# 相対パスなら
if config['Path']['DB'].startswith('./'):
# python起動パスでなく、このファイルをrootとする
path_dir_db = os.path.join(os.path.abspath(os.path.dirname(__file__)), config['Path']['DB'][2:])
else:
path_dir_db = os.path.abspath(config['Path']['DB'])
# print(path_dir_db)
web.log.Log.Log().Logger.debug(path_dir_db)
if None is args.username:
args.username = config['GitHub']['User']
# print('default-username: {0}'.format(args.username))
# print(os.path.join(path_dir_db, 'GitHub.Accounts.sqlite3'))
# print(os.path.join(path_dir_db, 'GitHub.Repositories.{0}.sqlite3'.format(args.username)))
# self.__db = database.src.Database.Database()
self.__db = database.src.Database.Database(os.path.abspath(os.path.dirname(__file__)))
self.__db.Initialize()
if None is self.__db.Accounts['Accounts'].find_one(Username=args.username):
# print('指定したユーザ {0} はDBに存在しません。GitHubUserRegister.pyで登録してください。')
web.log.Log.Log().Logger.warning('指定したユーザ {0} はDBに存在しません。GitHubUserRegister.pyで登録してください。'.format(args.username))
return
# Contributionsバックアップ
self.__UpdateAllUserContributions(path_dir_db, username=args.username)
# アップローダ起動
creator = web.service.github.api.v3.AuthenticationsCreator.AuthenticationsCreator(self.__db, args.username)
authentications = creator.Create()
# user = web.service.github.api.v3.CurrentUser.CurrentUser(self.__db, args.username)
repo = web.service.github.api.v3.CurrentRepository.CurrentRepository(self.__db, args.path_dir_pj, description=args.description, homepage=args.homepage)
authData = web.service.github.api.v3.AuthenticationData.AuthenticationData()
authData.Load(self.__db.Accounts, args.username)
client = web.service.github.api.v3.Client.Client(self.__db, authentications, authData=authData, repo=repo)
main = cui.uploader.Main.Main(self.__db, client, authData, repo)
main.Run()
def __UpdateAllUserContributions(self, path_dir_db, username=None):
m = database.src.contributions.Main.Main(path_dir_db)
for a in self.__db.Accounts['Accounts'].find():
m.Run(a['Username'])
if __name__ == '__main__':
main = Main()
main.Run()
| 42.409091 | 159 | 0.665327 |
import sys
import os.path
import subprocess
import configparser
import argparse
import web.service.github.api.v3.AuthenticationsCreator
import web.service.github.api.v3.AuthenticationData
import web.service.github.api.v3.CurrentRepository
import web.service.github.api.v3.Client
import database.src.Database
import cui.uploader.Main
import web.log.Log
import database.src.contributions.Main
class Main:
def __init__(self):
pass
def Run(self):
parser = argparse.ArgumentParser(
description='GitHub Repository Uploader.',
)
parser.add_argument('path_dir_pj')
parser.add_argument('-u', '--username')
parser.add_argument('-d', '--description')
parser.add_argument('-l', '--homepage', '--link', '--url')
args = parser.parse_args()
config = configparser.ConfigParser()
config.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config.ini'))
if config['Path']['DB'].startswith('./'):
path_dir_db = os.path.join(os.path.abspath(os.path.dirname(__file__)), config['Path']['DB'][2:])
else:
path_dir_db = os.path.abspath(config['Path']['DB'])
web.log.Log.Log().Logger.debug(path_dir_db)
if None is args.username:
args.username = config['GitHub']['User']
self.__db = database.src.Database.Database(os.path.abspath(os.path.dirname(__file__)))
self.__db.Initialize()
if None is self.__db.Accounts['Accounts'].find_one(Username=args.username):
web.log.Log.Log().Logger.warning('指定したユーザ {0} はDBに存在しません。GitHubUserRegister.pyで登録してください。'.format(args.username))
return
self.__UpdateAllUserContributions(path_dir_db, username=args.username)
creator = web.service.github.api.v3.AuthenticationsCreator.AuthenticationsCreator(self.__db, args.username)
authentications = creator.Create()
repo = web.service.github.api.v3.CurrentRepository.CurrentRepository(self.__db, args.path_dir_pj, description=args.description, homepage=args.homepage)
authData = web.service.github.api.v3.AuthenticationData.AuthenticationData()
authData.Load(self.__db.Accounts, args.username)
client = web.service.github.api.v3.Client.Client(self.__db, authentications, authData=authData, repo=repo)
main = cui.uploader.Main.Main(self.__db, client, authData, repo)
main.Run()
def __UpdateAllUserContributions(self, path_dir_db, username=None):
m = database.src.contributions.Main.Main(path_dir_db)
for a in self.__db.Accounts['Accounts'].find():
m.Run(a['Username'])
if __name__ == '__main__':
main = Main()
main.Run()
| true | true |
f72bac46a7bf89e92fd86af932bfe8a7135e61d2 | 13,197 | py | Python | src/sardana/util/funcgenerator.py | schooft/sardana | 76287b416650f40da79871ee3849340d0ff31f1d | [
"CC-BY-3.0"
] | null | null | null | src/sardana/util/funcgenerator.py | schooft/sardana | 76287b416650f40da79871ee3849340d0ff31f1d | [
"CC-BY-3.0"
] | null | null | null | src/sardana/util/funcgenerator.py | schooft/sardana | 76287b416650f40da79871ee3849340d0ff31f1d | [
"CC-BY-3.0"
] | null | null | null | ##############################################################################
##
# This file is part of Sardana
##
# http://www.sardana-controls.org/
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Sardana is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
##
# Sardana 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 General Public License for more details.
##
# You should have received a copy of the GNU Lesser General Public License
# along with Sardana. If not, see <http://www.gnu.org/licenses/>.
##
##############################################################################
import time
import threading
import math
import copy
import numpy
import traceback
from sardana import State
from sardana.sardanaevent import EventGenerator, EventType
from sardana.pool.pooldefs import SynchParam, SynchDomain
from taurus.core.util.log import Logger
def strictly_increasing(l):
"""Check whether list l has strictly increasing values"""
return all(x < y for x, y in zip(l, l[1:]))
def strictly_decreasing(l):
"""Check whether list l has strictly deacreasing values"""
return all(x > y for x, y in zip(l, l[1:]))
class FunctionGenerator(EventGenerator, Logger):
"""Generator of active and passive events describing a rectangular
function.
.. note::
The FunctionGenerator class has been included in Sardana
on a provisional basis. Backwards incompatible changes
(up to and including removal of the module) may occur if
deemed necessary by the core developers.
"""
MAX_NAP_TIME = 0.1
def __init__(self, name="FunctionGenerator"):
EventGenerator.__init__(self)
Logger.__init__(self, name)
self._name = name
self._initial_domain = None
self._active_domain = None
self._position_event = threading.Event()
self._position = None
self._initial_domain_in_use = None
self._active_domain_in_use = None
self._active_events = list()
self._passive_events = list()
self._started = False
self._stopped = False
self._running = False
self._start_time = None
self._direction = None
self._condition = None
self._id = None
self._start_fired = False
def get_name(self):
return self._name
name = property(get_name)
def set_initial_domain(self, domain):
self._initial_domain = domain
def get_initial_domain(self):
return self._initial_domain
initial_domain = property(get_initial_domain, set_initial_domain)
def set_active_domain(self, domain):
self._active_domain = domain
def get_active_domain(self):
return self._active_domain
active_domain = property(get_active_domain, set_active_domain)
def set_initial_domain_in_use(self, domain):
self._initial_domain_in_use = domain
def get_initial_domain_in_use(self):
return self._initial_domain_in_use
initial_domain_in_use = property(get_initial_domain_in_use,
set_initial_domain_in_use)
def set_active_domain_in_use(self, domain):
self._active_domain_in_use = domain
def get_active_domain_in_use(self):
return self._active_domain_in_use
active_domain_in_use = property(get_active_domain_in_use,
set_active_domain_in_use)
def add_active_event(self, event):
self._active_events.append(event)
def set_active_events(self, events):
self._active_events = events
def get_active_events(self):
return self._active_events
active_events = property(get_active_events, set_active_events)
def add_passive_event(self, event):
self._passive_events.append(event)
def set_passive_events(self, events):
self._passive_events = events
def get_passive_events(self):
return self._passive_events
passive_events = property(get_passive_events, set_passive_events)
def set_direction(self, direction):
self._direction = direction
if direction == 1:
self._condition = numpy.greater_equal
elif direction == -1:
self._condition = numpy.less_equal
else:
raise ValueError("direction can be -1 or 1 (negative or positive)")
def get_direction(self):
return self._direction
direction = property(get_direction, set_direction)
def event_received(self, *args, **kwargs):
_, _, v = args
if v.error:
exc_info = v.exc_info
self.error("Synchronization base attribute in error")
msg = "Details: " + "".join(traceback.format_exception(*exc_info))
self.debug(msg)
return
self._position = v.value
self._position_event.set()
def start(self):
self._start_time = time.time()
self._stopped = False
self._started = True
self._position = None
self._start_fired = False
self._position_event.clear()
self._id = 0
self.fire_event(EventType("state"), State.Moving)
def stop(self):
self._stopped = True
def is_started(self):
return self._started
def is_stopped(self):
return self._stopped
def is_running(self):
return self._running
def run(self):
self._running = True
try:
while len(self.active_events) > 0 and not self.is_stopped():
self.wait_active()
self.fire_active()
self.wait_passive()
self.fire_passive()
self._id += 1
finally:
self._started = False
self._running = False
self._stopped = False
self.fire_event(EventType("state"), State.On)
def sleep(self, period):
if period <= 0:
return
necessary_naps = int(math.ceil(period / self.MAX_NAP_TIME))
if necessary_naps == 0: # avoid zero ZeroDivisionError
nap = 0
else:
nap = period / necessary_naps
for _ in xrange(necessary_naps):
if self.is_stopped():
break
time.sleep(nap)
def fire_start(self):
self.fire_event(EventType("start"), self._id)
self._start_fired = True
if self._id > 0:
msg = "start was fired with {0} delay".format(self._id)
self.warning(msg)
def wait_active(self):
candidate = self.active_events[0]
if self.initial_domain_in_use == SynchDomain.Time:
now = time.time()
candidate += self._start_time
self.sleep(candidate - now)
else:
while True:
if self.is_stopped():
break
if self._position_event.isSet():
self._position_event.clear()
now = self._position
if self._condition(now, candidate):
break
else:
self._position_event.wait(self.MAX_NAP_TIME)
def fire_active(self):
# check if some events needs to be skipped
i = 0
while i < len(self.active_events) - 1:
candidate = self.active_events[i + 1]
if self.initial_domain_in_use is SynchDomain.Time:
candidate += self._start_time
now = time.time()
elif self.initial_domain_in_use is SynchDomain.Position:
now = self._position
if self._condition(now, candidate):
i += 1
else:
break
self._id += i
if not self._start_fired:
self.fire_start()
self.fire_event(EventType("active"), self._id)
self.active_events = self.active_events[i + 1:]
self.passive_events = self.passive_events[i:]
def wait_passive(self):
if self.active_domain_in_use == SynchDomain.Time:
now = time.time()
candidate = self._start_time + self.passive_events[0]
self.sleep(candidate - now)
else:
while True:
if self._position_event.isSet():
self._position_event.clear()
if self._condition(self._position, self.passive_events[0]):
break
else:
self._position_event.wait(self.MAX_NAP_TIME)
if self.is_stopped():
break
def fire_passive(self):
self.fire_event(EventType("passive"), self._id)
self.set_passive_events(self.passive_events[1:])
if len(self.passive_events) == 0:
self.fire_end()
def fire_end(self):
self.fire_event(EventType("end"), self._id)
def set_configuration(self, configuration):
# make a copy since we may inject the initial time
configuration = copy.deepcopy(configuration)
active_events = []
passive_events = []
self._direction = None
# create short variables for commodity
Time = SynchDomain.Time
Position = SynchDomain.Position
Initial = SynchParam.Initial
Delay = SynchParam.Delay
Active = SynchParam.Active
Total = SynchParam.Total
Repeats = SynchParam.Repeats
for i, group in enumerate(configuration):
# inject delay as initial time - generation will be
# relative to the start time
initial_param = group.get(Initial)
if initial_param is None:
initial_param = dict()
if Time not in initial_param:
delay_param = group.get(Delay)
if Time in delay_param:
initial_param[Time] = delay_param[Time]
group[Initial] = initial_param
# determine active domain in use
msg = "no initial value in group %d" % i
if self.initial_domain in initial_param:
self.initial_domain_in_use = self.initial_domain
elif Position in initial_param:
self.initial_domain_in_use = Position
elif Time in initial_param:
self.initial_domain_in_use = Time
else:
raise ValueError(msg)
# determine passive domain in use
active_param = group.get(Active)
msg = "no active value in group %d" % i
if self.active_domain is None:
if Time in active_param:
self.active_domain_in_use = Time
elif Position in active_param:
self.active_domain_in_use = Position
else:
raise ValueError(msg)
elif self.active_domain in active_param:
self.active_domain_in_use = self.active_domain
else:
raise ValueError(msg)
# create short variables for commodity
initial_domain_in_use = self.initial_domain_in_use
active_domain_in_use = self.active_domain_in_use
repeats = group.get(Repeats, 1)
active = active_param[active_domain_in_use]
initial_in_initial_domain = initial_param[initial_domain_in_use]
initial_in_active_domain = initial_param[active_domain_in_use]
active_event_in_initial_domain = initial_in_initial_domain
active_event_in_active_domain = initial_in_active_domain
if repeats > 1:
total_param = group[Total]
total_in_initial_domain = total_param[initial_domain_in_use]
total_in_active_domain = total_param[active_domain_in_use]
for _ in xrange(repeats):
passive_event = active_event_in_active_domain + active
active_events.append(active_event_in_initial_domain)
passive_events.append(passive_event)
active_event_in_initial_domain += total_in_initial_domain
active_event_in_active_domain += total_in_active_domain
else:
active_events.append(active_event_in_initial_domain)
passive_event = active_event_in_active_domain + active
passive_events.append(passive_event)
# determine direction
if self.direction is None:
if strictly_increasing(active_events):
self.direction = 1
elif strictly_decreasing(active_events):
self.direction = -1
else:
msg = "active values indicate contradictory directions"
raise ValueError(msg)
self.active_events = active_events
self.passive_events = passive_events
| 35.286096 | 79 | 0.608169 | elf._position_event.wait(self.MAX_NAP_TIME)
def fire_active(self):
i = 0
while i < len(self.active_events) - 1:
candidate = self.active_events[i + 1]
if self.initial_domain_in_use is SynchDomain.Time:
candidate += self._start_time
now = time.time()
elif self.initial_domain_in_use is SynchDomain.Position:
now = self._position
if self._condition(now, candidate):
i += 1
else:
break
self._id += i
if not self._start_fired:
self.fire_start()
self.fire_event(EventType("active"), self._id)
self.active_events = self.active_events[i + 1:]
self.passive_events = self.passive_events[i:]
def wait_passive(self):
if self.active_domain_in_use == SynchDomain.Time:
now = time.time()
candidate = self._start_time + self.passive_events[0]
self.sleep(candidate - now)
else:
while True:
if self._position_event.isSet():
self._position_event.clear()
if self._condition(self._position, self.passive_events[0]):
break
else:
self._position_event.wait(self.MAX_NAP_TIME)
if self.is_stopped():
break
def fire_passive(self):
self.fire_event(EventType("passive"), self._id)
self.set_passive_events(self.passive_events[1:])
if len(self.passive_events) == 0:
self.fire_end()
def fire_end(self):
self.fire_event(EventType("end"), self._id)
def set_configuration(self, configuration):
configuration = copy.deepcopy(configuration)
active_events = []
passive_events = []
self._direction = None
Time = SynchDomain.Time
Position = SynchDomain.Position
Initial = SynchParam.Initial
Delay = SynchParam.Delay
Active = SynchParam.Active
Total = SynchParam.Total
Repeats = SynchParam.Repeats
for i, group in enumerate(configuration):
initial_param = group.get(Initial)
if initial_param is None:
initial_param = dict()
if Time not in initial_param:
delay_param = group.get(Delay)
if Time in delay_param:
initial_param[Time] = delay_param[Time]
group[Initial] = initial_param
msg = "no initial value in group %d" % i
if self.initial_domain in initial_param:
self.initial_domain_in_use = self.initial_domain
elif Position in initial_param:
self.initial_domain_in_use = Position
elif Time in initial_param:
self.initial_domain_in_use = Time
else:
raise ValueError(msg)
active_param = group.get(Active)
msg = "no active value in group %d" % i
if self.active_domain is None:
if Time in active_param:
self.active_domain_in_use = Time
elif Position in active_param:
self.active_domain_in_use = Position
else:
raise ValueError(msg)
elif self.active_domain in active_param:
self.active_domain_in_use = self.active_domain
else:
raise ValueError(msg)
initial_domain_in_use = self.initial_domain_in_use
active_domain_in_use = self.active_domain_in_use
repeats = group.get(Repeats, 1)
active = active_param[active_domain_in_use]
initial_in_initial_domain = initial_param[initial_domain_in_use]
initial_in_active_domain = initial_param[active_domain_in_use]
active_event_in_initial_domain = initial_in_initial_domain
active_event_in_active_domain = initial_in_active_domain
if repeats > 1:
total_param = group[Total]
total_in_initial_domain = total_param[initial_domain_in_use]
total_in_active_domain = total_param[active_domain_in_use]
for _ in xrange(repeats):
passive_event = active_event_in_active_domain + active
active_events.append(active_event_in_initial_domain)
passive_events.append(passive_event)
active_event_in_initial_domain += total_in_initial_domain
active_event_in_active_domain += total_in_active_domain
else:
active_events.append(active_event_in_initial_domain)
passive_event = active_event_in_active_domain + active
passive_events.append(passive_event)
if self.direction is None:
if strictly_increasing(active_events):
self.direction = 1
elif strictly_decreasing(active_events):
self.direction = -1
else:
msg = "active values indicate contradictory directions"
raise ValueError(msg)
self.active_events = active_events
self.passive_events = passive_events
| true | true |
f72bac8581667e7935b4584979b404c4fdca5866 | 468 | py | Python | examples/trap.py | fthyssen/aiosnmp | 667a166214e2e70c333510a6d24208dd772a1f26 | [
"MIT"
] | null | null | null | examples/trap.py | fthyssen/aiosnmp | 667a166214e2e70c333510a6d24208dd772a1f26 | [
"MIT"
] | null | null | null | examples/trap.py | fthyssen/aiosnmp | 667a166214e2e70c333510a6d24208dd772a1f26 | [
"MIT"
] | null | null | null | import asyncio
import aiosnmp
async def handler(host: str, port: int, message: aiosnmp.SnmpV2TrapMessage) -> None:
print(f"got packet from {host}:{port}")
for d in message.data.varbinds:
print(f"oid: {d.oid}, value: {d.value}")
async def main():
p = aiosnmp.SnmpV2TrapServer(
host="127.0.0.1", port=162, communities=("public",), handler=handler
)
await p.run()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
| 22.285714 | 84 | 0.662393 | import asyncio
import aiosnmp
async def handler(host: str, port: int, message: aiosnmp.SnmpV2TrapMessage) -> None:
print(f"got packet from {host}:{port}")
for d in message.data.varbinds:
print(f"oid: {d.oid}, value: {d.value}")
async def main():
p = aiosnmp.SnmpV2TrapServer(
host="127.0.0.1", port=162, communities=("public",), handler=handler
)
await p.run()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
| true | true |
f72bacd78c4c106ed1626a1724d718b3f8d317dc | 481 | py | Python | _unittests/ut_plotting/test_dummy.py | sdpython/manyapi | dc2aadc58a5d72904f95424dbe57bb832d3ccd73 | [
"MIT"
] | 1 | 2020-08-08T13:38:45.000Z | 2020-08-08T13:38:45.000Z | _unittests/ut_plotting/test_dummy.py | sdpython/manyapi | dc2aadc58a5d72904f95424dbe57bb832d3ccd73 | [
"MIT"
] | 8 | 2018-05-05T10:03:04.000Z | 2019-06-08T10:21:30.000Z | _unittests/ut_plotting/test_dummy.py | sdpython/manyapi | dc2aadc58a5d72904f95424dbe57bb832d3ccd73 | [
"MIT"
] | null | null | null | """
@brief test log(time=13s)
"""
import unittest
from pyquickhelper.pycode import ExtTestCase
from manydataapi.plotting import plot_aggregated_ts, daily_timeseries
class TestDummm(ExtTestCase):
def test_agg_raise(self):
df = daily_timeseries()
from matplotlib import pyplot as plt
_, ax = plt.subplots(1, 1)
plot_aggregated_ts(df, ax=ax, value='X', agg='year')
plt.close('all')
if __name__ == "__main__":
unittest.main()
| 21.863636 | 69 | 0.675676 | import unittest
from pyquickhelper.pycode import ExtTestCase
from manydataapi.plotting import plot_aggregated_ts, daily_timeseries
class TestDummm(ExtTestCase):
def test_agg_raise(self):
df = daily_timeseries()
from matplotlib import pyplot as plt
_, ax = plt.subplots(1, 1)
plot_aggregated_ts(df, ax=ax, value='X', agg='year')
plt.close('all')
if __name__ == "__main__":
unittest.main()
| true | true |
f72bacee48dd612bab37d2f97351e60521569498 | 6,673 | py | Python | tests/test_lammps_cycle.py | irisTa56/ease4lmp | 0ad69632fbe0d8c2a55e58af13efd7be1d566394 | [
"MIT"
] | null | null | null | tests/test_lammps_cycle.py | irisTa56/ease4lmp | 0ad69632fbe0d8c2a55e58af13efd7be1d566394 | [
"MIT"
] | 2 | 2019-03-06T04:33:27.000Z | 2019-07-27T08:30:28.000Z | tests/test_lammps_cycle.py | irisTa56/ease4lmp | 0ad69632fbe0d8c2a55e58af13efd7be1d566394 | [
"MIT"
] | null | null | null | import unittest
from ease4lmp import (
BondedAtoms, LammpsWriter,
create_atoms_from_data, create_atoms_from_molecule)
from ase.build import bulk, molecule
import numpy as np
import os
import itertools
def write_files(atoms):
writer = LammpsWriter(atoms, atom_style="molecular")
writer.set_atom_data(mol=[0]*len(atoms))
writer.set_bond_types({
seq: i+1 for i, seq in enumerate(writer.get_bond_patterns())
})
writer.set_angle_types({
seq: i+1 for i, seq in enumerate(writer.get_angle_patterns())
})
writer.set_dihedral_types({
seq: i+1 for i, seq in enumerate(writer.get_dihedral_patterns())
})
writer.set_improper_types({
seq: i+1 for i, seq in enumerate(writer.get_improper_patterns())
})
writer.write_lammps_data("data.tmp", mass=True)
writer.write_lammps_molecule("molecule.tmp", mass=True)
def remove_files():
os.remove("data.tmp")
os.remove("molecule.tmp")
class TestLammpsCycle(unittest.TestCase):
def test_methanol(self):
"""Test for equivalence between original and written/read data."""
atoms = BondedAtoms(molecule("CH3OH"))
# confirm atomic numbers
self.assertTrue(np.allclose(
atoms.get_atomic_numbers(), np.array([6, 8, 1, 1, 1, 1])))
# confirm O-H distance
self.assertTrue(np.allclose(atoms.get_distance(1, 3), 0.97))
atoms.set_types([1, 2, 3, 4, 3, 3])
positions = atoms.get_positions()
bonded_pairs = [
(i, j) for i, j in itertools.combinations(range(len(atoms)), 2)
if np.linalg.norm(positions[i] - positions[j]) < 1.5]
# there are five bonds in CH3OH
self.assertEqual(len(bonded_pairs), 5)
for pair in bonded_pairs:
atoms.add_bond(*pair)
atoms.sort_bonds()
atoms.set_cell([[5., 0., 0.], [0., 5., 0.], [0., 0., 5.]])
atoms.center()
write_files(atoms)
atoms_from_data = create_atoms_from_data("data.tmp", "molecular")
atoms_from_molecule = create_atoms_from_molecule("molecule.tmp")
# atoms from Lammps' data and molecule file must be eaqual.
self.assertTrue(np.allclose(
atoms_from_data.get_positions(), atoms_from_molecule.get_positions()))
self.assertTrue(np.allclose(
atoms_from_data.get_masses(), atoms_from_molecule.get_masses()))
self.assertTrue(np.allclose(
atoms_from_data.get_types(), atoms_from_molecule.get_types()))
self.assertTrue(np.allclose(
atoms_from_data.get_bonds(), atoms_from_molecule.get_bonds()))
# comparison with original atoms
self.assertTrue(np.allclose(
atoms_from_data.get_positions(), atoms.get_positions()))
self.assertTrue(np.allclose(
atoms_from_data.get_masses(), atoms.get_masses()))
self.assertTrue(np.allclose(
atoms_from_data.get_types(), atoms.get_types()))
# storing order of bonds might be changed
atoms_from_data.sort_bonds()
self.assertTrue(np.allclose(
atoms_from_data.get_bonds(), atoms.get_bonds()))
remove_files()
def test_acetic(self):
"""Test for equivalence between original and written/read data."""
atoms = BondedAtoms(molecule("CH3COOH"))
# confirm atomic numbers
self.assertTrue(np.allclose(
atoms.get_atomic_numbers(), np.array([6, 8, 8, 1, 6, 1, 1, 1])))
# confirm O-H distance < C=H distance
self.assertTrue(all(
atoms.get_distance(2, 3) < atoms.get_distance(i, j)
for i, j in [(4, 5), (4, 6), (4, 7)]))
atoms.set_types([1, 2, 3, 4, 5, 6, 6, 6])
positions = atoms.get_positions()
bonded_pairs = [
(i, j) for i, j in itertools.combinations(range(len(atoms)), 2)
if np.linalg.norm(positions[i] - positions[j]) < 1.5]
# there are seven bonds in CH3COOH
self.assertEqual(len(bonded_pairs), 7)
for pair in bonded_pairs:
atoms.add_bond(*pair)
atoms.sort_bonds()
atoms.set_cell([[5., 0., 0.], [0., 5., 0.], [0., 0., 5.]])
atoms.center()
write_files(atoms)
atoms_from_data = create_atoms_from_data("data.tmp", "molecular")
atoms_from_molecule = create_atoms_from_molecule("molecule.tmp")
# atoms from Lammps' data and molecule file must be eaqual.
self.assertTrue(np.allclose(
atoms_from_data.get_positions(), atoms_from_molecule.get_positions()))
self.assertTrue(np.allclose(
atoms_from_data.get_masses(), atoms_from_molecule.get_masses()))
self.assertTrue(np.allclose(
atoms_from_data.get_types(), atoms_from_molecule.get_types()))
self.assertTrue(np.allclose(
atoms_from_data.get_bonds(), atoms_from_molecule.get_bonds()))
# comparison with original atoms
self.assertTrue(np.allclose(
atoms_from_data.get_positions(), atoms.get_positions()))
self.assertTrue(np.allclose(
atoms_from_data.get_masses(), atoms.get_masses()))
self.assertTrue(np.allclose(
atoms_from_data.get_types(), atoms.get_types()))
# storing order of bonds might be changed
atoms_from_data.sort_bonds()
self.assertTrue(np.allclose(
atoms_from_data.get_bonds(), atoms.get_bonds()))
remove_files()
def test_nacl(self):
"""Test for equivalence between original and written/read data."""
atoms = BondedAtoms(bulk("NaCl", "rocksalt", a=5.64, orthorhombic=True))
# confirm atomic numbers
self.assertTrue(np.allclose(
atoms.get_atomic_numbers(), np.array([11, 17, 11, 17])))
atoms.set_types([1, 2, 1, 2])
atoms.change_max_bonds(6)
cell = atoms.get_cell()
positions = atoms.get_positions()
for i, j in itertools.combinations(range(len(atoms)), 2):
r_original = positions[j] - positions[i]
for ix, iy, iz in itertools.product(*[(-1, 0, 1)]*3):
r = r_original + ix * cell[0] + iy * cell[1] + iz * cell[2]
if np.isclose(np.linalg.norm(r), 2.82):
atoms.add_bond(i, j, img2=(ix, iy, iz))
atoms *= 5
atoms.sort_bonds()
write_files(atoms)
atoms_from_data = create_atoms_from_data(
"data.tmp", "molecular", pbc=True)
# comparison with original atoms
self.assertTrue(np.allclose(
atoms_from_data.get_positions(), atoms.get_positions()))
self.assertTrue(np.allclose(
atoms_from_data.get_masses(), atoms.get_masses()))
self.assertTrue(np.allclose(
atoms_from_data.get_types(), atoms.get_types()))
# storing order of bonds might be changed
atoms_from_data.sort_bonds()
self.assertTrue(np.allclose(
atoms_from_data.get_bonds(), atoms.get_bonds()))
remove_files()
def suite():
suite = unittest.TestSuite()
suite.addTest(TestLammpsCycle("test_methanol"))
suite.addTest(TestLammpsCycle("test_acetic"))
suite.addTest(TestLammpsCycle("test_nacl"))
return suite | 30.47032 | 76 | 0.683051 | import unittest
from ease4lmp import (
BondedAtoms, LammpsWriter,
create_atoms_from_data, create_atoms_from_molecule)
from ase.build import bulk, molecule
import numpy as np
import os
import itertools
def write_files(atoms):
writer = LammpsWriter(atoms, atom_style="molecular")
writer.set_atom_data(mol=[0]*len(atoms))
writer.set_bond_types({
seq: i+1 for i, seq in enumerate(writer.get_bond_patterns())
})
writer.set_angle_types({
seq: i+1 for i, seq in enumerate(writer.get_angle_patterns())
})
writer.set_dihedral_types({
seq: i+1 for i, seq in enumerate(writer.get_dihedral_patterns())
})
writer.set_improper_types({
seq: i+1 for i, seq in enumerate(writer.get_improper_patterns())
})
writer.write_lammps_data("data.tmp", mass=True)
writer.write_lammps_molecule("molecule.tmp", mass=True)
def remove_files():
os.remove("data.tmp")
os.remove("molecule.tmp")
class TestLammpsCycle(unittest.TestCase):
def test_methanol(self):
atoms = BondedAtoms(molecule("CH3OH"))
self.assertTrue(np.allclose(
atoms.get_atomic_numbers(), np.array([6, 8, 1, 1, 1, 1])))
self.assertTrue(np.allclose(atoms.get_distance(1, 3), 0.97))
atoms.set_types([1, 2, 3, 4, 3, 3])
positions = atoms.get_positions()
bonded_pairs = [
(i, j) for i, j in itertools.combinations(range(len(atoms)), 2)
if np.linalg.norm(positions[i] - positions[j]) < 1.5]
self.assertEqual(len(bonded_pairs), 5)
for pair in bonded_pairs:
atoms.add_bond(*pair)
atoms.sort_bonds()
atoms.set_cell([[5., 0., 0.], [0., 5., 0.], [0., 0., 5.]])
atoms.center()
write_files(atoms)
atoms_from_data = create_atoms_from_data("data.tmp", "molecular")
atoms_from_molecule = create_atoms_from_molecule("molecule.tmp")
self.assertTrue(np.allclose(
atoms_from_data.get_positions(), atoms_from_molecule.get_positions()))
self.assertTrue(np.allclose(
atoms_from_data.get_masses(), atoms_from_molecule.get_masses()))
self.assertTrue(np.allclose(
atoms_from_data.get_types(), atoms_from_molecule.get_types()))
self.assertTrue(np.allclose(
atoms_from_data.get_bonds(), atoms_from_molecule.get_bonds()))
# comparison with original atoms
self.assertTrue(np.allclose(
atoms_from_data.get_positions(), atoms.get_positions()))
self.assertTrue(np.allclose(
atoms_from_data.get_masses(), atoms.get_masses()))
self.assertTrue(np.allclose(
atoms_from_data.get_types(), atoms.get_types()))
# storing order of bonds might be changed
atoms_from_data.sort_bonds()
self.assertTrue(np.allclose(
atoms_from_data.get_bonds(), atoms.get_bonds()))
remove_files()
def test_acetic(self):
atoms = BondedAtoms(molecule("CH3COOH"))
# confirm atomic numbers
self.assertTrue(np.allclose(
atoms.get_atomic_numbers(), np.array([6, 8, 8, 1, 6, 1, 1, 1])))
# confirm O-H distance < C=H distance
self.assertTrue(all(
atoms.get_distance(2, 3) < atoms.get_distance(i, j)
for i, j in [(4, 5), (4, 6), (4, 7)]))
atoms.set_types([1, 2, 3, 4, 5, 6, 6, 6])
positions = atoms.get_positions()
bonded_pairs = [
(i, j) for i, j in itertools.combinations(range(len(atoms)), 2)
if np.linalg.norm(positions[i] - positions[j]) < 1.5]
# there are seven bonds in CH3COOH
self.assertEqual(len(bonded_pairs), 7)
for pair in bonded_pairs:
atoms.add_bond(*pair)
atoms.sort_bonds()
atoms.set_cell([[5., 0., 0.], [0., 5., 0.], [0., 0., 5.]])
atoms.center()
write_files(atoms)
atoms_from_data = create_atoms_from_data("data.tmp", "molecular")
atoms_from_molecule = create_atoms_from_molecule("molecule.tmp")
# atoms from Lammps' data and molecule file must be eaqual.
self.assertTrue(np.allclose(
atoms_from_data.get_positions(), atoms_from_molecule.get_positions()))
self.assertTrue(np.allclose(
atoms_from_data.get_masses(), atoms_from_molecule.get_masses()))
self.assertTrue(np.allclose(
atoms_from_data.get_types(), atoms_from_molecule.get_types()))
self.assertTrue(np.allclose(
atoms_from_data.get_bonds(), atoms_from_molecule.get_bonds()))
self.assertTrue(np.allclose(
atoms_from_data.get_positions(), atoms.get_positions()))
self.assertTrue(np.allclose(
atoms_from_data.get_masses(), atoms.get_masses()))
self.assertTrue(np.allclose(
atoms_from_data.get_types(), atoms.get_types()))
atoms_from_data.sort_bonds()
self.assertTrue(np.allclose(
atoms_from_data.get_bonds(), atoms.get_bonds()))
remove_files()
def test_nacl(self):
atoms = BondedAtoms(bulk("NaCl", "rocksalt", a=5.64, orthorhombic=True))
self.assertTrue(np.allclose(
atoms.get_atomic_numbers(), np.array([11, 17, 11, 17])))
atoms.set_types([1, 2, 1, 2])
atoms.change_max_bonds(6)
cell = atoms.get_cell()
positions = atoms.get_positions()
for i, j in itertools.combinations(range(len(atoms)), 2):
r_original = positions[j] - positions[i]
for ix, iy, iz in itertools.product(*[(-1, 0, 1)]*3):
r = r_original + ix * cell[0] + iy * cell[1] + iz * cell[2]
if np.isclose(np.linalg.norm(r), 2.82):
atoms.add_bond(i, j, img2=(ix, iy, iz))
atoms *= 5
atoms.sort_bonds()
write_files(atoms)
atoms_from_data = create_atoms_from_data(
"data.tmp", "molecular", pbc=True)
self.assertTrue(np.allclose(
atoms_from_data.get_positions(), atoms.get_positions()))
self.assertTrue(np.allclose(
atoms_from_data.get_masses(), atoms.get_masses()))
self.assertTrue(np.allclose(
atoms_from_data.get_types(), atoms.get_types()))
atoms_from_data.sort_bonds()
self.assertTrue(np.allclose(
atoms_from_data.get_bonds(), atoms.get_bonds()))
remove_files()
def suite():
suite = unittest.TestSuite()
suite.addTest(TestLammpsCycle("test_methanol"))
suite.addTest(TestLammpsCycle("test_acetic"))
suite.addTest(TestLammpsCycle("test_nacl"))
return suite | true | true |
f72bacff2befd45529dc6156485e5eaa617d18a2 | 611 | py | Python | api/models/post_rank/migrations/0001_initial.py | eggmoid/GalleryManage-FastAPI | fa50cef623a03aed2d7b4ac9c76d74cfb9d898eb | [
"MIT"
] | null | null | null | api/models/post_rank/migrations/0001_initial.py | eggmoid/GalleryManage-FastAPI | fa50cef623a03aed2d7b4ac9c76d74cfb9d898eb | [
"MIT"
] | 6 | 2021-08-06T16:30:03.000Z | 2021-12-11T05:30:02.000Z | api/models/post_rank/migrations/0001_initial.py | eggmoid/GalleryManage-FastAPI | fa50cef623a03aed2d7b4ac9c76d74cfb9d898eb | [
"MIT"
] | null | null | null | # Generated by Django 3.2.5 on 2021-08-25 04:03
from django.db import migrations
class Migration(migrations.Migration):
initial = True
dependencies = [
('post', '0005_alter_post_options'),
]
operations = [
migrations.CreateModel(
name='PostRank',
fields=[
],
options={
'verbose_name': '8월 갤창랭킹',
'verbose_name_plural': '8월 갤창랭킹',
'proxy': True,
'indexes': [],
'constraints': [],
},
bases=('post.post',),
),
]
| 21.068966 | 49 | 0.464812 |
from django.db import migrations
class Migration(migrations.Migration):
initial = True
dependencies = [
('post', '0005_alter_post_options'),
]
operations = [
migrations.CreateModel(
name='PostRank',
fields=[
],
options={
'verbose_name': '8월 갤창랭킹',
'verbose_name_plural': '8월 갤창랭킹',
'proxy': True,
'indexes': [],
'constraints': [],
},
bases=('post.post',),
),
]
| true | true |
f72bad3d0b4002ad1cb2fcc9489978b3fa4f88bf | 3,577 | py | Python | checkers/utils.py | gbravoi/monte-carlo-tree-search | 578df8df925e5f569e7354daff6642e1781389b6 | [
"MIT"
] | null | null | null | checkers/utils.py | gbravoi/monte-carlo-tree-search | 578df8df925e5f569e7354daff6642e1781389b6 | [
"MIT"
] | null | null | null | checkers/utils.py | gbravoi/monte-carlo-tree-search | 578df8df925e5f569e7354daff6642e1781389b6 | [
"MIT"
] | null | null | null | """
Martin Kersner, m.kersner@gmail.com
seoulai.com
2018
Adapted by Gabriela B. to work with python 2.7 and ROS
"""
import random
import numpy as np
from base import Constants
from rules import Rules
class BoardEncoding(object):
def __init__(self):
self._constants = Constants()
self._encoding = {}
self.empty = 0
self.dark = 20
self.dark_king = 21
self.light = 10
self.light_king = 11
def __getitem__(self, name):
return self._encoding[name]
@property
def empty(self):
return self._encoding[self._constants.EMPTY]
@empty.setter
def empty(self, value):
self._encoding[self._constants.EMPTY] = value
@property
def dark(self):
return self._encoding[self._constants.DARK]
@dark.setter
def dark(self, value):
self._encoding[self._constants.DARK] = value
@property
def dark_king(self):
return self._encoding[self._constants.DARK_KING]
@dark_king.setter
def dark_king(self, value):
self._encoding[self._constants.DARK_KING] = value
@property
def light(self):
return self._encoding[self._constants.LIGHT]
@light.setter
def light(self, value):
self._encoding[self._constants.LIGHT] = value
@property
def light_king(self):
return self._encoding[self._constants.LIGHT_KING]
@light_king.setter
def light_king(self, value):
self._encoding[self._constants.LIGHT_KING] = value
def board_list2numpy(
board_list,
encoding) :
"""Convert the state of game (`board_list`) into 2D NumPy Array using `encoding`.
Args:
board_list: (List[List[Piece]]) State of the game.
encoding: (BoardEncoding) Optional argument. If not given default encoding will be utilized.
Returns:
board_numpy: (np.array)
"""
board_size = len(board_list)
constants = Constants()
board_numpy = encoding[constants.EMPTY] * np.ones((board_size, board_size))
for row in range(board_size):
for col in range(board_size):
if board_list[row][col] is not None:
ptype = board_list[row][col].ptype
king = board_list[row][col].king
if ptype == constants.LIGHT:
if king:
piece_type = constants.LIGHT_KING
else:
piece_type = constants.LIGHT
else: # DARK
if king:
piece_type = constants.DARK_KING
else:
piece_type = constants.DARK
board_numpy[row][col] = encoding[piece_type]
return board_numpy
def generate_random_move(
board,
ptype,
board_size):
"""Generate random move from all `ptype` valid moves but does not execute it.
Args:
board: (List[List[Piece]]) State of the game.
ptype: (int) type of piece for which random move will be generated
board_size: (int) size of board
"""
valid_moves = Rules.generate_valid_moves(board, ptype, board_size)
rand_from_row, rand_from_col = random.choice(list(valid_moves.keys()))
rand_to_row, rand_to_col = random.choice(valid_moves[(rand_from_row, rand_from_col)])
return rand_from_row, rand_from_col, rand_to_row, rand_to_col
#new functions
def print_board(board_list):
"""
print board for debugging putposes
receives board as a board_list: List[List],
"""
numpy_board=board_list2numpy(board_list)
print(numpy_board)
| 26.496296 | 100 | 0.632933 | import random
import numpy as np
from base import Constants
from rules import Rules
class BoardEncoding(object):
def __init__(self):
self._constants = Constants()
self._encoding = {}
self.empty = 0
self.dark = 20
self.dark_king = 21
self.light = 10
self.light_king = 11
def __getitem__(self, name):
return self._encoding[name]
@property
def empty(self):
return self._encoding[self._constants.EMPTY]
@empty.setter
def empty(self, value):
self._encoding[self._constants.EMPTY] = value
@property
def dark(self):
return self._encoding[self._constants.DARK]
@dark.setter
def dark(self, value):
self._encoding[self._constants.DARK] = value
@property
def dark_king(self):
return self._encoding[self._constants.DARK_KING]
@dark_king.setter
def dark_king(self, value):
self._encoding[self._constants.DARK_KING] = value
@property
def light(self):
return self._encoding[self._constants.LIGHT]
@light.setter
def light(self, value):
self._encoding[self._constants.LIGHT] = value
@property
def light_king(self):
return self._encoding[self._constants.LIGHT_KING]
@light_king.setter
def light_king(self, value):
self._encoding[self._constants.LIGHT_KING] = value
def board_list2numpy(
board_list,
encoding) :
board_size = len(board_list)
constants = Constants()
board_numpy = encoding[constants.EMPTY] * np.ones((board_size, board_size))
for row in range(board_size):
for col in range(board_size):
if board_list[row][col] is not None:
ptype = board_list[row][col].ptype
king = board_list[row][col].king
if ptype == constants.LIGHT:
if king:
piece_type = constants.LIGHT_KING
else:
piece_type = constants.LIGHT
else:
if king:
piece_type = constants.DARK_KING
else:
piece_type = constants.DARK
board_numpy[row][col] = encoding[piece_type]
return board_numpy
def generate_random_move(
board,
ptype,
board_size):
valid_moves = Rules.generate_valid_moves(board, ptype, board_size)
rand_from_row, rand_from_col = random.choice(list(valid_moves.keys()))
rand_to_row, rand_to_col = random.choice(valid_moves[(rand_from_row, rand_from_col)])
return rand_from_row, rand_from_col, rand_to_row, rand_to_col
def print_board(board_list):
numpy_board=board_list2numpy(board_list)
print(numpy_board)
| true | true |
f72bad4faefc64d772b991b54a1874f2f71d5c3b | 1,267 | py | Python | modules/AppTheme.py | Fa1c0n35/RootTheBoxs | 4f2a9886c8eedca3039604b93929c8c09866115e | [
"Apache-2.0"
] | 1 | 2019-06-29T08:40:54.000Z | 2019-06-29T08:40:54.000Z | modules/AppTheme.py | Fa1c0n35/RootTheBoxs | 4f2a9886c8eedca3039604b93929c8c09866115e | [
"Apache-2.0"
] | null | null | null | modules/AppTheme.py | Fa1c0n35/RootTheBoxs | 4f2a9886c8eedca3039604b93929c8c09866115e | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Mar 14, 2012
@author: moloch
Copyright 2012 Root the Box
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 tornado.web import UIModule
from tornado.options import options
from models.Theme import Theme
class AppTheme(UIModule):
theme = Theme.by_name(options.default_theme)
def render(self, *args, **kwargs):
""" Includes different CSS themes based on user prefs """
if options.allow_user_to_change_theme and (self.handler.session is not None):
return self.render_string(
"theme/theme.html", theme_files=self.handler.session["theme"]
)
else:
return self.render_string("theme/theme.html", theme_files=self.theme)
| 30.902439 | 85 | 0.697711 |
from tornado.web import UIModule
from tornado.options import options
from models.Theme import Theme
class AppTheme(UIModule):
theme = Theme.by_name(options.default_theme)
def render(self, *args, **kwargs):
if options.allow_user_to_change_theme and (self.handler.session is not None):
return self.render_string(
"theme/theme.html", theme_files=self.handler.session["theme"]
)
else:
return self.render_string("theme/theme.html", theme_files=self.theme)
| true | true |
f72bad64f0a9f77a3272ef388210f662dc6820c7 | 749 | py | Python | smbl/prog/plugins/picard.py | karel-brinda/snakemake-lib | 5922fa2fc4060d86172e991361a1cceb0af51af8 | [
"MIT"
] | 26 | 2015-03-16T03:37:02.000Z | 2021-01-18T17:34:16.000Z | smbl/prog/plugins/picard.py | karel-brinda/smbl | 5922fa2fc4060d86172e991361a1cceb0af51af8 | [
"MIT"
] | 12 | 2015-02-05T10:57:16.000Z | 2016-06-07T18:09:57.000Z | smbl/prog/plugins/picard.py | karel-brinda/snakemake-lib | 5922fa2fc4060d86172e991361a1cceb0af51af8 | [
"MIT"
] | 6 | 2015-06-03T20:06:49.000Z | 2020-12-13T09:48:03.000Z | import smbl
import snakemake
import os
from ._program import *
PICARD = get_bin_file_path("picard.jar")
##########################################
##########################################
class Picard(Program):
@classmethod
def get_installation_files(cls):
return [
PICARD,
]
@classmethod
def install(cls):
ver="1.140"
fn=cls.download_file("https://github.com/broadinstitute/picard/releases/download/{ver}/picard-tools-{ver}.zip".format(ver=ver),"picard.zip")
dir=os.path.dirname(fn)
smbl.utils.shell('(cd "{dir}" && unzip -j picard.zip) > /dev/null'.format(dir=dir))
cls.install_file("picard.jar",PICARD)
@classmethod
def supported_platforms(cls):
return ["osx","linux","cygwin"]
| 23.40625 | 143 | 0.599466 | import smbl
import snakemake
import os
from ._program import *
PICARD = get_bin_file_path("picard.jar")
| true | true |
f72badcfec08b1a7904807f002fbd7e59e89878d | 2,519 | py | Python | ckan/tests/cli/test_config_tool.py | jbrown-xentity/ckan | ecd9ac6bc6cfb5bb4fcbec82c431f4564ef649ed | [
"BSD-3-Clause"
] | 2,805 | 2015-01-02T18:13:15.000Z | 2022-03-31T03:35:01.000Z | ckan/tests/cli/test_config_tool.py | jbrown-xentity/ckan | ecd9ac6bc6cfb5bb4fcbec82c431f4564ef649ed | [
"BSD-3-Clause"
] | 3,801 | 2015-01-02T11:05:36.000Z | 2022-03-31T19:24:37.000Z | ckan/tests/cli/test_config_tool.py | jbrown-xentity/ckan | ecd9ac6bc6cfb5bb4fcbec82c431f4564ef649ed | [
"BSD-3-Clause"
] | 1,689 | 2015-01-02T19:46:43.000Z | 2022-03-28T14:59:43.000Z | # -*- coding: utf-8 -*-
import os
import pytest
from ckan.cli.cli import ckan
from configparser import ConfigParser, NoOptionError
@pytest.fixture
def config_file(tmp_path):
dest = tmp_path / u'config.ini'
tpl = os.path.join(
os.path.dirname(__file__),
u'templates/config_tool.ini.tpl')
with open(tpl, u'rb') as data:
dest.write_bytes(data.read())
return dest
def _parse(config_file):
parser = ConfigParser()
parser.read([str(config_file)])
return parser
def test_config_no_params(cli, config_file):
"""test-config requires some params for update.
"""
result = cli.invoke(ckan, [u'config-tool', str(config_file)])
assert result.exit_code
def test_config_unset_debug(cli, config_file):
"""Existing values can be updated.
"""
assert _parse(config_file).get(u'app:main', u'debug') == u'true'
result = cli.invoke(
ckan,
[u'config-tool', str(config_file), u'debug=false']
)
assert not result.exit_code, result.output
assert _parse(config_file).get(u'app:main', u'debug') == u'false'
def test_config_create_custom_debug(cli, config_file):
"""New values can be added
"""
with pytest.raises(NoOptionError):
_parse(config_file).get(u'app:main', u'custom_debug')
result = cli.invoke(
ckan, [u'config-tool',
str(config_file), u'custom_debug=false'])
assert not result.exit_code, result.output
assert _parse(config_file).get(u'app:main', u'custom_debug') == u'false'
def test_config_custom_section(cli, config_file):
"""Custom section updated when specified.
"""
assert _parse(config_file).get(u'server:main', u'port') == u'5000'
result = cli.invoke(ckan, [
u'config-tool',
str(config_file), u'-s', u'server:main', u'port=8000'
])
assert not result.exit_code, result.output
assert _parse(config_file).get(u'server:main', u'port') == u'8000'
def test_merge_into_new_file(cli, config_file, tmp_path):
"""New file can be created without updating old one.
"""
dest = tmp_path / u'new_config.ini'
dest.touch()
assert _parse(config_file).get(u'app:main', u'debug') == u'true'
result = cli.invoke(
ckan,
[u'config-tool',
str(dest), u'-f',
str(config_file), u'debug=false'])
assert not result.exit_code, result.output
assert _parse(config_file).get(u'app:main', u'debug') == u'true'
assert _parse(dest).get(u'app:main', u'debug') == u'false'
| 29.988095 | 76 | 0.653831 |
import os
import pytest
from ckan.cli.cli import ckan
from configparser import ConfigParser, NoOptionError
@pytest.fixture
def config_file(tmp_path):
dest = tmp_path / u'config.ini'
tpl = os.path.join(
os.path.dirname(__file__),
u'templates/config_tool.ini.tpl')
with open(tpl, u'rb') as data:
dest.write_bytes(data.read())
return dest
def _parse(config_file):
parser = ConfigParser()
parser.read([str(config_file)])
return parser
def test_config_no_params(cli, config_file):
result = cli.invoke(ckan, [u'config-tool', str(config_file)])
assert result.exit_code
def test_config_unset_debug(cli, config_file):
assert _parse(config_file).get(u'app:main', u'debug') == u'true'
result = cli.invoke(
ckan,
[u'config-tool', str(config_file), u'debug=false']
)
assert not result.exit_code, result.output
assert _parse(config_file).get(u'app:main', u'debug') == u'false'
def test_config_create_custom_debug(cli, config_file):
with pytest.raises(NoOptionError):
_parse(config_file).get(u'app:main', u'custom_debug')
result = cli.invoke(
ckan, [u'config-tool',
str(config_file), u'custom_debug=false'])
assert not result.exit_code, result.output
assert _parse(config_file).get(u'app:main', u'custom_debug') == u'false'
def test_config_custom_section(cli, config_file):
assert _parse(config_file).get(u'server:main', u'port') == u'5000'
result = cli.invoke(ckan, [
u'config-tool',
str(config_file), u'-s', u'server:main', u'port=8000'
])
assert not result.exit_code, result.output
assert _parse(config_file).get(u'server:main', u'port') == u'8000'
def test_merge_into_new_file(cli, config_file, tmp_path):
dest = tmp_path / u'new_config.ini'
dest.touch()
assert _parse(config_file).get(u'app:main', u'debug') == u'true'
result = cli.invoke(
ckan,
[u'config-tool',
str(dest), u'-f',
str(config_file), u'debug=false'])
assert not result.exit_code, result.output
assert _parse(config_file).get(u'app:main', u'debug') == u'true'
assert _parse(dest).get(u'app:main', u'debug') == u'false'
| true | true |
f72badfdcc7c9b8294a786b553d4648ee517ad6c | 12,634 | py | Python | tests/python/pants_test/util/test_contextutil.py | ghthor/pants | 450de702414f87f563081ddefaefd8a554de07a3 | [
"Apache-2.0"
] | null | null | null | tests/python/pants_test/util/test_contextutil.py | ghthor/pants | 450de702414f87f563081ddefaefd8a554de07a3 | [
"Apache-2.0"
] | null | null | null | tests/python/pants_test/util/test_contextutil.py | ghthor/pants | 450de702414f87f563081ddefaefd8a554de07a3 | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import pstats
import shutil
import signal
import sys
import unittest
import uuid
import zipfile
from builtins import next, object, range, str
from contextlib import contextmanager
import mock
from pants.util.contextutil import (HardSystemExit, InvalidZipPath, Timer, environment_as,
exception_logging, hard_exit_handler, hermetic_environment_as,
maybe_profiled, open_zip, pushd, signal_handler_as, stdio_as,
temporary_dir, temporary_file)
from pants.util.process_handler import subprocess
PATCH_OPTS = dict(autospec=True, spec_set=True)
class ContextutilTest(unittest.TestCase):
def test_empty_environment(self):
with environment_as():
pass
def test_override_single_variable(self):
with temporary_file() as output:
# test that the override takes place
with environment_as(HORK='BORK'):
subprocess.Popen([sys.executable, '-c', 'import os; print(os.environ["HORK"])'],
stdout=output).wait()
output.seek(0)
self.assertEquals('BORK\n', output.read())
# test that the variable is cleared
with temporary_file() as new_output:
subprocess.Popen([sys.executable, '-c', 'import os; print("HORK" in os.environ)'],
stdout=new_output).wait()
new_output.seek(0)
self.assertEquals('False\n', new_output.read())
def test_environment_negation(self):
with temporary_file() as output:
with environment_as(HORK='BORK'):
with environment_as(HORK=None):
# test that the variable is cleared
subprocess.Popen([sys.executable, '-c', 'import os; print("HORK" in os.environ)'],
stdout=output).wait()
output.seek(0)
self.assertEquals('False\n', output.read())
def test_hermetic_environment(self):
self.assertIn('USER', os.environ)
with hermetic_environment_as(**{}):
self.assertNotIn('USER', os.environ)
def test_hermetic_environment_subprocesses(self):
self.assertIn('USER', os.environ)
with hermetic_environment_as(**dict(AAA='333')):
output = subprocess.check_output('env', shell=True)
self.assertNotIn('USER=', output)
self.assertIn('AAA', os.environ)
self.assertEquals(os.environ['AAA'], '333')
self.assertIn('USER', os.environ)
self.assertNotIn('AAA', os.environ)
def test_hermetic_environment_unicode(self):
UNICODE_CHAR = '¡'
ENCODED_CHAR = UNICODE_CHAR.encode('utf-8')
with environment_as(**dict(XXX=UNICODE_CHAR)):
self.assertEquals(os.environ['XXX'], ENCODED_CHAR)
with hermetic_environment_as(**dict(AAA=UNICODE_CHAR)):
self.assertIn('AAA', os.environ)
self.assertEquals(os.environ['AAA'], ENCODED_CHAR)
self.assertEquals(os.environ['XXX'], ENCODED_CHAR)
def test_simple_pushd(self):
pre_cwd = os.getcwd()
with temporary_dir() as tempdir:
with pushd(tempdir) as path:
self.assertEquals(tempdir, path)
self.assertEquals(os.path.realpath(tempdir), os.getcwd())
self.assertEquals(pre_cwd, os.getcwd())
self.assertEquals(pre_cwd, os.getcwd())
def test_nested_pushd(self):
pre_cwd = os.getcwd()
with temporary_dir() as tempdir1:
with pushd(tempdir1):
self.assertEquals(os.path.realpath(tempdir1), os.getcwd())
with temporary_dir(root_dir=tempdir1) as tempdir2:
with pushd(tempdir2):
self.assertEquals(os.path.realpath(tempdir2), os.getcwd())
self.assertEquals(os.path.realpath(tempdir1), os.getcwd())
self.assertEquals(os.path.realpath(tempdir1), os.getcwd())
self.assertEquals(pre_cwd, os.getcwd())
self.assertEquals(pre_cwd, os.getcwd())
def test_temporary_file_no_args(self):
with temporary_file() as fp:
self.assertTrue(os.path.exists(fp.name), 'Temporary file should exist within the context.')
self.assertTrue(os.path.exists(fp.name) == False,
'Temporary file should not exist outside of the context.')
def test_temporary_file_without_cleanup(self):
with temporary_file(cleanup=False) as fp:
self.assertTrue(os.path.exists(fp.name), 'Temporary file should exist within the context.')
self.assertTrue(os.path.exists(fp.name),
'Temporary file should exist outside of context if cleanup=False.')
os.unlink(fp.name)
def test_temporary_file_within_other_dir(self):
with temporary_dir() as path:
with temporary_file(root_dir=path) as f:
self.assertTrue(os.path.realpath(f.name).startswith(os.path.realpath(path)),
'file should be created in root_dir if specified.')
def test_temporary_dir_no_args(self):
with temporary_dir() as path:
self.assertTrue(os.path.exists(path), 'Temporary dir should exist within the context.')
self.assertTrue(os.path.isdir(path), 'Temporary dir should be a dir and not a file.')
self.assertFalse(os.path.exists(path), 'Temporary dir should not exist outside of the context.')
def test_temporary_dir_without_cleanup(self):
with temporary_dir(cleanup=False) as path:
self.assertTrue(os.path.exists(path), 'Temporary dir should exist within the context.')
self.assertTrue(os.path.exists(path),
'Temporary dir should exist outside of context if cleanup=False.')
shutil.rmtree(path)
def test_temporary_dir_with_root_dir(self):
with temporary_dir() as path1:
with temporary_dir(root_dir=path1) as path2:
self.assertTrue(os.path.realpath(path2).startswith(os.path.realpath(path1)),
'Nested temporary dir should be created within outer dir.')
def test_timer(self):
class FakeClock(object):
def __init__(self):
self._time = 0.0
def time(self):
ret = self._time
self._time += 0.0001 # Force a little time to elapse.
return ret
def sleep(self, duration):
self._time += duration
clock = FakeClock()
# Note: to test with the real system clock, use this instead:
# import time
# clock = time
with Timer(clock=clock) as t:
self.assertLess(t.start, clock.time())
self.assertGreater(t.elapsed, 0)
clock.sleep(0.1)
self.assertGreater(t.elapsed, 0.1)
clock.sleep(0.1)
self.assertTrue(t.finish is None)
self.assertGreater(t.elapsed, 0.2)
self.assertLess(t.finish, clock.time())
def test_open_zipDefault(self):
with temporary_dir() as tempdir:
with open_zip(os.path.join(tempdir, 'test'), 'w') as zf:
self.assertTrue(zf._allowZip64)
def test_open_zipTrue(self):
with temporary_dir() as tempdir:
with open_zip(os.path.join(tempdir, 'test'), 'w', allowZip64=True) as zf:
self.assertTrue(zf._allowZip64)
def test_open_zipFalse(self):
with temporary_dir() as tempdir:
with open_zip(os.path.join(tempdir, 'test'), 'w', allowZip64=False) as zf:
self.assertFalse(zf._allowZip64)
def test_open_zip_raises_exception_on_falsey_paths(self):
falsey = (None, '', False)
for invalid in falsey:
with self.assertRaises(InvalidZipPath):
next(open_zip(invalid).gen)
def test_open_zip_returns_realpath_on_badzipfile(self):
# In case of file corruption, deleting a Pants-constructed symlink would not resolve the error.
with temporary_file() as not_zip:
with temporary_dir() as tempdir:
file_symlink = os.path.join(tempdir, 'foo')
os.symlink(not_zip.name, file_symlink)
self.assertEquals(os.path.realpath(file_symlink), os.path.realpath(not_zip.name))
with self.assertRaisesRegexp(zipfile.BadZipfile, r'{}'.format(not_zip.name)):
next(open_zip(file_symlink).gen)
@contextmanager
def _stdio_as_tempfiles(self):
"""Harness to replace `sys.std*` with tempfiles.
Validates that all files are read/written/flushed correctly, and acts as a
contextmanager to allow for recursive tests.
"""
# Prefix contents written within this instance with a unique string to differentiate
# them from other instances.
uuid_str = str(uuid.uuid4())
def u(string):
return '{}#{}'.format(uuid_str, string)
stdin_data = u('stdio')
stdout_data = u('stdout')
stderr_data = u('stderr')
with temporary_file() as tmp_stdin,\
temporary_file() as tmp_stdout,\
temporary_file() as tmp_stderr:
print(stdin_data, file=tmp_stdin)
tmp_stdin.seek(0)
# Read prepared content from stdin, and write content to stdout/stderr.
with stdio_as(stdout_fd=tmp_stdout.fileno(),
stderr_fd=tmp_stderr.fileno(),
stdin_fd=tmp_stdin.fileno()):
self.assertEquals(sys.stdin.fileno(), 0)
self.assertEquals(sys.stdout.fileno(), 1)
self.assertEquals(sys.stderr.fileno(), 2)
self.assertEquals(stdin_data, sys.stdin.read().strip())
print(stdout_data, file=sys.stdout)
yield
print(stderr_data, file=sys.stderr)
tmp_stdout.seek(0)
tmp_stderr.seek(0)
self.assertEquals(stdout_data, tmp_stdout.read().strip())
self.assertEquals(stderr_data, tmp_stderr.read().strip())
def test_stdio_as(self):
self.assertTrue(sys.stderr.fileno() > 2,
"Expected a pseudofile as stderr, got: {}".format(sys.stderr))
old_stdout, old_stderr, old_stdin = sys.stdout, sys.stderr, sys.stdin
# The first level tests that when `sys.std*` are file-likes (in particular, the ones set up in
# pytest's harness) rather than actual files, we stash and restore them properly.
with self._stdio_as_tempfiles():
# The second level stashes the first level's actual file objects and then re-opens them.
with self._stdio_as_tempfiles():
pass
# Validate that after the second level completes, the first level still sees valid
# fds on `sys.std*`.
self.assertEquals(sys.stdin.fileno(), 0)
self.assertEquals(sys.stdout.fileno(), 1)
self.assertEquals(sys.stderr.fileno(), 2)
self.assertEquals(sys.stdout, old_stdout)
self.assertEquals(sys.stderr, old_stderr)
self.assertEquals(sys.stdin, old_stdin)
def test_stdio_as_dev_null(self):
# Capture output to tempfiles.
with self._stdio_as_tempfiles():
# Read/write from/to `/dev/null`, which will be validated by the harness as not
# affecting the tempfiles.
with stdio_as(stdout_fd=-1, stderr_fd=-1, stdin_fd=-1):
self.assertEquals(b'', sys.stdin.read())
print('garbage', file=sys.stdout)
print('garbage', file=sys.stderr)
def test_signal_handler_as(self):
mock_initial_handler = 1
mock_new_handler = 2
with mock.patch('signal.signal', **PATCH_OPTS) as mock_signal:
mock_signal.return_value = mock_initial_handler
try:
with signal_handler_as(signal.SIGUSR2, mock_new_handler):
raise NotImplementedError('blah')
except NotImplementedError:
pass
self.assertEquals(mock_signal.call_count, 2)
mock_signal.assert_has_calls([
mock.call(signal.SIGUSR2, mock_new_handler),
mock.call(signal.SIGUSR2, mock_initial_handler)
])
def test_permissions(self):
with temporary_file(permissions=0o700) as f:
self.assertEquals(0o700, os.stat(f.name)[0] & 0o777)
with temporary_dir(permissions=0o644) as path:
self.assertEquals(0o644, os.stat(path)[0] & 0o777)
def test_exception_logging(self):
fake_logger = mock.Mock()
with self.assertRaises(AssertionError):
with exception_logging(fake_logger, 'error!'):
assert True is False
fake_logger.exception.assert_called_once_with('error!')
def test_maybe_profiled(self):
with temporary_dir() as td:
profile_path = os.path.join(td, 'profile.prof')
with maybe_profiled(profile_path):
for _ in range(5):
print('test')
# Ensure the profile data was written.
self.assertTrue(os.path.exists(profile_path))
# Ensure the profile data is valid.
pstats.Stats(profile_path).print_stats()
def test_hard_exit_handler(self):
with mock.patch('os._exit', **PATCH_OPTS) as mock_exit:
with hard_exit_handler():
raise HardSystemExit()
mock_exit.assert_called_once_with(0)
| 37.93994 | 100 | 0.679516 |
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import pstats
import shutil
import signal
import sys
import unittest
import uuid
import zipfile
from builtins import next, object, range, str
from contextlib import contextmanager
import mock
from pants.util.contextutil import (HardSystemExit, InvalidZipPath, Timer, environment_as,
exception_logging, hard_exit_handler, hermetic_environment_as,
maybe_profiled, open_zip, pushd, signal_handler_as, stdio_as,
temporary_dir, temporary_file)
from pants.util.process_handler import subprocess
PATCH_OPTS = dict(autospec=True, spec_set=True)
class ContextutilTest(unittest.TestCase):
def test_empty_environment(self):
with environment_as():
pass
def test_override_single_variable(self):
with temporary_file() as output:
with environment_as(HORK='BORK'):
subprocess.Popen([sys.executable, '-c', 'import os; print(os.environ["HORK"])'],
stdout=output).wait()
output.seek(0)
self.assertEquals('BORK\n', output.read())
with temporary_file() as new_output:
subprocess.Popen([sys.executable, '-c', 'import os; print("HORK" in os.environ)'],
stdout=new_output).wait()
new_output.seek(0)
self.assertEquals('False\n', new_output.read())
def test_environment_negation(self):
with temporary_file() as output:
with environment_as(HORK='BORK'):
with environment_as(HORK=None):
subprocess.Popen([sys.executable, '-c', 'import os; print("HORK" in os.environ)'],
stdout=output).wait()
output.seek(0)
self.assertEquals('False\n', output.read())
def test_hermetic_environment(self):
self.assertIn('USER', os.environ)
with hermetic_environment_as(**{}):
self.assertNotIn('USER', os.environ)
def test_hermetic_environment_subprocesses(self):
self.assertIn('USER', os.environ)
with hermetic_environment_as(**dict(AAA='333')):
output = subprocess.check_output('env', shell=True)
self.assertNotIn('USER=', output)
self.assertIn('AAA', os.environ)
self.assertEquals(os.environ['AAA'], '333')
self.assertIn('USER', os.environ)
self.assertNotIn('AAA', os.environ)
def test_hermetic_environment_unicode(self):
UNICODE_CHAR = '¡'
ENCODED_CHAR = UNICODE_CHAR.encode('utf-8')
with environment_as(**dict(XXX=UNICODE_CHAR)):
self.assertEquals(os.environ['XXX'], ENCODED_CHAR)
with hermetic_environment_as(**dict(AAA=UNICODE_CHAR)):
self.assertIn('AAA', os.environ)
self.assertEquals(os.environ['AAA'], ENCODED_CHAR)
self.assertEquals(os.environ['XXX'], ENCODED_CHAR)
def test_simple_pushd(self):
pre_cwd = os.getcwd()
with temporary_dir() as tempdir:
with pushd(tempdir) as path:
self.assertEquals(tempdir, path)
self.assertEquals(os.path.realpath(tempdir), os.getcwd())
self.assertEquals(pre_cwd, os.getcwd())
self.assertEquals(pre_cwd, os.getcwd())
def test_nested_pushd(self):
pre_cwd = os.getcwd()
with temporary_dir() as tempdir1:
with pushd(tempdir1):
self.assertEquals(os.path.realpath(tempdir1), os.getcwd())
with temporary_dir(root_dir=tempdir1) as tempdir2:
with pushd(tempdir2):
self.assertEquals(os.path.realpath(tempdir2), os.getcwd())
self.assertEquals(os.path.realpath(tempdir1), os.getcwd())
self.assertEquals(os.path.realpath(tempdir1), os.getcwd())
self.assertEquals(pre_cwd, os.getcwd())
self.assertEquals(pre_cwd, os.getcwd())
def test_temporary_file_no_args(self):
with temporary_file() as fp:
self.assertTrue(os.path.exists(fp.name), 'Temporary file should exist within the context.')
self.assertTrue(os.path.exists(fp.name) == False,
'Temporary file should not exist outside of the context.')
def test_temporary_file_without_cleanup(self):
with temporary_file(cleanup=False) as fp:
self.assertTrue(os.path.exists(fp.name), 'Temporary file should exist within the context.')
self.assertTrue(os.path.exists(fp.name),
'Temporary file should exist outside of context if cleanup=False.')
os.unlink(fp.name)
def test_temporary_file_within_other_dir(self):
with temporary_dir() as path:
with temporary_file(root_dir=path) as f:
self.assertTrue(os.path.realpath(f.name).startswith(os.path.realpath(path)),
'file should be created in root_dir if specified.')
def test_temporary_dir_no_args(self):
with temporary_dir() as path:
self.assertTrue(os.path.exists(path), 'Temporary dir should exist within the context.')
self.assertTrue(os.path.isdir(path), 'Temporary dir should be a dir and not a file.')
self.assertFalse(os.path.exists(path), 'Temporary dir should not exist outside of the context.')
def test_temporary_dir_without_cleanup(self):
with temporary_dir(cleanup=False) as path:
self.assertTrue(os.path.exists(path), 'Temporary dir should exist within the context.')
self.assertTrue(os.path.exists(path),
'Temporary dir should exist outside of context if cleanup=False.')
shutil.rmtree(path)
def test_temporary_dir_with_root_dir(self):
with temporary_dir() as path1:
with temporary_dir(root_dir=path1) as path2:
self.assertTrue(os.path.realpath(path2).startswith(os.path.realpath(path1)),
'Nested temporary dir should be created within outer dir.')
def test_timer(self):
class FakeClock(object):
def __init__(self):
self._time = 0.0
def time(self):
ret = self._time
self._time += 0.0001
return ret
def sleep(self, duration):
self._time += duration
clock = FakeClock()
with Timer(clock=clock) as t:
self.assertLess(t.start, clock.time())
self.assertGreater(t.elapsed, 0)
clock.sleep(0.1)
self.assertGreater(t.elapsed, 0.1)
clock.sleep(0.1)
self.assertTrue(t.finish is None)
self.assertGreater(t.elapsed, 0.2)
self.assertLess(t.finish, clock.time())
def test_open_zipDefault(self):
with temporary_dir() as tempdir:
with open_zip(os.path.join(tempdir, 'test'), 'w') as zf:
self.assertTrue(zf._allowZip64)
def test_open_zipTrue(self):
with temporary_dir() as tempdir:
with open_zip(os.path.join(tempdir, 'test'), 'w', allowZip64=True) as zf:
self.assertTrue(zf._allowZip64)
def test_open_zipFalse(self):
with temporary_dir() as tempdir:
with open_zip(os.path.join(tempdir, 'test'), 'w', allowZip64=False) as zf:
self.assertFalse(zf._allowZip64)
def test_open_zip_raises_exception_on_falsey_paths(self):
falsey = (None, '', False)
for invalid in falsey:
with self.assertRaises(InvalidZipPath):
next(open_zip(invalid).gen)
def test_open_zip_returns_realpath_on_badzipfile(self):
with temporary_file() as not_zip:
with temporary_dir() as tempdir:
file_symlink = os.path.join(tempdir, 'foo')
os.symlink(not_zip.name, file_symlink)
self.assertEquals(os.path.realpath(file_symlink), os.path.realpath(not_zip.name))
with self.assertRaisesRegexp(zipfile.BadZipfile, r'{}'.format(not_zip.name)):
next(open_zip(file_symlink).gen)
@contextmanager
def _stdio_as_tempfiles(self):
uuid_str = str(uuid.uuid4())
def u(string):
return '{}#{}'.format(uuid_str, string)
stdin_data = u('stdio')
stdout_data = u('stdout')
stderr_data = u('stderr')
with temporary_file() as tmp_stdin,\
temporary_file() as tmp_stdout,\
temporary_file() as tmp_stderr:
print(stdin_data, file=tmp_stdin)
tmp_stdin.seek(0)
with stdio_as(stdout_fd=tmp_stdout.fileno(),
stderr_fd=tmp_stderr.fileno(),
stdin_fd=tmp_stdin.fileno()):
self.assertEquals(sys.stdin.fileno(), 0)
self.assertEquals(sys.stdout.fileno(), 1)
self.assertEquals(sys.stderr.fileno(), 2)
self.assertEquals(stdin_data, sys.stdin.read().strip())
print(stdout_data, file=sys.stdout)
yield
print(stderr_data, file=sys.stderr)
tmp_stdout.seek(0)
tmp_stderr.seek(0)
self.assertEquals(stdout_data, tmp_stdout.read().strip())
self.assertEquals(stderr_data, tmp_stderr.read().strip())
def test_stdio_as(self):
self.assertTrue(sys.stderr.fileno() > 2,
"Expected a pseudofile as stderr, got: {}".format(sys.stderr))
old_stdout, old_stderr, old_stdin = sys.stdout, sys.stderr, sys.stdin
with self._stdio_as_tempfiles():
# The second level stashes the first level's actual file objects and then re-opens them.
with self._stdio_as_tempfiles():
pass
self.assertEquals(sys.stdin.fileno(), 0)
self.assertEquals(sys.stdout.fileno(), 1)
self.assertEquals(sys.stderr.fileno(), 2)
self.assertEquals(sys.stdout, old_stdout)
self.assertEquals(sys.stderr, old_stderr)
self.assertEquals(sys.stdin, old_stdin)
def test_stdio_as_dev_null(self):
with self._stdio_as_tempfiles():
with stdio_as(stdout_fd=-1, stderr_fd=-1, stdin_fd=-1):
self.assertEquals(b'', sys.stdin.read())
print('garbage', file=sys.stdout)
print('garbage', file=sys.stderr)
def test_signal_handler_as(self):
mock_initial_handler = 1
mock_new_handler = 2
with mock.patch('signal.signal', **PATCH_OPTS) as mock_signal:
mock_signal.return_value = mock_initial_handler
try:
with signal_handler_as(signal.SIGUSR2, mock_new_handler):
raise NotImplementedError('blah')
except NotImplementedError:
pass
self.assertEquals(mock_signal.call_count, 2)
mock_signal.assert_has_calls([
mock.call(signal.SIGUSR2, mock_new_handler),
mock.call(signal.SIGUSR2, mock_initial_handler)
])
def test_permissions(self):
with temporary_file(permissions=0o700) as f:
self.assertEquals(0o700, os.stat(f.name)[0] & 0o777)
with temporary_dir(permissions=0o644) as path:
self.assertEquals(0o644, os.stat(path)[0] & 0o777)
def test_exception_logging(self):
fake_logger = mock.Mock()
with self.assertRaises(AssertionError):
with exception_logging(fake_logger, 'error!'):
assert True is False
fake_logger.exception.assert_called_once_with('error!')
def test_maybe_profiled(self):
with temporary_dir() as td:
profile_path = os.path.join(td, 'profile.prof')
with maybe_profiled(profile_path):
for _ in range(5):
print('test')
self.assertTrue(os.path.exists(profile_path))
pstats.Stats(profile_path).print_stats()
def test_hard_exit_handler(self):
with mock.patch('os._exit', **PATCH_OPTS) as mock_exit:
with hard_exit_handler():
raise HardSystemExit()
mock_exit.assert_called_once_with(0)
| true | true |
f72bae6a1e0213eb229c54b75687299a18759829 | 1,090 | py | Python | IntroProPython/aula10-poo/ex10_9.py | SweydAbdul/estudos-python | b052708d0566a0afb9a1c04d035467d45f820879 | [
"MIT"
] | null | null | null | IntroProPython/aula10-poo/ex10_9.py | SweydAbdul/estudos-python | b052708d0566a0afb9a1c04d035467d45f820879 | [
"MIT"
] | null | null | null | IntroProPython/aula10-poo/ex10_9.py | SweydAbdul/estudos-python | b052708d0566a0afb9a1c04d035467d45f820879 | [
"MIT"
] | null | null | null | #Nilo soluction
class Estado:
def __init__(self, nome, sigla):
self.nome = nome
self.sigla = sigla
self.cidades = []
def adiciona_cidades(self, cidade):
cidade.estado = self
self.cidades.append(cidade)
def populacao(self):
return sum([c.populacao for c in self.cidades])
class Cidade:
def __init__(self, nome, populacao):
self.nome = nome
self.populacao = populacao
self.estado = None
def __str__(self):
return f'''Cidade (nome={self.nome}, populacao={self.populacao},
estado={self.estado})'''
# Populacoes obtidas no site da wikipedia
# IBGE estimativa 2012
am = Estado('Amazonas', 'AM')
am.adiciona_cidades(Cidade('manaus', 1861838))
am.adiciona_cidades(Cidade('Parintins', 103828))
am.adiciona_cidades(Cidade('Itacoatiara', 89064))
for estado in [am]:
print(f'Estado: {estado.nome} Sigla: {estado.sigla}')
for cidade in estado.cidades:
print(f'Cidade: {cidade.nome}, Populacao: {cidade.populacao}')
print(f'Populacaodo Estado: {estado.populacao()}\n') | 28.684211 | 72 | 0.655963 |
class Estado:
def __init__(self, nome, sigla):
self.nome = nome
self.sigla = sigla
self.cidades = []
def adiciona_cidades(self, cidade):
cidade.estado = self
self.cidades.append(cidade)
def populacao(self):
return sum([c.populacao for c in self.cidades])
class Cidade:
def __init__(self, nome, populacao):
self.nome = nome
self.populacao = populacao
self.estado = None
def __str__(self):
return f'''Cidade (nome={self.nome}, populacao={self.populacao},
estado={self.estado})'''
am = Estado('Amazonas', 'AM')
am.adiciona_cidades(Cidade('manaus', 1861838))
am.adiciona_cidades(Cidade('Parintins', 103828))
am.adiciona_cidades(Cidade('Itacoatiara', 89064))
for estado in [am]:
print(f'Estado: {estado.nome} Sigla: {estado.sigla}')
for cidade in estado.cidades:
print(f'Cidade: {cidade.nome}, Populacao: {cidade.populacao}')
print(f'Populacaodo Estado: {estado.populacao()}\n') | true | true |
f72baec4eeaab524e7f16dca567ab548d635f3bb | 3,949 | py | Python | samples/basic/crud/models/cisco-ios-xr/Cisco-IOS-XR-shellutil-oper/nc-read-xr-shellutil-oper-20-ydk.py | maccioni/ydk-py-samples | d1758694bef97327c5477e65649326c7595ce499 | [
"Apache-2.0"
] | 104 | 2016-03-15T17:04:01.000Z | 2021-12-31T06:09:35.000Z | samples/basic/crud/models/cisco-ios-xr/Cisco-IOS-XR-shellutil-oper/nc-read-xr-shellutil-oper-20-ydk.py | https-maxus-github-com/ydk-py-samples | 1ad6cc2b798f358ff835df93d12924df308b85fc | [
"Apache-2.0"
] | 15 | 2016-03-15T23:09:47.000Z | 2020-08-13T12:13:18.000Z | samples/basic/crud/models/cisco-ios-xr/Cisco-IOS-XR-shellutil-oper/nc-read-xr-shellutil-oper-20-ydk.py | https-maxus-github-com/ydk-py-samples | 1ad6cc2b798f358ff835df93d12924df308b85fc | [
"Apache-2.0"
] | 87 | 2016-04-15T16:59:23.000Z | 2021-09-18T18:05:47.000Z | #!/usr/bin/env python
#
# Copyright 2016 Cisco Systems, 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.
#
"""
Read all data for model Cisco-IOS-XR-shellutil-oper.
usage: nc-read-xr-shellutil-oper-20-ydk.py [-h] [-v] device
positional arguments:
device NETCONF device (ssh://user:password@host:port)
optional arguments:
-h, --help show this help message and exit
-v, --verbose print debugging messages
"""
from argparse import ArgumentParser
from urlparse import urlparse
from ydk.services import CRUDService
from ydk.providers import NetconfServiceProvider
from ydk.models.cisco_ios_xr import Cisco_IOS_XR_shellutil_oper \
as xr_shellutil_oper
import datetime
import textwrap
import logging
def process_system_time(system_time):
"""Process data in system_time object."""
# format string for system time
show_system_time = textwrap.dedent("""
Host: {host}
System time: {time} {tzone} {date}
Time source: {source}
System uptime: {uptime}
""").strip()
# create time object
clock_time = datetime.time(system_time.clock.hour,
system_time.clock.minute,
system_time.clock.second,
system_time.clock.millisecond / 1000)
# create date object
clock_date = datetime.date(system_time.clock.year,
system_time.clock.month,
system_time.clock.day)
# convert uptime from seconds
clock_delta = datetime.timedelta(seconds=system_time.uptime.uptime)
# return formatted string
return(show_system_time.format(host=system_time.uptime.host_name,
time=clock_time,
tzone=system_time.clock.time_zone,
date=clock_date,
source=system_time.clock.time_source.name,
uptime=clock_delta))
if __name__ == "__main__":
"""Execute main program."""
parser = ArgumentParser()
parser.add_argument("-v", "--verbose", help="print debugging messages",
action="store_true")
parser.add_argument("device",
help="NETCONF device (ssh://user:password@host:port)")
args = parser.parse_args()
device = urlparse(args.device)
# log debug messages if verbose argument specified
if args.verbose:
logger = logging.getLogger("ydk")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter(("%(asctime)s - %(name)s - "
"%(levelname)s - %(message)s"))
handler.setFormatter(formatter)
logger.addHandler(handler)
# create NETCONF provider
provider = NetconfServiceProvider(address=device.hostname,
port=device.port,
username=device.username,
password=device.password,
protocol=device.scheme)
# create CRUD service
crud = CRUDService()
system_time = xr_shellutil_oper.SystemTime() # create object
# read data from NETCONF device
system_time = crud.read(provider, system_time)
print(process_system_time(system_time)) # process object data
exit()
# End of script
| 34.946903 | 78 | 0.622436 |
from argparse import ArgumentParser
from urlparse import urlparse
from ydk.services import CRUDService
from ydk.providers import NetconfServiceProvider
from ydk.models.cisco_ios_xr import Cisco_IOS_XR_shellutil_oper \
as xr_shellutil_oper
import datetime
import textwrap
import logging
def process_system_time(system_time):
show_system_time = textwrap.dedent("""
Host: {host}
System time: {time} {tzone} {date}
Time source: {source}
System uptime: {uptime}
""").strip()
clock_time = datetime.time(system_time.clock.hour,
system_time.clock.minute,
system_time.clock.second,
system_time.clock.millisecond / 1000)
clock_date = datetime.date(system_time.clock.year,
system_time.clock.month,
system_time.clock.day)
clock_delta = datetime.timedelta(seconds=system_time.uptime.uptime)
return(show_system_time.format(host=system_time.uptime.host_name,
time=clock_time,
tzone=system_time.clock.time_zone,
date=clock_date,
source=system_time.clock.time_source.name,
uptime=clock_delta))
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("-v", "--verbose", help="print debugging messages",
action="store_true")
parser.add_argument("device",
help="NETCONF device (ssh://user:password@host:port)")
args = parser.parse_args()
device = urlparse(args.device)
if args.verbose:
logger = logging.getLogger("ydk")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter(("%(asctime)s - %(name)s - "
"%(levelname)s - %(message)s"))
handler.setFormatter(formatter)
logger.addHandler(handler)
provider = NetconfServiceProvider(address=device.hostname,
port=device.port,
username=device.username,
password=device.password,
protocol=device.scheme)
crud = CRUDService()
system_time = xr_shellutil_oper.SystemTime()
system_time = crud.read(provider, system_time)
print(process_system_time(system_time))
exit()
| true | true |
f72baf0f5132719036a4523e688ff00bace31589 | 6,130 | py | Python | scrape_mars.py | darrenluc93/web-scraping-challenge | 50a9a21161ab0920038c8e0d6a9390bb8e35c5f5 | [
"ADSL"
] | null | null | null | scrape_mars.py | darrenluc93/web-scraping-challenge | 50a9a21161ab0920038c8e0d6a9390bb8e35c5f5 | [
"ADSL"
] | null | null | null | scrape_mars.py | darrenluc93/web-scraping-challenge | 50a9a21161ab0920038c8e0d6a9390bb8e35c5f5 | [
"ADSL"
] | null | null | null | #Import Libraries
#Web Scraping tools
from bs4 import BeautifulSoup as bs
from selenium import webdriver
#from splinter import Browser
#DataFrame tools
import pandas as pd
#Misc tools for web scraping
import time
import requests
#Function to initianilze browser.
def init_browser():
#Settings for headless mode.
options = webdriver.ChromeOptions()
options.add_argument('headless')
#path to the driver and load the options.
browser = webdriver.Chrome("/usr/local/bin/chromedriver",chrome_options = options)
#returns the brower.
return browser
def scrapper():
#Call browser function
browser = init_browser()
#Dictionary to store all the results.
marsInfo_dict = {}
#Code to get NASA Mars News ----------------------------------------------------------------------------------------------
try:
url = "https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&year=2020%3Apublish_date&category=19%2C165%2C184%2C204&blank_scope=Latest"
#splinter option - open url
#browser.visit(url)
#Open url.
browser.get(url)
#Time to let the website load all the elements
time.sleep(4)
#splinter option - save HTML
#html = browser.html
#save the html source.
html = browser.page_source
#Use bs4 to parse the html response.
soup = bs(html, "html.parser")
#Collect the latest news title
news_title = soup.find_all('li', class_="slide")[0].find(class_="content_title").text
news_p = soup.find_all('li', class_="slide")[0].text
marsInfo_dict['news_title'] = news_title
marsInfo_dict['news_p'] = news_p
except :
print(f"Problem at website {url}")
#Code to get JPL Mars Space Images - Featured Image ---------------------------------------------------------------------------------
try:
url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars"
#splinter option - open url
#browser.visit(url)
#Opens the url.
browser.get(url)
#splinter option - FULL IMAGE BUTTON
#browser.click_link_by_id("full_image")
#Interact with the FULL IMAGE BUTTON
browser.find_element_by_id("full_image").click()
time.sleep(4)
#splinter option - save HTML
#html = browser.html
#save the html source.
html = browser.page_source
#Use bs4 to parse the html response.
soup = bs(html, "html.parser")
featured_image_url = "https://www.jpl.nasa.gov/" + soup.find_all('img', class_="fancybox-image")[0]['src']
marsInfo_dict['featured_image_url'] = featured_image_url
except :
print(f"Problem at website {url}")
#Mars Weather ------------------------------------------------------------------------------------------------------------------------
try:
url = "https://twitter.com/marswxreport?lang=en"
#splinter option - open url
#browser.visit(url)
#Open the url.
browser.get(url)
#Time to let the website load all the elements
time.sleep(4)
#splinter option - save HTML
#html = browser.html
#save the html source.
html = browser.page_source
#Use bs4 to parse the html response.
soup = bs(html, "html.parser")
mars_weather = soup.find_all('article', class_="css-1dbjc4n r-1loqt21 r-18u37iz r-1ny4l3l r-o7ynqc r-6416eg")[0].text.strip().replace('Mars Weather@MarsWxReport·19hInSight ','')
marsInfo_dict['mars_weather'] = mars_weather
except :
print(mars_weather)
print(f"Problem at website {url}")
# Mars Facts--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
try:
url = 'http://space-facts.com/mars/'
#Load url to pandas read html.
tables = pd.read_html(url)
#Tables
marsFacts_df = tables[0]
earthMars_df = tables[1]
#Rename columns
marsFacts_df.columns = ['Facts', 'Values']
#Outpout
html_outputFacts = marsFacts_df.to_html(index = False)
html_outputFacts = html_outputFacts.replace('\n', '')
html_outputMarsEarth = earthMars_df.to_html(index = False)
html_outputMarsEarth = html_outputMarsEarth.replace('\n', '')
marsInfo_dict['html_outputFacts'] = html_outputFacts
marsInfo_dict['html_outputMarsEarth'] = html_outputMarsEarth
except :
print(f"Problem at website {url}")
#hemisphereImages ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
try:
temp_list = []
url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars"
#splinter option - open url
#browser.visit(url)
#Opens the url.
browser.get(url)
time.sleep(4)
#splinter option - save HTML
#html = browser.html
#save the html source.
html = browser.page_source
# close web browser
browser.close()
#Use bs4 to parse the html response.
soup = bs(html, "html.parser")
links = soup.find_all('div', class_="description")
for link in links:
highDef_url = f"https://astrogeology.usgs.gov{link.find('a')['href']}"
responseHighDef = requests.get(highDef_url)
soupHighDef = bs(responseHighDef.text, 'html.parser')
highDef_url = soupHighDef.find_all("div", class_="downloads")[0].find('a')['href']
title = link.find('h3').text
temp_list.append({"title" : title, "img_url" : highDef_url})
marsInfo_dict['hemisphere_image_urls'] = temp_list
except :
print(f"Problem at website {url}")
return marsInfo_dict | 29.471154 | 194 | 0.556444 |
from bs4 import BeautifulSoup as bs
from selenium import webdriver
import pandas as pd
import time
import requests
def init_browser():
options = webdriver.ChromeOptions()
options.add_argument('headless')
browser = webdriver.Chrome("/usr/local/bin/chromedriver",chrome_options = options)
return browser
def scrapper():
browser = init_browser()
marsInfo_dict = {}
try:
url = "https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&year=2020%3Apublish_date&category=19%2C165%2C184%2C204&blank_scope=Latest"
browser.get(url)
time.sleep(4)
html = browser.page_source
soup = bs(html, "html.parser")
news_title = soup.find_all('li', class_="slide")[0].find(class_="content_title").text
news_p = soup.find_all('li', class_="slide")[0].text
marsInfo_dict['news_title'] = news_title
marsInfo_dict['news_p'] = news_p
except :
print(f"Problem at website {url}")
try:
url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars"
browser.get(url)
browser.find_element_by_id("full_image").click()
time.sleep(4)
html = browser.page_source
soup = bs(html, "html.parser")
featured_image_url = "https://www.jpl.nasa.gov/" + soup.find_all('img', class_="fancybox-image")[0]['src']
marsInfo_dict['featured_image_url'] = featured_image_url
except :
print(f"Problem at website {url}")
try:
url = "https://twitter.com/marswxreport?lang=en"
browser.get(url)
time.sleep(4)
html = browser.page_source
soup = bs(html, "html.parser")
mars_weather = soup.find_all('article', class_="css-1dbjc4n r-1loqt21 r-18u37iz r-1ny4l3l r-o7ynqc r-6416eg")[0].text.strip().replace('Mars Weather@MarsWxReport·19hInSight ','')
marsInfo_dict['mars_weather'] = mars_weather
except :
print(mars_weather)
print(f"Problem at website {url}")
try:
url = 'http://space-facts.com/mars/'
tables = pd.read_html(url)
marsFacts_df = tables[0]
earthMars_df = tables[1]
marsFacts_df.columns = ['Facts', 'Values']
html_outputFacts = marsFacts_df.to_html(index = False)
html_outputFacts = html_outputFacts.replace('\n', '')
html_outputMarsEarth = earthMars_df.to_html(index = False)
html_outputMarsEarth = html_outputMarsEarth.replace('\n', '')
marsInfo_dict['html_outputFacts'] = html_outputFacts
marsInfo_dict['html_outputMarsEarth'] = html_outputMarsEarth
except :
print(f"Problem at website {url}")
try:
temp_list = []
url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars"
browser.get(url)
time.sleep(4)
html = browser.page_source
browser.close()
soup = bs(html, "html.parser")
links = soup.find_all('div', class_="description")
for link in links:
highDef_url = f"https://astrogeology.usgs.gov{link.find('a')['href']}"
responseHighDef = requests.get(highDef_url)
soupHighDef = bs(responseHighDef.text, 'html.parser')
highDef_url = soupHighDef.find_all("div", class_="downloads")[0].find('a')['href']
title = link.find('h3').text
temp_list.append({"title" : title, "img_url" : highDef_url})
marsInfo_dict['hemisphere_image_urls'] = temp_list
except :
print(f"Problem at website {url}")
return marsInfo_dict | true | true |
f72bb0dfab67291261f8d64decce38b078e31dc2 | 1,812 | py | Python | API/client/python-client-generated/test/test_model_flow_chart_node_component_api.py | zhuofusong/machine-fault-diagnosis | 4c35885e3fbb3c552f526019313a8eae9df28905 | [
"MIT"
] | 2 | 2020-04-30T01:06:55.000Z | 2020-06-08T04:11:28.000Z | API/client/python-client-generated/test/test_model_flow_chart_node_component_api.py | zhuofusong/machine-fault-diagnosis | 4c35885e3fbb3c552f526019313a8eae9df28905 | [
"MIT"
] | 5 | 2020-04-13T14:13:53.000Z | 2021-08-24T17:16:30.000Z | API/client/python-client-generated/test/test_model_flow_chart_node_component_api.py | zhuofusong/machine-fault-diagnosis | 4c35885e3fbb3c552f526019313a8eae9df28905 | [
"MIT"
] | null | null | null | # coding: utf-8
"""
Machine fault diagnosis
List of top level server APIs # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from api.model_flow_chart_node_component_api import ModelFlowChartNodeComponentApi # noqa: E501
from swagger_client.rest import ApiException
class TestModelFlowChartNodeComponentApi(unittest.TestCase):
"""ModelFlowChartNodeComponentApi unit test stubs"""
def setUp(self):
self.api = api.model_flow_chart_node_component_api.ModelFlowChartNodeComponentApi() # noqa: E501
def tearDown(self):
pass
def test_model_flow_node_model_flow_id_node_id_component_delete(self):
"""Test case for model_flow_node_model_flow_id_node_id_component_delete
delete a node's components information in a model flow chart # noqa: E501
"""
pass
def test_model_flow_node_model_flow_id_node_id_component_get(self):
"""Test case for model_flow_node_model_flow_id_node_id_component_get
retrieve a node's components information in a model flow chart # noqa: E501
"""
pass
def test_model_flow_node_model_flow_id_node_id_component_post(self):
"""Test case for model_flow_node_model_flow_id_node_id_component_post
create a node's components information in a model flow chart # noqa: E501
"""
pass
def test_model_flow_node_model_flow_id_node_id_component_put(self):
"""Test case for model_flow_node_model_flow_id_node_id_component_put
update a node's components information in a model flow chart # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()
| 29.225806 | 105 | 0.734547 |
from __future__ import absolute_import
import unittest
import swagger_client
from api.model_flow_chart_node_component_api import ModelFlowChartNodeComponentApi
from swagger_client.rest import ApiException
class TestModelFlowChartNodeComponentApi(unittest.TestCase):
def setUp(self):
self.api = api.model_flow_chart_node_component_api.ModelFlowChartNodeComponentApi()
def tearDown(self):
pass
def test_model_flow_node_model_flow_id_node_id_component_delete(self):
pass
def test_model_flow_node_model_flow_id_node_id_component_get(self):
pass
def test_model_flow_node_model_flow_id_node_id_component_post(self):
pass
def test_model_flow_node_model_flow_id_node_id_component_put(self):
pass
if __name__ == '__main__':
unittest.main()
| true | true |
f72bb188e19f59d4f42c726c98471832b4cf7c08 | 62 | py | Python | run_ai_api.py | datesann0109/D_2117 | 07a94c65c622cf2aa9f2a852f1f28e647a5823bd | [
"MIT"
] | 1 | 2021-10-19T02:43:30.000Z | 2021-10-19T02:43:30.000Z | run_ai_api.py | datesann0109/D_2117 | 07a94c65c622cf2aa9f2a852f1f28e647a5823bd | [
"MIT"
] | 1 | 2021-10-30T04:46:00.000Z | 2021-10-30T04:46:00.000Z | run_ai_api.py | datesann0109/D_2117 | 07a94c65c622cf2aa9f2a852f1f28e647a5823bd | [
"MIT"
] | 2 | 2021-10-30T22:58:39.000Z | 2021-11-01T10:19:45.000Z | from ai.api import main
if __name__ == "__main__":
main() | 15.5 | 26 | 0.66129 | from ai.api import main
if __name__ == "__main__":
main() | true | true |
f72bb1d1d668b0faf7a48161762de174a03e8bff | 154 | py | Python | Cours-3/Programmes-Python/M3-2.py | Naereen/Introduction-au-Numerique-avec-Python-dpt-DEM-2020 | ee935f67970acbb3c8ba0373f57c21826340c3aa | [
"MIT"
] | 1 | 2020-10-07T19:44:29.000Z | 2020-10-07T19:44:29.000Z | Cours-3/Programmes-Python/M3-2.py | Naereen/Introduction-au-Num-rique-avec-Python-dpt-DEM-2020 | ee935f67970acbb3c8ba0373f57c21826340c3aa | [
"MIT"
] | null | null | null | Cours-3/Programmes-Python/M3-2.py | Naereen/Introduction-au-Num-rique-avec-Python-dpt-DEM-2020 | ee935f67970acbb3c8ba0373f57c21826340c3aa | [
"MIT"
] | null | null | null | somme = 0
n = 5 # valeur quelconque
i = 1
while i <= n:
somme = somme + i
i = i + 1
print("La somme des", n, "premiers entiers est :", somme)
| 19.25 | 57 | 0.558442 | somme = 0
n = 5
i = 1
while i <= n:
somme = somme + i
i = i + 1
print("La somme des", n, "premiers entiers est :", somme)
| true | true |
f72bb320c80fb2f7343a4f0f36be5c6b322a7a94 | 107,134 | py | Python | bigquery/google/cloud/bigquery/job.py | erikwebb/google-cloud-python | 288a878e9a07239015c78a193eca1cc15e926127 | [
"Apache-2.0"
] | 1 | 2019-01-23T21:54:51.000Z | 2019-01-23T21:54:51.000Z | bigquery/google/cloud/bigquery/job.py | erikwebb/google-cloud-python | 288a878e9a07239015c78a193eca1cc15e926127 | [
"Apache-2.0"
] | null | null | null | bigquery/google/cloud/bigquery/job.py | erikwebb/google-cloud-python | 288a878e9a07239015c78a193eca1cc15e926127 | [
"Apache-2.0"
] | 1 | 2020-11-15T11:44:36.000Z | 2020-11-15T11:44:36.000Z | # Copyright 2015 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define API Jobs."""
import copy
import threading
from six.moves import http_client
import google.api_core.future.polling
from google.cloud import exceptions
from google.cloud.exceptions import NotFound
from google.cloud.bigquery.dataset import DatasetReference
from google.cloud.bigquery.external_config import ExternalConfig
from google.cloud.bigquery.query import _query_param_from_api_repr
from google.cloud.bigquery.query import ArrayQueryParameter
from google.cloud.bigquery.query import ScalarQueryParameter
from google.cloud.bigquery.query import StructQueryParameter
from google.cloud.bigquery.query import UDFResource
from google.cloud.bigquery.retry import DEFAULT_RETRY
from google.cloud.bigquery.schema import SchemaField
from google.cloud.bigquery.table import _EmptyRowIterator
from google.cloud.bigquery.table import EncryptionConfiguration
from google.cloud.bigquery.table import TableReference
from google.cloud.bigquery.table import Table
from google.cloud.bigquery.table import TimePartitioning
from google.cloud.bigquery import _helpers
_DONE_STATE = "DONE"
_STOPPED_REASON = "stopped"
_TIMEOUT_BUFFER_SECS = 0.1
_ERROR_REASON_TO_EXCEPTION = {
"accessDenied": http_client.FORBIDDEN,
"backendError": http_client.INTERNAL_SERVER_ERROR,
"billingNotEnabled": http_client.FORBIDDEN,
"billingTierLimitExceeded": http_client.BAD_REQUEST,
"blocked": http_client.FORBIDDEN,
"duplicate": http_client.CONFLICT,
"internalError": http_client.INTERNAL_SERVER_ERROR,
"invalid": http_client.BAD_REQUEST,
"invalidQuery": http_client.BAD_REQUEST,
"notFound": http_client.NOT_FOUND,
"notImplemented": http_client.NOT_IMPLEMENTED,
"quotaExceeded": http_client.FORBIDDEN,
"rateLimitExceeded": http_client.FORBIDDEN,
"resourceInUse": http_client.BAD_REQUEST,
"resourcesExceeded": http_client.BAD_REQUEST,
"responseTooLarge": http_client.FORBIDDEN,
"stopped": http_client.OK,
"tableUnavailable": http_client.BAD_REQUEST,
}
def _error_result_to_exception(error_result):
"""Maps BigQuery error reasons to an exception.
The reasons and their matching HTTP status codes are documented on
the `troubleshooting errors`_ page.
.. _troubleshooting errors: https://cloud.google.com/bigquery\
/troubleshooting-errors
:type error_result: Mapping[str, str]
:param error_result: The error result from BigQuery.
:rtype google.cloud.exceptions.GoogleCloudError:
:returns: The mapped exception.
"""
reason = error_result.get("reason")
status_code = _ERROR_REASON_TO_EXCEPTION.get(
reason, http_client.INTERNAL_SERVER_ERROR
)
return exceptions.from_http_status(
status_code, error_result.get("message", ""), errors=[error_result]
)
class Compression(object):
"""The compression type to use for exported files. The default value is
:attr:`NONE`.
:attr:`DEFLATE` and :attr:`SNAPPY` are
only supported for Avro.
"""
GZIP = "GZIP"
"""Specifies GZIP format."""
DEFLATE = "DEFLATE"
"""Specifies DEFLATE format."""
SNAPPY = "SNAPPY"
"""Specifies SNAPPY format."""
NONE = "NONE"
"""Specifies no compression."""
class CreateDisposition(object):
"""Specifies whether the job is allowed to create new tables. The default
value is :attr:`CREATE_IF_NEEDED`.
Creation, truncation and append actions occur as one atomic update
upon job completion.
"""
CREATE_IF_NEEDED = "CREATE_IF_NEEDED"
"""If the table does not exist, BigQuery creates the table."""
CREATE_NEVER = "CREATE_NEVER"
"""The table must already exist. If it does not, a 'notFound' error is
returned in the job result."""
class DestinationFormat(object):
"""The exported file format. The default value is :attr:`CSV`.
Tables with nested or repeated fields cannot be exported as CSV.
"""
CSV = "CSV"
"""Specifies CSV format."""
NEWLINE_DELIMITED_JSON = "NEWLINE_DELIMITED_JSON"
"""Specifies newline delimited JSON format."""
AVRO = "AVRO"
"""Specifies Avro format."""
class Encoding(object):
"""The character encoding of the data. The default is :attr:`UTF_8`.
BigQuery decodes the data after the raw, binary data has been
split using the values of the quote and fieldDelimiter properties.
"""
UTF_8 = "UTF-8"
"""Specifies UTF-8 encoding."""
ISO_8859_1 = "ISO-8859-1"
"""Specifies ISO-8859-1 encoding."""
class QueryPriority(object):
"""Specifies a priority for the query. The default value is
:attr:`INTERACTIVE`.
"""
INTERACTIVE = "INTERACTIVE"
"""Specifies interactive priority."""
BATCH = "BATCH"
"""Specifies batch priority."""
class SourceFormat(object):
"""The format of the data files. The default value is :attr:`CSV`.
Note that the set of allowed values for loading data is different
than the set used for external data sources (see
:class:`~google.cloud.bigquery.external_config.ExternalSourceFormat`).
"""
CSV = "CSV"
"""Specifies CSV format."""
DATASTORE_BACKUP = "DATASTORE_BACKUP"
"""Specifies datastore backup format"""
NEWLINE_DELIMITED_JSON = "NEWLINE_DELIMITED_JSON"
"""Specifies newline delimited JSON format."""
AVRO = "AVRO"
"""Specifies Avro format."""
PARQUET = "PARQUET"
"""Specifies Parquet format."""
ORC = "ORC"
"""Specifies Orc format."""
class WriteDisposition(object):
"""Specifies the action that occurs if destination table already exists.
The default value is :attr:`WRITE_APPEND`.
Each action is atomic and only occurs if BigQuery is able to complete
the job successfully. Creation, truncation and append actions occur as one
atomic update upon job completion.
"""
WRITE_APPEND = "WRITE_APPEND"
"""If the table already exists, BigQuery appends the data to the table."""
WRITE_TRUNCATE = "WRITE_TRUNCATE"
"""If the table already exists, BigQuery overwrites the table data."""
WRITE_EMPTY = "WRITE_EMPTY"
"""If the table already exists and contains data, a 'duplicate' error is
returned in the job result."""
class SchemaUpdateOption(object):
"""Specifies an update to the destination table schema as a side effect of
a load job.
"""
ALLOW_FIELD_ADDITION = "ALLOW_FIELD_ADDITION"
"""Allow adding a nullable field to the schema."""
ALLOW_FIELD_RELAXATION = "ALLOW_FIELD_RELAXATION"
"""Allow relaxing a required field in the original schema to nullable."""
class _JobReference(object):
"""A reference to a job.
Arguments:
job_id (str): ID of the job to run.
project (str): ID of the project where the job runs.
location (str): Location of where the job runs.
"""
def __init__(self, job_id, project, location):
self._properties = {"jobId": job_id, "projectId": project}
# The location field must not be populated if it is None.
if location:
self._properties["location"] = location
@property
def job_id(self):
"""str: ID of the job."""
return self._properties.get("jobId")
@property
def project(self):
"""str: ID of the project where the job runs."""
return self._properties.get("projectId")
@property
def location(self):
"""str: Location where the job runs."""
return self._properties.get("location")
def _to_api_repr(self):
"""Returns the API resource representation of the job reference."""
return copy.deepcopy(self._properties)
@classmethod
def _from_api_repr(cls, resource):
"""Returns a job reference for an API resource representation."""
job_id = resource.get("jobId")
project = resource.get("projectId")
location = resource.get("location")
job_ref = cls(job_id, project, location)
return job_ref
class _AsyncJob(google.api_core.future.polling.PollingFuture):
"""Base class for asynchronous jobs.
Arguments:
job_id (Union[str, _JobReference]):
Job's ID in the project associated with the client or a
fully-qualified job reference.
client (google.cloud.bigquery.client.Client):
Client which holds credentials and project configuration.
"""
def __init__(self, job_id, client):
super(_AsyncJob, self).__init__()
# The job reference can be either a plain job ID or the full resource.
# Populate the properties dictionary consistently depending on what has
# been passed in.
job_ref = job_id
if not isinstance(job_id, _JobReference):
job_ref = _JobReference(job_id, client.project, None)
self._properties = {"jobReference": job_ref._to_api_repr()}
self._client = client
self._result_set = False
self._completion_lock = threading.Lock()
@property
def job_id(self):
"""str: ID of the job."""
return _helpers._get_sub_prop(self._properties, ["jobReference", "jobId"])
@property
def project(self):
"""Project bound to the job.
:rtype: str
:returns: the project (derived from the client).
"""
return _helpers._get_sub_prop(self._properties, ["jobReference", "projectId"])
@property
def location(self):
"""str: Location where the job runs."""
return _helpers._get_sub_prop(self._properties, ["jobReference", "location"])
def _require_client(self, client):
"""Check client or verify over-ride.
:type client: :class:`~google.cloud.bigquery.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current dataset.
:rtype: :class:`google.cloud.bigquery.client.Client`
:returns: The client passed in or the currently bound client.
"""
if client is None:
client = self._client
return client
@property
def job_type(self):
"""Type of job
:rtype: str
:returns: one of 'load', 'copy', 'extract', 'query'
"""
return self._JOB_TYPE
@property
def path(self):
"""URL path for the job's APIs.
:rtype: str
:returns: the path based on project and job ID.
"""
return "/projects/%s/jobs/%s" % (self.project, self.job_id)
@property
def labels(self):
"""Dict[str, str]: Labels for the job."""
return self._properties.setdefault("labels", {})
@property
def etag(self):
"""ETag for the job resource.
:rtype: str, or ``NoneType``
:returns: the ETag (None until set from the server).
"""
return self._properties.get("etag")
@property
def self_link(self):
"""URL for the job resource.
:rtype: str, or ``NoneType``
:returns: the URL (None until set from the server).
"""
return self._properties.get("selfLink")
@property
def user_email(self):
"""E-mail address of user who submitted the job.
:rtype: str, or ``NoneType``
:returns: the URL (None until set from the server).
"""
return self._properties.get("user_email")
@property
def created(self):
"""Datetime at which the job was created.
:rtype: ``datetime.datetime``, or ``NoneType``
:returns: the creation time (None until set from the server).
"""
statistics = self._properties.get("statistics")
if statistics is not None:
millis = statistics.get("creationTime")
if millis is not None:
return _helpers._datetime_from_microseconds(millis * 1000.0)
@property
def started(self):
"""Datetime at which the job was started.
:rtype: ``datetime.datetime``, or ``NoneType``
:returns: the start time (None until set from the server).
"""
statistics = self._properties.get("statistics")
if statistics is not None:
millis = statistics.get("startTime")
if millis is not None:
return _helpers._datetime_from_microseconds(millis * 1000.0)
@property
def ended(self):
"""Datetime at which the job finished.
:rtype: ``datetime.datetime``, or ``NoneType``
:returns: the end time (None until set from the server).
"""
statistics = self._properties.get("statistics")
if statistics is not None:
millis = statistics.get("endTime")
if millis is not None:
return _helpers._datetime_from_microseconds(millis * 1000.0)
def _job_statistics(self):
"""Helper for job-type specific statistics-based properties."""
statistics = self._properties.get("statistics", {})
return statistics.get(self._JOB_TYPE, {})
@property
def error_result(self):
"""Error information about the job as a whole.
:rtype: mapping, or ``NoneType``
:returns: the error information (None until set from the server).
"""
status = self._properties.get("status")
if status is not None:
return status.get("errorResult")
@property
def errors(self):
"""Information about individual errors generated by the job.
:rtype: list of mappings, or ``NoneType``
:returns: the error information (None until set from the server).
"""
status = self._properties.get("status")
if status is not None:
return status.get("errors")
@property
def state(self):
"""Status of the job.
:rtype: str, or ``NoneType``
:returns: the state (None until set from the server).
"""
status = self._properties.get("status")
if status is not None:
return status.get("state")
def _scrub_local_properties(self, cleaned):
"""Helper: handle subclass properties in cleaned."""
pass
def _copy_configuration_properties(self, configuration):
"""Helper: assign subclass configuration properties in cleaned."""
raise NotImplementedError("Abstract")
def _set_properties(self, api_response):
"""Update properties from resource in body of ``api_response``
:type api_response: dict
:param api_response: response returned from an API call
"""
cleaned = api_response.copy()
self._scrub_local_properties(cleaned)
statistics = cleaned.get("statistics", {})
if "creationTime" in statistics:
statistics["creationTime"] = float(statistics["creationTime"])
if "startTime" in statistics:
statistics["startTime"] = float(statistics["startTime"])
if "endTime" in statistics:
statistics["endTime"] = float(statistics["endTime"])
self._properties.clear()
self._properties.update(cleaned)
self._copy_configuration_properties(cleaned.get("configuration", {}))
# For Future interface
self._set_future_result()
@classmethod
def _get_resource_config(cls, resource):
"""Helper for :meth:`from_api_repr`
:type resource: dict
:param resource: resource for the job
:rtype: dict
:returns: tuple (string, dict), where the first element is the
job ID and the second contains job-specific configuration.
:raises: :class:`KeyError` if the resource has no identifier, or
is missing the appropriate configuration.
"""
if "jobReference" not in resource or "jobId" not in resource["jobReference"]:
raise KeyError(
"Resource lacks required identity information: "
'["jobReference"]["jobId"]'
)
job_id = resource["jobReference"]["jobId"]
if (
"configuration" not in resource
or cls._JOB_TYPE not in resource["configuration"]
):
raise KeyError(
"Resource lacks required configuration: "
'["configuration"]["%s"]' % cls._JOB_TYPE
)
return job_id, resource["configuration"]
def to_api_repr(self):
"""Generate a resource for the job."""
raise NotImplementedError("Abstract")
_build_resource = to_api_repr # backward-compatibility alias
def _begin(self, client=None, retry=DEFAULT_RETRY):
"""API call: begin the job via a POST request
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/insert
:type client: :class:`~google.cloud.bigquery.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current dataset.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the RPC.
:raises: :exc:`ValueError` if the job has already begin.
"""
if self.state is not None:
raise ValueError("Job already begun.")
client = self._require_client(client)
path = "/projects/%s/jobs" % (self.project,)
# jobs.insert is idempotent because we ensure that every new
# job has an ID.
api_response = client._call_api(
retry, method="POST", path=path, data=self.to_api_repr()
)
self._set_properties(api_response)
def exists(self, client=None, retry=DEFAULT_RETRY):
"""API call: test for the existence of the job via a GET request
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/get
:type client: :class:`~google.cloud.bigquery.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current dataset.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the RPC.
:rtype: bool
:returns: Boolean indicating existence of the job.
"""
client = self._require_client(client)
extra_params = {"fields": "id"}
if self.location:
extra_params["location"] = self.location
try:
client._call_api(
retry, method="GET", path=self.path, query_params=extra_params
)
except NotFound:
return False
else:
return True
def reload(self, client=None, retry=DEFAULT_RETRY):
"""API call: refresh job properties via a GET request.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/get
:type client: :class:`~google.cloud.bigquery.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current dataset.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the RPC.
"""
client = self._require_client(client)
extra_params = {}
if self.location:
extra_params["location"] = self.location
api_response = client._call_api(
retry, method="GET", path=self.path, query_params=extra_params
)
self._set_properties(api_response)
def cancel(self, client=None):
"""API call: cancel job via a POST request
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/cancel
:type client: :class:`~google.cloud.bigquery.client.Client` or
``NoneType``
:param client: the client to use. If not passed, falls back to the
``client`` stored on the current dataset.
:rtype: bool
:returns: Boolean indicating that the cancel request was sent.
"""
client = self._require_client(client)
extra_params = {}
if self.location:
extra_params["location"] = self.location
api_response = client._connection.api_request(
method="POST", path="%s/cancel" % (self.path,), query_params=extra_params
)
self._set_properties(api_response["job"])
# The Future interface requires that we return True if the *attempt*
# to cancel was successful.
return True
# The following methods implement the PollingFuture interface. Note that
# the methods above are from the pre-Future interface and are left for
# compatibility. The only "overloaded" method is :meth:`cancel`, which
# satisfies both interfaces.
def _set_future_result(self):
"""Set the result or exception from the job if it is complete."""
# This must be done in a lock to prevent the polling thread
# and main thread from both executing the completion logic
# at the same time.
with self._completion_lock:
# If the operation isn't complete or if the result has already been
# set, do not call set_result/set_exception again.
# Note: self._result_set is set to True in set_result and
# set_exception, in case those methods are invoked directly.
if self.state != _DONE_STATE or self._result_set:
return
if self.error_result is not None:
exception = _error_result_to_exception(self.error_result)
self.set_exception(exception)
else:
self.set_result(self)
def done(self, retry=DEFAULT_RETRY):
"""Refresh the job and checks if it is complete.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the RPC.
:rtype: bool
:returns: True if the job is complete, False otherwise.
"""
# Do not refresh is the state is already done, as the job will not
# change once complete.
if self.state != _DONE_STATE:
self.reload(retry=retry)
return self.state == _DONE_STATE
def result(self, timeout=None, retry=DEFAULT_RETRY):
"""Start the job and wait for it to complete and get the result.
:type timeout: float
:param timeout:
How long (in seconds) to wait for job to complete before raising
a :class:`concurrent.futures.TimeoutError`.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the RPC.
:rtype: _AsyncJob
:returns: This instance.
:raises:
:class:`~google.cloud.exceptions.GoogleCloudError` if the job
failed or :class:`concurrent.futures.TimeoutError` if the job did
not complete in the given timeout.
"""
if self.state is None:
self._begin(retry=retry)
# TODO: modify PollingFuture so it can pass a retry argument to done().
return super(_AsyncJob, self).result(timeout=timeout)
def cancelled(self):
"""Check if the job has been cancelled.
This always returns False. It's not possible to check if a job was
cancelled in the API. This method is here to satisfy the interface
for :class:`google.api_core.future.Future`.
:rtype: bool
:returns: False
"""
return (
self.error_result is not None
and self.error_result.get("reason") == _STOPPED_REASON
)
class _JobConfig(object):
"""Abstract base class for job configuration objects.
Arguments:
job_type (str): The key to use for the job configuration.
"""
def __init__(self, job_type, **kwargs):
self._job_type = job_type
self._properties = {job_type: {}}
for prop, val in kwargs.items():
setattr(self, prop, val)
@property
def labels(self):
"""Dict[str, str]: Labels for the job.
This method always returns a dict. To change a job's labels,
modify the dict, then call ``Client.update_job``. To delete a
label, set its value to :data:`None` before updating.
Raises:
ValueError: If ``value`` type is invalid.
"""
return self._properties.setdefault("labels", {})
@labels.setter
def labels(self, value):
if not isinstance(value, dict):
raise ValueError("Pass a dict")
self._properties["labels"] = value
def _get_sub_prop(self, key, default=None):
"""Get a value in the ``self._properties[self._job_type]`` dictionary.
Most job properties are inside the dictionary related to the job type
(e.g. 'copy', 'extract', 'load', 'query'). Use this method to access
those properties::
self._get_sub_prop('destinationTable')
This is equivalent to using the ``_helpers._get_sub_prop`` function::
_helpers._get_sub_prop(
self._properties, ['query', 'destinationTable'])
Arguments:
key (str):
Key for the value to get in the
``self._properties[self._job_type]`` dictionary.
default (object):
(Optional) Default value to return if the key is not found.
Defaults to :data:`None`.
Returns:
object: The value if present or the default.
"""
return _helpers._get_sub_prop(
self._properties, [self._job_type, key], default=default
)
def _set_sub_prop(self, key, value):
"""Set a value in the ``self._properties[self._job_type]`` dictionary.
Most job properties are inside the dictionary related to the job type
(e.g. 'copy', 'extract', 'load', 'query'). Use this method to set
those properties::
self._set_sub_prop('useLegacySql', False)
This is equivalent to using the ``_helper._set_sub_prop`` function::
_helper._set_sub_prop(
self._properties, ['query', 'useLegacySql'], False)
Arguments:
key (str):
Key to set in the ``self._properties[self._job_type]``
dictionary.
value (object): Value to set.
"""
_helpers._set_sub_prop(self._properties, [self._job_type, key], value)
def _del_sub_prop(self, key):
"""Remove ``key`` from the ``self._properties[self._job_type]`` dict.
Most job properties are inside the dictionary related to the job type
(e.g. 'copy', 'extract', 'load', 'query'). Use this method to clear
those properties::
self._del_sub_prop('useLegacySql')
This is equivalent to using the ``_helper._del_sub_prop`` function::
_helper._del_sub_prop(
self._properties, ['query', 'useLegacySql'])
Arguments:
key (str):
Key to remove in the ``self._properties[self._job_type]``
dictionary.
"""
_helpers._del_sub_prop(self._properties, [self._job_type, key])
def to_api_repr(self):
"""Build an API representation of the job config.
:rtype: dict
:returns: A dictionary in the format used by the BigQuery API.
"""
return copy.deepcopy(self._properties)
def _fill_from_default(self, default_job_config):
"""Merge this job config with a default job config.
The keys in this object take precedence over the keys in the default
config. The merge is done at the top-level as well as for keys one
level below the job type.
Arguments:
default_job_config (google.cloud.bigquery.job._JobConfig):
The default job config that will be used to fill in self.
Returns:
google.cloud.bigquery.job._JobConfig A new (merged) job config.
"""
if self._job_type != default_job_config._job_type:
raise TypeError(
"attempted to merge two incompatible job types: "
+ repr(self._job_type)
+ ", "
+ repr(default_job_config._job_type)
)
new_job_config = self.__class__()
default_job_properties = copy.deepcopy(default_job_config._properties)
for key in self._properties:
if key != self._job_type:
default_job_properties[key] = self._properties[key]
default_job_properties[self._job_type].update(self._properties[self._job_type])
new_job_config._properties = default_job_properties
return new_job_config
@classmethod
def from_api_repr(cls, resource):
"""Factory: construct a job configuration given its API representation
:type resource: dict
:param resource:
An extract job configuration in the same representation as is
returned from the API.
:rtype: :class:`google.cloud.bigquery.job._JobConfig`
:returns: Configuration parsed from ``resource``.
"""
config = cls()
config._properties = copy.deepcopy(resource)
return config
class LoadJobConfig(_JobConfig):
"""Configuration options for load jobs.
All properties in this class are optional. Values which are :data:`None` ->
server defaults. Set properties on the constructed configuration by using
the property name as the name of a keyword argument.
"""
def __init__(self, **kwargs):
super(LoadJobConfig, self).__init__("load", **kwargs)
@property
def allow_jagged_rows(self):
"""bool: Allow missing trailing optional columns (CSV only).
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.allowJaggedRows
"""
return self._get_sub_prop("allowJaggedRows")
@allow_jagged_rows.setter
def allow_jagged_rows(self, value):
self._set_sub_prop("allowJaggedRows", value)
@property
def allow_quoted_newlines(self):
"""bool: Allow quoted data containing newline characters (CSV only).
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.allowQuotedNewlines
"""
return self._get_sub_prop("allowQuotedNewlines")
@allow_quoted_newlines.setter
def allow_quoted_newlines(self, value):
self._set_sub_prop("allowQuotedNewlines", value)
@property
def autodetect(self):
"""bool: Automatically infer the schema from a sample of the data.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.autodetect
"""
return self._get_sub_prop("autodetect")
@autodetect.setter
def autodetect(self, value):
self._set_sub_prop("autodetect", value)
@property
def clustering_fields(self):
"""Union[List[str], None]: Fields defining clustering for the table
(Defaults to :data:`None`).
Clustering fields are immutable after table creation.
.. note::
As of 2018-06-29, clustering fields cannot be set on a table
which does not also have time partioning defined.
"""
prop = self._get_sub_prop("clustering")
if prop is not None:
return list(prop.get("fields", ()))
@clustering_fields.setter
def clustering_fields(self, value):
"""Union[List[str], None]: Fields defining clustering for the table
(Defaults to :data:`None`).
"""
if value is not None:
self._set_sub_prop("clustering", {"fields": value})
else:
self._del_sub_prop("clustering")
@property
def create_disposition(self):
"""google.cloud.bigquery.job.CreateDisposition: Specifies behavior
for creating tables.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.createDisposition
"""
return self._get_sub_prop("createDisposition")
@create_disposition.setter
def create_disposition(self, value):
self._set_sub_prop("createDisposition", value)
@property
def destination_encryption_configuration(self):
"""google.cloud.bigquery.table.EncryptionConfiguration: Custom
encryption configuration for the destination table.
Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None`
if using default encryption.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.destinationEncryptionConfiguration
"""
prop = self._get_sub_prop("destinationEncryptionConfiguration")
if prop is not None:
prop = EncryptionConfiguration.from_api_repr(prop)
return prop
@destination_encryption_configuration.setter
def destination_encryption_configuration(self, value):
api_repr = value
if value is not None:
api_repr = value.to_api_repr()
self._set_sub_prop("destinationEncryptionConfiguration", api_repr)
else:
self._del_sub_prop("destinationEncryptionConfiguration")
@property
def destination_table_description(self):
"""Union[str, None] name given to destination table.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.destinationTableProperties.description
"""
prop = self._get_sub_prop("destinationTableProperties")
if prop is not None:
return prop["description"]
@destination_table_description.setter
def destination_table_description(self, value):
keys = [self._job_type, "destinationTableProperties", "description"]
if value is not None:
_helpers._set_sub_prop(self._properties, keys, value)
else:
_helpers._del_sub_prop(self._properties, keys)
@property
def destination_table_friendly_name(self):
"""Union[str, None] name given to destination table.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.destinationTableProperties.friendlyName
"""
prop = self._get_sub_prop("destinationTableProperties")
if prop is not None:
return prop["friendlyName"]
@destination_table_friendly_name.setter
def destination_table_friendly_name(self, value):
keys = [self._job_type, "destinationTableProperties", "friendlyName"]
if value is not None:
_helpers._set_sub_prop(self._properties, keys, value)
else:
_helpers._del_sub_prop(self._properties, keys)
@property
def encoding(self):
"""google.cloud.bigquery.job.Encoding: The character encoding of the
data.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.encoding
"""
return self._get_sub_prop("encoding")
@encoding.setter
def encoding(self, value):
self._set_sub_prop("encoding", value)
@property
def field_delimiter(self):
"""str: The separator for fields in a CSV file.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.fieldDelimiter
"""
return self._get_sub_prop("fieldDelimiter")
@field_delimiter.setter
def field_delimiter(self, value):
self._set_sub_prop("fieldDelimiter", value)
@property
def ignore_unknown_values(self):
"""bool: Ignore extra values not represented in the table schema.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.ignoreUnknownValues
"""
return self._get_sub_prop("ignoreUnknownValues")
@ignore_unknown_values.setter
def ignore_unknown_values(self, value):
self._set_sub_prop("ignoreUnknownValues", value)
@property
def max_bad_records(self):
"""int: Number of invalid rows to ignore.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.maxBadRecords
"""
return _helpers._int_or_none(self._get_sub_prop("maxBadRecords"))
@max_bad_records.setter
def max_bad_records(self, value):
self._set_sub_prop("maxBadRecords", value)
@property
def null_marker(self):
"""str: Represents a null value (CSV only).
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.nullMarker
"""
return self._get_sub_prop("nullMarker")
@null_marker.setter
def null_marker(self, value):
self._set_sub_prop("nullMarker", value)
@property
def quote_character(self):
"""str: Character used to quote data sections (CSV only).
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.quote
"""
return self._get_sub_prop("quote")
@quote_character.setter
def quote_character(self, value):
self._set_sub_prop("quote", value)
@property
def schema(self):
"""List[google.cloud.bigquery.schema.SchemaField]: Schema of the
destination table.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.schema
"""
schema = _helpers._get_sub_prop(self._properties, ["load", "schema", "fields"])
if schema is None:
return
return [SchemaField.from_api_repr(field) for field in schema]
@schema.setter
def schema(self, value):
if not all(hasattr(field, "to_api_repr") for field in value):
raise ValueError("Schema items must be fields")
_helpers._set_sub_prop(
self._properties,
["load", "schema", "fields"],
[field.to_api_repr() for field in value],
)
@property
def schema_update_options(self):
"""List[google.cloud.bigquery.job.SchemaUpdateOption]: Specifies
updates to the destination table schema to allow as a side effect of
the load job.
"""
return self._get_sub_prop("schemaUpdateOptions")
@schema_update_options.setter
def schema_update_options(self, values):
self._set_sub_prop("schemaUpdateOptions", values)
@property
def skip_leading_rows(self):
"""int: Number of rows to skip when reading data (CSV only).
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.skipLeadingRows
"""
return _helpers._int_or_none(self._get_sub_prop("skipLeadingRows"))
@skip_leading_rows.setter
def skip_leading_rows(self, value):
self._set_sub_prop("skipLeadingRows", str(value))
@property
def source_format(self):
"""google.cloud.bigquery.job.SourceFormat: File format of the data.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.sourceFormat
"""
return self._get_sub_prop("sourceFormat")
@source_format.setter
def source_format(self, value):
self._set_sub_prop("sourceFormat", value)
@property
def time_partitioning(self):
"""google.cloud.bigquery.table.TimePartitioning: Specifies time-based
partitioning for the destination table.
"""
prop = self._get_sub_prop("timePartitioning")
if prop is not None:
prop = TimePartitioning.from_api_repr(prop)
return prop
@time_partitioning.setter
def time_partitioning(self, value):
api_repr = value
if value is not None:
api_repr = value.to_api_repr()
self._set_sub_prop("timePartitioning", api_repr)
else:
self._del_sub_prop("timePartitioning")
@property
def use_avro_logical_types(self):
"""bool: For loads of Avro data, governs whether Avro logical types are
converted to their corresponding BigQuery types(e.g. TIMESTAMP) rather than
raw types (e.g. INTEGER).
"""
return self._get_sub_prop("useAvroLogicalTypes")
@use_avro_logical_types.setter
def use_avro_logical_types(self, value):
self._set_sub_prop("useAvroLogicalTypes", bool(value))
@property
def write_disposition(self):
"""google.cloud.bigquery.job.WriteDisposition: Action that occurs if
the destination table already exists.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.writeDisposition
"""
return self._get_sub_prop("writeDisposition")
@write_disposition.setter
def write_disposition(self, value):
self._set_sub_prop("writeDisposition", value)
class LoadJob(_AsyncJob):
"""Asynchronous job for loading data into a table.
Can load from Google Cloud Storage URIs or from a file.
:type job_id: str
:param job_id: the job's ID
:type source_uris: sequence of string or ``NoneType``
:param source_uris:
URIs of one or more data files to be loaded. See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load.sourceUris
for supported URI formats. Pass None for jobs that load from a file.
:type destination: :class:`google.cloud.bigquery.table.TableReference`
:param destination: reference to table into which data is to be loaded.
:type client: :class:`google.cloud.bigquery.client.Client`
:param client: A client which holds credentials and project configuration
for the dataset (which requires a project).
"""
_JOB_TYPE = "load"
def __init__(self, job_id, source_uris, destination, client, job_config=None):
super(LoadJob, self).__init__(job_id, client)
if job_config is None:
job_config = LoadJobConfig()
self.source_uris = source_uris
self.destination = destination
self._configuration = job_config
@property
def allow_jagged_rows(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.allow_jagged_rows`.
"""
return self._configuration.allow_jagged_rows
@property
def allow_quoted_newlines(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.allow_quoted_newlines`.
"""
return self._configuration.allow_quoted_newlines
@property
def autodetect(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.autodetect`.
"""
return self._configuration.autodetect
@property
def create_disposition(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.create_disposition`.
"""
return self._configuration.create_disposition
@property
def encoding(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.encoding`.
"""
return self._configuration.encoding
@property
def field_delimiter(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.field_delimiter`.
"""
return self._configuration.field_delimiter
@property
def ignore_unknown_values(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.ignore_unknown_values`.
"""
return self._configuration.ignore_unknown_values
@property
def max_bad_records(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.max_bad_records`.
"""
return self._configuration.max_bad_records
@property
def null_marker(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.null_marker`.
"""
return self._configuration.null_marker
@property
def quote_character(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.quote_character`.
"""
return self._configuration.quote_character
@property
def skip_leading_rows(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.skip_leading_rows`.
"""
return self._configuration.skip_leading_rows
@property
def source_format(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.source_format`.
"""
return self._configuration.source_format
@property
def write_disposition(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.write_disposition`.
"""
return self._configuration.write_disposition
@property
def schema(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.schema`.
"""
return self._configuration.schema
@property
def destination_encryption_configuration(self):
"""google.cloud.bigquery.table.EncryptionConfiguration: Custom
encryption configuration for the destination table.
Custom encryption configuration (e.g., Cloud KMS keys)
or :data:`None` if using default encryption.
See
:attr:`google.cloud.bigquery.job.LoadJobConfig.destination_encryption_configuration`.
"""
return self._configuration.destination_encryption_configuration
@property
def time_partitioning(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.time_partitioning`.
"""
return self._configuration.time_partitioning
@property
def use_avro_logical_types(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.use_avro_logical_types`.
"""
return self._configuration.use_avro_logical_types
@property
def clustering_fields(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.clustering_fields`.
"""
return self._configuration.clustering_fields
@property
def schema_update_options(self):
"""See
:attr:`google.cloud.bigquery.job.LoadJobConfig.schema_update_options`.
"""
return self._configuration.schema_update_options
@property
def input_file_bytes(self):
"""Count of bytes loaded from source files.
:rtype: int, or ``NoneType``
:returns: the count (None until set from the server).
:raises: ValueError for invalid value types.
"""
return _helpers._int_or_none(
_helpers._get_sub_prop(
self._properties, ["statistics", "load", "inputFileBytes"]
)
)
@property
def input_files(self):
"""Count of source files.
:rtype: int, or ``NoneType``
:returns: the count (None until set from the server).
"""
return _helpers._int_or_none(
_helpers._get_sub_prop(
self._properties, ["statistics", "load", "inputFiles"]
)
)
@property
def output_bytes(self):
"""Count of bytes saved to destination table.
:rtype: int, or ``NoneType``
:returns: the count (None until set from the server).
"""
return _helpers._int_or_none(
_helpers._get_sub_prop(
self._properties, ["statistics", "load", "outputBytes"]
)
)
@property
def output_rows(self):
"""Count of rows saved to destination table.
:rtype: int, or ``NoneType``
:returns: the count (None until set from the server).
"""
return _helpers._int_or_none(
_helpers._get_sub_prop(
self._properties, ["statistics", "load", "outputRows"]
)
)
def to_api_repr(self):
"""Generate a resource for :meth:`_begin`."""
configuration = self._configuration.to_api_repr()
if self.source_uris is not None:
_helpers._set_sub_prop(
configuration, ["load", "sourceUris"], self.source_uris
)
_helpers._set_sub_prop(
configuration, ["load", "destinationTable"], self.destination.to_api_repr()
)
return {
"jobReference": self._properties["jobReference"],
"configuration": configuration,
}
def _copy_configuration_properties(self, configuration):
"""Helper: assign subclass configuration properties in cleaned."""
self._configuration._properties = copy.deepcopy(configuration)
@classmethod
def from_api_repr(cls, resource, client):
"""Factory: construct a job given its API representation
.. note:
This method assumes that the project found in the resource matches
the client's project.
:type resource: dict
:param resource: dataset job representation returned from the API
:type client: :class:`google.cloud.bigquery.client.Client`
:param client: Client which holds credentials and project
configuration for the dataset.
:rtype: :class:`google.cloud.bigquery.job.LoadJob`
:returns: Job parsed from ``resource``.
"""
config_resource = resource.get("configuration", {})
config = LoadJobConfig.from_api_repr(config_resource)
# A load job requires a destination table.
dest_config = config_resource["load"]["destinationTable"]
ds_ref = DatasetReference(dest_config["projectId"], dest_config["datasetId"])
destination = TableReference(ds_ref, dest_config["tableId"])
# sourceUris will be absent if this is a file upload.
source_uris = _helpers._get_sub_prop(config_resource, ["load", "sourceUris"])
job_ref = _JobReference._from_api_repr(resource["jobReference"])
job = cls(job_ref, source_uris, destination, client, config)
job._set_properties(resource)
return job
class CopyJobConfig(_JobConfig):
"""Configuration options for copy jobs.
All properties in this class are optional. Values which are :data:`None` ->
server defaults. Set properties on the constructed configuration by using
the property name as the name of a keyword argument.
"""
def __init__(self, **kwargs):
super(CopyJobConfig, self).__init__("copy", **kwargs)
@property
def create_disposition(self):
"""google.cloud.bigquery.job.CreateDisposition: Specifies behavior
for creating tables.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.copy.createDisposition
"""
return self._get_sub_prop("createDisposition")
@create_disposition.setter
def create_disposition(self, value):
self._set_sub_prop("createDisposition", value)
@property
def write_disposition(self):
"""google.cloud.bigquery.job.WriteDisposition: Action that occurs if
the destination table already exists.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.copy.writeDisposition
"""
return self._get_sub_prop("writeDisposition")
@write_disposition.setter
def write_disposition(self, value):
self._set_sub_prop("writeDisposition", value)
@property
def destination_encryption_configuration(self):
"""google.cloud.bigquery.table.EncryptionConfiguration: Custom
encryption configuration for the destination table.
Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None`
if using default encryption.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.copy.destinationEncryptionConfiguration
"""
prop = self._get_sub_prop("destinationEncryptionConfiguration")
if prop is not None:
prop = EncryptionConfiguration.from_api_repr(prop)
return prop
@destination_encryption_configuration.setter
def destination_encryption_configuration(self, value):
api_repr = value
if value is not None:
api_repr = value.to_api_repr()
self._set_sub_prop("destinationEncryptionConfiguration", api_repr)
class CopyJob(_AsyncJob):
"""Asynchronous job: copy data into a table from other tables.
:type job_id: str
:param job_id: the job's ID, within the project belonging to ``client``.
:type sources: list of :class:`google.cloud.bigquery.table.TableReference`
:param sources: Table from which data is to be loaded.
:type destination: :class:`google.cloud.bigquery.table.TableReference`
:param destination: Table into which data is to be loaded.
:type client: :class:`google.cloud.bigquery.client.Client`
:param client: A client which holds credentials and project configuration
for the dataset (which requires a project).
:type job_config: :class:`~google.cloud.bigquery.job.CopyJobConfig`
:param job_config:
(Optional) Extra configuration options for the copy job.
"""
_JOB_TYPE = "copy"
def __init__(self, job_id, sources, destination, client, job_config=None):
super(CopyJob, self).__init__(job_id, client)
if job_config is None:
job_config = CopyJobConfig()
self.destination = destination
self.sources = sources
self._configuration = job_config
@property
def create_disposition(self):
"""See
:attr:`google.cloud.bigquery.job.CopyJobConfig.create_disposition`.
"""
return self._configuration.create_disposition
@property
def write_disposition(self):
"""See
:attr:`google.cloud.bigquery.job.CopyJobConfig.write_disposition`.
"""
return self._configuration.write_disposition
@property
def destination_encryption_configuration(self):
"""google.cloud.bigquery.table.EncryptionConfiguration: Custom
encryption configuration for the destination table.
Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None`
if using default encryption.
See
:attr:`google.cloud.bigquery.job.CopyJobConfig.destination_encryption_configuration`.
"""
return self._configuration.destination_encryption_configuration
def to_api_repr(self):
"""Generate a resource for :meth:`_begin`."""
source_refs = [
{
"projectId": table.project,
"datasetId": table.dataset_id,
"tableId": table.table_id,
}
for table in self.sources
]
configuration = self._configuration.to_api_repr()
_helpers._set_sub_prop(configuration, ["copy", "sourceTables"], source_refs)
_helpers._set_sub_prop(
configuration,
["copy", "destinationTable"],
{
"projectId": self.destination.project,
"datasetId": self.destination.dataset_id,
"tableId": self.destination.table_id,
},
)
return {
"jobReference": self._properties["jobReference"],
"configuration": configuration,
}
def _copy_configuration_properties(self, configuration):
"""Helper: assign subclass configuration properties in cleaned."""
self._configuration._properties = copy.deepcopy(configuration)
@classmethod
def from_api_repr(cls, resource, client):
"""Factory: construct a job given its API representation
.. note:
This method assumes that the project found in the resource matches
the client's project.
:type resource: dict
:param resource: dataset job representation returned from the API
:type client: :class:`google.cloud.bigquery.client.Client`
:param client: Client which holds credentials and project
configuration for the dataset.
:rtype: :class:`google.cloud.bigquery.job.CopyJob`
:returns: Job parsed from ``resource``.
"""
job_id, config_resource = cls._get_resource_config(resource)
config = CopyJobConfig.from_api_repr(config_resource)
# Copy required fields to the job.
copy_resource = config_resource["copy"]
destination = TableReference.from_api_repr(copy_resource["destinationTable"])
sources = []
source_configs = copy_resource.get("sourceTables")
if source_configs is None:
single = copy_resource.get("sourceTable")
if single is None:
raise KeyError("Resource missing 'sourceTables' / 'sourceTable'")
source_configs = [single]
for source_config in source_configs:
table_ref = TableReference.from_api_repr(source_config)
sources.append(table_ref)
job = cls(job_id, sources, destination, client=client, job_config=config)
job._set_properties(resource)
return job
class ExtractJobConfig(_JobConfig):
"""Configuration options for extract jobs.
All properties in this class are optional. Values which are :data:`None` ->
server defaults. Set properties on the constructed configuration by using
the property name as the name of a keyword argument.
"""
def __init__(self, **kwargs):
super(ExtractJobConfig, self).__init__("extract", **kwargs)
@property
def compression(self):
"""google.cloud.bigquery.job.Compression: Compression type to use for
exported files.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.extract.compression
"""
return self._get_sub_prop("compression")
@compression.setter
def compression(self, value):
self._set_sub_prop("compression", value)
@property
def destination_format(self):
"""google.cloud.bigquery.job.DestinationFormat: Exported file format.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.extract.destinationFormat
"""
return self._get_sub_prop("destinationFormat")
@destination_format.setter
def destination_format(self, value):
self._set_sub_prop("destinationFormat", value)
@property
def field_delimiter(self):
"""str: Delimiter to use between fields in the exported data.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.extract.fieldDelimiter
"""
return self._get_sub_prop("fieldDelimiter")
@field_delimiter.setter
def field_delimiter(self, value):
self._set_sub_prop("fieldDelimiter", value)
@property
def print_header(self):
"""bool: Print a header row in the exported data.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.extract.printHeader
"""
return self._get_sub_prop("printHeader")
@print_header.setter
def print_header(self, value):
self._set_sub_prop("printHeader", value)
class ExtractJob(_AsyncJob):
"""Asynchronous job: extract data from a table into Cloud Storage.
:type job_id: str
:param job_id: the job's ID
:type source: :class:`google.cloud.bigquery.table.TableReference`
:param source: Table into which data is to be loaded.
:type destination_uris: list of string
:param destination_uris:
URIs describing where the extracted data will be written in Cloud
Storage, using the format ``gs://<bucket_name>/<object_name_or_glob>``.
:type client: :class:`google.cloud.bigquery.client.Client`
:param client:
A client which holds credentials and project configuration.
:type job_config: :class:`~google.cloud.bigquery.job.ExtractJobConfig`
:param job_config:
(Optional) Extra configuration options for the extract job.
"""
_JOB_TYPE = "extract"
def __init__(self, job_id, source, destination_uris, client, job_config=None):
super(ExtractJob, self).__init__(job_id, client)
if job_config is None:
job_config = ExtractJobConfig()
self.source = source
self.destination_uris = destination_uris
self._configuration = job_config
@property
def compression(self):
"""See
:attr:`google.cloud.bigquery.job.ExtractJobConfig.compression`.
"""
return self._configuration.compression
@property
def destination_format(self):
"""See
:attr:`google.cloud.bigquery.job.ExtractJobConfig.destination_format`.
"""
return self._configuration.destination_format
@property
def field_delimiter(self):
"""See
:attr:`google.cloud.bigquery.job.ExtractJobConfig.field_delimiter`.
"""
return self._configuration.field_delimiter
@property
def print_header(self):
"""See
:attr:`google.cloud.bigquery.job.ExtractJobConfig.print_header`.
"""
return self._configuration.print_header
@property
def destination_uri_file_counts(self):
"""Return file counts from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.extract.destinationUriFileCounts
Returns:
a list of integer counts, each representing the number of files
per destination URI or URI pattern specified in the extract
configuration. These values will be in the same order as the URIs
specified in the 'destinationUris' field. Returns None if job is
not yet complete.
"""
counts = self._job_statistics().get("destinationUriFileCounts")
if counts is not None:
return [int(count) for count in counts]
return None
def to_api_repr(self):
"""Generate a resource for :meth:`_begin`."""
source_ref = {
"projectId": self.source.project,
"datasetId": self.source.dataset_id,
"tableId": self.source.table_id,
}
configuration = self._configuration.to_api_repr()
_helpers._set_sub_prop(configuration, ["extract", "sourceTable"], source_ref)
_helpers._set_sub_prop(
configuration, ["extract", "destinationUris"], self.destination_uris
)
return {
"jobReference": self._properties["jobReference"],
"configuration": configuration,
}
def _copy_configuration_properties(self, configuration):
"""Helper: assign subclass configuration properties in cleaned."""
self._configuration._properties = copy.deepcopy(configuration)
@classmethod
def from_api_repr(cls, resource, client):
"""Factory: construct a job given its API representation
.. note:
This method assumes that the project found in the resource matches
the client's project.
:type resource: dict
:param resource: dataset job representation returned from the API
:type client: :class:`google.cloud.bigquery.client.Client`
:param client: Client which holds credentials and project
configuration for the dataset.
:rtype: :class:`google.cloud.bigquery.job.ExtractJob`
:returns: Job parsed from ``resource``.
"""
job_id, config_resource = cls._get_resource_config(resource)
config = ExtractJobConfig.from_api_repr(config_resource)
source_config = _helpers._get_sub_prop(
config_resource, ["extract", "sourceTable"]
)
dataset = DatasetReference(
source_config["projectId"], source_config["datasetId"]
)
source = dataset.table(source_config["tableId"])
destination_uris = _helpers._get_sub_prop(
config_resource, ["extract", "destinationUris"]
)
job = cls(job_id, source, destination_uris, client=client, job_config=config)
job._set_properties(resource)
return job
def _from_api_repr_query_parameters(resource):
return [_query_param_from_api_repr(mapping) for mapping in resource]
def _to_api_repr_query_parameters(value):
return [query_parameter.to_api_repr() for query_parameter in value]
def _from_api_repr_udf_resources(resource):
udf_resources = []
for udf_mapping in resource:
for udf_type, udf_value in udf_mapping.items():
udf_resources.append(UDFResource(udf_type, udf_value))
return udf_resources
def _to_api_repr_udf_resources(value):
return [{udf_resource.udf_type: udf_resource.value} for udf_resource in value]
def _from_api_repr_table_defs(resource):
return {k: ExternalConfig.from_api_repr(v) for k, v in resource.items()}
def _to_api_repr_table_defs(value):
return {k: ExternalConfig.to_api_repr(v) for k, v in value.items()}
class QueryJobConfig(_JobConfig):
"""Configuration options for query jobs.
All properties in this class are optional. Values which are :data:`None` ->
server defaults. Set properties on the constructed configuration by using
the property name as the name of a keyword argument.
"""
def __init__(self, **kwargs):
super(QueryJobConfig, self).__init__("query", **kwargs)
@property
def destination_encryption_configuration(self):
"""google.cloud.bigquery.table.EncryptionConfiguration: Custom
encryption configuration for the destination table.
Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None`
if using default encryption.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.destinationEncryptionConfiguration
"""
prop = self._get_sub_prop("destinationEncryptionConfiguration")
if prop is not None:
prop = EncryptionConfiguration.from_api_repr(prop)
return prop
@destination_encryption_configuration.setter
def destination_encryption_configuration(self, value):
api_repr = value
if value is not None:
api_repr = value.to_api_repr()
self._set_sub_prop("destinationEncryptionConfiguration", api_repr)
@property
def allow_large_results(self):
"""bool: Allow large query results tables (legacy SQL, only)
See
https://g.co/cloud/bigquery/docs/reference/rest/v2/jobs#configuration.query.allowLargeResults
"""
return self._get_sub_prop("allowLargeResults")
@allow_large_results.setter
def allow_large_results(self, value):
self._set_sub_prop("allowLargeResults", value)
@property
def create_disposition(self):
"""google.cloud.bigquery.job.CreateDisposition: Specifies behavior
for creating tables.
See
https://g.co/cloud/bigquery/docs/reference/rest/v2/jobs#configuration.query.createDisposition
"""
return self._get_sub_prop("createDisposition")
@create_disposition.setter
def create_disposition(self, value):
self._set_sub_prop("createDisposition", value)
@property
def default_dataset(self):
"""google.cloud.bigquery.dataset.DatasetReference: the default dataset
to use for unqualified table names in the query or :data:`None` if not
set.
See
https://g.co/cloud/bigquery/docs/reference/v2/jobs#configuration.query.defaultDataset
"""
prop = self._get_sub_prop("defaultDataset")
if prop is not None:
prop = DatasetReference.from_api_repr(prop)
return prop
@default_dataset.setter
def default_dataset(self, value):
resource = None
if value is not None:
resource = value.to_api_repr()
self._set_sub_prop("defaultDataset", resource)
@property
def destination(self):
"""google.cloud.bigquery.table.TableReference: table where results are
written or :data:`None` if not set.
See
https://g.co/cloud/bigquery/docs/reference/rest/v2/jobs#configuration.query.destinationTable
"""
prop = self._get_sub_prop("destinationTable")
if prop is not None:
prop = TableReference.from_api_repr(prop)
return prop
@destination.setter
def destination(self, value):
resource = None
if value is not None:
resource = value.to_api_repr()
self._set_sub_prop("destinationTable", resource)
@property
def dry_run(self):
"""bool: :data:`True` if this query should be a dry run to estimate
costs.
See
https://g.co/cloud/bigquery/docs/reference/v2/jobs#configuration.dryRun
"""
return self._properties.get("dryRun")
@dry_run.setter
def dry_run(self, value):
self._properties["dryRun"] = value
@property
def flatten_results(self):
"""bool: Flatten nested/repeated fields in results. (Legacy SQL only)
See
https://g.co/cloud/bigquery/docs/reference/rest/v2/jobs#configuration.query.flattenResults
"""
return self._get_sub_prop("flattenResults")
@flatten_results.setter
def flatten_results(self, value):
self._set_sub_prop("flattenResults", value)
@property
def maximum_billing_tier(self):
"""int: Deprecated. Changes the billing tier to allow high-compute
queries.
See
https://g.co/cloud/bigquery/docs/reference/rest/v2/jobs#configuration.query.maximumBillingTier
"""
return self._get_sub_prop("maximumBillingTier")
@maximum_billing_tier.setter
def maximum_billing_tier(self, value):
self._set_sub_prop("maximumBillingTier", value)
@property
def maximum_bytes_billed(self):
"""int: Maximum bytes to be billed for this job or :data:`None` if not set.
See
https://g.co/cloud/bigquery/docs/reference/rest/v2/jobs#configuration.query.maximumBytesBilled
"""
return _helpers._int_or_none(self._get_sub_prop("maximumBytesBilled"))
@maximum_bytes_billed.setter
def maximum_bytes_billed(self, value):
self._set_sub_prop("maximumBytesBilled", str(value))
@property
def priority(self):
"""google.cloud.bigquery.job.QueryPriority: Priority of the query.
See
https://g.co/cloud/bigquery/docs/reference/rest/v2/jobs#configuration.query.priority
"""
return self._get_sub_prop("priority")
@priority.setter
def priority(self, value):
self._set_sub_prop("priority", value)
@property
def query_parameters(self):
"""List[Union[google.cloud.bigquery.query.ArrayQueryParameter, \
google.cloud.bigquery.query.ScalarQueryParameter, \
google.cloud.bigquery.query.StructQueryParameter]]: list of parameters
for parameterized query (empty by default)
See:
https://g.co/cloud/bigquery/docs/reference/rest/v2/jobs#configuration.query.queryParameters
"""
prop = self._get_sub_prop("queryParameters", default=[])
return _from_api_repr_query_parameters(prop)
@query_parameters.setter
def query_parameters(self, values):
self._set_sub_prop("queryParameters", _to_api_repr_query_parameters(values))
@property
def udf_resources(self):
"""List[google.cloud.bigquery.query.UDFResource]: user
defined function resources (empty by default)
See:
https://g.co/cloud/bigquery/docs/reference/rest/v2/jobs#configuration.query.userDefinedFunctionResources
"""
prop = self._get_sub_prop("userDefinedFunctionResources", default=[])
return _from_api_repr_udf_resources(prop)
@udf_resources.setter
def udf_resources(self, values):
self._set_sub_prop(
"userDefinedFunctionResources", _to_api_repr_udf_resources(values)
)
@property
def use_legacy_sql(self):
"""bool: Use legacy SQL syntax.
See
https://g.co/cloud/bigquery/docs/reference/v2/jobs#configuration.query.useLegacySql
"""
return self._get_sub_prop("useLegacySql")
@use_legacy_sql.setter
def use_legacy_sql(self, value):
self._set_sub_prop("useLegacySql", value)
@property
def use_query_cache(self):
"""bool: Look for the query result in the cache.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.useQueryCache
"""
return self._get_sub_prop("useQueryCache")
@use_query_cache.setter
def use_query_cache(self, value):
self._set_sub_prop("useQueryCache", value)
@property
def write_disposition(self):
"""google.cloud.bigquery.job.WriteDisposition: Action that occurs if
the destination table already exists.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query.writeDisposition
"""
return self._get_sub_prop("writeDisposition")
@write_disposition.setter
def write_disposition(self, value):
self._set_sub_prop("writeDisposition", value)
@property
def table_definitions(self):
"""Dict[str, google.cloud.bigquery.external_config.ExternalConfig]:
Definitions for external tables or :data:`None` if not set.
See
https://g.co/cloud/bigquery/docs/reference/rest/v2/jobs#configuration.query.tableDefinitions
"""
prop = self._get_sub_prop("tableDefinitions")
if prop is not None:
prop = _from_api_repr_table_defs(prop)
return prop
@table_definitions.setter
def table_definitions(self, values):
self._set_sub_prop("tableDefinitions", _to_api_repr_table_defs(values))
@property
def time_partitioning(self):
"""google.cloud.bigquery.table.TimePartitioning: Specifies time-based
partitioning for the destination table.
"""
prop = self._get_sub_prop("timePartitioning")
if prop is not None:
prop = TimePartitioning.from_api_repr(prop)
return prop
@time_partitioning.setter
def time_partitioning(self, value):
api_repr = value
if value is not None:
api_repr = value.to_api_repr()
self._set_sub_prop("timePartitioning", api_repr)
@property
def clustering_fields(self):
"""Union[List[str], None]: Fields defining clustering for the table
(Defaults to :data:`None`).
Clustering fields are immutable after table creation.
.. note::
As of 2018-06-29, clustering fields cannot be set on a table
which does not also have time partioning defined.
"""
prop = self._get_sub_prop("clustering")
if prop is not None:
return list(prop.get("fields", ()))
@clustering_fields.setter
def clustering_fields(self, value):
"""Union[List[str], None]: Fields defining clustering for the table
(Defaults to :data:`None`).
"""
if value is not None:
self._set_sub_prop("clustering", {"fields": value})
else:
self._del_sub_prop("clustering")
@property
def schema_update_options(self):
"""List[google.cloud.bigquery.job.SchemaUpdateOption]: Specifies
updates to the destination table schema to allow as a side effect of
the query job.
"""
return self._get_sub_prop("schemaUpdateOptions")
@schema_update_options.setter
def schema_update_options(self, values):
self._set_sub_prop("schemaUpdateOptions", values)
def to_api_repr(self):
"""Build an API representation of the query job config.
Returns:
dict: A dictionary in the format used by the BigQuery API.
"""
resource = copy.deepcopy(self._properties)
# Query parameters have an addition property associated with them
# to indicate if the query is using named or positional parameters.
query_parameters = resource["query"].get("queryParameters")
if query_parameters:
if query_parameters[0].get("name") is None:
resource["query"]["parameterMode"] = "POSITIONAL"
else:
resource["query"]["parameterMode"] = "NAMED"
return resource
class QueryJob(_AsyncJob):
"""Asynchronous job: query tables.
:type job_id: str
:param job_id: the job's ID, within the project belonging to ``client``.
:type query: str
:param query: SQL query string
:type client: :class:`google.cloud.bigquery.client.Client`
:param client: A client which holds credentials and project configuration
for the dataset (which requires a project).
:type job_config: :class:`~google.cloud.bigquery.job.QueryJobConfig`
:param job_config:
(Optional) Extra configuration options for the query job.
"""
_JOB_TYPE = "query"
_UDF_KEY = "userDefinedFunctionResources"
def __init__(self, job_id, query, client, job_config=None):
super(QueryJob, self).__init__(job_id, client)
if job_config is None:
job_config = QueryJobConfig()
if job_config.use_legacy_sql is None:
job_config.use_legacy_sql = False
self.query = query
self._configuration = job_config
self._query_results = None
self._done_timeout = None
@property
def allow_large_results(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.allow_large_results`.
"""
return self._configuration.allow_large_results
@property
def create_disposition(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.create_disposition`.
"""
return self._configuration.create_disposition
@property
def default_dataset(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.default_dataset`.
"""
return self._configuration.default_dataset
@property
def destination(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.destination`.
"""
return self._configuration.destination
@property
def destination_encryption_configuration(self):
"""google.cloud.bigquery.table.EncryptionConfiguration: Custom
encryption configuration for the destination table.
Custom encryption configuration (e.g., Cloud KMS keys) or :data:`None`
if using default encryption.
See
:attr:`google.cloud.bigquery.job.QueryJobConfig.destination_encryption_configuration`.
"""
return self._configuration.destination_encryption_configuration
@property
def dry_run(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.dry_run`.
"""
return self._configuration.dry_run
@property
def flatten_results(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.flatten_results`.
"""
return self._configuration.flatten_results
@property
def priority(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.priority`.
"""
return self._configuration.priority
@property
def query_parameters(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.query_parameters`.
"""
return self._configuration.query_parameters
@property
def udf_resources(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.udf_resources`.
"""
return self._configuration.udf_resources
@property
def use_legacy_sql(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.use_legacy_sql`.
"""
return self._configuration.use_legacy_sql
@property
def use_query_cache(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.use_query_cache`.
"""
return self._configuration.use_query_cache
@property
def write_disposition(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.write_disposition`.
"""
return self._configuration.write_disposition
@property
def maximum_billing_tier(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.maximum_billing_tier`.
"""
return self._configuration.maximum_billing_tier
@property
def maximum_bytes_billed(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.maximum_bytes_billed`.
"""
return self._configuration.maximum_bytes_billed
@property
def table_definitions(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.table_definitions`.
"""
return self._configuration.table_definitions
@property
def time_partitioning(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.time_partitioning`.
"""
return self._configuration.time_partitioning
@property
def clustering_fields(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.clustering_fields`.
"""
return self._configuration.clustering_fields
@property
def schema_update_options(self):
"""See
:attr:`google.cloud.bigquery.job.QueryJobConfig.schema_update_options`.
"""
return self._configuration.schema_update_options
def to_api_repr(self):
"""Generate a resource for :meth:`_begin`."""
configuration = self._configuration.to_api_repr()
resource = {
"jobReference": self._properties["jobReference"],
"configuration": configuration,
}
configuration["query"]["query"] = self.query
return resource
def _copy_configuration_properties(self, configuration):
"""Helper: assign subclass configuration properties in cleaned."""
self._configuration._properties = copy.deepcopy(configuration)
self.query = _helpers._get_sub_prop(configuration, ["query", "query"])
@classmethod
def from_api_repr(cls, resource, client):
"""Factory: construct a job given its API representation
:type resource: dict
:param resource: dataset job representation returned from the API
:type client: :class:`google.cloud.bigquery.client.Client`
:param client: Client which holds credentials and project
configuration for the dataset.
:rtype: :class:`google.cloud.bigquery.job.QueryJob`
:returns: Job parsed from ``resource``.
"""
job_id, config = cls._get_resource_config(resource)
query = config["query"]["query"]
job = cls(job_id, query, client=client)
job._set_properties(resource)
return job
@property
def query_plan(self):
"""Return query plan from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.queryPlan
:rtype: list of :class:`QueryPlanEntry`
:returns: mappings describing the query plan, or an empty list
if the query has not yet completed.
"""
plan_entries = self._job_statistics().get("queryPlan", ())
return [QueryPlanEntry.from_api_repr(entry) for entry in plan_entries]
@property
def timeline(self):
"""List(TimelineEntry): Return the query execution timeline
from job statistics.
"""
raw = self._job_statistics().get("timeline", ())
return [TimelineEntry.from_api_repr(entry) for entry in raw]
@property
def total_bytes_processed(self):
"""Return total bytes processed from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.totalBytesProcessed
:rtype: int or None
:returns: total bytes processed by the job, or None if job is not
yet complete.
"""
result = self._job_statistics().get("totalBytesProcessed")
if result is not None:
result = int(result)
return result
@property
def total_bytes_billed(self):
"""Return total bytes billed from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.totalBytesBilled
:rtype: int or None
:returns: total bytes processed by the job, or None if job is not
yet complete.
"""
result = self._job_statistics().get("totalBytesBilled")
if result is not None:
result = int(result)
return result
@property
def billing_tier(self):
"""Return billing tier from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.billingTier
:rtype: int or None
:returns: billing tier used by the job, or None if job is not
yet complete.
"""
return self._job_statistics().get("billingTier")
@property
def cache_hit(self):
"""Return whether or not query results were served from cache.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.cacheHit
:rtype: bool or None
:returns: whether the query results were returned from cache, or None
if job is not yet complete.
"""
return self._job_statistics().get("cacheHit")
@property
def ddl_operation_performed(self):
"""Optional[str]: Return the DDL operation performed.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.ddlOperationPerformed
"""
return self._job_statistics().get("ddlOperationPerformed")
@property
def ddl_target_table(self):
"""Optional[TableReference]: Return the DDL target table, present
for CREATE/DROP TABLE/VIEW queries.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.ddlTargetTable
"""
prop = self._job_statistics().get("ddlTargetTable")
if prop is not None:
prop = TableReference.from_api_repr(prop)
return prop
@property
def num_dml_affected_rows(self):
"""Return the number of DML rows affected by the job.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.numDmlAffectedRows
:rtype: int or None
:returns: number of DML rows affected by the job, or None if job is not
yet complete.
"""
result = self._job_statistics().get("numDmlAffectedRows")
if result is not None:
result = int(result)
return result
@property
def slot_millis(self):
"""Union[int, None]: Slot-milliseconds used by this query job."""
return _helpers._int_or_none(self._job_statistics().get("totalSlotMs"))
@property
def statement_type(self):
"""Return statement type from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.statementType
:rtype: str or None
:returns: type of statement used by the job, or None if job is not
yet complete.
"""
return self._job_statistics().get("statementType")
@property
def referenced_tables(self):
"""Return referenced tables from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.referencedTables
:rtype: list of dict
:returns: mappings describing the query plan, or an empty list
if the query has not yet completed.
"""
tables = []
datasets_by_project_name = {}
for table in self._job_statistics().get("referencedTables", ()):
t_project = table["projectId"]
ds_id = table["datasetId"]
t_dataset = datasets_by_project_name.get((t_project, ds_id))
if t_dataset is None:
t_dataset = DatasetReference(t_project, ds_id)
datasets_by_project_name[(t_project, ds_id)] = t_dataset
t_name = table["tableId"]
tables.append(t_dataset.table(t_name))
return tables
@property
def undeclared_query_parameters(self):
"""Return undeclared query parameters from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.undeclaredQueryParameters
:rtype:
list of
:class:`~google.cloud.bigquery.ArrayQueryParameter`,
:class:`~google.cloud.bigquery.ScalarQueryParameter`, or
:class:`~google.cloud.bigquery.StructQueryParameter`
:returns: undeclared parameters, or an empty list if the query has
not yet completed.
"""
parameters = []
undeclared = self._job_statistics().get("undeclaredQueryParameters", ())
for parameter in undeclared:
p_type = parameter["parameterType"]
if "arrayType" in p_type:
klass = ArrayQueryParameter
elif "structTypes" in p_type:
klass = StructQueryParameter
else:
klass = ScalarQueryParameter
parameters.append(klass.from_api_repr(parameter))
return parameters
@property
def estimated_bytes_processed(self):
"""Return the estimated number of bytes processed by the query.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.estimatedBytesProcessed
:rtype: int or None
:returns: number of DML rows affected by the job, or None if job is not
yet complete.
"""
result = self._job_statistics().get("estimatedBytesProcessed")
if result is not None:
result = int(result)
return result
def done(self, retry=DEFAULT_RETRY):
"""Refresh the job and checks if it is complete.
:rtype: bool
:returns: True if the job is complete, False otherwise.
"""
# Since the API to getQueryResults can hang up to the timeout value
# (default of 10 seconds), set the timeout parameter to ensure that
# the timeout from the futures API is respected. See:
# https://github.com/GoogleCloudPlatform/google-cloud-python/issues/4135
timeout_ms = None
if self._done_timeout is not None:
# Subtract a buffer for context switching, network latency, etc.
timeout = self._done_timeout - _TIMEOUT_BUFFER_SECS
timeout = max(min(timeout, 10), 0)
self._done_timeout -= timeout
self._done_timeout = max(0, self._done_timeout)
timeout_ms = int(timeout * 1000)
# Do not refresh is the state is already done, as the job will not
# change once complete.
if self.state != _DONE_STATE:
self._query_results = self._client._get_query_results(
self.job_id,
retry,
project=self.project,
timeout_ms=timeout_ms,
location=self.location,
)
# Only reload the job once we know the query is complete.
# This will ensure that fields such as the destination table are
# correctly populated.
if self._query_results.complete:
self.reload(retry=retry)
return self.state == _DONE_STATE
def _blocking_poll(self, timeout=None):
self._done_timeout = timeout
super(QueryJob, self)._blocking_poll(timeout=timeout)
def result(self, timeout=None, retry=DEFAULT_RETRY):
"""Start the job and wait for it to complete and get the result.
:type timeout: float
:param timeout:
How long (in seconds) to wait for job to complete before raising
a :class:`concurrent.futures.TimeoutError`.
:type retry: :class:`google.api_core.retry.Retry`
:param retry: (Optional) How to retry the call that retrieves rows.
:rtype: :class:`~google.cloud.bigquery.table.RowIterator`
:returns:
Iterator of row data :class:`~google.cloud.bigquery.table.Row`-s.
During each page, the iterator will have the ``total_rows``
attribute set, which counts the total number of rows **in the
result set** (this is distinct from the total number of rows in
the current page: ``iterator.page.num_items``).
:raises:
:class:`~google.cloud.exceptions.GoogleCloudError` if the job
failed or :class:`concurrent.futures.TimeoutError` if the job did
not complete in the given timeout.
"""
super(QueryJob, self).result(timeout=timeout)
# Return an iterator instead of returning the job.
if not self._query_results:
self._query_results = self._client._get_query_results(
self.job_id, retry, project=self.project, location=self.location
)
# If the query job is complete but there are no query results, this was
# special job, such as a DDL query. Return an empty result set to
# indicate success and avoid calling tabledata.list on a table which
# can't be read (such as a view table).
if self._query_results.total_rows is None:
return _EmptyRowIterator()
schema = self._query_results.schema
dest_table_ref = self.destination
dest_table = Table(dest_table_ref, schema=schema)
return self._client.list_rows(dest_table, retry=retry)
def to_dataframe(self):
"""Return a pandas DataFrame from a QueryJob
Returns:
A :class:`~pandas.DataFrame` populated with row data and column
headers from the query results. The column headers are derived
from the destination table's schema.
Raises:
ValueError: If the `pandas` library cannot be imported.
"""
return self.result().to_dataframe()
def __iter__(self):
return iter(self.result())
class QueryPlanEntryStep(object):
"""Map a single step in a query plan entry.
:type kind: str
:param kind: step type
:type substeps:
:param substeps: names of substeps
"""
def __init__(self, kind, substeps):
self.kind = kind
self.substeps = list(substeps)
@classmethod
def from_api_repr(cls, resource):
"""Factory: construct instance from the JSON repr.
:type resource: dict
:param resource: JSON representation of the entry
:rtype: :class:`QueryPlanEntryStep`
:return: new instance built from the resource
"""
return cls(kind=resource.get("kind"), substeps=resource.get("substeps", ()))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.kind == other.kind and self.substeps == other.substeps
class QueryPlanEntry(object):
"""QueryPlanEntry represents a single stage of a query execution plan.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs
for the underlying API representation within query statistics.
"""
def __init__(self):
self._properties = {}
@classmethod
def from_api_repr(cls, resource):
"""Factory: construct instance from the JSON repr.
Args:
resource(Dict[str: object]):
ExplainQueryStage representation returned from API
Returns:
google.cloud.bigquery.QueryPlanEntry:
Query plan entry parsed from ``resource``
"""
entry = cls()
entry._properties = resource
return entry
@property
def name(self):
"""Union[str, None]: Human-readable name of the stage."""
return self._properties.get("name")
@property
def entry_id(self):
"""Union[str, None]: Unique ID for the stage within the plan."""
return self._properties.get("id")
@property
def start(self):
"""Union[Datetime, None]: Datetime when the stage started."""
if self._properties.get("startMs") is None:
return None
return _helpers._datetime_from_microseconds(
int(self._properties.get("startMs")) * 1000.0
)
@property
def end(self):
"""Union[Datetime, None]: Datetime when the stage ended."""
if self._properties.get("endMs") is None:
return None
return _helpers._datetime_from_microseconds(
int(self._properties.get("endMs")) * 1000.0
)
@property
def input_stages(self):
"""List(int): Entry IDs for stages that were inputs for this stage."""
if self._properties.get("inputStages") is None:
return []
return [
_helpers._int_or_none(entry)
for entry in self._properties.get("inputStages")
]
@property
def parallel_inputs(self):
"""Union[int, None]: Number of parallel input segments within
the stage.
"""
return _helpers._int_or_none(self._properties.get("parallelInputs"))
@property
def completed_parallel_inputs(self):
"""Union[int, None]: Number of parallel input segments completed."""
return _helpers._int_or_none(self._properties.get("completedParallelInputs"))
@property
def wait_ms_avg(self):
"""Union[int, None]: Milliseconds the average worker spent waiting to
be scheduled.
"""
return _helpers._int_or_none(self._properties.get("waitMsAvg"))
@property
def wait_ms_max(self):
"""Union[int, None]: Milliseconds the slowest worker spent waiting to
be scheduled.
"""
return _helpers._int_or_none(self._properties.get("waitMsMax"))
@property
def wait_ratio_avg(self):
"""Union[float, None]: Ratio of time the average worker spent waiting
to be scheduled, relative to the longest time spent by any worker in
any stage of the overall plan.
"""
return self._properties.get("waitRatioAvg")
@property
def wait_ratio_max(self):
"""Union[float, None]: Ratio of time the slowest worker spent waiting
to be scheduled, relative to the longest time spent by any worker in
any stage of the overall plan.
"""
return self._properties.get("waitRatioMax")
@property
def read_ms_avg(self):
"""Union[int, None]: Milliseconds the average worker spent reading
input.
"""
return _helpers._int_or_none(self._properties.get("readMsAvg"))
@property
def read_ms_max(self):
"""Union[int, None]: Milliseconds the slowest worker spent reading
input.
"""
return _helpers._int_or_none(self._properties.get("readMsMax"))
@property
def read_ratio_avg(self):
"""Union[float, None]: Ratio of time the average worker spent reading
input, relative to the longest time spent by any worker in any stage
of the overall plan.
"""
return self._properties.get("readRatioAvg")
@property
def read_ratio_max(self):
"""Union[float, None]: Ratio of time the slowest worker spent reading
to be scheduled, relative to the longest time spent by any worker in
any stage of the overall plan.
"""
return self._properties.get("readRatioMax")
@property
def compute_ms_avg(self):
"""Union[int, None]: Milliseconds the average worker spent on CPU-bound
processing.
"""
return _helpers._int_or_none(self._properties.get("computeMsAvg"))
@property
def compute_ms_max(self):
"""Union[int, None]: Milliseconds the slowest worker spent on CPU-bound
processing.
"""
return _helpers._int_or_none(self._properties.get("computeMsMax"))
@property
def compute_ratio_avg(self):
"""Union[float, None]: Ratio of time the average worker spent on
CPU-bound processing, relative to the longest time spent by any
worker in any stage of the overall plan.
"""
return self._properties.get("computeRatioAvg")
@property
def compute_ratio_max(self):
"""Union[float, None]: Ratio of time the slowest worker spent on
CPU-bound processing, relative to the longest time spent by any
worker in any stage of the overall plan.
"""
return self._properties.get("computeRatioMax")
@property
def write_ms_avg(self):
"""Union[int, None]: Milliseconds the average worker spent writing
output data.
"""
return _helpers._int_or_none(self._properties.get("writeMsAvg"))
@property
def write_ms_max(self):
"""Union[int, None]: Milliseconds the slowest worker spent writing
output data.
"""
return _helpers._int_or_none(self._properties.get("writeMsMax"))
@property
def write_ratio_avg(self):
"""Union[float, None]: Ratio of time the average worker spent writing
output data, relative to the longest time spent by any worker in any
stage of the overall plan.
"""
return self._properties.get("writeRatioAvg")
@property
def write_ratio_max(self):
"""Union[float, None]: Ratio of time the slowest worker spent writing
output data, relative to the longest time spent by any worker in any
stage of the overall plan.
"""
return self._properties.get("writeRatioMax")
@property
def records_read(self):
"""Union[int, None]: Number of records read by this stage."""
return _helpers._int_or_none(self._properties.get("recordsRead"))
@property
def records_written(self):
"""Union[int, None]: Number of records written by this stage."""
return _helpers._int_or_none(self._properties.get("recordsWritten"))
@property
def status(self):
"""Union[str, None]: status of this stage."""
return self._properties.get("status")
@property
def shuffle_output_bytes(self):
"""Union[int, None]: Number of bytes written by this stage to
intermediate shuffle.
"""
return _helpers._int_or_none(self._properties.get("shuffleOutputBytes"))
@property
def shuffle_output_bytes_spilled(self):
"""Union[int, None]: Number of bytes written by this stage to
intermediate shuffle and spilled to disk.
"""
return _helpers._int_or_none(self._properties.get("shuffleOutputBytesSpilled"))
@property
def steps(self):
"""List(QueryPlanEntryStep): List of step operations performed by
each worker in the stage.
"""
return [
QueryPlanEntryStep.from_api_repr(step)
for step in self._properties.get("steps", [])
]
class TimelineEntry(object):
"""TimelineEntry represents progress of a query job at a particular
point in time.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs
for the underlying API representation within query statistics.
"""
def __init__(self):
self._properties = {}
@classmethod
def from_api_repr(cls, resource):
"""Factory: construct instance from the JSON repr.
Args:
resource(Dict[str: object]):
QueryTimelineSample representation returned from API
Returns:
google.cloud.bigquery.TimelineEntry:
Timeline sample parsed from ``resource``
"""
entry = cls()
entry._properties = resource
return entry
@property
def elapsed_ms(self):
"""Union[int, None]: Milliseconds elapsed since start of query
execution."""
return _helpers._int_or_none(self._properties.get("elapsedMs"))
@property
def active_units(self):
"""Union[int, None]: Current number of input units being processed
by workers, reported as largest value since the last sample."""
return _helpers._int_or_none(self._properties.get("activeUnits"))
@property
def pending_units(self):
"""Union[int, None]: Current number of input units remaining for
query stages active at this sample time."""
return _helpers._int_or_none(self._properties.get("pendingUnits"))
@property
def completed_units(self):
"""Union[int, None]: Current number of input units completed by
this query."""
return _helpers._int_or_none(self._properties.get("completedUnits"))
@property
def slot_millis(self):
"""Union[int, None]: Cumulative slot-milliseconds consumed by
this query."""
return _helpers._int_or_none(self._properties.get("totalSlotMs"))
class UnknownJob(_AsyncJob):
"""A job whose type cannot be determined."""
@classmethod
def from_api_repr(cls, resource, client):
"""Construct an UnknownJob from the JSON representation.
Args:
resource (dict): JSON representation of a job.
client (google.cloud.bigquery.client.Client):
Client connected to BigQuery API.
Returns:
UnknownJob: Job corresponding to the resource.
"""
job_ref_properties = resource.get("jobReference", {"projectId": client.project})
job_ref = _JobReference._from_api_repr(job_ref_properties)
job = cls(job_ref, client)
# Populate the job reference with the project, even if it has been
# redacted, because we know it should equal that of the request.
resource["jobReference"] = job_ref_properties
job._properties = resource
return job
| 34 | 128 | 0.647908 |
import copy
import threading
from six.moves import http_client
import google.api_core.future.polling
from google.cloud import exceptions
from google.cloud.exceptions import NotFound
from google.cloud.bigquery.dataset import DatasetReference
from google.cloud.bigquery.external_config import ExternalConfig
from google.cloud.bigquery.query import _query_param_from_api_repr
from google.cloud.bigquery.query import ArrayQueryParameter
from google.cloud.bigquery.query import ScalarQueryParameter
from google.cloud.bigquery.query import StructQueryParameter
from google.cloud.bigquery.query import UDFResource
from google.cloud.bigquery.retry import DEFAULT_RETRY
from google.cloud.bigquery.schema import SchemaField
from google.cloud.bigquery.table import _EmptyRowIterator
from google.cloud.bigquery.table import EncryptionConfiguration
from google.cloud.bigquery.table import TableReference
from google.cloud.bigquery.table import Table
from google.cloud.bigquery.table import TimePartitioning
from google.cloud.bigquery import _helpers
_DONE_STATE = "DONE"
_STOPPED_REASON = "stopped"
_TIMEOUT_BUFFER_SECS = 0.1
_ERROR_REASON_TO_EXCEPTION = {
"accessDenied": http_client.FORBIDDEN,
"backendError": http_client.INTERNAL_SERVER_ERROR,
"billingNotEnabled": http_client.FORBIDDEN,
"billingTierLimitExceeded": http_client.BAD_REQUEST,
"blocked": http_client.FORBIDDEN,
"duplicate": http_client.CONFLICT,
"internalError": http_client.INTERNAL_SERVER_ERROR,
"invalid": http_client.BAD_REQUEST,
"invalidQuery": http_client.BAD_REQUEST,
"notFound": http_client.NOT_FOUND,
"notImplemented": http_client.NOT_IMPLEMENTED,
"quotaExceeded": http_client.FORBIDDEN,
"rateLimitExceeded": http_client.FORBIDDEN,
"resourceInUse": http_client.BAD_REQUEST,
"resourcesExceeded": http_client.BAD_REQUEST,
"responseTooLarge": http_client.FORBIDDEN,
"stopped": http_client.OK,
"tableUnavailable": http_client.BAD_REQUEST,
}
def _error_result_to_exception(error_result):
reason = error_result.get("reason")
status_code = _ERROR_REASON_TO_EXCEPTION.get(
reason, http_client.INTERNAL_SERVER_ERROR
)
return exceptions.from_http_status(
status_code, error_result.get("message", ""), errors=[error_result]
)
class Compression(object):
GZIP = "GZIP"
DEFLATE = "DEFLATE"
SNAPPY = "SNAPPY"
NONE = "NONE"
class CreateDisposition(object):
CREATE_IF_NEEDED = "CREATE_IF_NEEDED"
CREATE_NEVER = "CREATE_NEVER"
class DestinationFormat(object):
CSV = "CSV"
NEWLINE_DELIMITED_JSON = "NEWLINE_DELIMITED_JSON"
AVRO = "AVRO"
class Encoding(object):
UTF_8 = "UTF-8"
ISO_8859_1 = "ISO-8859-1"
class QueryPriority(object):
INTERACTIVE = "INTERACTIVE"
BATCH = "BATCH"
class SourceFormat(object):
CSV = "CSV"
DATASTORE_BACKUP = "DATASTORE_BACKUP"
NEWLINE_DELIMITED_JSON = "NEWLINE_DELIMITED_JSON"
AVRO = "AVRO"
PARQUET = "PARQUET"
ORC = "ORC"
class WriteDisposition(object):
WRITE_APPEND = "WRITE_APPEND"
WRITE_TRUNCATE = "WRITE_TRUNCATE"
WRITE_EMPTY = "WRITE_EMPTY"
class SchemaUpdateOption(object):
ALLOW_FIELD_ADDITION = "ALLOW_FIELD_ADDITION"
ALLOW_FIELD_RELAXATION = "ALLOW_FIELD_RELAXATION"
class _JobReference(object):
def __init__(self, job_id, project, location):
self._properties = {"jobId": job_id, "projectId": project}
if location:
self._properties["location"] = location
@property
def job_id(self):
return self._properties.get("jobId")
@property
def project(self):
return self._properties.get("projectId")
@property
def location(self):
return self._properties.get("location")
def _to_api_repr(self):
return copy.deepcopy(self._properties)
@classmethod
def _from_api_repr(cls, resource):
job_id = resource.get("jobId")
project = resource.get("projectId")
location = resource.get("location")
job_ref = cls(job_id, project, location)
return job_ref
class _AsyncJob(google.api_core.future.polling.PollingFuture):
def __init__(self, job_id, client):
super(_AsyncJob, self).__init__()
job_ref = job_id
if not isinstance(job_id, _JobReference):
job_ref = _JobReference(job_id, client.project, None)
self._properties = {"jobReference": job_ref._to_api_repr()}
self._client = client
self._result_set = False
self._completion_lock = threading.Lock()
@property
def job_id(self):
return _helpers._get_sub_prop(self._properties, ["jobReference", "jobId"])
@property
def project(self):
return _helpers._get_sub_prop(self._properties, ["jobReference", "projectId"])
@property
def location(self):
return _helpers._get_sub_prop(self._properties, ["jobReference", "location"])
def _require_client(self, client):
if client is None:
client = self._client
return client
@property
def job_type(self):
return self._JOB_TYPE
@property
def path(self):
return "/projects/%s/jobs/%s" % (self.project, self.job_id)
@property
def labels(self):
return self._properties.setdefault("labels", {})
@property
def etag(self):
return self._properties.get("etag")
@property
def self_link(self):
return self._properties.get("selfLink")
@property
def user_email(self):
return self._properties.get("user_email")
@property
def created(self):
statistics = self._properties.get("statistics")
if statistics is not None:
millis = statistics.get("creationTime")
if millis is not None:
return _helpers._datetime_from_microseconds(millis * 1000.0)
@property
def started(self):
statistics = self._properties.get("statistics")
if statistics is not None:
millis = statistics.get("startTime")
if millis is not None:
return _helpers._datetime_from_microseconds(millis * 1000.0)
@property
def ended(self):
statistics = self._properties.get("statistics")
if statistics is not None:
millis = statistics.get("endTime")
if millis is not None:
return _helpers._datetime_from_microseconds(millis * 1000.0)
def _job_statistics(self):
statistics = self._properties.get("statistics", {})
return statistics.get(self._JOB_TYPE, {})
@property
def error_result(self):
status = self._properties.get("status")
if status is not None:
return status.get("errorResult")
@property
def errors(self):
status = self._properties.get("status")
if status is not None:
return status.get("errors")
@property
def state(self):
status = self._properties.get("status")
if status is not None:
return status.get("state")
def _scrub_local_properties(self, cleaned):
pass
def _copy_configuration_properties(self, configuration):
raise NotImplementedError("Abstract")
def _set_properties(self, api_response):
cleaned = api_response.copy()
self._scrub_local_properties(cleaned)
statistics = cleaned.get("statistics", {})
if "creationTime" in statistics:
statistics["creationTime"] = float(statistics["creationTime"])
if "startTime" in statistics:
statistics["startTime"] = float(statistics["startTime"])
if "endTime" in statistics:
statistics["endTime"] = float(statistics["endTime"])
self._properties.clear()
self._properties.update(cleaned)
self._copy_configuration_properties(cleaned.get("configuration", {}))
self._set_future_result()
@classmethod
def _get_resource_config(cls, resource):
if "jobReference" not in resource or "jobId" not in resource["jobReference"]:
raise KeyError(
"Resource lacks required identity information: "
'["jobReference"]["jobId"]'
)
job_id = resource["jobReference"]["jobId"]
if (
"configuration" not in resource
or cls._JOB_TYPE not in resource["configuration"]
):
raise KeyError(
"Resource lacks required configuration: "
'["configuration"]["%s"]' % cls._JOB_TYPE
)
return job_id, resource["configuration"]
def to_api_repr(self):
raise NotImplementedError("Abstract")
_build_resource = to_api_repr
def _begin(self, client=None, retry=DEFAULT_RETRY):
if self.state is not None:
raise ValueError("Job already begun.")
client = self._require_client(client)
path = "/projects/%s/jobs" % (self.project,)
api_response = client._call_api(
retry, method="POST", path=path, data=self.to_api_repr()
)
self._set_properties(api_response)
def exists(self, client=None, retry=DEFAULT_RETRY):
client = self._require_client(client)
extra_params = {"fields": "id"}
if self.location:
extra_params["location"] = self.location
try:
client._call_api(
retry, method="GET", path=self.path, query_params=extra_params
)
except NotFound:
return False
else:
return True
def reload(self, client=None, retry=DEFAULT_RETRY):
client = self._require_client(client)
extra_params = {}
if self.location:
extra_params["location"] = self.location
api_response = client._call_api(
retry, method="GET", path=self.path, query_params=extra_params
)
self._set_properties(api_response)
def cancel(self, client=None):
client = self._require_client(client)
extra_params = {}
if self.location:
extra_params["location"] = self.location
api_response = client._connection.api_request(
method="POST", path="%s/cancel" % (self.path,), query_params=extra_params
)
self._set_properties(api_response["job"])
return True
def _set_future_result(self):
with self._completion_lock:
# set, do not call set_result/set_exception again.
# Note: self._result_set is set to True in set_result and
# set_exception, in case those methods are invoked directly.
if self.state != _DONE_STATE or self._result_set:
return
if self.error_result is not None:
exception = _error_result_to_exception(self.error_result)
self.set_exception(exception)
else:
self.set_result(self)
def done(self, retry=DEFAULT_RETRY):
# Do not refresh is the state is already done, as the job will not
# change once complete.
if self.state != _DONE_STATE:
self.reload(retry=retry)
return self.state == _DONE_STATE
def result(self, timeout=None, retry=DEFAULT_RETRY):
if self.state is None:
self._begin(retry=retry)
# TODO: modify PollingFuture so it can pass a retry argument to done().
return super(_AsyncJob, self).result(timeout=timeout)
def cancelled(self):
return (
self.error_result is not None
and self.error_result.get("reason") == _STOPPED_REASON
)
class _JobConfig(object):
def __init__(self, job_type, **kwargs):
self._job_type = job_type
self._properties = {job_type: {}}
for prop, val in kwargs.items():
setattr(self, prop, val)
@property
def labels(self):
return self._properties.setdefault("labels", {})
@labels.setter
def labels(self, value):
if not isinstance(value, dict):
raise ValueError("Pass a dict")
self._properties["labels"] = value
def _get_sub_prop(self, key, default=None):
return _helpers._get_sub_prop(
self._properties, [self._job_type, key], default=default
)
def _set_sub_prop(self, key, value):
_helpers._set_sub_prop(self._properties, [self._job_type, key], value)
def _del_sub_prop(self, key):
_helpers._del_sub_prop(self._properties, [self._job_type, key])
def to_api_repr(self):
return copy.deepcopy(self._properties)
def _fill_from_default(self, default_job_config):
if self._job_type != default_job_config._job_type:
raise TypeError(
"attempted to merge two incompatible job types: "
+ repr(self._job_type)
+ ", "
+ repr(default_job_config._job_type)
)
new_job_config = self.__class__()
default_job_properties = copy.deepcopy(default_job_config._properties)
for key in self._properties:
if key != self._job_type:
default_job_properties[key] = self._properties[key]
default_job_properties[self._job_type].update(self._properties[self._job_type])
new_job_config._properties = default_job_properties
return new_job_config
@classmethod
def from_api_repr(cls, resource):
config = cls()
config._properties = copy.deepcopy(resource)
return config
class LoadJobConfig(_JobConfig):
def __init__(self, **kwargs):
super(LoadJobConfig, self).__init__("load", **kwargs)
@property
def allow_jagged_rows(self):
return self._get_sub_prop("allowJaggedRows")
@allow_jagged_rows.setter
def allow_jagged_rows(self, value):
self._set_sub_prop("allowJaggedRows", value)
@property
def allow_quoted_newlines(self):
return self._get_sub_prop("allowQuotedNewlines")
@allow_quoted_newlines.setter
def allow_quoted_newlines(self, value):
self._set_sub_prop("allowQuotedNewlines", value)
@property
def autodetect(self):
return self._get_sub_prop("autodetect")
@autodetect.setter
def autodetect(self, value):
self._set_sub_prop("autodetect", value)
@property
def clustering_fields(self):
prop = self._get_sub_prop("clustering")
if prop is not None:
return list(prop.get("fields", ()))
@clustering_fields.setter
def clustering_fields(self, value):
if value is not None:
self._set_sub_prop("clustering", {"fields": value})
else:
self._del_sub_prop("clustering")
@property
def create_disposition(self):
return self._get_sub_prop("createDisposition")
@create_disposition.setter
def create_disposition(self, value):
self._set_sub_prop("createDisposition", value)
@property
def destination_encryption_configuration(self):
prop = self._get_sub_prop("destinationEncryptionConfiguration")
if prop is not None:
prop = EncryptionConfiguration.from_api_repr(prop)
return prop
@destination_encryption_configuration.setter
def destination_encryption_configuration(self, value):
api_repr = value
if value is not None:
api_repr = value.to_api_repr()
self._set_sub_prop("destinationEncryptionConfiguration", api_repr)
else:
self._del_sub_prop("destinationEncryptionConfiguration")
@property
def destination_table_description(self):
prop = self._get_sub_prop("destinationTableProperties")
if prop is not None:
return prop["description"]
@destination_table_description.setter
def destination_table_description(self, value):
keys = [self._job_type, "destinationTableProperties", "description"]
if value is not None:
_helpers._set_sub_prop(self._properties, keys, value)
else:
_helpers._del_sub_prop(self._properties, keys)
@property
def destination_table_friendly_name(self):
prop = self._get_sub_prop("destinationTableProperties")
if prop is not None:
return prop["friendlyName"]
@destination_table_friendly_name.setter
def destination_table_friendly_name(self, value):
keys = [self._job_type, "destinationTableProperties", "friendlyName"]
if value is not None:
_helpers._set_sub_prop(self._properties, keys, value)
else:
_helpers._del_sub_prop(self._properties, keys)
@property
def encoding(self):
return self._get_sub_prop("encoding")
@encoding.setter
def encoding(self, value):
self._set_sub_prop("encoding", value)
@property
def field_delimiter(self):
return self._get_sub_prop("fieldDelimiter")
@field_delimiter.setter
def field_delimiter(self, value):
self._set_sub_prop("fieldDelimiter", value)
@property
def ignore_unknown_values(self):
return self._get_sub_prop("ignoreUnknownValues")
@ignore_unknown_values.setter
def ignore_unknown_values(self, value):
self._set_sub_prop("ignoreUnknownValues", value)
@property
def max_bad_records(self):
return _helpers._int_or_none(self._get_sub_prop("maxBadRecords"))
@max_bad_records.setter
def max_bad_records(self, value):
self._set_sub_prop("maxBadRecords", value)
@property
def null_marker(self):
return self._get_sub_prop("nullMarker")
@null_marker.setter
def null_marker(self, value):
self._set_sub_prop("nullMarker", value)
@property
def quote_character(self):
return self._get_sub_prop("quote")
@quote_character.setter
def quote_character(self, value):
self._set_sub_prop("quote", value)
@property
def schema(self):
schema = _helpers._get_sub_prop(self._properties, ["load", "schema", "fields"])
if schema is None:
return
return [SchemaField.from_api_repr(field) for field in schema]
@schema.setter
def schema(self, value):
if not all(hasattr(field, "to_api_repr") for field in value):
raise ValueError("Schema items must be fields")
_helpers._set_sub_prop(
self._properties,
["load", "schema", "fields"],
[field.to_api_repr() for field in value],
)
@property
def schema_update_options(self):
return self._get_sub_prop("schemaUpdateOptions")
@schema_update_options.setter
def schema_update_options(self, values):
self._set_sub_prop("schemaUpdateOptions", values)
@property
def skip_leading_rows(self):
return _helpers._int_or_none(self._get_sub_prop("skipLeadingRows"))
@skip_leading_rows.setter
def skip_leading_rows(self, value):
self._set_sub_prop("skipLeadingRows", str(value))
@property
def source_format(self):
return self._get_sub_prop("sourceFormat")
@source_format.setter
def source_format(self, value):
self._set_sub_prop("sourceFormat", value)
@property
def time_partitioning(self):
prop = self._get_sub_prop("timePartitioning")
if prop is not None:
prop = TimePartitioning.from_api_repr(prop)
return prop
@time_partitioning.setter
def time_partitioning(self, value):
api_repr = value
if value is not None:
api_repr = value.to_api_repr()
self._set_sub_prop("timePartitioning", api_repr)
else:
self._del_sub_prop("timePartitioning")
@property
def use_avro_logical_types(self):
return self._get_sub_prop("useAvroLogicalTypes")
@use_avro_logical_types.setter
def use_avro_logical_types(self, value):
self._set_sub_prop("useAvroLogicalTypes", bool(value))
@property
def write_disposition(self):
return self._get_sub_prop("writeDisposition")
@write_disposition.setter
def write_disposition(self, value):
self._set_sub_prop("writeDisposition", value)
class LoadJob(_AsyncJob):
_JOB_TYPE = "load"
def __init__(self, job_id, source_uris, destination, client, job_config=None):
super(LoadJob, self).__init__(job_id, client)
if job_config is None:
job_config = LoadJobConfig()
self.source_uris = source_uris
self.destination = destination
self._configuration = job_config
@property
def allow_jagged_rows(self):
return self._configuration.allow_jagged_rows
@property
def allow_quoted_newlines(self):
return self._configuration.allow_quoted_newlines
@property
def autodetect(self):
return self._configuration.autodetect
@property
def create_disposition(self):
return self._configuration.create_disposition
@property
def encoding(self):
return self._configuration.encoding
@property
def field_delimiter(self):
return self._configuration.field_delimiter
@property
def ignore_unknown_values(self):
return self._configuration.ignore_unknown_values
@property
def max_bad_records(self):
return self._configuration.max_bad_records
@property
def null_marker(self):
return self._configuration.null_marker
@property
def quote_character(self):
return self._configuration.quote_character
@property
def skip_leading_rows(self):
return self._configuration.skip_leading_rows
@property
def source_format(self):
return self._configuration.source_format
@property
def write_disposition(self):
return self._configuration.write_disposition
@property
def schema(self):
return self._configuration.schema
@property
def destination_encryption_configuration(self):
return self._configuration.destination_encryption_configuration
@property
def time_partitioning(self):
return self._configuration.time_partitioning
@property
def use_avro_logical_types(self):
return self._configuration.use_avro_logical_types
@property
def clustering_fields(self):
return self._configuration.clustering_fields
@property
def schema_update_options(self):
return self._configuration.schema_update_options
@property
def input_file_bytes(self):
return _helpers._int_or_none(
_helpers._get_sub_prop(
self._properties, ["statistics", "load", "inputFileBytes"]
)
)
@property
def input_files(self):
return _helpers._int_or_none(
_helpers._get_sub_prop(
self._properties, ["statistics", "load", "inputFiles"]
)
)
@property
def output_bytes(self):
return _helpers._int_or_none(
_helpers._get_sub_prop(
self._properties, ["statistics", "load", "outputBytes"]
)
)
@property
def output_rows(self):
return _helpers._int_or_none(
_helpers._get_sub_prop(
self._properties, ["statistics", "load", "outputRows"]
)
)
def to_api_repr(self):
configuration = self._configuration.to_api_repr()
if self.source_uris is not None:
_helpers._set_sub_prop(
configuration, ["load", "sourceUris"], self.source_uris
)
_helpers._set_sub_prop(
configuration, ["load", "destinationTable"], self.destination.to_api_repr()
)
return {
"jobReference": self._properties["jobReference"],
"configuration": configuration,
}
def _copy_configuration_properties(self, configuration):
self._configuration._properties = copy.deepcopy(configuration)
@classmethod
def from_api_repr(cls, resource, client):
config_resource = resource.get("configuration", {})
config = LoadJobConfig.from_api_repr(config_resource)
# A load job requires a destination table.
dest_config = config_resource["load"]["destinationTable"]
ds_ref = DatasetReference(dest_config["projectId"], dest_config["datasetId"])
destination = TableReference(ds_ref, dest_config["tableId"])
# sourceUris will be absent if this is a file upload.
source_uris = _helpers._get_sub_prop(config_resource, ["load", "sourceUris"])
job_ref = _JobReference._from_api_repr(resource["jobReference"])
job = cls(job_ref, source_uris, destination, client, config)
job._set_properties(resource)
return job
class CopyJobConfig(_JobConfig):
def __init__(self, **kwargs):
super(CopyJobConfig, self).__init__("copy", **kwargs)
@property
def create_disposition(self):
return self._get_sub_prop("createDisposition")
@create_disposition.setter
def create_disposition(self, value):
self._set_sub_prop("createDisposition", value)
@property
def write_disposition(self):
return self._get_sub_prop("writeDisposition")
@write_disposition.setter
def write_disposition(self, value):
self._set_sub_prop("writeDisposition", value)
@property
def destination_encryption_configuration(self):
prop = self._get_sub_prop("destinationEncryptionConfiguration")
if prop is not None:
prop = EncryptionConfiguration.from_api_repr(prop)
return prop
@destination_encryption_configuration.setter
def destination_encryption_configuration(self, value):
api_repr = value
if value is not None:
api_repr = value.to_api_repr()
self._set_sub_prop("destinationEncryptionConfiguration", api_repr)
class CopyJob(_AsyncJob):
_JOB_TYPE = "copy"
def __init__(self, job_id, sources, destination, client, job_config=None):
super(CopyJob, self).__init__(job_id, client)
if job_config is None:
job_config = CopyJobConfig()
self.destination = destination
self.sources = sources
self._configuration = job_config
@property
def create_disposition(self):
return self._configuration.create_disposition
@property
def write_disposition(self):
return self._configuration.write_disposition
@property
def destination_encryption_configuration(self):
return self._configuration.destination_encryption_configuration
def to_api_repr(self):
source_refs = [
{
"projectId": table.project,
"datasetId": table.dataset_id,
"tableId": table.table_id,
}
for table in self.sources
]
configuration = self._configuration.to_api_repr()
_helpers._set_sub_prop(configuration, ["copy", "sourceTables"], source_refs)
_helpers._set_sub_prop(
configuration,
["copy", "destinationTable"],
{
"projectId": self.destination.project,
"datasetId": self.destination.dataset_id,
"tableId": self.destination.table_id,
},
)
return {
"jobReference": self._properties["jobReference"],
"configuration": configuration,
}
def _copy_configuration_properties(self, configuration):
self._configuration._properties = copy.deepcopy(configuration)
@classmethod
def from_api_repr(cls, resource, client):
job_id, config_resource = cls._get_resource_config(resource)
config = CopyJobConfig.from_api_repr(config_resource)
# Copy required fields to the job.
copy_resource = config_resource["copy"]
destination = TableReference.from_api_repr(copy_resource["destinationTable"])
sources = []
source_configs = copy_resource.get("sourceTables")
if source_configs is None:
single = copy_resource.get("sourceTable")
if single is None:
raise KeyError("Resource missing 'sourceTables' / 'sourceTable'")
source_configs = [single]
for source_config in source_configs:
table_ref = TableReference.from_api_repr(source_config)
sources.append(table_ref)
job = cls(job_id, sources, destination, client=client, job_config=config)
job._set_properties(resource)
return job
class ExtractJobConfig(_JobConfig):
def __init__(self, **kwargs):
super(ExtractJobConfig, self).__init__("extract", **kwargs)
@property
def compression(self):
return self._get_sub_prop("compression")
@compression.setter
def compression(self, value):
self._set_sub_prop("compression", value)
@property
def destination_format(self):
return self._get_sub_prop("destinationFormat")
@destination_format.setter
def destination_format(self, value):
self._set_sub_prop("destinationFormat", value)
@property
def field_delimiter(self):
return self._get_sub_prop("fieldDelimiter")
@field_delimiter.setter
def field_delimiter(self, value):
self._set_sub_prop("fieldDelimiter", value)
@property
def print_header(self):
return self._get_sub_prop("printHeader")
@print_header.setter
def print_header(self, value):
self._set_sub_prop("printHeader", value)
class ExtractJob(_AsyncJob):
_JOB_TYPE = "extract"
def __init__(self, job_id, source, destination_uris, client, job_config=None):
super(ExtractJob, self).__init__(job_id, client)
if job_config is None:
job_config = ExtractJobConfig()
self.source = source
self.destination_uris = destination_uris
self._configuration = job_config
@property
def compression(self):
return self._configuration.compression
@property
def destination_format(self):
return self._configuration.destination_format
@property
def field_delimiter(self):
return self._configuration.field_delimiter
@property
def print_header(self):
return self._configuration.print_header
@property
def destination_uri_file_counts(self):
counts = self._job_statistics().get("destinationUriFileCounts")
if counts is not None:
return [int(count) for count in counts]
return None
def to_api_repr(self):
source_ref = {
"projectId": self.source.project,
"datasetId": self.source.dataset_id,
"tableId": self.source.table_id,
}
configuration = self._configuration.to_api_repr()
_helpers._set_sub_prop(configuration, ["extract", "sourceTable"], source_ref)
_helpers._set_sub_prop(
configuration, ["extract", "destinationUris"], self.destination_uris
)
return {
"jobReference": self._properties["jobReference"],
"configuration": configuration,
}
def _copy_configuration_properties(self, configuration):
self._configuration._properties = copy.deepcopy(configuration)
@classmethod
def from_api_repr(cls, resource, client):
job_id, config_resource = cls._get_resource_config(resource)
config = ExtractJobConfig.from_api_repr(config_resource)
source_config = _helpers._get_sub_prop(
config_resource, ["extract", "sourceTable"]
)
dataset = DatasetReference(
source_config["projectId"], source_config["datasetId"]
)
source = dataset.table(source_config["tableId"])
destination_uris = _helpers._get_sub_prop(
config_resource, ["extract", "destinationUris"]
)
job = cls(job_id, source, destination_uris, client=client, job_config=config)
job._set_properties(resource)
return job
def _from_api_repr_query_parameters(resource):
return [_query_param_from_api_repr(mapping) for mapping in resource]
def _to_api_repr_query_parameters(value):
return [query_parameter.to_api_repr() for query_parameter in value]
def _from_api_repr_udf_resources(resource):
udf_resources = []
for udf_mapping in resource:
for udf_type, udf_value in udf_mapping.items():
udf_resources.append(UDFResource(udf_type, udf_value))
return udf_resources
def _to_api_repr_udf_resources(value):
return [{udf_resource.udf_type: udf_resource.value} for udf_resource in value]
def _from_api_repr_table_defs(resource):
return {k: ExternalConfig.from_api_repr(v) for k, v in resource.items()}
def _to_api_repr_table_defs(value):
return {k: ExternalConfig.to_api_repr(v) for k, v in value.items()}
class QueryJobConfig(_JobConfig):
def __init__(self, **kwargs):
super(QueryJobConfig, self).__init__("query", **kwargs)
@property
def destination_encryption_configuration(self):
prop = self._get_sub_prop("destinationEncryptionConfiguration")
if prop is not None:
prop = EncryptionConfiguration.from_api_repr(prop)
return prop
@destination_encryption_configuration.setter
def destination_encryption_configuration(self, value):
api_repr = value
if value is not None:
api_repr = value.to_api_repr()
self._set_sub_prop("destinationEncryptionConfiguration", api_repr)
@property
def allow_large_results(self):
return self._get_sub_prop("allowLargeResults")
@allow_large_results.setter
def allow_large_results(self, value):
self._set_sub_prop("allowLargeResults", value)
@property
def create_disposition(self):
return self._get_sub_prop("createDisposition")
@create_disposition.setter
def create_disposition(self, value):
self._set_sub_prop("createDisposition", value)
@property
def default_dataset(self):
prop = self._get_sub_prop("defaultDataset")
if prop is not None:
prop = DatasetReference.from_api_repr(prop)
return prop
@default_dataset.setter
def default_dataset(self, value):
resource = None
if value is not None:
resource = value.to_api_repr()
self._set_sub_prop("defaultDataset", resource)
@property
def destination(self):
prop = self._get_sub_prop("destinationTable")
if prop is not None:
prop = TableReference.from_api_repr(prop)
return prop
@destination.setter
def destination(self, value):
resource = None
if value is not None:
resource = value.to_api_repr()
self._set_sub_prop("destinationTable", resource)
@property
def dry_run(self):
return self._properties.get("dryRun")
@dry_run.setter
def dry_run(self, value):
self._properties["dryRun"] = value
@property
def flatten_results(self):
return self._get_sub_prop("flattenResults")
@flatten_results.setter
def flatten_results(self, value):
self._set_sub_prop("flattenResults", value)
@property
def maximum_billing_tier(self):
return self._get_sub_prop("maximumBillingTier")
@maximum_billing_tier.setter
def maximum_billing_tier(self, value):
self._set_sub_prop("maximumBillingTier", value)
@property
def maximum_bytes_billed(self):
return _helpers._int_or_none(self._get_sub_prop("maximumBytesBilled"))
@maximum_bytes_billed.setter
def maximum_bytes_billed(self, value):
self._set_sub_prop("maximumBytesBilled", str(value))
@property
def priority(self):
return self._get_sub_prop("priority")
@priority.setter
def priority(self, value):
self._set_sub_prop("priority", value)
@property
def query_parameters(self):
prop = self._get_sub_prop("queryParameters", default=[])
return _from_api_repr_query_parameters(prop)
@query_parameters.setter
def query_parameters(self, values):
self._set_sub_prop("queryParameters", _to_api_repr_query_parameters(values))
@property
def udf_resources(self):
prop = self._get_sub_prop("userDefinedFunctionResources", default=[])
return _from_api_repr_udf_resources(prop)
@udf_resources.setter
def udf_resources(self, values):
self._set_sub_prop(
"userDefinedFunctionResources", _to_api_repr_udf_resources(values)
)
@property
def use_legacy_sql(self):
return self._get_sub_prop("useLegacySql")
@use_legacy_sql.setter
def use_legacy_sql(self, value):
self._set_sub_prop("useLegacySql", value)
@property
def use_query_cache(self):
return self._get_sub_prop("useQueryCache")
@use_query_cache.setter
def use_query_cache(self, value):
self._set_sub_prop("useQueryCache", value)
@property
def write_disposition(self):
return self._get_sub_prop("writeDisposition")
@write_disposition.setter
def write_disposition(self, value):
self._set_sub_prop("writeDisposition", value)
@property
def table_definitions(self):
prop = self._get_sub_prop("tableDefinitions")
if prop is not None:
prop = _from_api_repr_table_defs(prop)
return prop
@table_definitions.setter
def table_definitions(self, values):
self._set_sub_prop("tableDefinitions", _to_api_repr_table_defs(values))
@property
def time_partitioning(self):
prop = self._get_sub_prop("timePartitioning")
if prop is not None:
prop = TimePartitioning.from_api_repr(prop)
return prop
@time_partitioning.setter
def time_partitioning(self, value):
api_repr = value
if value is not None:
api_repr = value.to_api_repr()
self._set_sub_prop("timePartitioning", api_repr)
@property
def clustering_fields(self):
prop = self._get_sub_prop("clustering")
if prop is not None:
return list(prop.get("fields", ()))
@clustering_fields.setter
def clustering_fields(self, value):
if value is not None:
self._set_sub_prop("clustering", {"fields": value})
else:
self._del_sub_prop("clustering")
@property
def schema_update_options(self):
return self._get_sub_prop("schemaUpdateOptions")
@schema_update_options.setter
def schema_update_options(self, values):
self._set_sub_prop("schemaUpdateOptions", values)
def to_api_repr(self):
resource = copy.deepcopy(self._properties)
# Query parameters have an addition property associated with them
# to indicate if the query is using named or positional parameters.
query_parameters = resource["query"].get("queryParameters")
if query_parameters:
if query_parameters[0].get("name") is None:
resource["query"]["parameterMode"] = "POSITIONAL"
else:
resource["query"]["parameterMode"] = "NAMED"
return resource
class QueryJob(_AsyncJob):
_JOB_TYPE = "query"
_UDF_KEY = "userDefinedFunctionResources"
def __init__(self, job_id, query, client, job_config=None):
super(QueryJob, self).__init__(job_id, client)
if job_config is None:
job_config = QueryJobConfig()
if job_config.use_legacy_sql is None:
job_config.use_legacy_sql = False
self.query = query
self._configuration = job_config
self._query_results = None
self._done_timeout = None
@property
def allow_large_results(self):
return self._configuration.allow_large_results
@property
def create_disposition(self):
return self._configuration.create_disposition
@property
def default_dataset(self):
return self._configuration.default_dataset
@property
def destination(self):
return self._configuration.destination
@property
def destination_encryption_configuration(self):
return self._configuration.destination_encryption_configuration
@property
def dry_run(self):
return self._configuration.dry_run
@property
def flatten_results(self):
return self._configuration.flatten_results
@property
def priority(self):
return self._configuration.priority
@property
def query_parameters(self):
return self._configuration.query_parameters
@property
def udf_resources(self):
return self._configuration.udf_resources
@property
def use_legacy_sql(self):
return self._configuration.use_legacy_sql
@property
def use_query_cache(self):
return self._configuration.use_query_cache
@property
def write_disposition(self):
return self._configuration.write_disposition
@property
def maximum_billing_tier(self):
return self._configuration.maximum_billing_tier
@property
def maximum_bytes_billed(self):
return self._configuration.maximum_bytes_billed
@property
def table_definitions(self):
return self._configuration.table_definitions
@property
def time_partitioning(self):
return self._configuration.time_partitioning
@property
def clustering_fields(self):
return self._configuration.clustering_fields
@property
def schema_update_options(self):
return self._configuration.schema_update_options
def to_api_repr(self):
configuration = self._configuration.to_api_repr()
resource = {
"jobReference": self._properties["jobReference"],
"configuration": configuration,
}
configuration["query"]["query"] = self.query
return resource
def _copy_configuration_properties(self, configuration):
self._configuration._properties = copy.deepcopy(configuration)
self.query = _helpers._get_sub_prop(configuration, ["query", "query"])
@classmethod
def from_api_repr(cls, resource, client):
job_id, config = cls._get_resource_config(resource)
query = config["query"]["query"]
job = cls(job_id, query, client=client)
job._set_properties(resource)
return job
@property
def query_plan(self):
plan_entries = self._job_statistics().get("queryPlan", ())
return [QueryPlanEntry.from_api_repr(entry) for entry in plan_entries]
@property
def timeline(self):
raw = self._job_statistics().get("timeline", ())
return [TimelineEntry.from_api_repr(entry) for entry in raw]
@property
def total_bytes_processed(self):
result = self._job_statistics().get("totalBytesProcessed")
if result is not None:
result = int(result)
return result
@property
def total_bytes_billed(self):
result = self._job_statistics().get("totalBytesBilled")
if result is not None:
result = int(result)
return result
@property
def billing_tier(self):
return self._job_statistics().get("billingTier")
@property
def cache_hit(self):
return self._job_statistics().get("cacheHit")
@property
def ddl_operation_performed(self):
return self._job_statistics().get("ddlOperationPerformed")
@property
def ddl_target_table(self):
prop = self._job_statistics().get("ddlTargetTable")
if prop is not None:
prop = TableReference.from_api_repr(prop)
return prop
@property
def num_dml_affected_rows(self):
result = self._job_statistics().get("numDmlAffectedRows")
if result is not None:
result = int(result)
return result
@property
def slot_millis(self):
return _helpers._int_or_none(self._job_statistics().get("totalSlotMs"))
@property
def statement_type(self):
return self._job_statistics().get("statementType")
@property
def referenced_tables(self):
tables = []
datasets_by_project_name = {}
for table in self._job_statistics().get("referencedTables", ()):
t_project = table["projectId"]
ds_id = table["datasetId"]
t_dataset = datasets_by_project_name.get((t_project, ds_id))
if t_dataset is None:
t_dataset = DatasetReference(t_project, ds_id)
datasets_by_project_name[(t_project, ds_id)] = t_dataset
t_name = table["tableId"]
tables.append(t_dataset.table(t_name))
return tables
@property
def undeclared_query_parameters(self):
parameters = []
undeclared = self._job_statistics().get("undeclaredQueryParameters", ())
for parameter in undeclared:
p_type = parameter["parameterType"]
if "arrayType" in p_type:
klass = ArrayQueryParameter
elif "structTypes" in p_type:
klass = StructQueryParameter
else:
klass = ScalarQueryParameter
parameters.append(klass.from_api_repr(parameter))
return parameters
@property
def estimated_bytes_processed(self):
result = self._job_statistics().get("estimatedBytesProcessed")
if result is not None:
result = int(result)
return result
def done(self, retry=DEFAULT_RETRY):
# Since the API to getQueryResults can hang up to the timeout value
# (default of 10 seconds), set the timeout parameter to ensure that
# the timeout from the futures API is respected. See:
# https://github.com/GoogleCloudPlatform/google-cloud-python/issues/4135
timeout_ms = None
if self._done_timeout is not None:
# Subtract a buffer for context switching, network latency, etc.
timeout = self._done_timeout - _TIMEOUT_BUFFER_SECS
timeout = max(min(timeout, 10), 0)
self._done_timeout -= timeout
self._done_timeout = max(0, self._done_timeout)
timeout_ms = int(timeout * 1000)
# Do not refresh is the state is already done, as the job will not
# change once complete.
if self.state != _DONE_STATE:
self._query_results = self._client._get_query_results(
self.job_id,
retry,
project=self.project,
timeout_ms=timeout_ms,
location=self.location,
)
# Only reload the job once we know the query is complete.
# This will ensure that fields such as the destination table are
# correctly populated.
if self._query_results.complete:
self.reload(retry=retry)
return self.state == _DONE_STATE
def _blocking_poll(self, timeout=None):
self._done_timeout = timeout
super(QueryJob, self)._blocking_poll(timeout=timeout)
def result(self, timeout=None, retry=DEFAULT_RETRY):
super(QueryJob, self).result(timeout=timeout)
# Return an iterator instead of returning the job.
if not self._query_results:
self._query_results = self._client._get_query_results(
self.job_id, retry, project=self.project, location=self.location
)
# If the query job is complete but there are no query results, this was
# special job, such as a DDL query. Return an empty result set to
# indicate success and avoid calling tabledata.list on a table which
# can't be read (such as a view table).
if self._query_results.total_rows is None:
return _EmptyRowIterator()
schema = self._query_results.schema
dest_table_ref = self.destination
dest_table = Table(dest_table_ref, schema=schema)
return self._client.list_rows(dest_table, retry=retry)
def to_dataframe(self):
return self.result().to_dataframe()
def __iter__(self):
return iter(self.result())
class QueryPlanEntryStep(object):
def __init__(self, kind, substeps):
self.kind = kind
self.substeps = list(substeps)
@classmethod
def from_api_repr(cls, resource):
return cls(kind=resource.get("kind"), substeps=resource.get("substeps", ()))
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return self.kind == other.kind and self.substeps == other.substeps
class QueryPlanEntry(object):
def __init__(self):
self._properties = {}
@classmethod
def from_api_repr(cls, resource):
entry = cls()
entry._properties = resource
return entry
@property
def name(self):
return self._properties.get("name")
@property
def entry_id(self):
return self._properties.get("id")
@property
def start(self):
if self._properties.get("startMs") is None:
return None
return _helpers._datetime_from_microseconds(
int(self._properties.get("startMs")) * 1000.0
)
@property
def end(self):
if self._properties.get("endMs") is None:
return None
return _helpers._datetime_from_microseconds(
int(self._properties.get("endMs")) * 1000.0
)
@property
def input_stages(self):
if self._properties.get("inputStages") is None:
return []
return [
_helpers._int_or_none(entry)
for entry in self._properties.get("inputStages")
]
@property
def parallel_inputs(self):
return _helpers._int_or_none(self._properties.get("parallelInputs"))
@property
def completed_parallel_inputs(self):
return _helpers._int_or_none(self._properties.get("completedParallelInputs"))
@property
def wait_ms_avg(self):
return _helpers._int_or_none(self._properties.get("waitMsAvg"))
@property
def wait_ms_max(self):
return _helpers._int_or_none(self._properties.get("waitMsMax"))
@property
def wait_ratio_avg(self):
return self._properties.get("waitRatioAvg")
@property
def wait_ratio_max(self):
return self._properties.get("waitRatioMax")
@property
def read_ms_avg(self):
return _helpers._int_or_none(self._properties.get("readMsAvg"))
@property
def read_ms_max(self):
return _helpers._int_or_none(self._properties.get("readMsMax"))
@property
def read_ratio_avg(self):
return self._properties.get("readRatioAvg")
@property
def read_ratio_max(self):
return self._properties.get("readRatioMax")
@property
def compute_ms_avg(self):
return _helpers._int_or_none(self._properties.get("computeMsAvg"))
@property
def compute_ms_max(self):
return _helpers._int_or_none(self._properties.get("computeMsMax"))
@property
def compute_ratio_avg(self):
return self._properties.get("computeRatioAvg")
@property
def compute_ratio_max(self):
return self._properties.get("computeRatioMax")
@property
def write_ms_avg(self):
return _helpers._int_or_none(self._properties.get("writeMsAvg"))
@property
def write_ms_max(self):
return _helpers._int_or_none(self._properties.get("writeMsMax"))
@property
def write_ratio_avg(self):
return self._properties.get("writeRatioAvg")
@property
def write_ratio_max(self):
return self._properties.get("writeRatioMax")
@property
def records_read(self):
return _helpers._int_or_none(self._properties.get("recordsRead"))
@property
def records_written(self):
return _helpers._int_or_none(self._properties.get("recordsWritten"))
@property
def status(self):
return self._properties.get("status")
@property
def shuffle_output_bytes(self):
return _helpers._int_or_none(self._properties.get("shuffleOutputBytes"))
@property
def shuffle_output_bytes_spilled(self):
return _helpers._int_or_none(self._properties.get("shuffleOutputBytesSpilled"))
@property
def steps(self):
return [
QueryPlanEntryStep.from_api_repr(step)
for step in self._properties.get("steps", [])
]
class TimelineEntry(object):
def __init__(self):
self._properties = {}
@classmethod
def from_api_repr(cls, resource):
entry = cls()
entry._properties = resource
return entry
@property
def elapsed_ms(self):
return _helpers._int_or_none(self._properties.get("elapsedMs"))
@property
def active_units(self):
return _helpers._int_or_none(self._properties.get("activeUnits"))
@property
def pending_units(self):
return _helpers._int_or_none(self._properties.get("pendingUnits"))
@property
def completed_units(self):
return _helpers._int_or_none(self._properties.get("completedUnits"))
@property
def slot_millis(self):
return _helpers._int_or_none(self._properties.get("totalSlotMs"))
class UnknownJob(_AsyncJob):
@classmethod
def from_api_repr(cls, resource, client):
job_ref_properties = resource.get("jobReference", {"projectId": client.project})
job_ref = _JobReference._from_api_repr(job_ref_properties)
job = cls(job_ref, client)
resource["jobReference"] = job_ref_properties
job._properties = resource
return job
| true | true |
f72bb4debf4ce516c6fa1d5f7294e9cce53c4b79 | 4,826 | py | Python | cccp/__init__.py | sloev/cccp | 829c359a8607d3f3fb2e1e82f2114bb1c8404ce3 | [
"MIT"
] | 1 | 2020-03-14T11:56:09.000Z | 2020-03-14T11:56:09.000Z | cccp/__init__.py | sloev/cccp | 829c359a8607d3f3fb2e1e82f2114bb1c8404ce3 | [
"MIT"
] | null | null | null | cccp/__init__.py | sloev/cccp | 829c359a8607d3f3fb2e1e82f2114bb1c8404ce3 | [
"MIT"
] | 3 | 2020-03-08T13:23:37.000Z | 2021-12-06T19:46:27.000Z | from string import Template
from dominate.tags import script, link, style
from dominate.util import raw
import json
REQUIRED = [
script(
src="https://unpkg.com/axios@0.19.0/dist/axios.min.js", crossorigin="anonymous"
),
script(
src="https://code.jquery.com/jquery-3.3.1.slim.min.js",
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo",
crossorigin="anonymous",
),
]
BOOTSTRAP = [
link(
rel="stylesheet",
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css",
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T",
crossorigin="anonymous",
),
script(
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js",
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1",
crossorigin="anonymous",
),
script(
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js",
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM",
crossorigin="anonymous",
),
]
CHARTJS = script(
src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"
)
def render(x):
if isinstance(x, list):
return "".join(e.render(pretty=False) for e in x)
return x.render(pretty=False)
class CustomTemplate(Template):
delimiter = "$$"
class JavaScript:
defaults = None
js_source = ""
def render(self, values, with_script_tag=True):
template = CustomTemplate(self.js_source)
rendered = raw(template.substitute(values).strip())
if with_script_tag:
return script(rendered, type="text/javascript")
else:
return rendered
def __new__(cls, with_script_tag=True, **kwargs):
values = cls.defaults or {}
values.update(kwargs)
inst = super(JavaScript, cls).__new__(cls)
return inst.render(values, with_script_tag)
class CreateReplaceOuterHtmlFunc(JavaScript):
js_source = """
function ReplaceOuterHtml(url, id, params){
axios.get(url, {params: params === undefined ? {} : params})
.then(function (response) {
document.getElementById(id).outerHTML = response.data;
});
};
"""
def replaceOuterHtml(url, id, **kwargs):
params = json.dumps(kwargs)
return f"ReplaceOuterHtml('{url}', '{id}', {params})"
class CreateReplaceInnerHtmlFunc(JavaScript):
js_source = """
function ReplaceInnerHtml(url, id, params){
axios.get(url, {params: params === undefined ? {} : params})
.then(function (response) {
document.getElementById(id).innerHTML = response.data;
});
};
"""
def replaceInnerHtml(url, id, **kwargs):
params = json.dumps(kwargs)
return f"ReplaceInnerHtml('{url}', '{id}', {params})"
# backwards compatibility
replaceHtml = replaceInnerHtml
class CreateAppendHtmlFunc(JavaScript):
js_source = """
function AppendHtml(url, id, params){
axios.get(url, {params: params === undefined ? {} : params})
.then( function (response) {
$("#"+id).append(response.data);
});
};
"""
def appendHtml(url, id, **kwargs):
params = json.dumps(kwargs)
return f"AppendHtml('{url}', '{id}', {params})"
class CreatePrependHtmlFunc(JavaScript):
js_source = """
function PrependHtml(url, id, params){
axios.get(url, {params: params === undefined ? {} : params})
.then( function(response) {
$("#"+id).prepend(response.data);
});
};
"""
def prependHtml(url, id, **kwargs):
params = json.dumps(kwargs)
return f"PrependHtml('{url}', '{id}', {params})"
class CreateRemoveHtmlFunc(JavaScript):
js_source = """
function RemoveHtml(id){
$("#"+id).remove();
};
"""
class CreateSetAttributeFunction(JavaScript):
js_source = """
function SetAttribute(id, attribute, value){
$("#"+id).attr(attribute, value)
};
"""
def removeHtml(id):
return f"RemoveHtml('{id}')"
def chain_functions(*function_strings):
return "; ".join(function_strings) + ";"
def style_tag_with_css(css):
return style(raw(css))
class LineChart(JavaScript):
js_source = """
const canvas$$id = $('#$$id')
const lineChart$$id = new Chart(canvas$$id, {
type: "line",
data: {
labels: $$xlabels,
datasets: $$datasets
},
options: $$options
});
"""
def line_chart(id, xlabels, datasets, options):
return LineChart(id=id, xlabels=json.dumps(xlabels), datasets=json.dumps(datasets), options=json.dumps(options or {}))
| 26.371585 | 122 | 0.623291 | from string import Template
from dominate.tags import script, link, style
from dominate.util import raw
import json
REQUIRED = [
script(
src="https://unpkg.com/axios@0.19.0/dist/axios.min.js", crossorigin="anonymous"
),
script(
src="https://code.jquery.com/jquery-3.3.1.slim.min.js",
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo",
crossorigin="anonymous",
),
]
BOOTSTRAP = [
link(
rel="stylesheet",
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css",
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T",
crossorigin="anonymous",
),
script(
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js",
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1",
crossorigin="anonymous",
),
script(
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js",
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM",
crossorigin="anonymous",
),
]
CHARTJS = script(
src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"
)
def render(x):
if isinstance(x, list):
return "".join(e.render(pretty=False) for e in x)
return x.render(pretty=False)
class CustomTemplate(Template):
delimiter = "$$"
class JavaScript:
defaults = None
js_source = ""
def render(self, values, with_script_tag=True):
template = CustomTemplate(self.js_source)
rendered = raw(template.substitute(values).strip())
if with_script_tag:
return script(rendered, type="text/javascript")
else:
return rendered
def __new__(cls, with_script_tag=True, **kwargs):
values = cls.defaults or {}
values.update(kwargs)
inst = super(JavaScript, cls).__new__(cls)
return inst.render(values, with_script_tag)
class CreateReplaceOuterHtmlFunc(JavaScript):
js_source = """
function ReplaceOuterHtml(url, id, params){
axios.get(url, {params: params === undefined ? {} : params})
.then(function (response) {
document.getElementById(id).outerHTML = response.data;
});
};
"""
def replaceOuterHtml(url, id, **kwargs):
params = json.dumps(kwargs)
return f"ReplaceOuterHtml('{url}', '{id}', {params})"
class CreateReplaceInnerHtmlFunc(JavaScript):
js_source = """
function ReplaceInnerHtml(url, id, params){
axios.get(url, {params: params === undefined ? {} : params})
.then(function (response) {
document.getElementById(id).innerHTML = response.data;
});
};
"""
def replaceInnerHtml(url, id, **kwargs):
params = json.dumps(kwargs)
return f"ReplaceInnerHtml('{url}', '{id}', {params})"
replaceHtml = replaceInnerHtml
class CreateAppendHtmlFunc(JavaScript):
js_source = """
function AppendHtml(url, id, params){
axios.get(url, {params: params === undefined ? {} : params})
.then( function (response) {
$("#"+id).append(response.data);
});
};
"""
def appendHtml(url, id, **kwargs):
params = json.dumps(kwargs)
return f"AppendHtml('{url}', '{id}', {params})"
class CreatePrependHtmlFunc(JavaScript):
js_source = """
function PrependHtml(url, id, params){
axios.get(url, {params: params === undefined ? {} : params})
.then( function(response) {
$("#"+id).prepend(response.data);
});
};
"""
def prependHtml(url, id, **kwargs):
params = json.dumps(kwargs)
return f"PrependHtml('{url}', '{id}', {params})"
class CreateRemoveHtmlFunc(JavaScript):
js_source = """
function RemoveHtml(id){
$("#"+id).remove();
};
"""
class CreateSetAttributeFunction(JavaScript):
js_source = """
function SetAttribute(id, attribute, value){
$("#"+id).attr(attribute, value)
};
"""
def removeHtml(id):
return f"RemoveHtml('{id}')"
def chain_functions(*function_strings):
return "; ".join(function_strings) + ";"
def style_tag_with_css(css):
return style(raw(css))
class LineChart(JavaScript):
js_source = """
const canvas$$id = $('#$$id')
const lineChart$$id = new Chart(canvas$$id, {
type: "line",
data: {
labels: $$xlabels,
datasets: $$datasets
},
options: $$options
});
"""
def line_chart(id, xlabels, datasets, options):
return LineChart(id=id, xlabels=json.dumps(xlabels), datasets=json.dumps(datasets), options=json.dumps(options or {}))
| true | true |
f72bb5154ac3efc57f3e05c96a98460ac4436137 | 4,661 | py | Python | lbrynet/core/PaymentRateManager.py | anon4040/lbry | 1f1b34863805f4954fbef3f163ef65268a66771a | [
"MIT"
] | 1 | 2018-12-08T04:42:11.000Z | 2018-12-08T04:42:11.000Z | lbrynet/core/PaymentRateManager.py | mrlucky9/lbry | bf6bc02828ed55e98a3002f487041acbd7841883 | [
"MIT"
] | null | null | null | lbrynet/core/PaymentRateManager.py | mrlucky9/lbry | bf6bc02828ed55e98a3002f487041acbd7841883 | [
"MIT"
] | 1 | 2018-05-01T09:28:52.000Z | 2018-05-01T09:28:52.000Z | from lbrynet.core.Strategy import get_default_strategy, OnlyFreeStrategy
from lbrynet import conf
from decimal import Decimal
class BasePaymentRateManager(object):
def __init__(self, rate=None, info_rate=None):
self.min_blob_data_payment_rate = rate if rate is not None else conf.settings['data_rate']
self.min_blob_info_payment_rate = (
info_rate if info_rate is not None else conf.settings['min_info_rate'])
class PaymentRateManager(object):
def __init__(self, base, rate=None):
"""
@param base: a BasePaymentRateManager
@param rate: the min blob data payment rate
"""
self.base = base
self.min_blob_data_payment_rate = rate
self.points_paid = 0.0
def get_rate_blob_data(self, peer):
return self.get_effective_min_blob_data_payment_rate()
def accept_rate_blob_data(self, peer, payment_rate):
return payment_rate >= self.get_effective_min_blob_data_payment_rate()
def get_effective_min_blob_data_payment_rate(self):
if self.min_blob_data_payment_rate is None:
return self.base.min_blob_data_payment_rate
return self.min_blob_data_payment_rate
def record_points_paid(self, amount):
self.points_paid += amount
class NegotiatedPaymentRateManager(object):
def __init__(self, base, availability_tracker, generous=None):
"""
@param base: a BasePaymentRateManager
@param availability_tracker: a BlobAvailabilityTracker
@param rate: the min blob data payment rate
"""
self.base = base
self.min_blob_data_payment_rate = base.min_blob_data_payment_rate
self.points_paid = 0.0
self.blob_tracker = availability_tracker
self.generous = generous if generous is not None else conf.settings['is_generous_host']
self.strategy = get_default_strategy(self.blob_tracker,
base_price=self.base.min_blob_data_payment_rate,
is_generous=generous)
def get_rate_blob_data(self, peer, blobs):
response = self.strategy.make_offer(peer, blobs)
return response.rate
def accept_rate_blob_data(self, peer, blobs, offer):
offer = self.strategy.respond_to_offer(offer, peer, blobs)
self.strategy.update_accepted_offers(peer, offer)
return offer.is_accepted
def reply_to_offer(self, peer, blobs, offer):
reply = self.strategy.respond_to_offer(offer, peer, blobs)
self.strategy.update_accepted_offers(peer, reply)
return reply
def get_rate_for_peer(self, peer):
return self.strategy.accepted_offers.get(peer, False)
def record_points_paid(self, amount):
self.points_paid += amount
def record_offer_reply(self, peer, offer):
self.strategy.update_accepted_offers(peer, offer)
def price_limit_reached(self, peer):
if peer in self.strategy.pending_sent_offers:
offer = self.strategy.pending_sent_offers[peer]
return (offer.is_too_low and
round(Decimal.from_float(offer.rate), 5) >= round(self.strategy.max_rate, 5))
return False
class OnlyFreePaymentsManager(object):
def __init__(self, **kwargs):
"""
A payment rate manager that will only ever accept and offer a rate of 0.0,
Used for testing
"""
self.base = BasePaymentRateManager(0.0, 0.0)
self.points_paid = 0.0
self.generous = True
self.strategy = OnlyFreeStrategy()
def get_rate_blob_data(self, peer, blobs):
response = self.strategy.make_offer(peer, blobs)
return response.rate
def accept_rate_blob_data(self, peer, blobs, offer):
offer = self.strategy.respond_to_offer(offer, peer, blobs)
self.strategy.update_accepted_offers(peer, offer)
return offer.is_accepted
def reply_to_offer(self, peer, blobs, offer):
reply = self.strategy.respond_to_offer(offer, peer, blobs)
self.strategy.update_accepted_offers(peer, reply)
return reply
def get_rate_for_peer(self, peer):
return self.strategy.accepted_offers.get(peer, False)
def record_points_paid(self, amount):
self.points_paid += amount
def record_offer_reply(self, peer, offer):
self.strategy.update_accepted_offers(peer, offer)
def price_limit_reached(self, peer):
if peer in self.strategy.pending_sent_offers:
offer = self.strategy.pending_sent_offers[peer]
if offer.rate > 0.0:
return True
return False
| 36.414063 | 98 | 0.679897 | from lbrynet.core.Strategy import get_default_strategy, OnlyFreeStrategy
from lbrynet import conf
from decimal import Decimal
class BasePaymentRateManager(object):
def __init__(self, rate=None, info_rate=None):
self.min_blob_data_payment_rate = rate if rate is not None else conf.settings['data_rate']
self.min_blob_info_payment_rate = (
info_rate if info_rate is not None else conf.settings['min_info_rate'])
class PaymentRateManager(object):
def __init__(self, base, rate=None):
self.base = base
self.min_blob_data_payment_rate = rate
self.points_paid = 0.0
def get_rate_blob_data(self, peer):
return self.get_effective_min_blob_data_payment_rate()
def accept_rate_blob_data(self, peer, payment_rate):
return payment_rate >= self.get_effective_min_blob_data_payment_rate()
def get_effective_min_blob_data_payment_rate(self):
if self.min_blob_data_payment_rate is None:
return self.base.min_blob_data_payment_rate
return self.min_blob_data_payment_rate
def record_points_paid(self, amount):
self.points_paid += amount
class NegotiatedPaymentRateManager(object):
def __init__(self, base, availability_tracker, generous=None):
self.base = base
self.min_blob_data_payment_rate = base.min_blob_data_payment_rate
self.points_paid = 0.0
self.blob_tracker = availability_tracker
self.generous = generous if generous is not None else conf.settings['is_generous_host']
self.strategy = get_default_strategy(self.blob_tracker,
base_price=self.base.min_blob_data_payment_rate,
is_generous=generous)
def get_rate_blob_data(self, peer, blobs):
response = self.strategy.make_offer(peer, blobs)
return response.rate
def accept_rate_blob_data(self, peer, blobs, offer):
offer = self.strategy.respond_to_offer(offer, peer, blobs)
self.strategy.update_accepted_offers(peer, offer)
return offer.is_accepted
def reply_to_offer(self, peer, blobs, offer):
reply = self.strategy.respond_to_offer(offer, peer, blobs)
self.strategy.update_accepted_offers(peer, reply)
return reply
def get_rate_for_peer(self, peer):
return self.strategy.accepted_offers.get(peer, False)
def record_points_paid(self, amount):
self.points_paid += amount
def record_offer_reply(self, peer, offer):
self.strategy.update_accepted_offers(peer, offer)
def price_limit_reached(self, peer):
if peer in self.strategy.pending_sent_offers:
offer = self.strategy.pending_sent_offers[peer]
return (offer.is_too_low and
round(Decimal.from_float(offer.rate), 5) >= round(self.strategy.max_rate, 5))
return False
class OnlyFreePaymentsManager(object):
def __init__(self, **kwargs):
self.base = BasePaymentRateManager(0.0, 0.0)
self.points_paid = 0.0
self.generous = True
self.strategy = OnlyFreeStrategy()
def get_rate_blob_data(self, peer, blobs):
response = self.strategy.make_offer(peer, blobs)
return response.rate
def accept_rate_blob_data(self, peer, blobs, offer):
offer = self.strategy.respond_to_offer(offer, peer, blobs)
self.strategy.update_accepted_offers(peer, offer)
return offer.is_accepted
def reply_to_offer(self, peer, blobs, offer):
reply = self.strategy.respond_to_offer(offer, peer, blobs)
self.strategy.update_accepted_offers(peer, reply)
return reply
def get_rate_for_peer(self, peer):
return self.strategy.accepted_offers.get(peer, False)
def record_points_paid(self, amount):
self.points_paid += amount
def record_offer_reply(self, peer, offer):
self.strategy.update_accepted_offers(peer, offer)
def price_limit_reached(self, peer):
if peer in self.strategy.pending_sent_offers:
offer = self.strategy.pending_sent_offers[peer]
if offer.rate > 0.0:
return True
return False
| true | true |
f72bb56ed6f1866f992171ab177c9a2074f78328 | 1,005 | py | Python | cea/examples/extract_reference_case.py | AlexJew/CityEnergyAnalyst | 6eb372c79e5100a2d0abce78561ae368fb409cd1 | [
"MIT"
] | null | null | null | cea/examples/extract_reference_case.py | AlexJew/CityEnergyAnalyst | 6eb372c79e5100a2d0abce78561ae368fb409cd1 | [
"MIT"
] | null | null | null | cea/examples/extract_reference_case.py | AlexJew/CityEnergyAnalyst | 6eb372c79e5100a2d0abce78561ae368fb409cd1 | [
"MIT"
] | null | null | null | """
Extract the reference case (``cea/examples/reference-case-open.zip``).
"""
from __future__ import division
import os
import zipfile
import cea.examples
import cea.config
import cea.inputlocator
# list the sections in the configuration file that are used by this script
# this value is used to generate the help menu for the command-line interface
CEA_CONFIG_SECTIONS = ['extract-reference-case']
def main(config):
"""
Extract the reference case in ``reference-case-open.zip`` to the destination folder.
:param config: Contains the PathParameter ``config.extract_reference_case.destination``
:type config: cea.config.Configuration
:return:
"""
reference_case = 'reference-case-{case}.zip'.format(case=config.extract_reference_case.case)
archive = zipfile.ZipFile(os.path.join(os.path.dirname(cea.examples.__file__), reference_case))
archive.extractall(config.extract_reference_case.destination)
if __name__ == '__main__':
main(cea.config.Configuration())
| 31.40625 | 99 | 0.758209 | from __future__ import division
import os
import zipfile
import cea.examples
import cea.config
import cea.inputlocator
CEA_CONFIG_SECTIONS = ['extract-reference-case']
def main(config):
reference_case = 'reference-case-{case}.zip'.format(case=config.extract_reference_case.case)
archive = zipfile.ZipFile(os.path.join(os.path.dirname(cea.examples.__file__), reference_case))
archive.extractall(config.extract_reference_case.destination)
if __name__ == '__main__':
main(cea.config.Configuration())
| true | true |
f72bb6f0058e6022c5654db644c4f3a8d1350c2a | 18,976 | py | Python | ssd/modeling/backbone/basic.py | Sethan/deeplearning-graphics | ce164847a323d3f07cfe241f4bbed6029777c58d | [
"MIT"
] | null | null | null | ssd/modeling/backbone/basic.py | Sethan/deeplearning-graphics | ce164847a323d3f07cfe241f4bbed6029777c58d | [
"MIT"
] | null | null | null | ssd/modeling/backbone/basic.py | Sethan/deeplearning-graphics | ce164847a323d3f07cfe241f4bbed6029777c58d | [
"MIT"
] | null | null | null | import torch
class BasicModel(torch.nn.Module):
"""
This is a basic backbone for SSD.
The feature extractor outputs a list of 6 feature maps, with the sizes:
[shape(-1, output_channels[0], 38, 38),
shape(-1, output_channels[1], 19, 19),
shape(-1, output_channels[2], 10, 10),
shape(-1, output_channels[3], 5, 5),
shape(-1, output_channels[3], 3, 3),
shape(-1, output_channels[4], 1, 1)]
where "output_channels" is the same as cfg.BACKBONE.OUT_CHANNELS
"""
def __init__(self, cfg):
super().__init__()
image_size = cfg.INPUT.IMAGE_SIZE
output_channels = cfg.MODEL.BACKBONE.OUT_CHANNELS
self.output_channels = output_channels
image_channels = cfg.MODEL.BACKBONE.INPUT_CHANNELS
self.output_feature_size = cfg.MODEL.PRIORS.FEATURE_MAPS
self.num_filters = [32,64]
self.feature_extractor38 = torch.nn.Sequential(
#part 1 38x38
torch.nn.Conv2d(
in_channels=image_channels,
out_channels=self.num_filters[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[0]),
torch.nn.MaxPool2d(2, stride=2),
torch.nn.ELU(),
torch.nn.Dropout2d(0.05),
torch.nn.Conv2d(
in_channels=self.num_filters[0],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.06),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.07),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.08),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.09),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.01),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.MaxPool2d(2, stride=2),
torch.nn.ELU(),
torch.nn.Dropout2d(0.11),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.12),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.13),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.14),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.output_channels[0],
kernel_size=3,
stride=2,
padding=1
)
)
self.feature_extractor19 = torch.nn.Sequential(
#part 2 19x19
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.15),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.16),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.17),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.18),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.19),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.2),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.21),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.22),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[1],
kernel_size=3,
stride=2,
padding=1
))
self.feature_extractor9 = torch.nn.Sequential(
#part 3 10x10
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.23),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.24),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.25),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.26),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.27),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.28),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.29),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.30),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[2],
kernel_size=3,
stride=2,
padding=1
))
self.feature_extractor5 = torch.nn.Sequential(
#part 4 5x5
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.31),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.32),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.33),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.34),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.35),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.36),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.37),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.38),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[3],
kernel_size=3,
stride=2,
padding=1
))
self.feature_extractor3 = torch.nn.Sequential(
#part 5 3x3
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.39),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.40),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.ELU(),
torch.nn.Dropout2d(0.41),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.42),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.43),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.44),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.45),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.46),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[4],
kernel_size=3,
stride=2,
padding=1
))
self.feature_extractor1 = torch.nn.Sequential(
#part 6 1x1
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.48),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.49),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.50),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.51),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.52),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.53),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.54),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.55),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[5],
kernel_size=3,
stride=1,
padding=0
))
def forward(self, x):
"""
The forward functiom should output features with shape:
[shape(-1, output_channels[0], 38, 38),
shape(-1, output_channels[1], 19, 19),
shape(-1, output_channels[2], 10, 10),
shape(-1, output_channels[3], 5, 5),
shape(-1, output_channels[3], 3, 3),
shape(-1, output_channels[4], 1, 1)]
We have added assertion tests to check this, iteration through out_features,
where out_features[0] should have the shape:
shape(-1, output_channels[0], 38, 38),
"""
out_features = []
out = self.feature_extractor38(x)
out_features.append(out)
out = self.feature_extractor19(out)
out_features.append(out)
out = self.feature_extractor9(out)
out_features.append(out)
out = self.feature_extractor5(out)
out_features.append(out)
out = self.feature_extractor3(out)
out_features.append(out)
out = self.feature_extractor1(out)
out_features.append(out)
feature_list = [38,19,10,5,3,1]
for idx, feature in enumerate(out_features):
expected_shape = (self.output_channels[idx], feature_list[idx], feature_list[idx])
assert feature.shape[1:] == expected_shape, \
f"Expected shape: {expected_shape}, got: {feature.shape[1:]} at output IDX: {idx}"
return tuple(out_features)
| 32.108291 | 98 | 0.539155 | import torch
class BasicModel(torch.nn.Module):
def __init__(self, cfg):
super().__init__()
image_size = cfg.INPUT.IMAGE_SIZE
output_channels = cfg.MODEL.BACKBONE.OUT_CHANNELS
self.output_channels = output_channels
image_channels = cfg.MODEL.BACKBONE.INPUT_CHANNELS
self.output_feature_size = cfg.MODEL.PRIORS.FEATURE_MAPS
self.num_filters = [32,64]
self.feature_extractor38 = torch.nn.Sequential(
torch.nn.Conv2d(
in_channels=image_channels,
out_channels=self.num_filters[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[0]),
torch.nn.MaxPool2d(2, stride=2),
torch.nn.ELU(),
torch.nn.Dropout2d(0.05),
torch.nn.Conv2d(
in_channels=self.num_filters[0],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.06),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.07),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.08),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.09),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.01),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.MaxPool2d(2, stride=2),
torch.nn.ELU(),
torch.nn.Dropout2d(0.11),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.12),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.13),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.num_filters[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.num_filters[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.14),
torch.nn.Conv2d(
in_channels=self.num_filters[1],
out_channels=self.output_channels[0],
kernel_size=3,
stride=2,
padding=1
)
)
self.feature_extractor19 = torch.nn.Sequential(
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.15),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.16),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.17),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.18),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.19),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.2),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.21),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[0],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[0]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.22),
torch.nn.Conv2d(
in_channels=self.output_channels[0],
out_channels=self.output_channels[1],
kernel_size=3,
stride=2,
padding=1
))
self.feature_extractor9 = torch.nn.Sequential(
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.23),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.24),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.25),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.26),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.27),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.28),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.29),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[1],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[1]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.30),
torch.nn.Conv2d(
in_channels=self.output_channels[1],
out_channels=self.output_channels[2],
kernel_size=3,
stride=2,
padding=1
))
self.feature_extractor5 = torch.nn.Sequential(
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.31),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.32),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.33),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.34),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.35),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.36),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.37),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[2],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[2]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.38),
torch.nn.Conv2d(
in_channels=self.output_channels[2],
out_channels=self.output_channels[3],
kernel_size=3,
stride=2,
padding=1
))
self.feature_extractor3 = torch.nn.Sequential(
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.39),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.40),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.ELU(),
torch.nn.Dropout2d(0.41),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.42),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.43),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.44),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.45),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[3],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[3]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.46),
torch.nn.Conv2d(
in_channels=self.output_channels[3],
out_channels=self.output_channels[4],
kernel_size=3,
stride=2,
padding=1
))
self.feature_extractor1 = torch.nn.Sequential(
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.48),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.49),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.50),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.51),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.52),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.53),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.54),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[4],
kernel_size=3,
stride=1,
padding=1
),
torch.nn.BatchNorm2d(self.output_channels[4]),
torch.nn.ELU(),
torch.nn.Dropout2d(0.55),
torch.nn.Conv2d(
in_channels=self.output_channels[4],
out_channels=self.output_channels[5],
kernel_size=3,
stride=1,
padding=0
))
def forward(self, x):
out_features = []
out = self.feature_extractor38(x)
out_features.append(out)
out = self.feature_extractor19(out)
out_features.append(out)
out = self.feature_extractor9(out)
out_features.append(out)
out = self.feature_extractor5(out)
out_features.append(out)
out = self.feature_extractor3(out)
out_features.append(out)
out = self.feature_extractor1(out)
out_features.append(out)
feature_list = [38,19,10,5,3,1]
for idx, feature in enumerate(out_features):
expected_shape = (self.output_channels[idx], feature_list[idx], feature_list[idx])
assert feature.shape[1:] == expected_shape, \
f"Expected shape: {expected_shape}, got: {feature.shape[1:]} at output IDX: {idx}"
return tuple(out_features)
| true | true |
f72bb74728607daee649873c96466e293323f858 | 400 | py | Python | packages/pytea/pytest/unit_tests/passes/pass_argmax_dim01.py | lego0901/pytea | 8ede650def2e68f4610ba816451d8b9e28f09f76 | [
"MIT"
] | null | null | null | packages/pytea/pytest/unit_tests/passes/pass_argmax_dim01.py | lego0901/pytea | 8ede650def2e68f4610ba816451d8b9e28f09f76 | [
"MIT"
] | null | null | null | packages/pytea/pytest/unit_tests/passes/pass_argmax_dim01.py | lego0901/pytea | 8ede650def2e68f4610ba816451d8b9e28f09f76 | [
"MIT"
] | null | null | null | '''
pass_argmax_dim01.py
Copyright (c) Seoul National University
Licensed under the MIT license.
Author: Woo Sung Song
torch.Tensor.argmax with dim parameter.
! This is not available since maximum stack size exceeding error has been occured
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
a = torch.rand(2, 3)
#m = a.argmax(dim=1)
# shape assertion
#m + torch.rand(2, 4, 5) | 21.052632 | 81 | 0.75 |
import torch
import torch.nn as nn
import torch.nn.functional as F
a = torch.rand(2, 3)
| true | true |
f72bb761694ffb3a80f6774d7de879a210505611 | 5,192 | py | Python | backend/game.py | KatrichKostiantin/CheckersGame | 3a552335d3ce344b203129a230d64db303491bb2 | [
"MIT"
] | null | null | null | backend/game.py | KatrichKostiantin/CheckersGame | 3a552335d3ce344b203129a230d64db303491bb2 | [
"MIT"
] | null | null | null | backend/game.py | KatrichKostiantin/CheckersGame | 3a552335d3ce344b203129a230d64db303491bb2 | [
"MIT"
] | null | null | null | import asyncio
import datetime
import logging
import secrets
from main import game
class GameError(Exception):
pass
class ForbiddenMoveError(GameError):
pass
class MoveIsNotPossible(GameError):
pass
class Game:
def __init__(self):
self._game = game
self._is_started = False
self._is_finished = False
self._available_move_time = 2.2 # 200 ms plus, cause for network latency
self._available_current_move_time = self._available_move_time
self._players = {}
self._lost_time_player = None
self._last_move = None
self._colors_table = {
1: 'RED',
2: 'BLACK',
None: 'None'
}
def _whose_turn(self):
return self._colors_table[self._game.whose_turn()]
def _status(self):
if not self._is_started:
return 'Not yet started'
if self._lost_time_player:
return f'Player {self._colors_table[self._lost_time_player]} reached time limit'
return 'Game is over' if self._game.is_over() else 'Game is playing'
def _winner(self):
if self._lost_time_player:
return self._colors_table[1] \
if self._lost_time_player == 2 \
else self._colors_table[2]
return self._colors_table[self._game.get_winner()] if self._game.get_winner() else None
def _board(self):
output = []
for piece in self._game.board.pieces:
if not piece.captured:
output.append({
'color': 'RED' if piece.player == 1 else 'BLACK',
'row': piece.get_row(),
'column': piece.get_column(),
'king': piece.king,
'position': piece.position
})
return output
def add_player(self, team_name):
if self._is_started:
return
player_num = 2 if 1 in self._players else 1
token = secrets.token_hex(16)
self._players[player_num] = {
'token': token,
'team_name': team_name
}
if 1 in self._players and 2 in self._players:
asyncio.ensure_future(self.start())
return {
'color': self._colors_table[player_num],
'token': token
}
async def start(self):
logging.info(f'...GAME IS STARTED at {datetime.datetime.now().isoformat()}...')
logging.info(
f'1 player, color: {self._colors_table[1]}, team name: {self._players[1]["team_name"]}'
)
logging.info(
f'2 player, color: {self._colors_table[2]}, team name: {self._players[2]["team_name"]}'
)
self._is_started = True
while True:
logging.info(
f'Available time for player "{self._colors_table[self._game.whose_turn()]}" '
f'move: {self._available_current_move_time}'
)
await asyncio.sleep(0.05)
self._available_current_move_time -= 0.05
if self._available_current_move_time < 0:
self._lost_time_player = self._game.whose_turn()
self._is_finished = True
break
if self._game.is_over():
self._is_finished = True
break
if self._lost_time_player == 1:
winner = 2
elif self._lost_time_player == 2:
winner = 1
else:
winner = self._game.get_winner()
self._game.set_winner({
'color': self._colors_table[winner],
'team_name': self._players[winner]['team_name']
})
logging.info(
f'...GAME WAS FINISHED at {datetime.datetime.now().isoformat()}, winner: {self._game.get_board_winner()}'
)
def move(self, token, move):
player = self._players[self._game.whose_turn()]
if player['token'] != token:
raise ForbiddenMoveError
try:
if self._last_move is not None and self._last_move['player'] == self._whose_turn():
self._last_move['last_moves'].append(move)
else:
self._last_move = {
'player': self._whose_turn(),
'last_moves': [move]
}
self._game.move(move)
logging.info(
f'{player["team_name"]} made move ({move}) at {datetime.datetime.now().isoformat()}'
)
self._available_current_move_time = self._available_move_time
except ValueError as e:
raise MoveIsNotPossible(str(e))
def is_started(self):
return self._is_started
def is_finished(self):
return self._is_finished
@property
def json(self):
return {
'status': self._status(),
'whose_turn': self._whose_turn(),
'winner': self._winner(),
'board': self._board(),
'available_time': self._available_current_move_time,
'last_move': self._last_move,
'is_started': self.is_started(),
'is_finished': self.is_finished()
}
| 30.011561 | 117 | 0.55624 | import asyncio
import datetime
import logging
import secrets
from main import game
class GameError(Exception):
pass
class ForbiddenMoveError(GameError):
pass
class MoveIsNotPossible(GameError):
pass
class Game:
def __init__(self):
self._game = game
self._is_started = False
self._is_finished = False
self._available_move_time = 2.2
self._available_current_move_time = self._available_move_time
self._players = {}
self._lost_time_player = None
self._last_move = None
self._colors_table = {
1: 'RED',
2: 'BLACK',
None: 'None'
}
def _whose_turn(self):
return self._colors_table[self._game.whose_turn()]
def _status(self):
if not self._is_started:
return 'Not yet started'
if self._lost_time_player:
return f'Player {self._colors_table[self._lost_time_player]} reached time limit'
return 'Game is over' if self._game.is_over() else 'Game is playing'
def _winner(self):
if self._lost_time_player:
return self._colors_table[1] \
if self._lost_time_player == 2 \
else self._colors_table[2]
return self._colors_table[self._game.get_winner()] if self._game.get_winner() else None
def _board(self):
output = []
for piece in self._game.board.pieces:
if not piece.captured:
output.append({
'color': 'RED' if piece.player == 1 else 'BLACK',
'row': piece.get_row(),
'column': piece.get_column(),
'king': piece.king,
'position': piece.position
})
return output
def add_player(self, team_name):
if self._is_started:
return
player_num = 2 if 1 in self._players else 1
token = secrets.token_hex(16)
self._players[player_num] = {
'token': token,
'team_name': team_name
}
if 1 in self._players and 2 in self._players:
asyncio.ensure_future(self.start())
return {
'color': self._colors_table[player_num],
'token': token
}
async def start(self):
logging.info(f'...GAME IS STARTED at {datetime.datetime.now().isoformat()}...')
logging.info(
f'1 player, color: {self._colors_table[1]}, team name: {self._players[1]["team_name"]}'
)
logging.info(
f'2 player, color: {self._colors_table[2]}, team name: {self._players[2]["team_name"]}'
)
self._is_started = True
while True:
logging.info(
f'Available time for player "{self._colors_table[self._game.whose_turn()]}" '
f'move: {self._available_current_move_time}'
)
await asyncio.sleep(0.05)
self._available_current_move_time -= 0.05
if self._available_current_move_time < 0:
self._lost_time_player = self._game.whose_turn()
self._is_finished = True
break
if self._game.is_over():
self._is_finished = True
break
if self._lost_time_player == 1:
winner = 2
elif self._lost_time_player == 2:
winner = 1
else:
winner = self._game.get_winner()
self._game.set_winner({
'color': self._colors_table[winner],
'team_name': self._players[winner]['team_name']
})
logging.info(
f'...GAME WAS FINISHED at {datetime.datetime.now().isoformat()}, winner: {self._game.get_board_winner()}'
)
def move(self, token, move):
player = self._players[self._game.whose_turn()]
if player['token'] != token:
raise ForbiddenMoveError
try:
if self._last_move is not None and self._last_move['player'] == self._whose_turn():
self._last_move['last_moves'].append(move)
else:
self._last_move = {
'player': self._whose_turn(),
'last_moves': [move]
}
self._game.move(move)
logging.info(
f'{player["team_name"]} made move ({move}) at {datetime.datetime.now().isoformat()}'
)
self._available_current_move_time = self._available_move_time
except ValueError as e:
raise MoveIsNotPossible(str(e))
def is_started(self):
return self._is_started
def is_finished(self):
return self._is_finished
@property
def json(self):
return {
'status': self._status(),
'whose_turn': self._whose_turn(),
'winner': self._winner(),
'board': self._board(),
'available_time': self._available_current_move_time,
'last_move': self._last_move,
'is_started': self.is_started(),
'is_finished': self.is_finished()
}
| true | true |
f72bb7c009ac666bf6b4d3d4ca6e8865981ed9cf | 3,079 | py | Python | model/app/LearnTfidfCNB.py | jgharris7/DocClass | 9ef62e655272cca8374187040eb3dd73f3f82b72 | [
"MIT"
] | null | null | null | model/app/LearnTfidfCNB.py | jgharris7/DocClass | 9ef62e655272cca8374187040eb3dd73f3f82b72 | [
"MIT"
] | null | null | null | model/app/LearnTfidfCNB.py | jgharris7/DocClass | 9ef62e655272cca8374187040eb3dd73f3f82b72 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 22:43:22 2021
@author: jgharris
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 21:09:34 2021
@author: jgharris
"""
root='C:/Users/jgharris/DocClass/'
dataFile='/data/shuffled-full-set-hashed.csv'
import statistics as stat
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pickle
from DocClfTfidfCNB import DocClfTfidfCNB
from Documents import Documents
#dataFile='/test/testshort.csv'
modelName="nbtfidfv0"
maxlines=80000000
testsize=.3
random_state=45
MAXSTRINGLENGH=4000
FIRSTSTRINGLENGTH=80
conf_mat=[]
def main():
# Set up corpus for training
corpus=Documents()
corpus.readFromFile(root+dataFile,maxline=maxlines)
'''
model1=DocClfComplNB(maxStringLength=MAXSTRINGLENGH, \
firstStringLength=FIRSTSTRINGLENGTH)
'''
model1=DocClfTfidfCNB(maxStringLength=MAXSTRINGLENGH, \
firstStringLength=FIRSTSTRINGLENGTH)
print()
# split into test and training sets
xtrain,xtest,ytrain,ytest=\
train_test_split(corpus.words,corpus.y,test_size=testsize, \
random_state=random_state)
ytrainpred=model1.fit(xtrain,ytrain)
ytestpred=model1.predict(xtest)
trainAccuracy=accuracy_score(ytrain,ytrainpred)
testAccuracy=accuracy_score(ytest,ytestpred)
controlAccuracy=accuracy_score(np.random.permutation(ytest),ytestpred)
global conf_mat
conf_mat =model1.confidence(ytest, ytestpred)
print(model1.confidence)
print()
print( np.unique(ytestpred,return_counts=True))
print()
[print("%-20s" % key +" %5.3f" % value) for key,value in model1.confidence.items()]
for row in range(0,conf_mat.shape[0]):
print( [" %4d" % conf_mat[row,col] for col in range(0,conf_mat.shape[1])])
rowsum=conf_mat.sum(axis=0)
colsum=conf_mat.sum(axis=1)
labels=[]
[labels.append(key) for key in model1.confidence.keys()]
print("item rowsum colsum")
for ic in range(0,conf_mat.shape[0]):
print("%-25s" % labels[ic] + " %5d" % rowsum[ic]+ " %5d" % colsum[ic])
print("")
print('train=%6.2f test=%6.2f control=%6.2f' %
(trainAccuracy,testAccuracy,controlAccuracy))
# compute accuracy given predicted value
pickle.dump(model1,open(root+modelName+".pckmdl","wb"))
print(ytestpred[0])
print(xtest[0][0:20])
testfile=open(root+modelName+"testdata.txt","wt")
testfile.write(ytestpred[0])
testfile.write("\n")
testfile.write(xtest[0])
testfile.write("\n")
testfile.write(ytestpred[10])
testfile.write("\n")
testfile.write(xtest[10])
testfile.write("\n")
testfile.close()
print( model1.message)
if __name__=='__main__':
main()
| 27.008772 | 88 | 0.642416 |
root='C:/Users/jgharris/DocClass/'
dataFile='/data/shuffled-full-set-hashed.csv'
import statistics as stat
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pickle
from DocClfTfidfCNB import DocClfTfidfCNB
from Documents import Documents
modelName="nbtfidfv0"
maxlines=80000000
testsize=.3
random_state=45
MAXSTRINGLENGH=4000
FIRSTSTRINGLENGTH=80
conf_mat=[]
def main():
corpus=Documents()
corpus.readFromFile(root+dataFile,maxline=maxlines)
model1=DocClfTfidfCNB(maxStringLength=MAXSTRINGLENGH, \
firstStringLength=FIRSTSTRINGLENGTH)
print()
xtrain,xtest,ytrain,ytest=\
train_test_split(corpus.words,corpus.y,test_size=testsize, \
random_state=random_state)
ytrainpred=model1.fit(xtrain,ytrain)
ytestpred=model1.predict(xtest)
trainAccuracy=accuracy_score(ytrain,ytrainpred)
testAccuracy=accuracy_score(ytest,ytestpred)
controlAccuracy=accuracy_score(np.random.permutation(ytest),ytestpred)
global conf_mat
conf_mat =model1.confidence(ytest, ytestpred)
print(model1.confidence)
print()
print( np.unique(ytestpred,return_counts=True))
print()
[print("%-20s" % key +" %5.3f" % value) for key,value in model1.confidence.items()]
for row in range(0,conf_mat.shape[0]):
print( [" %4d" % conf_mat[row,col] for col in range(0,conf_mat.shape[1])])
rowsum=conf_mat.sum(axis=0)
colsum=conf_mat.sum(axis=1)
labels=[]
[labels.append(key) for key in model1.confidence.keys()]
print("item rowsum colsum")
for ic in range(0,conf_mat.shape[0]):
print("%-25s" % labels[ic] + " %5d" % rowsum[ic]+ " %5d" % colsum[ic])
print("")
print('train=%6.2f test=%6.2f control=%6.2f' %
(trainAccuracy,testAccuracy,controlAccuracy))
pickle.dump(model1,open(root+modelName+".pckmdl","wb"))
print(ytestpred[0])
print(xtest[0][0:20])
testfile=open(root+modelName+"testdata.txt","wt")
testfile.write(ytestpred[0])
testfile.write("\n")
testfile.write(xtest[0])
testfile.write("\n")
testfile.write(ytestpred[10])
testfile.write("\n")
testfile.write(xtest[10])
testfile.write("\n")
testfile.close()
print( model1.message)
if __name__=='__main__':
main()
| true | true |
f72bb7e51487a16740709aa74b453a9e4b4dfec5 | 1,107 | py | Python | sortByWeather.py | LeahGabrielle/Clothes | 72a829358ad6a60aef26b7fce80d854451124a32 | [
"Apache-2.0"
] | null | null | null | sortByWeather.py | LeahGabrielle/Clothes | 72a829358ad6a60aef26b7fce80d854451124a32 | [
"Apache-2.0"
] | null | null | null | sortByWeather.py | LeahGabrielle/Clothes | 72a829358ad6a60aef26b7fce80d854451124a32 | [
"Apache-2.0"
] | null | null | null | #clothes by weather
import random
def pickTop(clothesList):
return random.choice(clothesList[0])
def pickBottoms(clothesList):
return random.choice(clothesList[1])
#sorts clothes into weather type and returns a list of clothes of the correct weather
def sortWeather(clothesList, weather):
#eventually combine the two loops
'''
for i in range(0,len(clothesList)):
for j in range(0, len(clothesList[i]):
'''
#change to switch later
#go through tops
i=0
for top in clothesList[0]:
if top[2] != weather:
clothesList[0].pop(i)
i+=1
#go through bottoms
i=0
for bottom in clothesList[1]:
if bottom[2] != weather:
clothesList[1].pop(i)
i+=1
return clothesList
#Asks user for their weather choice
def requestWeather(clothesList):
weather = input("Is the weather hot or cold?\n")
clothesList = sortWeather(clothesList, weather)
finalChoice = []
finalChoice.append(pickTop(clothesList))
finalChoice.append(pickBottoms(clothesList))
return finalChoice
| 27 | 85 | 0.65673 |
import random
def pickTop(clothesList):
return random.choice(clothesList[0])
def pickBottoms(clothesList):
return random.choice(clothesList[1])
def sortWeather(clothesList, weather):
i=0
for top in clothesList[0]:
if top[2] != weather:
clothesList[0].pop(i)
i+=1
i=0
for bottom in clothesList[1]:
if bottom[2] != weather:
clothesList[1].pop(i)
i+=1
return clothesList
def requestWeather(clothesList):
weather = input("Is the weather hot or cold?\n")
clothesList = sortWeather(clothesList, weather)
finalChoice = []
finalChoice.append(pickTop(clothesList))
finalChoice.append(pickBottoms(clothesList))
return finalChoice
| true | true |
f72bb87a2474ba7c90c9d75c1d943aae0014a860 | 403 | py | Python | core/mixon_core.py | onuratakan/MIXON | 74d8b1fc7ec2e84dbe4e29f411ae09d701838579 | [
"MIT"
] | 14 | 2021-01-22T20:39:43.000Z | 2022-02-20T00:30:41.000Z | core/mixon_core.py | onuratakan/MIXON | 74d8b1fc7ec2e84dbe4e29f411ae09d701838579 | [
"MIT"
] | null | null | null | core/mixon_core.py | onuratakan/MIXON | 74d8b1fc7ec2e84dbe4e29f411ae09d701838579 | [
"MIT"
] | 3 | 2021-03-20T00:02:24.000Z | 2021-03-22T07:36:49.000Z |
import sys
import os
def start_tojas():
os.system("cd tojas && python3 tojas.py -nb && cd ..")
def start_tojas_gui():
os.system("python3 lib/tojas_gui.py -nb")
def start_scanizen():
os.system("cd scanizen && python3 scanizen.py -nb && cd ..")
def start_doser():
os.system("cd doser && python3 doser.py -nb && cd ..")
def start_routersploit():
os.system("python3 routersploit/rsf.py")
| 16.791667 | 62 | 0.667494 |
import sys
import os
def start_tojas():
os.system("cd tojas && python3 tojas.py -nb && cd ..")
def start_tojas_gui():
os.system("python3 lib/tojas_gui.py -nb")
def start_scanizen():
os.system("cd scanizen && python3 scanizen.py -nb && cd ..")
def start_doser():
os.system("cd doser && python3 doser.py -nb && cd ..")
def start_routersploit():
os.system("python3 routersploit/rsf.py")
| true | true |
f72bb9cc461f8b012834228510d2ae37ee6fc7a0 | 2,184 | py | Python | p130_surrounded_regions.py | feigaochn/leetcode | abf0877fae02aa9c2549051f0b68df0ace952512 | [
"MIT"
] | null | null | null | p130_surrounded_regions.py | feigaochn/leetcode | abf0877fae02aa9c2549051f0b68df0ace952512 | [
"MIT"
] | null | null | null | p130_surrounded_regions.py | feigaochn/leetcode | abf0877fae02aa9c2549051f0b68df0ace952512 | [
"MIT"
] | null | null | null | # Surrounded Regions
# Total Accepted: 7716 Total Submissions: 56446 My Submissions
#
# Given a 2D board containing 'X' and 'O', capture all regions surrounded by
# 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded
# region.
#
# For example,
# X X X X
# X O O X
# X X O X
# X O X X
#
# After running your function, the board should be:
# X X X X
# X X X X
# X X X X
# X O X X
class Solution:
# @param board, a 2D array
# Capture all regions by modifying the input board in-place.
# Do not return any value.
def solve(self, board):
if len(board) is 0:
return
q = []
# first row
for j in range(len(board[0])):
if board[0][j] is 'O':
q.append((0, j))
board[0][j] = 'o'
# last row
for j in range(len(board[-1])):
if board[len(board)-1][j] is 'O':
q.append((len(board)-1, j))
board[len(board)-1][j] = 'o'
for i in range(len(board)):
n = len(board[i])
if n > 0:
# first column
if board[i][0] is 'O':
board[i][0] = 'o'
q.append((i, 0))
# last column
if board[i][n-1] is 'O':
board[i][n-1] = 'o'
q.append((i, n-1))
while len(q) > 0:
i, j = q.pop(0)
for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
if 0 <= i+di < len(board) and 0 <= j+dj < len(board[i+di]) \
and board[i+di][j+dj] is 'O':
board[i+di][j+dj] = 'o'
q.append((i+di, j+dj))
for row in board:
for j in range(len(row)):
if row[j] is 'o':
row[j] = 'O'
elif row[j] is 'O':
row[j] = 'X'
if __name__ == '__main__':
board = [['X', 'X', 'X', 'X'],
['X', 'O', 'O', 'X'],
['X', 'X', 'O', 'X'],
['X', 'O', 'X', 'X']]
Solution().solve(board)
print(board)
board = []
Solution().solve(board)
print(board)
| 28.736842 | 77 | 0.422619 |
class Solution:
def solve(self, board):
if len(board) is 0:
return
q = []
for j in range(len(board[0])):
if board[0][j] is 'O':
q.append((0, j))
board[0][j] = 'o'
for j in range(len(board[-1])):
if board[len(board)-1][j] is 'O':
q.append((len(board)-1, j))
board[len(board)-1][j] = 'o'
for i in range(len(board)):
n = len(board[i])
if n > 0:
if board[i][0] is 'O':
board[i][0] = 'o'
q.append((i, 0))
if board[i][n-1] is 'O':
board[i][n-1] = 'o'
q.append((i, n-1))
while len(q) > 0:
i, j = q.pop(0)
for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
if 0 <= i+di < len(board) and 0 <= j+dj < len(board[i+di]) \
and board[i+di][j+dj] is 'O':
board[i+di][j+dj] = 'o'
q.append((i+di, j+dj))
for row in board:
for j in range(len(row)):
if row[j] is 'o':
row[j] = 'O'
elif row[j] is 'O':
row[j] = 'X'
if __name__ == '__main__':
board = [['X', 'X', 'X', 'X'],
['X', 'O', 'O', 'X'],
['X', 'X', 'O', 'X'],
['X', 'O', 'X', 'X']]
Solution().solve(board)
print(board)
board = []
Solution().solve(board)
print(board)
| true | true |
f72bb9ed94ed86bf9e276452065cfabb93084887 | 647 | py | Python | 4.py | Michanix/Math-Stat-Homework | 18f4f915ea0f2dd7fa14ebaeb0d357510aef4808 | [
"MIT"
] | null | null | null | 4.py | Michanix/Math-Stat-Homework | 18f4f915ea0f2dd7fa14ebaeb0d357510aef4808 | [
"MIT"
] | null | null | null | 4.py | Michanix/Math-Stat-Homework | 18f4f915ea0f2dd7fa14ebaeb0d357510aef4808 | [
"MIT"
] | null | null | null | from math import sqrt
from random import randrange
arr1 = [i for i in range(1, 11)]
arr2 = [i for i in range(1, 11)]
arr3 = [randrange(i) for i in range(1, 11)]
arr4 = [randrange(i) for i in range(1, 11)]
def avg(data):
return sum(data) / len(data)
def std(data):
mu = avg(data)
std = (sum([(i - mu)**2 for i in data]) / len(data))**0.5
return std
def koef_pirsona(x, y):
# x,y - list of values
avg_x = avg(x)
avg_y = avg(y)
std_x = std(x)
std_y = std(y)
avg_xy = avg([i*j for i,j in zip(x,y)])
result = (avg_xy - avg_x * avg_y) / (std_x * std_y)
return result
print(koef_pirsona(arr3, arr4))
| 22.310345 | 61 | 0.591963 | from math import sqrt
from random import randrange
arr1 = [i for i in range(1, 11)]
arr2 = [i for i in range(1, 11)]
arr3 = [randrange(i) for i in range(1, 11)]
arr4 = [randrange(i) for i in range(1, 11)]
def avg(data):
return sum(data) / len(data)
def std(data):
mu = avg(data)
std = (sum([(i - mu)**2 for i in data]) / len(data))**0.5
return std
def koef_pirsona(x, y):
avg_x = avg(x)
avg_y = avg(y)
std_x = std(x)
std_y = std(y)
avg_xy = avg([i*j for i,j in zip(x,y)])
result = (avg_xy - avg_x * avg_y) / (std_x * std_y)
return result
print(koef_pirsona(arr3, arr4))
| true | true |
f72bba260dbdc0d48d601f070334e34f0095da0b | 6,016 | py | Python | scripts/gdc_req_legacy.py | dampierch/herv | 9f1ce0e676977b6c8d25fdf446c0807826b80bea | [
"MIT"
] | null | null | null | scripts/gdc_req_legacy.py | dampierch/herv | 9f1ce0e676977b6c8d25fdf446c0807826b80bea | [
"MIT"
] | null | null | null | scripts/gdc_req_legacy.py | dampierch/herv | 9f1ce0e676977b6c8d25fdf446c0807826b80bea | [
"MIT"
] | null | null | null | '''
this script queries the gdc legacy archive via the search and retrieve api and
returns msi_status object (from files endpoint on legacy)
-- get uuids of xml files with the msi annotations from legacy server
-- download each xml file
-- parse xml files to extract msi annotations for each subject
script should be called from within gdc_ann_make, which itself should be called
as part of snakemake pipeline
-- usage: snakemake setup_tcga
'''
import io
import json
import os
import pandas as pd
import requests
import re
import subprocess
import glob
import xml.etree.ElementTree as ET
modname = 'gdc_req_legacy'
def set_filters():
'''
set filters for gdc legacy files endpoint search
-- json format
-- for files.data_type, values for MSI status are 'Auxiliary test' and
'Microsatellite instability'
-- here use 'Auxiliary test' per TCGAbiolinks examples
'''
filters = {
'op':'and',
'content':[
{'op':'or',
'content':[
{'op':'in',
'content':{
'field':'cases.project.project_id',
'value':'TCGA-COAD'
}
},
{'op':'in',
'content':{
'field':'cases.project.project_id',
'value':'TCGA-READ'
}
}
]
},
{'op':'and',
'content':[
{'op':'in',
'content':{
'field':'files.data_category',
'value':'Other'
}
},
{'op':'in',
'content':{
'field':'files.data_type',
'value':'Auxiliary test'
}
},
{'op':'in',
'content':{
'field':'files.access',
'value':'open'
}
}
]
}
]
}
filters = json.dumps(filters)
return filters
def set_fields():
'''
set fields for extraction from endpoint
'''
fields = [
'file_name',
'file_id',
'md5sum',
'file_size',
'state'
]
fields = ','.join(fields)
return fields
def set_params(filters,fields):
'''
set parameters for https get request to endpoint
-- set size parameter empirically to a level greater than number of target
cases to get all records at once
'''
params = {
'filters': filters,
'fields': fields,
'format': 'TSV',
'size': '1500'
}
return params
def get_results(endpoint,params):
'''
given an endpoint and parameters, execute https GET request for xml file_id
entities and build results dataframe with msi results
'''
response = requests.get(endpoint, params=params)
object = io.StringIO(response.content.decode('utf-8'))
results = pd.read_table(object)
return results
def download_xml_uuid(files_res,dest):
'''
download xml files one at a time by uuid
'''
file_count = 0
for uuid in files_res.id:
cmd = ' '.join(['gdc-client download',uuid,'-d',dest])
subprocess.call(cmd, shell=True)
print(' '.join([uuid,'downloaded']))
file_count = file_count + 1
print(' '.join([str(file_count),'files downloaded']))
def download_xml_manifest(files_res,dest):
'''
-- create manifest object
-- write manifest to file
-- use manifest for bulk download
'''
select = ['file_id', 'file_name', 'md5sum', 'file_size', 'state']
manifest = files_res[select]
manifest.columns = ['id', 'filename', 'md5', 'size', 'state']
manifest = manifest.sort_values(by=['id'])
out_file = dest + 'manifest.tsv'
manifest.to_csv(out_file, sep='\t', index=False)
cmd = ' '.join(['gdc-client download','-m',out_file,'-d',dest])
subprocess.call(cmd, shell=True)
print('manifest downloaded')
def parse_xml(files_res,dest):
'''
parse xml files to extract msi status
'''
msi_dict = {}
msi_dict['subject_id'] = []
msi_dict['msi_status'] = []
tag1 = 'mononucleotide_and_dinucleotide_marker_panel_analysis_status'
tag2 = 'mononucleotide_marker_panel_analysis_status'
file_count = 0
for uuid in files_res.id:
pattern = dest + uuid + '/*.xml'
fn = glob.glob(pattern)[0]
tree = ET.parse(fn)
for elem in tree.getiterator():
if 'bcr_patient_barcode' in elem.tag:
subject_id = elem.text
if tag1 in elem.tag and elem.text != None:
msi_status = elem.text
elif tag2 in elem.tag and elem.text != None:
msi_status = elem.text
msi_dict['subject_id'].append(subject_id)
msi_dict['msi_status'].append(msi_status)
file_count = file_count + 1
print(' '.join([str(file_count),'files parsed']))
msi_res = pd.DataFrame.from_dict(msi_dict)
return msi_res
def check_outpath(out_path):
'''
check for presence of absence of out_path and make directory if absent
'''
l = out_path.strip('/').split('/')
d = ''
for e in l:
d = d + '/' + e
if os.path.exists(d):
print(d,'present')
else:
print(d,'absent')
print('making',d,'now')
os.mkdir(d)
def main():
endpoint = 'https://api.gdc.cancer.gov/legacy/files/'
filters = set_filters()
fields = set_fields()
params = set_params(filters, fields)
files_res = get_results(endpoint, params)
dest = os.environ['ann_dir'] + 'tcga/msi/'
check_outpath(dest)
download_xml_manifest(files_res, dest)
msi_res = parse_xml(files_res, dest)
return msi_res
if __name__ == '__main__':
print('This script is not meant to be run as main. See usage statment:')
print('usage: snakemake setup_tcga')
else:
msi_res = main()
| 27.723502 | 79 | 0.562001 |
import io
import json
import os
import pandas as pd
import requests
import re
import subprocess
import glob
import xml.etree.ElementTree as ET
modname = 'gdc_req_legacy'
def set_filters():
filters = {
'op':'and',
'content':[
{'op':'or',
'content':[
{'op':'in',
'content':{
'field':'cases.project.project_id',
'value':'TCGA-COAD'
}
},
{'op':'in',
'content':{
'field':'cases.project.project_id',
'value':'TCGA-READ'
}
}
]
},
{'op':'and',
'content':[
{'op':'in',
'content':{
'field':'files.data_category',
'value':'Other'
}
},
{'op':'in',
'content':{
'field':'files.data_type',
'value':'Auxiliary test'
}
},
{'op':'in',
'content':{
'field':'files.access',
'value':'open'
}
}
]
}
]
}
filters = json.dumps(filters)
return filters
def set_fields():
fields = [
'file_name',
'file_id',
'md5sum',
'file_size',
'state'
]
fields = ','.join(fields)
return fields
def set_params(filters,fields):
params = {
'filters': filters,
'fields': fields,
'format': 'TSV',
'size': '1500'
}
return params
def get_results(endpoint,params):
response = requests.get(endpoint, params=params)
object = io.StringIO(response.content.decode('utf-8'))
results = pd.read_table(object)
return results
def download_xml_uuid(files_res,dest):
file_count = 0
for uuid in files_res.id:
cmd = ' '.join(['gdc-client download',uuid,'-d',dest])
subprocess.call(cmd, shell=True)
print(' '.join([uuid,'downloaded']))
file_count = file_count + 1
print(' '.join([str(file_count),'files downloaded']))
def download_xml_manifest(files_res,dest):
select = ['file_id', 'file_name', 'md5sum', 'file_size', 'state']
manifest = files_res[select]
manifest.columns = ['id', 'filename', 'md5', 'size', 'state']
manifest = manifest.sort_values(by=['id'])
out_file = dest + 'manifest.tsv'
manifest.to_csv(out_file, sep='\t', index=False)
cmd = ' '.join(['gdc-client download','-m',out_file,'-d',dest])
subprocess.call(cmd, shell=True)
print('manifest downloaded')
def parse_xml(files_res,dest):
msi_dict = {}
msi_dict['subject_id'] = []
msi_dict['msi_status'] = []
tag1 = 'mononucleotide_and_dinucleotide_marker_panel_analysis_status'
tag2 = 'mononucleotide_marker_panel_analysis_status'
file_count = 0
for uuid in files_res.id:
pattern = dest + uuid + '/*.xml'
fn = glob.glob(pattern)[0]
tree = ET.parse(fn)
for elem in tree.getiterator():
if 'bcr_patient_barcode' in elem.tag:
subject_id = elem.text
if tag1 in elem.tag and elem.text != None:
msi_status = elem.text
elif tag2 in elem.tag and elem.text != None:
msi_status = elem.text
msi_dict['subject_id'].append(subject_id)
msi_dict['msi_status'].append(msi_status)
file_count = file_count + 1
print(' '.join([str(file_count),'files parsed']))
msi_res = pd.DataFrame.from_dict(msi_dict)
return msi_res
def check_outpath(out_path):
l = out_path.strip('/').split('/')
d = ''
for e in l:
d = d + '/' + e
if os.path.exists(d):
print(d,'present')
else:
print(d,'absent')
print('making',d,'now')
os.mkdir(d)
def main():
endpoint = 'https://api.gdc.cancer.gov/legacy/files/'
filters = set_filters()
fields = set_fields()
params = set_params(filters, fields)
files_res = get_results(endpoint, params)
dest = os.environ['ann_dir'] + 'tcga/msi/'
check_outpath(dest)
download_xml_manifest(files_res, dest)
msi_res = parse_xml(files_res, dest)
return msi_res
if __name__ == '__main__':
print('This script is not meant to be run as main. See usage statment:')
print('usage: snakemake setup_tcga')
else:
msi_res = main()
| true | true |
f72bba363e60dcda05c1e3254d05eaf5e83fbdac | 10,188 | py | Python | esse3api/esse3api.py | hpsc-smartlab/esse3api | 416c52149f28c886cab72671b20b209b40857edf | [
"MIT"
] | 2 | 2018-04-04T15:56:40.000Z | 2018-05-23T11:46:06.000Z | esse3api/esse3api.py | hpsc-smartlab/esse3api | 416c52149f28c886cab72671b20b209b40857edf | [
"MIT"
] | null | null | null | esse3api/esse3api.py | hpsc-smartlab/esse3api | 416c52149f28c886cab72671b20b209b40857edf | [
"MIT"
] | null | null | null |
import json, sys, re, urllib, urllib2, socket, json, pydoc, cgi, os, time, inspect
from hashlib import md5
from datetime import datetime
import time
import csv
from scraper import Scraper
from flask import Flask
from flask import Response
from flask import request
from flask import jsonify
from flask import current_app
from flask import make_response
from flask import session
from flask import url_for
from flask import redirect
from flask import render_template
from flask import abort
from flask import g
from flask import flash
from flask import _app_ctx_stack
from flask_restplus import Resource, Api
from flask_restplus import fields
from functools import wraps
from functools import update_wrapper
import logging
import traceback
log = logging.getLogger(__name__)
app = Flask(__name__)
api = Api(app)
app.config.from_object(__name__) # load config from this file , esse3api.py
# Load default config and override config from an environment variable
app.config.update(dict(
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default'
))
app.config.from_envvar('ESSE3API_SETTINGS', silent=True)
@api.errorhandler
def default_error_handler(e):
message = 'An unhandled exception occurred.'
log.exception(message)
if not settings.FLASK_DEBUG:
return {'message': message}, 500
#### CROSSDOMAIN DECORATOR ####
def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
h['Access-Control-Allow-Credentials'] = 'true'
h['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept, Authorization"
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
#### JSONP DECORATOR ####
def jsonp(func):
""" Wrap json as jsonp """
@wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callback:
data = str(func(*args, **kwargs).data)
content = str(callback) + '(' + data + ')'
mimetype = 'application/javascript'
return current_app.response_class(content, mimetype=mimetype)
else:
return func(*args, **kwargs)
return decorated_function
parser = api.parser()
parser.add_argument('username', help='The username', location='form')
parser.add_argument('password', help='The passowrd', location='form')
@api.route('/dati_anagrafici')
class DatiAnagrafici(Resource):
@api.doc(parser=parser)
def post(self):
"""Recuper i dati anagrafici
:param: username: Nome utente
:param: password: Password
:example: /dati_anagrafici
:returns: json -- I dati personali
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
log.info(username)
s = Scraper(username, password)
return jsonify(s.dati_anagrafici())
@api.route('/login')
class Login(Resource):
@api.doc(parser=parser)
def post(self):
"""Permette il login al portale esse3
:param: username: Nome utente
:param: password: Password
:example: /login
:returns: json -- Risultato del login
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.login())
@api.route('/riepilogo_esami')
class RiepilogoEsami(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce il riepilogo degli esami effettuati dallo studente
:param: username: Nome utente
:param: password: Password
:example: /riepilogo_esami
:returns: json -- Lista degli esami sostenuti
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.riepilogo_esami())
@api.route('/residenza')
class Residenza(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce la residenza dello studente
:param: username: Nome utente
:param: password: Password
:example: /residenza
:returns: json -- Residenza dello studente
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.residenza())
@api.route('/domicilio')
class Domicilio(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce il domicilio dello studente
:param: username: Nome utente
:param: password: Password
:example: /domicilio
:returns: json -- Domicilio dello studente
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.domicilio())
@api.route('/libretto')
class Libretto(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce il libretto universitario dello studente
:param: username: Nome utente
:param: password: Password
:example: /libretto
:returns: json -- Libretto dello studente
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.libretto())
@api.route('/pagamenti')
class Pagamenti(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce i pagamenti effettuati dello studente
:param: username: Nome utente
:param: password: Password
:example: /pagamenti
:returns: json -- Pagamenti effettuati dallo studente
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.pagamenti())
@api.route('/prenotazioni_effettuate')
class PrenotazioniEffettuate(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce le prenotazioni alle sedute d'esame effettuati dello studente
:param: username: Nome utente
:param: password: Password
:example: /prenotazioni_effettuate
:returns: json -- Prenotazioni effettuate dallo studente
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.prenotazioni_effettuate())
@api.route('/piano')
class Piano(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce il piano di studio dello studente
:param: username: Nome utente
:param: password: Password
:example: /piano
:returns: json -- Lista degli esami sostenuti
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.piano())
@api.route('/pannello')
class Pannello(Resource):
@api.doc(parser=parser)
def post(self) :
"""Restituisce il pannello di controllo dello studente
:param: username: Nome utente
:param: password: Password
:example: /pannello
:returns: json -- Lista degli esami sostenuti
-------------------------------------------------------------------------------------------
"""
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.pannello_di_controllo())
if __name__ == '__main__':
app.debug = True
app.run()
| 31.060976 | 116 | 0.575775 |
import json, sys, re, urllib, urllib2, socket, json, pydoc, cgi, os, time, inspect
from hashlib import md5
from datetime import datetime
import time
import csv
from scraper import Scraper
from flask import Flask
from flask import Response
from flask import request
from flask import jsonify
from flask import current_app
from flask import make_response
from flask import session
from flask import url_for
from flask import redirect
from flask import render_template
from flask import abort
from flask import g
from flask import flash
from flask import _app_ctx_stack
from flask_restplus import Resource, Api
from flask_restplus import fields
from functools import wraps
from functools import update_wrapper
import logging
import traceback
log = logging.getLogger(__name__)
app = Flask(__name__)
api = Api(app)
app.config.from_object(__name__)
app.config.update(dict(
SECRET_KEY='development key',
USERNAME='admin',
PASSWORD='default'
))
app.config.from_envvar('ESSE3API_SETTINGS', silent=True)
@api.errorhandler
def default_error_handler(e):
message = 'An unhandled exception occurred.'
log.exception(message)
if not settings.FLASK_DEBUG:
return {'message': message}, 500
matic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
h['Access-Control-Allow-Credentials'] = 'true'
h['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept, Authorization"
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
callback = request.args.get('callback', False)
if callback:
data = str(func(*args, **kwargs).data)
content = str(callback) + '(' + data + ')'
mimetype = 'application/javascript'
return current_app.response_class(content, mimetype=mimetype)
else:
return func(*args, **kwargs)
return decorated_function
parser = api.parser()
parser.add_argument('username', help='The username', location='form')
parser.add_argument('password', help='The passowrd', location='form')
@api.route('/dati_anagrafici')
class DatiAnagrafici(Resource):
@api.doc(parser=parser)
def post(self):
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
log.info(username)
s = Scraper(username, password)
return jsonify(s.dati_anagrafici())
@api.route('/login')
class Login(Resource):
@api.doc(parser=parser)
def post(self):
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.login())
@api.route('/riepilogo_esami')
class RiepilogoEsami(Resource):
@api.doc(parser=parser)
def post(self) :
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.riepilogo_esami())
@api.route('/residenza')
class Residenza(Resource):
@api.doc(parser=parser)
def post(self) :
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.residenza())
@api.route('/domicilio')
class Domicilio(Resource):
@api.doc(parser=parser)
def post(self) :
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.domicilio())
@api.route('/libretto')
class Libretto(Resource):
@api.doc(parser=parser)
def post(self) :
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.libretto())
@api.route('/pagamenti')
class Pagamenti(Resource):
@api.doc(parser=parser)
def post(self) :
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.pagamenti())
@api.route('/prenotazioni_effettuate')
class PrenotazioniEffettuate(Resource):
@api.doc(parser=parser)
def post(self) :
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.prenotazioni_effettuate())
@api.route('/piano')
class Piano(Resource):
@api.doc(parser=parser)
def post(self) :
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.piano())
@api.route('/pannello')
class Pannello(Resource):
@api.doc(parser=parser)
def post(self) :
args = parser.parse_args(strict=True)
username = args['username']
password = args['password']
s = Scraper(username, password)
return jsonify(s.pannello_di_controllo())
if __name__ == '__main__':
app.debug = True
app.run()
| true | true |
f72bba8e3526c1ea6ffcb838cd2c3598c2a72e30 | 3,094 | py | Python | app/forms.py | credwood/bitplayers | 4ca6b6c6a21bb21d7cd963c64028415559c3dcc4 | [
"MIT"
] | 1 | 2020-06-26T21:49:14.000Z | 2020-06-26T21:49:14.000Z | app/forms.py | credwood/bitplayers | 4ca6b6c6a21bb21d7cd963c64028415559c3dcc4 | [
"MIT"
] | 2 | 2020-03-31T11:11:04.000Z | 2021-12-13T20:38:48.000Z | app/forms.py | credwood/bitplayers | 4ca6b6c6a21bb21d7cd963c64028415559c3dcc4 | [
"MIT"
] | null | null | null | from flask_wtf import FlaskForm, RecaptchaField
from wtforms import BooleanField, TextAreaField
from wtforms import PasswordField
from wtforms import StringField
from wtforms import SubmitField, TextField
from wtforms import Form, BooleanField, validators
from wtforms.validators import DataRequired, InputRequired, EqualTo, Length, Email, ValidationError
from wtforms.fields.html5 import EmailField
from wtf_tinymce.forms.fields import TinyMceField
from .models import Blog, User
class NewPost(FlaskForm):
blog_title = StringField('Title', validators=[DataRequired(message="All posts must have a title")])
blog_slug = StringField('Slug', validators=[DataRequired()])
blog_author = StringField('By', validators=[DataRequired()])
blog_content = TextAreaField(validators=[DataRequired()])
submit = SubmitField('submit', validators=[DataRequired()])
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Login')
remember_me = BooleanField('Remember Me')
class RequestResetForm(FlaskForm):
email = EmailField('Email address', [validators.DataRequired(), validators.Email()])
submit = SubmitField('Request Password Reset')
def validate_email(self, email):
user = User.query.filter_by(email=email.data).first()
if not user:
raise ValidationError("No account registered with that email. ")
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
confirm = PasswordField('Confirm Password', validators=[DataRequired(),InputRequired(), EqualTo('password', message='Passwords must match')])
email = EmailField('Email address', [validators.DataRequired(), validators.Email()])
submit = SubmitField('Register')
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError("That username is already taken. Please try another")
def validate_email(self, email):
user = User.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError("There is an account associated with this email address already.")
class ResetPassword(FlaskForm):
password = PasswordField('Password', validators=[DataRequired()])
confirm = PasswordField('Confirm Password', validators=[DataRequired(),InputRequired(), EqualTo('password', message='Passwords must match')])
submit = SubmitField('Reset Password')
class ContactForm(FlaskForm):
"""Contact form."""
name = StringField('Name', [
DataRequired()])
email = StringField('Email', [
Email(message=('Not a valid email address.')),
DataRequired()])
body = TextField('Message', [
DataRequired(),
Length(min=4, message=('Your message is too short.'))])
#recaptcha = RecaptchaField()
submit = SubmitField('Submit')
| 44.84058 | 145 | 0.72075 | from flask_wtf import FlaskForm, RecaptchaField
from wtforms import BooleanField, TextAreaField
from wtforms import PasswordField
from wtforms import StringField
from wtforms import SubmitField, TextField
from wtforms import Form, BooleanField, validators
from wtforms.validators import DataRequired, InputRequired, EqualTo, Length, Email, ValidationError
from wtforms.fields.html5 import EmailField
from wtf_tinymce.forms.fields import TinyMceField
from .models import Blog, User
class NewPost(FlaskForm):
blog_title = StringField('Title', validators=[DataRequired(message="All posts must have a title")])
blog_slug = StringField('Slug', validators=[DataRequired()])
blog_author = StringField('By', validators=[DataRequired()])
blog_content = TextAreaField(validators=[DataRequired()])
submit = SubmitField('submit', validators=[DataRequired()])
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Login')
remember_me = BooleanField('Remember Me')
class RequestResetForm(FlaskForm):
email = EmailField('Email address', [validators.DataRequired(), validators.Email()])
submit = SubmitField('Request Password Reset')
def validate_email(self, email):
user = User.query.filter_by(email=email.data).first()
if not user:
raise ValidationError("No account registered with that email. ")
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
confirm = PasswordField('Confirm Password', validators=[DataRequired(),InputRequired(), EqualTo('password', message='Passwords must match')])
email = EmailField('Email address', [validators.DataRequired(), validators.Email()])
submit = SubmitField('Register')
def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user:
raise ValidationError("That username is already taken. Please try another")
def validate_email(self, email):
user = User.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError("There is an account associated with this email address already.")
class ResetPassword(FlaskForm):
password = PasswordField('Password', validators=[DataRequired()])
confirm = PasswordField('Confirm Password', validators=[DataRequired(),InputRequired(), EqualTo('password', message='Passwords must match')])
submit = SubmitField('Reset Password')
class ContactForm(FlaskForm):
name = StringField('Name', [
DataRequired()])
email = StringField('Email', [
Email(message=('Not a valid email address.')),
DataRequired()])
body = TextField('Message', [
DataRequired(),
Length(min=4, message=('Your message is too short.'))])
submit = SubmitField('Submit')
| true | true |
f72bba9d57d9b9c86ad129995eaf5cd82c8bbdc8 | 5,764 | py | Python | test/integration/ggrc/proposal/test_proposal_email.py | MikalaiMikalalai/ggrc-core | f0f83b3638574bb64de474f3b70ed27436ca812a | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-01-12T23:46:00.000Z | 2019-01-12T23:46:00.000Z | test/integration/ggrc/proposal/test_proposal_email.py | MikalaiMikalalai/ggrc-core | f0f83b3638574bb64de474f3b70ed27436ca812a | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | test/integration/ggrc/proposal/test_proposal_email.py | MikalaiMikalalai/ggrc-core | f0f83b3638574bb64de474f3b70ed27436ca812a | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""This module contains test about sending emails for proposals."""
import ddt
import mock
from ggrc.notifications import fast_digest
from integration.ggrc import TestCase
from integration.ggrc.api_helper import Api
from integration.ggrc.models import factories
@ddt.ddt
class TestProposalEmail(TestCase):
"""Test case about email sending and email presenting for proposals."""
def setUp(self):
super(TestProposalEmail, self).setUp()
self.api = Api()
self.client.get("/login")
@ddt.data(True, False)
def test_email_presentation(self, is_admin):
"""Test presentation of proposal digest email if is_admin is {0}."""
person = factories.PersonFactory()
self.api.set_user(person=person)
with mock.patch("ggrc.rbac.permissions.is_admin", return_value=is_admin):
resp = self.client.get("/_notifications/show_fast_digest")
if is_admin:
self.assert200(resp)
else:
self.assert403(resp)
def test_email_sending(self):
"""Test sending emails about proposals."""
role_1 = factories.AccessControlRoleFactory(object_type="Program",
notify_about_proposal=True)
role_2 = factories.AccessControlRoleFactory(object_type="Program",
notify_about_proposal=True)
role_3 = factories.AccessControlRoleFactory(object_type="Program",
notify_about_proposal=False)
with factories.single_commit():
program = factories.ProgramFactory()
person_1 = factories.PersonFactory() # has 1 role
person_2 = factories.PersonFactory() # has no roles
person_3 = factories.PersonFactory() # has 2 roles
factories.PersonFactory() # not related to program at all
factories.AccessControlPersonFactory(
ac_list=program.acr_acl_map[role_1],
person=person_1
)
factories.AccessControlPersonFactory(
ac_list=program.acr_acl_map[role_1],
person=person_3
)
factories.AccessControlPersonFactory(
ac_list=program.acr_acl_map[role_2],
person=person_3
)
factories.AccessControlPersonFactory(
ac_list=program.acr_acl_map[role_3],
person=person_2
)
proposal_1 = factories.ProposalFactory(
instance=program,
content={
"fields": {"title": "a"},
"access_control_list": {},
"custom_attribute_values": {},
"mapping_fields": {},
"mapping_list_fields": {},
},
agenda="agenda 1")
proposal_2 = factories.ProposalFactory(
instance=program,
content={
"fields": {"title": "b"},
"access_control_list": {},
"custom_attribute_values": {},
"mapping_fields": {},
"mapping_list_fields": {},
},
agenda="agenda 2")
self.assertIsNone(proposal_1.proposed_notified_datetime)
self.assertIsNone(proposal_2.proposed_notified_datetime)
with mock.patch("ggrc.notifications.common.send_email") as send_email_mock:
with mock.patch.object(fast_digest.DIGEST_TMPL,
"render") as bodybuilder_mock:
fast_digest.send_notification()
self.assertIsNotNone(proposal_1.proposed_notified_datetime)
self.assertIsNotNone(proposal_2.proposed_notified_datetime)
self.assertEqual(2, len(bodybuilder_mock.call_args_list))
self.assertEqual(2, len(send_email_mock.call_args_list))
# email to each required person
self.assertListEqual(
sorted([person_1.email, person_3.email]),
sorted([a[1]["user_email"] for a in send_email_mock.call_args_list]))
# no matter how many roles each proposal should be otified
# only once for that person
self.assertListEqual(
[2] * 2,
[len(a[1]["proposals"]) for a in bodybuilder_mock.call_args_list])
@ddt.data(
'Program Managers',
'Program Editors',
'Primary Contacts'
)
def test_email_proposal_program(self, role_name):
"""Test sending email to Program manager/Editor/Primary Contacts"""
from ggrc.models import all_models
role_1 = all_models.AccessControlRole.query.filter(
all_models.AccessControlRole.name == role_name,
all_models.AccessControlRole.object_type == 'Program',
).one()
with factories.single_commit():
program = factories.ProgramFactory()
person_1 = factories.PersonFactory() # has 1 role
factories.AccessControlPersonFactory(
ac_list=program.acr_acl_map[role_1],
person=person_1
)
proposal_1 = factories.ProposalFactory(
instance=program,
content={
"fields": {"title": "a"},
"access_control_list": {},
"custom_attribute_values": {},
"mapping_fields": {},
"mapping_list_fields": {},
},
agenda="agenda 1")
self.assertIsNone(proposal_1.proposed_notified_datetime)
with mock.patch("ggrc.notifications.common.send_email") as send_email_mock:
with mock.patch.object(fast_digest.DIGEST_TMPL,
"render") as bodybuilder_mock:
fast_digest.send_notification()
self.assertIsNotNone(proposal_1.proposed_notified_datetime)
self.assertEqual(1, len(bodybuilder_mock.call_args_list))
self.assertEqual(1, len(send_email_mock.call_args_list))
# email to each required person
self.assertEqual(
[person_1.email],
[a[1]["user_email"] for a in send_email_mock.call_args_list])
| 39.479452 | 79 | 0.653539 |
import ddt
import mock
from ggrc.notifications import fast_digest
from integration.ggrc import TestCase
from integration.ggrc.api_helper import Api
from integration.ggrc.models import factories
@ddt.ddt
class TestProposalEmail(TestCase):
def setUp(self):
super(TestProposalEmail, self).setUp()
self.api = Api()
self.client.get("/login")
@ddt.data(True, False)
def test_email_presentation(self, is_admin):
person = factories.PersonFactory()
self.api.set_user(person=person)
with mock.patch("ggrc.rbac.permissions.is_admin", return_value=is_admin):
resp = self.client.get("/_notifications/show_fast_digest")
if is_admin:
self.assert200(resp)
else:
self.assert403(resp)
def test_email_sending(self):
role_1 = factories.AccessControlRoleFactory(object_type="Program",
notify_about_proposal=True)
role_2 = factories.AccessControlRoleFactory(object_type="Program",
notify_about_proposal=True)
role_3 = factories.AccessControlRoleFactory(object_type="Program",
notify_about_proposal=False)
with factories.single_commit():
program = factories.ProgramFactory()
person_1 = factories.PersonFactory()
person_2 = factories.PersonFactory()
person_3 = factories.PersonFactory()
factories.PersonFactory()
factories.AccessControlPersonFactory(
ac_list=program.acr_acl_map[role_1],
person=person_1
)
factories.AccessControlPersonFactory(
ac_list=program.acr_acl_map[role_1],
person=person_3
)
factories.AccessControlPersonFactory(
ac_list=program.acr_acl_map[role_2],
person=person_3
)
factories.AccessControlPersonFactory(
ac_list=program.acr_acl_map[role_3],
person=person_2
)
proposal_1 = factories.ProposalFactory(
instance=program,
content={
"fields": {"title": "a"},
"access_control_list": {},
"custom_attribute_values": {},
"mapping_fields": {},
"mapping_list_fields": {},
},
agenda="agenda 1")
proposal_2 = factories.ProposalFactory(
instance=program,
content={
"fields": {"title": "b"},
"access_control_list": {},
"custom_attribute_values": {},
"mapping_fields": {},
"mapping_list_fields": {},
},
agenda="agenda 2")
self.assertIsNone(proposal_1.proposed_notified_datetime)
self.assertIsNone(proposal_2.proposed_notified_datetime)
with mock.patch("ggrc.notifications.common.send_email") as send_email_mock:
with mock.patch.object(fast_digest.DIGEST_TMPL,
"render") as bodybuilder_mock:
fast_digest.send_notification()
self.assertIsNotNone(proposal_1.proposed_notified_datetime)
self.assertIsNotNone(proposal_2.proposed_notified_datetime)
self.assertEqual(2, len(bodybuilder_mock.call_args_list))
self.assertEqual(2, len(send_email_mock.call_args_list))
self.assertListEqual(
sorted([person_1.email, person_3.email]),
sorted([a[1]["user_email"] for a in send_email_mock.call_args_list]))
self.assertListEqual(
[2] * 2,
[len(a[1]["proposals"]) for a in bodybuilder_mock.call_args_list])
@ddt.data(
'Program Managers',
'Program Editors',
'Primary Contacts'
)
def test_email_proposal_program(self, role_name):
from ggrc.models import all_models
role_1 = all_models.AccessControlRole.query.filter(
all_models.AccessControlRole.name == role_name,
all_models.AccessControlRole.object_type == 'Program',
).one()
with factories.single_commit():
program = factories.ProgramFactory()
person_1 = factories.PersonFactory()
factories.AccessControlPersonFactory(
ac_list=program.acr_acl_map[role_1],
person=person_1
)
proposal_1 = factories.ProposalFactory(
instance=program,
content={
"fields": {"title": "a"},
"access_control_list": {},
"custom_attribute_values": {},
"mapping_fields": {},
"mapping_list_fields": {},
},
agenda="agenda 1")
self.assertIsNone(proposal_1.proposed_notified_datetime)
with mock.patch("ggrc.notifications.common.send_email") as send_email_mock:
with mock.patch.object(fast_digest.DIGEST_TMPL,
"render") as bodybuilder_mock:
fast_digest.send_notification()
self.assertIsNotNone(proposal_1.proposed_notified_datetime)
self.assertEqual(1, len(bodybuilder_mock.call_args_list))
self.assertEqual(1, len(send_email_mock.call_args_list))
self.assertEqual(
[person_1.email],
[a[1]["user_email"] for a in send_email_mock.call_args_list])
| true | true |
f72bbb6109eb7cd126564a721c3685fff15dd47b | 1,919 | py | Python | pyretrommo/gen/player_stats.py | snwhd/pyretrommo | fabb523d9b4385ed8a1ff0b2ac787cc5d88a23b7 | [
"blessing"
] | 1 | 2021-11-25T09:33:30.000Z | 2021-11-25T09:33:30.000Z | pyretrommo/gen/player_stats.py | snwhd/pyretrommo | fabb523d9b4385ed8a1ff0b2ac787cc5d88a23b7 | [
"blessing"
] | null | null | null | pyretrommo/gen/player_stats.py | snwhd/pyretrommo | fabb523d9b4385ed8a1ff0b2ac787cc5d88a23b7 | [
"blessing"
] | null | null | null | #!/usr/bin/env python3
# this file is auto-generated by gen_from_wiki.py
from __future__ import annotations
from .player_class import PlayerClass
from ..stats import Stats
STATS_BY_PLAYER_CLASS = {
PlayerClass.Cleric: [
Stats(*(0, 0, 0, 0, 0, 0, 0, 0)),
Stats(*(17, 11, 8, 9, 12, 12, 10, 11)),
Stats(*(23, 15, 9, 11, 15, 14, 12, 13)),
Stats(*(29, 19, 11, 12, 17, 16, 14, 16)),
Stats(*(35, 23, 12, 14, 20, 19, 16, 18)),
Stats(*(40, 26, 14, 16, 22, 21, 18, 20)),
Stats(*(46, 30, 16, 18, 25, 23, 20, 22)),
Stats(*(52, 34, 17, 20, 27, 26, 22, 24)),
Stats(*(58, 38, 19, 21, 30, 28, 23, 27)),
Stats(*(63, 41, 20, 23, 32, 30, 25, 29)),
Stats(*(69, 45, 22, 25, 35, 33, 27, 31)),
],
PlayerClass.Warrior: [
Stats(*(0, 0, 0, 0, 0, 0, 0, 0)),
Stats(*(17, 11, 8, 9, 12, 12, 10, 11)),
Stats(*(23, 15, 9, 11, 15, 14, 12, 13)),
Stats(*(29, 19, 11, 12, 17, 16, 14, 16)),
Stats(*(35, 23, 12, 14, 20, 19, 16, 18)),
Stats(*(40, 26, 14, 16, 22, 21, 18, 20)),
Stats(*(46, 30, 16, 18, 25, 23, 20, 22)),
Stats(*(52, 34, 17, 20, 27, 26, 22, 24)),
Stats(*(58, 38, 19, 21, 30, 28, 23, 27)),
Stats(*(63, 41, 20, 23, 32, 30, 25, 29)),
Stats(*(69, 45, 22, 25, 35, 33, 27, 31)),
],
PlayerClass.Wizard: [
Stats(*(0, 0, 0, 0, 0, 0, 0, 0)),
Stats(*(17, 11, 8, 9, 12, 12, 10, 11)),
Stats(*(23, 15, 9, 11, 15, 14, 12, 13)),
Stats(*(29, 19, 11, 12, 17, 16, 14, 16)),
Stats(*(35, 23, 12, 14, 20, 19, 16, 18)),
Stats(*(40, 26, 14, 16, 22, 21, 18, 20)),
Stats(*(46, 30, 16, 18, 25, 23, 20, 22)),
Stats(*(52, 34, 17, 20, 27, 26, 22, 24)),
Stats(*(58, 38, 19, 21, 30, 28, 23, 27)),
Stats(*(63, 41, 20, 23, 32, 30, 25, 29)),
Stats(*(69, 45, 22, 25, 35, 33, 27, 31)),
],
}
| 39.163265 | 49 | 0.454924 |
from __future__ import annotations
from .player_class import PlayerClass
from ..stats import Stats
STATS_BY_PLAYER_CLASS = {
PlayerClass.Cleric: [
Stats(*(0, 0, 0, 0, 0, 0, 0, 0)),
Stats(*(17, 11, 8, 9, 12, 12, 10, 11)),
Stats(*(23, 15, 9, 11, 15, 14, 12, 13)),
Stats(*(29, 19, 11, 12, 17, 16, 14, 16)),
Stats(*(35, 23, 12, 14, 20, 19, 16, 18)),
Stats(*(40, 26, 14, 16, 22, 21, 18, 20)),
Stats(*(46, 30, 16, 18, 25, 23, 20, 22)),
Stats(*(52, 34, 17, 20, 27, 26, 22, 24)),
Stats(*(58, 38, 19, 21, 30, 28, 23, 27)),
Stats(*(63, 41, 20, 23, 32, 30, 25, 29)),
Stats(*(69, 45, 22, 25, 35, 33, 27, 31)),
],
PlayerClass.Warrior: [
Stats(*(0, 0, 0, 0, 0, 0, 0, 0)),
Stats(*(17, 11, 8, 9, 12, 12, 10, 11)),
Stats(*(23, 15, 9, 11, 15, 14, 12, 13)),
Stats(*(29, 19, 11, 12, 17, 16, 14, 16)),
Stats(*(35, 23, 12, 14, 20, 19, 16, 18)),
Stats(*(40, 26, 14, 16, 22, 21, 18, 20)),
Stats(*(46, 30, 16, 18, 25, 23, 20, 22)),
Stats(*(52, 34, 17, 20, 27, 26, 22, 24)),
Stats(*(58, 38, 19, 21, 30, 28, 23, 27)),
Stats(*(63, 41, 20, 23, 32, 30, 25, 29)),
Stats(*(69, 45, 22, 25, 35, 33, 27, 31)),
],
PlayerClass.Wizard: [
Stats(*(0, 0, 0, 0, 0, 0, 0, 0)),
Stats(*(17, 11, 8, 9, 12, 12, 10, 11)),
Stats(*(23, 15, 9, 11, 15, 14, 12, 13)),
Stats(*(29, 19, 11, 12, 17, 16, 14, 16)),
Stats(*(35, 23, 12, 14, 20, 19, 16, 18)),
Stats(*(40, 26, 14, 16, 22, 21, 18, 20)),
Stats(*(46, 30, 16, 18, 25, 23, 20, 22)),
Stats(*(52, 34, 17, 20, 27, 26, 22, 24)),
Stats(*(58, 38, 19, 21, 30, 28, 23, 27)),
Stats(*(63, 41, 20, 23, 32, 30, 25, 29)),
Stats(*(69, 45, 22, 25, 35, 33, 27, 31)),
],
}
| true | true |
f72bbba8b340d6dadd4bd602a0a79cc67d8d633b | 236 | py | Python | src/silicium/scene.py | PH-KDX/silicium | 813e8719a4ba381691d3d1b11ea5738bb2ee2d36 | [
"MIT"
] | 2 | 2021-12-12T12:06:46.000Z | 2021-12-12T12:21:18.000Z | src/silicium/scene.py | PH-KDX/silicium | 813e8719a4ba381691d3d1b11ea5738bb2ee2d36 | [
"MIT"
] | 1 | 2021-12-12T12:21:43.000Z | 2021-12-12T22:49:46.000Z | src/silicium/scene.py | PH-KDX/silicium | 813e8719a4ba381691d3d1b11ea5738bb2ee2d36 | [
"MIT"
] | 2 | 2021-12-12T15:13:54.000Z | 2021-12-21T09:08:42.000Z | from dataclasses import dataclass
from abc import ABC, abstractmethod
from .builder import AbstractBuilder
@dataclass
class AbstractScene(ABC):
builder: AbstractBuilder
@abstractmethod
def run(self) -> None:
...
| 16.857143 | 36 | 0.728814 | from dataclasses import dataclass
from abc import ABC, abstractmethod
from .builder import AbstractBuilder
@dataclass
class AbstractScene(ABC):
builder: AbstractBuilder
@abstractmethod
def run(self) -> None:
...
| true | true |
f72bbc0a917dfbe976b673ecf7b7fb9a01ec6ce3 | 1,391 | py | Python | app/user/serializers.py | faridos/my_delivery_app_django | 87b487a064b190bfb8e71ba40e6edb9ebc9bd817 | [
"MIT"
] | null | null | null | app/user/serializers.py | faridos/my_delivery_app_django | 87b487a064b190bfb8e71ba40e6edb9ebc9bd817 | [
"MIT"
] | null | null | null | app/user/serializers.py | faridos/my_delivery_app_django | 87b487a064b190bfb8e71ba40e6edb9ebc9bd817 | [
"MIT"
] | null | null | null | from django.contrib.auth import get_user_model, authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
"""Serializer for the users object"""
class Meta:
model = get_user_model()
fields = ('email', 'password', 'name')
extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}
def create(self, validated_data):
"""Create a new user with encrypted password and return it"""
return get_user_model().objects.create_user(**validated_data)
class AuthTokenSerializer(serializers.Serializer):
"""Serializer for the user authentication object"""
email = serializers.CharField()
password = serializers.CharField(
style={'input_type': 'password'},
trim_whitespace=False
)
def validate(self, attrs):
"""Validate and authenticate the user"""
email = attrs.get('email')
password = attrs.get('password')
user = authenticate(
request=self.context.get('request'),
username=email,
password=password
)
if not user:
msg = _('Unable to authenticate with provided credentials')
raise serializers.ValidationError(msg, code='authorization')
attrs['user'] = user
return attrs | 33.119048 | 74 | 0.65133 | from django.contrib.auth import get_user_model, authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('email', 'password', 'name')
extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}
def create(self, validated_data):
return get_user_model().objects.create_user(**validated_data)
class AuthTokenSerializer(serializers.Serializer):
email = serializers.CharField()
password = serializers.CharField(
style={'input_type': 'password'},
trim_whitespace=False
)
def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')
user = authenticate(
request=self.context.get('request'),
username=email,
password=password
)
if not user:
msg = _('Unable to authenticate with provided credentials')
raise serializers.ValidationError(msg, code='authorization')
attrs['user'] = user
return attrs | true | true |
f72bbc4cec7a7d7ee13488d5aad10549c5740f87 | 171 | py | Python | tests/model_control/detailed/transf_Anscombe/model_control_one_enabled_Anscombe_MovingAverage_Seasonal_MonthOfYear_ARX.py | jmabry/pyaf | afbc15a851a2445a7824bf255af612dc429265af | [
"BSD-3-Clause"
] | null | null | null | tests/model_control/detailed/transf_Anscombe/model_control_one_enabled_Anscombe_MovingAverage_Seasonal_MonthOfYear_ARX.py | jmabry/pyaf | afbc15a851a2445a7824bf255af612dc429265af | [
"BSD-3-Clause"
] | 1 | 2019-11-30T23:39:38.000Z | 2019-12-01T04:34:35.000Z | tests/model_control/detailed/transf_Anscombe/model_control_one_enabled_Anscombe_MovingAverage_Seasonal_MonthOfYear_ARX.py | jmabry/pyaf | afbc15a851a2445a7824bf255af612dc429265af | [
"BSD-3-Clause"
] | null | null | null | import pyaf.tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Anscombe'] , ['MovingAverage'] , ['Seasonal_MonthOfYear'] , ['ARX'] ); | 42.75 | 93 | 0.766082 | import pyaf.tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Anscombe'] , ['MovingAverage'] , ['Seasonal_MonthOfYear'] , ['ARX'] ); | true | true |
f72bbca3b2e8a2f4ec524e851e80d4cf38f9ab9d | 4,759 | py | Python | David and Pooja/++Validating Linked Mods/Python-3.0/Lib/lib2to3/pgen2/driver.py | LinkedModernismProject/web_code | 4cf6bf53d5c3249e52a75f0a3f57d106e31daf9e | [
"Apache-2.0"
] | 1 | 2015-05-21T23:47:54.000Z | 2015-05-21T23:47:54.000Z | front-end/testsuite-python-lib/Python-3.0/Lib/lib2to3/pgen2/driver.py | MalloyPower/parsing-python | b2bca5eed07ea2af7a2001cd4f63becdfb0570be | [
"MIT"
] | 1 | 2015-10-29T20:51:31.000Z | 2015-10-29T20:51:31.000Z | front-end/testsuite-python-lib/Python-3.0/Lib/lib2to3/pgen2/driver.py | MalloyPower/parsing-python | b2bca5eed07ea2af7a2001cd4f63becdfb0570be | [
"MIT"
] | 1 | 2019-04-11T11:27:01.000Z | 2019-04-11T11:27:01.000Z | # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
# Modifications:
# Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Parser driver.
This provides a high-level interface to parse a file into a syntax tree.
"""
__author__ = "Guido van Rossum <guido@python.org>"
__all__ = ["Driver", "load_grammar"]
# Python imports
import os
import logging
import sys
# Pgen imports
from . import grammar, parse, token, tokenize, pgen
class Driver(object):
def __init__(self, grammar, convert=None, logger=None):
self.grammar = grammar
if logger is None:
logger = logging.getLogger()
self.logger = logger
self.convert = convert
def parse_tokens(self, tokens, debug=False):
"""Parse a series of tokens and return the syntax tree."""
# XXX Move the prefix computation into a wrapper around tokenize.
p = parse.Parser(self.grammar, self.convert)
p.setup()
lineno = 1
column = 0
type = value = start = end = line_text = None
prefix = ""
for quintuple in tokens:
type, value, start, end, line_text = quintuple
if start != (lineno, column):
assert (lineno, column) <= start, ((lineno, column), start)
s_lineno, s_column = start
if lineno < s_lineno:
prefix += "\n" * (s_lineno - lineno)
lineno = s_lineno
column = 0
if column < s_column:
prefix += line_text[column:s_column]
column = s_column
if type in (tokenize.COMMENT, tokenize.NL):
prefix += value
lineno, column = end
if value.endswith("\n"):
lineno += 1
column = 0
continue
if type == token.OP:
type = grammar.opmap[value]
if debug:
self.logger.debug("%s %r (prefix=%r)",
token.tok_name[type], value, prefix)
if p.addtoken(type, value, (prefix, start)):
if debug:
self.logger.debug("Stop.")
break
prefix = ""
lineno, column = end
if value.endswith("\n"):
lineno += 1
column = 0
else:
# We never broke out -- EOF is too soon (how can this happen???)
raise parse.ParseError("incomplete input", t, v, x)
return p.rootnode
def parse_stream_raw(self, stream, debug=False):
"""Parse a stream and return the syntax tree."""
tokens = tokenize.generate_tokens(stream.readline)
return self.parse_tokens(tokens, debug)
def parse_stream(self, stream, debug=False):
"""Parse a stream and return the syntax tree."""
return self.parse_stream_raw(stream, debug)
def parse_file(self, filename, debug=False):
"""Parse a file and return the syntax tree."""
stream = open(filename)
try:
return self.parse_stream(stream, debug)
finally:
stream.close()
def parse_string(self, text, debug=False):
"""Parse a string and return the syntax tree."""
tokens = tokenize.generate_tokens(generate_lines(text).__next__)
return self.parse_tokens(tokens, debug)
def generate_lines(text):
"""Generator that behaves like readline without using StringIO."""
for line in text.splitlines(True):
yield line
while True:
yield ""
def load_grammar(gt="Grammar.txt", gp=None,
save=True, force=False, logger=None):
"""Load the grammar (maybe from a pickle)."""
if logger is None:
logger = logging.getLogger()
if gp is None:
head, tail = os.path.splitext(gt)
if tail == ".txt":
tail = ""
gp = head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
if force or not _newer(gp, gt):
logger.info("Generating grammar tables from %s", gt)
g = pgen.generate_grammar(gt)
if save:
logger.info("Writing grammar tables to %s", gp)
try:
g.dump(gp)
except IOError as e:
logger.info("Writing failed:"+str(e))
else:
g = grammar.Grammar()
g.load(gp)
return g
def _newer(a, b):
"""Inquire whether file a was written since file b."""
if not os.path.exists(a):
return False
if not os.path.exists(b):
return True
return os.path.getmtime(a) >= os.path.getmtime(b)
| 32.59589 | 76 | 0.562093 |
__author__ = "Guido van Rossum <guido@python.org>"
__all__ = ["Driver", "load_grammar"]
import os
import logging
import sys
from . import grammar, parse, token, tokenize, pgen
class Driver(object):
def __init__(self, grammar, convert=None, logger=None):
self.grammar = grammar
if logger is None:
logger = logging.getLogger()
self.logger = logger
self.convert = convert
def parse_tokens(self, tokens, debug=False):
p = parse.Parser(self.grammar, self.convert)
p.setup()
lineno = 1
column = 0
type = value = start = end = line_text = None
prefix = ""
for quintuple in tokens:
type, value, start, end, line_text = quintuple
if start != (lineno, column):
assert (lineno, column) <= start, ((lineno, column), start)
s_lineno, s_column = start
if lineno < s_lineno:
prefix += "\n" * (s_lineno - lineno)
lineno = s_lineno
column = 0
if column < s_column:
prefix += line_text[column:s_column]
column = s_column
if type in (tokenize.COMMENT, tokenize.NL):
prefix += value
lineno, column = end
if value.endswith("\n"):
lineno += 1
column = 0
continue
if type == token.OP:
type = grammar.opmap[value]
if debug:
self.logger.debug("%s %r (prefix=%r)",
token.tok_name[type], value, prefix)
if p.addtoken(type, value, (prefix, start)):
if debug:
self.logger.debug("Stop.")
break
prefix = ""
lineno, column = end
if value.endswith("\n"):
lineno += 1
column = 0
else:
raise parse.ParseError("incomplete input", t, v, x)
return p.rootnode
def parse_stream_raw(self, stream, debug=False):
tokens = tokenize.generate_tokens(stream.readline)
return self.parse_tokens(tokens, debug)
def parse_stream(self, stream, debug=False):
return self.parse_stream_raw(stream, debug)
def parse_file(self, filename, debug=False):
stream = open(filename)
try:
return self.parse_stream(stream, debug)
finally:
stream.close()
def parse_string(self, text, debug=False):
tokens = tokenize.generate_tokens(generate_lines(text).__next__)
return self.parse_tokens(tokens, debug)
def generate_lines(text):
for line in text.splitlines(True):
yield line
while True:
yield ""
def load_grammar(gt="Grammar.txt", gp=None,
save=True, force=False, logger=None):
if logger is None:
logger = logging.getLogger()
if gp is None:
head, tail = os.path.splitext(gt)
if tail == ".txt":
tail = ""
gp = head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
if force or not _newer(gp, gt):
logger.info("Generating grammar tables from %s", gt)
g = pgen.generate_grammar(gt)
if save:
logger.info("Writing grammar tables to %s", gp)
try:
g.dump(gp)
except IOError as e:
logger.info("Writing failed:"+str(e))
else:
g = grammar.Grammar()
g.load(gp)
return g
def _newer(a, b):
if not os.path.exists(a):
return False
if not os.path.exists(b):
return True
return os.path.getmtime(a) >= os.path.getmtime(b)
| true | true |
f72bbd8a0db5fae809ca9c1b2443d5383f6ae83e | 5,635 | py | Python | sdk/python/pulumi_azure_native/devtestlab/v20180915/list_service_fabric_applicable_schedules.py | pulumi-bot/pulumi-azure-native | f7b9490b5211544318e455e5cceafe47b628e12c | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/devtestlab/v20180915/list_service_fabric_applicable_schedules.py | pulumi-bot/pulumi-azure-native | f7b9490b5211544318e455e5cceafe47b628e12c | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/devtestlab/v20180915/list_service_fabric_applicable_schedules.py | pulumi-bot/pulumi-azure-native | f7b9490b5211544318e455e5cceafe47b628e12c | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'ListServiceFabricApplicableSchedulesResult',
'AwaitableListServiceFabricApplicableSchedulesResult',
'list_service_fabric_applicable_schedules',
]
@pulumi.output_type
class ListServiceFabricApplicableSchedulesResult:
"""
Schedules applicable to a virtual machine. The schedules may have been defined on a VM or on lab level.
"""
def __init__(__self__, id=None, lab_vms_shutdown=None, lab_vms_startup=None, location=None, name=None, tags=None, type=None):
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if lab_vms_shutdown and not isinstance(lab_vms_shutdown, dict):
raise TypeError("Expected argument 'lab_vms_shutdown' to be a dict")
pulumi.set(__self__, "lab_vms_shutdown", lab_vms_shutdown)
if lab_vms_startup and not isinstance(lab_vms_startup, dict):
raise TypeError("Expected argument 'lab_vms_startup' to be a dict")
pulumi.set(__self__, "lab_vms_startup", lab_vms_startup)
if location and not isinstance(location, str):
raise TypeError("Expected argument 'location' to be a str")
pulumi.set(__self__, "location", location)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if tags and not isinstance(tags, dict):
raise TypeError("Expected argument 'tags' to be a dict")
pulumi.set(__self__, "tags", tags)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def id(self) -> str:
"""
The identifier of the resource.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="labVmsShutdown")
def lab_vms_shutdown(self) -> Optional['outputs.ScheduleResponse']:
"""
The auto-shutdown schedule, if one has been set at the lab or lab resource level.
"""
return pulumi.get(self, "lab_vms_shutdown")
@property
@pulumi.getter(name="labVmsStartup")
def lab_vms_startup(self) -> Optional['outputs.ScheduleResponse']:
"""
The auto-startup schedule, if one has been set at the lab or lab resource level.
"""
return pulumi.get(self, "lab_vms_startup")
@property
@pulumi.getter
def location(self) -> Optional[str]:
"""
The location of the resource.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> str:
"""
The name of the resource.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def tags(self) -> Optional[Mapping[str, str]]:
"""
The tags of the resource.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> str:
"""
The type of the resource.
"""
return pulumi.get(self, "type")
class AwaitableListServiceFabricApplicableSchedulesResult(ListServiceFabricApplicableSchedulesResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return ListServiceFabricApplicableSchedulesResult(
id=self.id,
lab_vms_shutdown=self.lab_vms_shutdown,
lab_vms_startup=self.lab_vms_startup,
location=self.location,
name=self.name,
tags=self.tags,
type=self.type)
def list_service_fabric_applicable_schedules(lab_name: Optional[str] = None,
name: Optional[str] = None,
resource_group_name: Optional[str] = None,
user_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListServiceFabricApplicableSchedulesResult:
"""
Schedules applicable to a virtual machine. The schedules may have been defined on a VM or on lab level.
:param str lab_name: The name of the lab.
:param str name: The name of the service fabric.
:param str resource_group_name: The name of the resource group.
:param str user_name: The name of the user profile.
"""
__args__ = dict()
__args__['labName'] = lab_name
__args__['name'] = name
__args__['resourceGroupName'] = resource_group_name
__args__['userName'] = user_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-native:devtestlab/v20180915:listServiceFabricApplicableSchedules', __args__, opts=opts, typ=ListServiceFabricApplicableSchedulesResult).value
return AwaitableListServiceFabricApplicableSchedulesResult(
id=__ret__.id,
lab_vms_shutdown=__ret__.lab_vms_shutdown,
lab_vms_startup=__ret__.lab_vms_startup,
location=__ret__.location,
name=__ret__.name,
tags=__ret__.tags,
type=__ret__.type)
| 37.317881 | 184 | 0.644898 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'ListServiceFabricApplicableSchedulesResult',
'AwaitableListServiceFabricApplicableSchedulesResult',
'list_service_fabric_applicable_schedules',
]
@pulumi.output_type
class ListServiceFabricApplicableSchedulesResult:
def __init__(__self__, id=None, lab_vms_shutdown=None, lab_vms_startup=None, location=None, name=None, tags=None, type=None):
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if lab_vms_shutdown and not isinstance(lab_vms_shutdown, dict):
raise TypeError("Expected argument 'lab_vms_shutdown' to be a dict")
pulumi.set(__self__, "lab_vms_shutdown", lab_vms_shutdown)
if lab_vms_startup and not isinstance(lab_vms_startup, dict):
raise TypeError("Expected argument 'lab_vms_startup' to be a dict")
pulumi.set(__self__, "lab_vms_startup", lab_vms_startup)
if location and not isinstance(location, str):
raise TypeError("Expected argument 'location' to be a str")
pulumi.set(__self__, "location", location)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if tags and not isinstance(tags, dict):
raise TypeError("Expected argument 'tags' to be a dict")
pulumi.set(__self__, "tags", tags)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def id(self) -> str:
return pulumi.get(self, "id")
@property
@pulumi.getter(name="labVmsShutdown")
def lab_vms_shutdown(self) -> Optional['outputs.ScheduleResponse']:
return pulumi.get(self, "lab_vms_shutdown")
@property
@pulumi.getter(name="labVmsStartup")
def lab_vms_startup(self) -> Optional['outputs.ScheduleResponse']:
return pulumi.get(self, "lab_vms_startup")
@property
@pulumi.getter
def location(self) -> Optional[str]:
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> str:
return pulumi.get(self, "name")
@property
@pulumi.getter
def tags(self) -> Optional[Mapping[str, str]]:
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> str:
return pulumi.get(self, "type")
class AwaitableListServiceFabricApplicableSchedulesResult(ListServiceFabricApplicableSchedulesResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return ListServiceFabricApplicableSchedulesResult(
id=self.id,
lab_vms_shutdown=self.lab_vms_shutdown,
lab_vms_startup=self.lab_vms_startup,
location=self.location,
name=self.name,
tags=self.tags,
type=self.type)
def list_service_fabric_applicable_schedules(lab_name: Optional[str] = None,
name: Optional[str] = None,
resource_group_name: Optional[str] = None,
user_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListServiceFabricApplicableSchedulesResult:
__args__ = dict()
__args__['labName'] = lab_name
__args__['name'] = name
__args__['resourceGroupName'] = resource_group_name
__args__['userName'] = user_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-native:devtestlab/v20180915:listServiceFabricApplicableSchedules', __args__, opts=opts, typ=ListServiceFabricApplicableSchedulesResult).value
return AwaitableListServiceFabricApplicableSchedulesResult(
id=__ret__.id,
lab_vms_shutdown=__ret__.lab_vms_shutdown,
lab_vms_startup=__ret__.lab_vms_startup,
location=__ret__.location,
name=__ret__.name,
tags=__ret__.tags,
type=__ret__.type)
| true | true |
f72bbedeed16b94339a910792bc18059766dde94 | 5,337 | py | Python | alacrity/core.py | OLeoghain/alacrity | d49453f5f998dbaf36006fe7ec6c6753cd5ef4c1 | [
"MIT"
] | null | null | null | alacrity/core.py | OLeoghain/alacrity | d49453f5f998dbaf36006fe7ec6c6753cd5ef4c1 | [
"MIT"
] | null | null | null | alacrity/core.py | OLeoghain/alacrity | d49453f5f998dbaf36006fe7ec6c6753cd5ef4c1 | [
"MIT"
] | null | null | null | #!/bin/python
import importlib
import logging
import os
import sys
import argparse
import shutil
from clint.textui import colored
try:
from alacrity import lib
except ImportError:
lib = importlib.import_module('lib', '../alacrity')
def main():
"""
Entry point for the package, alacrity.exe in win and alacrity in linux
:return: None
"""
# Start the process
try:
from alacrity import version
except ImportError:
version = importlib.import_module('version', '../alacrity')
# Get version information from version.py
v = version.version()
parser = argparse.ArgumentParser(description="Alacrity : "
"Quickstart your Python "
"package from a terminal")
parser.add_argument('--make', action='store_true', help="Rebuild "
"persistence")
parser.add_argument('--debug', action='store_true', help="Display verbose "
"debug messages")
parser.add_argument('--version', action="version", version=v)
parser.add_argument('package_name')
args = parser.parse_args()
if args.make:
lib.rebuild_persistence()
if not args.package_name:
logging.error(" package_name is a required argument")
sys.exit()
# Initialize logging depending on debug mode
if args.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.CRITICAL)
# Initialise status dictionary
status = {
'structure_created': False,
'gitignore_created': False,
'setup_created': False,
'license_created': False,
'manifest_created': False,
'readme_created': False,
'requirements_created': False,
'tests_created': False,
'git_initialized': False,
'venv_created': False,
'sphinx_created': False
}
try:
try:
package_name = args.package_name
# Check if the package already exists
logging.debug("[-] Checking if the package already exists")
check_is_file = os.path.isfile(
"{0}/{0}/__init__.py".format(package_name))
# Check for clean_make
if os.path.isdir(package_name) or check_is_file:
logging.debug("[-] Package already exists, "
"launching clean make prompt")
print(colored.red("[!] A package by that name already exists, "
"destroy and clean make? (y/n) : "), end="")
choice = input()
logging.debug("[-] Choice prompt input : {}".format(choice))
if choice == 'y':
logging.debug("[-] Removing existing package")
lib.remove_package(package_name)
elif choice == 'n':
logging.debug("[-] Clean make cancelled")
print(colored.red("[!] Please pick a different package "
"name, aborting."))
sys.exit()
else:
logging.error(colored.red(" Invalid choice"))
print(colored.red("[!] Invalid choice, aborting"))
sys.exit()
# Create the initial structure
logging.debug("[-] Creating package structure")
lib.create_package_structure(package_name, status)
# Create starter files
logging.debug("[-] Creating starter files in package")
author, version = lib.create_starter_files(package_name, status)
# Create tests directory
logging.debug("[-] Creating tests package in structure")
lib.create_tests_package(package_name, status)
# Initialize git if required and available
logging.debug("[-] Launching git init submodule")
lib.git_init(package_name, status)
# Initialize venv if required and available
logging.debug("[-] Launching venv init submodule")
lib.venv_init(package_name, status)
# Initialize sphinx docs if required and available
logging.debug("[-] Launching sphinx init submodule")
lib.sphinx_init(package_name, author, version, status)
logging.debug("[-] Launching status reporter submodule")
lib.report_status(status)
print(colored.green("[|]"))
print(colored.green("[*] Package {} was created "
"successfully.".format(package_name)))
except EOFError:
# Catch error thrown by clint.main
print(colored.yellow("\n[!] Ctrl+C : Aborting package creation."))
sys.exit()
except KeyboardInterrupt:
print(colored.yellow("\n[!] Ctrl+C : Aborting package creation."))
# Rollback changes
if os.path.isdir(args.package_name):
logging.debug("[-] Rolling back committed changes, deleting files")
shutil.rmtree(args.package_name)
logging.debug("[-] alacrity:ROOT :: quiting")
sys.exit()
if __name__ == '__main__':
main()
| 36.554795 | 79 | 0.564737 |
import importlib
import logging
import os
import sys
import argparse
import shutil
from clint.textui import colored
try:
from alacrity import lib
except ImportError:
lib = importlib.import_module('lib', '../alacrity')
def main():
try:
from alacrity import version
except ImportError:
version = importlib.import_module('version', '../alacrity')
v = version.version()
parser = argparse.ArgumentParser(description="Alacrity : "
"Quickstart your Python "
"package from a terminal")
parser.add_argument('--make', action='store_true', help="Rebuild "
"persistence")
parser.add_argument('--debug', action='store_true', help="Display verbose "
"debug messages")
parser.add_argument('--version', action="version", version=v)
parser.add_argument('package_name')
args = parser.parse_args()
if args.make:
lib.rebuild_persistence()
if not args.package_name:
logging.error(" package_name is a required argument")
sys.exit()
if args.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.CRITICAL)
status = {
'structure_created': False,
'gitignore_created': False,
'setup_created': False,
'license_created': False,
'manifest_created': False,
'readme_created': False,
'requirements_created': False,
'tests_created': False,
'git_initialized': False,
'venv_created': False,
'sphinx_created': False
}
try:
try:
package_name = args.package_name
logging.debug("[-] Checking if the package already exists")
check_is_file = os.path.isfile(
"{0}/{0}/__init__.py".format(package_name))
if os.path.isdir(package_name) or check_is_file:
logging.debug("[-] Package already exists, "
"launching clean make prompt")
print(colored.red("[!] A package by that name already exists, "
"destroy and clean make? (y/n) : "), end="")
choice = input()
logging.debug("[-] Choice prompt input : {}".format(choice))
if choice == 'y':
logging.debug("[-] Removing existing package")
lib.remove_package(package_name)
elif choice == 'n':
logging.debug("[-] Clean make cancelled")
print(colored.red("[!] Please pick a different package "
"name, aborting."))
sys.exit()
else:
logging.error(colored.red(" Invalid choice"))
print(colored.red("[!] Invalid choice, aborting"))
sys.exit()
logging.debug("[-] Creating package structure")
lib.create_package_structure(package_name, status)
logging.debug("[-] Creating starter files in package")
author, version = lib.create_starter_files(package_name, status)
logging.debug("[-] Creating tests package in structure")
lib.create_tests_package(package_name, status)
logging.debug("[-] Launching git init submodule")
lib.git_init(package_name, status)
logging.debug("[-] Launching venv init submodule")
lib.venv_init(package_name, status)
logging.debug("[-] Launching sphinx init submodule")
lib.sphinx_init(package_name, author, version, status)
logging.debug("[-] Launching status reporter submodule")
lib.report_status(status)
print(colored.green("[|]"))
print(colored.green("[*] Package {} was created "
"successfully.".format(package_name)))
except EOFError:
print(colored.yellow("\n[!] Ctrl+C : Aborting package creation."))
sys.exit()
except KeyboardInterrupt:
print(colored.yellow("\n[!] Ctrl+C : Aborting package creation."))
if os.path.isdir(args.package_name):
logging.debug("[-] Rolling back committed changes, deleting files")
shutil.rmtree(args.package_name)
logging.debug("[-] alacrity:ROOT :: quiting")
sys.exit()
if __name__ == '__main__':
main()
| true | true |
f72bbf8d0fa245c9c5a1214dc4f10dd0bf1f40bc | 56,360 | py | Python | release/stubs.min/System/Windows/Forms/__init___parts/NumericUpDown.py | htlcnn/ironpython-stubs | 780d829e2104b2789d5f4d6f32b0ec9f2930ca03 | [
"MIT"
] | 182 | 2017-06-27T02:26:15.000Z | 2022-03-30T18:53:43.000Z | release/stubs.min/System/Windows/Forms/__init___parts/NumericUpDown.py | htlcnn/ironpython-stubs | 780d829e2104b2789d5f4d6f32b0ec9f2930ca03 | [
"MIT"
] | 28 | 2017-06-27T13:38:23.000Z | 2022-03-15T11:19:44.000Z | release/stubs.min/System/Windows/Forms/__init___parts/NumericUpDown.py | htlcnn/ironpython-stubs | 780d829e2104b2789d5f4d6f32b0ec9f2930ca03 | [
"MIT"
] | 67 | 2017-06-28T09:43:59.000Z | 2022-03-20T21:17:10.000Z | class NumericUpDown(UpDownBase,IComponent,IDisposable,IOleControl,IOleObject,IOleInPlaceObject,IOleInPlaceActiveObject,IOleWindow,IViewObject,IViewObject2,IPersist,IPersistStreamInit,IPersistPropertyBag,IPersistStorage,IQuickActivate,ISupportOleDropSource,IDropTarget,ISynchronizeInvoke,IWin32Window,IArrangedElement,IBindableComponent,IContainerControl,ISupportInitialize):
"""
Represents a Windows spin box (also known as an up-down control) that displays numeric values.
NumericUpDown()
"""
def AccessibilityNotifyClients(self,*args):
"""
AccessibilityNotifyClients(self: Control,accEvent: AccessibleEvents,objectID: int,childID: int)
Notifies the accessibility client applications of the specified
System.Windows.Forms.AccessibleEvents for the specified child control .
accEvent: The System.Windows.Forms.AccessibleEvents to notify the accessibility client applications of.
objectID: The identifier of the System.Windows.Forms.AccessibleObject.
childID: The child System.Windows.Forms.Control to notify of the accessible event.
AccessibilityNotifyClients(self: Control,accEvent: AccessibleEvents,childID: int)
Notifies the accessibility client applications of the specified
System.Windows.Forms.AccessibleEvents for the specified child control.
accEvent: The System.Windows.Forms.AccessibleEvents to notify the accessibility client applications of.
childID: The child System.Windows.Forms.Control to notify of the accessible event.
"""
pass
def AdjustFormScrollbars(self,*args):
"""
AdjustFormScrollbars(self: ContainerControl,displayScrollbars: bool)
displayScrollbars: true to show the scroll bars; otherwise,false.
"""
pass
def BeginInit(self):
"""
BeginInit(self: NumericUpDown)
Begins the initialization of a System.Windows.Forms.NumericUpDown control that is used on a form
or used by another component. The initialization occurs at run time.
"""
pass
def CreateAccessibilityInstance(self,*args):
"""
CreateAccessibilityInstance(self: NumericUpDown) -> AccessibleObject
Returns: A new System.Windows.Forms.AccessibleObject for the control.
"""
pass
def CreateControlsInstance(self,*args):
"""
CreateControlsInstance(self: Control) -> ControlCollection
Creates a new instance of the control collection for the control.
Returns: A new instance of System.Windows.Forms.Control.ControlCollection assigned to the control.
"""
pass
def CreateHandle(self,*args):
"""
CreateHandle(self: Control)
Creates a handle for the control.
"""
pass
def DefWndProc(self,*args):
"""
DefWndProc(self: Control,m: Message) -> Message
Sends the specified message to the default window procedure.
m: The Windows System.Windows.Forms.Message to process.
"""
pass
def DestroyHandle(self,*args):
"""
DestroyHandle(self: Control)
Destroys the handle associated with the control.
"""
pass
def Dispose(self):
"""
Dispose(self: ContainerControl,disposing: bool)
disposing: true to release both managed and unmanaged resources; false to release only unmanaged resources.
"""
pass
def DownButton(self):
"""
DownButton(self: NumericUpDown)
Decrements the value of the spin box (also known as an up-down control).
"""
pass
def EndInit(self):
"""
EndInit(self: NumericUpDown)
Ends the initialization of a System.Windows.Forms.NumericUpDown control that is used on a form
or used by another component. The initialization occurs at run time.
"""
pass
def GetAccessibilityObjectById(self,*args):
"""
GetAccessibilityObjectById(self: Control,objectId: int) -> AccessibleObject
Retrieves the specified System.Windows.Forms.AccessibleObject.
objectId: An Int32 that identifies the System.Windows.Forms.AccessibleObject to retrieve.
Returns: An System.Windows.Forms.AccessibleObject.
"""
pass
def GetAutoSizeMode(self,*args):
"""
GetAutoSizeMode(self: Control) -> AutoSizeMode
Retrieves a value indicating how a control will behave when its
System.Windows.Forms.Control.AutoSize property is enabled.
Returns: One of the System.Windows.Forms.AutoSizeMode values.
"""
pass
def GetScaledBounds(self,*args):
"""
GetScaledBounds(self: Control,bounds: Rectangle,factor: SizeF,specified: BoundsSpecified) -> Rectangle
Retrieves the bounds within which the control is scaled.
bounds: A System.Drawing.Rectangle that specifies the area for which to retrieve the display bounds.
factor: The height and width of the control's bounds.
specified: One of the values of System.Windows.Forms.BoundsSpecified that specifies the bounds of the
control to use when defining its size and position.
Returns: A System.Drawing.Rectangle representing the bounds within which the control is scaled.
"""
pass
def GetScrollState(self,*args):
"""
GetScrollState(self: ScrollableControl,bit: int) -> bool
Determines whether the specified flag has been set.
bit: The flag to check.
Returns: true if the specified flag has been set; otherwise,false.
"""
pass
def GetService(self,*args):
"""
GetService(self: Component,service: Type) -> object
Returns an object that represents a service provided by the System.ComponentModel.Component or
by its System.ComponentModel.Container.
service: A service provided by the System.ComponentModel.Component.
Returns: An System.Object that represents a service provided by the System.ComponentModel.Component,or
null if the System.ComponentModel.Component does not provide the specified service.
"""
pass
def GetStyle(self,*args):
"""
GetStyle(self: Control,flag: ControlStyles) -> bool
Retrieves the value of the specified control style bit for the control.
flag: The System.Windows.Forms.ControlStyles bit to return the value from.
Returns: true if the specified control style bit is set to true; otherwise,false.
"""
pass
def GetTopLevel(self,*args):
"""
GetTopLevel(self: Control) -> bool
Determines if the control is a top-level control.
Returns: true if the control is a top-level control; otherwise,false.
"""
pass
def InitLayout(self,*args):
"""
InitLayout(self: Control)
Called after the control has been added to another container.
"""
pass
def InvokeGotFocus(self,*args):
"""
InvokeGotFocus(self: Control,toInvoke: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.GotFocus event for the specified control.
toInvoke: The System.Windows.Forms.Control to assign the event to.
e: An System.EventArgs that contains the event data.
"""
pass
def InvokeLostFocus(self,*args):
"""
InvokeLostFocus(self: Control,toInvoke: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.LostFocus event for the specified control.
toInvoke: The System.Windows.Forms.Control to assign the event to.
e: An System.EventArgs that contains the event data.
"""
pass
def InvokeOnClick(self,*args):
"""
InvokeOnClick(self: Control,toInvoke: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.Click event for the specified control.
toInvoke: The System.Windows.Forms.Control to assign the System.Windows.Forms.Control.Click event to.
e: An System.EventArgs that contains the event data.
"""
pass
def InvokePaint(self,*args):
"""
InvokePaint(self: Control,c: Control,e: PaintEventArgs)
Raises the System.Windows.Forms.Control.Paint event for the specified control.
c: The System.Windows.Forms.Control to assign the System.Windows.Forms.Control.Paint event to.
e: An System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def InvokePaintBackground(self,*args):
"""
InvokePaintBackground(self: Control,c: Control,e: PaintEventArgs)
Raises the PaintBackground event for the specified control.
c: The System.Windows.Forms.Control to assign the System.Windows.Forms.Control.Paint event to.
e: An System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def IsInputChar(self,*args):
"""
IsInputChar(self: Control,charCode: Char) -> bool
Determines if a character is an input character that the control recognizes.
charCode: The character to test.
Returns: true if the character should be sent directly to the control and not preprocessed; otherwise,
false.
"""
pass
def IsInputKey(self,*args):
"""
IsInputKey(self: Control,keyData: Keys) -> bool
Determines whether the specified key is a regular input key or a special key that requires
preprocessing.
keyData: One of the System.Windows.Forms.Keys values.
Returns: true if the specified key is a regular input key; otherwise,false.
"""
pass
def MemberwiseClone(self,*args):
"""
MemberwiseClone(self: MarshalByRefObject,cloneIdentity: bool) -> MarshalByRefObject
Creates a shallow copy of the current System.MarshalByRefObject object.
cloneIdentity: false to delete the current System.MarshalByRefObject object's identity,which will cause the
object to be assigned a new identity when it is marshaled across a remoting boundary. A value of
false is usually appropriate. true to copy the current System.MarshalByRefObject object's
identity to its clone,which will cause remoting client calls to be routed to the remote server
object.
Returns: A shallow copy of the current System.MarshalByRefObject object.
MemberwiseClone(self: object) -> object
Creates a shallow copy of the current System.Object.
Returns: A shallow copy of the current System.Object.
"""
pass
def NotifyInvalidate(self,*args):
"""
NotifyInvalidate(self: Control,invalidatedArea: Rectangle)
Raises the System.Windows.Forms.Control.Invalidated event with a specified region of the control
to invalidate.
invalidatedArea: A System.Drawing.Rectangle representing the area to invalidate.
"""
pass
def OnAutoSizeChanged(self,*args):
"""
OnAutoSizeChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.AutoSizeChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnAutoValidateChanged(self,*args):
"""
OnAutoValidateChanged(self: ContainerControl,e: EventArgs)
Raises the System.Windows.Forms.ContainerControl.AutoValidateChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBackColorChanged(self,*args):
"""
OnBackColorChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BackColorChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBackgroundImageChanged(self,*args):
"""
OnBackgroundImageChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BackgroundImageChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBackgroundImageLayoutChanged(self,*args):
"""
OnBackgroundImageLayoutChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BackgroundImageLayoutChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBindingContextChanged(self,*args):
"""
OnBindingContextChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BindingContextChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnCausesValidationChanged(self,*args):
"""
OnCausesValidationChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.CausesValidationChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnChanged(self,*args):
"""
OnChanged(self: UpDownBase,source: object,e: EventArgs)
When overridden in a derived class,raises the Changed event.
source: The source of the event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnChangeUICues(self,*args):
"""
OnChangeUICues(self: Control,e: UICuesEventArgs)
Raises the System.Windows.Forms.Control.ChangeUICues event.
e: A System.Windows.Forms.UICuesEventArgs that contains the event data.
"""
pass
def OnClick(self,*args):
"""
OnClick(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.Click event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnClientSizeChanged(self,*args):
"""
OnClientSizeChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.ClientSizeChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnContextMenuChanged(self,*args):
"""
OnContextMenuChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.ContextMenuChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnContextMenuStripChanged(self,*args):
"""
OnContextMenuStripChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.ContextMenuStripChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnControlAdded(self,*args):
"""
OnControlAdded(self: Control,e: ControlEventArgs)
Raises the System.Windows.Forms.Control.ControlAdded event.
e: A System.Windows.Forms.ControlEventArgs that contains the event data.
"""
pass
def OnControlRemoved(self,*args):
"""
OnControlRemoved(self: Control,e: ControlEventArgs)
Raises the System.Windows.Forms.Control.ControlRemoved event.
e: A System.Windows.Forms.ControlEventArgs that contains the event data.
"""
pass
def OnCreateControl(self,*args):
""" OnCreateControl(self: ContainerControl) """
pass
def OnCursorChanged(self,*args):
"""
OnCursorChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.CursorChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDockChanged(self,*args):
"""
OnDockChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.DockChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDoubleClick(self,*args):
"""
OnDoubleClick(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.DoubleClick event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDpiChangedAfterParent(self,*args):
""" OnDpiChangedAfterParent(self: Control,e: EventArgs) """
pass
def OnDpiChangedBeforeParent(self,*args):
""" OnDpiChangedBeforeParent(self: Control,e: EventArgs) """
pass
def OnDragDrop(self,*args):
"""
OnDragDrop(self: Control,drgevent: DragEventArgs)
Raises the System.Windows.Forms.Control.DragDrop event.
drgevent: A System.Windows.Forms.DragEventArgs that contains the event data.
"""
pass
def OnDragEnter(self,*args):
"""
OnDragEnter(self: Control,drgevent: DragEventArgs)
Raises the System.Windows.Forms.Control.DragEnter event.
drgevent: A System.Windows.Forms.DragEventArgs that contains the event data.
"""
pass
def OnDragLeave(self,*args):
"""
OnDragLeave(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.DragLeave event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDragOver(self,*args):
"""
OnDragOver(self: Control,drgevent: DragEventArgs)
Raises the System.Windows.Forms.Control.DragOver event.
drgevent: A System.Windows.Forms.DragEventArgs that contains the event data.
"""
pass
def OnEnabledChanged(self,*args):
"""
OnEnabledChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.EnabledChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnEnter(self,*args):
"""
OnEnter(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.Enter event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnFontChanged(self,*args):
"""
OnFontChanged(self: UpDownBase,e: EventArgs)
Raises the System.Windows.Forms.Control.FontChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnForeColorChanged(self,*args):
"""
OnForeColorChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.ForeColorChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnGiveFeedback(self,*args):
"""
OnGiveFeedback(self: Control,gfbevent: GiveFeedbackEventArgs)
Raises the System.Windows.Forms.Control.GiveFeedback event.
gfbevent: A System.Windows.Forms.GiveFeedbackEventArgs that contains the event data.
"""
pass
def OnGotFocus(self,*args):
"""
OnGotFocus(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.GotFocus event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnHandleCreated(self,*args):
"""
OnHandleCreated(self: UpDownBase,e: EventArgs)
Raises the System.Windows.Forms.Control.HandleCreated event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnHandleDestroyed(self,*args):
"""
OnHandleDestroyed(self: UpDownBase,e: EventArgs)
Raises the System.Windows.Forms.Control.HandleDestroyed event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnHelpRequested(self,*args):
"""
OnHelpRequested(self: Control,hevent: HelpEventArgs)
Raises the System.Windows.Forms.Control.HelpRequested event.
hevent: A System.Windows.Forms.HelpEventArgs that contains the event data.
"""
pass
def OnImeModeChanged(self,*args):
"""
OnImeModeChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.ImeModeChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnInvalidated(self,*args):
"""
OnInvalidated(self: Control,e: InvalidateEventArgs)
Raises the System.Windows.Forms.Control.Invalidated event.
e: An System.Windows.Forms.InvalidateEventArgs that contains the event data.
"""
pass
def OnKeyDown(self,*args):
"""
OnKeyDown(self: NumericUpDown,e: KeyEventArgs)
Raises the System.Windows.Forms.Control.KeyDown event.
e: A System.Windows.Forms.KeyEventArgs that contains the event data.
"""
pass
def OnKeyPress(self,*args):
"""
OnKeyPress(self: Control,e: KeyPressEventArgs)
Raises the System.Windows.Forms.Control.KeyPress event.
e: A System.Windows.Forms.KeyPressEventArgs that contains the event data.
"""
pass
def OnKeyUp(self,*args):
"""
OnKeyUp(self: NumericUpDown,e: KeyEventArgs)
Raises the System.Windows.Forms.Control.KeyUp event.
e: A System.Windows.Forms.KeyEventArgs that contains the event data.
"""
pass
def OnLayout(self,*args):
"""
OnLayout(self: UpDownBase,e: LayoutEventArgs)
Raises the System.Windows.Forms.Control.Layout event.
e: A System.Windows.Forms.LayoutEventArgs that contains the event data.
"""
pass
def OnLeave(self,*args):
"""
OnLeave(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.Leave event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnLocationChanged(self,*args):
"""
OnLocationChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.LocationChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnLostFocus(self,*args):
"""
OnLostFocus(self: NumericUpDown,e: EventArgs)
Raises the System.Windows.Forms.Control.LostFocus event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnMarginChanged(self,*args):
"""
OnMarginChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.MarginChanged event.
e: A System.EventArgs that contains the event data.
"""
pass
def OnMouseCaptureChanged(self,*args):
"""
OnMouseCaptureChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.MouseCaptureChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnMouseClick(self,*args):
"""
OnMouseClick(self: Control,e: MouseEventArgs)
Raises the System.Windows.Forms.Control.MouseClick event.
e: An System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def OnMouseDoubleClick(self,*args):
"""
OnMouseDoubleClick(self: Control,e: MouseEventArgs)
Raises the System.Windows.Forms.Control.MouseDoubleClick event.
e: An System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def OnMouseDown(self,*args):
"""
OnMouseDown(self: UpDownBase,e: MouseEventArgs)
Raises the System.Windows.Forms.Control.MouseDown event.
e: A System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def OnMouseEnter(self,*args):
"""
OnMouseEnter(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.MouseEnter event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnMouseHover(self,*args):
"""
OnMouseHover(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.MouseHover event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnMouseLeave(self,*args):
"""
OnMouseLeave(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.MouseLeave event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnMouseMove(self,*args):
"""
OnMouseMove(self: Control,e: MouseEventArgs)
Raises the System.Windows.Forms.Control.MouseMove event.
e: A System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def OnMouseUp(self,*args):
"""
OnMouseUp(self: UpDownBase,mevent: MouseEventArgs)
Raises the System.Windows.Forms.Control.MouseUp event.
mevent: A System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def OnMouseWheel(self,*args):
"""
OnMouseWheel(self: UpDownBase,e: MouseEventArgs)
Raises the System.Windows.Forms.Control.MouseWheel event.
e: A System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def OnMove(self,*args):
"""
OnMove(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.Move event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnNotifyMessage(self,*args):
"""
OnNotifyMessage(self: Control,m: Message)
Notifies the control of Windows messages.
m: A System.Windows.Forms.Message that represents the Windows message.
"""
pass
def OnPaddingChanged(self,*args):
"""
OnPaddingChanged(self: ScrollableControl,e: EventArgs)
Raises the System.Windows.Forms.Control.PaddingChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnPaint(self,*args):
"""
OnPaint(self: UpDownBase,e: PaintEventArgs)
Raises the System.Windows.Forms.Control.Paint event.
e: A System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def OnPaintBackground(self,*args):
"""
OnPaintBackground(self: ScrollableControl,e: PaintEventArgs)
Paints the background of the control.
e: A System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def OnParentBackColorChanged(self,*args):
"""
OnParentBackColorChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BackColorChanged event when the
System.Windows.Forms.Control.BackColor property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentBackgroundImageChanged(self,*args):
"""
OnParentBackgroundImageChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BackgroundImageChanged event when the
System.Windows.Forms.Control.BackgroundImage property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentBindingContextChanged(self,*args):
"""
OnParentBindingContextChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.BindingContextChanged event when the
System.Windows.Forms.Control.BindingContext property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentChanged(self,*args):
"""
OnParentChanged(self: ContainerControl,e: EventArgs)
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentCursorChanged(self,*args):
"""
OnParentCursorChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.CursorChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentEnabledChanged(self,*args):
"""
OnParentEnabledChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.EnabledChanged event when the
System.Windows.Forms.Control.Enabled property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentFontChanged(self,*args):
"""
OnParentFontChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.FontChanged event when the
System.Windows.Forms.Control.Font property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentForeColorChanged(self,*args):
"""
OnParentForeColorChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.ForeColorChanged event when the
System.Windows.Forms.Control.ForeColor property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentRightToLeftChanged(self,*args):
"""
OnParentRightToLeftChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.RightToLeftChanged event when the
System.Windows.Forms.Control.RightToLeft property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnParentVisibleChanged(self,*args):
"""
OnParentVisibleChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.VisibleChanged event when the
System.Windows.Forms.Control.Visible property value of the control's container changes.
e: An System.EventArgs that contains the event data.
"""
pass
def OnPreviewKeyDown(self,*args):
"""
OnPreviewKeyDown(self: Control,e: PreviewKeyDownEventArgs)
Raises the System.Windows.Forms.Control.PreviewKeyDown event.
e: A System.Windows.Forms.PreviewKeyDownEventArgs that contains the event data.
"""
pass
def OnPrint(self,*args):
"""
OnPrint(self: Control,e: PaintEventArgs)
Raises the System.Windows.Forms.Control.Paint event.
e: A System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def OnQueryContinueDrag(self,*args):
"""
OnQueryContinueDrag(self: Control,qcdevent: QueryContinueDragEventArgs)
Raises the System.Windows.Forms.Control.QueryContinueDrag event.
qcdevent: A System.Windows.Forms.QueryContinueDragEventArgs that contains the event data.
"""
pass
def OnRegionChanged(self,*args):
"""
OnRegionChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.RegionChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnResize(self,*args):
"""
OnResize(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.Resize event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnRightToLeftChanged(self,*args):
"""
OnRightToLeftChanged(self: ScrollableControl,e: EventArgs)
e: An System.EventArgs that contains the event data.
"""
pass
def OnScroll(self,*args):
"""
OnScroll(self: ScrollableControl,se: ScrollEventArgs)
Raises the System.Windows.Forms.ScrollableControl.Scroll event.
se: A System.Windows.Forms.ScrollEventArgs that contains the event data.
"""
pass
def OnSizeChanged(self,*args):
"""
OnSizeChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.SizeChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnStyleChanged(self,*args):
"""
OnStyleChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.StyleChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnSystemColorsChanged(self,*args):
"""
OnSystemColorsChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.SystemColorsChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnTabIndexChanged(self,*args):
"""
OnTabIndexChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.TabIndexChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnTabStopChanged(self,*args):
"""
OnTabStopChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.TabStopChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnTextBoxKeyDown(self,*args):
"""
OnTextBoxKeyDown(self: UpDownBase,source: object,e: KeyEventArgs)
Raises the System.Windows.Forms.Control.KeyDown event.
source: The source of the event.
e: A System.Windows.Forms.KeyEventArgs that contains the event data.
"""
pass
def OnTextBoxKeyPress(self,*args):
"""
OnTextBoxKeyPress(self: NumericUpDown,source: object,e: KeyPressEventArgs)
Raises the System.Windows.Forms.Control.KeyPress event.
source: The source of the event.
e: A System.Windows.Forms.KeyPressEventArgs that contains the event data.
"""
pass
def OnTextBoxLostFocus(self,*args):
"""
OnTextBoxLostFocus(self: UpDownBase,source: object,e: EventArgs)
Raises the System.Windows.Forms.Control.LostFocus event.
source: The source of the event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnTextBoxResize(self,*args):
"""
OnTextBoxResize(self: UpDownBase,source: object,e: EventArgs)
Raises the System.Windows.Forms.Control.Resize event.
source: The source of the event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnTextBoxTextChanged(self,*args):
"""
OnTextBoxTextChanged(self: UpDownBase,source: object,e: EventArgs)
Raises the System.Windows.Forms.Control.TextChanged event.
source: The source of the event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnTextChanged(self,*args):
"""
OnTextChanged(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.TextChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnValidated(self,*args):
"""
OnValidated(self: Control,e: EventArgs)
Raises the System.Windows.Forms.Control.Validated event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnValidating(self,*args):
"""
OnValidating(self: Control,e: CancelEventArgs)
Raises the System.Windows.Forms.Control.Validating event.
e: A System.ComponentModel.CancelEventArgs that contains the event data.
"""
pass
def OnValueChanged(self,*args):
"""
OnValueChanged(self: NumericUpDown,e: EventArgs)
Raises the System.Windows.Forms.NumericUpDown.ValueChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnVisibleChanged(self,*args):
"""
OnVisibleChanged(self: ScrollableControl,e: EventArgs)
e: An System.EventArgs that contains the event data.
"""
pass
def ParseEditText(self,*args):
"""
ParseEditText(self: NumericUpDown)
Converts the text displayed in the spin box (also known as an up-down control) to a numeric
value and evaluates it.
"""
pass
def ProcessCmdKey(self,*args):
"""
ProcessCmdKey(self: ContainerControl,msg: Message,keyData: Keys) -> (bool,Message)
msg: A System.Windows.Forms.Message,passed by reference,that represents the window message to
process.
keyData: One of the System.Windows.Forms.Keys values that represents the key to process.
Returns: true if the character was processed by the control; otherwise,false.
"""
pass
def ProcessDialogChar(self,*args):
"""
ProcessDialogChar(self: ContainerControl,charCode: Char) -> bool
charCode: The character to process.
Returns: true if the character was processed by the control; otherwise,false.
"""
pass
def ProcessDialogKey(self,*args):
"""
ProcessDialogKey(self: ContainerControl,keyData: Keys) -> bool
keyData: One of the System.Windows.Forms.Keys values that represents the key to process.
Returns: true if the key was processed by the control; otherwise,false.
"""
pass
def ProcessKeyEventArgs(self,*args):
"""
ProcessKeyEventArgs(self: Control,m: Message) -> (bool,Message)
Processes a key message and generates the appropriate control events.
m: A System.Windows.Forms.Message,passed by reference,that represents the window message to
process.
Returns: true if the message was processed by the control; otherwise,false.
"""
pass
def ProcessKeyMessage(self,*args):
"""
ProcessKeyMessage(self: Control,m: Message) -> (bool,Message)
Processes a keyboard message.
m: A System.Windows.Forms.Message,passed by reference,that represents the window message to
process.
Returns: true if the message was processed by the control; otherwise,false.
"""
pass
def ProcessKeyPreview(self,*args):
"""
ProcessKeyPreview(self: Control,m: Message) -> (bool,Message)
Previews a keyboard message.
m: A System.Windows.Forms.Message,passed by reference,that represents the window message to
process.
Returns: true if the message was processed by the control; otherwise,false.
"""
pass
def ProcessMnemonic(self,*args):
"""
ProcessMnemonic(self: ContainerControl,charCode: Char) -> bool
charCode: The character to process.
Returns: true if the character was processed as a mnemonic by the control; otherwise,false.
"""
pass
def ProcessTabKey(self,*args):
"""
ProcessTabKey(self: ContainerControl,forward: bool) -> bool
Selects the next available control and makes it the active control.
forward: true to cycle forward through the controls in the System.Windows.Forms.ContainerControl;
otherwise,false.
Returns: true if a control is selected; otherwise,false.
"""
pass
def RaiseDragEvent(self,*args):
"""
RaiseDragEvent(self: Control,key: object,e: DragEventArgs)
Raises the appropriate drag event.
key: The event to raise.
e: A System.Windows.Forms.DragEventArgs that contains the event data.
"""
pass
def RaiseKeyEvent(self,*args):
"""
RaiseKeyEvent(self: Control,key: object,e: KeyEventArgs)
Raises the appropriate key event.
key: The event to raise.
e: A System.Windows.Forms.KeyEventArgs that contains the event data.
"""
pass
def RaiseMouseEvent(self,*args):
"""
RaiseMouseEvent(self: Control,key: object,e: MouseEventArgs)
Raises the appropriate mouse event.
key: The event to raise.
e: A System.Windows.Forms.MouseEventArgs that contains the event data.
"""
pass
def RaisePaintEvent(self,*args):
"""
RaisePaintEvent(self: Control,key: object,e: PaintEventArgs)
Raises the appropriate paint event.
key: The event to raise.
e: A System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def RecreateHandle(self,*args):
"""
RecreateHandle(self: Control)
Forces the re-creation of the handle for the control.
"""
pass
def RescaleConstantsForDpi(self,*args):
""" RescaleConstantsForDpi(self: UpDownBase,deviceDpiOld: int,deviceDpiNew: int) """
pass
def ResetMouseEventArgs(self,*args):
"""
ResetMouseEventArgs(self: Control)
Resets the control to handle the System.Windows.Forms.Control.MouseLeave event.
"""
pass
def RtlTranslateAlignment(self,*args):
"""
RtlTranslateAlignment(self: Control,align: ContentAlignment) -> ContentAlignment
Converts the specified System.Drawing.ContentAlignment to the appropriate
System.Drawing.ContentAlignment to support right-to-left text.
align: One of the System.Drawing.ContentAlignment values.
Returns: One of the System.Drawing.ContentAlignment values.
RtlTranslateAlignment(self: Control,align: LeftRightAlignment) -> LeftRightAlignment
Converts the specified System.Windows.Forms.LeftRightAlignment to the appropriate
System.Windows.Forms.LeftRightAlignment to support right-to-left text.
align: One of the System.Windows.Forms.LeftRightAlignment values.
Returns: One of the System.Windows.Forms.LeftRightAlignment values.
RtlTranslateAlignment(self: Control,align: HorizontalAlignment) -> HorizontalAlignment
Converts the specified System.Windows.Forms.HorizontalAlignment to the appropriate
System.Windows.Forms.HorizontalAlignment to support right-to-left text.
align: One of the System.Windows.Forms.HorizontalAlignment values.
Returns: One of the System.Windows.Forms.HorizontalAlignment values.
"""
pass
def RtlTranslateContent(self,*args):
"""
RtlTranslateContent(self: Control,align: ContentAlignment) -> ContentAlignment
Converts the specified System.Drawing.ContentAlignment to the appropriate
System.Drawing.ContentAlignment to support right-to-left text.
align: One of the System.Drawing.ContentAlignment values.
Returns: One of the System.Drawing.ContentAlignment values.
"""
pass
def RtlTranslateHorizontal(self,*args):
"""
RtlTranslateHorizontal(self: Control,align: HorizontalAlignment) -> HorizontalAlignment
Converts the specified System.Windows.Forms.HorizontalAlignment to the appropriate
System.Windows.Forms.HorizontalAlignment to support right-to-left text.
align: One of the System.Windows.Forms.HorizontalAlignment values.
Returns: One of the System.Windows.Forms.HorizontalAlignment values.
"""
pass
def RtlTranslateLeftRight(self,*args):
"""
RtlTranslateLeftRight(self: Control,align: LeftRightAlignment) -> LeftRightAlignment
Converts the specified System.Windows.Forms.LeftRightAlignment to the appropriate
System.Windows.Forms.LeftRightAlignment to support right-to-left text.
align: One of the System.Windows.Forms.LeftRightAlignment values.
Returns: One of the System.Windows.Forms.LeftRightAlignment values.
"""
pass
def ScaleControl(self,*args):
"""
ScaleControl(self: ScrollableControl,factor: SizeF,specified: BoundsSpecified)
factor: The factor by which the height and width of the control will be scaled.
specified: A System.Windows.Forms.BoundsSpecified value that specifies the bounds of the control to use
when defining its size and position.
"""
pass
def ScaleCore(self,*args):
"""
ScaleCore(self: ScrollableControl,dx: Single,dy: Single)
dx: The horizontal scaling factor.
dy: The vertical scaling factor.
"""
pass
def ScrollToControl(self,*args):
"""
ScrollToControl(self: ScrollableControl,activeControl: Control) -> Point
Calculates the scroll offset to the specified child control.
activeControl: The child control to scroll into view.
Returns: The upper-left hand System.Drawing.Point of the display area relative to the client area
required to scroll the control into view.
"""
pass
def Select(self,start=None,length=None):
"""
Select(self: ContainerControl,directed: bool,forward: bool)
directed: true to specify the direction of the control to select; otherwise,false.
forward: true to move forward in the tab order; false to move backward in the tab order.
"""
pass
def SetAutoSizeMode(self,*args):
"""
SetAutoSizeMode(self: Control,mode: AutoSizeMode)
Sets a value indicating how a control will behave when its System.Windows.Forms.Control.AutoSize
property is enabled.
mode: One of the System.Windows.Forms.AutoSizeMode values.
"""
pass
def SetBoundsCore(self,*args):
"""
SetBoundsCore(self: Control,x: int,y: int,width: int,height: int,specified: BoundsSpecified)
Performs the work of setting the specified bounds of this control.
x: The new System.Windows.Forms.Control.Left property value of the control.
y: The new System.Windows.Forms.Control.Top property value of the control.
width: The new System.Windows.Forms.Control.Width property value of the control.
height: The new System.Windows.Forms.Control.Height property value of the control.
specified: A bitwise combination of the System.Windows.Forms.BoundsSpecified values.
"""
pass
def SetClientSizeCore(self,*args):
"""
SetClientSizeCore(self: Control,x: int,y: int)
Sets the size of the client area of the control.
x: The client area width,in pixels.
y: The client area height,in pixels.
"""
pass
def SetDisplayRectLocation(self,*args):
"""
SetDisplayRectLocation(self: ScrollableControl,x: int,y: int)
Positions the display window to the specified value.
x: The horizontal offset at which to position the System.Windows.Forms.ScrollableControl.
y: The vertical offset at which to position the System.Windows.Forms.ScrollableControl.
"""
pass
def SetScrollState(self,*args):
"""
SetScrollState(self: ScrollableControl,bit: int,value: bool)
Sets the specified scroll state flag.
bit: The scroll state flag to set.
value: The value to set the flag.
"""
pass
def SetStyle(self,*args):
"""
SetStyle(self: Control,flag: ControlStyles,value: bool)
Sets a specified System.Windows.Forms.ControlStyles flag to either true or false.
flag: The System.Windows.Forms.ControlStyles bit to set.
value: true to apply the specified style to the control; otherwise,false.
"""
pass
def SetTopLevel(self,*args):
"""
SetTopLevel(self: Control,value: bool)
Sets the control as the top-level control.
value: true to set the control as the top-level control; otherwise,false.
"""
pass
def SetVisibleCore(self,*args):
"""
SetVisibleCore(self: Control,value: bool)
Sets the control to the specified visible state.
value: true to make the control visible; otherwise,false.
"""
pass
def SizeFromClientSize(self,*args):
"""
SizeFromClientSize(self: Control,clientSize: Size) -> Size
Determines the size of the entire control from the height and width of its client area.
clientSize: A System.Drawing.Size value representing the height and width of the control's client area.
Returns: A System.Drawing.Size value representing the height and width of the entire control.
"""
pass
def ToString(self):
"""
ToString(self: NumericUpDown) -> str
Returns a string that represents the System.Windows.Forms.NumericUpDown control.
Returns: A string that represents the current System.Windows.Forms.NumericUpDown.
"""
pass
def UpButton(self):
"""
UpButton(self: NumericUpDown)
Increments the value of the spin box (also known as an up-down control).
"""
pass
def UpdateBounds(self,*args):
"""
UpdateBounds(self: Control,x: int,y: int,width: int,height: int,clientWidth: int,clientHeight: int)
Updates the bounds of the control with the specified size,location,and client size.
x: The System.Drawing.Point.X coordinate of the control.
y: The System.Drawing.Point.Y coordinate of the control.
width: The System.Drawing.Size.Width of the control.
height: The System.Drawing.Size.Height of the control.
clientWidth: The client System.Drawing.Size.Width of the control.
clientHeight: The client System.Drawing.Size.Height of the control.
UpdateBounds(self: Control,x: int,y: int,width: int,height: int)
Updates the bounds of the control with the specified size and location.
x: The System.Drawing.Point.X coordinate of the control.
y: The System.Drawing.Point.Y coordinate of the control.
width: The System.Drawing.Size.Width of the control.
height: The System.Drawing.Size.Height of the control.
UpdateBounds(self: Control)
Updates the bounds of the control with the current size and location.
"""
pass
def UpdateDefaultButton(self,*args):
"""
UpdateDefaultButton(self: ContainerControl)
When overridden by a derived class,updates which button is the default button.
"""
pass
def UpdateEditText(self,*args):
"""
UpdateEditText(self: NumericUpDown)
Displays the current value of the spin box (also known as an up-down control) in the appropriate
format.
"""
pass
def UpdateStyles(self,*args):
"""
UpdateStyles(self: Control)
Forces the assigned styles to be reapplied to the control.
"""
pass
def UpdateZOrder(self,*args):
"""
UpdateZOrder(self: Control)
Updates the control in its parent's z-order.
"""
pass
def ValidateEditText(self,*args):
"""
ValidateEditText(self: NumericUpDown)
Validates and updates the text displayed in the spin box (also known as an up-down control).
"""
pass
def WndProc(self,*args):
"""
WndProc(self: UpDownBase,m: Message) -> Message
Processes Windows messages.
m: The Windows System.Windows.Forms.Message to process.
"""
pass
def __enter__(self,*args):
"""
__enter__(self: IDisposable) -> object
Provides the implementation of __enter__ for objects which implement IDisposable.
"""
pass
def __exit__(self,*args):
"""
__exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object)
Provides the implementation of __exit__ for objects which implement IDisposable.
"""
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __str__(self,*args):
pass
Accelerations=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a collection of sorted acceleration objects for the System.Windows.Forms.NumericUpDown control.
Get: Accelerations(self: NumericUpDown) -> NumericUpDownAccelerationCollection
"""
AutoScaleFactor=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the scaling factor between the current and design-time automatic scaling dimensions.
"""
CanEnableIme=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the System.Windows.Forms.Control.ImeMode property can be set to an active value,to enable IME support.
"""
CanRaiseEvents=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Determines if events can be raised on the control.
"""
ChangingText=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the text property is being changed internally by its parent class.
"""
CreateParams=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the required creation parameters when the control handle is created.
"""
DecimalPlaces=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the number of decimal places to display in the spin box (also known as an up-down control).
Get: DecimalPlaces(self: NumericUpDown) -> int
Set: DecimalPlaces(self: NumericUpDown)=value
"""
DefaultCursor=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the default cursor for the control.
"""
DefaultImeMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the default Input Method Editor (IME) mode supported by the control.
"""
DefaultMargin=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the space,in pixels,that is specified by default between controls.
"""
DefaultMaximumSize=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the length and height,in pixels,that is specified as the default maximum size of a control.
"""
DefaultMinimumSize=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the length and height,in pixels,that is specified as the default minimum size of a control.
"""
DefaultPadding=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the internal spacing,in pixels,of the contents of a control.
"""
DefaultSize=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the default size of the control.
"""
DesignMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value that indicates whether the System.ComponentModel.Component is currently in design mode.
"""
DoubleBuffered=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether this control should redraw its surface using a secondary buffer to reduce or prevent flicker.
"""
Events=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the list of event handlers that are attached to this System.ComponentModel.Component.
"""
FontHeight=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the height of the font of the control.
"""
Hexadecimal=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the spin box (also known as an up-down control) should display the value it contains in hexadecimal format.
Get: Hexadecimal(self: NumericUpDown) -> bool
Set: Hexadecimal(self: NumericUpDown)=value
"""
HScroll=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the horizontal scroll bar is visible.
"""
ImeModeBase=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the IME mode of a control.
"""
Increment=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the value to increment or decrement the spin box (also known as an up-down control) when the up or down buttons are clicked.
Get: Increment(self: NumericUpDown) -> Decimal
Set: Increment(self: NumericUpDown)=value
"""
Maximum=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the maximum value for the spin box (also known as an up-down control).
Get: Maximum(self: NumericUpDown) -> Decimal
Set: Maximum(self: NumericUpDown)=value
"""
Minimum=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the minimum allowed value for the spin box (also known as an up-down control).
Get: Minimum(self: NumericUpDown) -> Decimal
Set: Minimum(self: NumericUpDown)=value
"""
Padding=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the space between the edges of a System.Windows.Forms.NumericUpDown control and its contents.
Get: Padding(self: NumericUpDown) -> Padding
Set: Padding(self: NumericUpDown)=value
"""
RenderRightToLeft=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""This property is now obsolete.
"""
ResizeRedraw=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the control redraws itself when resized.
"""
ScaleChildren=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value that determines the scaling of child controls.
"""
ShowFocusCues=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the control should display focus rectangles.
"""
ShowKeyboardCues=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets a value indicating whether the user interface is in the appropriate state to show or hide keyboard accelerators.
"""
Text=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the text to be displayed in the System.Windows.Forms.NumericUpDown control.
Get: Text(self: NumericUpDown) -> str
Set: Text(self: NumericUpDown)=value
"""
ThousandsSeparator=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether a thousands separator is displayed in the spin box (also known as an up-down control) when appropriate.
Get: ThousandsSeparator(self: NumericUpDown) -> bool
Set: ThousandsSeparator(self: NumericUpDown)=value
"""
UserEdit=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether a value has been entered by the user.
"""
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the value assigned to the spin box (also known as an up-down control).
Get: Value(self: NumericUpDown) -> Decimal
Set: Value(self: NumericUpDown)=value
"""
VScroll=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets a value indicating whether the vertical scroll bar is visible.
"""
PaddingChanged=None
TextChanged=None
ValueChanged=None
| 24.261731 | 375 | 0.700053 | class NumericUpDown(UpDownBase,IComponent,IDisposable,IOleControl,IOleObject,IOleInPlaceObject,IOleInPlaceActiveObject,IOleWindow,IViewObject,IViewObject2,IPersist,IPersistStreamInit,IPersistPropertyBag,IPersistStorage,IQuickActivate,ISupportOleDropSource,IDropTarget,ISynchronizeInvoke,IWin32Window,IArrangedElement,IBindableComponent,IContainerControl,ISupportInitialize):
def AccessibilityNotifyClients(self,*args):
pass
def AdjustFormScrollbars(self,*args):
pass
def BeginInit(self):
pass
def CreateAccessibilityInstance(self,*args):
pass
def CreateControlsInstance(self,*args):
pass
def CreateHandle(self,*args):
pass
def DefWndProc(self,*args):
pass
def DestroyHandle(self,*args):
pass
def Dispose(self):
pass
def DownButton(self):
pass
def EndInit(self):
pass
def GetAccessibilityObjectById(self,*args):
pass
def GetAutoSizeMode(self,*args):
pass
def GetScaledBounds(self,*args):
pass
def GetScrollState(self,*args):
pass
def GetService(self,*args):
pass
def GetStyle(self,*args):
pass
def GetTopLevel(self,*args):
pass
def InitLayout(self,*args):
pass
def InvokeGotFocus(self,*args):
pass
def InvokeLostFocus(self,*args):
pass
def InvokeOnClick(self,*args):
pass
def InvokePaint(self,*args):
pass
def InvokePaintBackground(self,*args):
pass
def IsInputChar(self,*args):
pass
def IsInputKey(self,*args):
pass
def MemberwiseClone(self,*args):
pass
def NotifyInvalidate(self,*args):
pass
def OnAutoSizeChanged(self,*args):
pass
def OnAutoValidateChanged(self,*args):
pass
def OnBackColorChanged(self,*args):
pass
def OnBackgroundImageChanged(self,*args):
pass
def OnBackgroundImageLayoutChanged(self,*args):
pass
def OnBindingContextChanged(self,*args):
pass
def OnCausesValidationChanged(self,*args):
pass
def OnChanged(self,*args):
pass
def OnChangeUICues(self,*args):
pass
def OnClick(self,*args):
pass
def OnClientSizeChanged(self,*args):
pass
def OnContextMenuChanged(self,*args):
pass
def OnContextMenuStripChanged(self,*args):
pass
def OnControlAdded(self,*args):
pass
def OnControlRemoved(self,*args):
pass
def OnCreateControl(self,*args):
pass
def OnCursorChanged(self,*args):
pass
def OnDockChanged(self,*args):
pass
def OnDoubleClick(self,*args):
pass
def OnDpiChangedAfterParent(self,*args):
pass
def OnDpiChangedBeforeParent(self,*args):
pass
def OnDragDrop(self,*args):
pass
def OnDragEnter(self,*args):
pass
def OnDragLeave(self,*args):
pass
def OnDragOver(self,*args):
pass
def OnEnabledChanged(self,*args):
pass
def OnEnter(self,*args):
pass
def OnFontChanged(self,*args):
pass
def OnForeColorChanged(self,*args):
pass
def OnGiveFeedback(self,*args):
pass
def OnGotFocus(self,*args):
pass
def OnHandleCreated(self,*args):
pass
def OnHandleDestroyed(self,*args):
pass
def OnHelpRequested(self,*args):
pass
def OnImeModeChanged(self,*args):
pass
def OnInvalidated(self,*args):
pass
def OnKeyDown(self,*args):
pass
def OnKeyPress(self,*args):
pass
def OnKeyUp(self,*args):
pass
def OnLayout(self,*args):
pass
def OnLeave(self,*args):
pass
def OnLocationChanged(self,*args):
pass
def OnLostFocus(self,*args):
pass
def OnMarginChanged(self,*args):
pass
def OnMouseCaptureChanged(self,*args):
pass
def OnMouseClick(self,*args):
pass
def OnMouseDoubleClick(self,*args):
pass
def OnMouseDown(self,*args):
pass
def OnMouseEnter(self,*args):
pass
def OnMouseHover(self,*args):
pass
def OnMouseLeave(self,*args):
pass
def OnMouseMove(self,*args):
pass
def OnMouseUp(self,*args):
pass
def OnMouseWheel(self,*args):
pass
def OnMove(self,*args):
pass
def OnNotifyMessage(self,*args):
pass
def OnPaddingChanged(self,*args):
pass
def OnPaint(self,*args):
pass
def OnPaintBackground(self,*args):
pass
def OnParentBackColorChanged(self,*args):
pass
def OnParentBackgroundImageChanged(self,*args):
pass
def OnParentBindingContextChanged(self,*args):
pass
def OnParentChanged(self,*args):
pass
def OnParentCursorChanged(self,*args):
pass
def OnParentEnabledChanged(self,*args):
pass
def OnParentFontChanged(self,*args):
pass
def OnParentForeColorChanged(self,*args):
pass
def OnParentRightToLeftChanged(self,*args):
pass
def OnParentVisibleChanged(self,*args):
pass
def OnPreviewKeyDown(self,*args):
pass
def OnPrint(self,*args):
pass
def OnQueryContinueDrag(self,*args):
pass
def OnRegionChanged(self,*args):
pass
def OnResize(self,*args):
pass
def OnRightToLeftChanged(self,*args):
pass
def OnScroll(self,*args):
pass
def OnSizeChanged(self,*args):
pass
def OnStyleChanged(self,*args):
pass
def OnSystemColorsChanged(self,*args):
pass
def OnTabIndexChanged(self,*args):
pass
def OnTabStopChanged(self,*args):
pass
def OnTextBoxKeyDown(self,*args):
pass
def OnTextBoxKeyPress(self,*args):
pass
def OnTextBoxLostFocus(self,*args):
pass
def OnTextBoxResize(self,*args):
pass
def OnTextBoxTextChanged(self,*args):
pass
def OnTextChanged(self,*args):
pass
def OnValidated(self,*args):
pass
def OnValidating(self,*args):
pass
def OnValueChanged(self,*args):
pass
def OnVisibleChanged(self,*args):
pass
def ParseEditText(self,*args):
pass
def ProcessCmdKey(self,*args):
pass
def ProcessDialogChar(self,*args):
pass
def ProcessDialogKey(self,*args):
pass
def ProcessKeyEventArgs(self,*args):
pass
def ProcessKeyMessage(self,*args):
pass
def ProcessKeyPreview(self,*args):
pass
def ProcessMnemonic(self,*args):
pass
def ProcessTabKey(self,*args):
pass
def RaiseDragEvent(self,*args):
pass
def RaiseKeyEvent(self,*args):
pass
def RaiseMouseEvent(self,*args):
pass
def RaisePaintEvent(self,*args):
pass
def RecreateHandle(self,*args):
pass
def RescaleConstantsForDpi(self,*args):
pass
def ResetMouseEventArgs(self,*args):
pass
def RtlTranslateAlignment(self,*args):
pass
def RtlTranslateContent(self,*args):
pass
def RtlTranslateHorizontal(self,*args):
pass
def RtlTranslateLeftRight(self,*args):
pass
def ScaleControl(self,*args):
pass
def ScaleCore(self,*args):
pass
def ScrollToControl(self,*args):
pass
def Select(self,start=None,length=None):
pass
def SetAutoSizeMode(self,*args):
pass
def SetBoundsCore(self,*args):
pass
def SetClientSizeCore(self,*args):
pass
def SetDisplayRectLocation(self,*args):
pass
def SetScrollState(self,*args):
pass
def SetStyle(self,*args):
pass
def SetTopLevel(self,*args):
pass
def SetVisibleCore(self,*args):
pass
def SizeFromClientSize(self,*args):
pass
def ToString(self):
pass
def UpButton(self):
pass
def UpdateBounds(self,*args):
pass
def UpdateDefaultButton(self,*args):
pass
def UpdateEditText(self,*args):
pass
def UpdateStyles(self,*args):
pass
def UpdateZOrder(self,*args):
pass
def ValidateEditText(self,*args):
pass
def WndProc(self,*args):
pass
def __enter__(self,*args):
pass
def __exit__(self,*args):
pass
def __init__(self,*args):
pass
def __str__(self,*args):
pass
Accelerations=property(lambda self: object(),lambda self,v: None,lambda self: None)
AutoScaleFactor=property(lambda self: object(),lambda self,v: None,lambda self: None)
CanEnableIme=property(lambda self: object(),lambda self,v: None,lambda self: None)
CanRaiseEvents=property(lambda self: object(),lambda self,v: None,lambda self: None)
ChangingText=property(lambda self: object(),lambda self,v: None,lambda self: None)
CreateParams=property(lambda self: object(),lambda self,v: None,lambda self: None)
DecimalPlaces=property(lambda self: object(),lambda self,v: None,lambda self: None)
DefaultCursor=property(lambda self: object(),lambda self,v: None,lambda self: None)
DefaultImeMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
DefaultMargin=property(lambda self: object(),lambda self,v: None,lambda self: None)
DefaultMaximumSize=property(lambda self: object(),lambda self,v: None,lambda self: None)
DefaultMinimumSize=property(lambda self: object(),lambda self,v: None,lambda self: None)
DefaultPadding=property(lambda self: object(),lambda self,v: None,lambda self: None)
DefaultSize=property(lambda self: object(),lambda self,v: None,lambda self: None)
DesignMode=property(lambda self: object(),lambda self,v: None,lambda self: None)
DoubleBuffered=property(lambda self: object(),lambda self,v: None,lambda self: None)
Events=property(lambda self: object(),lambda self,v: None,lambda self: None)
FontHeight=property(lambda self: object(),lambda self,v: None,lambda self: None)
Hexadecimal=property(lambda self: object(),lambda self,v: None,lambda self: None)
HScroll=property(lambda self: object(),lambda self,v: None,lambda self: None)
ImeModeBase=property(lambda self: object(),lambda self,v: None,lambda self: None)
Increment=property(lambda self: object(),lambda self,v: None,lambda self: None)
Maximum=property(lambda self: object(),lambda self,v: None,lambda self: None)
Minimum=property(lambda self: object(),lambda self,v: None,lambda self: None)
Padding=property(lambda self: object(),lambda self,v: None,lambda self: None)
RenderRightToLeft=property(lambda self: object(),lambda self,v: None,lambda self: None)
ResizeRedraw=property(lambda self: object(),lambda self,v: None,lambda self: None)
ScaleChildren=property(lambda self: object(),lambda self,v: None,lambda self: None)
ShowFocusCues=property(lambda self: object(),lambda self,v: None,lambda self: None)
ShowKeyboardCues=property(lambda self: object(),lambda self,v: None,lambda self: None)
Text=property(lambda self: object(),lambda self,v: None,lambda self: None)
ThousandsSeparator=property(lambda self: object(),lambda self,v: None,lambda self: None)
UserEdit=property(lambda self: object(),lambda self,v: None,lambda self: None)
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
VScroll=property(lambda self: object(),lambda self,v: None,lambda self: None)
PaddingChanged=None
TextChanged=None
ValueChanged=None
| true | true |
f72bc0bbb4aca05776043b6a2bbf09555f2323ed | 498 | py | Python | barberShopControl/core/migrations/0017_reserva_res_servicos.py | YohaneSilva/Barbearia-Amizades | 8550cc5de7a0055be78f9e539de9e5c72a8c3a61 | [
"Apache-2.0"
] | 1 | 2020-03-19T21:09:24.000Z | 2020-03-19T21:09:24.000Z | barberShopControl/core/migrations/0017_reserva_res_servicos.py | YohaneSilva/Barbearia-Amizades | 8550cc5de7a0055be78f9e539de9e5c72a8c3a61 | [
"Apache-2.0"
] | null | null | null | barberShopControl/core/migrations/0017_reserva_res_servicos.py | YohaneSilva/Barbearia-Amizades | 8550cc5de7a0055be78f9e539de9e5c72a8c3a61 | [
"Apache-2.0"
] | null | null | null | # Generated by Django 3.0.5 on 2020-05-18 04:14
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('core', '0016_auto_20200516_0338'),
]
operations = [
migrations.AddField(
model_name='reserva',
name='res_servicos',
field=models.TextField(default=django.utils.timezone.now, verbose_name='Servicos'),
preserve_default=False,
),
]
| 23.714286 | 95 | 0.634538 |
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('core', '0016_auto_20200516_0338'),
]
operations = [
migrations.AddField(
model_name='reserva',
name='res_servicos',
field=models.TextField(default=django.utils.timezone.now, verbose_name='Servicos'),
preserve_default=False,
),
]
| true | true |
f72bc16d4a055439bb4d5c75416bba366abd7fa1 | 21,675 | py | Python | generated/nidcpower/nidcpower/_converters.py | AlexHearnNI/nimi-python | 39d7c4d9aa66d826c60a5d700982eff173e051e5 | [
"MIT"
] | null | null | null | generated/nidcpower/nidcpower/_converters.py | AlexHearnNI/nimi-python | 39d7c4d9aa66d826c60a5d700982eff173e051e5 | [
"MIT"
] | null | null | null | generated/nidcpower/nidcpower/_converters.py | AlexHearnNI/nimi-python | 39d7c4d9aa66d826c60a5d700982eff173e051e5 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# This file was generated
import nidcpower._visatype as _visatype
import nidcpower.errors as errors
import array
import datetime
import numbers
from functools import singledispatch
@singledispatch
def _convert_repeated_capabilities(arg, prefix): # noqa: F811
'''Base version that should not be called
Overall purpose is to convert the repeated capabilities to a list of strings with prefix from what ever form
Supported types:
- str - List (comma delimited)
- str - Range (using '-' or ':')
- str - single item
- int
- tuple
- range
- slice
Each instance should return a list of strings, without prefix
- '0' --> ['0']
- 0 --> ['0']
- '0, 1' --> ['0', '1']
- 'ScriptTrigger0, ScriptTrigger1' --> ['0', '1']
- '0-1' --> ['0', '1']
- '0:1' --> ['0', '1']
- '0-1,4' --> ['0', '1', '4']
- range(0, 2) --> ['0', '1']
- slice(0, 2) --> ['0', '1']
- (0, 1, 4) --> ['0', '1', '4']
- ('0-1', 4) --> ['0', '1', '4']
- (slice(0, 1), '2', [4, '5-6'], '7-9', '11:14', '16, 17') -->
['0', '2', '4', '5', '6', '7', '8', '9', '11', '12', '13', '14', '16', '17']
'''
raise errors.InvalidRepeatedCapabilityError('Invalid type', type(arg))
@_convert_repeated_capabilities.register(numbers.Integral) # noqa: F811
def _(repeated_capability, prefix):
'''Integer version'''
return [str(repeated_capability)]
# This parsing function duplicate the parsing in the driver, so if changes to the allowed format are made there, they will need to be replicated here.
@_convert_repeated_capabilities.register(str) # noqa: F811
def _(repeated_capability, prefix):
'''String version (this is the most complex)
We need to deal with a range ('0-3' or '0:3'), a list ('0,1,2,3') and a single item
'''
# First we deal with a list
rep_cap_list = repeated_capability.split(',')
if len(rep_cap_list) > 1:
# We have a list so call ourselves again to let the iterable instance handle it
return _convert_repeated_capabilities(rep_cap_list, prefix)
# Now we deal with ranges
# We remove any prefix and change ':' to '-'
r = repeated_capability.strip().replace(prefix, '').replace(':', '-')
rc = r.split('-')
if len(rc) > 1:
if len(rc) > 2:
raise errors.InvalidRepeatedCapabilityError("Multiple '-' or ':'", repeated_capability)
start = int(rc[0])
end = int(rc[1])
if end < start:
rng = range(start, end - 1, -1)
else:
rng = range(start, end + 1)
return _convert_repeated_capabilities(rng, prefix)
# If we made it here, it must be a simple item so we remove any prefix and return
return [repeated_capability.replace(prefix, '').strip()]
# We cannot use collections.abc.Iterable here because strings are also iterable and then this
# instance is what gets called instead of the string one.
@_convert_repeated_capabilities.register(list) # noqa: F811
@_convert_repeated_capabilities.register(range) # noqa: F811
@_convert_repeated_capabilities.register(tuple) # noqa: F811
def _(repeated_capability, prefix):
'''Iterable version - can handle lists, ranges, and tuples'''
rep_cap_list = []
for r in repeated_capability:
rep_cap_list += _convert_repeated_capabilities(r, prefix)
return rep_cap_list
@_convert_repeated_capabilities.register(slice) # noqa: F811
def _(repeated_capability, prefix):
'''slice version'''
def ifnone(a, b):
return b if a is None else a
# Turn the slice into a list and call ourselves again to let the iterable instance handle it
rng = range(ifnone(repeated_capability.start, 0), repeated_capability.stop, ifnone(repeated_capability.step, 1))
return _convert_repeated_capabilities(rng, prefix)
def convert_repeated_capabilities(repeated_capability, prefix=''):
'''Convert a repeated capabilities object to a comma delimited list
Args:
repeated_capability (str, list, tuple, slice, None) -
prefix (str) - common prefix for all strings
Returns:
rep_cal_list (list of str) - list of each repeated capability item with ranges expanded and prefix added
'''
# We need to explicitly handle None here. Everything else we can pass on to the singledispatch functions
if repeated_capability is None:
return []
return [prefix + r for r in _convert_repeated_capabilities(repeated_capability, prefix)]
def convert_repeated_capabilities_from_init(repeated_capability):
'''Convert a repeated capabilities object to a comma delimited list
Parameter list is so it can be called from the code generated __init__(). We know it is for channels when called
this was so we use a prefix of ''
Args:
repeated_capability (str, list, tuple, slice, None) -
Returns:
rep_cal (str) - comma delimited string of each repeated capability item with ranges expanded
'''
return ','.join(convert_repeated_capabilities(repeated_capability, ''))
def _convert_timedelta(value, library_type, scaling):
try:
# We first assume it is a datetime.timedelta object
scaled_value = value.total_seconds() * scaling
except AttributeError:
# If that doesn't work, assume it is a value in seconds
# cast to float so scaled_value is always a float. This allows `timeout=10` to work as expected
scaled_value = float(value) * scaling
# ctype integer types don't convert to int from float so we need to
if library_type in [_visatype.ViInt64, _visatype.ViInt32, _visatype.ViUInt32, _visatype.ViInt16, _visatype.ViUInt16, _visatype.ViInt8]:
scaled_value = int(scaled_value)
return library_type(scaled_value)
def convert_timedelta_to_seconds_real64(value):
return _convert_timedelta(value, _visatype.ViReal64, 1)
def convert_timedelta_to_milliseconds_int32(value):
return _convert_timedelta(value, _visatype.ViInt32, 1000)
def convert_timedeltas_to_seconds_real64(values):
return [convert_timedelta_to_seconds_real64(i) for i in values]
def convert_seconds_real64_to_timedeltas(seconds):
return [datetime.timedelta(seconds=i) for i in seconds]
def convert_month_to_timedelta(months):
return datetime.timedelta(days=(30.4167 * months))
# This converter is not called from the normal codegen path for function. Instead it is
# call from init and is a special case.
def convert_init_with_options_dictionary(values):
if type(values) is str:
init_with_options_string = values
else:
good_keys = {
'rangecheck': 'RangeCheck',
'queryinstrstatus': 'QueryInstrStatus',
'cache': 'Cache',
'simulate': 'Simulate',
'recordcoercions': 'RecordCoercions',
'interchangecheck': 'InterchangeCheck',
'driversetup': 'DriverSetup',
'range_check': 'RangeCheck',
'query_instr_status': 'QueryInstrStatus',
'record_coercions': 'RecordCoercions',
'interchange_check': 'InterchangeCheck',
'driver_setup': 'DriverSetup',
}
init_with_options = []
for k in sorted(values.keys()):
value = None
if k.lower() in good_keys and not good_keys[k.lower()] == 'DriverSetup':
value = good_keys[k.lower()] + ('=1' if values[k] is True else '=0')
elif k.lower() in good_keys and good_keys[k.lower()] == 'DriverSetup':
if not isinstance(values[k], dict):
raise TypeError('DriverSetup must be a dictionary')
value = 'DriverSetup=' + (';'.join([key + ':' + values[k][key] for key in sorted(values[k])]))
else:
value = k + ('=1' if values[k] is True else '=0')
init_with_options.append(value)
init_with_options_string = ','.join(init_with_options)
return init_with_options_string
# convert value to bytes
@singledispatch
def _convert_to_bytes(value): # noqa: F811
pass
@_convert_to_bytes.register(list) # noqa: F811
@_convert_to_bytes.register(bytes) # noqa: F811
@_convert_to_bytes.register(bytearray) # noqa: F811
@_convert_to_bytes.register(array.array) # noqa: F811
def _(value):
return value
@_convert_to_bytes.register(str) # noqa: F811
def _(value):
return value.encode()
def convert_to_bytes(value): # noqa: F811
return bytes(_convert_to_bytes(value))
# Let's run some tests
def test_convert_init_with_options_dictionary():
assert convert_init_with_options_dictionary('') == ''
assert convert_init_with_options_dictionary('Simulate=1') == 'Simulate=1'
assert convert_init_with_options_dictionary({'Simulate': True, }) == 'Simulate=1'
assert convert_init_with_options_dictionary({'Simulate': False, }) == 'Simulate=0'
assert convert_init_with_options_dictionary({'Simulate': True, 'Cache': False}) == 'Cache=0,Simulate=1'
assert convert_init_with_options_dictionary({'DriverSetup': {'Model': '5162 (4CH)', 'Bitfile': 'CustomProcessing'}}) == 'DriverSetup=Bitfile:CustomProcessing;Model:5162 (4CH)'
assert convert_init_with_options_dictionary({'Simulate': True, 'DriverSetup': {'Model': '5162 (4CH)', 'Bitfile': 'CustomProcessing'}}) == 'DriverSetup=Bitfile:CustomProcessing;Model:5162 (4CH),Simulate=1'
assert convert_init_with_options_dictionary({'simulate': True, 'cache': False}) == 'Cache=0,Simulate=1'
assert convert_init_with_options_dictionary({'driver_setup': {'Model': '5162 (4CH)', 'Bitfile': 'CustomProcessing'}}) == 'DriverSetup=Bitfile:CustomProcessing;Model:5162 (4CH)'
assert convert_init_with_options_dictionary({'simulate': True, 'driver_setup': {'Model': '5162 (4CH)', 'Bitfile': 'CustomProcessing'}}) == 'DriverSetup=Bitfile:CustomProcessing;Model:5162 (4CH),Simulate=1'
# Tests - time
def test_convert_timedelta_to_seconds_double():
test_result = convert_timedelta_to_seconds_real64(datetime.timedelta(seconds=10))
assert test_result.value == 10.0
assert isinstance(test_result, _visatype.ViReal64)
test_result = convert_timedelta_to_seconds_real64(datetime.timedelta(seconds=-1))
assert test_result.value == -1
assert isinstance(test_result, _visatype.ViReal64)
test_result = convert_timedelta_to_seconds_real64(10.5)
assert test_result.value == 10.5
assert isinstance(test_result, _visatype.ViReal64)
test_result = convert_timedelta_to_seconds_real64(-1)
assert test_result.value == -1
assert isinstance(test_result, _visatype.ViReal64)
def test_convert_timedelta_to_milliseconds_int32():
test_result = convert_timedelta_to_milliseconds_int32(datetime.timedelta(seconds=10))
assert test_result.value == 10000
assert isinstance(test_result, _visatype.ViInt32)
test_result = convert_timedelta_to_milliseconds_int32(datetime.timedelta(seconds=-1))
assert test_result.value == -1000
assert isinstance(test_result, _visatype.ViInt32)
test_result = convert_timedelta_to_milliseconds_int32(10.5)
assert test_result.value == 10500
assert isinstance(test_result, _visatype.ViInt32)
test_result = convert_timedelta_to_milliseconds_int32(-1)
assert test_result.value == -1000
assert isinstance(test_result, _visatype.ViInt32)
def test_convert_timedeltas_to_seconds_real64():
time_values = [10.5, -1]
test_result = convert_timedeltas_to_seconds_real64(time_values)
assert all([actual.value == expected for actual, expected in zip(test_result, time_values)])
assert all([isinstance(i, _visatype.ViReal64) for i in test_result])
timedeltas = [datetime.timedelta(seconds=s, milliseconds=ms) for s, ms in zip([10, -1], [500, 0])]
test_result = convert_timedeltas_to_seconds_real64(timedeltas)
assert all([actual.value == expected for actual, expected in zip(test_result, time_values)])
assert all([isinstance(i, _visatype.ViReal64) for i in test_result])
def test_convert_seconds_real64_to_timedeltas():
time_values = [10.5, -1]
timedeltas = convert_seconds_real64_to_timedeltas(time_values)
assert all([actual.total_seconds() == expected for actual, expected in zip(timedeltas, time_values)])
# Tests - repeated capabilities
def test_repeated_capabilies_string_channel():
test_result_list = convert_repeated_capabilities('0')
assert test_result_list == ['0']
test_result_list = convert_repeated_capabilities('r0')
assert test_result_list == ['r0']
test_result_list = convert_repeated_capabilities('0,1')
assert test_result_list == ['0', '1']
def test_repeated_capabilies_string_prefix():
test_result_list = convert_repeated_capabilities('0', prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0']
def test_repeated_capabilies_list_channel():
test_result_list = convert_repeated_capabilities(['0'])
assert test_result_list == ['0']
test_result_list = convert_repeated_capabilities(['r0'])
assert test_result_list == ['r0']
test_result_list = convert_repeated_capabilities(['0', '1'])
assert test_result_list == ['0', '1']
test_result_list = convert_repeated_capabilities([0, 1])
assert test_result_list == ['0', '1']
test_result_list = convert_repeated_capabilities([0, 1, '3'])
assert test_result_list == ['0', '1', '3']
def test_repeated_capabilies_list_prefix():
test_result_list = convert_repeated_capabilities(['ScriptTrigger0', 'ScriptTrigger1'], prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(['0'], prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0']
test_result_list = convert_repeated_capabilities(['0', '1'], prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities([0, 1], prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
def test_repeated_capabilies_tuple_channel():
test_result_list = convert_repeated_capabilities(('0'))
assert test_result_list == ['0']
test_result_list = convert_repeated_capabilities(('0,1'))
assert test_result_list == ['0', '1']
test_result_list = convert_repeated_capabilities(('0', '1'))
assert test_result_list == ['0', '1']
test_result_list = convert_repeated_capabilities((0, 1))
assert test_result_list == ['0', '1']
test_result_list = convert_repeated_capabilities((0, 1, '3'))
assert test_result_list == ['0', '1', '3']
def test_repeated_capabilies_tuple_prefix():
test_result_list = convert_repeated_capabilities(('ScriptTrigger0,ScriptTrigger1'), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(('0'), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0']
test_result_list = convert_repeated_capabilities(('0', '1'), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities((0, 1), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
def test_repeated_capabilies_unicode():
test_result_list = convert_repeated_capabilities(u'ScriptTrigger0,ScriptTrigger1', prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(u'ScriptTrigger0,ScriptTrigger1', prefix=u'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities('ScriptTrigger0,ScriptTrigger1', prefix=u'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
def test_repeated_capabilies_raw():
test_result_list = convert_repeated_capabilities(r'ScriptTrigger0,ScriptTrigger1', prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(r'ScriptTrigger0,ScriptTrigger1', prefix=r'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities('ScriptTrigger0,ScriptTrigger1', prefix=r'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(r'ScriptTrigger0,ScriptTrigger1', prefix=u'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(r'ScriptTrigger0,ScriptTrigger1', prefix=r'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(u'ScriptTrigger0,ScriptTrigger1', prefix=r'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
def test_repeated_capabilies_slice_channel():
test_result_list = convert_repeated_capabilities(slice(0, 1))
assert test_result_list == ['0']
test_result_list = convert_repeated_capabilities(slice(0, 2))
assert test_result_list == ['0', '1']
test_result_list = convert_repeated_capabilities(slice(None, 2))
assert test_result_list == ['0', '1']
def test_repeated_capabilies_mixed_channel():
test_result_list = convert_repeated_capabilities((slice(0, 1), '2', [4, '5-6'], '7-9', '11:14', '16, 17'))
assert test_result_list == ['0', '2', '4', '5', '6', '7', '8', '9', '11', '12', '13', '14', '16', '17']
test_result_list = convert_repeated_capabilities([slice(0, 1), '2', [4, '5-6'], '7-9', '11:14', '16, 17'])
assert test_result_list == ['0', '2', '4', '5', '6', '7', '8', '9', '11', '12', '13', '14', '16', '17']
def test_repeated_capabilies_mixed_prefix():
test_result_list = convert_repeated_capabilities((slice(0, 1), '2', [4, '5-6'], '7-9', '11:14', '16, 17'), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger2', 'ScriptTrigger4', 'ScriptTrigger5', 'ScriptTrigger6', 'ScriptTrigger7', 'ScriptTrigger8', 'ScriptTrigger9', 'ScriptTrigger11', 'ScriptTrigger12', 'ScriptTrigger13', 'ScriptTrigger14', 'ScriptTrigger16', 'ScriptTrigger17']
test_result_list = convert_repeated_capabilities([slice(0, 1), '2', [4, '5-6'], '7-9', '11:14', '16, 17'], prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger2', 'ScriptTrigger4', 'ScriptTrigger5', 'ScriptTrigger6', 'ScriptTrigger7', 'ScriptTrigger8', 'ScriptTrigger9', 'ScriptTrigger11', 'ScriptTrigger12', 'ScriptTrigger13', 'ScriptTrigger14', 'ScriptTrigger16', 'ScriptTrigger17']
def test_invalid_repeated_capabilies():
try:
convert_repeated_capabilities('6-8-10')
assert False
except errors.InvalidRepeatedCapabilityError:
pass
try:
convert_repeated_capabilities(['5', '6-8-10'])
assert False
except errors.InvalidRepeatedCapabilityError:
pass
try:
convert_repeated_capabilities(('5', '6-8-10'))
assert False
except errors.InvalidRepeatedCapabilityError:
pass
try:
convert_repeated_capabilities('5,6-8-10')
assert False
except errors.InvalidRepeatedCapabilityError:
pass
try:
convert_repeated_capabilities(5.0)
assert False
except errors.InvalidRepeatedCapabilityError:
pass
try:
convert_repeated_capabilities([5.0, '0'])
assert False
except errors.InvalidRepeatedCapabilityError:
pass
try:
convert_repeated_capabilities((5.0, '0'))
assert False
except errors.InvalidRepeatedCapabilityError:
pass
def test_repeated_capabilies_slice_prefix():
test_result_list = convert_repeated_capabilities(slice(0, 1), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0']
test_result_list = convert_repeated_capabilities(slice(0, 2), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(slice(None, 2), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
def test_repeated_capabilies_from_init():
test_result = convert_repeated_capabilities_from_init((slice(0, 1), '2', [4, '5-6'], '7-9', '11:14', '16, 17'))
assert test_result == '0,2,4,5,6,7,8,9,11,12,13,14,16,17'
def test_string_to_list_channel():
test_result = _convert_repeated_capabilities('r0', '')
assert test_result == ['r0']
test_result = _convert_repeated_capabilities(['0-2'], '')
assert test_result == ['0', '1', '2']
test_result = _convert_repeated_capabilities(['3:7'], '')
assert test_result == ['3', '4', '5', '6', '7']
test_result = _convert_repeated_capabilities(['2-0'], '')
assert test_result == ['2', '1', '0']
test_result = _convert_repeated_capabilities(['2:0'], '')
assert test_result == ['2', '1', '0']
def test_string_to_list_prefix():
test_result = _convert_repeated_capabilities(['ScriptTrigger3-ScriptTrigger7'], 'ScriptTrigger')
assert test_result == ['3', '4', '5', '6', '7']
test_result = _convert_repeated_capabilities(['ScriptTrigger3:ScriptTrigger7'], 'ScriptTrigger')
assert test_result == ['3', '4', '5', '6', '7']
test_result = _convert_repeated_capabilities(['ScriptTrigger2-ScriptTrigger0'], 'ScriptTrigger')
assert test_result == ['2', '1', '0']
test_result = _convert_repeated_capabilities(['ScriptTrigger2:ScriptTrigger0'], 'ScriptTrigger')
assert test_result == ['2', '1', '0']
| 44.875776 | 289 | 0.705421 |
import nidcpower._visatype as _visatype
import nidcpower.errors as errors
import array
import datetime
import numbers
from functools import singledispatch
@singledispatch
def _convert_repeated_capabilities(arg, prefix):
raise errors.InvalidRepeatedCapabilityError('Invalid type', type(arg))
@_convert_repeated_capabilities.register(numbers.Integral)
def _(repeated_capability, prefix):
return [str(repeated_capability)]
@_convert_repeated_capabilities.register(str)
def _(repeated_capability, prefix):
rep_cap_list = repeated_capability.split(',')
if len(rep_cap_list) > 1:
return _convert_repeated_capabilities(rep_cap_list, prefix)
r = repeated_capability.strip().replace(prefix, '').replace(':', '-')
rc = r.split('-')
if len(rc) > 1:
if len(rc) > 2:
raise errors.InvalidRepeatedCapabilityError("Multiple '-' or ':'", repeated_capability)
start = int(rc[0])
end = int(rc[1])
if end < start:
rng = range(start, end - 1, -1)
else:
rng = range(start, end + 1)
return _convert_repeated_capabilities(rng, prefix)
return [repeated_capability.replace(prefix, '').strip()]
@_convert_repeated_capabilities.register(list)
@_convert_repeated_capabilities.register(range)
@_convert_repeated_capabilities.register(tuple)
def _(repeated_capability, prefix):
rep_cap_list = []
for r in repeated_capability:
rep_cap_list += _convert_repeated_capabilities(r, prefix)
return rep_cap_list
@_convert_repeated_capabilities.register(slice)
def _(repeated_capability, prefix):
def ifnone(a, b):
return b if a is None else a
rng = range(ifnone(repeated_capability.start, 0), repeated_capability.stop, ifnone(repeated_capability.step, 1))
return _convert_repeated_capabilities(rng, prefix)
def convert_repeated_capabilities(repeated_capability, prefix=''):
if repeated_capability is None:
return []
return [prefix + r for r in _convert_repeated_capabilities(repeated_capability, prefix)]
def convert_repeated_capabilities_from_init(repeated_capability):
return ','.join(convert_repeated_capabilities(repeated_capability, ''))
def _convert_timedelta(value, library_type, scaling):
try:
scaled_value = value.total_seconds() * scaling
except AttributeError:
# cast to float so scaled_value is always a float. This allows `timeout=10` to work as expected
scaled_value = float(value) * scaling
# ctype integer types don't convert to int from float so we need to
if library_type in [_visatype.ViInt64, _visatype.ViInt32, _visatype.ViUInt32, _visatype.ViInt16, _visatype.ViUInt16, _visatype.ViInt8]:
scaled_value = int(scaled_value)
return library_type(scaled_value)
def convert_timedelta_to_seconds_real64(value):
return _convert_timedelta(value, _visatype.ViReal64, 1)
def convert_timedelta_to_milliseconds_int32(value):
return _convert_timedelta(value, _visatype.ViInt32, 1000)
def convert_timedeltas_to_seconds_real64(values):
return [convert_timedelta_to_seconds_real64(i) for i in values]
def convert_seconds_real64_to_timedeltas(seconds):
return [datetime.timedelta(seconds=i) for i in seconds]
def convert_month_to_timedelta(months):
return datetime.timedelta(days=(30.4167 * months))
def convert_init_with_options_dictionary(values):
if type(values) is str:
init_with_options_string = values
else:
good_keys = {
'rangecheck': 'RangeCheck',
'queryinstrstatus': 'QueryInstrStatus',
'cache': 'Cache',
'simulate': 'Simulate',
'recordcoercions': 'RecordCoercions',
'interchangecheck': 'InterchangeCheck',
'driversetup': 'DriverSetup',
'range_check': 'RangeCheck',
'query_instr_status': 'QueryInstrStatus',
'record_coercions': 'RecordCoercions',
'interchange_check': 'InterchangeCheck',
'driver_setup': 'DriverSetup',
}
init_with_options = []
for k in sorted(values.keys()):
value = None
if k.lower() in good_keys and not good_keys[k.lower()] == 'DriverSetup':
value = good_keys[k.lower()] + ('=1' if values[k] is True else '=0')
elif k.lower() in good_keys and good_keys[k.lower()] == 'DriverSetup':
if not isinstance(values[k], dict):
raise TypeError('DriverSetup must be a dictionary')
value = 'DriverSetup=' + (';'.join([key + ':' + values[k][key] for key in sorted(values[k])]))
else:
value = k + ('=1' if values[k] is True else '=0')
init_with_options.append(value)
init_with_options_string = ','.join(init_with_options)
return init_with_options_string
@singledispatch
def _convert_to_bytes(value):
pass
@_convert_to_bytes.register(list)
@_convert_to_bytes.register(bytes)
@_convert_to_bytes.register(bytearray)
@_convert_to_bytes.register(array.array)
def _(value):
return value
@_convert_to_bytes.register(str)
def _(value):
return value.encode()
def convert_to_bytes(value):
return bytes(_convert_to_bytes(value))
def test_convert_init_with_options_dictionary():
assert convert_init_with_options_dictionary('') == ''
assert convert_init_with_options_dictionary('Simulate=1') == 'Simulate=1'
assert convert_init_with_options_dictionary({'Simulate': True, }) == 'Simulate=1'
assert convert_init_with_options_dictionary({'Simulate': False, }) == 'Simulate=0'
assert convert_init_with_options_dictionary({'Simulate': True, 'Cache': False}) == 'Cache=0,Simulate=1'
assert convert_init_with_options_dictionary({'DriverSetup': {'Model': '5162 (4CH)', 'Bitfile': 'CustomProcessing'}}) == 'DriverSetup=Bitfile:CustomProcessing;Model:5162 (4CH)'
assert convert_init_with_options_dictionary({'Simulate': True, 'DriverSetup': {'Model': '5162 (4CH)', 'Bitfile': 'CustomProcessing'}}) == 'DriverSetup=Bitfile:CustomProcessing;Model:5162 (4CH),Simulate=1'
assert convert_init_with_options_dictionary({'simulate': True, 'cache': False}) == 'Cache=0,Simulate=1'
assert convert_init_with_options_dictionary({'driver_setup': {'Model': '5162 (4CH)', 'Bitfile': 'CustomProcessing'}}) == 'DriverSetup=Bitfile:CustomProcessing;Model:5162 (4CH)'
assert convert_init_with_options_dictionary({'simulate': True, 'driver_setup': {'Model': '5162 (4CH)', 'Bitfile': 'CustomProcessing'}}) == 'DriverSetup=Bitfile:CustomProcessing;Model:5162 (4CH),Simulate=1'
# Tests - time
def test_convert_timedelta_to_seconds_double():
test_result = convert_timedelta_to_seconds_real64(datetime.timedelta(seconds=10))
assert test_result.value == 10.0
assert isinstance(test_result, _visatype.ViReal64)
test_result = convert_timedelta_to_seconds_real64(datetime.timedelta(seconds=-1))
assert test_result.value == -1
assert isinstance(test_result, _visatype.ViReal64)
test_result = convert_timedelta_to_seconds_real64(10.5)
assert test_result.value == 10.5
assert isinstance(test_result, _visatype.ViReal64)
test_result = convert_timedelta_to_seconds_real64(-1)
assert test_result.value == -1
assert isinstance(test_result, _visatype.ViReal64)
def test_convert_timedelta_to_milliseconds_int32():
test_result = convert_timedelta_to_milliseconds_int32(datetime.timedelta(seconds=10))
assert test_result.value == 10000
assert isinstance(test_result, _visatype.ViInt32)
test_result = convert_timedelta_to_milliseconds_int32(datetime.timedelta(seconds=-1))
assert test_result.value == -1000
assert isinstance(test_result, _visatype.ViInt32)
test_result = convert_timedelta_to_milliseconds_int32(10.5)
assert test_result.value == 10500
assert isinstance(test_result, _visatype.ViInt32)
test_result = convert_timedelta_to_milliseconds_int32(-1)
assert test_result.value == -1000
assert isinstance(test_result, _visatype.ViInt32)
def test_convert_timedeltas_to_seconds_real64():
time_values = [10.5, -1]
test_result = convert_timedeltas_to_seconds_real64(time_values)
assert all([actual.value == expected for actual, expected in zip(test_result, time_values)])
assert all([isinstance(i, _visatype.ViReal64) for i in test_result])
timedeltas = [datetime.timedelta(seconds=s, milliseconds=ms) for s, ms in zip([10, -1], [500, 0])]
test_result = convert_timedeltas_to_seconds_real64(timedeltas)
assert all([actual.value == expected for actual, expected in zip(test_result, time_values)])
assert all([isinstance(i, _visatype.ViReal64) for i in test_result])
def test_convert_seconds_real64_to_timedeltas():
time_values = [10.5, -1]
timedeltas = convert_seconds_real64_to_timedeltas(time_values)
assert all([actual.total_seconds() == expected for actual, expected in zip(timedeltas, time_values)])
# Tests - repeated capabilities
def test_repeated_capabilies_string_channel():
test_result_list = convert_repeated_capabilities('0')
assert test_result_list == ['0']
test_result_list = convert_repeated_capabilities('r0')
assert test_result_list == ['r0']
test_result_list = convert_repeated_capabilities('0,1')
assert test_result_list == ['0', '1']
def test_repeated_capabilies_string_prefix():
test_result_list = convert_repeated_capabilities('0', prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0']
def test_repeated_capabilies_list_channel():
test_result_list = convert_repeated_capabilities(['0'])
assert test_result_list == ['0']
test_result_list = convert_repeated_capabilities(['r0'])
assert test_result_list == ['r0']
test_result_list = convert_repeated_capabilities(['0', '1'])
assert test_result_list == ['0', '1']
test_result_list = convert_repeated_capabilities([0, 1])
assert test_result_list == ['0', '1']
test_result_list = convert_repeated_capabilities([0, 1, '3'])
assert test_result_list == ['0', '1', '3']
def test_repeated_capabilies_list_prefix():
test_result_list = convert_repeated_capabilities(['ScriptTrigger0', 'ScriptTrigger1'], prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(['0'], prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0']
test_result_list = convert_repeated_capabilities(['0', '1'], prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities([0, 1], prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
def test_repeated_capabilies_tuple_channel():
test_result_list = convert_repeated_capabilities(('0'))
assert test_result_list == ['0']
test_result_list = convert_repeated_capabilities(('0,1'))
assert test_result_list == ['0', '1']
test_result_list = convert_repeated_capabilities(('0', '1'))
assert test_result_list == ['0', '1']
test_result_list = convert_repeated_capabilities((0, 1))
assert test_result_list == ['0', '1']
test_result_list = convert_repeated_capabilities((0, 1, '3'))
assert test_result_list == ['0', '1', '3']
def test_repeated_capabilies_tuple_prefix():
test_result_list = convert_repeated_capabilities(('ScriptTrigger0,ScriptTrigger1'), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(('0'), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0']
test_result_list = convert_repeated_capabilities(('0', '1'), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities((0, 1), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
def test_repeated_capabilies_unicode():
test_result_list = convert_repeated_capabilities(u'ScriptTrigger0,ScriptTrigger1', prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(u'ScriptTrigger0,ScriptTrigger1', prefix=u'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities('ScriptTrigger0,ScriptTrigger1', prefix=u'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
def test_repeated_capabilies_raw():
test_result_list = convert_repeated_capabilities(r'ScriptTrigger0,ScriptTrigger1', prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(r'ScriptTrigger0,ScriptTrigger1', prefix=r'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities('ScriptTrigger0,ScriptTrigger1', prefix=r'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(r'ScriptTrigger0,ScriptTrigger1', prefix=u'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(r'ScriptTrigger0,ScriptTrigger1', prefix=r'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(u'ScriptTrigger0,ScriptTrigger1', prefix=r'ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
def test_repeated_capabilies_slice_channel():
test_result_list = convert_repeated_capabilities(slice(0, 1))
assert test_result_list == ['0']
test_result_list = convert_repeated_capabilities(slice(0, 2))
assert test_result_list == ['0', '1']
test_result_list = convert_repeated_capabilities(slice(None, 2))
assert test_result_list == ['0', '1']
def test_repeated_capabilies_mixed_channel():
test_result_list = convert_repeated_capabilities((slice(0, 1), '2', [4, '5-6'], '7-9', '11:14', '16, 17'))
assert test_result_list == ['0', '2', '4', '5', '6', '7', '8', '9', '11', '12', '13', '14', '16', '17']
test_result_list = convert_repeated_capabilities([slice(0, 1), '2', [4, '5-6'], '7-9', '11:14', '16, 17'])
assert test_result_list == ['0', '2', '4', '5', '6', '7', '8', '9', '11', '12', '13', '14', '16', '17']
def test_repeated_capabilies_mixed_prefix():
test_result_list = convert_repeated_capabilities((slice(0, 1), '2', [4, '5-6'], '7-9', '11:14', '16, 17'), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger2', 'ScriptTrigger4', 'ScriptTrigger5', 'ScriptTrigger6', 'ScriptTrigger7', 'ScriptTrigger8', 'ScriptTrigger9', 'ScriptTrigger11', 'ScriptTrigger12', 'ScriptTrigger13', 'ScriptTrigger14', 'ScriptTrigger16', 'ScriptTrigger17']
test_result_list = convert_repeated_capabilities([slice(0, 1), '2', [4, '5-6'], '7-9', '11:14', '16, 17'], prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger2', 'ScriptTrigger4', 'ScriptTrigger5', 'ScriptTrigger6', 'ScriptTrigger7', 'ScriptTrigger8', 'ScriptTrigger9', 'ScriptTrigger11', 'ScriptTrigger12', 'ScriptTrigger13', 'ScriptTrigger14', 'ScriptTrigger16', 'ScriptTrigger17']
def test_invalid_repeated_capabilies():
try:
convert_repeated_capabilities('6-8-10')
assert False
except errors.InvalidRepeatedCapabilityError:
pass
try:
convert_repeated_capabilities(['5', '6-8-10'])
assert False
except errors.InvalidRepeatedCapabilityError:
pass
try:
convert_repeated_capabilities(('5', '6-8-10'))
assert False
except errors.InvalidRepeatedCapabilityError:
pass
try:
convert_repeated_capabilities('5,6-8-10')
assert False
except errors.InvalidRepeatedCapabilityError:
pass
try:
convert_repeated_capabilities(5.0)
assert False
except errors.InvalidRepeatedCapabilityError:
pass
try:
convert_repeated_capabilities([5.0, '0'])
assert False
except errors.InvalidRepeatedCapabilityError:
pass
try:
convert_repeated_capabilities((5.0, '0'))
assert False
except errors.InvalidRepeatedCapabilityError:
pass
def test_repeated_capabilies_slice_prefix():
test_result_list = convert_repeated_capabilities(slice(0, 1), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0']
test_result_list = convert_repeated_capabilities(slice(0, 2), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
test_result_list = convert_repeated_capabilities(slice(None, 2), prefix='ScriptTrigger')
assert test_result_list == ['ScriptTrigger0', 'ScriptTrigger1']
def test_repeated_capabilies_from_init():
test_result = convert_repeated_capabilities_from_init((slice(0, 1), '2', [4, '5-6'], '7-9', '11:14', '16, 17'))
assert test_result == '0,2,4,5,6,7,8,9,11,12,13,14,16,17'
def test_string_to_list_channel():
test_result = _convert_repeated_capabilities('r0', '')
assert test_result == ['r0']
test_result = _convert_repeated_capabilities(['0-2'], '')
assert test_result == ['0', '1', '2']
test_result = _convert_repeated_capabilities(['3:7'], '')
assert test_result == ['3', '4', '5', '6', '7']
test_result = _convert_repeated_capabilities(['2-0'], '')
assert test_result == ['2', '1', '0']
test_result = _convert_repeated_capabilities(['2:0'], '')
assert test_result == ['2', '1', '0']
def test_string_to_list_prefix():
test_result = _convert_repeated_capabilities(['ScriptTrigger3-ScriptTrigger7'], 'ScriptTrigger')
assert test_result == ['3', '4', '5', '6', '7']
test_result = _convert_repeated_capabilities(['ScriptTrigger3:ScriptTrigger7'], 'ScriptTrigger')
assert test_result == ['3', '4', '5', '6', '7']
test_result = _convert_repeated_capabilities(['ScriptTrigger2-ScriptTrigger0'], 'ScriptTrigger')
assert test_result == ['2', '1', '0']
test_result = _convert_repeated_capabilities(['ScriptTrigger2:ScriptTrigger0'], 'ScriptTrigger')
assert test_result == ['2', '1', '0']
| true | true |
f72bc1b96d03b897b764119148a72447728fb58c | 3,110 | py | Python | DQMServices/Components/python/test/create_filePB_ref_cfg.py | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | DQMServices/Components/python/test/create_filePB_ref_cfg.py | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | DQMServices/Components/python/test/create_filePB_ref_cfg.py | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | import FWCore.ParameterSet.Config as cms
import DQMServices.Components.test.checkBooking as booking
import DQMServices.Components.test.createElements as c
import sys
process = cms.Process("TEST")
# load DQM
process.load("DQMServices.Core.DQM_cfg")
process.load("DQMServices.Components.DQMEnvironment_cfi")
b = booking.BookingParams(sys.argv)
b.doCheck(testOnly=False)
process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(10))
process.source = cms.Source("EmptySource",
firstLuminosityBlock = cms.untracked.uint32(1),
firstEvent = cms.untracked.uint32(1),
numberEventsInLuminosityBlock = cms.untracked.uint32(1))
elements = c.createElements()
readRunElements = c.createReadRunElements()
readLumiElements = c.createReadLumiElements()
process.filler = cms.EDAnalyzer("DummyBookFillDQMStore" + b.mt_postfix(),
folder = cms.untracked.string("TestFolder/"),
elements = cms.untracked.VPSet(*elements),
fillRuns = cms.untracked.bool(True),
fillLumis = cms.untracked.bool(True),
book_at_constructor = cms.untracked.bool(b.getBookLogic('CTOR')),
book_at_beginJob = cms.untracked.bool(b.getBookLogic('BJ')),
book_at_beginRun = cms.untracked.bool(b.getBookLogic('BR')))
process.out = cms.OutputModule("DQMRootOutputModule",
fileName = cms.untracked.string("dqm_filePB_ref.root"))
process.p = cms.Path(process.filler)
process.o = cms.EndPath(process.out)
process.schedule = cms.Schedule(
process.p,
process.o
)
process.add_(cms.Service("DQMStore"))
if b.multithread():
process.out.enableMultiThread = cms.untracked.bool(True)
process.DQMStore.enableMultiThread = cms.untracked.bool(True)
process.options = cms.untracked.PSet(
numberOfThreads = cms.untracked.uint32(4),
numberOfStreams = cms.untracked.uint32(4)
)
if len(sys.argv) > 3:
if sys.argv[3] == "ForceReset":
print "Forcing Reset of histograms at every Run Transition."
process.DQMStore.forceResetOnBeginRun = cms.untracked.bool(True)
#----------------------------------------------------------#
### global options Online ###
process.DQMStore.LSbasedMode = cms.untracked.bool(False)
process.DQMStore.verbose = cms.untracked.int32(5)
process.dqmSaver.workflow = ''
process.dqmSaver.convention = 'FilterUnit'
process.dqmSaver.saveByLumiSection = -1
process.dqmSaver.fileFormat = cms.untracked.string('ROOT')
process.dqmSaver.fakeFilterUnitMode = cms.untracked.bool(True)
#process.add_(cms.Service("Tracer"))
| 39.367089 | 196 | 0.586174 | import FWCore.ParameterSet.Config as cms
import DQMServices.Components.test.checkBooking as booking
import DQMServices.Components.test.createElements as c
import sys
process = cms.Process("TEST")
process.load("DQMServices.Core.DQM_cfg")
process.load("DQMServices.Components.DQMEnvironment_cfi")
b = booking.BookingParams(sys.argv)
b.doCheck(testOnly=False)
process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(10))
process.source = cms.Source("EmptySource",
firstLuminosityBlock = cms.untracked.uint32(1),
firstEvent = cms.untracked.uint32(1),
numberEventsInLuminosityBlock = cms.untracked.uint32(1))
elements = c.createElements()
readRunElements = c.createReadRunElements()
readLumiElements = c.createReadLumiElements()
process.filler = cms.EDAnalyzer("DummyBookFillDQMStore" + b.mt_postfix(),
folder = cms.untracked.string("TestFolder/"),
elements = cms.untracked.VPSet(*elements),
fillRuns = cms.untracked.bool(True),
fillLumis = cms.untracked.bool(True),
book_at_constructor = cms.untracked.bool(b.getBookLogic('CTOR')),
book_at_beginJob = cms.untracked.bool(b.getBookLogic('BJ')),
book_at_beginRun = cms.untracked.bool(b.getBookLogic('BR')))
process.out = cms.OutputModule("DQMRootOutputModule",
fileName = cms.untracked.string("dqm_filePB_ref.root"))
process.p = cms.Path(process.filler)
process.o = cms.EndPath(process.out)
process.schedule = cms.Schedule(
process.p,
process.o
)
process.add_(cms.Service("DQMStore"))
if b.multithread():
process.out.enableMultiThread = cms.untracked.bool(True)
process.DQMStore.enableMultiThread = cms.untracked.bool(True)
process.options = cms.untracked.PSet(
numberOfThreads = cms.untracked.uint32(4),
numberOfStreams = cms.untracked.uint32(4)
)
if len(sys.argv) > 3:
if sys.argv[3] == "ForceReset":
print "Forcing Reset of histograms at every Run Transition."
process.DQMStore.forceResetOnBeginRun = cms.untracked.bool(True)
| false | true |
f72bc1d5aefbd73272c909b63fc43b86465f5c78 | 29,314 | py | Python | tensor2tensor/layers/discretization.py | spacegoing/t2t_caps | ded708b738fa8966eb7544708c4a785479da4c3c | [
"Apache-2.0"
] | null | null | null | tensor2tensor/layers/discretization.py | spacegoing/t2t_caps | ded708b738fa8966eb7544708c4a785479da4c3c | [
"Apache-2.0"
] | null | null | null | tensor2tensor/layers/discretization.py | spacegoing/t2t_caps | ded708b738fa8966eb7544708c4a785479da4c3c | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# 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.
"""Discretization bottlenecks used to train discrete latent variables."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from functools import partial
# Dependency imports
from tensor2tensor.layers import common_layers
import tensorflow as tf
from tensorflow.python.training import moving_averages
def project_hidden(x, projection_tensors, hidden_size, num_blocks):
"""Project encoder hidden state into block_dim using projection tensors.
Args:
x: Encoder hidden state of shape [-1, hidden_size].
projection_tensors: Projection tensors used to project the hidden state.
hidden_size: Dimension of the latent space.
num_blocks: Number of blocks in DVQ.
Returns:
Projected states of shape [-1, num_blocks, block_dim].
"""
x = tf.reshape(x, shape=[1, -1, hidden_size])
x_tiled = tf.reshape(
tf.tile(x, multiples=[num_blocks, 1, 1]),
shape=[num_blocks, -1, hidden_size])
x_projected = tf.matmul(x_tiled, projection_tensors)
x_projected = tf.transpose(x_projected, perm=[1, 0, 2])
return x_projected
def slice_hidden(x, hidden_size, num_blocks):
"""Slice encoder hidden state into block_dim.
Args:
x: Encoder hidden state of shape [-1, hidden_size].
hidden_size: Dimension of the latent space.
num_blocks: Number of blocks in DVQ.
Returns:
Sliced states of shape [-1, num_blocks, block_dim].
"""
block_dim = int(hidden_size // num_blocks)
x_sliced = tf.reshape(x, shape=[-1, num_blocks, block_dim])
return x_sliced
def nearest_neighbor(x,
means,
block_v_size,
random_top_k=1,
soft_em=False,
num_samples=1):
"""Find the nearest element in means to elements in x.
Args:
x: Batch of encoder continuous latent states sliced/projected into shape
[-1, num_blocks, block_dim].
means: Embedding table of shpae [num_blocks, block_v_size, block_dim].
block_v_size: Number of table entries per block.
random_top_k: Noisy top-k if this is bigger than 1 (Default: 1).
soft_em: If True then use soft EM rather than hard EM (Default: False).
num_samples: Number of samples to take in soft EM (Default: 1).
Returns:
Tensor with nearest element in mean encoded in one-hot notation
and distances.
"""
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keep_dims=True)
means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keep_dims=True)
scalar_prod = tf.matmul(
tf.transpose(x, perm=[1, 0, 2]), tf.transpose(means, perm=[0, 2, 1]))
scalar_prod = tf.transpose(scalar_prod, perm=[1, 0, 2])
dist = x_norm_sq + tf.transpose(
means_norm_sq, perm=[2, 0, 1]) - 2 * scalar_prod
# computing cluster probabilities
if soft_em:
num_blocks = common_layers.shape_list(dist)[1]
nearest_idx = tf.stack(
[
tf.multinomial(-dist[:, i, :], num_samples=num_samples)
for i in range(num_blocks)
],
axis=1)
nearest_hot = tf.one_hot(nearest_idx, depth=block_v_size)
nearest_hot = tf.reduce_mean(nearest_hot, axis=-2)
else:
if random_top_k > 1:
_, top_k_idx = tf.nn.top_k(-dist, k=random_top_k)
nearest_idx = tf.gather(
top_k_idx,
tf.random_uniform(
[1], minval=0, maxval=random_top_k - 1, dtype=tf.int32),
axis=-1)
else:
nearest_idx = tf.argmax(-dist, axis=-1)
nearest_hot = tf.one_hot(nearest_idx, block_v_size)
return nearest_hot
def embedding_lookup(x,
means,
num_blocks,
block_v_size,
random_top_k=1,
soft_em=False,
num_samples=1):
"""Compute nearest neighbors and loss for training the embeddings via DVQ.
Args:
x: Batch of encoder continuous latent states sliced/projected into shape
[-1, num_blocks, block_dim].
means: Embedding table of shape [num_blocks, block_v_size, block_dim].
num_blocks: Number of blocks in DVQ.
block_v_size: Number of table entries per block.
random_top_k: Noisy top-k if this is bigger than 1 (Default: 1).
soft_em: If True then use soft EM rather than hard EM (Default: False).
num_samples: Number of samples to use for soft EM (Default: 1).
Returns:
The nearest neighbor in one hot form, the nearest neighbor itself, the
commitment loss, embedding training loss and distances.
"""
x_means_hot = nearest_neighbor(
x,
means,
block_v_size,
random_top_k,
soft_em=soft_em,
num_samples=num_samples)
x_means_hot_flat = tf.reshape(x_means_hot, [-1, num_blocks, block_v_size])
x_means = tf.matmul(tf.transpose(x_means_hot_flat, perm=[1, 0, 2]), means)
x_means = tf.transpose(x_means, [1, 0, 2])
q_loss = tf.reduce_mean(tf.square((tf.stop_gradient(x) - x_means)))
e_loss = tf.reduce_mean(tf.square(x - tf.stop_gradient(x_means)))
return x_means_hot, x_means, q_loss, e_loss
def bit_to_int(x_bit, num_bits, base=2):
"""Turn x_bit representing numbers bitwise (lower-endian) to int tensor.
Args:
x_bit: Tensor containing numbers in a particular base to be converted to
int.
num_bits: Number of bits in the representation.
base: Base of the representation.
Returns:
Integer representation of this number.
"""
x_l = tf.stop_gradient(tf.to_int32(tf.reshape(x_bit, [-1, num_bits])))
x_labels = []
for i in range(num_bits):
x_labels.append(x_l[:, i] * tf.to_int32(base)**tf.to_int32(i))
res = sum(x_labels)
return tf.to_int32(tf.reshape(res, common_layers.shape_list(x_bit)[:-1]))
def int_to_bit(x_int, num_bits, base=2):
"""Turn x_int representing numbers into a bitwise (lower-endian) tensor.
Args:
x_int: Tensor containing integer to be converted into base notation.
num_bits: Number of bits in the representation.
base: Base of the representation.
Returns:
Corresponding number expressed in base.
"""
x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1))
x_labels = []
for i in range(num_bits):
x_labels.append(
tf.floormod(
tf.floordiv(tf.to_int32(x_l),
tf.to_int32(base)**i), tf.to_int32(base)))
res = tf.concat(x_labels, axis=-1)
return tf.to_float(res)
def int_to_bit_embed(x_int, num_bits, embedding_size, base=2):
"""Turn x_int into a bitwise (lower-endian) tensor and embed densly."""
shape = common_layers.shape_list(x_int)
inputs = int_to_bit(x_int, num_bits, base=base)
inputs = tf.reshape(inputs, shape[:-1] + [shape[-1] * 8])
inputs = 2.0 * tf.to_float(inputs) - 1.0 # Move from 0/1 to -1/1.
return tf.layers.dense(inputs, embedding_size, name="int_to_bit_embed")
def embed(x,
hidden_size,
z_size,
filter_size,
name,
bottleneck_kind="dvq",
soft_em=False,
num_blocks=2,
num_residuals=1,
block_v_size=None,
means=None):
"""Embedding function that takes discrete latent and returns embedding.
Args:
x: Input to the discretization bottleneck.
hidden_size: Dimension of the latent state.
z_size: Number of bits used to produce discrete code; discrete codes range
from 1 to 2**z_size.
filter_size: Filter size to be used for the embedding function.
name: Name for the bottleneck scope.
bottleneck_kind: Kind of discretization bottleneck to use; one of dvq,
semhash, gumbel-softmax (Default: dvq).
soft_em: If True then it uses a multi-sample version of EM (Default: False).
num_blocks: Number of blocks in DVQ (Default: 2).
num_residuals: Number of residuals (Default: 1).
block_v_size: Number of embedding entries per block (Default: None).
means: The embedding table for dvq (Default: None).
Returns:
Continuous embedding to be passed on to the decoder.
Raises:
ValueError: For unknown or missing arguments.
"""
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
if bottleneck_kind == "semhash":
c = int_to_bit(x, z_size)
h1a = tf.layers.dense(c, filter_size, name="vch1a")
h1b = tf.layers.dense(1.0 - c, filter_size, name="vch1b")
h1 = h1a + h1b
elif bottleneck_kind == "gumbel-softmax":
hot = tf.one_hot(x, 2**z_size)
h1 = tf.layers.dense(hot, hidden_size, name="dae_dense")
elif bottleneck_kind == "dvq":
if block_v_size is None:
raise ValueError("Bottleneck kind is dvq but block_v_size is None.")
if soft_em:
assert num_residuals == 1
x_hot_flat = tf.reshape(x, shape=[-1, num_blocks, block_v_size])
h1 = tf.matmul(tf.transpose(x_hot_flat, perm=[1, 0, 2]), means[0])
h1 = tf.transpose(h1, perm=[1, 0, 2])
new_shape = common_layers.shape_list(x)
new_shape[-1] = hidden_size
h1 = tf.reshape(h1, shape=new_shape)
else:
shape_x = common_layers.shape_list(x)
x_flat = tf.reshape(x, [-1, 1])
c = int_to_bit(x_flat, num_bits=z_size, base=2)
shape = common_layers.shape_list(c)
new_shape = shape
new_shape[-1] = num_residuals
new_shape.append(num_blocks)
new_shape.append(int(z_size / (num_residuals * num_blocks)))
c = tf.to_int32(tf.reshape(c, shape=new_shape))
h1_shape = shape_x
h1_shape.append(hidden_size)
h1 = tf.zeros(dtype=tf.float32, shape=h1_shape)
for i in range(num_residuals):
c_residual = bit_to_int(
c[:, :, i, :, :],
num_bits=int(z_size / (num_residuals * num_blocks)),
base=2)
c_hot = tf.one_hot(c_residual, depth=block_v_size, axis=-1)
c_hot_flat = tf.reshape(c_hot, shape=[-1, num_blocks, block_v_size])
h1_residual = tf.matmul(
tf.transpose(c_hot_flat, perm=[1, 0, 2]), means[i])
h1_residual = tf.transpose(h1_residual, perm=[1, 0, 2])
h1_residual = tf.reshape(h1_residual, shape=h1_shape)
h1 += h1_residual
elif bottleneck_kind == "rounding":
h1 = x
else:
raise ValueError("Unknown bottleneck kind.")
h2 = tf.layers.dense(tf.nn.relu(h1), filter_size, name="vch2")
return tf.layers.dense(tf.nn.relu(h2), hidden_size, name="vcfin")
def vae(x, name, z_size):
"""Simple variational autoencoder without discretization.
Args:
x: Input to the discretization bottleneck.
name: Name for the bottleneck scope.
z_size: Number of bits used to produce discrete code; discrete codes range
from 1 to 2**z_size.
Returns:
Embedding function, latent, loss, mu and log_simga.
"""
with tf.variable_scope(name):
mu = tf.layers.dense(x, z_size, name="mu")
log_sigma = tf.layers.dense(x, z_size, name="log_sigma")
shape = common_layers.shape_list(x)
epsilon = tf.random_normal([shape[0], shape[1], 1, z_size])
z = mu + tf.exp(log_sigma / 2) * epsilon
kl = 0.5 * tf.reduce_mean(
tf.exp(log_sigma) + tf.square(mu) - 1. - log_sigma, axis=-1)
free_bits = z_size // 4
kl_loss = tf.reduce_mean(tf.maximum(kl - free_bits, 0.0))
return z, kl_loss, mu, log_sigma
def top_k_softmax(x, k):
"""Calculate softmax(x), select top-k and rescale to sum to 1.
Args:
x: Input to softmax over.
k: Number of top-k to select.
Returns:
softmax(x) and maximum item.
"""
x = tf.nn.softmax(x)
top_x, _ = tf.nn.top_k(x, k=k + 1)
min_top = tf.reduce_min(top_x, axis=-1, keep_dims=True)
x = tf.nn.relu((x - min_top) + 1e-12)
x /= tf.reduce_sum(x, axis=-1, keep_dims=True)
return x, tf.reduce_max(top_x, axis=-1)
def gumbel_sample(shape):
"""Sample from the Gumbel distribution, protect from overflows.
Args:
shape: Shape of Gumbel samples.
Returns:
Noise drawn from Gumbel distribution.
"""
uniform_samples = tf.random_uniform(shape, minval=0.00001, maxval=0.99998)
return -tf.log(-tf.log(uniform_samples))
def gumbel_softmax(x,
name,
z_size,
mode,
softmax_k=0,
kl_warmup_steps=150000,
summary=True):
"""Gumbel softmax discretization bottleneck.
Args:
x: Input to the discretization bottleneck.
name: Name for the bottleneck scope.
z_size: Number of bits used to produce discrete code; discrete codes range
from 1 to 2**z_size.
mode: Mode represents whether we are training or testing for bottlenecks
that differ in behavior (Default: None).
softmax_k: If > 1 then do top-k softmax (Default: 0).
kl_warmup_steps: Number of steps for kl warmup (Default: 150000).
summary: If True, then write summaries (Default: True).
Returns:
Embedding function, discrete code and loss.
"""
with tf.variable_scope(name):
m = tf.layers.dense(x, 2**z_size, name="mask")
if softmax_k > 0:
m, kl = top_k_softmax(m, softmax_k)
return m, m, 1.0 - tf.reduce_mean(kl)
logsm = tf.nn.log_softmax(m)
# Gumbel-softmax sample.
gumbel_samples = gumbel_sample(common_layers.shape_list(m))
steps = kl_warmup_steps
gumbel_samples *= common_layers.inverse_exp_decay(steps // 5) * 0.5
temperature = 1.2 - common_layers.inverse_lin_decay(steps)
# 10% of the time keep reasonably high temperature to keep learning.
temperature = tf.cond(
tf.less(tf.random_uniform([]), 0.9), lambda: temperature,
lambda: tf.random_uniform([], minval=0.5, maxval=1.0))
s = tf.nn.softmax((logsm + gumbel_samples) / temperature)
m = tf.nn.softmax(m)
kl = -tf.reduce_max(logsm, axis=-1)
if summary:
tf.summary.histogram("max-log", tf.reshape(kl, [-1]))
# Calculate the argmax and construct hot vectors.
maxvec = tf.reshape(tf.argmax(m, axis=-1), [-1])
maxvhot = tf.stop_gradient(tf.one_hot(maxvec, 2**z_size))
# Add losses that prevent too few being used.
distrib = tf.reshape(logsm, [-1, 2**z_size]) * maxvhot
d_mean = tf.reduce_mean(distrib, axis=[0], keep_dims=True)
d_variance = tf.reduce_mean(tf.square(distrib - d_mean), axis=[0])
d_dev = -tf.reduce_mean(d_variance)
ret = s
if mode != tf.contrib.learn.ModeKeys.TRAIN:
ret = tf.reshape(maxvhot, common_layers.shape_list(s)) # Just hot @eval.
return m, ret, d_dev * 5.0 + tf.reduce_mean(kl) * 0.002
def discrete_bottleneck(x,
hidden_size,
z_size,
filter_size,
name,
mode=None,
startup_steps=50000,
bottleneck_kind="dvq",
num_blocks=2,
num_residuals=1,
reshape_method="slice",
projection_tensors=None,
means=None,
beta=0.25,
noise_dev=1.,
decay=0.999,
discrete_mix=0.5,
random_top_k=1,
soft_em=False,
num_samples=1,
epsilon=1e-5,
softmax_k=0,
kl_warmup_steps=150000,
ema=True,
ema_count=None,
ema_means=None,
summary=True):
"""Discretization bottleneck for latent variables.
Args:
x: Input to the discretization bottleneck.
hidden_size: Dimension of the latent state.
z_size: Number of bits used to produce discrete code; discrete codes range
from 1 to 2**z_size.
filter_size: Filter size to be used for the embedding function.
name: Name for the bottleneck scope.
mode: Mode represents whether we are training or testing for bottlenecks
that differ in behavior (Default: None).
startup_steps: Number of steps after which latent predictor is trained
(Default: 50000).
bottleneck_kind: Kind of discretization bottleneck to use; one of dvq,
semhash, gumbel-softmax (Default: dvq).
num_blocks: Number of blocks to use for decomposed vector
quantization (Default: 2).
num_residuals: Number of residual units used to compute nearest
neighbors (Default: 1).
reshape_method: Method to reshape for DVQ (Default: slice).
projection_tensors: If the reshape method is project, then these are the
tensors used to project (Default: None).
means: The embedding table for dvq (Default: None).
beta: Beta factor for the DVQ loss (Default: 0.25).
noise_dev: Stddev for noise added for semhash (Default: 0).
decay: Decay factor for the exponential moving average (Default: 0.999).
discrete_mix: Factor for mixing discrete and non-discrete input for semhash
(Default: 0.5).
random_top_k: Noisy top-k for DVQ (Default: 1).
soft_em: If True then use soft EM rather than hard EM (Default: False).
num_samples: Number of samples for soft EM (Default: 1).
epsilon: Epsilon parameter for DVQ (Default: 1e-5).
softmax_k: If > 1 then do top-k softmax (Default: 0).
kl_warmup_steps: Number of steps for kl warmup (Default: 150000).
ema: If True update embeddings using exponential moving averages (Default:
True).
ema_count: Table of counts for each embedding corresponding to how many
examples in a batch it was the closest to (Default: None).
ema_means: Exponentially averaged version of the embeddings (Default: None).
summary: If True, then write summaries (Default: True).
Returns:
Embedding to pass to the decoder, discrete latent, loss, and the embedding
function.
Raises:
ValueError: If projection_tensors is None for reshape_method project, or
ema_count or ema_means is None if we are using ema, or unknown args.
"""
block_v_size = None
if bottleneck_kind == "dvq":
# Define the dvq parameters
assert means is not None
# Check block dimensions add up
if hidden_size % num_blocks != 0:
raise ValueError("num_blocks does not divide hidden size")
if z_size % num_residuals != 0:
raise ValueError("num_residuals does not divide embedding table size")
z_size_per_residual = int(z_size / num_residuals)
if z_size_per_residual % num_blocks != 0:
raise ValueError("num_blocks does not divide embedding table size")
block_v_size = 2**(z_size_per_residual / num_blocks)
block_v_size = int(block_v_size)
# Set the reshape method corresponding to projections or slices
if reshape_method == "slice":
reshape_fn = partial(
slice_hidden, hidden_size=hidden_size, num_blocks=num_blocks)
elif reshape_method == "project":
if projection_tensors is None:
raise ValueError(
"Projection tensors is None for reshape_method project")
reshape_fn = partial(
project_hidden,
projection_tensors=projection_tensors,
hidden_size=hidden_size,
num_blocks=num_blocks)
else:
raise ValueError("Unknown reshape_method")
# Check if the ema settings make sense
if ema:
if ema_count is None:
raise ValueError("ema_count is None but ema is True")
if ema_means is None:
raise ValueError("ema_means is None but ema is True")
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
l = tf.constant(0.0)
if bottleneck_kind == "dense":
c = tf.layers.dense(x, z_size, name="vcc")
h1 = tf.layers.dense(c, filter_size, name="vch1")
elif bottleneck_kind == "vae":
c, l, _, _ = vae(x, z_size, "vae")
h1 = tf.layers.dense(c, filter_size, name="vch1")
elif bottleneck_kind == "semhash":
c = tf.layers.dense(x, z_size, name="vcc")
y_clean = common_layers.saturating_sigmoid(c)
if summary:
tf.summary.histogram("y_clean", tf.reshape(y_clean, [-1]))
if noise_dev > 0 and mode == tf.estimator.ModeKeys.TRAIN:
noise = tf.truncated_normal(
common_layers.shape_list(c), mean=0.0, stddev=noise_dev)
y = common_layers.saturating_sigmoid(c + noise)
else:
y = y_clean
d = tf.to_float(tf.less(0.5, y))
y_discrete = tf.stop_gradient(d) + y - tf.stop_gradient(y)
pd = common_layers.inverse_exp_decay(startup_steps * 2)
pd *= discrete_mix
pd = pd if mode == tf.estimator.ModeKeys.TRAIN else 1.0
c = tf.where(
tf.less(tf.random_uniform([common_layers.shape_list(y)[0]]), pd),
y_discrete, y)
h1a = tf.layers.dense(c, filter_size, name="vch1a")
h1b = tf.layers.dense(1.0 - c, filter_size, name="vch1b")
h1 = h1a + h1b
dx = tf.to_int32(tf.stop_gradient(d))
c = bit_to_int(dx, z_size)
elif bottleneck_kind == "gumbel-softmax":
_, hot, l = gumbel_softmax(x, name, z_size, mode, softmax_k,
kl_warmup_steps, summary)
c = tf.argmax(hot, axis=-1)
h1 = tf.layers.dense(hot, hidden_size, name="dae_dense")
elif bottleneck_kind == "dvq":
x_reshaped = reshape_fn(x)
x_res = x_reshaped
x_means_hot = []
x_means = 0
l = 0
for i in range(num_residuals):
x_means_hot_res, x_means_res, q_loss_res, e_loss_res = embedding_lookup(
x_res, means[i], num_blocks, block_v_size, random_top_k, soft_em,
num_samples)
# Update the ema variables
if ema:
tf.logging.info("Using EMA with beta = {}".format(beta))
updated_ema_count_res = moving_averages.assign_moving_average(
ema_count[i],
tf.reduce_sum(
tf.reshape(
x_means_hot_res, shape=[-1, num_blocks, block_v_size]),
axis=0),
decay,
zero_debias=False)
dw = tf.matmul(
tf.transpose(x_means_hot_res, perm=[1, 2, 0]),
tf.transpose(x_res, perm=[1, 0, 2]))
updated_ema_means_res = moving_averages.assign_moving_average(
ema_means[i], dw, decay, zero_debias=False)
n = tf.reduce_sum(updated_ema_count_res, axis=-1, keep_dims=True)
updated_ema_count_res = ((updated_ema_count_res + epsilon) /
(n + 2**z_size * epsilon) * n)
# pylint: disable=g-no-augmented-assignment
updated_ema_means_res = updated_ema_means_res / tf.expand_dims(
updated_ema_count_res, axis=-1)
# pylint: enable=g-no-augmented-assignment
with tf.control_dependencies([e_loss_res]):
update_means_res = tf.assign(means[i], updated_ema_means_res)
with tf.control_dependencies([update_means_res]):
l += beta * e_loss_res
else:
l += q_loss_res + beta * e_loss_res
# Update the residuals
x_res -= x_means_res
x_means += x_means_res
x_means_hot.append(x_means_hot_res)
# Get the discrete latent representation
x_means_hot = tf.stack(x_means_hot, axis=1)
x_means_idx = tf.argmax(x_means_hot, axis=-1)
# Get the binary representation
x_means_bits = int_to_bit(
x_means_idx,
num_bits=int(z_size / (num_residuals * num_blocks)),
base=2)
shape = common_layers.shape_list(x_means_bits)
new_shape = shape[:-2]
new_shape[-1] = z_size
x_means_bits = tf.reshape(x_means_bits, shape=new_shape)
c = bit_to_int(tf.to_int32(x_means_bits), num_bits=z_size, base=2)
# Adjust shape of c
shape_x = common_layers.shape_list(x)
new_shape = shape_x[:-1]
c = tf.reshape(c, new_shape)
# If we are doing soft EM then c is x_means_hot
if soft_em:
c = x_means_hot
new_shape.append(block_v_size)
c = tf.reshape(c, new_shape)
x_means = tf.reshape(x_means, shape_x)
x_reshaped = tf.reshape(x_reshaped, shape_x)
h1 = x_reshaped + tf.stop_gradient(x_means - x_reshaped)
else:
raise ValueError("Unknown discretization method.")
h2 = tf.layers.dense(tf.nn.relu(h1), filter_size, name="vch2")
res = tf.layers.dense(tf.nn.relu(h2), hidden_size, name="vcfin")
embed_fn = partial(
embed,
hidden_size=hidden_size,
z_size=z_size,
filter_size=filter_size,
name=name,
bottleneck_kind=bottleneck_kind,
soft_em=soft_em,
num_blocks=num_blocks,
num_residuals=num_residuals,
block_v_size=block_v_size,
means=means)
return res, c, l, embed_fn
# New API for discretization bottlenecks:
# * Each method is separate and provides 2 functions:
# * The [method]_bottleneck function returns discretized state.
# * The [method]_unbottleneck function moves from discretized state to dense.
def tanh_discrete_bottleneck(x, bottleneck_size, bottleneck_noise,
discretize_warmup_steps, mode):
"""Simple discretization through tanh, flip bottleneck_noise many bits."""
x = tf.tanh(tf.layers.dense(x, bottleneck_size,
name="tanh_discrete_bottleneck"))
d = x + tf.stop_gradient(2.0 * tf.to_float(tf.less(0.0, x)) - 1.0 - x)
if mode == tf.estimator.ModeKeys.TRAIN:
noise = tf.random_uniform(common_layers.shape_list(x))
noise = 2.0 * tf.to_float(tf.less(bottleneck_noise, noise)) - 1.0
d *= noise
d = common_layers.mix(d, x, discretize_warmup_steps,
mode == tf.estimator.ModeKeys.TRAIN)
return d
def tanh_discrete_unbottleneck(x, hidden_size):
"""Simple un-discretization from tanh."""
x = tf.layers.dense(x, hidden_size, name="tanh_discrete_unbottleneck")
return x
def isemhash_bottleneck(x, bottleneck_size, bottleneck_noise,
discretize_warmup_steps, mode,
isemhash_noise_dev=0.5, isemhash_mix_prob=0.5):
"""Improved semantic hashing bottleneck."""
with tf.variable_scope("isemhash_bottleneck"):
x = tf.layers.dense(x, bottleneck_size, name="dense")
y = common_layers.saturating_sigmoid(x)
if isemhash_noise_dev > 0 and mode == tf.estimator.ModeKeys.TRAIN:
noise = tf.truncated_normal(
common_layers.shape_list(x), mean=0.0, stddev=isemhash_noise_dev)
y = common_layers.saturating_sigmoid(x + noise)
d = tf.to_float(tf.less(0.5, y)) + y - tf.stop_gradient(y)
d = 2.0 * d - 1.0 # Move from [0, 1] to [-1, 1].
if mode == tf.estimator.ModeKeys.TRAIN: # Flip some bits.
noise = tf.random_uniform(common_layers.shape_list(x))
noise = 2.0 * tf.to_float(tf.less(bottleneck_noise, noise)) - 1.0
d *= noise
d = common_layers.mix(d, 2.0 * y - 1.0, discretize_warmup_steps,
mode == tf.estimator.ModeKeys.TRAIN,
max_prob=isemhash_mix_prob)
return d
def isemhash_unbottleneck(x, hidden_size, isemhash_filter_size_multiplier=1.0):
"""Improved semantic hashing un-bottleneck."""
filter_size = int(hidden_size * isemhash_filter_size_multiplier)
x = 0.5 * (x - 1.0) # Move from [-1, 1] to [0, 1].
with tf.variable_scope("isemhash_unbottleneck"):
h1a = tf.layers.dense(x, filter_size, name="hidden1a")
h1b = tf.layers.dense(1.0 - x, filter_size, name="hidden1b")
h2 = tf.layers.dense(tf.nn.relu(h1a + h1b), filter_size, name="hidden2")
return tf.layers.dense(tf.nn.relu(h2), hidden_size, name="final")
def parametrized_bottleneck(x, hparams):
"""Meta-function calling all the above bottlenecks with hparams."""
if hparams.bottleneck_kind == "tanh_discrete":
return tanh_discrete_bottleneck(
x, hparams.bottleneck_size, hparams.bottleneck_noise * 0.5,
hparams.discretize_warmup_steps, hparams.mode)
if hparams.bottleneck_kind == "isemhash":
return isemhash_bottleneck(
x, hparams.bottleneck_size, hparams.bottleneck_noise * 0.5,
hparams.discretize_warmup_steps, hparams.mode,
hparams.isemhash_noise_dev, hparams.isemhash_mix_prob)
raise ValueError("Unsupported hparams.bottleneck_kind %s"
% hparams.bottleneck_kind)
def parametrized_unbottleneck(x, hidden_size, hparams):
"""Meta-function calling all the above un-bottlenecks with hparams."""
if hparams.bottleneck_kind == "tanh_discrete":
return tanh_discrete_unbottleneck(x, hidden_size)
if hparams.bottleneck_kind == "isemhash":
return isemhash_unbottleneck(
x, hidden_size, hparams.isemhash_filter_size_multiplier)
raise ValueError("Unsupported hparams.bottleneck_kind %s"
% hparams.bottleneck_kind)
| 38.877984 | 80 | 0.651395 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from functools import partial
from tensor2tensor.layers import common_layers
import tensorflow as tf
from tensorflow.python.training import moving_averages
def project_hidden(x, projection_tensors, hidden_size, num_blocks):
x = tf.reshape(x, shape=[1, -1, hidden_size])
x_tiled = tf.reshape(
tf.tile(x, multiples=[num_blocks, 1, 1]),
shape=[num_blocks, -1, hidden_size])
x_projected = tf.matmul(x_tiled, projection_tensors)
x_projected = tf.transpose(x_projected, perm=[1, 0, 2])
return x_projected
def slice_hidden(x, hidden_size, num_blocks):
block_dim = int(hidden_size // num_blocks)
x_sliced = tf.reshape(x, shape=[-1, num_blocks, block_dim])
return x_sliced
def nearest_neighbor(x,
means,
block_v_size,
random_top_k=1,
soft_em=False,
num_samples=1):
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keep_dims=True)
means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keep_dims=True)
scalar_prod = tf.matmul(
tf.transpose(x, perm=[1, 0, 2]), tf.transpose(means, perm=[0, 2, 1]))
scalar_prod = tf.transpose(scalar_prod, perm=[1, 0, 2])
dist = x_norm_sq + tf.transpose(
means_norm_sq, perm=[2, 0, 1]) - 2 * scalar_prod
if soft_em:
num_blocks = common_layers.shape_list(dist)[1]
nearest_idx = tf.stack(
[
tf.multinomial(-dist[:, i, :], num_samples=num_samples)
for i in range(num_blocks)
],
axis=1)
nearest_hot = tf.one_hot(nearest_idx, depth=block_v_size)
nearest_hot = tf.reduce_mean(nearest_hot, axis=-2)
else:
if random_top_k > 1:
_, top_k_idx = tf.nn.top_k(-dist, k=random_top_k)
nearest_idx = tf.gather(
top_k_idx,
tf.random_uniform(
[1], minval=0, maxval=random_top_k - 1, dtype=tf.int32),
axis=-1)
else:
nearest_idx = tf.argmax(-dist, axis=-1)
nearest_hot = tf.one_hot(nearest_idx, block_v_size)
return nearest_hot
def embedding_lookup(x,
means,
num_blocks,
block_v_size,
random_top_k=1,
soft_em=False,
num_samples=1):
x_means_hot = nearest_neighbor(
x,
means,
block_v_size,
random_top_k,
soft_em=soft_em,
num_samples=num_samples)
x_means_hot_flat = tf.reshape(x_means_hot, [-1, num_blocks, block_v_size])
x_means = tf.matmul(tf.transpose(x_means_hot_flat, perm=[1, 0, 2]), means)
x_means = tf.transpose(x_means, [1, 0, 2])
q_loss = tf.reduce_mean(tf.square((tf.stop_gradient(x) - x_means)))
e_loss = tf.reduce_mean(tf.square(x - tf.stop_gradient(x_means)))
return x_means_hot, x_means, q_loss, e_loss
def bit_to_int(x_bit, num_bits, base=2):
x_l = tf.stop_gradient(tf.to_int32(tf.reshape(x_bit, [-1, num_bits])))
x_labels = []
for i in range(num_bits):
x_labels.append(x_l[:, i] * tf.to_int32(base)**tf.to_int32(i))
res = sum(x_labels)
return tf.to_int32(tf.reshape(res, common_layers.shape_list(x_bit)[:-1]))
def int_to_bit(x_int, num_bits, base=2):
x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1))
x_labels = []
for i in range(num_bits):
x_labels.append(
tf.floormod(
tf.floordiv(tf.to_int32(x_l),
tf.to_int32(base)**i), tf.to_int32(base)))
res = tf.concat(x_labels, axis=-1)
return tf.to_float(res)
def int_to_bit_embed(x_int, num_bits, embedding_size, base=2):
shape = common_layers.shape_list(x_int)
inputs = int_to_bit(x_int, num_bits, base=base)
inputs = tf.reshape(inputs, shape[:-1] + [shape[-1] * 8])
inputs = 2.0 * tf.to_float(inputs) - 1.0
return tf.layers.dense(inputs, embedding_size, name="int_to_bit_embed")
def embed(x,
hidden_size,
z_size,
filter_size,
name,
bottleneck_kind="dvq",
soft_em=False,
num_blocks=2,
num_residuals=1,
block_v_size=None,
means=None):
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
if bottleneck_kind == "semhash":
c = int_to_bit(x, z_size)
h1a = tf.layers.dense(c, filter_size, name="vch1a")
h1b = tf.layers.dense(1.0 - c, filter_size, name="vch1b")
h1 = h1a + h1b
elif bottleneck_kind == "gumbel-softmax":
hot = tf.one_hot(x, 2**z_size)
h1 = tf.layers.dense(hot, hidden_size, name="dae_dense")
elif bottleneck_kind == "dvq":
if block_v_size is None:
raise ValueError("Bottleneck kind is dvq but block_v_size is None.")
if soft_em:
assert num_residuals == 1
x_hot_flat = tf.reshape(x, shape=[-1, num_blocks, block_v_size])
h1 = tf.matmul(tf.transpose(x_hot_flat, perm=[1, 0, 2]), means[0])
h1 = tf.transpose(h1, perm=[1, 0, 2])
new_shape = common_layers.shape_list(x)
new_shape[-1] = hidden_size
h1 = tf.reshape(h1, shape=new_shape)
else:
shape_x = common_layers.shape_list(x)
x_flat = tf.reshape(x, [-1, 1])
c = int_to_bit(x_flat, num_bits=z_size, base=2)
shape = common_layers.shape_list(c)
new_shape = shape
new_shape[-1] = num_residuals
new_shape.append(num_blocks)
new_shape.append(int(z_size / (num_residuals * num_blocks)))
c = tf.to_int32(tf.reshape(c, shape=new_shape))
h1_shape = shape_x
h1_shape.append(hidden_size)
h1 = tf.zeros(dtype=tf.float32, shape=h1_shape)
for i in range(num_residuals):
c_residual = bit_to_int(
c[:, :, i, :, :],
num_bits=int(z_size / (num_residuals * num_blocks)),
base=2)
c_hot = tf.one_hot(c_residual, depth=block_v_size, axis=-1)
c_hot_flat = tf.reshape(c_hot, shape=[-1, num_blocks, block_v_size])
h1_residual = tf.matmul(
tf.transpose(c_hot_flat, perm=[1, 0, 2]), means[i])
h1_residual = tf.transpose(h1_residual, perm=[1, 0, 2])
h1_residual = tf.reshape(h1_residual, shape=h1_shape)
h1 += h1_residual
elif bottleneck_kind == "rounding":
h1 = x
else:
raise ValueError("Unknown bottleneck kind.")
h2 = tf.layers.dense(tf.nn.relu(h1), filter_size, name="vch2")
return tf.layers.dense(tf.nn.relu(h2), hidden_size, name="vcfin")
def vae(x, name, z_size):
with tf.variable_scope(name):
mu = tf.layers.dense(x, z_size, name="mu")
log_sigma = tf.layers.dense(x, z_size, name="log_sigma")
shape = common_layers.shape_list(x)
epsilon = tf.random_normal([shape[0], shape[1], 1, z_size])
z = mu + tf.exp(log_sigma / 2) * epsilon
kl = 0.5 * tf.reduce_mean(
tf.exp(log_sigma) + tf.square(mu) - 1. - log_sigma, axis=-1)
free_bits = z_size // 4
kl_loss = tf.reduce_mean(tf.maximum(kl - free_bits, 0.0))
return z, kl_loss, mu, log_sigma
def top_k_softmax(x, k):
x = tf.nn.softmax(x)
top_x, _ = tf.nn.top_k(x, k=k + 1)
min_top = tf.reduce_min(top_x, axis=-1, keep_dims=True)
x = tf.nn.relu((x - min_top) + 1e-12)
x /= tf.reduce_sum(x, axis=-1, keep_dims=True)
return x, tf.reduce_max(top_x, axis=-1)
def gumbel_sample(shape):
uniform_samples = tf.random_uniform(shape, minval=0.00001, maxval=0.99998)
return -tf.log(-tf.log(uniform_samples))
def gumbel_softmax(x,
name,
z_size,
mode,
softmax_k=0,
kl_warmup_steps=150000,
summary=True):
with tf.variable_scope(name):
m = tf.layers.dense(x, 2**z_size, name="mask")
if softmax_k > 0:
m, kl = top_k_softmax(m, softmax_k)
return m, m, 1.0 - tf.reduce_mean(kl)
logsm = tf.nn.log_softmax(m)
gumbel_samples = gumbel_sample(common_layers.shape_list(m))
steps = kl_warmup_steps
gumbel_samples *= common_layers.inverse_exp_decay(steps // 5) * 0.5
temperature = 1.2 - common_layers.inverse_lin_decay(steps)
temperature = tf.cond(
tf.less(tf.random_uniform([]), 0.9), lambda: temperature,
lambda: tf.random_uniform([], minval=0.5, maxval=1.0))
s = tf.nn.softmax((logsm + gumbel_samples) / temperature)
m = tf.nn.softmax(m)
kl = -tf.reduce_max(logsm, axis=-1)
if summary:
tf.summary.histogram("max-log", tf.reshape(kl, [-1]))
maxvec = tf.reshape(tf.argmax(m, axis=-1), [-1])
maxvhot = tf.stop_gradient(tf.one_hot(maxvec, 2**z_size))
distrib = tf.reshape(logsm, [-1, 2**z_size]) * maxvhot
d_mean = tf.reduce_mean(distrib, axis=[0], keep_dims=True)
d_variance = tf.reduce_mean(tf.square(distrib - d_mean), axis=[0])
d_dev = -tf.reduce_mean(d_variance)
ret = s
if mode != tf.contrib.learn.ModeKeys.TRAIN:
ret = tf.reshape(maxvhot, common_layers.shape_list(s))
return m, ret, d_dev * 5.0 + tf.reduce_mean(kl) * 0.002
def discrete_bottleneck(x,
hidden_size,
z_size,
filter_size,
name,
mode=None,
startup_steps=50000,
bottleneck_kind="dvq",
num_blocks=2,
num_residuals=1,
reshape_method="slice",
projection_tensors=None,
means=None,
beta=0.25,
noise_dev=1.,
decay=0.999,
discrete_mix=0.5,
random_top_k=1,
soft_em=False,
num_samples=1,
epsilon=1e-5,
softmax_k=0,
kl_warmup_steps=150000,
ema=True,
ema_count=None,
ema_means=None,
summary=True):
block_v_size = None
if bottleneck_kind == "dvq":
assert means is not None
if hidden_size % num_blocks != 0:
raise ValueError("num_blocks does not divide hidden size")
if z_size % num_residuals != 0:
raise ValueError("num_residuals does not divide embedding table size")
z_size_per_residual = int(z_size / num_residuals)
if z_size_per_residual % num_blocks != 0:
raise ValueError("num_blocks does not divide embedding table size")
block_v_size = 2**(z_size_per_residual / num_blocks)
block_v_size = int(block_v_size)
if reshape_method == "slice":
reshape_fn = partial(
slice_hidden, hidden_size=hidden_size, num_blocks=num_blocks)
elif reshape_method == "project":
if projection_tensors is None:
raise ValueError(
"Projection tensors is None for reshape_method project")
reshape_fn = partial(
project_hidden,
projection_tensors=projection_tensors,
hidden_size=hidden_size,
num_blocks=num_blocks)
else:
raise ValueError("Unknown reshape_method")
if ema:
if ema_count is None:
raise ValueError("ema_count is None but ema is True")
if ema_means is None:
raise ValueError("ema_means is None but ema is True")
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
l = tf.constant(0.0)
if bottleneck_kind == "dense":
c = tf.layers.dense(x, z_size, name="vcc")
h1 = tf.layers.dense(c, filter_size, name="vch1")
elif bottleneck_kind == "vae":
c, l, _, _ = vae(x, z_size, "vae")
h1 = tf.layers.dense(c, filter_size, name="vch1")
elif bottleneck_kind == "semhash":
c = tf.layers.dense(x, z_size, name="vcc")
y_clean = common_layers.saturating_sigmoid(c)
if summary:
tf.summary.histogram("y_clean", tf.reshape(y_clean, [-1]))
if noise_dev > 0 and mode == tf.estimator.ModeKeys.TRAIN:
noise = tf.truncated_normal(
common_layers.shape_list(c), mean=0.0, stddev=noise_dev)
y = common_layers.saturating_sigmoid(c + noise)
else:
y = y_clean
d = tf.to_float(tf.less(0.5, y))
y_discrete = tf.stop_gradient(d) + y - tf.stop_gradient(y)
pd = common_layers.inverse_exp_decay(startup_steps * 2)
pd *= discrete_mix
pd = pd if mode == tf.estimator.ModeKeys.TRAIN else 1.0
c = tf.where(
tf.less(tf.random_uniform([common_layers.shape_list(y)[0]]), pd),
y_discrete, y)
h1a = tf.layers.dense(c, filter_size, name="vch1a")
h1b = tf.layers.dense(1.0 - c, filter_size, name="vch1b")
h1 = h1a + h1b
dx = tf.to_int32(tf.stop_gradient(d))
c = bit_to_int(dx, z_size)
elif bottleneck_kind == "gumbel-softmax":
_, hot, l = gumbel_softmax(x, name, z_size, mode, softmax_k,
kl_warmup_steps, summary)
c = tf.argmax(hot, axis=-1)
h1 = tf.layers.dense(hot, hidden_size, name="dae_dense")
elif bottleneck_kind == "dvq":
x_reshaped = reshape_fn(x)
x_res = x_reshaped
x_means_hot = []
x_means = 0
l = 0
for i in range(num_residuals):
x_means_hot_res, x_means_res, q_loss_res, e_loss_res = embedding_lookup(
x_res, means[i], num_blocks, block_v_size, random_top_k, soft_em,
num_samples)
if ema:
tf.logging.info("Using EMA with beta = {}".format(beta))
updated_ema_count_res = moving_averages.assign_moving_average(
ema_count[i],
tf.reduce_sum(
tf.reshape(
x_means_hot_res, shape=[-1, num_blocks, block_v_size]),
axis=0),
decay,
zero_debias=False)
dw = tf.matmul(
tf.transpose(x_means_hot_res, perm=[1, 2, 0]),
tf.transpose(x_res, perm=[1, 0, 2]))
updated_ema_means_res = moving_averages.assign_moving_average(
ema_means[i], dw, decay, zero_debias=False)
n = tf.reduce_sum(updated_ema_count_res, axis=-1, keep_dims=True)
updated_ema_count_res = ((updated_ema_count_res + epsilon) /
(n + 2**z_size * epsilon) * n)
updated_ema_means_res = updated_ema_means_res / tf.expand_dims(
updated_ema_count_res, axis=-1)
with tf.control_dependencies([e_loss_res]):
update_means_res = tf.assign(means[i], updated_ema_means_res)
with tf.control_dependencies([update_means_res]):
l += beta * e_loss_res
else:
l += q_loss_res + beta * e_loss_res
x_res -= x_means_res
x_means += x_means_res
x_means_hot.append(x_means_hot_res)
x_means_hot = tf.stack(x_means_hot, axis=1)
x_means_idx = tf.argmax(x_means_hot, axis=-1)
x_means_bits = int_to_bit(
x_means_idx,
num_bits=int(z_size / (num_residuals * num_blocks)),
base=2)
shape = common_layers.shape_list(x_means_bits)
new_shape = shape[:-2]
new_shape[-1] = z_size
x_means_bits = tf.reshape(x_means_bits, shape=new_shape)
c = bit_to_int(tf.to_int32(x_means_bits), num_bits=z_size, base=2)
shape_x = common_layers.shape_list(x)
new_shape = shape_x[:-1]
c = tf.reshape(c, new_shape)
if soft_em:
c = x_means_hot
new_shape.append(block_v_size)
c = tf.reshape(c, new_shape)
x_means = tf.reshape(x_means, shape_x)
x_reshaped = tf.reshape(x_reshaped, shape_x)
h1 = x_reshaped + tf.stop_gradient(x_means - x_reshaped)
else:
raise ValueError("Unknown discretization method.")
h2 = tf.layers.dense(tf.nn.relu(h1), filter_size, name="vch2")
res = tf.layers.dense(tf.nn.relu(h2), hidden_size, name="vcfin")
embed_fn = partial(
embed,
hidden_size=hidden_size,
z_size=z_size,
filter_size=filter_size,
name=name,
bottleneck_kind=bottleneck_kind,
soft_em=soft_em,
num_blocks=num_blocks,
num_residuals=num_residuals,
block_v_size=block_v_size,
means=means)
return res, c, l, embed_fn
def tanh_discrete_bottleneck(x, bottleneck_size, bottleneck_noise,
discretize_warmup_steps, mode):
x = tf.tanh(tf.layers.dense(x, bottleneck_size,
name="tanh_discrete_bottleneck"))
d = x + tf.stop_gradient(2.0 * tf.to_float(tf.less(0.0, x)) - 1.0 - x)
if mode == tf.estimator.ModeKeys.TRAIN:
noise = tf.random_uniform(common_layers.shape_list(x))
noise = 2.0 * tf.to_float(tf.less(bottleneck_noise, noise)) - 1.0
d *= noise
d = common_layers.mix(d, x, discretize_warmup_steps,
mode == tf.estimator.ModeKeys.TRAIN)
return d
def tanh_discrete_unbottleneck(x, hidden_size):
x = tf.layers.dense(x, hidden_size, name="tanh_discrete_unbottleneck")
return x
def isemhash_bottleneck(x, bottleneck_size, bottleneck_noise,
discretize_warmup_steps, mode,
isemhash_noise_dev=0.5, isemhash_mix_prob=0.5):
with tf.variable_scope("isemhash_bottleneck"):
x = tf.layers.dense(x, bottleneck_size, name="dense")
y = common_layers.saturating_sigmoid(x)
if isemhash_noise_dev > 0 and mode == tf.estimator.ModeKeys.TRAIN:
noise = tf.truncated_normal(
common_layers.shape_list(x), mean=0.0, stddev=isemhash_noise_dev)
y = common_layers.saturating_sigmoid(x + noise)
d = tf.to_float(tf.less(0.5, y)) + y - tf.stop_gradient(y)
d = 2.0 * d - 1.0
if mode == tf.estimator.ModeKeys.TRAIN:
noise = tf.random_uniform(common_layers.shape_list(x))
noise = 2.0 * tf.to_float(tf.less(bottleneck_noise, noise)) - 1.0
d *= noise
d = common_layers.mix(d, 2.0 * y - 1.0, discretize_warmup_steps,
mode == tf.estimator.ModeKeys.TRAIN,
max_prob=isemhash_mix_prob)
return d
def isemhash_unbottleneck(x, hidden_size, isemhash_filter_size_multiplier=1.0):
filter_size = int(hidden_size * isemhash_filter_size_multiplier)
x = 0.5 * (x - 1.0)
with tf.variable_scope("isemhash_unbottleneck"):
h1a = tf.layers.dense(x, filter_size, name="hidden1a")
h1b = tf.layers.dense(1.0 - x, filter_size, name="hidden1b")
h2 = tf.layers.dense(tf.nn.relu(h1a + h1b), filter_size, name="hidden2")
return tf.layers.dense(tf.nn.relu(h2), hidden_size, name="final")
def parametrized_bottleneck(x, hparams):
if hparams.bottleneck_kind == "tanh_discrete":
return tanh_discrete_bottleneck(
x, hparams.bottleneck_size, hparams.bottleneck_noise * 0.5,
hparams.discretize_warmup_steps, hparams.mode)
if hparams.bottleneck_kind == "isemhash":
return isemhash_bottleneck(
x, hparams.bottleneck_size, hparams.bottleneck_noise * 0.5,
hparams.discretize_warmup_steps, hparams.mode,
hparams.isemhash_noise_dev, hparams.isemhash_mix_prob)
raise ValueError("Unsupported hparams.bottleneck_kind %s"
% hparams.bottleneck_kind)
def parametrized_unbottleneck(x, hidden_size, hparams):
if hparams.bottleneck_kind == "tanh_discrete":
return tanh_discrete_unbottleneck(x, hidden_size)
if hparams.bottleneck_kind == "isemhash":
return isemhash_unbottleneck(
x, hidden_size, hparams.isemhash_filter_size_multiplier)
raise ValueError("Unsupported hparams.bottleneck_kind %s"
% hparams.bottleneck_kind)
| true | true |
f72bc2026dd2bf64e09da4b3d2a51aebf0adea83 | 5,122 | py | Python | perfect_information_game/tablebases/symmetry_transform.py | amaarquadri/perfect-information-game | 6755f9633935be762d039ece9c0b646c64de6ab8 | [
"MIT"
] | null | null | null | perfect_information_game/tablebases/symmetry_transform.py | amaarquadri/perfect-information-game | 6755f9633935be762d039ece9c0b646c64de6ab8 | [
"MIT"
] | null | null | null | perfect_information_game/tablebases/symmetry_transform.py | amaarquadri/perfect-information-game | 6755f9633935be762d039ece9c0b646c64de6ab8 | [
"MIT"
] | null | null | null | import numpy as np
from perfect_information_game.games import Chess
from perfect_information_game.utils import iter_product
from perfect_information_game.tablebases import get_verified_chess_subclass
class SymmetryTransform:
# noinspection PyChainedComparisons
PAWNLESS_UNIQUE_SQUARE_INDICES = [(i, j) for i, j in iter_product(Chess.BOARD_SHAPE)
if i < 4 and j < 4 and i <= j]
UNIQUE_SQUARE_INDICES = [(i, j) for i, j in iter_product(Chess.BOARD_SHAPE) if j < 4]
def __init__(self, GameClass, state):
self.GameClass = get_verified_chess_subclass(GameClass)
self.flip_colors = self.flip_i = self.flip_j = self.flip_diagonal = False
if self.should_swap_colours(state):
# black is attacking, so switch white and black
self.flip_colors = True
i, j = self.GameClass.get_king_pos(state, self.GameClass.BLACK_SLICE)
i = self.GameClass.ROWS - 1 - i
else:
i, j = self.GameClass.get_king_pos(state, self.GameClass.WHITE_SLICE)
pawnless = np.all(state[:, :, self.GameClass.WHITE_PAWN] == 0) and \
np.all(state[:, :, self.GameClass.BLACK_PAWN] == 0)
if pawnless and not (i < 4):
self.flip_i = True
i = self.GameClass.ROWS - 1 - i
if not (j < 4): # horizontal flipping can be done, even with pawns
self.flip_j = True
j = self.GameClass.COLUMNS - 1 - j
if pawnless and not (i <= j):
self.flip_diagonal = True
def should_swap_colours(self, state):
heuristic = self.GameClass.heuristic(state)
if heuristic > 0:
# white is up in material, so don't swap colours
return False
if heuristic < 0:
# black is up in material, so swap colours
return True
# compare the number of pawns on each rank, from most advanced to least advanced pawns
# no need to check second rank pawns, because if everything else is equal they must be equal too
for rank in range(7, 2, -1):
if np.sum(state[rank - 1, :, self.GameClass.BLACK_PAWN]) > \
np.sum(state[8 - rank, :, self.GameClass.WHITE_PAWN]):
# black has more pawns than white on this rank, so swap colours
return True
return False
@staticmethod
def identity(GameClass):
identity = SymmetryTransform(GameClass, GameClass.STARTING_STATE)
identity.flip_colors = identity.flip_i = identity.flip_j = identity.flip_diagonal = False
return identity
@staticmethod
def random(GameClass, descriptor):
"""
Returns a random symmetry transform for the given descriptor.
"""
random = SymmetryTransform.identity(GameClass)
pawnless = 'p' not in descriptor and 'P' not in descriptor
random.flip_colors = np.random.random() < 0.5
random.flip_j = np.random.random() < 0.5
if pawnless:
random.flip_i = np.random.random() < 0.5
random.flip_diagonal = np.random.random() < 0.5
return random
def is_identity(self):
return not self.flip_colors and not self.flip_i and not self.flip_j and not self.flip_diagonal
def transform_state(self, state):
if self.flip_colors:
state = self.flip_state_colors(self.GameClass, state)
if self.flip_i:
state = self.flip_state_i(state)
if self.flip_j:
state = self.flip_state_j(state)
if self.flip_diagonal:
state = self.flip_state_diagonal(state)
return state
def untransform_state(self, state):
# since all transform_funcs are their own inverses, we can just run through them in reverse
if self.flip_diagonal:
state = self.flip_state_diagonal(state)
if self.flip_j:
state = self.flip_state_j(state)
if self.flip_i:
state = self.flip_state_i(state)
if self.flip_colors:
state = self.flip_state_colors(self.GameClass, state)
return state
def transform_outcome(self, outcome):
return -outcome if self.flip_colors else outcome
@staticmethod
def flip_state_colors(GameClass, state):
special_layers = np.copy(state[..., -2:])
special_layers[..., -1] = 1 - special_layers[..., -1] # flip whose turn it is
new_state = np.concatenate((state[..., GameClass.BLACK_SLICE], state[..., GameClass.WHITE_SLICE],
special_layers),
axis=-1)
# need to flip board vertically after flipping colours
# this ensures that the pawns move in the correct directions
return SymmetryTransform.flip_state_i(new_state)
@staticmethod
def flip_state_i(state):
return np.flip(state, axis=0)
@staticmethod
def flip_state_j(state):
return np.flip(state, axis=1)
@staticmethod
def flip_state_diagonal(state):
return np.rot90(np.flip(state, axis=1), axes=(0, 1))
| 40.650794 | 105 | 0.625927 | import numpy as np
from perfect_information_game.games import Chess
from perfect_information_game.utils import iter_product
from perfect_information_game.tablebases import get_verified_chess_subclass
class SymmetryTransform:
PAWNLESS_UNIQUE_SQUARE_INDICES = [(i, j) for i, j in iter_product(Chess.BOARD_SHAPE)
if i < 4 and j < 4 and i <= j]
UNIQUE_SQUARE_INDICES = [(i, j) for i, j in iter_product(Chess.BOARD_SHAPE) if j < 4]
def __init__(self, GameClass, state):
self.GameClass = get_verified_chess_subclass(GameClass)
self.flip_colors = self.flip_i = self.flip_j = self.flip_diagonal = False
if self.should_swap_colours(state):
self.flip_colors = True
i, j = self.GameClass.get_king_pos(state, self.GameClass.BLACK_SLICE)
i = self.GameClass.ROWS - 1 - i
else:
i, j = self.GameClass.get_king_pos(state, self.GameClass.WHITE_SLICE)
pawnless = np.all(state[:, :, self.GameClass.WHITE_PAWN] == 0) and \
np.all(state[:, :, self.GameClass.BLACK_PAWN] == 0)
if pawnless and not (i < 4):
self.flip_i = True
i = self.GameClass.ROWS - 1 - i
if not (j < 4):
self.flip_j = True
j = self.GameClass.COLUMNS - 1 - j
if pawnless and not (i <= j):
self.flip_diagonal = True
def should_swap_colours(self, state):
heuristic = self.GameClass.heuristic(state)
if heuristic > 0:
return False
if heuristic < 0:
# black is up in material, so swap colours
return True
# compare the number of pawns on each rank, from most advanced to least advanced pawns
# no need to check second rank pawns, because if everything else is equal they must be equal too
for rank in range(7, 2, -1):
if np.sum(state[rank - 1, :, self.GameClass.BLACK_PAWN]) > \
np.sum(state[8 - rank, :, self.GameClass.WHITE_PAWN]):
# black has more pawns than white on this rank, so swap colours
return True
return False
@staticmethod
def identity(GameClass):
identity = SymmetryTransform(GameClass, GameClass.STARTING_STATE)
identity.flip_colors = identity.flip_i = identity.flip_j = identity.flip_diagonal = False
return identity
@staticmethod
def random(GameClass, descriptor):
random = SymmetryTransform.identity(GameClass)
pawnless = 'p' not in descriptor and 'P' not in descriptor
random.flip_colors = np.random.random() < 0.5
random.flip_j = np.random.random() < 0.5
if pawnless:
random.flip_i = np.random.random() < 0.5
random.flip_diagonal = np.random.random() < 0.5
return random
def is_identity(self):
return not self.flip_colors and not self.flip_i and not self.flip_j and not self.flip_diagonal
def transform_state(self, state):
if self.flip_colors:
state = self.flip_state_colors(self.GameClass, state)
if self.flip_i:
state = self.flip_state_i(state)
if self.flip_j:
state = self.flip_state_j(state)
if self.flip_diagonal:
state = self.flip_state_diagonal(state)
return state
def untransform_state(self, state):
# since all transform_funcs are their own inverses, we can just run through them in reverse
if self.flip_diagonal:
state = self.flip_state_diagonal(state)
if self.flip_j:
state = self.flip_state_j(state)
if self.flip_i:
state = self.flip_state_i(state)
if self.flip_colors:
state = self.flip_state_colors(self.GameClass, state)
return state
def transform_outcome(self, outcome):
return -outcome if self.flip_colors else outcome
@staticmethod
def flip_state_colors(GameClass, state):
special_layers = np.copy(state[..., -2:])
special_layers[..., -1] = 1 - special_layers[..., -1] # flip whose turn it is
new_state = np.concatenate((state[..., GameClass.BLACK_SLICE], state[..., GameClass.WHITE_SLICE],
special_layers),
axis=-1)
# need to flip board vertically after flipping colours
# this ensures that the pawns move in the correct directions
return SymmetryTransform.flip_state_i(new_state)
@staticmethod
def flip_state_i(state):
return np.flip(state, axis=0)
@staticmethod
def flip_state_j(state):
return np.flip(state, axis=1)
@staticmethod
def flip_state_diagonal(state):
return np.rot90(np.flip(state, axis=1), axes=(0, 1))
| true | true |
f72bc25c098c14f516c7757477bbf04b559e5b10 | 8,291 | py | Python | custom_components/dahua/config_flow.py | ikke-zelf/dahua | 9fca03b3d0caf5661efee7d71668a838b0478587 | [
"MIT"
] | null | null | null | custom_components/dahua/config_flow.py | ikke-zelf/dahua | 9fca03b3d0caf5661efee7d71668a838b0478587 | [
"MIT"
] | null | null | null | custom_components/dahua/config_flow.py | ikke-zelf/dahua | 9fca03b3d0caf5661efee7d71668a838b0478587 | [
"MIT"
] | null | null | null | """Adds config flow (UI flow) for Dahua IP cameras."""
import logging
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.core import callback
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from homeassistant.helpers import config_validation as cv
from .client import DahuaClient
from .const import (
CONF_PASSWORD,
CONF_USERNAME,
CONF_ADDRESS,
CONF_RTSP_PORT,
CONF_PORT,
CONF_STREAMS,
CONF_EVENTS,
CONF_NAME,
STREAM_MAIN,
STREAM_SUB,
STREAM_BOTH,
DOMAIN,
PLATFORMS,
)
from .rpc2 import DahuaRpc2Client
"""
https://developers.home-assistant.io/docs/config_entries_config_flow_handler
https://developers.home-assistant.io/docs/data_entry_flow_index/
"""
_LOGGER: logging.Logger = logging.getLogger(__package__)
STREAMS = [STREAM_MAIN, STREAM_SUB, STREAM_BOTH]
DEFAULT_EVENTS = ["VideoMotion", "CrossLineDetection", "AlarmLocal", "VideoLoss", "VideoBlind"]
ALL_EVENTS = ["VideoMotion",
"VideoLoss",
"AlarmLocal",
"CrossLineDetection",
"AudioAnomaly",
"AudioMutation",
"VideoMotionInfo",
"SmartMotionHuman",
"SmartMotionVehicle",
"NewFile",
"VideoBlind",
"IntelliFrame",
"CrossRegionDetection",
"LeftDetection",
"TakenAwayDetection",
"VideoAbnormalDetection",
"FaceDetection",
"VideoUnFocus",
"WanderDetection",
"RioterDetection",
"ParkingDetection",
"MoveDetection",
"StorageNotExist",
"StorageFailure",
"StorageLowSpace",
"AlarmOutput",
"InterVideoAccess",
"NTPAdjustTime",
"TimeChange",
"MDResult",
"HeatImagingTemper",
"CrowdDetection",
"FireWarning",
"FireWarningInfo",
]
"""
https://developers.home-assistant.io/docs/data_entry_flow_index
"""
class DahuaFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Config flow for Dahua Camera API."""
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
def __init__(self):
"""Initialize."""
self.dahua_config = {}
self._errors = {}
self.init_info = None
async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user to add a camera."""
self._errors = {}
# Uncomment the next 2 lines if only a single instance of the integration is allowed:
# if self._async_current_entries():
# return self.async_abort(reason="single_instance_allowed")
if user_input is not None:
data = await self._test_credentials(
user_input[CONF_USERNAME],
user_input[CONF_PASSWORD],
user_input[CONF_ADDRESS],
user_input[CONF_PORT],
user_input[CONF_RTSP_PORT],
)
if data is not None:
# Only allow a camera to be setup once
if "serialNumber" in data and data["serialNumber"] is not None:
await self.async_set_unique_id(data["serialNumber"])
self._abort_if_unique_id_configured()
user_input[CONF_NAME] = data["name"]
self.init_info = user_input
return await self._show_config_form_name(user_input)
else:
self._errors["base"] = "auth"
return await self._show_config_form_user(user_input)
async def async_step_name(self, user_input=None):
"""Handle a flow to configure the camera name."""
self._errors = {}
if user_input is not None:
if self.init_info is not None:
self.init_info.update(user_input)
return self.async_create_entry(
title=self.init_info["name"],
data=self.init_info,
)
return await self._show_config_form_name(user_input)
@staticmethod
@callback
def async_get_options_flow(config_entry):
return DahuaOptionsFlowHandler(config_entry)
async def _show_config_form_user(self, user_input): # pylint: disable=unused-argument
"""Show the configuration form to edit camera name."""
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
vol.Required(CONF_ADDRESS): str,
vol.Required(CONF_PORT, default="80"): str,
vol.Required(CONF_RTSP_PORT, default="554"): str,
vol.Required(CONF_STREAMS, default=STREAMS[0]): vol.In(STREAMS),
vol.Optional(CONF_EVENTS, default=DEFAULT_EVENTS): cv.multi_select(ALL_EVENTS),
}
),
errors=self._errors,
)
async def _show_config_form_name(self, user_input): # pylint: disable=unused-argument
"""Show the configuration form to edit location data."""
return self.async_show_form(
step_id="name",
data_schema=vol.Schema(
{
vol.Required(CONF_NAME, default=user_input[CONF_NAME]): str,
}
),
errors=self._errors,
)
async def _test_credentials(self, username, password, address, port, rtsp_port):
"""Return name and serialNumber if credentials is valid."""
session = async_create_clientsession(self.hass)
try:
# The long term goal is to migrate to the DahuaRpc2Client client and remove the DahuaClient
# Testing this out via login to see how it goes
client = DahuaRpc2Client(username, password, address, port, rtsp_port, session)
await client.login()
_LOGGER.info("Authenticated with the RPC2 API")
name = await client.get_device_name()
serial = await client.get_serial_number()
await client.logout()
return {
"name": name,
"serialNumber": serial,
}
except Exception: # pylint: disable=broad-except
_LOGGER.warning("Could not connect to Dahua device via the RPC2 API, falling back to cgi")
try:
client2 = DahuaClient(username, password, address, port, rtsp_port, session)
data = await client2.get_machine_name()
serial = await client2.async_get_system_info()
data.update(serial)
if "name" in data:
return data
except Exception as exception: # pylint: disable=broad-except
_LOGGER.warning("Could not connect to Dahua device", exc_info=exception)
return None
class DahuaOptionsFlowHandler(config_entries.OptionsFlow):
"""Dahua config flow options handler."""
def __init__(self, config_entry):
"""Initialize HACS options flow."""
self.config_entry = config_entry
self.options = dict(config_entry.options)
async def async_step_init(self, user_input=None): # pylint: disable=unused-argument
"""Manage the options."""
return await self.async_step_user()
async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
if user_input is not None:
self.options.update(user_input)
return await self._update_options()
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(x, default=self.options.get(x, True)): bool
for x in sorted(PLATFORMS)
}
),
)
async def _update_options(self):
"""Update config entry options."""
return self.async_create_entry(
title=self.config_entry.data.get(CONF_USERNAME), data=self.options
)
| 34.983122 | 103 | 0.592329 | import logging
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.core import callback
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from homeassistant.helpers import config_validation as cv
from .client import DahuaClient
from .const import (
CONF_PASSWORD,
CONF_USERNAME,
CONF_ADDRESS,
CONF_RTSP_PORT,
CONF_PORT,
CONF_STREAMS,
CONF_EVENTS,
CONF_NAME,
STREAM_MAIN,
STREAM_SUB,
STREAM_BOTH,
DOMAIN,
PLATFORMS,
)
from .rpc2 import DahuaRpc2Client
_LOGGER: logging.Logger = logging.getLogger(__package__)
STREAMS = [STREAM_MAIN, STREAM_SUB, STREAM_BOTH]
DEFAULT_EVENTS = ["VideoMotion", "CrossLineDetection", "AlarmLocal", "VideoLoss", "VideoBlind"]
ALL_EVENTS = ["VideoMotion",
"VideoLoss",
"AlarmLocal",
"CrossLineDetection",
"AudioAnomaly",
"AudioMutation",
"VideoMotionInfo",
"SmartMotionHuman",
"SmartMotionVehicle",
"NewFile",
"VideoBlind",
"IntelliFrame",
"CrossRegionDetection",
"LeftDetection",
"TakenAwayDetection",
"VideoAbnormalDetection",
"FaceDetection",
"VideoUnFocus",
"WanderDetection",
"RioterDetection",
"ParkingDetection",
"MoveDetection",
"StorageNotExist",
"StorageFailure",
"StorageLowSpace",
"AlarmOutput",
"InterVideoAccess",
"NTPAdjustTime",
"TimeChange",
"MDResult",
"HeatImagingTemper",
"CrowdDetection",
"FireWarning",
"FireWarningInfo",
]
class DahuaFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
def __init__(self):
self.dahua_config = {}
self._errors = {}
self.init_info = None
async def async_step_user(self, user_input=None):
self._errors = {}
if user_input is not None:
data = await self._test_credentials(
user_input[CONF_USERNAME],
user_input[CONF_PASSWORD],
user_input[CONF_ADDRESS],
user_input[CONF_PORT],
user_input[CONF_RTSP_PORT],
)
if data is not None:
if "serialNumber" in data and data["serialNumber"] is not None:
await self.async_set_unique_id(data["serialNumber"])
self._abort_if_unique_id_configured()
user_input[CONF_NAME] = data["name"]
self.init_info = user_input
return await self._show_config_form_name(user_input)
else:
self._errors["base"] = "auth"
return await self._show_config_form_user(user_input)
async def async_step_name(self, user_input=None):
self._errors = {}
if user_input is not None:
if self.init_info is not None:
self.init_info.update(user_input)
return self.async_create_entry(
title=self.init_info["name"],
data=self.init_info,
)
return await self._show_config_form_name(user_input)
@staticmethod
@callback
def async_get_options_flow(config_entry):
return DahuaOptionsFlowHandler(config_entry)
async def _show_config_form_user(self, user_input):
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
vol.Required(CONF_ADDRESS): str,
vol.Required(CONF_PORT, default="80"): str,
vol.Required(CONF_RTSP_PORT, default="554"): str,
vol.Required(CONF_STREAMS, default=STREAMS[0]): vol.In(STREAMS),
vol.Optional(CONF_EVENTS, default=DEFAULT_EVENTS): cv.multi_select(ALL_EVENTS),
}
),
errors=self._errors,
)
async def _show_config_form_name(self, user_input):
return self.async_show_form(
step_id="name",
data_schema=vol.Schema(
{
vol.Required(CONF_NAME, default=user_input[CONF_NAME]): str,
}
),
errors=self._errors,
)
async def _test_credentials(self, username, password, address, port, rtsp_port):
session = async_create_clientsession(self.hass)
try:
client = DahuaRpc2Client(username, password, address, port, rtsp_port, session)
await client.login()
_LOGGER.info("Authenticated with the RPC2 API")
name = await client.get_device_name()
serial = await client.get_serial_number()
await client.logout()
return {
"name": name,
"serialNumber": serial,
}
except Exception:
_LOGGER.warning("Could not connect to Dahua device via the RPC2 API, falling back to cgi")
try:
client2 = DahuaClient(username, password, address, port, rtsp_port, session)
data = await client2.get_machine_name()
serial = await client2.async_get_system_info()
data.update(serial)
if "name" in data:
return data
except Exception as exception:
_LOGGER.warning("Could not connect to Dahua device", exc_info=exception)
return None
class DahuaOptionsFlowHandler(config_entries.OptionsFlow):
def __init__(self, config_entry):
self.config_entry = config_entry
self.options = dict(config_entry.options)
async def async_step_init(self, user_input=None):
return await self.async_step_user()
async def async_step_user(self, user_input=None):
if user_input is not None:
self.options.update(user_input)
return await self._update_options()
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(x, default=self.options.get(x, True)): bool
for x in sorted(PLATFORMS)
}
),
)
async def _update_options(self):
return self.async_create_entry(
title=self.config_entry.data.get(CONF_USERNAME), data=self.options
)
| true | true |
f72bc3b606d3adbd104ee19fb8f0f98ea61cc6ed | 36,568 | py | Python | python/avi/migrationtools/ace_converter/ace_parser.py | Crypto89/sdk | 56c48329b7ced2c56b7c92aa40bb52efb5f2e6c0 | [
"Apache-2.0"
] | 4 | 2017-06-16T18:51:52.000Z | 2020-02-11T15:22:42.000Z | vendor/github.com/avinetworks/sdk/python/avi/migrationtools/ace_converter/ace_parser.py | sudswasavi/servicemesh | 4f07c228e9b62c9b621cb0bfc464c75e85351f7f | [
"Apache-2.0"
] | 17 | 2019-01-11T05:57:35.000Z | 2019-08-29T05:33:38.000Z | vendor/github.com/avinetworks/sdk/python/avi/migrationtools/ace_converter/ace_parser.py | sudswasavi/servicemesh | 4f07c228e9b62c9b621cb0bfc464c75e85351f7f | [
"Apache-2.0"
] | 8 | 2017-06-26T18:15:58.000Z | 2021-04-12T08:09:03.000Z | import os
import sys
import logging
from pyparsing import Keyword, Word, OneOrMore, printables, Group, nums,\
alphas, ZeroOrMore, Optional, Combine, QuotedString, restOfLine
from itertools import cycle
from avi.migrationtools.ace_converter.ace_utils import printProgressBar,\
set_excel_dict
LOG = logging.getLogger(__name__)
def create_ace_grammer():
""" This function creates grammer for ace configuration parsing.
:return grammer for parsing
"""
# Pyparsing grammer starts here :excitement :-O
command = Group(Keyword('logging') | Keyword(
'access-list') | Keyword('probe'))
# Grammer Global
name = Word(printables)
ipaddress = Combine(Word(nums) + ('.' + Word(nums)) * 3)
num = Word(nums)
# Grammer 1:
# logging enable
# logging timestamp
# logging trap 9
# logging buffered 9
# logging host 127.0.0.1 udp/619
log = Keyword('logging')
single_key = Keyword('enable') | Keyword('timestamp')
double_key = (Keyword('trap') | Keyword('buffered')) + num
triple_key = Keyword('host') + ipaddress + name
grammer_1 = Group(log + (single_key | double_key | triple_key))
# Grammer 2:
# eg : access-list FROM_INSIDE line 11 extended permit ip <ip> 255.255.255.0 any
access = Keyword('access-list')
in_out = Keyword('FROM_INSIDE') | Keyword('FROM_OUTSIDE')
line = Keyword('line')
extend = Keyword('extended')
permit = Keyword('permit')
ip_key = Keyword('ip')
any_key = Keyword('any')
ip_any = ipaddress | any_key
grammer_2 = Group(access + in_out + line + num + extend + permit + ip_key +
ip_any + ip_any + ip_any)
# Grammer 3:
# eg: probe http prb_HTTP-1234
# port 1234
# receive 5
# interval 10
# expect status 200 200
# expect regex "(200|302)"
# ssl version all
# request method get url /test/test:ping
# passdetect interval 10
# open 3
probe = Keyword('probe')
type_key = Keyword('http') | Keyword(
'icmp') | Keyword('https') | Keyword('tcp')
grammer_3_1 = Group(probe + type_key + name)
grammer_3_2 = Group(Keyword('port') + Word(nums))
grammer_3_3 = Group(Keyword('receive') + Word(nums))
grammer_3_4 = Group(Keyword('interval') + Word(nums))
grammer_3_5 = Group((Keyword('expect') +
Keyword('status') + Word(nums) + Word(nums)) |
(Keyword('expect') +
Keyword('regex') + Word(printables)))
# grammer_3_6 = Group(Keyword('passdetect') + Keyword('interval') + num)
#grammer_3_7 = Group(Keyword('open') + num)
grammer_3_6 = Group(Keyword('ssl') + Keyword('version') + Keyword('all'))
grammer_3_7 = Group(Keyword('request') + Keyword('method') + Keyword('get') + Keyword('url') + Word(printables))
grammer_3_8 = Group(Keyword('request') + Keyword('method') + Word(printables))
grammer_3_9 = Group(Keyword('header') + Keyword('Host') + Keyword('header-value') + Word(printables))
grammer_3 = Group(grammer_3_1 + ZeroOrMore(grammer_3_2 | grammer_3_3 |
grammer_3_4 | grammer_3_5 |
grammer_3_6 | grammer_3_7 |
grammer_3_8 | grammer_3_9 ))
# grammer 4:
# rserver host rs_Test123
# description TEST_DESC
# ip address 127.0.0.1
# webhost-redirection https://www.google.com/test/1234/ 301
# probe prb_HTTP-1234
# inservice
rserver_key = Keyword('rserver')
host = Keyword('host')
rserver_name = Word(printables)
grammer_4_1 = Group(rserver_key + host + rserver_name)
grammer_4_2 = Group(Keyword('description') + restOfLine)
grammer_4_3 = Group(Keyword('ip address') + ipaddress)
grammer_4_4 = Group(Keyword('probe') + Word(printables))
grammer_4_5 = Group(Keyword('inservice'))
grammer_4_6 = Group(Keyword('webhost-redirection') + Word(printables) +
num)
grammer_4 = Group(grammer_4_1 + ZeroOrMore(grammer_4_2 | grammer_4_3 |
grammer_4_4 | grammer_4_5 |
grammer_4_6))
# grammer 5
# parameter-map type <connection|http|ssl> ALLOW_TEST
# tcp-options selective-ack allow
# tcp-options timestamp allow
# tcp-options window-scale allow
# persistence-rebalance strict
# set timeout inactivity 9999
# session-cache timeout 300
# queue-delay timeout 1
# set header-maxparse-length 65535
# set content-maxparse-length 65535
# cipher RSA_EXPORT1024_WITH_RC4_56_SHA
param_key = Keyword('parameter-map')
type_key = Word('type')
connection = Word('connection') | Word('http') | Word('ssl')
param_name = Word(printables)
tcp_key = Word('tcp-options')
tcp_type = Keyword('timestamp') | Keyword(
'window-scale') | Keyword('selective-ack')
allow = Word('allow')
sess_queue = Keyword('session-cache') | Keyword('queue-delay')
timeout = Keyword('timeout')
set = Keyword('set')
length = Keyword(
'header-maxparse-length') | Keyword('content-maxparse-length')
grammer_5_1 = Group(param_key + type_key + connection + param_name)
grammer_5_2 = Group(tcp_key + tcp_type + allow)
grammer_5_3 = Group(
Keyword('persistence-rebalance') + Keyword('strict'))
grammer_5_4 = Group(Keyword('set') + Keyword('timeout') + Keyword('inactivity') +
Word(nums))
grammer_5_5 = Group(set + length + num)
grammer_5_6 = Group(sess_queue + timeout + num)
grammer_5_7 = Group(Keyword('cipher') + name)
grammer_5_8 = Keyword('case-insensitive')
grammer_5_9 = Group(Keyword('parsing') + name)
grammer_5_10 = Group(Keyword('exceed-mss') + name)
grammer_5 = Group(grammer_5_1 + ZeroOrMore(
grammer_5_2 | grammer_5_3 | grammer_5_4 | grammer_5_6 |
grammer_5_7 | grammer_5_8 | grammer_5_9 | grammer_5_10))
# Grammer 6:
# sticky ip-netmask 255.255.255.255 address source test-adfdas-$5D
# sticky http-cookie TEST TEST_COOKIE
# serverfarm sf_TEST
# timeout 1000
# replicate sticky
# cookie insert browser-expire
# 8 static cookie-value "ONETXEIS" rserver ESC20_TXEIS_APP_1 443
sticky = Keyword('sticky')
ipnetmask = Keyword('ip-netmask')
http_cookie = Keyword('http-cookie')
address = Keyword('address')
source = Keyword('source')
sticky_name = Word(printables)
cookie = Keyword('cookie')
insert = Keyword('insert')
browser_expire = Keyword('browser-expire')
static = Keyword('static')
cookie_val = Keyword('cookie-value')
grammer_6_1 = Group(sticky + ipnetmask + ipaddress +
address + source + sticky_name) | Group(sticky +
http_cookie + name + name)
grammer_6_2 = Group(Keyword('serverfarm') + Word(printables))
grammer_6_3 = Group(Keyword('timeout') + Word(nums))
grammer_6_4 = Group(Keyword('replicate') + sticky)
grammer_6_5 = Group(cookie + insert + browser_expire)
grammer_6_6 = Group(num + static + cookie_val + name + rserver_key +
name + num)
grammer_6 = Group(grammer_6_1 + ZeroOrMore(grammer_6_2 | grammer_6_3 |
grammer_6_4 | grammer_6_5 |
grammer_6_6))
# grammer7:
# class-map type management match-any TEST-PROTOCOLS
# class-map match-any TEST_TEST_123
# class-map match-any TEST_TEST_123
# class-map match-all TEST_TEST_123
# 2 match protocol icmp source-address 127.0.0.1 255.0.0.0
# 3 match protocol snmp source-address 127.0.0.1 255.255.255.0
# 2 match destination-address 127.0.0.1 255.255.255.0
# 3 match source-address 127.0.0.1 255.255.255.0
# 2 match virtual-address 127.0.0.1 tcp eq 1234
# 2 match virtual-address 127.0.0.1 tcp any
# 2 match http url .*
classmap = Keyword('class-map')
classmap_type = Keyword('type')
mgmt = Keyword('management') | (
Keyword('http') + Keyword('loadbalance'))
type_key_att = classmap_type + mgmt
match_key = Keyword('match-any') | Keyword('match-all')
grammer7_1 = Group(classmap + match_key + name)
match_key = Keyword('match')
proto_key = Keyword('protocol')
grammer_url = Group(
num + match_key + Keyword('http') + Keyword('url') + name)
proto_type = Keyword('tcp') | Keyword('icmp') | Keyword(
'snmp') | Keyword('http') | Keyword('https') | Keyword('udp')
proto = proto_key + proto_type
source_dest = Keyword(
'source-address') | Keyword('destination-address')
virtual_add = Keyword('virtual-address')
eq_key = Keyword('eq')
eq_val = Keyword('https') | Keyword('www') | Keyword('http') | num
any_key = Keyword('any')
add_att = Optional(proto) + source_dest + ipaddress + ipaddress
virt_att = virtual_add + ipaddress + \
proto_type + ((eq_key + eq_val) | any_key)
grammer7_2 = Group(num + match_key +
(add_att | virt_att)) | grammer_url
grammer_7 = Group(grammer7_1 + ZeroOrMore(grammer7_2))
# grammer8:
# policy-map type loadbalance first-match LB_TEST_MAP_1235
# class class-default
# serverfarm TEST_FARM_2
# sticky-serverfarm TEST_FARM_2
# connection advanced-options TEST_CONN123
# loadbalance vip inservice
# loadbalance vip icmp-reply
# loadbalance policy LB_TEST_123
# inspect ftp
# ssl-proxy server ssl_name
# nat dynamic 5 vlan 2100
# appl-parameter http advanced-options ADV-HTTP
# connection advanced-options NETSETTINGS
# action test_rewrite
policy_key = Keyword('policy-map')
lb_key = Keyword('loadbalance')
match = Keyword('first-match') | Keyword('multi-match')
grammer_8_1 = Group(
policy_key + Optional(type_key + lb_key) + match + name)
grammer_8_2_1 = Group(Keyword('class') + name)
grammer_8_2_2 = Group((
(Keyword('serverfarm') | Keyword('action') |
Keyword('sticky-serverfarm')) + name) | Keyword('drop') |
Keyword('insert-http') + restOfLine)
grammer_8_2_3 = Group(Keyword('connection') +
Keyword('advanced-option') + name)
lb_vip = Keyword('vip') + (
Keyword('inservice') | Keyword('icmp-reply') +
ZeroOrMore(Keyword('active') +
ZeroOrMore(Keyword('primary-inservice'))) | Keyword('inservice'))
lb_policy = Keyword('policy') + name
grammer_8_2_4 = Group(Keyword('loadbalance') + (lb_vip | lb_policy))
grammer_8_2_5 = Group(Keyword('inspect') + Keyword('ftp'))
grammer_8_2_6 = Group(Keyword('ssl-proxy') + Keyword('server') + name)
grammer_8_2_7 = Group(Keyword('nat') + Keyword('dynamic') + num +
Keyword('vlan') + num)
grammer_8_2_8 = Group(Keyword('appl-parameter') + Keyword('http') +
Keyword('advanced-options') + name)
grammer_8_2_9 = Group(Keyword('connection') +
Keyword('advanced-options') +
name)
grammer_8_2_10 = Group(Keyword('action') + name)
grammer_8_3 = Group(Keyword('description') + restOfLine)
grammer_8_2 = Group(grammer_8_2_1 + ZeroOrMore(
grammer_8_2_2 | grammer_8_2_3 | grammer_8_2_4 | grammer_8_2_5 |
grammer_8_2_6 | grammer_8_2_7 | grammer_8_2_8 | grammer_8_2_9 |
grammer_8_2_10))
grammer_8 = Group(grammer_8_1 + ZeroOrMore(grammer_8_3) +
ZeroOrMore(grammer_8_2))
# grammer9:
# interface vlan 1011
# ip address 127.0.0.1 255.255.255.0
# alias 127.0.0.1 255.255.255.0
# peer ip address 127.0.0.1 255.255.255.0
# access-group input FROM_TEST
# service-policy input TEST_ACCESS
# service-policy input vs_TEST
# service-policy input TEST_POLICY_8080
# no shutdown
# nat-pool 1 127.0.0.1 127.0.0.1 netmask 255.255.255.255 pat
grammer_9_1 = Group(Keyword('interface') + Keyword('vlan') + num)
grammer_9_2 = Group(ip_key + address + ipaddress + ipaddress)
grammer_9_3 = Group(Keyword('alias') + ipaddress + ipaddress)
grammer_9_4 = Group(Keyword('peer') + ip_key +
address + ipaddress + ipaddress)
grammer_9_5 = Group(Keyword('access-group') + Keyword('input') + name)
grammer_9_6 = Group(Keyword('service-policy') +
Keyword('input') + name)
grammer_9_7 = Group(Keyword('no') + Keyword('shutdown'))
grammer_9_8 = Group(Keyword('nat-pool') + num + ipaddress + ipaddress +
Keyword('netmask') + ipaddress + Keyword('pat'))
grammer_9 = Group(grammer_9_1 + ZeroOrMore(grammer_9_2 | grammer_9_3 |
grammer_9_4 | grammer_9_5 |
grammer_9_6 | grammer_9_7 |
grammer_9_8))
# grammer 10:
# ip route 0.0.0.0 0.0.0.0 127.0.0.1
grammer_10 = Group(ip_key + Keyword('route') + ipaddress + ipaddress)
# grammer 11:
# snmp-server host 127.0.0.1 traps version 2c ********
# snmp-server enable traps slb k7server
snmp = Keyword('snmp-server')
host = Keyword('host')
traps = Keyword('traps')
slb = Keyword('slb')
version = Keyword('version')
enable = Keyword('enable')
host_att = host + ipaddress + traps + version + name + name
ord_att = enable + traps + slb + name
grammer_11 = Group(snmp + (host_att | ord_att))
# grammer 12
# serverfarm host TEST_TEST_79
# probe probe_TEST_123
# inband-health check count
# predictor leastconns slowstart 30
# rserver RS_TEST123
# inservice
serverfarm = Keyword('serverfarm')
host = Keyword('host')
grammer_12_1 = Group(serverfarm + host + name)
grammer_12_2 = Group(Keyword('probe') + name)
grammer_12_3 = Group(Keyword('inband-health') +
Keyword('check') + name)
grammer_12_4_1 = Keyword('rserver') + ~Word(
'host') + name + ZeroOrMore(num)
grammer_12_4_2 = Keyword('inservice') + Optional(Keyword('standby'))
grammer_12_4_3 = Group(Keyword('probe') + restOfLine)
grammer_12_4_4 = Group(Keyword('backup-rserver') + restOfLine)
grammer_12_4 = Group(grammer_12_4_1 + ZeroOrMore(grammer_12_4_3) +
ZeroOrMore(grammer_12_4_4) +
ZeroOrMore(grammer_12_4_2))
grammer_12_5 = Group(Keyword('predictor') + Keyword('leastconns') +
Keyword('slowstart') + num)
grammer_12_6 = Group(Keyword('description') + restOfLine)
grammer_12_7 = Group(Keyword('predictor') + restOfLine)
grammer_12_8 = Group(Keyword('retcode') + restOfLine)
grammer_12_9 = Group(Keyword('failaction') + restOfLine)
grammer_12_10 = Keyword('fail-on-all')
grammer_12 = Group(grammer_12_1 + ZeroOrMore(
grammer_12_2 | grammer_12_3 | grammer_12_4 | grammer_12_5 |
grammer_12_6 | grammer_12_7 | grammer_12_8 | grammer_12_9 |
grammer_12_10))
# grammer ssl
# ssl-proxy service SSL_CLIENT
# key KEY12.PEM
# cert CERT12.PEM
# ssl advanced-options PM1
grammer_ssl = Group(Keyword('ssl-proxy') + Keyword('service') + name)
grammer_ssl_key = Group(Keyword('key') + name)
grammer_ssl_cert = Group(Keyword('cert') + name)
grammer_ssl_chaingroup = Group(Keyword('chaingroup') + name)
grammer_ssl_opt = Group(Keyword('ssl') + Keyword('advanced-options') +
name)
grammer_ssl_comp = Group(grammer_ssl + ZeroOrMore(grammer_ssl_key |
grammer_ssl_cert |
grammer_ssl_chaingroup |
grammer_ssl_opt))
# Grammer crypto:
# eg: crypto chaingroup ACME-PROD-CA_CHAINGROUP
# cert acme-prod-root-ca_24092044.crt
# cert acme-prod-issuing-ca_22102028.crt
#
# crypto csr-params llprd-frontend-csr
# country DK
# state Sealand
# organization-name ACME
# organization-unit ACME Input Management
# common-name tcpwebprod.prod.acmeintern.dk
# crypto csr-params llprd-backend-csr
# country DK
# state Sealand
# organization-name ACME
# organization-unit ACME Input Management
# common-name acmenpap.prod.acmeintern.dk
#grammer for crypto chaingroup test_group
# cert Test_cert.crt
grammer_crypto_1 = Group(
Keyword('crypto') + Keyword('chaingroup') + name)
grammer_crypto_2 = Group(Keyword('cert') + name)
grammer_crypto_3 = Group(grammer_crypto_1 + ZeroOrMore(grammer_crypto_2))
#grammer for crypto csr-params
grammer_crypto_4 = Group(
Keyword('crypto') + Keyword('csr-params') + name)
grammer_crypto_5 = Group(Keyword('country') + name)
grammer_crypto_6 = Group(Keyword('state') + name)
grammer_crypto_7 = Group(Keyword('organization-name') + restOfLine)
grammer_crypto_8 = Group(Keyword('organization-unit') + name)
grammer_crypto_9 = Group(Keyword('common-name') + name)
grammer_crypto_10 = Group(grammer_crypto_4 + ZeroOrMore(grammer_crypto_5 |
grammer_crypto_6 | grammer_crypto_7 | grammer_crypto_8 |
grammer_crypto_9))
# aaa authentication login default group TAC_PLUS local
# aaa accounting default group TAC_PLUS
grammer_aaa_1 = Keyword('aaa')
grammer_aaa_2 = Keyword(
'authentication login') | Keyword('accounting')
grammer_aaa_3 = Keyword('default')
grammer_aaa_4 = Keyword('group')
grammer_aaa_5 = Keyword('local')
grammer_aaa = Group(grammer_aaa_1 + grammer_aaa_2 + grammer_aaa_3 +
grammer_aaa_4 + (name | grammer_aaa_5))
# action-list type modify http test-ssl-rewrite
# ssl url rewrite location ".*"
# header rewrite request Host header-value "(.*)" replace "%1\/"
grammer_al_1 = Keyword('action-list')
grammer_al_2 = Keyword('type')
grammer_al_3 = Keyword('modify')
grammer_al_4 = Keyword('http')
grammer_al_5 = Keyword('ssl')
grammer_al_6 = Keyword('url')
grammer_al_7 = Keyword('rewrite')
grammer_al_8 = Keyword('location')
grammer_al_9 = Keyword('header')
grammer_al_10 = Keyword('request')
grammer_al_11 = Keyword('Host')
grammer_al_12 = Keyword('header-value')
grammer_al_13 = Keyword('replace')
grammer_al_1_1 = Group(
grammer_al_5 + grammer_al_6 + grammer_al_7 + grammer_al_8 + name)
grammer_al_1_2 = Group(
grammer_al_9 + grammer_al_7 + grammer_al_10 + grammer_al_11 +
grammer_al_12 + name + grammer_al_13 + name
)
grammer_al = Group(Group(grammer_al_1 + grammer_al_2 +
grammer_al_3 + grammer_al_4 + name) +
ZeroOrMore(grammer_al_1_1 | grammer_al_1_2))
# Overall Grammer
grammer = Group(grammer_1 | grammer_2 | grammer_3 | grammer_4 |
grammer_5 | grammer_6 | grammer_7 | grammer_8 |
grammer_9 | grammer_10 | grammer_11 | grammer_12 |
grammer_ssl_comp | grammer_aaa | grammer_crypto_3 | grammer_crypto_10 | grammer_al)
print "Grammer created for ace config parser."
LOG.info("Grammer created for ace config parser.")
return grammer
def parse_ace_grammer(grammer, data, file_size, out_dict, final_excel, total_parse_count):
""" This function parse grammer for ace converter convertes to intermediate parser output.
:return parsed intermediate output.
"""
LOG.info("Started ace grammer parsing.")
final_dict = dict()
for match, start, end in grammer.scanString(data):
key = ''
extra_dict = {}
# printing progress bar
msg = ''
printProgressBar(end, file_size, msg, prefix='Progress', suffix='')
if match:
matched = match.asList()
out_dict.append(matched)
if type(matched[0][0][0]) is list:
key = matched[0][0][0][0]
name_to_log = matched[0][0][0][1]
else:
key = matched[0][0][0]
name_to_log = matched[0][0][1]
LOG.info('Parsing happening for :{} -> {}'.format(key, name_to_log))
excel_dict = {
'name': '',
'type': '',
'command': '',
'converted': 'n',
'status': 'Not Supported',
'skipped': [],
'indirect': [],
'NA': [],
'Avi Object': ''
}
name_to_log = None
type_to_log = ['logging', 'access-list', 'rserver', 'serverfarm',
'parameter-map', 'class-map', 'policy-map', 'sticky',
'probe', 'action-list', 'crypto']
if key == 'logging':
matched = matched[0][0]
name_to_log = matched[1]
if len(matched) == 2:
extra_dict = {
'log_type': matched[1]
}
elif len(matched) == 3:
extra_dict = {
'log_type': matched[1],
'value': matched[2]
}
elif len(matched) == 4:
extra_dict = {
'log_type': matched[1],
'value': matched[2],
'packet': matched[3]
}
LOG.info('parsing: Logging for value : {}'.format(name_to_log))
if key == 'access-list':
matched = matched[0][0]
name_to_log = "{} line {}".format(matched[0][1], matched[0][4])
extra_dict = {
'type': matched[1],
matched[2]: matched[3],
'extend': matched[4],
'permit': matched[5],
'ip1': matched[7],
'ip2': matched[8],
'ip3': matched[9]
}
LOG.info('parsing: Access-list {}'.format(name_to_log))
if key == 'rserver':
matched = matched[0][0]
name_to_log = matched[0][2]
extra_dict = {
matched[0][1]: matched[0][2],
'desc': []
}
for match in matched[1:]:
if len(match) == 1:
temp_dict = {
'type': match[0]
}
elif len(match) == 3:
temp_dict = {
'type': 'redirect',
'code': match[2],
'location': match[1]
}
else:
temp_dict = {
match[0]: match[1]
}
extra_dict['desc'].append(temp_dict)
LOG.info('parsing: rserver for value : {}'.format(name_to_log))
if key == 'serverfarm':
matched = matched[0][0]
name_to_log = matched[0][2]
extra_dict = {
matched[0][1]: matched[0][2], # getting serverfarm name
'desc': []
}
for match in matched[1:]:
temp_dict = dict()
if len(match) < 3:
temp_dict = {
match[0]: match[1]
}
# Handled object such as ['rserver', 'ACMENPMOS01', '9217', 'inservice'] or #For Object such as
# ['rserver', 'ACMENPMOS02', 'inservice']. Taken care of port is present or not in input
# configuration file.
elif 'rserver' in match:
if len(match) >= 4:
temp_dict = {
match[0]: match[1],
# if port no is present in configuration.
'port': match[2],
# inservice status
'enabled': match[4] if len(match) > 4 else match[3]
}
else:
temp_dict = {
match[0]: match[1],
'enabled': match[2] if len(match)>2 else 'false'
}
# Atleast 2 keys must be presents. i.e. rserver keyword and rserver name. If both present then only add
# that filed into serverfarm otherwise just ignore.
if len(temp_dict.keys()) > 1:
extra_dict['desc'].append(temp_dict)
LOG.info('parsing: server farm for value : {}'.format(name_to_log))
if key == 'parameter-map':
matched = matched[0][0]
name_to_log = matched[0][3]
extra_dict = {
matched[0][1]: matched[0][2],
'conn_name': matched[0][3],
'desc': []
}
for match in matched[1:]:
if len(match) == 2:
temp_dict = {
match[0]: match[1]
}
else:
temp_dict = {
match[0]: match[1],
'allow': match[2]
}
extra_dict['desc'].append(temp_dict)
LOG.info(
'parsing: parameter-map for value : {}'.format(name_to_log))
if key == 'class-map':
matched = matched[0][0]
name_to_log = matched[0][2]
extra_dict = {
matched[0][0]: matched[0][2],
'type': matched[0][1],
'desc': []
}
for match in matched[1:]:
temp_dict = dict()
if len(match) == 7:
temp_dict = {
match[1]: match[0],
match[2]: match[3],
match[4]: match[6]
}
elif len(match) == 5:
temp_dict = {
match[1]: match[0],
match[2]: match[3],
"mask": match[4]
}
elif len(match) == 6:
temp_dict = {
match[1]: match[0],
match[2]: match[3],
match[4]: match[5]
}
extra_dict['desc'].append(temp_dict)
LOG.info('parsing: class-map for value : {}'.format(name_to_log))
if key == 'policy-map':
matched = matched[0][0]
if len(matched[0]) == 5:
extra_dict = {
matched[0][1]: matched[0][2],
'match': matched[0][3],
'name': matched[0][4],
'desc': []
}
name_to_log = matched[0][4]
else:
extra_dict = {
matched[0][0]: matched[0][2],
'match': matched[0][1],
'desc': []
}
name_to_log = matched[0][2]
for match in matched[1:]:
temp_dict = dict()
temp_dict = {
match[0][0]: match[0][1],
'class_desc': []
}
for match1 in match[1:]:
temp_dict_1 = dict()
if len(match1) == 2:
temp_dict_1 = {
match1[0]: match1[1]
}
elif len(match1) == 3:
temp_dict_1 = {
match1[0]: match1[1],
'type': match1[2]
}
temp_dict['class_desc'].append(temp_dict_1)
extra_dict['desc'].append(temp_dict)
LOG.info('parsing: policy-map for value : {}'.format(name_to_log))
if key == 'sticky':
matched = matched[0][0]
if len(matched[0]) == 6:
name_to_log = matched[0][5]
extra_dict = {
matched[0][1]: matched[0][2],
'name': matched[0][5],
'desc': []
}
if len(matched[0]) == 4:
name_to_log = matched[0][3]
extra_dict = {
matched[0][1]: matched[0][1],
'name': name_to_log,
'desc': []
}
for match in matched[1:]:
temp_dict = dict()
if len(match) == 2:
temp_dict = {
match[0]: match[1]
}
extra_dict['desc'].append(temp_dict)
LOG.info('parsing: sticky for value : {}'.format(name_to_log))
if key == 'ssl-proxy':
matched = matched[0][0]
name_to_log = matched[0][2]
extra_dict = {
'type': matched[0][1],
'name': name_to_log,
'desc': []
}
for match in matched[1:]:
if len(match) == 2:
temp_dict = {
match[0]: match[1]
}
if len(match) == 3:
temp_dict = {
match[0]: match[1],
'name': match[2]
}
extra_dict['desc'].append(temp_dict)
# action-list type modify http test-ssl-rewrite
# ssl url rewrite location ".*"
# header rewrite request Host header-value "(.*)" replace "%1\/"
if key == 'action-list':
matched = matched[0][0]
name_to_log = matched[0][4]
extra_dict = {
matched[0][0]: name_to_log,
matched[0][1]: matched[0][2],
matched[0][3]: matched[0][4],
'desc': []
}
for match in matched[1:]:
if len(match) == 5:
temp_dict = {
match[0]: match[1],
match[2]: match[3],
"to": match[4]
}
if len(match) == 8:
temp_dict = {
match[0]: match[1],
match[2]: match[3],
match[4]: match[5],
match[6]: match[7],
}
extra_dict['desc'].append(temp_dict)
LOG.info('parsing: action-list for value : {}'.format(name_to_log))
if key == 'probe':
matched = matched[0][0]
name_to_log = matched[0][2]
extra_dict = {
'type': matched[0][1],
'name': matched[0][2],
}
for match in matched[1:]:
temp_dict = dict()
if len(match) == 2:
temp_dict = {
match[0]: match[1]
}
if len(match) == 4:
if 'status' in match:
temp_dict = {
'status': match[2],
'status1': match[3]
}
elif 'header' in match:
temp_dict = {
'host': match[1],
'header-value': match[3]
}
if len(match) == 3:
if 'regex' in match:
temp_dict = {
'regex': 'yes'
}
if len(match) == 5:
temp_dict = {
match[1]: match[2],
match[3]: match[4]
}
extra_dict.update(temp_dict)
LOG.info('parsing: probe for value : {}'.format(name_to_log))
if key == 'crypto':
matched = matched[0][0]
name_to_log = matched[0][2]
if matched[0][1] == 'chaingroup':
extra_dict = {
'cert': [],
matched[0][1]: matched[0][2],
}
for match in matched[0:]:
temp_dict = dict()
if 'cert' in match:
# getting chaingroup certs
extra_dict['cert'].append(match[1])
elif 'csr-params' in match:
temp_dict = {
# getting CSR params such as country, state, organization name.
match[1]: match[2]
}
else:
temp_dict = {
match[0]: match[1]
}
extra_dict.update(temp_dict)
LOG.info('parsing: crypto for value : {}'.format(name_to_log))
# Updating excel sheet
if key in type_to_log and name_to_log:
excel_dict['name'] = name_to_log
excel_dict['type'] = key
final_excel.append(excel_dict)
if key not in final_dict.keys():
final_dict.update({key: [extra_dict]})
else:
final_dict[key].append(extra_dict)
set_excel_dict(final_excel)
printProgressBar(file_size, file_size, msg,
prefix='Progress', suffix='')
return final_dict
class Parser():
""" This class is for Parsing
- Parsing grammars are written in pyparsing
"""
def __init__(self, file_name):
self.file_name = file_name
def parse_ace(self):
out_dict = []
total_parse_count = 0
final_excel = []
with open(self.file_name, 'r') as input_config:
input_data = input_config.read()
input_config.seek(0, 2)
file_size = input_config.tell()
overall_grammer = create_ace_grammer()
parsed_ace_config = parse_ace_grammer(overall_grammer, input_data, file_size, out_dict, final_excel, total_parse_count)
return parsed_ace_config
if __name__ == '__main__':
s = """
serverfarm host sfarm_IDST-EXTADRESSBUCH-HTTPS
probe probe_L7_IDST-EXTADRESSBUCH-HTTPS
fail-on-all
rserver rserver_L0550022 443
inservice
rserver rserver_L0551022 443
inservice
"""
name = Word(printables)
num = Word(nums)
serverfarm = Keyword('serverfarm')
host = Keyword('host')
grammer_12_1 = Group(serverfarm + host + name)
grammer_12_2 = Group(Keyword('probe') + name)
grammer_12_3 = Group(Keyword('inband-health') +
Keyword('check') + name)
grammer_12_4_1 = Keyword('rserver') + ~Word(
'host') + name + ZeroOrMore(num)
grammer_12_4_2 = Keyword('inservice') + Optional(Keyword('standby'))
grammer_12_4_3 = Group(Keyword('probe')+ restOfLine)
grammer_12_4_4 = Group(Keyword('backup-rserver') + restOfLine)
grammer_12_4 = Group(grammer_12_4_1 + ZeroOrMore(grammer_12_4_3) +
ZeroOrMore(grammer_12_4_4) +
ZeroOrMore(grammer_12_4_2))
grammer_12_5 = Group(Keyword('predictor') + Keyword('leastconns') +
Keyword('slowstart') + num)
# grammer_12_6 = Group(Keyword('description') + printables)
# grammer_12_7 = Group(Keyword('predictor') + printables)
grammer_12_6 = Group(Keyword('description') + restOfLine)
grammer_12_7 = Group(Keyword('predictor') + restOfLine)
grammer_12_8 = Group(Keyword('retcode') + restOfLine)
grammer_12_9 = Keyword('fail-on-all')
grammer_12 = Group(grammer_12_1 + ZeroOrMore(
grammer_12_2 | grammer_12_2 | grammer_12_3 | grammer_12_4 |
grammer_12_5 | grammer_12_6 | grammer_12_7 | grammer_12_8 |
grammer_12_9))
for match, start, end in grammer_12.scanString(s):
print match
| 39.834423 | 127 | 0.52751 | import os
import sys
import logging
from pyparsing import Keyword, Word, OneOrMore, printables, Group, nums,\
alphas, ZeroOrMore, Optional, Combine, QuotedString, restOfLine
from itertools import cycle
from avi.migrationtools.ace_converter.ace_utils import printProgressBar,\
set_excel_dict
LOG = logging.getLogger(__name__)
def create_ace_grammer():
""" This function creates grammer for ace configuration parsing.
:return grammer for parsing
"""
command = Group(Keyword('logging') | Keyword(
'access-list') | Keyword('probe'))
name = Word(printables)
ipaddress = Combine(Word(nums) + ('.' + Word(nums)) * 3)
num = Word(nums)
log = Keyword('logging')
single_key = Keyword('enable') | Keyword('timestamp')
double_key = (Keyword('trap') | Keyword('buffered')) + num
triple_key = Keyword('host') + ipaddress + name
grammer_1 = Group(log + (single_key | double_key | triple_key))
access = Keyword('access-list')
in_out = Keyword('FROM_INSIDE') | Keyword('FROM_OUTSIDE')
line = Keyword('line')
extend = Keyword('extended')
permit = Keyword('permit')
ip_key = Keyword('ip')
any_key = Keyword('any')
ip_any = ipaddress | any_key
grammer_2 = Group(access + in_out + line + num + extend + permit + ip_key +
ip_any + ip_any + ip_any)
probe = Keyword('probe')
type_key = Keyword('http') | Keyword(
'icmp') | Keyword('https') | Keyword('tcp')
grammer_3_1 = Group(probe + type_key + name)
grammer_3_2 = Group(Keyword('port') + Word(nums))
grammer_3_3 = Group(Keyword('receive') + Word(nums))
grammer_3_4 = Group(Keyword('interval') + Word(nums))
grammer_3_5 = Group((Keyword('expect') +
Keyword('status') + Word(nums) + Word(nums)) |
(Keyword('expect') +
Keyword('regex') + Word(printables)))
grammer_3_6 = Group(Keyword('ssl') + Keyword('version') + Keyword('all'))
grammer_3_7 = Group(Keyword('request') + Keyword('method') + Keyword('get') + Keyword('url') + Word(printables))
grammer_3_8 = Group(Keyword('request') + Keyword('method') + Word(printables))
grammer_3_9 = Group(Keyword('header') + Keyword('Host') + Keyword('header-value') + Word(printables))
grammer_3 = Group(grammer_3_1 + ZeroOrMore(grammer_3_2 | grammer_3_3 |
grammer_3_4 | grammer_3_5 |
grammer_3_6 | grammer_3_7 |
grammer_3_8 | grammer_3_9 ))
rserver_key = Keyword('rserver')
host = Keyword('host')
rserver_name = Word(printables)
grammer_4_1 = Group(rserver_key + host + rserver_name)
grammer_4_2 = Group(Keyword('description') + restOfLine)
grammer_4_3 = Group(Keyword('ip address') + ipaddress)
grammer_4_4 = Group(Keyword('probe') + Word(printables))
grammer_4_5 = Group(Keyword('inservice'))
grammer_4_6 = Group(Keyword('webhost-redirection') + Word(printables) +
num)
grammer_4 = Group(grammer_4_1 + ZeroOrMore(grammer_4_2 | grammer_4_3 |
grammer_4_4 | grammer_4_5 |
grammer_4_6))
param_key = Keyword('parameter-map')
type_key = Word('type')
connection = Word('connection') | Word('http') | Word('ssl')
param_name = Word(printables)
tcp_key = Word('tcp-options')
tcp_type = Keyword('timestamp') | Keyword(
'window-scale') | Keyword('selective-ack')
allow = Word('allow')
sess_queue = Keyword('session-cache') | Keyword('queue-delay')
timeout = Keyword('timeout')
set = Keyword('set')
length = Keyword(
'header-maxparse-length') | Keyword('content-maxparse-length')
grammer_5_1 = Group(param_key + type_key + connection + param_name)
grammer_5_2 = Group(tcp_key + tcp_type + allow)
grammer_5_3 = Group(
Keyword('persistence-rebalance') + Keyword('strict'))
grammer_5_4 = Group(Keyword('set') + Keyword('timeout') + Keyword('inactivity') +
Word(nums))
grammer_5_5 = Group(set + length + num)
grammer_5_6 = Group(sess_queue + timeout + num)
grammer_5_7 = Group(Keyword('cipher') + name)
grammer_5_8 = Keyword('case-insensitive')
grammer_5_9 = Group(Keyword('parsing') + name)
grammer_5_10 = Group(Keyword('exceed-mss') + name)
grammer_5 = Group(grammer_5_1 + ZeroOrMore(
grammer_5_2 | grammer_5_3 | grammer_5_4 | grammer_5_6 |
grammer_5_7 | grammer_5_8 | grammer_5_9 | grammer_5_10))
sticky = Keyword('sticky')
ipnetmask = Keyword('ip-netmask')
http_cookie = Keyword('http-cookie')
address = Keyword('address')
source = Keyword('source')
sticky_name = Word(printables)
cookie = Keyword('cookie')
insert = Keyword('insert')
browser_expire = Keyword('browser-expire')
static = Keyword('static')
cookie_val = Keyword('cookie-value')
grammer_6_1 = Group(sticky + ipnetmask + ipaddress +
address + source + sticky_name) | Group(sticky +
http_cookie + name + name)
grammer_6_2 = Group(Keyword('serverfarm') + Word(printables))
grammer_6_3 = Group(Keyword('timeout') + Word(nums))
grammer_6_4 = Group(Keyword('replicate') + sticky)
grammer_6_5 = Group(cookie + insert + browser_expire)
grammer_6_6 = Group(num + static + cookie_val + name + rserver_key +
name + num)
grammer_6 = Group(grammer_6_1 + ZeroOrMore(grammer_6_2 | grammer_6_3 |
grammer_6_4 | grammer_6_5 |
grammer_6_6))
classmap = Keyword('class-map')
classmap_type = Keyword('type')
mgmt = Keyword('management') | (
Keyword('http') + Keyword('loadbalance'))
type_key_att = classmap_type + mgmt
match_key = Keyword('match-any') | Keyword('match-all')
grammer7_1 = Group(classmap + match_key + name)
match_key = Keyword('match')
proto_key = Keyword('protocol')
grammer_url = Group(
num + match_key + Keyword('http') + Keyword('url') + name)
proto_type = Keyword('tcp') | Keyword('icmp') | Keyword(
'snmp') | Keyword('http') | Keyword('https') | Keyword('udp')
proto = proto_key + proto_type
source_dest = Keyword(
'source-address') | Keyword('destination-address')
virtual_add = Keyword('virtual-address')
eq_key = Keyword('eq')
eq_val = Keyword('https') | Keyword('www') | Keyword('http') | num
any_key = Keyword('any')
add_att = Optional(proto) + source_dest + ipaddress + ipaddress
virt_att = virtual_add + ipaddress + \
proto_type + ((eq_key + eq_val) | any_key)
grammer7_2 = Group(num + match_key +
(add_att | virt_att)) | grammer_url
grammer_7 = Group(grammer7_1 + ZeroOrMore(grammer7_2))
policy_key = Keyword('policy-map')
lb_key = Keyword('loadbalance')
match = Keyword('first-match') | Keyword('multi-match')
grammer_8_1 = Group(
policy_key + Optional(type_key + lb_key) + match + name)
grammer_8_2_1 = Group(Keyword('class') + name)
grammer_8_2_2 = Group((
(Keyword('serverfarm') | Keyword('action') |
Keyword('sticky-serverfarm')) + name) | Keyword('drop') |
Keyword('insert-http') + restOfLine)
grammer_8_2_3 = Group(Keyword('connection') +
Keyword('advanced-option') + name)
lb_vip = Keyword('vip') + (
Keyword('inservice') | Keyword('icmp-reply') +
ZeroOrMore(Keyword('active') +
ZeroOrMore(Keyword('primary-inservice'))) | Keyword('inservice'))
lb_policy = Keyword('policy') + name
grammer_8_2_4 = Group(Keyword('loadbalance') + (lb_vip | lb_policy))
grammer_8_2_5 = Group(Keyword('inspect') + Keyword('ftp'))
grammer_8_2_6 = Group(Keyword('ssl-proxy') + Keyword('server') + name)
grammer_8_2_7 = Group(Keyword('nat') + Keyword('dynamic') + num +
Keyword('vlan') + num)
grammer_8_2_8 = Group(Keyword('appl-parameter') + Keyword('http') +
Keyword('advanced-options') + name)
grammer_8_2_9 = Group(Keyword('connection') +
Keyword('advanced-options') +
name)
grammer_8_2_10 = Group(Keyword('action') + name)
grammer_8_3 = Group(Keyword('description') + restOfLine)
grammer_8_2 = Group(grammer_8_2_1 + ZeroOrMore(
grammer_8_2_2 | grammer_8_2_3 | grammer_8_2_4 | grammer_8_2_5 |
grammer_8_2_6 | grammer_8_2_7 | grammer_8_2_8 | grammer_8_2_9 |
grammer_8_2_10))
grammer_8 = Group(grammer_8_1 + ZeroOrMore(grammer_8_3) +
ZeroOrMore(grammer_8_2))
grammer_9_1 = Group(Keyword('interface') + Keyword('vlan') + num)
grammer_9_2 = Group(ip_key + address + ipaddress + ipaddress)
grammer_9_3 = Group(Keyword('alias') + ipaddress + ipaddress)
grammer_9_4 = Group(Keyword('peer') + ip_key +
address + ipaddress + ipaddress)
grammer_9_5 = Group(Keyword('access-group') + Keyword('input') + name)
grammer_9_6 = Group(Keyword('service-policy') +
Keyword('input') + name)
grammer_9_7 = Group(Keyword('no') + Keyword('shutdown'))
grammer_9_8 = Group(Keyword('nat-pool') + num + ipaddress + ipaddress +
Keyword('netmask') + ipaddress + Keyword('pat'))
grammer_9 = Group(grammer_9_1 + ZeroOrMore(grammer_9_2 | grammer_9_3 |
grammer_9_4 | grammer_9_5 |
grammer_9_6 | grammer_9_7 |
grammer_9_8))
grammer_10 = Group(ip_key + Keyword('route') + ipaddress + ipaddress)
snmp = Keyword('snmp-server')
host = Keyword('host')
traps = Keyword('traps')
slb = Keyword('slb')
version = Keyword('version')
enable = Keyword('enable')
host_att = host + ipaddress + traps + version + name + name
ord_att = enable + traps + slb + name
grammer_11 = Group(snmp + (host_att | ord_att))
serverfarm = Keyword('serverfarm')
host = Keyword('host')
grammer_12_1 = Group(serverfarm + host + name)
grammer_12_2 = Group(Keyword('probe') + name)
grammer_12_3 = Group(Keyword('inband-health') +
Keyword('check') + name)
grammer_12_4_1 = Keyword('rserver') + ~Word(
'host') + name + ZeroOrMore(num)
grammer_12_4_2 = Keyword('inservice') + Optional(Keyword('standby'))
grammer_12_4_3 = Group(Keyword('probe') + restOfLine)
grammer_12_4_4 = Group(Keyword('backup-rserver') + restOfLine)
grammer_12_4 = Group(grammer_12_4_1 + ZeroOrMore(grammer_12_4_3) +
ZeroOrMore(grammer_12_4_4) +
ZeroOrMore(grammer_12_4_2))
grammer_12_5 = Group(Keyword('predictor') + Keyword('leastconns') +
Keyword('slowstart') + num)
grammer_12_6 = Group(Keyword('description') + restOfLine)
grammer_12_7 = Group(Keyword('predictor') + restOfLine)
grammer_12_8 = Group(Keyword('retcode') + restOfLine)
grammer_12_9 = Group(Keyword('failaction') + restOfLine)
grammer_12_10 = Keyword('fail-on-all')
grammer_12 = Group(grammer_12_1 + ZeroOrMore(
grammer_12_2 | grammer_12_3 | grammer_12_4 | grammer_12_5 |
grammer_12_6 | grammer_12_7 | grammer_12_8 | grammer_12_9 |
grammer_12_10))
grammer_ssl = Group(Keyword('ssl-proxy') + Keyword('service') + name)
grammer_ssl_key = Group(Keyword('key') + name)
grammer_ssl_cert = Group(Keyword('cert') + name)
grammer_ssl_chaingroup = Group(Keyword('chaingroup') + name)
grammer_ssl_opt = Group(Keyword('ssl') + Keyword('advanced-options') +
name)
grammer_ssl_comp = Group(grammer_ssl + ZeroOrMore(grammer_ssl_key |
grammer_ssl_cert |
grammer_ssl_chaingroup |
grammer_ssl_opt))
grammer_crypto_1 = Group(
Keyword('crypto') + Keyword('chaingroup') + name)
grammer_crypto_2 = Group(Keyword('cert') + name)
grammer_crypto_3 = Group(grammer_crypto_1 + ZeroOrMore(grammer_crypto_2))
grammer_crypto_4 = Group(
Keyword('crypto') + Keyword('csr-params') + name)
grammer_crypto_5 = Group(Keyword('country') + name)
grammer_crypto_6 = Group(Keyword('state') + name)
grammer_crypto_7 = Group(Keyword('organization-name') + restOfLine)
grammer_crypto_8 = Group(Keyword('organization-unit') + name)
grammer_crypto_9 = Group(Keyword('common-name') + name)
grammer_crypto_10 = Group(grammer_crypto_4 + ZeroOrMore(grammer_crypto_5 |
grammer_crypto_6 | grammer_crypto_7 | grammer_crypto_8 |
grammer_crypto_9))
grammer_aaa_1 = Keyword('aaa')
grammer_aaa_2 = Keyword(
'authentication login') | Keyword('accounting')
grammer_aaa_3 = Keyword('default')
grammer_aaa_4 = Keyword('group')
grammer_aaa_5 = Keyword('local')
grammer_aaa = Group(grammer_aaa_1 + grammer_aaa_2 + grammer_aaa_3 +
grammer_aaa_4 + (name | grammer_aaa_5))
grammer_al_1 = Keyword('action-list')
grammer_al_2 = Keyword('type')
grammer_al_3 = Keyword('modify')
grammer_al_4 = Keyword('http')
grammer_al_5 = Keyword('ssl')
grammer_al_6 = Keyword('url')
grammer_al_7 = Keyword('rewrite')
grammer_al_8 = Keyword('location')
grammer_al_9 = Keyword('header')
grammer_al_10 = Keyword('request')
grammer_al_11 = Keyword('Host')
grammer_al_12 = Keyword('header-value')
grammer_al_13 = Keyword('replace')
grammer_al_1_1 = Group(
grammer_al_5 + grammer_al_6 + grammer_al_7 + grammer_al_8 + name)
grammer_al_1_2 = Group(
grammer_al_9 + grammer_al_7 + grammer_al_10 + grammer_al_11 +
grammer_al_12 + name + grammer_al_13 + name
)
grammer_al = Group(Group(grammer_al_1 + grammer_al_2 +
grammer_al_3 + grammer_al_4 + name) +
ZeroOrMore(grammer_al_1_1 | grammer_al_1_2))
grammer = Group(grammer_1 | grammer_2 | grammer_3 | grammer_4 |
grammer_5 | grammer_6 | grammer_7 | grammer_8 |
grammer_9 | grammer_10 | grammer_11 | grammer_12 |
grammer_ssl_comp | grammer_aaa | grammer_crypto_3 | grammer_crypto_10 | grammer_al)
print "Grammer created for ace config parser."
LOG.info("Grammer created for ace config parser.")
return grammer
def parse_ace_grammer(grammer, data, file_size, out_dict, final_excel, total_parse_count):
""" This function parse grammer for ace converter convertes to intermediate parser output.
:return parsed intermediate output.
"""
LOG.info("Started ace grammer parsing.")
final_dict = dict()
for match, start, end in grammer.scanString(data):
key = ''
extra_dict = {}
msg = ''
printProgressBar(end, file_size, msg, prefix='Progress', suffix='')
if match:
matched = match.asList()
out_dict.append(matched)
if type(matched[0][0][0]) is list:
key = matched[0][0][0][0]
name_to_log = matched[0][0][0][1]
else:
key = matched[0][0][0]
name_to_log = matched[0][0][1]
LOG.info('Parsing happening for :{} -> {}'.format(key, name_to_log))
excel_dict = {
'name': '',
'type': '',
'command': '',
'converted': 'n',
'status': 'Not Supported',
'skipped': [],
'indirect': [],
'NA': [],
'Avi Object': ''
}
name_to_log = None
type_to_log = ['logging', 'access-list', 'rserver', 'serverfarm',
'parameter-map', 'class-map', 'policy-map', 'sticky',
'probe', 'action-list', 'crypto']
if key == 'logging':
matched = matched[0][0]
name_to_log = matched[1]
if len(matched) == 2:
extra_dict = {
'log_type': matched[1]
}
elif len(matched) == 3:
extra_dict = {
'log_type': matched[1],
'value': matched[2]
}
elif len(matched) == 4:
extra_dict = {
'log_type': matched[1],
'value': matched[2],
'packet': matched[3]
}
LOG.info('parsing: Logging for value : {}'.format(name_to_log))
if key == 'access-list':
matched = matched[0][0]
name_to_log = "{} line {}".format(matched[0][1], matched[0][4])
extra_dict = {
'type': matched[1],
matched[2]: matched[3],
'extend': matched[4],
'permit': matched[5],
'ip1': matched[7],
'ip2': matched[8],
'ip3': matched[9]
}
LOG.info('parsing: Access-list {}'.format(name_to_log))
if key == 'rserver':
matched = matched[0][0]
name_to_log = matched[0][2]
extra_dict = {
matched[0][1]: matched[0][2],
'desc': []
}
for match in matched[1:]:
if len(match) == 1:
temp_dict = {
'type': match[0]
}
elif len(match) == 3:
temp_dict = {
'type': 'redirect',
'code': match[2],
'location': match[1]
}
else:
temp_dict = {
match[0]: match[1]
}
extra_dict['desc'].append(temp_dict)
LOG.info('parsing: rserver for value : {}'.format(name_to_log))
if key == 'serverfarm':
matched = matched[0][0]
name_to_log = matched[0][2]
extra_dict = {
matched[0][1]: matched[0][2],
'desc': []
}
for match in matched[1:]:
temp_dict = dict()
if len(match) < 3:
temp_dict = {
match[0]: match[1]
}
elif 'rserver' in match:
if len(match) >= 4:
temp_dict = {
match[0]: match[1],
'port': match[2],
'enabled': match[4] if len(match) > 4 else match[3]
}
else:
temp_dict = {
match[0]: match[1],
'enabled': match[2] if len(match)>2 else 'false'
}
if len(temp_dict.keys()) > 1:
extra_dict['desc'].append(temp_dict)
LOG.info('parsing: server farm for value : {}'.format(name_to_log))
if key == 'parameter-map':
matched = matched[0][0]
name_to_log = matched[0][3]
extra_dict = {
matched[0][1]: matched[0][2],
'conn_name': matched[0][3],
'desc': []
}
for match in matched[1:]:
if len(match) == 2:
temp_dict = {
match[0]: match[1]
}
else:
temp_dict = {
match[0]: match[1],
'allow': match[2]
}
extra_dict['desc'].append(temp_dict)
LOG.info(
'parsing: parameter-map for value : {}'.format(name_to_log))
if key == 'class-map':
matched = matched[0][0]
name_to_log = matched[0][2]
extra_dict = {
matched[0][0]: matched[0][2],
'type': matched[0][1],
'desc': []
}
for match in matched[1:]:
temp_dict = dict()
if len(match) == 7:
temp_dict = {
match[1]: match[0],
match[2]: match[3],
match[4]: match[6]
}
elif len(match) == 5:
temp_dict = {
match[1]: match[0],
match[2]: match[3],
"mask": match[4]
}
elif len(match) == 6:
temp_dict = {
match[1]: match[0],
match[2]: match[3],
match[4]: match[5]
}
extra_dict['desc'].append(temp_dict)
LOG.info('parsing: class-map for value : {}'.format(name_to_log))
if key == 'policy-map':
matched = matched[0][0]
if len(matched[0]) == 5:
extra_dict = {
matched[0][1]: matched[0][2],
'match': matched[0][3],
'name': matched[0][4],
'desc': []
}
name_to_log = matched[0][4]
else:
extra_dict = {
matched[0][0]: matched[0][2],
'match': matched[0][1],
'desc': []
}
name_to_log = matched[0][2]
for match in matched[1:]:
temp_dict = dict()
temp_dict = {
match[0][0]: match[0][1],
'class_desc': []
}
for match1 in match[1:]:
temp_dict_1 = dict()
if len(match1) == 2:
temp_dict_1 = {
match1[0]: match1[1]
}
elif len(match1) == 3:
temp_dict_1 = {
match1[0]: match1[1],
'type': match1[2]
}
temp_dict['class_desc'].append(temp_dict_1)
extra_dict['desc'].append(temp_dict)
LOG.info('parsing: policy-map for value : {}'.format(name_to_log))
if key == 'sticky':
matched = matched[0][0]
if len(matched[0]) == 6:
name_to_log = matched[0][5]
extra_dict = {
matched[0][1]: matched[0][2],
'name': matched[0][5],
'desc': []
}
if len(matched[0]) == 4:
name_to_log = matched[0][3]
extra_dict = {
matched[0][1]: matched[0][1],
'name': name_to_log,
'desc': []
}
for match in matched[1:]:
temp_dict = dict()
if len(match) == 2:
temp_dict = {
match[0]: match[1]
}
extra_dict['desc'].append(temp_dict)
LOG.info('parsing: sticky for value : {}'.format(name_to_log))
if key == 'ssl-proxy':
matched = matched[0][0]
name_to_log = matched[0][2]
extra_dict = {
'type': matched[0][1],
'name': name_to_log,
'desc': []
}
for match in matched[1:]:
if len(match) == 2:
temp_dict = {
match[0]: match[1]
}
if len(match) == 3:
temp_dict = {
match[0]: match[1],
'name': match[2]
}
extra_dict['desc'].append(temp_dict)
if key == 'action-list':
matched = matched[0][0]
name_to_log = matched[0][4]
extra_dict = {
matched[0][0]: name_to_log,
matched[0][1]: matched[0][2],
matched[0][3]: matched[0][4],
'desc': []
}
for match in matched[1:]:
if len(match) == 5:
temp_dict = {
match[0]: match[1],
match[2]: match[3],
"to": match[4]
}
if len(match) == 8:
temp_dict = {
match[0]: match[1],
match[2]: match[3],
match[4]: match[5],
match[6]: match[7],
}
extra_dict['desc'].append(temp_dict)
LOG.info('parsing: action-list for value : {}'.format(name_to_log))
if key == 'probe':
matched = matched[0][0]
name_to_log = matched[0][2]
extra_dict = {
'type': matched[0][1],
'name': matched[0][2],
}
for match in matched[1:]:
temp_dict = dict()
if len(match) == 2:
temp_dict = {
match[0]: match[1]
}
if len(match) == 4:
if 'status' in match:
temp_dict = {
'status': match[2],
'status1': match[3]
}
elif 'header' in match:
temp_dict = {
'host': match[1],
'header-value': match[3]
}
if len(match) == 3:
if 'regex' in match:
temp_dict = {
'regex': 'yes'
}
if len(match) == 5:
temp_dict = {
match[1]: match[2],
match[3]: match[4]
}
extra_dict.update(temp_dict)
LOG.info('parsing: probe for value : {}'.format(name_to_log))
if key == 'crypto':
matched = matched[0][0]
name_to_log = matched[0][2]
if matched[0][1] == 'chaingroup':
extra_dict = {
'cert': [],
matched[0][1]: matched[0][2],
}
for match in matched[0:]:
temp_dict = dict()
if 'cert' in match:
extra_dict['cert'].append(match[1])
elif 'csr-params' in match:
temp_dict = {
match[1]: match[2]
}
else:
temp_dict = {
match[0]: match[1]
}
extra_dict.update(temp_dict)
LOG.info('parsing: crypto for value : {}'.format(name_to_log))
if key in type_to_log and name_to_log:
excel_dict['name'] = name_to_log
excel_dict['type'] = key
final_excel.append(excel_dict)
if key not in final_dict.keys():
final_dict.update({key: [extra_dict]})
else:
final_dict[key].append(extra_dict)
set_excel_dict(final_excel)
printProgressBar(file_size, file_size, msg,
prefix='Progress', suffix='')
return final_dict
class Parser():
""" This class is for Parsing
- Parsing grammars are written in pyparsing
"""
def __init__(self, file_name):
self.file_name = file_name
def parse_ace(self):
out_dict = []
total_parse_count = 0
final_excel = []
with open(self.file_name, 'r') as input_config:
input_data = input_config.read()
input_config.seek(0, 2)
file_size = input_config.tell()
overall_grammer = create_ace_grammer()
parsed_ace_config = parse_ace_grammer(overall_grammer, input_data, file_size, out_dict, final_excel, total_parse_count)
return parsed_ace_config
if __name__ == '__main__':
s = """
serverfarm host sfarm_IDST-EXTADRESSBUCH-HTTPS
probe probe_L7_IDST-EXTADRESSBUCH-HTTPS
fail-on-all
rserver rserver_L0550022 443
inservice
rserver rserver_L0551022 443
inservice
"""
name = Word(printables)
num = Word(nums)
serverfarm = Keyword('serverfarm')
host = Keyword('host')
grammer_12_1 = Group(serverfarm + host + name)
grammer_12_2 = Group(Keyword('probe') + name)
grammer_12_3 = Group(Keyword('inband-health') +
Keyword('check') + name)
grammer_12_4_1 = Keyword('rserver') + ~Word(
'host') + name + ZeroOrMore(num)
grammer_12_4_2 = Keyword('inservice') + Optional(Keyword('standby'))
grammer_12_4_3 = Group(Keyword('probe')+ restOfLine)
grammer_12_4_4 = Group(Keyword('backup-rserver') + restOfLine)
grammer_12_4 = Group(grammer_12_4_1 + ZeroOrMore(grammer_12_4_3) +
ZeroOrMore(grammer_12_4_4) +
ZeroOrMore(grammer_12_4_2))
grammer_12_5 = Group(Keyword('predictor') + Keyword('leastconns') +
Keyword('slowstart') + num)
grammer_12_6 = Group(Keyword('description') + restOfLine)
grammer_12_7 = Group(Keyword('predictor') + restOfLine)
grammer_12_8 = Group(Keyword('retcode') + restOfLine)
grammer_12_9 = Keyword('fail-on-all')
grammer_12 = Group(grammer_12_1 + ZeroOrMore(
grammer_12_2 | grammer_12_2 | grammer_12_3 | grammer_12_4 |
grammer_12_5 | grammer_12_6 | grammer_12_7 | grammer_12_8 |
grammer_12_9))
for match, start, end in grammer_12.scanString(s):
print match
| false | true |
f72bc3e123cf5d71ec9dfa9b87624f01ea910d05 | 7,358 | py | Python | src/ptb/ptb_enas_controller.py | tremblerz/enas | 329ee3f8beb5e715bf2dad1182cfb5120b3485f9 | [
"Apache-2.0"
] | null | null | null | src/ptb/ptb_enas_controller.py | tremblerz/enas | 329ee3f8beb5e715bf2dad1182cfb5120b3485f9 | [
"Apache-2.0"
] | null | null | null | src/ptb/ptb_enas_controller.py | tremblerz/enas | 329ee3f8beb5e715bf2dad1182cfb5120b3485f9 | [
"Apache-2.0"
] | null | null | null |
import sys
import os
import time
import numpy as np
import tensorflow as tf
from src.utils import get_train_ops
from src.common_ops import stack_lstm
from tensorflow.python.training import moving_averages
class PTBEnasController(object):
def __init__(self,
rhn_depth=5,
lstm_size=32,
lstm_num_layers=2,
lstm_keep_prob=1.0,
tanh_constant=None,
temperature=None,
num_funcs=2,
lr_init=1e-3,
lr_dec_start=0,
lr_dec_every=100,
lr_dec_rate=0.9,
l2_reg=0,
entropy_weight=None,
clip_mode=None,
grad_bound=None,
bl_dec=0.999,
optim_algo="adam",
sync_replicas=False,
num_aggregate=None,
num_replicas=None,
name="controller"):
print("-" * 80)
print("Building PTBEnasController")
self.rhn_depth = rhn_depth
self.lstm_size = lstm_size
self.lstm_num_layers = lstm_num_layers
self.lstm_keep_prob = lstm_keep_prob
self.tanh_constant = tanh_constant
self.temperature = temperature
self.num_funcs = num_funcs
self.lr_init = lr_init
self.lr_dec_start = lr_dec_start
self.lr_dec_every = lr_dec_every
self.lr_dec_rate = lr_dec_rate
self.l2_reg = l2_reg
self.entropy_weight = entropy_weight
self.clip_mode = clip_mode
self.grad_bound = grad_bound
self.bl_dec = bl_dec
self.optim_algo = optim_algo
self.sync_replicas = sync_replicas
self.num_aggregate = num_aggregate
self.num_replicas = num_replicas
self.name = name
self._create_params()
self._build_sampler()
def _create_params(self):
initializer = tf.random_uniform_initializer(minval=-0.1, maxval=0.1)
with tf.variable_scope(self.name, initializer=initializer):
with tf.variable_scope("lstm"):
self.w_lstm = []
for layer_id in range(self.lstm_num_layers):
with tf.variable_scope("layer_{}".format(layer_id)):
w = tf.get_variable("w", [2 * self.lstm_size, 4 * self.lstm_size])
self.w_lstm.append(w)
num_funcs = self.num_funcs
with tf.variable_scope("embedding"):
self.g_emb = tf.get_variable("g_emb", [1, self.lstm_size])
self.w_emb = tf.get_variable("w", [num_funcs, self.lstm_size])
with tf.variable_scope("softmax"):
self.w_soft = tf.get_variable("w", [self.lstm_size, num_funcs])
with tf.variable_scope("attention"):
self.attn_w_1 = tf.get_variable("w_1", [self.lstm_size, self.lstm_size])
self.attn_w_2 = tf.get_variable("w_2", [self.lstm_size, self.lstm_size])
self.attn_v = tf.get_variable("v", [self.lstm_size, 1])
def _build_sampler(self):
"""Build the sampler ops and the log_prob ops."""
arc_seq = []
sample_log_probs = []
sample_entropy = []
all_h = []
all_h_w = []
# sampler ops
inputs = self.g_emb
prev_c, prev_h = [], []
for _ in range(self.lstm_num_layers):
prev_c.append(tf.zeros([1, self.lstm_size], dtype=tf.float32))
prev_h.append(tf.zeros([1, self.lstm_size], dtype=tf.float32))
# used = tf.zeros([self.rhn_depth, 2], dtype=tf.int32)
for layer_id in range(self.rhn_depth):
next_c, next_h = stack_lstm(inputs, prev_c, prev_h, self.w_lstm)
prev_c, prev_h = next_c, next_h
all_h.append(next_h[-1])
all_h_w.append(tf.matmul(next_h[-1], self.attn_w_1))
if layer_id > 0:
query = tf.matmul(next_h[-1], self.attn_w_2)
query = query + tf.concat(all_h_w[:-1], axis=0)
query = tf.tanh(query)
logits = tf.matmul(query, self.attn_v)
logits = tf.reshape(logits, [1, layer_id])
if self.temperature is not None:
logits /= self.temperature
if self.tanh_constant is not None:
logits = self.tanh_constant * tf.tanh(logits)
diff = tf.to_float(layer_id - tf.range(0, layer_id)) ** 2
logits -= tf.reshape(diff, [1, layer_id]) / 6.0
skip_index = tf.multinomial(logits, 1)
skip_index = tf.to_int32(skip_index)
skip_index = tf.reshape(skip_index, [1])
arc_seq.append(skip_index)
log_prob = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=skip_index)
sample_log_probs.append(log_prob)
entropy = log_prob * tf.exp(-log_prob)
sample_entropy.append(tf.stop_gradient(entropy))
inputs = tf.nn.embedding_lookup(
tf.concat(all_h[:-1], axis=0), skip_index)
inputs /= (0.1 + tf.to_float(layer_id - skip_index))
else:
inputs = self.g_emb
next_c, next_h = stack_lstm(inputs, prev_c, prev_h, self.w_lstm)
prev_c, prev_h = next_c, next_h
logits = tf.matmul(next_h[-1], self.w_soft)
if self.temperature is not None:
logits /= self.temperature
if self.tanh_constant is not None:
logits = self.tanh_constant * tf.tanh(logits)
func = tf.multinomial(logits, 1)
func = tf.to_int32(func)
func = tf.reshape(func, [1])
arc_seq.append(func)
log_prob = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=func)
sample_log_probs.append(log_prob)
entropy = log_prob * tf.exp(-log_prob)
sample_entropy.append(tf.stop_gradient(entropy))
inputs = tf.nn.embedding_lookup(self.w_emb, func)
arc_seq = tf.concat(arc_seq, axis=0)
self.sample_arc = arc_seq
self.sample_log_probs = tf.concat(sample_log_probs, axis=0)
self.ppl = tf.exp(tf.reduce_mean(self.sample_log_probs))
sample_entropy = tf.concat(sample_entropy, axis=0)
self.sample_entropy = tf.reduce_sum(sample_entropy)
self.all_h = all_h
def build_trainer(self, child_model):
# actor
self.valid_loss = tf.to_float(child_model.rl_loss)
self.valid_loss = tf.stop_gradient(self.valid_loss)
self.valid_ppl = tf.exp(self.valid_loss)
self.reward = 80.0 / self.valid_ppl
if self.entropy_weight is not None:
self.reward += self.entropy_weight * self.sample_entropy
# or baseline
self.sample_log_probs = tf.reduce_sum(self.sample_log_probs)
self.baseline = tf.Variable(0.0, dtype=tf.float32, trainable=False)
baseline_update = tf.assign_sub(
self.baseline, (1 - self.bl_dec) * (self.baseline - self.reward))
with tf.control_dependencies([baseline_update]):
self.reward = tf.identity(self.reward)
self.loss = self.sample_log_probs * (self.reward - self.baseline)
self.train_step = tf.Variable(
0, dtype=tf.int32, trainable=False, name="train_step")
tf_variables = [var
for var in tf.trainable_variables() if var.name.startswith(self.name)]
self.train_op, self.lr, self.grad_norm, self.optimizer = get_train_ops(
self.loss,
tf_variables,
self.train_step,
clip_mode=self.clip_mode,
grad_bound=self.grad_bound,
l2_reg=self.l2_reg,
lr_init=self.lr_init,
lr_dec_start=self.lr_dec_start,
lr_dec_every=self.lr_dec_every,
lr_dec_rate=self.lr_dec_rate,
optim_algo=self.optim_algo,
sync_replicas=self.sync_replicas,
num_aggregate=self.num_aggregate,
num_replicas=self.num_replicas)
| 33.907834 | 80 | 0.651536 |
import sys
import os
import time
import numpy as np
import tensorflow as tf
from src.utils import get_train_ops
from src.common_ops import stack_lstm
from tensorflow.python.training import moving_averages
class PTBEnasController(object):
def __init__(self,
rhn_depth=5,
lstm_size=32,
lstm_num_layers=2,
lstm_keep_prob=1.0,
tanh_constant=None,
temperature=None,
num_funcs=2,
lr_init=1e-3,
lr_dec_start=0,
lr_dec_every=100,
lr_dec_rate=0.9,
l2_reg=0,
entropy_weight=None,
clip_mode=None,
grad_bound=None,
bl_dec=0.999,
optim_algo="adam",
sync_replicas=False,
num_aggregate=None,
num_replicas=None,
name="controller"):
print("-" * 80)
print("Building PTBEnasController")
self.rhn_depth = rhn_depth
self.lstm_size = lstm_size
self.lstm_num_layers = lstm_num_layers
self.lstm_keep_prob = lstm_keep_prob
self.tanh_constant = tanh_constant
self.temperature = temperature
self.num_funcs = num_funcs
self.lr_init = lr_init
self.lr_dec_start = lr_dec_start
self.lr_dec_every = lr_dec_every
self.lr_dec_rate = lr_dec_rate
self.l2_reg = l2_reg
self.entropy_weight = entropy_weight
self.clip_mode = clip_mode
self.grad_bound = grad_bound
self.bl_dec = bl_dec
self.optim_algo = optim_algo
self.sync_replicas = sync_replicas
self.num_aggregate = num_aggregate
self.num_replicas = num_replicas
self.name = name
self._create_params()
self._build_sampler()
def _create_params(self):
initializer = tf.random_uniform_initializer(minval=-0.1, maxval=0.1)
with tf.variable_scope(self.name, initializer=initializer):
with tf.variable_scope("lstm"):
self.w_lstm = []
for layer_id in range(self.lstm_num_layers):
with tf.variable_scope("layer_{}".format(layer_id)):
w = tf.get_variable("w", [2 * self.lstm_size, 4 * self.lstm_size])
self.w_lstm.append(w)
num_funcs = self.num_funcs
with tf.variable_scope("embedding"):
self.g_emb = tf.get_variable("g_emb", [1, self.lstm_size])
self.w_emb = tf.get_variable("w", [num_funcs, self.lstm_size])
with tf.variable_scope("softmax"):
self.w_soft = tf.get_variable("w", [self.lstm_size, num_funcs])
with tf.variable_scope("attention"):
self.attn_w_1 = tf.get_variable("w_1", [self.lstm_size, self.lstm_size])
self.attn_w_2 = tf.get_variable("w_2", [self.lstm_size, self.lstm_size])
self.attn_v = tf.get_variable("v", [self.lstm_size, 1])
def _build_sampler(self):
arc_seq = []
sample_log_probs = []
sample_entropy = []
all_h = []
all_h_w = []
inputs = self.g_emb
prev_c, prev_h = [], []
for _ in range(self.lstm_num_layers):
prev_c.append(tf.zeros([1, self.lstm_size], dtype=tf.float32))
prev_h.append(tf.zeros([1, self.lstm_size], dtype=tf.float32))
for layer_id in range(self.rhn_depth):
next_c, next_h = stack_lstm(inputs, prev_c, prev_h, self.w_lstm)
prev_c, prev_h = next_c, next_h
all_h.append(next_h[-1])
all_h_w.append(tf.matmul(next_h[-1], self.attn_w_1))
if layer_id > 0:
query = tf.matmul(next_h[-1], self.attn_w_2)
query = query + tf.concat(all_h_w[:-1], axis=0)
query = tf.tanh(query)
logits = tf.matmul(query, self.attn_v)
logits = tf.reshape(logits, [1, layer_id])
if self.temperature is not None:
logits /= self.temperature
if self.tanh_constant is not None:
logits = self.tanh_constant * tf.tanh(logits)
diff = tf.to_float(layer_id - tf.range(0, layer_id)) ** 2
logits -= tf.reshape(diff, [1, layer_id]) / 6.0
skip_index = tf.multinomial(logits, 1)
skip_index = tf.to_int32(skip_index)
skip_index = tf.reshape(skip_index, [1])
arc_seq.append(skip_index)
log_prob = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=skip_index)
sample_log_probs.append(log_prob)
entropy = log_prob * tf.exp(-log_prob)
sample_entropy.append(tf.stop_gradient(entropy))
inputs = tf.nn.embedding_lookup(
tf.concat(all_h[:-1], axis=0), skip_index)
inputs /= (0.1 + tf.to_float(layer_id - skip_index))
else:
inputs = self.g_emb
next_c, next_h = stack_lstm(inputs, prev_c, prev_h, self.w_lstm)
prev_c, prev_h = next_c, next_h
logits = tf.matmul(next_h[-1], self.w_soft)
if self.temperature is not None:
logits /= self.temperature
if self.tanh_constant is not None:
logits = self.tanh_constant * tf.tanh(logits)
func = tf.multinomial(logits, 1)
func = tf.to_int32(func)
func = tf.reshape(func, [1])
arc_seq.append(func)
log_prob = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=func)
sample_log_probs.append(log_prob)
entropy = log_prob * tf.exp(-log_prob)
sample_entropy.append(tf.stop_gradient(entropy))
inputs = tf.nn.embedding_lookup(self.w_emb, func)
arc_seq = tf.concat(arc_seq, axis=0)
self.sample_arc = arc_seq
self.sample_log_probs = tf.concat(sample_log_probs, axis=0)
self.ppl = tf.exp(tf.reduce_mean(self.sample_log_probs))
sample_entropy = tf.concat(sample_entropy, axis=0)
self.sample_entropy = tf.reduce_sum(sample_entropy)
self.all_h = all_h
def build_trainer(self, child_model):
self.valid_loss = tf.to_float(child_model.rl_loss)
self.valid_loss = tf.stop_gradient(self.valid_loss)
self.valid_ppl = tf.exp(self.valid_loss)
self.reward = 80.0 / self.valid_ppl
if self.entropy_weight is not None:
self.reward += self.entropy_weight * self.sample_entropy
self.sample_log_probs = tf.reduce_sum(self.sample_log_probs)
self.baseline = tf.Variable(0.0, dtype=tf.float32, trainable=False)
baseline_update = tf.assign_sub(
self.baseline, (1 - self.bl_dec) * (self.baseline - self.reward))
with tf.control_dependencies([baseline_update]):
self.reward = tf.identity(self.reward)
self.loss = self.sample_log_probs * (self.reward - self.baseline)
self.train_step = tf.Variable(
0, dtype=tf.int32, trainable=False, name="train_step")
tf_variables = [var
for var in tf.trainable_variables() if var.name.startswith(self.name)]
self.train_op, self.lr, self.grad_norm, self.optimizer = get_train_ops(
self.loss,
tf_variables,
self.train_step,
clip_mode=self.clip_mode,
grad_bound=self.grad_bound,
l2_reg=self.l2_reg,
lr_init=self.lr_init,
lr_dec_start=self.lr_dec_start,
lr_dec_every=self.lr_dec_every,
lr_dec_rate=self.lr_dec_rate,
optim_algo=self.optim_algo,
sync_replicas=self.sync_replicas,
num_aggregate=self.num_aggregate,
num_replicas=self.num_replicas)
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.