gt
stringclasses
1 value
context
stringlengths
2.49k
119k
""" Support for installing and building the "wheel" binary package format. """ from __future__ import absolute_import import compileall import csv import errno import functools import hashlib import logging import os import os.path import re import shutil import stat import sys import tempfile import warnings from base64 import urlsafe_b64encode from email.parser import Parser from pip._vendor.six import StringIO import pip from pip.compat import expanduser from pip.download import path_to_url, unpack_url from pip.exceptions import ( InstallationError, InvalidWheelFilename, UnsupportedWheel) from pip.locations import distutils_scheme, PIP_DELETE_MARKER_FILENAME from pip import pep425tags from pip.utils import ( call_subprocess, ensure_dir, captured_stdout, rmtree, read_chunks, ) from pip.utils.ui import open_spinner from pip.utils.logging import indent_log from pip.utils.setuptools_build import SETUPTOOLS_SHIM from pip._vendor.distlib.scripts import ScriptMaker from pip._vendor import pkg_resources from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.six.moves import configparser wheel_ext = '.whl' VERSION_COMPATIBLE = (1, 0) logger = logging.getLogger(__name__) class WheelCache(object): """A cache of wheels for future installs.""" def __init__(self, cache_dir, format_control): """Create a wheel cache. :param cache_dir: The root of the cache. :param format_control: A pip.index.FormatControl object to limit binaries being read from the cache. """ self._cache_dir = expanduser(cache_dir) if cache_dir else None self._format_control = format_control def cached_wheel(self, link, package_name): return cached_wheel( self._cache_dir, link, self._format_control, package_name) def _cache_for_link(cache_dir, link): """ Return a directory to store cached wheels in for link. Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param cache_dir: The cache_dir being used by pip. :param link: The link of the sdist for which this will cache wheels. """ # We want to generate an url to use as our cache key, we don't want to just # re-use the URL because it might have other items in the fragment and we # don't care about those. key_parts = [link.url_without_fragment] if link.hash_name is not None and link.hash is not None: key_parts.append("=".join([link.hash_name, link.hash])) key_url = "#".join(key_parts) # Encode our key url with sha224, we'll use this because it has similar # security properties to sha256, but with a shorter total output (and thus # less secure). However the differences don't make a lot of difference for # our use case here. hashed = hashlib.sha224(key_url.encode()).hexdigest() # We want to nest the directories some to prevent having a ton of top level # directories where we might run out of sub directories on some FS. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]] # Inside of the base location for cached wheels, expand our parts and join # them all together. return os.path.join(cache_dir, "wheels", *parts) def cached_wheel(cache_dir, link, format_control, package_name): if not cache_dir: return link if not link: return link if link.is_wheel: return link if not link.is_artifact: return link if not package_name: return link canonical_name = canonicalize_name(package_name) formats = pip.index.fmt_ctl_formats(format_control, canonical_name) if "binary" not in formats: return link root = _cache_for_link(cache_dir, link) try: wheel_names = os.listdir(root) except OSError as e: if e.errno in (errno.ENOENT, errno.ENOTDIR): return link raise candidates = [] for wheel_name in wheel_names: try: wheel = Wheel(wheel_name) except InvalidWheelFilename: continue if not wheel.supported(): # Built for a different python/arch/etc continue candidates.append((wheel.support_index_min(), wheel_name)) if not candidates: return link candidates.sort() path = os.path.join(root, candidates[0][1]) return pip.index.Link(path_to_url(path)) def rehash(path, algo='sha256', blocksize=1 << 20): """Return (hash, length) for path using hashlib.new(algo)""" h = hashlib.new(algo) length = 0 with open(path, 'rb') as f: for block in read_chunks(f, size=blocksize): length += len(block) h.update(block) digest = 'sha256=' + urlsafe_b64encode( h.digest() ).decode('latin1').rstrip('=') return (digest, length) def open_for_csv(name, mode): if sys.version_info[0] < 3: nl = {} bin = 'b' else: nl = {'newline': ''} bin = '' return open(name, mode + bin, **nl) def fix_script(path): """Replace #!python with #!/path/to/python Return True if file was changed.""" # XXX RECORD hashes will need to be updated if os.path.isfile(path): with open(path, 'rb') as script: firstline = script.readline() if not firstline.startswith(b'#!python'): return False exename = sys.executable.encode(sys.getfilesystemencoding()) firstline = b'#!' + exename + os.linesep.encode("ascii") rest = script.read() with open(path, 'wb') as script: script.write(firstline) script.write(rest) return True dist_info_re = re.compile(r"""^(?P<namever>(?P<name>.+?)(-(?P<ver>\d.+?))?) \.dist-info$""", re.VERBOSE) def root_is_purelib(name, wheeldir): """ Return True if the extracted wheel in wheeldir should go into purelib. """ name_folded = name.replace("-", "_") for item in os.listdir(wheeldir): match = dist_info_re.match(item) if match and match.group('name') == name_folded: with open(os.path.join(wheeldir, item, 'WHEEL')) as wheel: for line in wheel: line = line.lower().rstrip() if line == "root-is-purelib: true": return True return False def get_entrypoints(filename): if not os.path.exists(filename): return {}, {} # This is done because you can pass a string to entry_points wrappers which # means that they may or may not be valid INI files. The attempt here is to # strip leading and trailing whitespace in order to make them valid INI # files. with open(filename) as fp: data = StringIO() for line in fp: data.write(line.strip()) data.write("\n") data.seek(0) cp = configparser.RawConfigParser() cp.optionxform = lambda option: option cp.readfp(data) console = {} gui = {} if cp.has_section('console_scripts'): console = dict(cp.items('console_scripts')) if cp.has_section('gui_scripts'): gui = dict(cp.items('gui_scripts')) return console, gui def move_wheel_files(name, req, wheeldir, user=False, home=None, root=None, pycompile=True, scheme=None, isolated=False, prefix=None): """Install a wheel""" if not scheme: scheme = distutils_scheme( name, user=user, home=home, root=root, isolated=isolated, prefix=prefix, ) if root_is_purelib(name, wheeldir): lib_dir = scheme['purelib'] else: lib_dir = scheme['platlib'] info_dir = [] data_dirs = [] source = wheeldir.rstrip(os.path.sep) + os.path.sep # Record details of the files moved # installed = files copied from the wheel to the destination # changed = files changed while installing (scripts #! line typically) # generated = files newly generated during the install (script wrappers) installed = {} changed = set() generated = [] # Compile all of the pyc files that we're going to be installing if pycompile: with captured_stdout() as stdout: with warnings.catch_warnings(): warnings.filterwarnings('ignore') compileall.compile_dir(source, force=True, quiet=True) logger.debug(stdout.getvalue()) def normpath(src, p): return os.path.relpath(src, p).replace(os.path.sep, '/') def record_installed(srcfile, destfile, modified=False): """Map archive RECORD paths to installation RECORD paths.""" oldpath = normpath(srcfile, wheeldir) newpath = normpath(destfile, lib_dir) installed[oldpath] = newpath if modified: changed.add(destfile) def clobber(source, dest, is_base, fixer=None, filter=None): ensure_dir(dest) # common for the 'include' path for dir, subdirs, files in os.walk(source): basedir = dir[len(source):].lstrip(os.path.sep) destdir = os.path.join(dest, basedir) if is_base and basedir.split(os.path.sep, 1)[0].endswith('.data'): continue for s in subdirs: destsubdir = os.path.join(dest, basedir, s) if is_base and basedir == '' and destsubdir.endswith('.data'): data_dirs.append(s) continue elif (is_base and s.endswith('.dist-info') and # is self.req.project_name case preserving? s.lower().startswith( req.name.replace('-', '_').lower())): assert not info_dir, ('Multiple .dist-info directories: ' + destsubdir + ', ' + ', '.join(info_dir)) info_dir.append(destsubdir) for f in files: # Skip unwanted files if filter and filter(f): continue srcfile = os.path.join(dir, f) destfile = os.path.join(dest, basedir, f) # directory creation is lazy and after the file filtering above # to ensure we don't install empty dirs; empty dirs can't be # uninstalled. ensure_dir(destdir) # We use copyfile (not move, copy, or copy2) to be extra sure # that we are not moving directories over (copyfile fails for # directories) as well as to ensure that we are not copying # over any metadata because we want more control over what # metadata we actually copy over. shutil.copyfile(srcfile, destfile) # Copy over the metadata for the file, currently this only # includes the atime and mtime. st = os.stat(srcfile) if hasattr(os, "utime"): os.utime(destfile, (st.st_atime, st.st_mtime)) # If our file is executable, then make our destination file # executable. if os.access(srcfile, os.X_OK): st = os.stat(srcfile) permissions = ( st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH ) os.chmod(destfile, permissions) changed = False if fixer: changed = fixer(destfile) record_installed(srcfile, destfile, changed) clobber(source, lib_dir, True) assert info_dir, "%s .dist-info directory not found" % req # Get the defined entry points ep_file = os.path.join(info_dir[0], 'entry_points.txt') console, gui = get_entrypoints(ep_file) def is_entrypoint_wrapper(name): # EP, EP.exe and EP-script.py are scripts generated for # entry point EP by setuptools if name.lower().endswith('.exe'): matchname = name[:-4] elif name.lower().endswith('-script.py'): matchname = name[:-10] elif name.lower().endswith(".pya"): matchname = name[:-4] else: matchname = name # Ignore setuptools-generated scripts return (matchname in console or matchname in gui) for datadir in data_dirs: fixer = None filter = None for subdir in os.listdir(os.path.join(wheeldir, datadir)): fixer = None if subdir == 'scripts': fixer = fix_script filter = is_entrypoint_wrapper source = os.path.join(wheeldir, datadir, subdir) dest = scheme[subdir] clobber(source, dest, False, fixer=fixer, filter=filter) maker = ScriptMaker(None, scheme['scripts']) # Ensure old scripts are overwritten. # See https://github.com/pypa/pip/issues/1800 maker.clobber = True # Ensure we don't generate any variants for scripts because this is almost # never what somebody wants. # See https://bitbucket.org/pypa/distlib/issue/35/ maker.variants = set(('', )) # This is required because otherwise distlib creates scripts that are not # executable. # See https://bitbucket.org/pypa/distlib/issue/32/ maker.set_mode = True # Simplify the script and fix the fact that the default script swallows # every single stack trace. # See https://bitbucket.org/pypa/distlib/issue/34/ # See https://bitbucket.org/pypa/distlib/issue/33/ def _get_script_text(entry): if entry.suffix is None: raise InstallationError( "Invalid script entry point: %s for req: %s - A callable " "suffix is required. Cf https://packaging.python.org/en/" "latest/distributing.html#console-scripts for more " "information." % (entry, req) ) return maker.script_template % { "module": entry.prefix, "import_name": entry.suffix.split(".")[0], "func": entry.suffix, } maker._get_script_text = _get_script_text maker.script_template = """# -*- coding: utf-8 -*- import sys from %(module)s import %(import_name)s if __name__ == '__main__': sys.exit(%(func)s()) """ # Special case pip and setuptools to generate versioned wrappers # # The issue is that some projects (specifically, pip and setuptools) use # code in setup.py to create "versioned" entry points - pip2.7 on Python # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into # the wheel metadata at build time, and so if the wheel is installed with # a *different* version of Python the entry points will be wrong. The # correct fix for this is to enhance the metadata to be able to describe # such versioned entry points, but that won't happen till Metadata 2.0 is # available. # In the meantime, projects using versioned entry points will either have # incorrect versioned entry points, or they will not be able to distribute # "universal" wheels (i.e., they will need a wheel per Python version). # # Because setuptools and pip are bundled with _ensurepip and virtualenv, # we need to use universal wheels. So, as a stopgap until Metadata 2.0, we # override the versioned entry points in the wheel and generate the # correct ones. This code is purely a short-term measure until Metadat 2.0 # is available. # # To add the level of hack in this section of code, in order to support # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment # variable which will control which version scripts get installed. # # ENSUREPIP_OPTIONS=altinstall # - Only pipX.Y and easy_install-X.Y will be generated and installed # ENSUREPIP_OPTIONS=install # - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note # that this option is technically if ENSUREPIP_OPTIONS is set and is # not altinstall # DEFAULT # - The default behavior is to install pip, pipX, pipX.Y, easy_install # and easy_install-X.Y. pip_script = console.pop('pip', None) if pip_script: if "ENSUREPIP_OPTIONS" not in os.environ: spec = 'pip = ' + pip_script generated.extend(maker.make(spec)) if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall": spec = 'pip%s = %s' % (sys.version[:1], pip_script) generated.extend(maker.make(spec)) spec = 'pip%s = %s' % (sys.version[:3], pip_script) generated.extend(maker.make(spec)) # Delete any other versioned pip entry points pip_ep = [k for k in console if re.match(r'pip(\d(\.\d)?)?$', k)] for k in pip_ep: del console[k] easy_install_script = console.pop('easy_install', None) if easy_install_script: if "ENSUREPIP_OPTIONS" not in os.environ: spec = 'easy_install = ' + easy_install_script generated.extend(maker.make(spec)) spec = 'easy_install-%s = %s' % (sys.version[:3], easy_install_script) generated.extend(maker.make(spec)) # Delete any other versioned easy_install entry points easy_install_ep = [ k for k in console if re.match(r'easy_install(-\d\.\d)?$', k) ] for k in easy_install_ep: del console[k] # Generate the console and GUI entry points specified in the wheel if len(console) > 0: generated.extend( maker.make_multiple(['%s = %s' % kv for kv in console.items()]) ) if len(gui) > 0: generated.extend( maker.make_multiple( ['%s = %s' % kv for kv in gui.items()], {'gui': True} ) ) # Record pip as the installer installer = os.path.join(info_dir[0], 'INSTALLER') temp_installer = os.path.join(info_dir[0], 'INSTALLER.pip') with open(temp_installer, 'wb') as installer_file: installer_file.write(b'pip\n') shutil.move(temp_installer, installer) generated.append(installer) # Record details of all files installed record = os.path.join(info_dir[0], 'RECORD') temp_record = os.path.join(info_dir[0], 'RECORD.pip') with open_for_csv(record, 'r') as record_in: with open_for_csv(temp_record, 'w+') as record_out: reader = csv.reader(record_in) writer = csv.writer(record_out) for row in reader: row[0] = installed.pop(row[0], row[0]) if row[0] in changed: row[1], row[2] = rehash(row[0]) writer.writerow(row) for f in generated: h, l = rehash(f) writer.writerow((normpath(f, lib_dir), h, l)) for f in installed: writer.writerow((installed[f], '', '')) shutil.move(temp_record, record) def _unique(fn): @functools.wraps(fn) def unique(*args, **kw): seen = set() for item in fn(*args, **kw): if item not in seen: seen.add(item) yield item return unique # TODO: this goes somewhere besides the wheel module @_unique def uninstallation_paths(dist): """ Yield all the uninstallation paths for dist based on RECORD-without-.pyc Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc in the same directory. UninstallPathSet.add() takes care of the __pycache__ .pyc. """ from pip.utils import FakeFile # circular import r = csv.reader(FakeFile(dist.get_metadata_lines('RECORD'))) for row in r: path = os.path.join(dist.location, row[0]) yield path if path.endswith('.py'): dn, fn = os.path.split(path) base = fn[:-3] path = os.path.join(dn, base + '.pyc') yield path def wheel_version(source_dir): """ Return the Wheel-Version of an extracted wheel, if possible. Otherwise, return False if we couldn't parse / extract it. """ try: dist = [d for d in pkg_resources.find_on_path(None, source_dir)][0] wheel_data = dist.get_metadata('WHEEL') wheel_data = Parser().parsestr(wheel_data) version = wheel_data['Wheel-Version'].strip() version = tuple(map(int, version.split('.'))) return version except: return False def check_compatibility(version, name): """ Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given """ if not version: raise UnsupportedWheel( "%s is in an unsupported or invalid wheel" % name ) if version[0] > VERSION_COMPATIBLE[0]: raise UnsupportedWheel( "%s's Wheel-Version (%s) is not compatible with this version " "of pip" % (name, '.'.join(map(str, version))) ) elif version > VERSION_COMPATIBLE: logger.warning( 'Installing from a newer Wheel-Version (%s)', '.'.join(map(str, version)), ) class Wheel(object): """A wheel file""" # TODO: maybe move the install code into this class wheel_file_re = re.compile( r"""^(?P<namever>(?P<name>.+?)-(?P<ver>\d.*?)) ((-(?P<build>\d.*?))?-(?P<pyver>.+?)-(?P<abi>.+?)-(?P<plat>.+?) \.whl|\.dist-info)$""", re.VERBOSE ) def __init__(self, filename): """ :raises InvalidWheelFilename: when the filename is invalid for a wheel """ wheel_info = self.wheel_file_re.match(filename) if not wheel_info: raise InvalidWheelFilename( "%s is not a valid wheel filename." % filename ) self.filename = filename self.name = wheel_info.group('name').replace('_', '-') # we'll assume "_" means "-" due to wheel naming scheme # (https://github.com/pypa/pip/issues/1150) self.version = wheel_info.group('ver').replace('_', '-') self.pyversions = wheel_info.group('pyver').split('.') self.abis = wheel_info.group('abi').split('.') self.plats = wheel_info.group('plat').split('.') # All the tag combinations from this file self.file_tags = set( (x, y, z) for x in self.pyversions for y in self.abis for z in self.plats ) def support_index_min(self, tags=None): """ Return the lowest index that one of the wheel's file_tag combinations achieves in the supported_tags list e.g. if there are 8 supported tags, and one of the file tags is first in the list, then return 0. Returns None is the wheel is not supported. """ if tags is None: # for mock tags = pep425tags.supported_tags indexes = [tags.index(c) for c in self.file_tags if c in tags] return min(indexes) if indexes else None def supported(self, tags=None): """Is this wheel supported on this system?""" if tags is None: # for mock tags = pep425tags.supported_tags return bool(set(tags).intersection(self.file_tags)) class WheelBuilder(object): """Build wheels from a RequirementSet.""" def __init__(self, requirement_set, finder, build_options=None, global_options=None): self.requirement_set = requirement_set self.finder = finder self._cache_root = requirement_set._wheel_cache._cache_dir self._wheel_dir = requirement_set.wheel_download_dir self.build_options = build_options or [] self.global_options = global_options or [] def _build_one(self, req, output_dir, python_tag=None): """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ tempd = tempfile.mkdtemp('pip-wheel-') try: if self.__build_one(req, tempd, python_tag=python_tag): try: wheel_name = os.listdir(tempd)[0] wheel_path = os.path.join(output_dir, wheel_name) shutil.move(os.path.join(tempd, wheel_name), wheel_path) logger.info('Stored in directory: %s', output_dir) return wheel_path except: pass # Ignore return, we can't do anything else useful. self._clean_one(req) return None finally: rmtree(tempd) def _base_setup_args(self, req): return [ sys.executable, "-u", '-c', SETUPTOOLS_SHIM % req.setup_py ] + list(self.global_options) def __build_one(self, req, tempd, python_tag=None): base_args = self._base_setup_args(req) spin_message = 'Running setup.py bdist_wheel for %s' % (req.name,) with open_spinner(spin_message) as spinner: logger.debug('Destination directory: %s', tempd) wheel_args = base_args + ['bdist_wheel', '-d', tempd] \ + self.build_options if python_tag is not None: wheel_args += ["--python-tag", python_tag] try: call_subprocess(wheel_args, cwd=req.setup_py_dir, show_stdout=False, spinner=spinner) return True except: spinner.finish("error") logger.error('Failed building wheel for %s', req.name) return False def _clean_one(self, req): base_args = self._base_setup_args(req) logger.info('Running setup.py clean for %s', req.name) clean_args = base_args + ['clean', '--all'] try: call_subprocess(clean_args, cwd=req.source_dir, show_stdout=False) return True except: logger.error('Failed cleaning build dir for %s', req.name) return False def build(self, autobuilding=False): """Build wheels. :param unpack: If True, replace the sdist we built from with the newly built wheel, in preparation for installation. :return: True if all the wheels built correctly. """ assert self._wheel_dir or (autobuilding and self._cache_root) # unpack sdists and constructs req set self.requirement_set.prepare_files(self.finder) reqset = self.requirement_set.requirements.values() buildset = [] for req in reqset: if req.constraint: continue if req.is_wheel: if not autobuilding: logger.info( 'Skipping %s, due to already being wheel.', req.name) elif req.editable: if not autobuilding: logger.info( 'Skipping bdist_wheel for %s, due to being editable', req.name) elif autobuilding and req.link and not req.link.is_artifact: pass elif autobuilding and not req.source_dir: pass else: if autobuilding: link = req.link base, ext = link.splitext() if pip.index.egg_info_matches(base, None, link) is None: # Doesn't look like a package - don't autobuild a wheel # because we'll have no way to lookup the result sanely continue if "binary" not in pip.index.fmt_ctl_formats( self.finder.format_control, canonicalize_name(req.name)): logger.info( "Skipping bdist_wheel for %s, due to binaries " "being disabled for it.", req.name) continue buildset.append(req) if not buildset: return True # Build the wheels. logger.info( 'Building wheels for collected packages: %s', ', '.join([req.name for req in buildset]), ) with indent_log(): build_success, build_failure = [], [] for req in buildset: python_tag = None if autobuilding: python_tag = pep425tags.implementation_tag output_dir = _cache_for_link(self._cache_root, req.link) try: ensure_dir(output_dir) except OSError as e: logger.warning("Building wheel for %s failed: %s", req.name, e) build_failure.append(req) continue else: output_dir = self._wheel_dir wheel_file = self._build_one( req, output_dir, python_tag=python_tag, ) if wheel_file: build_success.append(req) if autobuilding: # XXX: This is mildly duplicative with prepare_files, # but not close enough to pull out to a single common # method. # The code below assumes temporary source dirs - # prevent it doing bad things. if req.source_dir and not os.path.exists(os.path.join( req.source_dir, PIP_DELETE_MARKER_FILENAME)): raise AssertionError( "bad source dir - missing marker") # Delete the source we built the wheel from req.remove_temporary_source() # set the build directory again - name is known from # the work prepare_files did. req.source_dir = req.build_location( self.requirement_set.build_dir) # Update the link for this. req.link = pip.index.Link( path_to_url(wheel_file)) assert req.link.is_wheel # extract the wheel into the dir unpack_url( req.link, req.source_dir, None, False, session=self.requirement_set.session) else: build_failure.append(req) # notify success/failure if build_success: logger.info( 'Successfully built %s', ' '.join([req.name for req in build_success]), ) if build_failure: logger.info( 'Failed to build %s', ' '.join([req.name for req in build_failure]), ) # Return True if all builds were successful return len(build_failure) == 0
# coding: utf-8 """ Wavefront REST API Documentation <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST API documentation you must add the header \"Authorization: Bearer &lt;&lt;API-TOKEN&gt;&gt;\" to your HTTP requests.</p> # noqa: E501 OpenAPI spec version: v2 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from wavefront_api_client.configuration import Configuration class RoleDTO(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'created_epoch_millis': 'int', 'customer': 'str', 'description': 'str', 'id': 'str', 'last_updated_account_id': 'str', 'last_updated_ms': 'int', 'linked_accounts_count': 'int', 'linked_groups_count': 'int', 'name': 'str', 'permissions': 'list[str]', 'sample_linked_accounts': 'list[str]', 'sample_linked_groups': 'list[UserGroup]' } attribute_map = { 'created_epoch_millis': 'createdEpochMillis', 'customer': 'customer', 'description': 'description', 'id': 'id', 'last_updated_account_id': 'lastUpdatedAccountId', 'last_updated_ms': 'lastUpdatedMs', 'linked_accounts_count': 'linkedAccountsCount', 'linked_groups_count': 'linkedGroupsCount', 'name': 'name', 'permissions': 'permissions', 'sample_linked_accounts': 'sampleLinkedAccounts', 'sample_linked_groups': 'sampleLinkedGroups' } def __init__(self, created_epoch_millis=None, customer=None, description=None, id=None, last_updated_account_id=None, last_updated_ms=None, linked_accounts_count=None, linked_groups_count=None, name=None, permissions=None, sample_linked_accounts=None, sample_linked_groups=None, _configuration=None): # noqa: E501 """RoleDTO - a model defined in Swagger""" # noqa: E501 if _configuration is None: _configuration = Configuration() self._configuration = _configuration self._created_epoch_millis = None self._customer = None self._description = None self._id = None self._last_updated_account_id = None self._last_updated_ms = None self._linked_accounts_count = None self._linked_groups_count = None self._name = None self._permissions = None self._sample_linked_accounts = None self._sample_linked_groups = None self.discriminator = None if created_epoch_millis is not None: self.created_epoch_millis = created_epoch_millis if customer is not None: self.customer = customer if description is not None: self.description = description if id is not None: self.id = id if last_updated_account_id is not None: self.last_updated_account_id = last_updated_account_id if last_updated_ms is not None: self.last_updated_ms = last_updated_ms if linked_accounts_count is not None: self.linked_accounts_count = linked_accounts_count if linked_groups_count is not None: self.linked_groups_count = linked_groups_count if name is not None: self.name = name if permissions is not None: self.permissions = permissions if sample_linked_accounts is not None: self.sample_linked_accounts = sample_linked_accounts if sample_linked_groups is not None: self.sample_linked_groups = sample_linked_groups @property def created_epoch_millis(self): """Gets the created_epoch_millis of this RoleDTO. # noqa: E501 :return: The created_epoch_millis of this RoleDTO. # noqa: E501 :rtype: int """ return self._created_epoch_millis @created_epoch_millis.setter def created_epoch_millis(self, created_epoch_millis): """Sets the created_epoch_millis of this RoleDTO. :param created_epoch_millis: The created_epoch_millis of this RoleDTO. # noqa: E501 :type: int """ self._created_epoch_millis = created_epoch_millis @property def customer(self): """Gets the customer of this RoleDTO. # noqa: E501 The id of the customer to which the role belongs # noqa: E501 :return: The customer of this RoleDTO. # noqa: E501 :rtype: str """ return self._customer @customer.setter def customer(self, customer): """Sets the customer of this RoleDTO. The id of the customer to which the role belongs # noqa: E501 :param customer: The customer of this RoleDTO. # noqa: E501 :type: str """ self._customer = customer @property def description(self): """Gets the description of this RoleDTO. # noqa: E501 The description of the role # noqa: E501 :return: The description of this RoleDTO. # noqa: E501 :rtype: str """ return self._description @description.setter def description(self, description): """Sets the description of this RoleDTO. The description of the role # noqa: E501 :param description: The description of this RoleDTO. # noqa: E501 :type: str """ self._description = description @property def id(self): """Gets the id of this RoleDTO. # noqa: E501 The unique identifier of the role # noqa: E501 :return: The id of this RoleDTO. # noqa: E501 :rtype: str """ return self._id @id.setter def id(self, id): """Sets the id of this RoleDTO. The unique identifier of the role # noqa: E501 :param id: The id of this RoleDTO. # noqa: E501 :type: str """ self._id = id @property def last_updated_account_id(self): """Gets the last_updated_account_id of this RoleDTO. # noqa: E501 The account that updated this role last time # noqa: E501 :return: The last_updated_account_id of this RoleDTO. # noqa: E501 :rtype: str """ return self._last_updated_account_id @last_updated_account_id.setter def last_updated_account_id(self, last_updated_account_id): """Sets the last_updated_account_id of this RoleDTO. The account that updated this role last time # noqa: E501 :param last_updated_account_id: The last_updated_account_id of this RoleDTO. # noqa: E501 :type: str """ self._last_updated_account_id = last_updated_account_id @property def last_updated_ms(self): """Gets the last_updated_ms of this RoleDTO. # noqa: E501 The last time when the role is updated, in epoch milliseconds # noqa: E501 :return: The last_updated_ms of this RoleDTO. # noqa: E501 :rtype: int """ return self._last_updated_ms @last_updated_ms.setter def last_updated_ms(self, last_updated_ms): """Sets the last_updated_ms of this RoleDTO. The last time when the role is updated, in epoch milliseconds # noqa: E501 :param last_updated_ms: The last_updated_ms of this RoleDTO. # noqa: E501 :type: int """ self._last_updated_ms = last_updated_ms @property def linked_accounts_count(self): """Gets the linked_accounts_count of this RoleDTO. # noqa: E501 Total number of accounts that are linked to the role # noqa: E501 :return: The linked_accounts_count of this RoleDTO. # noqa: E501 :rtype: int """ return self._linked_accounts_count @linked_accounts_count.setter def linked_accounts_count(self, linked_accounts_count): """Sets the linked_accounts_count of this RoleDTO. Total number of accounts that are linked to the role # noqa: E501 :param linked_accounts_count: The linked_accounts_count of this RoleDTO. # noqa: E501 :type: int """ self._linked_accounts_count = linked_accounts_count @property def linked_groups_count(self): """Gets the linked_groups_count of this RoleDTO. # noqa: E501 Total number of groups that are linked to the role # noqa: E501 :return: The linked_groups_count of this RoleDTO. # noqa: E501 :rtype: int """ return self._linked_groups_count @linked_groups_count.setter def linked_groups_count(self, linked_groups_count): """Sets the linked_groups_count of this RoleDTO. Total number of groups that are linked to the role # noqa: E501 :param linked_groups_count: The linked_groups_count of this RoleDTO. # noqa: E501 :type: int """ self._linked_groups_count = linked_groups_count @property def name(self): """Gets the name of this RoleDTO. # noqa: E501 The name of the role # noqa: E501 :return: The name of this RoleDTO. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this RoleDTO. The name of the role # noqa: E501 :param name: The name of this RoleDTO. # noqa: E501 :type: str """ self._name = name @property def permissions(self): """Gets the permissions of this RoleDTO. # noqa: E501 List of permissions the role has been granted access to # noqa: E501 :return: The permissions of this RoleDTO. # noqa: E501 :rtype: list[str] """ return self._permissions @permissions.setter def permissions(self, permissions): """Sets the permissions of this RoleDTO. List of permissions the role has been granted access to # noqa: E501 :param permissions: The permissions of this RoleDTO. # noqa: E501 :type: list[str] """ self._permissions = permissions @property def sample_linked_accounts(self): """Gets the sample_linked_accounts of this RoleDTO. # noqa: E501 A sample of the accounts assigned to this role. Please use the Role facet of the Account Search API to get the full list of accounts for this role # noqa: E501 :return: The sample_linked_accounts of this RoleDTO. # noqa: E501 :rtype: list[str] """ return self._sample_linked_accounts @sample_linked_accounts.setter def sample_linked_accounts(self, sample_linked_accounts): """Sets the sample_linked_accounts of this RoleDTO. A sample of the accounts assigned to this role. Please use the Role facet of the Account Search API to get the full list of accounts for this role # noqa: E501 :param sample_linked_accounts: The sample_linked_accounts of this RoleDTO. # noqa: E501 :type: list[str] """ self._sample_linked_accounts = sample_linked_accounts @property def sample_linked_groups(self): """Gets the sample_linked_groups of this RoleDTO. # noqa: E501 A sample of the groups assigned to this role. Please use the Role facet of the Group Search API to get the full list of groups for this role # noqa: E501 :return: The sample_linked_groups of this RoleDTO. # noqa: E501 :rtype: list[UserGroup] """ return self._sample_linked_groups @sample_linked_groups.setter def sample_linked_groups(self, sample_linked_groups): """Sets the sample_linked_groups of this RoleDTO. A sample of the groups assigned to this role. Please use the Role facet of the Group Search API to get the full list of groups for this role # noqa: E501 :param sample_linked_groups: The sample_linked_groups of this RoleDTO. # noqa: E501 :type: list[UserGroup] """ self._sample_linked_groups = sample_linked_groups def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(RoleDTO, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, RoleDTO): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, RoleDTO): return True return self.to_dict() != other.to_dict()
# # This source file is part of appleseed. # Visit https://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2016-2019 Esteban Tovagliari, The appleseedhq Organization # # 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. # # Maya imports. import maya.cmds as mc import maya.mel as mel import maya.OpenMaya as om import maya.OpenMayaUI as omui # appleseedMaya imports. from logger import logger from appleseedMaya.renderGlobals import createGlobalNodes def translatorOptions(parent, action, initialSettings, resultCallback): defaults = { "activeCamera": "<Current>", "exportAnim": False, "startFrame": 1, "endFrame": 100, "stepFrame": 1 } createGlobalNodes() if initialSettings: logger.debug( "Parsing initial translator settings %s" % initialSettings) opts = initialSettings.split(";") for opt in opts: opt = opt.strip() if opt == "": continue name, value = opt.split("=") if name in defaults: if isinstance(defaults[name], basestring): defaults[name] = value elif isinstance(defaults[name], bool): defaults[name] = bool(value) elif isinstance(defaults[name], int): defaults[name] = int(value) else: logger.warning( "Unhandled param %s in translator options" % name) if action == "post": mc.setParent(parent) mc.setUITemplate("DefaultTemplate", pushTemplate=True) mc.columnLayout(adj=True) mc.optionMenuGrp( "as_exportOpts_activeCamera", label="Render camera") mc.menuItem(label='<Current>', divider=True) for camera in mc.ls(type='camera'): if mc.getAttr(camera + '.orthographic'): continue if not mc.getAttr(camera + ".renderable"): continue mc.menuItem(label=camera) mc.separator(style="single") def exportAnimChanged(value): mc.intSliderGrp( "as_exportOpts_startFrame", edit=True, enable=value) mc.intSliderGrp( "as_exportOpts_endFrame", edit=True, enable=value) mc.intSliderGrp( "as_exportOpts_stepFrame", edit=True, enable=value) exportAnim = defaults["exportAnim"] mc.checkBoxGrp( "as_exportOpts_exportAnim", numberOfCheckBoxes=1, label=" ", label1="Animation", cc=exportAnimChanged, value1=exportAnim) mc.intSliderGrp( "as_exportOpts_startFrame", label="Start:", field=True, min=1, max=1000, enable=exportAnim, value=defaults["startFrame"]) mc.intSliderGrp( "as_exportOpts_endFrame", label="End:", field=True, min=1, max=1000, enable=exportAnim, value=defaults["endFrame"]) mc.intSliderGrp( "as_exportOpts_stepFrame", label="Step:", field=True, min=1, max=100, enable=exportAnim, value=defaults["stepFrame"]) elif action == "query": options = "" value = mc.optionMenuGrp( "as_exportOpts_activeCamera", query=True, value=True) # Replace current by the active camera. if value == "<Current>": if om.MGlobal.mayaState() == om.MGlobal.kInteractive: camera = om.MDagPath() omui.M3dView.active3dView().getCamera(camera) if mc.getAttr(camera.partialPathName() + ".renderable"): value = camera.partialPathName() else: logger.warning("Active camera not renderable. Ignoring.") value = "" else: logger.warning("Active camera specified for maya batch.") value = "" if value: options += "activeCamera=" + value + ";" exportAnim = mc.checkBoxGrp( "as_exportOpts_exportAnim", query=True, value1=True) if exportAnim: options += "exportAnim=true;" value = mc.intSliderGrp( "as_exportOpts_startFrame", query=True, value=True) options += "startFrame=" + str(value) + ";" value = mc.intSliderGrp( "as_exportOpts_endFrame", query=True, value=True) options += "endFrame=" + str(value) + ";" value = mc.intSliderGrp( "as_exportOpts_stepFrame", query=True, value=True) options += "stepFrame=" + str(value) + ";" logger.debug("calling translator callback, options = %s" % options) mel.eval('%s "%s"' % (resultCallback, options)) def createTranslatorMelProcedures(): mel.eval(''' global proc appleseedTranslatorOpts(string $parent, string $action, string $initialSettings, string $resultCallback) { python("import appleseedMaya.renderGlobals"); python("appleseedMaya.renderGlobals.createGlobalNodes()"); python("import appleseedMaya.translator"); string $pythonCmd = "appleseedMaya.translator.translatorOptions("; $pythonCmd = $pythonCmd + "\\\"" + $parent + "\\\", "; $pythonCmd = $pythonCmd + "\\\"" + $action + "\\\", "; $pythonCmd = $pythonCmd + "\\\"" + $initialSettings + "\\\", "; $pythonCmd = $pythonCmd + "\\\"" + $resultCallback + "\\\")"; python($pythonCmd); } ''' )
""" Attempt to implement a reactive system in Python. With that I mean a system in which signals are bound implicitly, as in Shiny. The Signal is the core element here. It is like the Property in HasProps. A function can easily be turned into a Signal object by decorating it. Other than Properties, signals have a function associated with them. that compute stuff (maybe rename signal to behavior). They also cache their value. """ import re import sys import time import inspect class Signal: #todo: or is this a "behavior"? """ Wrap a function in a class to allow marking it dirty and caching last result. """ def __init__(self, fun): self._fun = fun self._value = None self._dirty = True self._dependers = [] def __call__(self, *args): if self._dirty: self._value = self._fun(*args) self._dirty = False return self._value def set_dirty(self): self._dirty = True for dep in self._dependers: dep.set_dirty() dep() class Input(Signal): """ A signal defined simply by a value that can be set. You can consider this a source signal. """ def __init__(self): Signal.__init__(self, lambda x=None:None) def set(self, value): self._value = value self.set_dirty() class Output(Signal): pass # I don't think that I need this? def check_deps(fun, locals, globals): """ Analyse the source code of fun to get the signals that the reactive function depends on. It then registers the function at these signals. """ # Get source of function and find uses of inputs # todo: use AST parsing instead s = inspect.getsource(fun._fun) matches = re.findall(r'([a-zA-Z0-9_.]+?)\.get_signal\([\'\"](\w+?)[\'\"]\)', s) fun._nmatches = 0 # print('found %i deps on %r' % (len(matches), fun)) # For each used input, try to retrieve the actual object for match in matches: ob = locals.get(match[0], globals.get(match[0], None)) if ob is None: print('could not locate dependency %r' % match[0]) else: ob._bind_signal(match[1], fun) fun._nmatches += 1 # print('bound signal for', ob) #dep = getattr(ob, 'input_'+match[1]) #print('found dep ', dep) # Detect outputs #matches = re.findall(r'([a-zA-Z0-9_.]+?)\.set_output\([\'\"](\w+?)[\'\"]\,', s) # Detect calls if fun._nmatches: matches = re.findall(r'([a-zA-Z0-9_.]+?)\(', s) for match in matches: ob = locals.get(match[0], globals.get(match[0], None)) if isinstance(ob, Signal): ob._dependers.append(fun) # # For each used input, try to retrieve the actual object # for match in matches: # ob = locals.get(match[0], globals.get(match[0], None)) # if ob is None: # print('could not locate dependency %r' % match[0]) # else: # ob._bind_signal(match[1], fun2) fun._deps_checked = len(matches) def react(fun): """ decorator """ # fun should be called, when any of its deps gets called # can I get that info? # Probably with sys.settrace(), but that is CPython specific. # Evaluating source code via inspect? # Evaluating the AST? # -> We can detect "input.slider" or something, but can we detect # what object its called on? What is "w"? # Note: only works on Python implementations that have a stack _frame = sys._getframe(1) # todo: from trellis: # if isinstance(rule, types.FunctionType): # only pick up name if a function # if frame.f_locals.get(rule.__name__) is rule: # and locally-defined! # name = name or rule.__name__ if not isinstance(fun, Signal): fun = Signal(fun) check_deps(fun, _frame.f_locals, _frame.f_globals) if fun._nmatches: return fun else: return fun._fun # return original, its probbaly a method that we shoukd try later class Reactive: """ Base class for classes that can have signals and reactive methods. """ SIGNALS = [] def __init__(self): self._signals = {} self._downstream = {} for name, val in self.SIGNALS: self._signals[name] = val for name in dir(self.__class__): cls_ob = getattr(self.__class__, name) if hasattr(cls_ob, '_deps_checked'): fun = getattr(self, name) # print('re-trying reactive') react(fun) def _emit_signal(self, name, value): self._signals[name] = value for f in self._downstream.get(name, ()): f.set_dirty() f() def _bind_signal(self, name, fun): funcs = self._downstream.setdefault(name, []) if fun not in funcs: funcs.append(fun) def bind_signals(self, *args): # Alternative: explicit binding def bind(fun): if not isinstance(fun, Signal): fun = Signal(fun) for name in names: funcs = self._downstream.setdefault(name, []) if fun not in funcs: funcs.append(fun) return fun fun = None names = [] for arg in args: if callable(arg): fun = arg else: names.append(arg) print('binding ', names) if fun is None: return bind else: return bin(fun) def get_signal(self, name): # i = inspect.getframeinfo(inspect.currentframe()) if False: s = inspect.stack() caller = s[1] print(caller[0].f_locals.keys()) print(caller[0].f_globals.keys()) id = caller[1], caller[2], caller[3] # if 'self' in f_locals: # fun = f_locals() self.caller = caller self.caller2 = sys._getframe(1) fun = caller[0].f_globals[id[-1]] print(id, fun) self._bind_signal(name, fun) return self._signals[name] def set_output(self, name, value): # def xx(fun): # def yy(): # value = fun() # f = getattr(self, 'on_' + name) # f(value) # fun() # return yy # return xx f = getattr(self, 'on_' + name) f(value) print('-----') class Widget(Reactive): SIGNALS = [('slider1', 0), ('slider2', 0)] def manual_slider1(self, v): """ Simulate changing a slider value. """ # if this is called, outpus should be shown # todo: also store latest value self._emit_signal('slider1', v) def manual_slider2(self, v): self._emit_signal('slider2', v) def on_show(self, val): print('hooray!', val) class Widget1(Widget): @react def bla1(self): x = self.get_signal('slider1') * 3 self.set_output('show', x) w = Widget1() @react def something_that_takes_long(): # when slider1 changes, it should invoke bla! (and other inputs/signals that depend on it print('this may take a while') time.sleep(1) return w.get_signal('slider1') * 2 @react def bla(): # to an output. x = something_that_takes_long() x += w.get_signal('slider2') w.set_output('show', x - 1) # todo: set_output, or return and connect somehow? print('-----') class Widget2(Widget): def on_slider1_change(self): # but can only bind to single change x = self.get_signal('slider1') * 3 self.set_output('show', x) # # maybe this? but then slider1 of what? # @binding('slider1', 'slider2') # def xxx(self): # pass w2 = Widget2() @w2.bind_signals('slider1') def something_that_takes_long(): # when slider1 changes, it should invoke bla! (and other inputs/signals that depend on it print('this may take a while') time.sleep(1) return w2.get_signal('slider1') * 2 #@some_widget.bind_signals('foo') #@some_other_widget.bind_signals('bar') @w2.bind_signals('slider2') # todo: w2.bind_signals('slider2', something_that_takes_long) def bla(): # to an output. x = something_that_takes_long() x += w2.get_signal('slider2') w2.set_output('show', x - 1) # todo: set_output, or return and connect somehow? print('-----') class Temp2(Reactive): """ Simple example of object that has signals for temperature in both Celcius and Fahrenheit. Changing either automatically changes the other. """ SIGNALS = [('C', 0), ('F', 32)] t2 = Temp2() self = t2 @t2.bind_signals('F') def _c2f(): self._signals['C'] = (self.get_signal('F')-32) / 1.8 @t2.bind_signals('C') def _f2c(): self._signals['F'] = self.get_signal('C') * 1.8 + 32 @t2.bind_signals('C', 'F') def _show(): print('C:', self.get_signal('C')) print('F:', self.get_signal('F'))
''' Created on 1 Feb 2013 @author: Kieran Finn ''' import pylab as p import urllib2 import sys import json from glob import glob import pickle from functions import * from random import random from collections import defaultdict import webbrowser import os #folder='D:/Documents/Planet_hunters/results/01_Feb_2013_11_14/' #folder='full_data_28_01_13' folder='final_run/' fname='investigate_full.csv' data_folder='D:/Documents/Planet_hunters/ph-stars/' if not os.path.isdir(data_folder): data_folder='/Users/kieranfinn/Documents/ph-stars/' out=fname.split('.')[0]+'.pkl' colormap=p.get_cmap() colours=pload('user_scores.dat') colours['NULL']=1.0 #colours=defaultdict(lambda:0.5) zooniverse_dict=pload('source_zooniverse.dat') def open_url(url): N=3 n=0 while n<N: try: return urllib2.urlopen(url) except: n+=1 return False def read_url(url): fname=data_folder+url.split('/')[-1] if not os.path.isfile(fname) or os.path.getsize(fname)==0: print '\n%s not downloaded' %fname try: f=open_url(url) g=open(fname,'w') g.write(f.read()) g.close() f.close() except: print 'Problem with url %s' %url return [] f=open(fname,'r') r=f.read() f.close() try: if r[0]=='l': r=r[17:].rstrip('\n;)') #there is a problem with some of the json files for the data. need to strip some of the header except: print url print fname print r try: out=json.loads(r) except: print 'error reading json file' print r[:100]+'...'+r[-100:] return {} try: out=out['data']#gets rid of meta data if there except: pass return out def get_scores(folder): out={} files=glob(folder+'*.dat') #files=['weighted mean.csv','mean.csv','frequentist.csv','ibcc.csv'] for fname in files: name=fname.split('\\')[-1].split('.')[0] out[name]=pload(fname) #out[name]=csvload(fname) return out class box(): def __init__(self,x,y,width,height,colour): self.x1=x self.x2=x+width self.y1=y self.y2=y+height self.colour=colour def points(self): x=[self.x1,self.x1,self.x2,self.x2,self.x1] y=[self.y1,self.y2,self.y2,self.y1,self.y1] return [x,y] def plot(self): x,y=self.points() p.plot(x,y,color=self.colour) class light_curve(): def __init__(self,light_curve_id,url,release_id): self.id=light_curve_id self.data=False self.release_id=release_id self.boxes=[] self.url=url def add_box(self,x,y,width,height,user): try: x=float(x) y=float(y) width=float(width) height=float(height) self.boxes.append(box(x,y,width,height,colormap(colours[user]))) except: pass def get_data(self): if not self.data: self.data=read_url(self.url) return self.data def plot(self,clean=False): fig=p.figure(int(float(self.release_id)*10)) x=[] y=[] dy=[] for point in self.get_data(): try: x.append(float(point['x'])) y.append(float(point['y'])) dy.append(float(point['dy'])) except: print point print 'error with point' continue p.errorbar(x,y,yerr=dy,fmt='ro') p.title('light curve id: %s\nrelease id: %s' %(self.id,self.release_id)) if not clean: for box in self.boxes: box.plot() ax=fig.axes[0] ax=p.mpl.colorbar.make_axes(ax)[0] p.mpl.colorbar.ColorbarBase(ax,cmap=colormap) class source(): def __init__(self,source_id,label): self.id=source_id self.light_curves={} self.label=label def get_light_curve(self,light_curve_id,url,release_id): if light_curve_id not in self.light_curves.keys(): self.light_curves[light_curve_id]=light_curve(light_curve_id,url,release_id) return self.light_curves[light_curve_id] def plot(self,clean=False): print 'Details for source number %s' %self.id print 'Label: %s' %self.label for method in scores.keys(): try: print '%s: %.4f' %(method, scores[method][self.id]) except: pass for light_curve_id in self.light_curves.keys(): self.light_curves[light_curve_id].plot(clean=clean) def read_data(fname): out={} f=open(fname,'r') r=f.readlines() f.close() count=0 for line in r: if count%100==0: overprint('processing line %s of %s' %(add_comma(count),add_comma(len(r)))) count +=1 source_id,light_curve_id,user_id,label,url,release_id,x,y,width,height=line.strip().split(',') url=url.strip('"') if source_id not in out.keys(): out[source_id]=source(source_id,label) lc=out[source_id].get_light_curve(light_curve_id,url,release_id) lc.add_box(x,y,width,height,user_id) print '\n' return out def openpage(s): url='http://www.planethunters.org/sources/%s' %zooniverse_dict[s] webbrowser.open(url) def user_plots(): while True: source_id=raw_input('Enter the source id: ') if source_id=='0': break p.close('all') try: sources[source_id].plot() openpage(source_id) except KeyError: print 'not a valid source id' def transit_plot(source,release): p.close('all') source=str(source) sources[source].plot(clean=True) light='' for lc in sources[source].light_curves.keys(): if sources[source].light_curves[lc].release_id==str(release): light=lc p.figure(int(release*10)) p.title('Source id: %s\nLight Curve id: %s Release id: %.1f' %(source,light,release)) p.xlabel('Day') p.ylabel('Relative Luminosity') scores=get_scores(folder) #scores=defaultdict(lambda:defaultdict(lambda:1)) sources=read_data(fname) '''for source_id in sources.keys(): for light_curve_id in sources[source_id].light_curves.keys(): sources[source_id].light_curves[light_curve_id].colours=dict(sources[source_id].light_curves[light_curve_id].colours) f=open(out,'w') pickle.dump(sources,f) f.close()''' print 'done'
# # FitsImageCanvasTypesGtk.py -- drawing classes for FitsImageCanvas widget # # Eric Jeschke ([email protected]) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. import math import gtk, re import cairo from ginga.FitsImageCanvas import * from ginga import Mixins from ginga.misc import Callback, Bunch class CanvasObject(CanvasObjectBase): def set_color(self, cr, color): if isinstance(color, str): color = gtk.gdk.color_parse(color) rgb_s = color.to_string() match = re.match(r'^#(\w{4})(\w{4})(\w{4})$', rgb_s) r, g, b = map(lambda s: float(int(s, 16))/65535.0, match.groups()) elif isinstance(color, tuple): # color is assumed to be a 3-tuple of RGB values as floats # between 0 and 1 r, g, b = color else: r, g, b = 1.0, 1.0, 1.0 cr.set_source_rgb(r, g, b) def setup_cr(self): cr = self.fitsimage.get_offscreen_context() self.set_color(cr, self.color) if hasattr(self, 'linewidth'): cr.set_line_width(self.linewidth) else: cr.set_line_width(1) if hasattr(self, 'linestyle'): if self.linestyle == 'dash': cr.set_dash([ 3.0, 4.0, 6.0, 4.0], 5.0) return cr def draw_arrowhead(self, cr, x1, y1, x2, y2): i1, j1, i2, j2 = self.calcVertexes(x1, y1, x2, y2) cr.move_to (x2, y2) cr.line_to (i1, j1) cr.line_to (i2, j2) cr.close_path() cr.stroke_preserve() cr.fill() def draw_cap(self, cr, cap, x, y, radius=2): if cap == 'ball': cr.arc(x, y, radius, 0, 2*math.pi) cr.fill() def draw_caps(self, cr, cap, points, radius=2): for x, y in points: self.draw_cap(cr, cap, x, y, radius=radius) def text_extents(self, cr, text): a, b, wd, ht, i, j = cr.text_extents(text) return wd, ht class CompoundObject(CompoundMixin, CanvasObject): """Compound object on a FitsImageCanvas. Parameters are: the child objects making up the compound object. Objects are drawn in the order listed. Example: CompoundObject(Point(x, y, radius, ...), Circle(x, y, radius, ...)) This makes a point inside a circle. """ def __init__(self, *objects): CanvasObject.__init__(self) CompoundMixin.__init__(self) self.kind = 'compound' self.objects = list(objects) class Canvas(CanvasMixin, CompoundObject, CanvasObject): def __init__(self, *objects): CanvasObject.__init__(self) CompoundObject.__init__(self, *objects) CanvasMixin.__init__(self) self.kind = 'canvas' class Text(CanvasObject): """Draws text on a FitsImageCanvas. Parameters are: x, y: 0-based coordinates in the data space text: the text to draw Optional parameters for fontsize, color, etc. """ def __init__(self, x, y, text, font='Sans Serif', fontsize=None, color='yellow'): self.kind = 'text' super(Text, self).__init__(color=color, x=x, y=y, font=font, fontsize=fontsize, text=text) def draw(self): cx, cy = self.canvascoords(self.x, self.y) cr = self.setup_cr() cr.select_font_face(self.font) if not self.fontsize: fontsize = self.scale_font() else: fontsize = self.fontsize cr.set_font_size(fontsize) cr.move_to(cx, cy) cr.show_text(self.text) def rotate(self, theta, xoff=0, yoff=0): self.x, self.y = self.rotate_pt(self.x, self.y, theta, xoff=xoff, yoff=yoff) class Polygon(CanvasObject): """Draws a polygon on a FitsImageCanvas. Parameters are: List of (x, y) points in the polygon. The last one is assumed to be connected to the first. Optional parameters for linesize, color, etc. """ def __init__(self, points, color='red', linewidth=1, linestyle='solid', cap=None, fill=False, fillcolor=None): self.kind = 'polygon' super(Polygon, self).__init__(points=points, color=color, linewidth=linewidth, cap=cap, linestyle=linestyle, fill=fill, fillcolor=fillcolor) def draw(self): cpoints = map(lambda p: self.canvascoords(p[0], p[1]), self.points) cr = self.setup_cr() (cx0, cy0) = cpoints[-1] cr.move_to(cx0, cy0) for cx, cy in cpoints: cr.line_to(cx, cy) #cr.move_to(cx, cy) cr.close_path() cr.stroke_preserve() if self.fill: if self.fillcolor: self.set_color(cr, self.fillcolor) cr.fill() self.set_color(cr, self.color) if self.cap: self.draw_caps(cr, self.cap, cpoints) def contains(self, x, y): # NOTE: we use a version of the ray casting algorithm # See: http://alienryderflex.com/polygon/ result = False xj, yj = self.points[-1] for (xi, yi) in self.points: if ((((yi < y) and (yj >= y)) or ((yj < y) and (yi >= y))) and ((xi <= x) or (xj <= x))): cross = (xi + float(y - yi)/(yj - yi)*(xj - xi)) < x result ^= cross xj, yj = xi, yi return result def rotate(self, theta, xoff=0, yoff=0): newpts = map(lambda p: self.rotate_pt(p[0], p[1], theta, xoff=xoff, yoff=yoff), self.points) self.points = newpts class Rectangle(CanvasObject): """Draws a rectangle on a FitsImageCanvas. Parameters are: x1, y1: 0-based coordinates of one corner in the data space x2, y2: 0-based coordinates of the opposing corner in the data space Optional parameters for linesize, color, etc. PLEASE NOTE: that the coordinates will be arranged in the final object such that x1, y1 always refers to the lower-left corner. """ def __init__(self, x1, y1, x2, y2, color='red', linewidth=1, linestyle='solid', cap=None, fill=False, fillcolor=None, drawdims=False, font='Sans Serif'): self.kind = 'rectangle' # ensure that rectangles are always bounded LL to UR x1, y1, x2, y2 = self.swapxy(x1, y1, x2, y2) super(Rectangle, self).__init__(color=color, x1=x1, y1=y1, x2=x2, y2=y2, linewidth=linewidth, cap=cap, linestyle=linestyle, fill=fill, fillcolor=fillcolor, drawdims=drawdims, font=font) def draw(self): cr = self.setup_cr() cpoints = map(lambda p: self.canvascoords(p[0], p[1]), ((self.x1, self.y1), (self.x2, self.y1), (self.x2, self.y2), (self.x1, self.y2))) (cx0, cy0) = cpoints[-1] cr.move_to(cx0, cy0) for cx, cy in cpoints: cr.line_to(cx, cy) #cr.move_to(cx, cy) cr.close_path() cr.stroke_preserve() if self.fill: if self.fillcolor: self.set_color(cr, self.fillcolor) cr.fill() self.set_color(cr, self.color) if self.cap: self.draw_caps(cr, self.cap, cpoints) if self.drawdims: cr.select_font_face(self.font) fontsize = self.scale_font() cr.set_font_size(fontsize) cx1, cy1 = cpoints[0] cx2, cy2 = cpoints[2] # draw label on X dimension cx = cx1 + (cx2 - cx1) // 2 cy = cy2 + -4 cr.move_to(cx, cy) cr.show_text("%d" % (self.x2 - self.x1)) cy = cy1 + (cy2 - cy1) // 2 cx = cx2 + 4 cr.move_to(cx, cy) cr.show_text("%d" % (self.y2 - self.y1)) def contains(self, x, y): if ((x >= self.x1) and (x <= self.x2) and (y >= self.y1) and (y <= self.y2)): return True return False def rotate(self, theta, xoff=0, yoff=0): x1, y1 = self.rotate_pt(self.x1, self.y1, theta, xoff=xoff, yoff=yoff) x2, y2 = self.rotate_pt(self.x2, self.y2, theta, xoff=xoff, yoff=yoff) self.x1, self.y1, self.x2, self.y2 = self.swapxy(x1, y1, x2, y2) def toPolygon(self): points = [(self.x1, self.y1), (self.x2, self.y1), (self.x2, self.y2), (self.x1, self.y2)] p = Polygon(points, color=self.color, linewidth=self.linewidth, linestyle=self.linestyle, cap=self.cap, fill=self.fill, fillcolor=self.fillcolor) return p class Square(Rectangle): """Draws a square on a FitsImageCanvas. Parameters are: x, y: 0-based coordinates of the center in the data space length: size of a side (pixels in data space) Optional parameters for linesize, color, etc. """ def __init__(self, x, y, length, color='red', linewidth=1, linestyle='solid', cap=None, fill=False, fillcolor=None, drawdims=False, font='Sans Serif'): super(Square, self).__init__(x1=x, y1=y, x2=x-length, y2=y-length, color=color, linewidth=linewidth, cap=cap, linestyle=linestyle, fill=fill, fillcolor=fillcolor, drawdims=drawdims, font=font) self.kind = 'square' class Circle(CanvasObject): """Draws a circle on a FitsImageCanvas. Parameters are: x, y: 0-based coordinates of the center in the data space radius: radius based on the number of pixels in data space Optional parameters for linesize, color, etc. """ def __init__(self, x, y, radius, color='yellow', linewidth=1, linestyle='solid', cap=None, fill=False, fillcolor=None): super(Circle, self).__init__(color=color, linewidth=linewidth, cap=cap, linestyle=linestyle, fill=fill, fillcolor=fillcolor, x=x, y=y, radius=radius) self.kind = 'circle' def draw(self): cx1, cy1, cradius = self.calc_radius(self.x, self.y, self.radius) cr = self.setup_cr() cr.arc(cx1, cy1, cradius, 0, 2*math.pi) cr.stroke_preserve() if self.fill: if self.fillcolor: self.set_color(cr, self.fillcolor) cr.fill() self.set_color(cr, self.color) if self.cap: self.draw_caps(cr, self.cap, ((cx1, cy1), )) def contains(self, x, y): radius = math.sqrt(math.fabs(x - self.x)**2 + math.fabs(y - self.y)**2) if radius <= self.radius: return True return False def rotate(self, theta, xoff=0, yoff=0): self.x, self.y = self.rotate_pt(self.x, self.y, theta, xoff=xoff, yoff=yoff) class Point(CanvasObject): """Draws a point on a FitsImageCanvas. Parameters are: x, y: 0-based coordinates of the center in the data space radius: radius based on the number of pixels in data space Optional parameters for linesize, color, etc. PLEASE NOTE: currently on the 'cross' style of point is drawn. """ def __init__(self, x, y, radius, style='cross', color='yellow', linewidth=1, linestyle='solid', cap=None): self.kind = 'point' super(Point, self).__init__(color=color, linewidth=linewidth, linestyle=linestyle, x=x, y=y, radius=radius, cap=cap) def draw(self): cx, cy, cradius = self.calc_radius(self.x, self.y, self.radius) cx1, cy1 = cx - cradius, cy - cradius cx2, cy2 = cx + cradius, cy + cradius cr = self.setup_cr() cr.set_line_cap(cairo.LINE_CAP_ROUND) cr.move_to(cx1, cy1) cr.line_to(cx2, cy2) cr.stroke() cr.move_to(cx1, cy2) cr.line_to(cx2, cy1) cr.stroke() if self.cap: self.draw_caps(cr, self.cap, ((cx, cy), )) def contains(self, x, y): if (x == self.x) and (y == self.y): return True return False def rotate(self, theta, xoff=0, yoff=0): self.x, self.y = self.rotate_pt(self.x, self.y, theta, xoff=xoff, yoff=yoff) class Line(CanvasObject): """Draws a line on a FitsImageCanvas. Parameters are: x1, y1: 0-based coordinates of one end in the data space x2, y2: 0-based coordinates of the opposing end in the data space Optional parameters for linesize, color, etc. """ def __init__(self, x1, y1, x2, y2, color='red', linewidth=1, linestyle='solid', cap=None): self.kind = 'line' super(Line, self).__init__(color=color, linewidth=linewidth, cap=cap, linestyle=linestyle, x1=x1, y1=y1, x2=x2, y2=y2) def draw(self): cx1, cy1 = self.canvascoords(self.x1, self.y1) cx2, cy2 = self.canvascoords(self.x2, self.y2) cr = self.setup_cr() cr.set_line_cap(cairo.LINE_CAP_ROUND) cr.move_to(cx1, cy1) cr.line_to(cx2, cy2) cr.stroke() if self.cap: self.draw_caps(cr, self.cap, ((cx1, cy1), (cx2, cy2))) def rotate(self, theta, xoff=0, yoff=0): self.x1, self.y1 = self.rotate_pt(self.x1, self.y1, theta, xoff=xoff, yoff=yoff) self.x2, self.y2 = self.rotate_pt(self.x2, self.y2, theta, xoff=xoff, yoff=yoff) class Compass(CanvasObject): """Draws a WCS compass on a FitsImageCanvas. Parameters are: x1, y1: 0-based coordinates of the center in the data space x2, y2: 0-based coordinates of the 'North' end in the data space x3, y3: 0-based coordinates of the 'East' end in the data space Optional parameters for linesize, color, etc. """ def __init__(self, x1, y1, x2, y2, x3, y3, color='skyblue', linewidth=1, fontsize=None, cap='ball'): self.kind = 'compass' super(Compass, self).__init__(color=color, linewidth=linewidth, cap=cap, x1=x1, y1=y1, x2=x2, y2=y2, x3=x3, y3=y3, fontsize=fontsize) def draw(self): cx1, cy1 = self.canvascoords(self.x1, self.y1) cx2, cy2 = self.canvascoords(self.x2, self.y2) cx3, cy3 = self.canvascoords(self.x3, self.y3) cr = self.setup_cr() # draw North line and arrowhead cr.set_line_cap(cairo.LINE_CAP_ROUND) cr.move_to(cx1, cy1) cr.line_to(cx2, cy2) cr.stroke() self.draw_arrowhead(cr, cx1, cy1, cx2, cy2) # draw East line and arrowhead cr.move_to(cx1, cy1) cr.line_to(cx3, cy3) cr.stroke() self.draw_arrowhead(cr, cx1, cy1, cx3, cy3) # draw "N" & "E" cr.select_font_face('Sans Serif') if not self.fontsize: fontsize = self.scale_font() else: fontsize = self.fontsize cr.set_font_size(fontsize) cx, cy = self.get_textpos(cr, 'N', cx1, cy1, cx2, cy2) # cr.move_to(cx2, cy2) cr.move_to(cx, cy) cr.show_text('N') cx, cy = self.get_textpos(cr, 'E', cx1, cy1, cx3, cy3) # cr.move_to(cx3, cy3) cr.move_to(cx, cy) cr.show_text('E') if self.cap: self.draw_caps(cr, self.cap, ((cx1, cy1), )) def get_textpos(self, cr, text, cx1, cy1, cx2, cy2): htwd, htht = self.text_extents(cr, text) diag_xoffset = 0 diag_yoffset = 0 xplumb_yoffset = 0 yplumb_xoffset = 0 diag_yoffset = 14 if abs(cy1 - cy2) < 5: pass elif cy1 < cy2: xplumb_yoffset = -4 else: xplumb_yoffset = 14 diag_yoffset = -4 if abs(cx1 - cx2) < 5: diag_xoffset = -(4 + htwd) elif (cx1 < cx2): diag_xoffset = -(4 + htwd) yplumb_xoffset = 4 else: diag_xoffset = 4 yplumb_xoffset = -(4 + 0) xh = min(cx1, cx2); y = cy1 + xplumb_yoffset xh += (max(cx1, cx2) - xh) // 2 yh = min(cy1, cy2); x = cx2 + yplumb_xoffset yh += (max(cy1, cy2) - yh) // 2 xd = xh + diag_xoffset yd = yh + diag_yoffset return (xd, yd) class Triangle(CanvasObject): """Draws a right triangle on a FitsImageCanvas. Parameters are: x1, y1: 0-based coordinates of one end of the diagonal in the data space x2, y2: 0-based coordinates of the opposite end of the diagonal Optional parameters for linesize, color, etc. """ def __init__(self, x1, y1, x2, y2, color='pink', linewidth=1, linestyle='solid', cap=None): self.kind='triangle' super(Triangle, self).__init__(color=color, linewidth=linewidth, cap=cap, linestyle=linestyle, x1=x1, y1=y1, x2=x2, y2=y2) def draw(self): cx1, cy1 = self.canvascoords(self.x1, self.y1) cx2, cy2 = self.canvascoords(self.x2, self.y2) cr = self.setup_cr() cr.set_line_cap(cairo.LINE_CAP_ROUND) cr.move_to(cx1, cy1) cr.line_to(cx2, cy2) cr.stroke() cr.move_to(cx1, cy1) cr.line_to(cx2, cy1) cr.stroke() cr.move_to(cx2, cy1) cr.line_to(cx2, cy2) cr.stroke() if self.cap: self.draw_caps(cr, self.cap, ((cx1, cy1), (cx2, cy2), (cx2, cy1))) class Ruler(CanvasObject): """Draws a WCS ruler (like a right triangle) on a FitsImageCanvas. Parameters are: x1, y1: 0-based coordinates of one end of the diagonal in the data space x2, y2: 0-based coordinates of the opposite end of the diagonal Optional parameters for linesize, color, etc. """ def __init__(self, x1, y1, x2, y2, color='red', color2='yellow', linewidth=1, cap='ball', units='arcsec', font='Sans Serif', fontsize=None, text_x='kon', text_y='ban', text_h='wa'): self.kind = 'ruler' super(Ruler, self).__init__(color=color, color2=color2, linewidth=linewidth, cap=cap, x1=x1, y1=y1, x2=x2, y2=y2, font=font, fontsize=fontsize, text_x=text_x, text_y=text_y, text_h=text_h) def draw(self): cx1, cy1 = self.canvascoords(self.x1, self.y1) cx2, cy2 = self.canvascoords(self.x2, self.y2) cr = self.setup_cr() cr.select_font_face(self.font) if not self.fontsize: fontsize = self.scale_font() else: fontsize = self.fontsize cr.set_font_size(fontsize) cr.set_line_cap(cairo.LINE_CAP_ROUND) cr.move_to(cx1, cy1) cr.line_to(cx2, cy2) cr.stroke() self.draw_arrowhead(cr, cx1, cy1, cx2, cy2) self.draw_arrowhead(cr, cx2, cy2, cx1, cy1) cr.set_dash([ 3.0, 4.0, 6.0, 4.0], 5.0) # calculate offsets and positions for drawing labels # try not to cover anything up xtwd, xtht = self.text_extents(cr, self.text_x) ytwd, ytht = self.text_extents(cr, self.text_y) htwd, htht = self.text_extents(cr, self.text_h) diag_xoffset = 0 diag_yoffset = 0 xplumb_yoffset = 0 yplumb_xoffset = 0 diag_yoffset = 14 if abs(cy1 - cy2) < 5: show_angle = 0 elif cy1 < cy2: xplumb_yoffset = -4 else: xplumb_yoffset = 14 diag_yoffset = -4 if abs(cx1 - cx2) < 5: diag_xoffset = -(4 + htwd) show_angle = 0 elif (cx1 < cx2): diag_xoffset = -(4 + htwd) yplumb_xoffset = 4 else: diag_xoffset = 4 yplumb_xoffset = -(4 + ytwd) xh = min(cx1, cx2); y = cy1 + xplumb_yoffset xh += (max(cx1, cx2) - xh) // 2 yh = min(cy1, cy2); x = cx2 + yplumb_xoffset yh += (max(cy1, cy2) - yh) // 2 xd = xh + diag_xoffset yd = yh + diag_yoffset cr.move_to(xd, yd) cr.show_text(self.text_h) if self.color2: self.set_color(cr, self.color2) # draw X plumb line cr.move_to(cx1, cy1) cr.line_to(cx2, cy1) cr.stroke() # draw Y plumb line cr.move_to(cx2, cy1) cr.line_to(cx2, cy2) cr.stroke() # draw X plum line label xh -= xtwd // 2 cr.move_to(xh, y) cr.show_text(self.text_x) # draw Y plum line label cr.move_to(x, yh) cr.show_text(self.text_y) if self.cap: self.draw_caps(cr, self.cap, ((cx2, cy1), )) drawCatalog = { 'rectangle': Rectangle, 'circle': Circle, 'line': Line, 'point': Point, 'ruler': Ruler, 'triangle': Triangle, } class DrawingCanvas(DrawingMixin, CanvasMixin, CompoundMixin, CanvasObject, Mixins.UIMixin, Callback.Callbacks): def __init__(self): CanvasObject.__init__(self) CompoundMixin.__init__(self) CanvasMixin.__init__(self) Callback.Callbacks.__init__(self) Mixins.UIMixin.__init__(self) DrawingMixin.__init__(self, drawCatalog) self.kind = 'drawingcanvas' #END
"""Contains AssetManager, AssetLoader, and Asset parent classes""" # assets.py # Mission Pinball Framework # Written by Brian Madden & Gabe Knuth # Released under the MIT License. (See license info at the end of this file.) # Documentation and more info at http://missionpinball.com/mpf import logging import os import threading import copy from Queue import PriorityQueue import sys import traceback from mpf.system.config import CaseInsensitiveDict class AssetManager(object): """Base class for an Asset Manager. Args: machine: The main ``MachineController`` object. config_section: String of the name of the section in the config file for the asset settings that this Asset Manager will machine. e.g. 'image'. path_string: The setting in the paths section of the config file that specifies what path these asset files are in. e.g. 'images'. asset_class: A class object of the base class for the assets that this Asset Manager will manage. e.g. Image. asset_attribute: The string name that you want to refer to this asset collection as. e.g. a value of 'images' means that assets will be accessible via ``self.machine.images``. file_extensions: A tuple of strings of valid file extensions that files for this asset will use. e.g. ``('png', 'jpg', 'jpeg', 'bmp')`` There will be one Asset Manager for each different type of asset. (e.g. one for images, one for movies, one for sounds, etc.) """ def __init__(self, machine, config_section, path_string, asset_class, asset_attribute, file_extensions): self.log = logging.getLogger(config_section + ' Asset Manager') self.log.info("Initializing...") self.machine = machine self.max_memory = None self.registered_assets = set() self.path_string = path_string self.config_section = config_section self.asset_class = asset_class self.file_extensions = file_extensions self.loader_queue = PriorityQueue() self.loader_thread = None self.machine.asset_managers[config_section] = self if not hasattr(self.machine, asset_attribute): setattr(self.machine, asset_attribute, CaseInsensitiveDict()) self.asset_list = getattr(self.machine, asset_attribute) self.create_loader_thread() self.machine.modes.register_load_method(self.load_assets, self.config_section, load_key='preload') self.machine.modes.register_start_method(self.load_assets, self.config_section, load_key='mode_start') # register & load systemwide assets self.machine.events.add_handler('init_phase_4', self.register_and_load_machine_assets) self.defaults = self.setup_defaults(self.machine.config) def process_assets_from_disk(self, config, path=None): """Looks at a path and finds all the assets in the folder. Looks in a subfolder based on the asset's path string. Crawls subfolders too. The first subfolder it finds is used for the asset's default config section. If an asset has a related entry in the config file, it will create the asset with that config. Otherwise it uses the default Args: config: A dictionary which contains a list of asset names with settings that will be used for the specific asset. (Note this is not needed for all assets, as any asset file found not in the config dictionary will be set up with the folder it was found in's assetdefaults settings.) path: A full system path to the root folder that will be searched for assetsk. This should *not* include the asset-specific path string. If omitted, only the machine's root folder will be searched. """ if not path: path = self.machine.machine_path if not config: config = dict() root_path = os.path.join(path, self.path_string) self.log.info("Processing assets from base folder: %s", root_path) for path, _, files in os.walk(root_path, followlinks=True): valid_files = [f for f in files if f.endswith(self.file_extensions)] for file_name in valid_files: folder = os.path.basename(path) name = os.path.splitext(file_name)[0].lower() full_file_path = os.path.join(path, file_name) if folder == self.path_string or folder not in self.defaults: default_string = 'default' else: default_string = folder #print "------" #print "path:", path #print "full_path", full_file_path #print "file:", file_name #print "name:", name #print "folder:", folder #print "default settings name:", default_string #print "default settings:", self.defaults[default_string] built_up_config = copy.deepcopy(self.defaults[default_string]) for k, v in config.iteritems(): if ('file' in v and v['file'] == file_name) or name == k: if name != k: name = k #print "NEW NAME:", name built_up_config.update(config[k]) break built_up_config['file'] = full_file_path config[name] = built_up_config self.log.debug("Registering Asset: %s, File: %s, Default Group:" " %s, Final Config: %s", name, file_name, default_string, built_up_config) return config def register_and_load_machine_assets(self): """Called on MPF boot to register any assets found in the machine-wide configuration files. (i.e. any assets not specified in mode config files.) If an asset is set with the load type of 'preload', this method will also load the asset file into memory. """ self.log.debug("Registering machine-wide %s", self.config_section) if self.config_section in self.machine.config: config = self.machine.config[self.config_section] else: config = None self.machine.config[self.config_section] = self.register_assets( config=config) self.log.debug("Loading machine-wide 'preload' %s", self.config_section) # Load preload systemwide assets self.load_assets(self.machine.config[self.config_section], load_key='preload') def setup_defaults(self, config): """Processed the ``assetdefaults`` section of the machine config files. """ default_config_dict = dict() if 'assetdefaults' in config and config['assetdefaults']: if (self.config_section in config['assetdefaults'] and config['assetdefaults'][self.config_section]): this_config = config['assetdefaults'][self.config_section] # set the default default_config_dict['default'] = this_config.pop('default') for default_section_name in this_config: # first get a copy of the default for this section default_config_dict[default_section_name] = ( copy.deepcopy(default_config_dict['default'])) # then merge in this section's specific settings default_config_dict[default_section_name].update( this_config[default_section_name]) return default_config_dict def create_loader_thread(self): """Creates a loader thread which will handle the actual reading from disk and loading into memory for assets of this class. Note that one loader thread is created for each class of assets used in your game. Note that this asset loader as a separate *thread*, not a separate *process*. It will run on the same core as your main MPF Python instance. Note that it's possible to call this method multiple times to create multiple loader threads, but that will not make things load any faster since this process is limited by CPU and disk I/O. In fact if it's a magnetic disk, think multiple threads would make it slower. """ self.loader_thread = AssetLoader(name=self.config_section, queue=self.loader_queue, machine=self.machine) self.loader_thread.daemon = True self.loader_thread.start() def register_assets(self, config, mode_path=None): """Scans a config dictionary and registers any asset entries it finds. Args: config: A dictionary of asset entries. This dictionary needs to be "localized" to just the section for this particular asset type. e.g. if you're loading "Images" the keys of this dictionary should be image_1, image_2, etc., not "Images". mode_path: The full path to the base folder that will be seaerched for the asset file on disk. This folder should *not* include the asset-specific folder. If omitted, the base machine folder will be searched. Note that this method merely registers the assets so they can be referenced in MPF. It does not actually load the asset files into memory. """ # config here is already localized config = self.process_assets_from_disk(config=config, path=mode_path) for asset in config: if not os.path.isfile(config[asset]['file']): config[asset]['file'] = self.locate_asset_file( file_name=config[asset]['file'], path=mode_path) self.register_asset(asset=asset.lower(), config=config[asset]) return config def load_assets(self, config, mode=None, load_key=None, callback=None, **kwargs): """Loads the assets from a config dictionary. Args: config: Dictionary that holds the assets to load. mode: Not used. Included here since this method is registered as a mode start handler. load_key: String name of the load key which specifies which assets should be loaded. callback: Callback method which is called by each asset once it's loaded. **kwargs: Not used. Included to allow this method to be used as an event handler. The assets must already be registered in order for this method to work. """ # actually loads assets from a config file. Assumes that they've # aleady been registered. asset_set = set() for asset in config: if self.asset_list[asset].config['load'] == load_key: self.asset_list[asset].load(callback=callback) asset_set.add(self.asset_list[asset]) return self.unload_assets, asset_set def register_asset(self, asset, config): """Registers an asset with the Asset Manager. Args: asset: String name of the asset to register. config: Dictionary which contains settings for this asset. Registering an asset is what makes it available to be used in the game. Note that registering an asset is separate from loading an asset. All assets will be registered on MPF boot, but they can be loaded and unloaded as needed to save on memory. """ #file_name = self.locate_asset_file(config['file'], path) # ## get the defaults based on the path name #this_config = copy.deepcopy(self.defaults[default_config_name]) #this_config.update(config) self.asset_list[asset] = self.asset_class(self.machine, config, config['file'], self) def unload_assets(self, asset_set): """Unloads assets from memory. Args: asset_set: A set (or any iterable) of Asset objects which will be unloaded. Unloading an asset does not de-register it. It's still available to be used, but it's just unloaded from memory to save on memory. """ for asset in asset_set: self.log.debug("Unloading asset: %s", asset.file_name) asset.unload() def load_asset(self, asset, callback, priority=10): """Loads an asset into memory. Args: asset: The Asset object to load. callback: The callback that will be called once the asset has been loaded by the loader thread. priority: The relative loading priority of the asset. If there's a queue of assets waiting to be loaded, this load request will be inserted into the queue in a position based on its priority. """ self.loader_queue.put((-priority, asset, callback)) # priority above is negative so this becomes a LIFO queue self.log.debug("Adding %s to loader queue at priority %s. New queue " "size: %s", asset, priority, self.loader_queue.qsize()) self.machine.num_assets_to_load += 1 def locate_asset_file(self, file_name, path=None): """Takes a file name and a root path and returns a link to the absolute path of the file Args: file_name: String of the file name path: root of the path to check (without the specific asset path string) Returns: String of the full path (path + file name) of the asset. Note this method will add the path string between the path you pass and the file. Also if it can't find the file in the path you pass, it will look for the file in the machine root plus the path string location. """ if path: path_list = [path] else: path_list = list() path_list.append(self.machine.machine_path) for path in path_list: full_path = os.path.join(path, self.path_string, file_name) if os.path.isfile(full_path): return full_path self.log.critical("Could not locate asset file '%s'. Quitting...", file_name) raise Exception() class AssetLoader(threading.Thread): """Base class for the Asset Loader with runs as a separate thread and actually loads the assets from disk. Args: name: String name of what this loader will be called. (Only really used to give a friendly name to it in logs.) queue: A reference to the asset loader ``Queue`` which holds assets waiting to be loaded. machine: The main ``MachineController`` object. """ def __init__(self, name, queue, machine): threading.Thread.__init__(self) self.log = logging.getLogger(name + ' Asset Loader') self.queue = queue self.machine = machine def run(self): """Run loop for the loader thread.""" try: while True: asset = self.queue.get() if not asset[1].loaded: self.log.debug("Loading Asset: %s. Callback: %s", asset[1], asset[2]) asset[1]._load(asset[2]) self.log.debug("Asset Finished Loading: %s. Remaining: %s", asset[1], self.queue.qsize()) # If the asset is already loaded and we don't need to load it # again, we still need to call the callback. elif asset[2]: self.log.debug("Calling callback for asset %s since it's " "already loaded. Callback: %s", asset[1], asset[2]) asset[2]() self.machine.num_assets_to_load -= 1 # If the asset is already loaded, just ignore it and move on. # I thought about trying to make sure that an asset isn't # in the queue before it gets added. But since this is separate # threads that would require all sorts of work. It's actually # more efficient to add it to the queue anyway and then just # skip it if it's already loaded by the time the loader gets to # it. except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) msg = ''.join(line for line in lines) self.machine.crash_queue.put(msg) class Asset(object): def __init__(self, machine, config, file_name, asset_manager): self.machine = machine self.config = config self.file_name = file_name self.asset_manager = asset_manager self.loaded = False self._initialize_asset() def __str__(self): if self.file_name: return self.file_name else: return "Dynamically created show" # todo change this? def load(self, callback=None): self.asset_manager.load_asset(self, callback) def unload(self): self._unload() self.loaded = False # todo also check the loader queue to remove this asset from there # The MIT License (MIT) # Copyright (c) 2013-2015 Brian Madden and Gabe Knuth # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE.
import glob import sys import os import sphinx_bootstrap_theme import skbio # NOTE: parts of this file were taken from scipy's doc/source/conf.py. See # scikit-bio/licenses/scipy.txt for scipy's license. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../sphinxext/numpydoc')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = '1.1' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.mathjax', 'numpydoc', 'sphinx.ext.coverage', 'sphinx.ext.doctest', 'sphinx.ext.autosummary', 'sphinx.ext.intersphinx' ] # Determine if the matplotlib has a recent enough version of the # plot_directive. try: from matplotlib.sphinxext import plot_directive except ImportError: use_matplotlib_plot_directive = False else: try: use_matplotlib_plot_directive = (plot_directive.__version__ >= 2) except AttributeError: use_matplotlib_plot_directive = False if use_matplotlib_plot_directive: extensions.append('matplotlib.sphinxext.plot_directive') else: raise RuntimeError("You need a recent enough version of matplotlib") # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'scikit-bio' copyright = u'2014--, scikit-bio development team' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = skbio.__version__ # The full version, including alpha/beta/rc tags. release = skbio.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # Exclude this file since it is only used by autosummary to generate other RST # files during the build process, and it will generate sphinx errors and # warnings otherwise. exclude_patterns = ['_templates/autosummary/*.rst'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'bootstrap' html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { # Navigation bar title. (Default: ``project`` value) 'navbar_title': 'scikit-bio docs', # Render the next and previous page links in navbar. (Default: true) 'navbar_sidebarrel': False, # Bootswatch (http://bootswatch.com/) theme. # # Options are nothing with "" (default) or the name of a valid theme # such as "amelia" or "cosmo". 'bootswatch_theme': 'united', # Location of link to source. # Options are "nav" (default), "footer" or anything else to exclude. 'source_link_position': False } # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static/'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'scikit-biodoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'scikit-bio.tex', u'scikit-bio Documentation', u'scikit-bio development team', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'scikit-bio', u'scikit-bio Documentation', [u'scikit-bio development team'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'scikit-bio', u'scikit-bio Documentation', u'scikit-bio development team', 'scikit-bio', 'Core objects, functions and statistics for working with biological data ' 'in Python.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # -- Options for autosummary ---------------------------------------------- autosummary_generate = glob.glob('*.rst') # -- Options for numpydoc ------------------------------------------------- # Generate plots for example sections numpydoc_use_plots = True #------------------------------------------------------------------------------ # Plot #------------------------------------------------------------------------------ plot_pre_code = """ import numpy as np import scipy as sp np.random.seed(123) """ plot_include_source = True #plot_formats = [('png', 96), 'pdf'] #plot_html_show_formats = False import math phi = (math.sqrt(5) + 1)/2 font_size = 13*72/96.0 # 13 px plot_rcparams = { 'font.size': font_size, 'axes.titlesize': font_size, 'axes.labelsize': font_size, 'xtick.labelsize': font_size, 'ytick.labelsize': font_size, 'legend.fontsize': font_size, 'figure.figsize': (3*phi, 3), 'figure.subplot.bottom': 0.2, 'figure.subplot.left': 0.2, 'figure.subplot.right': 0.9, 'figure.subplot.top': 0.85, 'figure.subplot.wspace': 0.4, 'text.usetex': False, } if not use_matplotlib_plot_directive: import matplotlib matplotlib.rcParams.update(plot_rcparams) # ----------------------------------------------------------------------------- # Intersphinx configuration # ----------------------------------------------------------------------------- intersphinx_mapping = { 'http://docs.python.org/dev': None, 'http://docs.scipy.org/doc/numpy': None, 'http://docs.scipy.org/doc/scipy/reference': None, 'http://matplotlib.org': None, 'http://pandas.pydata.org': None, 'http://www.biom-format.org':None } # ----------------------------------------------------------------------------- # Source code links # ----------------------------------------------------------------------------- import inspect from os.path import relpath, dirname for name in ['sphinx.ext.linkcode', 'linkcode', 'numpydoc.linkcode']: try: __import__(name) extensions.append(name) break except ImportError: pass else: print "NOTE: linkcode extension not found -- no links to source generated" def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.split('.'): try: obj = getattr(obj, part) except: return None try: fn = inspect.getsourcefile(obj) except: fn = None if not fn: try: fn = inspect.getsourcefile(sys.modules[obj.__module__]) except: fn = None if not fn: return None try: source, lineno = inspect.findsource(obj) except: lineno = None if lineno: linespec = "#L%d" % (lineno + 1) else: linespec = "" fn = relpath(fn, start=dirname(skbio.__file__)) if 'dev' in skbio.__version__: return "http://github.com/biocore/scikit-bio/blob/master/skbio/%s%s" % ( fn, linespec) else: return "http://github.com/biocore/scikit-bio/blob/%s/skbio/%s%s" % ( skbio.__version__, fn, linespec) #------------------------------------------------------------------------------ # linkcheck #------------------------------------------------------------------------------ # Link-checking on Travis sometimes times out. linkcheck_timeout = 30 # Add the 'copybutton' javascript, to hide/show the prompt in code # examples, originally taken from scikit-learn's doc/conf.py def setup(app): app.add_javascript('copybutton.js') app.add_stylesheet('style.css')
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock import webob from nova.api.openstack import api_version_request from nova.api.openstack.compute import remote_consoles \ as console_v21 from nova.compute import api as compute_api from nova import exception from nova import test from nova.tests.unit.api.openstack import fakes def fake_get_vnc_console(self, _context, _instance, _console_type): return {'url': 'http://fake'} def fake_get_spice_console(self, _context, _instance, _console_type): return {'url': 'http://fake'} def fake_get_rdp_console(self, _context, _instance, _console_type): return {'url': 'http://fake'} def fake_get_serial_console(self, _context, _instance, _console_type): return {'url': 'ws://fake'} def fake_get_vnc_console_invalid_type(self, _context, _instance, _console_type): raise exception.ConsoleTypeInvalid(console_type=_console_type) def fake_get_spice_console_invalid_type(self, _context, _instance, _console_type): raise exception.ConsoleTypeInvalid(console_type=_console_type) def fake_get_rdp_console_invalid_type(self, _context, _instance, _console_type): raise exception.ConsoleTypeInvalid(console_type=_console_type) def fake_get_vnc_console_type_unavailable(self, _context, _instance, _console_type): raise exception.ConsoleTypeUnavailable(console_type=_console_type) def fake_get_spice_console_type_unavailable(self, _context, _instance, _console_type): raise exception.ConsoleTypeUnavailable(console_type=_console_type) def fake_get_rdp_console_type_unavailable(self, _context, _instance, _console_type): raise exception.ConsoleTypeUnavailable(console_type=_console_type) def fake_get_vnc_console_not_ready(self, _context, instance, _console_type): raise exception.InstanceNotReady(instance_id=instance["uuid"]) def fake_get_spice_console_not_ready(self, _context, instance, _console_type): raise exception.InstanceNotReady(instance_id=instance["uuid"]) def fake_get_rdp_console_not_ready(self, _context, instance, _console_type): raise exception.InstanceNotReady(instance_id=instance["uuid"]) def fake_get_vnc_console_not_found(self, _context, instance, _console_type): raise exception.InstanceNotFound(instance_id=instance["uuid"]) def fake_get_spice_console_not_found(self, _context, instance, _console_type): raise exception.InstanceNotFound(instance_id=instance["uuid"]) def fake_get_rdp_console_not_found(self, _context, instance, _console_type): raise exception.InstanceNotFound(instance_id=instance["uuid"]) def fake_get(self, context, instance_uuid, want_objects=False, expected_attrs=None): return {'uuid': instance_uuid} def fake_get_not_found(self, context, instance_uuid, want_objects=False, expected_attrs=None): raise exception.InstanceNotFound(instance_id=instance_uuid) class ConsolesExtensionTestV21(test.NoDBTestCase): controller_class = console_v21.RemoteConsolesController validation_error = exception.ValidationError def setUp(self): super(ConsolesExtensionTestV21, self).setUp() self.stubs.Set(compute_api.API, 'get_vnc_console', fake_get_vnc_console) self.stubs.Set(compute_api.API, 'get_spice_console', fake_get_spice_console) self.stubs.Set(compute_api.API, 'get_rdp_console', fake_get_rdp_console) self.stubs.Set(compute_api.API, 'get_serial_console', fake_get_serial_console) self.stubs.Set(compute_api.API, 'get', fake_get) self.controller = self.controller_class() def _check_console_failure(self, func, exception, body): req = fakes.HTTPRequest.blank('') self.assertRaises(exception, eval(func), req, fakes.FAKE_UUID, body=body) def test_get_vnc_console(self): body = {'os-getVNCConsole': {'type': 'novnc'}} req = fakes.HTTPRequest.blank('') output = self.controller.get_vnc_console(req, fakes.FAKE_UUID, body=body) self.assertEqual(output, {u'console': {u'url': u'http://fake', u'type': u'novnc'}}) def test_get_vnc_console_not_ready(self): self.stubs.Set(compute_api.API, 'get_vnc_console', fake_get_vnc_console_not_ready) body = {'os-getVNCConsole': {'type': 'novnc'}} self._check_console_failure('self.controller.get_vnc_console', webob.exc.HTTPConflict, body) def test_get_vnc_console_no_type(self): self.stubs.Set(compute_api.API, 'get_vnc_console', fake_get_vnc_console_invalid_type) body = {'os-getVNCConsole': {}} self._check_console_failure('self.controller.get_vnc_console', self.validation_error, body) def test_get_vnc_console_no_instance(self): self.stubs.Set(compute_api.API, 'get', fake_get_not_found) body = {'os-getVNCConsole': {'type': 'novnc'}} self._check_console_failure('self.controller.get_vnc_console', webob.exc.HTTPNotFound, body) def test_get_vnc_console_no_instance_on_console_get(self): self.stubs.Set(compute_api.API, 'get_vnc_console', fake_get_vnc_console_not_found) body = {'os-getVNCConsole': {'type': 'novnc'}} self._check_console_failure('self.controller.get_vnc_console', webob.exc.HTTPNotFound, body) def test_get_vnc_console_invalid_type(self): body = {'os-getVNCConsole': {'type': 'invalid'}} self.stubs.Set(compute_api.API, 'get_vnc_console', fake_get_vnc_console_invalid_type) self._check_console_failure('self.controller.get_vnc_console', self.validation_error, body) def test_get_vnc_console_type_unavailable(self): body = {'os-getVNCConsole': {'type': 'unavailable'}} self.stubs.Set(compute_api.API, 'get_vnc_console', fake_get_vnc_console_type_unavailable) self._check_console_failure('self.controller.get_vnc_console', self.validation_error, body) def test_get_vnc_console_not_implemented(self): self.stubs.Set(compute_api.API, 'get_vnc_console', fakes.fake_not_implemented) body = {'os-getVNCConsole': {'type': 'novnc'}} self._check_console_failure('self.controller.get_vnc_console', webob.exc.HTTPNotImplemented, body) def test_get_spice_console(self): body = {'os-getSPICEConsole': {'type': 'spice-html5'}} req = fakes.HTTPRequest.blank('') output = self.controller.get_spice_console(req, fakes.FAKE_UUID, body=body) self.assertEqual(output, {u'console': {u'url': u'http://fake', u'type': u'spice-html5'}}) def test_get_spice_console_not_ready(self): self.stubs.Set(compute_api.API, 'get_spice_console', fake_get_spice_console_not_ready) body = {'os-getSPICEConsole': {'type': 'spice-html5'}} self._check_console_failure('self.controller.get_spice_console', webob.exc.HTTPConflict, body) def test_get_spice_console_no_type(self): self.stubs.Set(compute_api.API, 'get_spice_console', fake_get_spice_console_invalid_type) body = {'os-getSPICEConsole': {}} self._check_console_failure('self.controller.get_spice_console', self.validation_error, body) def test_get_spice_console_no_instance(self): self.stubs.Set(compute_api.API, 'get', fake_get_not_found) body = {'os-getSPICEConsole': {'type': 'spice-html5'}} self._check_console_failure('self.controller.get_spice_console', webob.exc.HTTPNotFound, body) def test_get_spice_console_no_instance_on_console_get(self): self.stubs.Set(compute_api.API, 'get_spice_console', fake_get_spice_console_not_found) body = {'os-getSPICEConsole': {'type': 'spice-html5'}} self._check_console_failure('self.controller.get_spice_console', webob.exc.HTTPNotFound, body) def test_get_spice_console_invalid_type(self): body = {'os-getSPICEConsole': {'type': 'invalid'}} self.stubs.Set(compute_api.API, 'get_spice_console', fake_get_spice_console_invalid_type) self._check_console_failure('self.controller.get_spice_console', self.validation_error, body) def test_get_spice_console_not_implemented(self): body = {'os-getSPICEConsole': {'type': 'spice-html5'}} self.stubs.Set(compute_api.API, 'get_spice_console', fakes.fake_not_implemented) self._check_console_failure('self.controller.get_spice_console', webob.exc.HTTPNotImplemented, body) def test_get_spice_console_type_unavailable(self): body = {'os-getSPICEConsole': {'type': 'unavailable'}} self.stubs.Set(compute_api.API, 'get_spice_console', fake_get_spice_console_type_unavailable) self._check_console_failure('self.controller.get_spice_console', self.validation_error, body) def test_get_rdp_console(self): body = {'os-getRDPConsole': {'type': 'rdp-html5'}} req = fakes.HTTPRequest.blank('') output = self.controller.get_rdp_console(req, fakes.FAKE_UUID, body=body) self.assertEqual(output, {u'console': {u'url': u'http://fake', u'type': u'rdp-html5'}}) def test_get_rdp_console_not_ready(self): self.stubs.Set(compute_api.API, 'get_rdp_console', fake_get_rdp_console_not_ready) body = {'os-getRDPConsole': {'type': 'rdp-html5'}} self._check_console_failure('self.controller.get_rdp_console', webob.exc.HTTPConflict, body) def test_get_rdp_console_no_type(self): self.stubs.Set(compute_api.API, 'get_rdp_console', fake_get_rdp_console_invalid_type) body = {'os-getRDPConsole': {}} self._check_console_failure('self.controller.get_rdp_console', self.validation_error, body) def test_get_rdp_console_no_instance(self): self.stubs.Set(compute_api.API, 'get', fake_get_not_found) body = {'os-getRDPConsole': {'type': 'rdp-html5'}} self._check_console_failure('self.controller.get_rdp_console', webob.exc.HTTPNotFound, body) def test_get_rdp_console_no_instance_on_console_get(self): self.stubs.Set(compute_api.API, 'get_rdp_console', fake_get_rdp_console_not_found) body = {'os-getRDPConsole': {'type': 'rdp-html5'}} self._check_console_failure('self.controller.get_rdp_console', webob.exc.HTTPNotFound, body) def test_get_rdp_console_invalid_type(self): body = {'os-getRDPConsole': {'type': 'invalid'}} self.stubs.Set(compute_api.API, 'get_rdp_console', fake_get_rdp_console_invalid_type) self._check_console_failure('self.controller.get_rdp_console', self.validation_error, body) def test_get_rdp_console_type_unavailable(self): body = {'os-getRDPConsole': {'type': 'unavailable'}} self.stubs.Set(compute_api.API, 'get_rdp_console', fake_get_rdp_console_type_unavailable) self._check_console_failure('self.controller.get_rdp_console', self.validation_error, body) def test_get_vnc_console_with_undefined_param(self): body = {'os-getVNCConsole': {'type': 'novnc', 'undefined': 'foo'}} self._check_console_failure('self.controller.get_vnc_console', self.validation_error, body) def test_get_spice_console_with_undefined_param(self): body = {'os-getSPICEConsole': {'type': 'spice-html5', 'undefined': 'foo'}} self._check_console_failure('self.controller.get_spice_console', self.validation_error, body) def test_get_rdp_console_with_undefined_param(self): body = {'os-getRDPConsole': {'type': 'rdp-html5', 'undefined': 'foo'}} self._check_console_failure('self.controller.get_rdp_console', self.validation_error, body) def test_get_serial_console(self): body = {'os-getSerialConsole': {'type': 'serial'}} req = fakes.HTTPRequest.blank('') output = self.controller.get_serial_console(req, fakes.FAKE_UUID, body=body) self.assertEqual({u'console': {u'url': u'ws://fake', u'type': u'serial'}}, output) @mock.patch.object(compute_api.API, 'get_serial_console') def test_get_serial_console_not_enable(self, get_serial_console): get_serial_console.side_effect = exception.ConsoleTypeUnavailable( console_type="serial") body = {'os-getSerialConsole': {'type': 'serial'}} self._check_console_failure('self.controller.get_serial_console', webob.exc.HTTPBadRequest, body) self.assertTrue(get_serial_console.called) @mock.patch.object(compute_api.API, 'get_serial_console') def test_get_serial_console_invalid_type(self, get_serial_console): get_serial_console.side_effect = ( exception.ConsoleTypeInvalid(console_type='invalid')) body = {'os-getSerialConsole': {'type': 'invalid'}} self._check_console_failure('self.controller.get_serial_console', self.validation_error, body) @mock.patch.object(compute_api.API, 'get_serial_console') def test_get_serial_console_no_type(self, get_serial_console): get_serial_console.side_effect = ( exception.ConsoleTypeInvalid(console_type='')) body = {'os-getSerialConsole': {}} self._check_console_failure('self.controller.get_serial_console', self.validation_error, body) @mock.patch.object(compute_api.API, 'get_serial_console') def test_get_serial_console_no_instance(self, get_serial_console): get_serial_console.side_effect = ( exception.InstanceNotFound(instance_id='xxx')) body = {'os-getSerialConsole': {'type': 'serial'}} self._check_console_failure('self.controller.get_serial_console', webob.exc.HTTPNotFound, body) self.assertTrue(get_serial_console.called) @mock.patch.object(compute_api.API, 'get_serial_console') def test_get_serial_console_instance_not_ready(self, get_serial_console): get_serial_console.side_effect = ( exception.InstanceNotReady(instance_id='xxx')) body = {'os-getSerialConsole': {'type': 'serial'}} self._check_console_failure('self.controller.get_serial_console', webob.exc.HTTPConflict, body) self.assertTrue(get_serial_console.called) @mock.patch.object(compute_api.API, 'get_serial_console') def test_get_serial_console_socket_exhausted(self, get_serial_console): get_serial_console.side_effect = ( exception.SocketPortRangeExhaustedException( host='127.0.0.1')) body = {'os-getSerialConsole': {'type': 'serial'}} self._check_console_failure('self.controller.get_serial_console', webob.exc.HTTPBadRequest, body) self.assertTrue(get_serial_console.called) @mock.patch.object(compute_api.API, 'get_serial_console') def test_get_serial_console_image_nport_invalid(self, get_serial_console): get_serial_console.side_effect = ( exception.ImageSerialPortNumberInvalid( num_ports='x', property="hw_serial_port_count")) body = {'os-getSerialConsole': {'type': 'serial'}} self._check_console_failure('self.controller.get_serial_console', webob.exc.HTTPBadRequest, body) self.assertTrue(get_serial_console.called) @mock.patch.object(compute_api.API, 'get_serial_console') def test_get_serial_console_image_nport_exceed(self, get_serial_console): get_serial_console.side_effect = ( exception.ImageSerialPortNumberExceedFlavorValue()) body = {'os-getSerialConsole': {'type': 'serial'}} self._check_console_failure('self.controller.get_serial_console', webob.exc.HTTPBadRequest, body) self.assertTrue(get_serial_console.called) class ConsolesExtensionTestV26(test.NoDBTestCase): def setUp(self): super(ConsolesExtensionTestV26, self).setUp() self.req = fakes.HTTPRequest.blank('') self.context = self.req.environ['nova.context'] self.req.api_version_request = api_version_request.APIVersionRequest( '2.6') self.controller = console_v21.RemoteConsolesController() @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_vnc_console(self, mock_get): mock_handler = mock.MagicMock() mock_handler.return_value = {'url': "http://fake"} self.controller.handlers['vnc'] = mock_handler body = {'remote_console': {'protocol': 'vnc', 'type': 'novnc'}} output = self.controller.create(self.req, fakes.FAKE_UUID, body=body) self.assertEqual({'remote_console': {'protocol': 'vnc', 'type': 'novnc', 'url': 'http://fake'}}, output) mock_handler.assert_called_once_with(self.context, 'fake_instance', 'novnc') @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_spice_console(self, mock_get): mock_handler = mock.MagicMock() mock_handler.return_value = {'url': "http://fake"} self.controller.handlers['spice'] = mock_handler body = {'remote_console': {'protocol': 'spice', 'type': 'spice-html5'}} output = self.controller.create(self.req, fakes.FAKE_UUID, body=body) self.assertEqual({'remote_console': {'protocol': 'spice', 'type': 'spice-html5', 'url': 'http://fake'}}, output) mock_handler.assert_called_once_with(self.context, 'fake_instance', 'spice-html5') @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_rdp_console(self, mock_get): mock_handler = mock.MagicMock() mock_handler.return_value = {'url': "http://fake"} self.controller.handlers['rdp'] = mock_handler body = {'remote_console': {'protocol': 'rdp', 'type': 'rdp-html5'}} output = self.controller.create(self.req, fakes.FAKE_UUID, body=body) self.assertEqual({'remote_console': {'protocol': 'rdp', 'type': 'rdp-html5', 'url': 'http://fake'}}, output) mock_handler.assert_called_once_with(self.context, 'fake_instance', 'rdp-html5') @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_serial_console(self, mock_get): mock_handler = mock.MagicMock() mock_handler.return_value = {'url': "ws://fake"} self.controller.handlers['serial'] = mock_handler body = {'remote_console': {'protocol': 'serial', 'type': 'serial'}} output = self.controller.create(self.req, fakes.FAKE_UUID, body=body) self.assertEqual({'remote_console': {'protocol': 'serial', 'type': 'serial', 'url': 'ws://fake'}}, output) mock_handler.assert_called_once_with(self.context, 'fake_instance', 'serial') @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_console_instance_not_ready(self, mock_get): mock_handler = mock.MagicMock() mock_handler.side_effect = exception.InstanceNotReady( instance_id='xxx') self.controller.handlers['vnc'] = mock_handler body = {'remote_console': {'protocol': 'vnc', 'type': 'novnc'}} self.assertRaises(webob.exc.HTTPConflict, self.controller.create, self.req, fakes.FAKE_UUID, body=body) @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_console_unavailable(self, mock_get): mock_handler = mock.MagicMock() mock_handler.side_effect = exception.ConsoleTypeUnavailable( console_type='vnc') self.controller.handlers['vnc'] = mock_handler body = {'remote_console': {'protocol': 'vnc', 'type': 'novnc'}} self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, self.req, fakes.FAKE_UUID, body=body) self.assertTrue(mock_handler.called) @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_console_not_found(self, mock_get): mock_handler = mock.MagicMock() mock_handler.side_effect = exception.InstanceNotFound( instance_id='xxx') self.controller.handlers['vnc'] = mock_handler body = {'remote_console': {'protocol': 'vnc', 'type': 'novnc'}} self.assertRaises(webob.exc.HTTPNotFound, self.controller.create, self.req, fakes.FAKE_UUID, body=body) @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_console_not_implemented(self, mock_get): mock_handler = mock.MagicMock() mock_handler.side_effect = NotImplementedError() self.controller.handlers['vnc'] = mock_handler body = {'remote_console': {'protocol': 'vnc', 'type': 'novnc'}} self.assertRaises(webob.exc.HTTPNotImplemented, self.controller.create, self.req, fakes.FAKE_UUID, body=body) @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_console_nport_invalid(self, mock_get): mock_handler = mock.MagicMock() mock_handler.side_effect = exception.ImageSerialPortNumberInvalid( num_ports='x', property="hw_serial_port_count") self.controller.handlers['serial'] = mock_handler body = {'remote_console': {'protocol': 'serial', 'type': 'serial'}} self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, self.req, fakes.FAKE_UUID, body=body) @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_console_nport_exceed(self, mock_get): mock_handler = mock.MagicMock() mock_handler.side_effect = ( exception.ImageSerialPortNumberExceedFlavorValue()) self.controller.handlers['serial'] = mock_handler body = {'remote_console': {'protocol': 'serial', 'type': 'serial'}} self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, self.req, fakes.FAKE_UUID, body=body) @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_console_socket_exhausted(self, mock_get): mock_handler = mock.MagicMock() mock_handler.side_effect = ( exception.SocketPortRangeExhaustedException(host='127.0.0.1')) self.controller.handlers['serial'] = mock_handler body = {'remote_console': {'protocol': 'serial', 'type': 'serial'}} self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, self.req, fakes.FAKE_UUID, body=body) @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_console_invalid_type(self, mock_get): mock_handler = mock.MagicMock() mock_handler.side_effect = ( exception.ConsoleTypeInvalid(console_type='invalid_type')) self.controller.handlers['serial'] = mock_handler body = {'remote_console': {'protocol': 'serial', 'type': 'xvpvnc'}} self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, self.req, fakes.FAKE_UUID, body=body) class ConsolesExtensionTestV28(ConsolesExtensionTestV26): def setUp(self): super(ConsolesExtensionTestV28, self).setUp() self.req = fakes.HTTPRequest.blank('') self.context = self.req.environ['nova.context'] self.req.api_version_request = api_version_request.APIVersionRequest( '2.8') self.controller = console_v21.RemoteConsolesController() @mock.patch.object(compute_api.API, 'get', return_value='fake_instance') def test_create_mks_console(self, mock_get): mock_handler = mock.MagicMock() mock_handler.return_value = {'url': "http://fake"} self.controller.handlers['mks'] = mock_handler body = {'remote_console': {'protocol': 'mks', 'type': 'webmks'}} output = self.controller.create(self.req, fakes.FAKE_UUID, body=body) self.assertEqual({'remote_console': {'protocol': 'mks', 'type': 'webmks', 'url': 'http://fake'}}, output) mock_handler.assert_called_once_with(self.context, 'fake_instance', 'webmks') class TestRemoteConsolePolicyEnforcementV21(test.NoDBTestCase): def setUp(self): super(TestRemoteConsolePolicyEnforcementV21, self).setUp() self.controller = console_v21.RemoteConsolesController() self.req = fakes.HTTPRequest.blank('') def _common_policy_check(self, func, *arg, **kwarg): rule_name = "os_compute_api:os-remote-consoles" rule = {rule_name: "project:non_fake"} self.policy.set_rules(rule) exc = self.assertRaises( exception.PolicyNotAuthorized, func, *arg, **kwarg) self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message()) def test_remote_vnc_console_policy_failed(self): body = {'os-getVNCConsole': {'type': 'novnc'}} self._common_policy_check(self.controller.get_vnc_console, self.req, fakes.FAKE_UUID, body=body) def test_remote_splice_console_policy_failed(self): body = {'os-getSPICEConsole': {'type': 'spice-html5'}} self._common_policy_check(self.controller.get_spice_console, self.req, fakes.FAKE_UUID, body=body) def test_remote_rdp_console_policy_failed(self): body = {'os-getRDPConsole': {'type': 'rdp-html5'}} self._common_policy_check(self.controller.get_rdp_console, self.req, fakes.FAKE_UUID, body=body) def test_remote_serial_console_policy_failed(self): body = {'os-getSerialConsole': {'type': 'serial'}} self._common_policy_check(self.controller.get_serial_console, self.req, fakes.FAKE_UUID, body=body)
""" Mike Eller UVML July 2017 """ import os import matplotlib.pyplot as plt import numpy as np import csv from statsmodels.nonparametric.smoothers_lowess import lowess from shutil import copyfile plt.style.use('bmh') # helper function to print polynomial fit def print_polynomial(p): s = '$' for coef in range(0, len(p)): s += str(p[coef]) + '*x^' + str(len(p) - 1 - coef) if coef < len(p) - 1: s += '+' return s + '$' # helper function to convert values in file name format into float values # i.e. convert 'p' to '.' and cast to float def convert_to_float(num): s = "" for x in range(0, len(num)): if num[x] == 'p': s += '.' else: s += num[x] return float(s) # used to set the directory structure # WILL UPDATE to sort any directory with any given amounts of files with varying independent variables def sort_directory(path, power=True): files = os.listdir(path) if power: powers = [] for f in files: if f.endswith(".txt"): sdf = SpectrumDataFile(path + "/" + f) if str(sdf.power) not in powers: powers.append(str(sdf.power)) else: files.remove(f) for p in powers: os.mkdir(path + "/" + p) for f in files: sdf = SpectrumDataFile(path + "/" + f) if str(sdf.power) == p: copyfile(path + "/" + f, path + "/" + p + "/" + f) os.remove(path + "/" + f) # struct to handle units # parameters for data files are stored with value and unit class SpectrumDataParameter(object): def __init__(self, value, units): self.value = value self.units = units def __str__(self): return str(self.value) + " " + self.units """ This class is a representation of one data file. You must pass the path to the data file on creation. Object automatically calculates dissociation using the trapezoid integral method (trapz) from numpy. You can plot the spectrum and save it to a .png file. Params: spacing - width of integration peaks data_range - range of data to plot peaks - where to start integration current - SpectrumDataParameter power - SpectrumDataParameter pressure - SpectrumDataParameter dissociation - float filepath - used to generate filename filename - just the base file name dataname - formatted name of data data_points - all the data parsed from the file (a list of tuples) Methods: parse_spectral_data plot_spectrum save_spectrum_plot get_range calculate_dissociation """ class SpectrumDataFile(object): def __init__(self, filepath, data_range=(740, 765), peaks=(740.5, 752.5), spacing=6.5): if filepath[-4:] != ".txt": raise ValueError("Invalid File Extension") elif not os.path.isfile(filepath): raise IOError("Invalid Path") self._spacing = spacing self._data_range = data_range self._peaks = peaks self.filepath = filepath self.filename = os.path.basename(filepath) self.power = SpectrumDataParameter(convert_to_float(self.filename.split("_")[0].split("W")[0]), "W") self.pressure = SpectrumDataParameter(convert_to_float(self.filename.split("_")[1].split("m")[0]), "mTorr") self.current = SpectrumDataParameter(convert_to_float(self.filename.split("_")[2].split("A")[0]), "A") if len(self.filename.split("_")) > 3: self.time = SpectrumDataParameter(int(self.filename.split("_")[3][:-7]), "min") else: self.time = SpectrumDataParameter('N/A', 'min') self.dataname = str(self.power) + ", " + str(self.pressure) + ", " + str(self.current) + ", " + str(self.time) self.data_points = self.parse_spectral_data() self.dissociation = self.calculate_dissociation() # for readability def __str__(self): return self.dataname def __repr__(self): return self.__str__() # I chose to use properties so that I can recalculate dissociation # when any of these properties are changed @property def data_range(self): return self._data_range @data_range.setter def data_range(self, new_range): self._data_range = new_range self.data_points = self.parse_spectral_data() self.dissociation = self.calculate_dissociation() @property def peaks(self): return self._peaks @peaks.setter def peaks(self, new_peaks): self._peaks = new_peaks self.dissociation = self.calculate_dissociation() @property def spacing(self): return self._spacing @spacing.setter def spacing(self, val): self._spacing = val self.dissociation = self.calculate_dissociation() # this function reads the file and creates a list of points in the format (wavelength, intensity) # list is stored in the 'data_points' parameter # data_range corresponds to the desired wavelengths in the plot def parse_spectral_data(self): data_points = [] with open(self.filepath, 'r') as datafile: # burn the header lines for x in range(0, 17): line = datafile.readline() line = datafile.readline() # for data files with thickness added as the top line if line[0] == ">": line = datafile.readline() if hex(ord(line[0])) == '0xd' and hex(ord(line[1])) == '0xa': return while line: # split the line on tabs and convert to float # adds a tuple (wavelength, intensity) to data_points data_point = (float(line.split("\t")[0]), float(line.split("\t")[1].split("\r")[0])) if self.data_range[0] <= data_point[0] <= self.data_range[1]: data_points.append(data_point) line = datafile.readline() # must break because last line isn't actually data (will throw errors in loop above) if line[0] == ">": break max = np.max([x[1] for x in data_points]) return [(x, y/max) for (x, y) in data_points] """ Plots the data in memory using pyplot Params: ax - axes object you can optionally plot to save - if true the plot will be saved to the current working directory with its dataname filtered - you can optionally plot a filtered version of the data frac - filter parameter fill - if true, the integral regions will be filled in with color """ def plot_spectrum(self, ax=None, save=False, filtered=False, frac=0.025, fill=True): # the axes (ax) param is so that this function can be used within another function # i.e. this can be used to plot to an external figure -- just pass that fig's axes object as ax # when you call this function if ax is None: plt.figure() ax = plt.gca() ax.set_title("Spectrum") ax.set_xlabel("Wavelength (nm)") ax.set_ylabel("Normalized Intensity (AU)") xs = [x[0] for x in self.data_points] ys = [x[1] for x in self.data_points] if not filtered: ax.plot(xs, ys, 'b--', label=self.dataname) # filtered plot could be usefull when plotting the whole spectrum -- pretty noisy else: filtered = lowess(ys, xs, is_sorted=True, frac=frac, it=0) ax.plot(filtered[:, 0], filtered[:, 1], label='filtered data') # fill in the integral regions defined by peaks and spacing if fill: fill_point_1 = self.get_range(self.peaks[0], self.peaks[0] + self.spacing) fill_point_2 = self.get_range(self.peaks[1], self.peaks[1] + self.spacing) fill_xs_1 = [x[0] for x in fill_point_1] fill_ys_1 = [x[1] for x in fill_point_1] fill_xs_2 = [x[0] for x in fill_point_2] fill_ys_2 = [x[1] for x in fill_point_2] ax.fill_between(fill_xs_1, fill_ys_1, color='lightblue', label='Region I') ax.fill_between(fill_xs_2, fill_ys_2, color='orange', label='Region II') ax.set_ylim(ymin=0) ax.margins(0.05) ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) if save: ax.savefig(self.filename[:-4]) # ax is used in the same way as in 'plot_spectrum' def plot_difference(self, ax=None): if ax is None: plt.figure() ax = plt.gca() ax.set_title("Spectrum Shadow") ax.set_xlabel("Wavelength") ax.set_ylabel("Normalized Intensity (AU)") # points_1 contains all the points for the first region points_1 = self.get_range(self.peaks[0], self.peaks[0] + self.spacing) # points_2 -> region 2 points_2 = self.get_range(self.peaks[1], self.peaks[1] + self.spacing) # get the y values from the points ys_1 = [x[1] for x in points_1] ys_2 = [x[1] for x in points_2] # check and make sure the lists have the same length # if they don't, just truncate the end of the longer one diff = np.abs(len(ys_1) - len(ys_2)) if diff < 0: ys_1 = ys_1[:-diff] elif diff > 0: ys_2 = ys_2[:-diff] # build the y values for the difference between the two ys_3 = [] for x in range(0, len(ys_2)): if ys_1[x] - ys_2[x] > 0: ys_3.append(ys_1[x] - ys_2[x]) else: ys_3.append(0) # make a generic x's list xs = np.linspace(0, 1, num=len(ys_1)) ax.plot(xs, ys_1, 'b', label='Region I (' + str(self.peaks[0]) + ' nm - ' + str(self.peaks[0] + self.spacing) + ' nm)') ax.plot(xs, ys_2, 'r', label='Region II (' + str(self.peaks[1]) + ' nm - ' + str(self.peaks[1] + self.spacing) + ' nm)') ax.plot(xs, ys_3, 'm--', label='Difference (No Negatives)') ax.set_ylim(ymin=0) labels = [item.get_text() for item in ax.get_xticklabels()] empty_string_labels = [''] * len(labels) ax.set_xticklabels(empty_string_labels) ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) return plt.gca() # this is a method just to save the figure (will also plot to memory) # can give a custom name for the image # a little redundant but oh well def save_spectrum_plot(self, name=False): plt.figure() plt.title("Spectrum - " + self.dataname) plt.xlabel("Wavelength (nm)") plt.ylabel("Intensity") plt.plot([x[0] for x in self.data_points], [x[1] for x in self.data_points]) if name: plt.savefig(name) else: plt.savefig(self.filename[:-4]) # this is a helper function to get the points within the range given by lower and upper def get_range(self, lower, upper): subset = [] for x in range(0, len(self.data_points)): if lower <= self.data_points[x][0] <= upper: subset.append(self.data_points[x]) return subset # calculates the two integrals of the major peaks, takes the difference, and computes the ratio def calculate_dissociation(self, scaling=0.91, *args, **kwargs): if self.data_points is None: return integral1 = np.trapz([x[1] for x in self.get_range(self.peaks[0], self.peaks[0] + self.spacing)], *args, **kwargs) integral2 = np.trapz([x[1] for x in self.get_range(self.peaks[1], self.peaks[1] + self.spacing)], *args, **kwargs) * scaling return np.abs(integral1 - integral2) / integral2 """ This class is basically a container for multiple SpectrumDataFile objects. It is an extension of the python built-in dictionary - {SpectrumDataFile object: all data points} Automatically reads a directory given by path on creation and creates a SpectrumDataFile object for each file. A plot can then be generated for dissociation vs. current. Files in a single directory should have the same power and pressure. Params: path - directory of .txt spectrum files Methods: compile_dataset plot_dissociation save_dissociation_plot """ class SpectrumDataSet(dict): def __init__(self, pathname, *args, **kw): super(SpectrumDataSet, self).__init__(*args, **kw) self.path = pathname # this function reads a directory of spectrum data text files, populates the dict of this class # and writes a csv file def compile_dataset(self, save=True, fname=None): self.clear() if not os.path.exists(self.path): raise ValueError("Path does not exist.") else: files = os.listdir(self.path) try: os.remove('output.csv') except OSError: pass if not fname: n = 'output.csv' else: n = fname if save: with open(n, "w") as output: # I thought csv's would be better than a text file, but I can change it to whatever # reading and writing csv's is also much nicer writer = csv.DictWriter(output, fieldnames=["Time (min)", "Pressure (mTorr)", "Power (W)", "Current (A)", "Ratio"]) writer.writeheader() for f in files: if f.endswith(".txt"): # create a SpectrumDataFile object with each file sdf = SpectrumDataFile(self.path + "/" + f) # write all the values to the csv file writer.writerow({"Time (min)": sdf.time.value, "Pressure (mTorr)": sdf.pressure.value, "Power (W)": sdf.power.value, "Current (A)": sdf.current.value, "Ratio": sdf.dissociation}) # add the dict entry to the object sdf.data_points = sdf.parse_spectral_data() self[sdf] = sdf.data_points else: for f in files: if f.endswith(".txt"): # create a SpectrumDataFile object with each file sdf = SpectrumDataFile(self.path + "/" + f) # add the dict entry to the object sdf.data_points = sdf.parse_spectral_data() self[sdf] = sdf.data_points """ This function is most useful when used in iPython notebook with sliders. function auto sorts files in dict object based on power - will update eventually to sort by independent variable Params: save - can save plot in current directory ind_var - 'power' | 'current' | 'pressure' spectrum - you can plot the spectrum for a file in the SpectrumDataSet file - index of SpectrumDataSet to plot spectrum shadow - you can plot the shadow of the current file region1 - start of integral 1, if changed it adjusts all files in the data set - and therefore all dissociations region2 - integral 2 spacing - width of integral regions, if changed: changes all files in data set fit - can plot just points and a poly fit degree - the degree of fitting polynomial """ def plot_dissociation(self, ax=None, ind_var='current', spectrum=False, shadow=False, f=-1, region1=740.5, region2=752.5, spacing=6.5, fit=False, degree=5, labeloverride=None, xlim=None, ylim=None, pattern='.-', **kwargs): # get selected spectrum data file sdf = sorted(self.keys(), key=lambda spec: spec.power.value)[f] # change all the files to the specified param values for spec in self.keys(): spec.peaks = (region1, region2) spec.spacing = spacing if ax is None: plt.figure(figsize=(6, 10)) ax3 = plt.subplot(312) if spectrum: ax1 = plt.subplot(311) sdf.plot_spectrum(ax1) if shadow: ax2 = plt.subplot(313) sdf.plot_difference(ax2) else: ax3 = ax ax3.set_title("Relative Dissociation vs " + ind_var.title()) ax3.set_ylabel("Relative Dissociation") if xlim: ax3.set_xlim(xlim) if ylim: ax3.set_ylim(ylim) if ind_var == 'current': ax3.set_xlabel("Current (A)") points = sorted([(x.current.value, x.dissociation) for x in self.keys()]) label = str(self.keys()[0].power) + " " + str(self.keys()[0].pressure) elif ind_var == 'power': ax3.set_xlabel("Power (W)") points = sorted([(x.power.value, x.dissociation) for x in self.keys()]) label = str(self.keys()[0].current) + " " + str(self.keys()[0].pressure) elif ind_var == 'pressure': ax3.set_xlabel("Pressure (mTorr)") points = sorted([(x.pressure.value, x.dissociation) for x in self.keys()]) label = str(self.keys()[0].power) + " " + str(self.keys()[0].current) elif ind_var == 'time': ax3.set_xlabel("Time (min)") points = sorted([(x.time.value, x.dissociation) for x in self.keys()]) label = str(self.keys()[0].power) + " " + str(self.keys()[0].current) else: raise ValueError("Incorrect independent variable name.") xs = [x[0] for x in points] ys = [x[1] for x in points] if labeloverride is not None: label = labeloverride if not fit: ax3.plot(xs, ys, pattern, label=label, **kwargs) else: c = ax3.plot(xs, ys, pattern, label=label, **kwargs) xp = np.linspace(np.min(xs), np.max(xs), 100) p = np.poly1d(np.polyfit(xs, ys, degree)) ax3.plot(xp, p(xp), '-', label='Poly Fit: ' + label, color=c[0].get_color()) ax3.margins(0.05) ax3.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.tight_layout() def errorbar(datasets, ax=None, save=False, ind_var='current', region1=740.5, region2=752.5, spacing=6.5, labeloverride=None, xlim=None, ylim=None, capthick=0, capcolor='black', **kwargs): # change all the files to the specified param values for dataset in datasets: for spec in dataset.keys(): spec.peaks = (region1, region2) spec.spacing = spacing for x in range(1, len(datasets)): if len(datasets[0].keys()) == len(datasets[x].keys()): continue else: raise ValueError("Spectrum Data Set Objects are not the same length.") D = {} for x in range(0, len(datasets)): for y in range(0, len(datasets[x].keys())): if ind_var == 'time': key = datasets[x].keys()[y].time.value elif ind_var == 'current': key = datasets[x].keys()[y].current.value elif ind_var == 'power': key = datasets[x].keys()[y].power.value elif ind_var == 'pressure': key = datasets[x].keys()[y].pressure.value if key not in D.keys(): D[key] = [] D[key].append(datasets[x].keys()[y].dissociation) Davg = D.copy() Dmax = D.copy() Dmin = D.copy() for key in D.keys(): Davg[key] = 0 for x in range(0, len(datasets)): Davg[key] += D[key][x] Davg[key] /= len(datasets) Dmin[key] = min(D[key]) Dmax[key] = max(D[key]) if ax is None: plt.figure(figsize=(10, 6)) ax3 = plt.gca() else: ax3 = ax ax3.set_title("Relative Dissociation vs " + ind_var.title()) ax3.set_ylabel("Relative Dissociation") if xlim: ax3.set_xlim(xlim) if ylim: ax3.set_ylim(ylim) if ind_var == 'current': ax3.set_xlabel("Current (A)") points = sorted([(x.current.value, x.dissociation) for x in datasets[0].keys()]) label = str(datasets[0].keys()[0].power) + " " + str(datasets[0].keys()[0].pressure) elif ind_var == 'power': ax3.set_xlabel("Power (W)") points = sorted([(x.power.value, x.dissociation) for x in datasets[0].keys()]) label = str(datasets[0].keys()[0].current) + " " + str(datasets[0].keys()[0].pressure) elif ind_var == 'pressure': ax3.set_xlabel("Pressure (mTorr)") points = sorted([(x.pressure.value, x.dissociation) for x in datasets[0].keys()]) label = str(datasets[0].keys()[0].power) + " " + str(datasets[0].keys()[0].current) elif ind_var == 'time': ax3.set_xlabel("Time (min)") points = sorted([(x.time.value, x.dissociation) for x in datasets[0].keys()]) label = str(datasets[0].keys()[0].power) + " " + str(datasets[0].keys()[0].current) else: raise ValueError("Incorrect independent variable name.") if labeloverride is not None: label = labeloverride x = [] y = [] yerr_min = [] yerr_max = [] for i in range(0, len(D.keys())): x.append(D.keys()[i]) y.append(Davg[D.keys()[i]]) yerr_min.append(np.abs(Dmin[D.keys()[i]] - Davg[D.keys()[i]])) yerr_max.append(Dmax[D.keys()[i]] - Davg[D.keys()[i]]) (_, caps, _) = ax3.errorbar(x, y, yerr=[yerr_min, yerr_max], label=label, **kwargs) for cap in caps: cap.set_color(capcolor) cap.set_markeredgewidth(capthick) ax3.margins(0.05) ax3.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.tight_layout() return D if __name__ == "__main__": pass
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # coding=utf-8 # Copyright (c) 2011-2013 University of Southern California / ISI # 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 baremetal tilera driver.""" import os from oslo.config import cfg from nova import exception from nova.openstack.common.db import exception as db_exc from nova.tests.image import fake as fake_image from nova.tests import utils from nova.tests.virt.baremetal.db import base as bm_db_base from nova.tests.virt.baremetal.db import utils as bm_db_utils from nova.virt.baremetal import baremetal_states from nova.virt.baremetal import db from nova.virt.baremetal import tilera from nova.virt.baremetal import utils as bm_utils from nova.virt.disk import api as disk_api from nova.virt import fake as fake_virt CONF = cfg.CONF COMMON_FLAGS = dict( firewall_driver='nova.virt.baremetal.fake.FakeFirewallDriver', host='test_host', ) BAREMETAL_FLAGS = dict( driver='nova.virt.baremetal.tilera.Tilera', instance_type_extra_specs=['cpu_arch:test', 'test_spec:test_value'], power_manager='nova.virt.baremetal.fake.FakePowerManager', vif_driver='nova.virt.baremetal.fake.FakeVifDriver', volume_driver='nova.virt.baremetal.fake.FakeVolumeDriver', group='baremetal', ) class BareMetalTileraTestCase(bm_db_base.BMDBTestCase): def setUp(self): super(BareMetalTileraTestCase, self).setUp() self.flags(**COMMON_FLAGS) self.flags(**BAREMETAL_FLAGS) self.driver = tilera.Tilera(fake_virt.FakeVirtAPI()) fake_image.stub_out_image_service(self.stubs) self.addCleanup(fake_image.FakeImageService_reset) self.context = utils.get_test_admin_context() self.test_block_device_info = None, self.instance = utils.get_test_instance() self.test_network_info = utils.get_test_network_info( legacy_model=False), self.node_info = bm_db_utils.new_bm_node( service_host='test_host', cpus=4, memory_mb=2048, ) self.nic_info = [ {'address': '22:22:22:22:22:22', 'datapath_id': '0x1', 'port_no': 1}, {'address': '33:33:33:33:33:33', 'datapath_id': '0x2', 'port_no': 2}, ] def _create_node(self): self.node = db.bm_node_create(self.context, self.node_info) for nic in self.nic_info: db.bm_interface_create( self.context, self.node['id'], nic['address'], nic['datapath_id'], nic['port_no'], ) self.instance['node'] = self.node['id'] self.spawn_params = dict( admin_password='test_pass', block_device_info=self.test_block_device_info, context=self.context, image_meta=utils.get_test_image_info(None, self.instance), injected_files=[('/fake/path', 'hello world')], instance=self.instance, network_info=self.test_network_info, ) class TileraClassMethodsTestCase(BareMetalTileraTestCase): def test_build_network_config(self): net = utils.get_test_network_info(1, legacy_model=False) config = tilera.build_network_config(net) self.assertIn('eth0', config) self.assertNotIn('eth1', config) net = utils.get_test_network_info(2, legacy_model=False) config = tilera.build_network_config(net) self.assertIn('eth0', config) self.assertIn('eth1', config) def test_build_network_config_dhcp(self): self.flags( net_config_template='$pybasedir/nova/virt/baremetal/' 'net-dhcp.ubuntu.template', group='baremetal', ) net = utils.get_test_network_info(legacy_model=False) net[0]['network']['subnets'][0]['ips'][0]['address'] = '1.2.3.4' config = tilera.build_network_config(net) self.assertIn('iface eth0 inet dhcp', config) self.assertNotIn('address 1.2.3.4', config) def test_build_network_config_static(self): self.flags( net_config_template='$pybasedir/nova/virt/baremetal/' 'net-static.ubuntu.template', group='baremetal', ) net = utils.get_test_network_info(legacy_model=False) net[0]['network']['subnets'][0]['ips'][0]['address'] = '1.2.3.4' config = tilera.build_network_config(net) self.assertIn('iface eth0 inet static', config) self.assertIn('address 1.2.3.4', config) def test_image_dir_path(self): self.assertEqual( tilera.get_image_dir_path(self.instance), os.path.join(CONF.instances_path, 'instance-00000001')) def test_image_file_path(self): self.assertEqual( tilera.get_image_file_path(self.instance), os.path.join( CONF.instances_path, 'instance-00000001', 'disk')) def test_tilera_nfs_path(self): self._create_node() self.node['id'] = '123' tilera_nfs_dir = "fs_" + self.node['id'] self.assertEqual( tilera.get_tilera_nfs_path(self.node['id']), os.path.join(CONF.baremetal.tftp_root, tilera_nfs_dir)) def test_get_partition_sizes(self): # default "kinda.big" instance sizes = tilera.get_partition_sizes(self.instance) self.assertEqual(sizes[0], 40960) self.assertEqual(sizes[1], 1024) def test_swap_not_zero(self): # override swap to 0 instance_type = utils.get_test_instance_type(self.context) instance_type['swap'] = 0 self.instance = utils.get_test_instance(self.context, instance_type) sizes = tilera.get_partition_sizes(self.instance) self.assertEqual(sizes[0], 40960) self.assertEqual(sizes[1], 1) def test_get_tftp_image_info(self): # Tilera case needs only kernel_id. self.instance['kernel_id'] = 'aaaa' self.instance['uuid'] = 'fake-uuid' # Here, we confirm both that kernel_id was set # and that the proper paths are getting set for all of them base = os.path.join(CONF.baremetal.tftp_root, self.instance['uuid']) res = tilera.get_tftp_image_info(self.instance) expected = { 'kernel': ['aaaa', os.path.join(base, 'kernel')], } self.assertEqual(res, expected) class TileraPrivateMethodsTestCase(BareMetalTileraTestCase): def test_collect_mac_addresses(self): self._create_node() address_list = [nic['address'] for nic in self.nic_info] address_list.sort() macs = self.driver._collect_mac_addresses(self.context, self.node) self.assertEqual(macs, address_list) def test_cache_tftp_images(self): self.instance['kernel_id'] = 'aaaa' image_info = tilera.get_tftp_image_info(self.instance) self.mox.StubOutWithMock(os, 'makedirs') self.mox.StubOutWithMock(os.path, 'exists') os.makedirs(os.path.join(CONF.baremetal.tftp_root, self.instance['uuid'])).AndReturn(True) for uuid, path in [image_info[label] for label in image_info]: os.path.exists(path).AndReturn(True) self.mox.ReplayAll() self.driver._cache_tftp_images( self.context, self.instance, image_info) self.mox.VerifyAll() def test_cache_image(self): self.mox.StubOutWithMock(os, 'makedirs') self.mox.StubOutWithMock(os.path, 'exists') os.makedirs(tilera.get_image_dir_path(self.instance)).\ AndReturn(True) os.path.exists(tilera.get_image_file_path(self.instance)).\ AndReturn(True) self.mox.ReplayAll() image_meta = utils.get_test_image_info( self.context, self.instance) self.driver._cache_image( self.context, self.instance, image_meta) self.mox.VerifyAll() def test_inject_into_image(self): self._create_node() files = [] self.instance['hostname'] = 'fake hostname' files.append(('/etc/hostname', 'fake hostname')) self.instance['key_data'] = 'fake ssh key' net_info = utils.get_test_network_info(1, legacy_model=False) net = tilera.build_network_config(net_info) admin_password = 'fake password' self.mox.StubOutWithMock(disk_api, 'inject_data') disk_api.inject_data( admin_password=admin_password, image=tilera.get_image_file_path(self.instance), key='fake ssh key', metadata=None, partition=None, net=net, files=files, ).AndReturn(True) self.mox.ReplayAll() self.driver._inject_into_image( self.context, self.node, self.instance, network_info=net_info, admin_password=admin_password, injected_files=None) self.mox.VerifyAll() class TileraPublicMethodsTestCase(BareMetalTileraTestCase): def test_cache_images(self): self._create_node() self.mox.StubOutWithMock(tilera, "get_tftp_image_info") self.mox.StubOutWithMock(self.driver, "_cache_tftp_images") self.mox.StubOutWithMock(self.driver, "_cache_image") self.mox.StubOutWithMock(self.driver, "_inject_into_image") tilera.get_tftp_image_info(self.instance).AndReturn([]) self.driver._cache_tftp_images(self.context, self.instance, []) self.driver._cache_image(self.context, self.instance, []) self.driver._inject_into_image(self.context, self.node, self.instance, self.test_network_info, None, '') self.mox.ReplayAll() self.driver.cache_images( self.context, self.node, self.instance, admin_password='', image_meta=[], injected_files=None, network_info=self.test_network_info, ) self.mox.VerifyAll() def test_destroy_images(self): self._create_node() self.mox.StubOutWithMock(bm_utils, 'unlink_without_raise') self.mox.StubOutWithMock(bm_utils, 'rmtree_without_raise') bm_utils.unlink_without_raise(tilera.get_image_file_path( self.instance)) bm_utils.rmtree_without_raise(tilera.get_image_dir_path(self.instance)) self.mox.ReplayAll() self.driver.destroy_images(self.context, self.node, self.instance) self.mox.VerifyAll() def test_activate_bootloader_passes_details(self): self._create_node() image_info = { 'kernel': [None, 'cccc'], } self.instance['uuid'] = 'fake-uuid' iqn = "iqn-%s" % self.instance['uuid'] tilera_config = 'this is a fake tilera config' self.instance['uuid'] = 'fake-uuid' tilera_path = tilera.get_tilera_nfs_path(self.instance) image_path = tilera.get_image_file_path(self.instance) self.mox.StubOutWithMock(tilera, 'get_tftp_image_info') self.mox.StubOutWithMock(tilera, 'get_partition_sizes') tilera.get_tftp_image_info(self.instance).AndReturn(image_info) tilera.get_partition_sizes(self.instance).AndReturn((0, 0)) self.mox.ReplayAll() self.driver.activate_bootloader(self.context, self.node, self.instance, network_info=self.test_network_info) self.mox.VerifyAll() def test_activate_and_deactivate_bootloader(self): self._create_node() self.instance['uuid'] = 'fake-uuid' tilera_path = tilera.get_tilera_nfs_path(self.instance) image_path = tilera.get_image_file_path(self.instance) self.mox.ReplayAll() # activate and deactivate the bootloader # and check the deployment task_state in the database row = db.bm_node_get(self.context, 1) self.assertTrue(row['deploy_key'] is None) self.driver.activate_bootloader(self.context, self.node, self.instance, network_info=self.test_network_info) row = db.bm_node_get(self.context, 1) self.assertTrue(row['deploy_key'] is not None) self.driver.deactivate_bootloader(self.context, self.node, self.instance) row = db.bm_node_get(self.context, 1) self.assertTrue(row['deploy_key'] is None) self.mox.VerifyAll() def test_deactivate_bootloader_for_nonexistent_instance(self): self._create_node() self.node['id'] = 'fake-node-id' self.mox.StubOutWithMock(bm_utils, 'unlink_without_raise') self.mox.StubOutWithMock(bm_utils, 'rmtree_without_raise') self.mox.StubOutWithMock(tilera, 'get_tftp_image_info') self.mox.StubOutWithMock(self.driver, '_collect_mac_addresses') tilera_path = tilera.get_tilera_nfs_path(self.node['id']) tilera.get_tftp_image_info(self.instance).\ AndRaise(exception.NovaException) self.driver._collect_mac_addresses(self.context, self.node).\ AndRaise(db_exc.DBError) self.mox.ReplayAll() self.driver.deactivate_bootloader( self.context, self.node, self.instance) self.mox.VerifyAll() def test_activate_node(self): self._create_node() self.instance['uuid'] = 'fake-uuid' db.bm_node_update(self.context, 1, {'task_state': baremetal_states.DEPLOYING, 'instance_uuid': 'fake-uuid'}) # test DEPLOYDONE db.bm_node_update(self.context, 1, {'task_state': baremetal_states.DEPLOYDONE}) self.driver.activate_node(self.context, self.node, self.instance) # test no deploy -- state is just ACTIVE db.bm_node_update(self.context, 1, {'task_state': baremetal_states.ACTIVE}) self.driver.activate_node(self.context, self.node, self.instance) # test node gone db.bm_node_destroy(self.context, 1) self.assertRaises(exception.InstanceDeployFailure, self.driver.activate_node, self.context, self.node, self.instance)
BASE = 9 BLOCK_HEIGHT = 3 BLOCK_WIDTH = 3 field = [ [1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9, 1, 2, 3], [7, 8, 9, 1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6, 7, 8, 9, 1], [5, 6, 7, 8, 9, 1, 2, 3, 4], [8, 9, 1, 2, 3, 4, 5, 6, 7], [3, 4, 5, 6, 7, 8, 9, 1, 2], [6, 7, 8, 9, 1, 2, 3, 4, 5], [9, 1, 2, 3, 4, 5, 6, 7, 8] ] def precheck(): # Step 0: Pre-solve consistency checks global BASE, BLOCK_HEIGHT, BLOCK_WIDTH, field try: BASE = int(BASE) except Exception as err: err.message = "Failed to convert BASE ({}) to int: ".format(BASE) + err.message raise global BASE_RANGE BASE_RANGE = range(1, BASE+1) try: BLOCK_HEIGHT = int(BLOCK_HEIGHT) except Exception as err: err.message = "Failed to convert BLOCK_HEIGHT ({}) to int: ".format(BLOCK_HEIGHT) + err.message raise try: BLOCK_WIDTH = int(BLOCK_WIDTH) except Exception as err: err.message = "Failed to convert BLOCK_WIDTH ({}) to int: ".format(BLOCK_WIDTH) + err.message raise if BLOCK_HEIGHT * BLOCK_WIDTH != BASE: raise ValueError("Block size ({} by {}) does not match number base ({})".format(BLOCK_WIDTH, BLOCK_HEIGHT, BASE)) try: field = list(field) except Exception as err: err.message = "Failed to convert field ({}) to list: ".format(field) + err.message raise if len(field) != BASE: raise ValueError("Field height ({}) is not equal to number base ({})".format(len(field), BASE)) if len(field) % BLOCK_HEIGHT != 0: raise ValueError("Field height ({}) is not divisible by block height ({})".format(len(field), BLOCK_HEIGHT)) for y, row in enumerate(field): try: field[y] = list(row) except Exception as err: err.message = "Failed to convert row {} ({}) to list: ".format(y, row) + err.message if len(row) != BASE: raise ValueError("Width of row {} ({}) is not equal to number base ({})".format(i, len(row), BASE)) if len(row) % BLOCK_HEIGHT != 0: raise ValueError("Width of row {} ({}) is not divisible by block height ({})".format(i, len(row), BLOCK_HEIGHT)) for x, cell in enumerate(row): try: field[y][x] = int(cell) except Exception as err: err.message = "Failed to parse cell {} in row {} ({}) as int: ".format(x, y, cell) + err.message raise if not 0 <= cell <= BASE: raise ValueError("Cell {} in row {} ({}) must be greater than 0 and less than {}".format(x, y, cell, BASE)) for n in BASE_RANGE: if row.count(n) > 1: raise ValueError("Number {} appears more than once in row {}".format(n, y)) for x, col in enumerate(zip(*field)): for n in BASE_RANGE: if col.count(n) > 1: raise ValueError("Number {} appears more than once in column {}".format(n, x)) for y in range(BASE / BLOCK_HEIGHT): rows = field[BLOCK_HEIGHT*y:BLOCK_HEIGHT*(y+1)] for x in range(BASE / BLOCK_WIDTH): block = [] for row in rows: block += row[BLOCK_WIDTH*x:BLOCK_WIDTH*(x+1)] for n in BASE_RANGE: if block.count(n) > 1: raise ValueError("Number {} appears more than once in block y={}, x={}".format(n, y, x)) print("Checks done, field appears to be a valid sudoku. Proceeding to solve...") def solve(): global field # the following loop is just to be able to use "continue", it terminates after one full loop step = 1 while step >= 0: # reread variables zipfield = zip(*field) blocks = [] for y in range(BASE / BLOCK_HEIGHT): blocks.append([]) rows = field[BLOCK_HEIGHT*y:BLOCK_HEIGHT*(y+1)] for x in range(BASE / BLOCK_WIDTH): block = [] for row in rows: block += row[BLOCK_WIDTH*x:BLOCK_WIDTH*(x+1)] blocks[y].append(block) if step == 0: step = 1 elif step == 1: # Step 1: Basic solving of single-possibility cells print("Step 1...") for y, row in enumerate(field): for x, cell in enumerate(row): if isinstance(cell, set) or cell == 0: # cell is a list or nonzero number, i. e. unsolved poss = set() for n in BASE_RANGE: if n not in row and n not in zipfield[x] and n not in blocks[y//BLOCK_HEIGHT][x//BLOCK_WIDTH]: # n does not yet exist in row, column or block poss.add(n) if len(poss) == 1: # single possibility, cell is solved print("Cell {} in row {} must be {}".format(x, y, list(poss)[0])) field[y][x] = list(poss)[0] step = 0 elif len(poss) == 0: # no possibilities, something went wrong print("No possibilities for cell {} in row {}, this should never happen!".format(x, y)) retry = True step = -1 else: # more than one possibility, store for later field[y][x] = poss if step <= 0: break if step <= 0: break if step == 1: step = 2 elif step == 2: # Step 2: Analyze mutually exclusive possibilities print("Step 2...") for y, row in enumerate(field): for x, cell in enumerate(row): if isinstance(cell, set): poss = set() # Step 2.1: Correlate with other possibilities in same row oposs = set() for ocell in row: if isinstance(ocell, set) and ocell is not cell: oposs.update(ocell) for n in cell: if n not in oposs: # if n cannot go elsewhere, it must go here poss.add(n) # Step 2.2: Correlate with other possibilities in same column oposs = set() for ocell in zipfield[x]: if isinstance(ocell, set) and ocell is not cell: oposs.update(ocell) for n in cell: if n not in oposs: # if n cannot go elsewhere, it must go here poss.add(n) # Step 2.3: Correlate with other possibilities in same block oposs = set() for ocell in blocks[y//BLOCK_HEIGHT][x//BLOCK_WIDTH]: if isinstance(ocell, set) and ocell is not cell: oposs.update(ocell) for n in cell: if n not in oposs: # if n cannot go elsewhere, it must go here poss.add(n) if len(poss) == 1: # single possibility, cell is solved print("Cell {} in row {} must be {}".format(x, y, list(poss)[0])) field[y][x] = list(poss)[0] step = 0 elif len(poss) == 0: # no possibilities, simply ignore pass else: # more than one possibility, something went wrong print("More than one possibility ({}) in step 2 for cell {} in row {}, this should not happen!".format(poss, x, y)) if step <= 0: break if step <= 0: break if step == 2: step = -1 print("Final result: [") for row in field: print(str(row) + ",") print("]") if __name__ == "__main__": precheck() solve()
# Copyright 2013 Hewlett-Packard Development Company, L.P. # 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 manipulating Conductors via the DB API""" import datetime import mock from oslo_utils import timeutils from ironic.common import exception from ironic.tests.unit.db import base from ironic.tests.unit.db import utils class DbConductorTestCase(base.DbTestCase): def test_register_conductor_existing_fails(self): c = utils.get_test_conductor() self.dbapi.register_conductor(c) self.assertRaises( exception.ConductorAlreadyRegistered, self.dbapi.register_conductor, c) def test_register_conductor_override(self): c = utils.get_test_conductor() self.dbapi.register_conductor(c) self.dbapi.register_conductor(c, update_existing=True) def _create_test_cdr(self, **kwargs): c = utils.get_test_conductor(**kwargs) return self.dbapi.register_conductor(c) def test_get_conductor(self): c1 = self._create_test_cdr() c2 = self.dbapi.get_conductor(c1.hostname) self.assertEqual(c1.id, c2.id) def test_get_conductor_not_found(self): self._create_test_cdr() self.assertRaises( exception.ConductorNotFound, self.dbapi.get_conductor, 'bad-hostname') def test_unregister_conductor(self): c = self._create_test_cdr() self.dbapi.unregister_conductor(c.hostname) self.assertRaises( exception.ConductorNotFound, self.dbapi.unregister_conductor, c.hostname) @mock.patch.object(timeutils, 'utcnow', autospec=True) def test_touch_conductor(self, mock_utcnow): test_time = datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value = test_time c = self._create_test_cdr() self.assertEqual(test_time, timeutils.normalize_time(c.updated_at)) test_time = datetime.datetime(2000, 1, 1, 0, 1) mock_utcnow.return_value = test_time self.dbapi.touch_conductor(c.hostname) c = self.dbapi.get_conductor(c.hostname) self.assertEqual(test_time, timeutils.normalize_time(c.updated_at)) def test_touch_conductor_not_found(self): # A conductor's heartbeat will not create a new record, # it will only update existing ones self._create_test_cdr() self.assertRaises( exception.ConductorNotFound, self.dbapi.touch_conductor, 'bad-hostname') def test_touch_offline_conductor(self): # Ensure that a conductor's periodic heartbeat task can make the # conductor visible again, even if it was spuriously marked offline c = self._create_test_cdr() self.dbapi.unregister_conductor(c.hostname) self.assertRaises( exception.ConductorNotFound, self.dbapi.get_conductor, c.hostname) self.dbapi.touch_conductor(c.hostname) self.dbapi.get_conductor(c.hostname) def test_clear_node_reservations_for_conductor(self): node1 = self.dbapi.create_node({'reservation': 'hostname1'}) node2 = self.dbapi.create_node({'reservation': 'hostname2'}) node3 = self.dbapi.create_node({'reservation': None}) self.dbapi.clear_node_reservations_for_conductor('hostname1') node1 = self.dbapi.get_node_by_id(node1.id) node2 = self.dbapi.get_node_by_id(node2.id) node3 = self.dbapi.get_node_by_id(node3.id) self.assertIsNone(node1.reservation) self.assertEqual('hostname2', node2.reservation) self.assertIsNone(node3.reservation) @mock.patch.object(timeutils, 'utcnow', autospec=True) def test_get_active_driver_dict_one_host_no_driver(self, mock_utcnow): h = 'fake-host' expected = {} mock_utcnow.return_value = datetime.datetime.utcnow() self._create_test_cdr(hostname=h, drivers=[]) result = self.dbapi.get_active_driver_dict() self.assertEqual(expected, result) @mock.patch.object(timeutils, 'utcnow', autospec=True) def test_get_active_driver_dict_one_host_one_driver(self, mock_utcnow): h = 'fake-host' d = 'fake-driver' expected = {d: set([h])} mock_utcnow.return_value = datetime.datetime.utcnow() self._create_test_cdr(hostname=h, drivers=[d]) result = self.dbapi.get_active_driver_dict() self.assertEqual(expected, result) @mock.patch.object(timeutils, 'utcnow', autospec=True) def test_get_active_driver_dict_one_host_many_drivers(self, mock_utcnow): h = 'fake-host' d1 = 'driver-one' d2 = 'driver-two' expected = {d1: set([h]), d2: set([h])} mock_utcnow.return_value = datetime.datetime.utcnow() self._create_test_cdr(hostname=h, drivers=[d1, d2]) result = self.dbapi.get_active_driver_dict() self.assertEqual(expected, result) @mock.patch.object(timeutils, 'utcnow', autospec=True) def test_get_active_driver_dict_many_hosts_one_driver(self, mock_utcnow): h1 = 'host-one' h2 = 'host-two' d = 'fake-driver' expected = {d: set([h1, h2])} mock_utcnow.return_value = datetime.datetime.utcnow() self._create_test_cdr(id=1, hostname=h1, drivers=[d]) self._create_test_cdr(id=2, hostname=h2, drivers=[d]) result = self.dbapi.get_active_driver_dict() self.assertEqual(expected, result) @mock.patch.object(timeutils, 'utcnow', autospec=True) def test_get_active_driver_dict_many_hosts_and_drivers(self, mock_utcnow): h1 = 'host-one' h2 = 'host-two' h3 = 'host-three' d1 = 'driver-one' d2 = 'driver-two' expected = {d1: set([h1, h2]), d2: set([h2, h3])} mock_utcnow.return_value = datetime.datetime.utcnow() self._create_test_cdr(id=1, hostname=h1, drivers=[d1]) self._create_test_cdr(id=2, hostname=h2, drivers=[d1, d2]) self._create_test_cdr(id=3, hostname=h3, drivers=[d2]) result = self.dbapi.get_active_driver_dict() self.assertEqual(expected, result) @mock.patch.object(timeutils, 'utcnow', autospec=True) def test_get_active_driver_dict_with_old_conductor(self, mock_utcnow): past = datetime.datetime(2000, 1, 1, 0, 0) present = past + datetime.timedelta(minutes=2) d = 'common-driver' h1 = 'old-host' d1 = 'old-driver' mock_utcnow.return_value = past self._create_test_cdr(id=1, hostname=h1, drivers=[d, d1]) h2 = 'new-host' d2 = 'new-driver' mock_utcnow.return_value = present self._create_test_cdr(id=2, hostname=h2, drivers=[d, d2]) # verify that old-host does not show up in current list one_minute = 60 expected = {d: set([h2]), d2: set([h2])} result = self.dbapi.get_active_driver_dict(interval=one_minute) self.assertEqual(expected, result) # change the interval, and verify that old-host appears two_minute = one_minute * 2 expected = {d: set([h1, h2]), d1: set([h1]), d2: set([h2])} result = self.dbapi.get_active_driver_dict(interval=two_minute) self.assertEqual(expected, result) @mock.patch.object(timeutils, 'utcnow', autospec=True) def test_get_offline_conductors(self, mock_utcnow): self.config(heartbeat_timeout=60, group='conductor') time_ = datetime.datetime(2000, 1, 1, 0, 0) mock_utcnow.return_value = time_ c = self._create_test_cdr() # Only 30 seconds passed since last heartbeat, it's still # considered alive mock_utcnow.return_value = time_ + datetime.timedelta(seconds=30) self.assertEqual([], self.dbapi.get_offline_conductors()) # 61 seconds passed since last heartbeat, it's dead mock_utcnow.return_value = time_ + datetime.timedelta(seconds=61) self.assertEqual([c.hostname], self.dbapi.get_offline_conductors())
import numpy as np from numba import jit, njit, errors from numba.extending import register_jitable from numba.tests import usecases import unittest X = np.arange(10) def global_ndarray_func(x): y = x + X.shape[0] return y # Create complex array with real and imaginary parts of distinct value cplx_X = np.arange(10, dtype=np.complex128) tmp = np.arange(10, dtype=np.complex128) cplx_X += (tmp+10)*1j def global_cplx_arr_copy(a): for i in range(len(a)): a[i] = cplx_X[i] # Create a recarray with fields of distinct value x_dt = np.dtype([('a', np.int32), ('b', np.float32)]) rec_X = np.recarray(10, dtype=x_dt) for i in range(len(rec_X)): rec_X[i].a = i rec_X[i].b = i + 0.5 def global_rec_arr_copy(a): for i in range(len(a)): a[i] = rec_X[i] def global_rec_arr_extract_fields(a, b): for i in range(len(a)): a[i] = rec_X[i].a b[i] = rec_X[i].b # Create additional global recarray y_dt = np.dtype([('c', np.int16), ('d', np.float64)]) rec_Y = np.recarray(10, dtype=y_dt) for i in range(len(rec_Y)): rec_Y[i].c = i + 10 rec_Y[i].d = i + 10.5 def global_two_rec_arrs(a, b, c, d): for i in range(len(a)): a[i] = rec_X[i].a b[i] = rec_X[i].b c[i] = rec_Y[i].c d[i] = rec_Y[i].d # Test a global record record_only_X = np.recarray(1, dtype=x_dt)[0] record_only_X.a = 1 record_only_X.b = 1.5 @jit(nopython=True) def global_record_func(x): return x.a == record_only_X.a @jit(nopython=True) def global_module_func(x, y): return usecases.andornopython(x, y) # Test a global tuple tup_int = (1, 2) tup_str = ('a', 'b') tup_mixed = (1, 'a') tup_float = (1.2, 3.5) tup_npy_ints = (np.uint64(12), np.int8(3)) tup_tup_array = ((np.ones(5),),) mixed_tup_tup_array = (('Z', np.ones(5),), 2j, 'A') def global_int_tuple(): return tup_int[0] + tup_int[1] def global_str_tuple(): return tup_str[0] + tup_str[1] def global_mixed_tuple(): idx = tup_mixed[0] field = tup_mixed[1] return rec_X[idx][field] def global_float_tuple(): return tup_float[0] + tup_float[1] def global_npy_int_tuple(): return tup_npy_ints[0] + tup_npy_ints[1] def global_write_to_arr_in_tuple(): tup_tup_array[0][0][0] = 10. def global_write_to_arr_in_mixed_tuple(): mixed_tup_tup_array[0][1][0] = 10. _glbl_np_bool_T = np.bool_(True) _glbl_np_bool_F = np.bool_(False) @register_jitable # consumer function def _sink(*args): pass def global_npy_bool(): _sink(_glbl_np_bool_T, _glbl_np_bool_F) return _glbl_np_bool_T, _glbl_np_bool_F class TestGlobals(unittest.TestCase): def check_global_ndarray(self, **jitargs): # (see github issue #448) ctestfunc = jit(**jitargs)(global_ndarray_func) self.assertEqual(ctestfunc(1), 11) def test_global_ndarray(self): # This also checks we can access an unhashable global value # (see issue #697) self.check_global_ndarray(forceobj=True) def test_global_ndarray_npm(self): self.check_global_ndarray(nopython=True) def check_global_complex_arr(self, **jitargs): # (see github issue #897) ctestfunc = jit(**jitargs)(global_cplx_arr_copy) arr = np.zeros(len(cplx_X), dtype=np.complex128) ctestfunc(arr) np.testing.assert_equal(arr, cplx_X) def test_global_complex_arr(self): self.check_global_complex_arr(forceobj=True) def test_global_complex_arr_npm(self): self.check_global_complex_arr(nopython=True) def check_global_rec_arr(self, **jitargs): # (see github issue #897) ctestfunc = jit(**jitargs)(global_rec_arr_copy) arr = np.zeros(rec_X.shape, dtype=x_dt) ctestfunc(arr) np.testing.assert_equal(arr, rec_X) def test_global_rec_arr(self): self.check_global_rec_arr(forceobj=True) def test_global_rec_arr_npm(self): self.check_global_rec_arr(nopython=True) def check_global_rec_arr_extract(self, **jitargs): # (see github issue #897) ctestfunc = jit(**jitargs)(global_rec_arr_extract_fields) arr1 = np.zeros(rec_X.shape, dtype=np.int32) arr2 = np.zeros(rec_X.shape, dtype=np.float32) ctestfunc(arr1, arr2) np.testing.assert_equal(arr1, rec_X.a) np.testing.assert_equal(arr2, rec_X.b) def test_global_rec_arr_extract(self): self.check_global_rec_arr_extract(forceobj=True) def test_global_rec_arr_extract_npm(self): self.check_global_rec_arr_extract(nopython=True) def check_two_global_rec_arrs(self, **jitargs): # (see github issue #897) ctestfunc = jit(**jitargs)(global_two_rec_arrs) arr1 = np.zeros(rec_X.shape, dtype=np.int32) arr2 = np.zeros(rec_X.shape, dtype=np.float32) arr3 = np.zeros(rec_Y.shape, dtype=np.int16) arr4 = np.zeros(rec_Y.shape, dtype=np.float64) ctestfunc(arr1, arr2, arr3, arr4) np.testing.assert_equal(arr1, rec_X.a) np.testing.assert_equal(arr2, rec_X.b) np.testing.assert_equal(arr3, rec_Y.c) np.testing.assert_equal(arr4, rec_Y.d) def test_two_global_rec_arrs(self): self.check_two_global_rec_arrs(forceobj=True) def test_two_global_rec_arrs_npm(self): self.check_two_global_rec_arrs(nopython=True) def test_global_module(self): # (see github issue #1059) res = global_module_func(5, 6) self.assertEqual(True, res) def test_global_record(self): # (see github issue #1081) x = np.recarray(1, dtype=x_dt)[0] x.a = 1 res = global_record_func(x) self.assertEqual(True, res) x.a = 2 res = global_record_func(x) self.assertEqual(False, res) def test_global_int_tuple(self): pyfunc = global_int_tuple jitfunc = njit(pyfunc) self.assertEqual(pyfunc(), jitfunc()) def test_global_str_tuple(self): pyfunc = global_str_tuple jitfunc = njit(pyfunc) self.assertEqual(pyfunc(), jitfunc()) def test_global_mixed_tuple(self): pyfunc = global_mixed_tuple jitfunc = njit(pyfunc) self.assertEqual(pyfunc(), jitfunc()) def test_global_float_tuple(self): pyfunc = global_float_tuple jitfunc = njit(pyfunc) self.assertEqual(pyfunc(), jitfunc()) def test_global_npy_int_tuple(self): pyfunc = global_npy_int_tuple jitfunc = njit(pyfunc) self.assertEqual(pyfunc(), jitfunc()) def test_global_write_to_arr_in_tuple(self): # Test writing to an array in a global tuple # See issue https://github.com/numba/numba/issues/7120 for func in (global_write_to_arr_in_tuple, global_write_to_arr_in_mixed_tuple): jitfunc = njit(func) with self.assertRaises(errors.TypingError) as e: jitfunc() msg = "Cannot modify readonly array of type:" self.assertIn(msg, str(e.exception)) def test_global_npy_bool(self): # Test global NumPy bool # See issue https://github.com/numba/numba/issues/6979 pyfunc = global_npy_bool jitfunc = njit(pyfunc) self.assertEqual(pyfunc(), jitfunc()) if __name__ == '__main__': unittest.main()
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Functional tests for modules/course_explorer/course_explorer.py.""" __author__ = '[email protected] (Rahul Singal)' import actions from actions import assert_contains from actions import assert_does_not_contain from actions import assert_equals from controllers import sites from models import config from models import courses from models import models from models import transforms from models.models import PersonalProfile from modules.course_explorer import course_explorer from modules.course_explorer import student class BaseExplorerTest(actions.TestBase): """Base class for testing explorer pages.""" def setUp(self): super(BaseExplorerTest, self).setUp() config.Registry.test_overrides[ models.CAN_SHARE_STUDENT_PROFILE.name] = True config.Registry.test_overrides[ course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True def tearDown(self): config.Registry.test_overrides = {} super(BaseExplorerTest, self).tearDown() class CourseExplorerTest(BaseExplorerTest): """Tests course_explorer module.""" def test_single_uncompleted_course(self): """Tests for a single available course.""" # This call should redirect to explorer page. response = self.get('/') assert_contains('/explorer', response.location) name = 'Test student courses page' email = 'Student' actions.login(email) # Test the explorer page. response = self.get('/explorer') assert_equals(response.status_int, 200) assert_contains('Register', response.body) # Navbar should not contain profile tab. assert_does_not_contain( '<a href="/explorer/profile">Profile</a>', response.body) # Test 'my courses' page when a student is not enrolled in any course. response = self.get('/explorer/courses') assert_equals(response.status_int, 200) assert_contains('You are not currently enrolled in any course', response.body) # Test 'my courses' page when a student is enrolled in all courses. actions.register(self, name) response = self.get('/explorer/courses') assert_equals(response.status_int, 200) assert_contains('Go to course', response.body) assert_does_not_contain('You are not currently enrolled in any course', response.body) # After the student registers for a course, # profile tab should be visible in navbar. assert_contains( '<a href="/explorer/profile">Profile</a>', response.body) # Test profile page. response = self.get('/explorer/profile') assert_contains('<td>%s</td>' % email, response.body) assert_contains('<td>%s</td>' % name, response.body) assert_contains('Progress', response.body) assert_does_not_contain('View score', response.body) def test_single_completed_course(self): """Tests when a single completed course is present.""" name = 'Test Assessments' # Register. user = actions.login('[email protected]') actions.register(self, name) response = self.get('/explorer') # Before a course is not completed, # explorer page should not show 'view score' button. assert_does_not_contain('View score', response.body) # Assign a grade to the course enrolled to mark it complete. profile = PersonalProfile.get_by_key_name(user.user_id()) info = {'final_grade': 'A'} course_info_dict = {'': info} profile.course_info = transforms.dumps(course_info_dict) profile.put() # Check if 'View score' text is visible on profile page. response = self.get('/explorer/profile') assert_contains('View score', response.body) # Check if 'Go to course' button is not visible on explorer page. response = self.get('/explorer') assert_does_not_contain('Go to course', response.body) # Check if 'View score' button is visible on explorer page. response = self.get('/explorer') assert_contains('View score', response.body) def test_multiple_course(self): """Tests when multiple courses are available.""" sites.setup_courses('course:/test::ns_test, course:/:/') name = 'Test completed course' email = 'Student' # Make the course available. get_environ_old = sites.ApplicationContext.get_environ def get_environ_new(self): environ = get_environ_old(self) environ['course']['now_available'] = True return environ sites.ApplicationContext.get_environ = get_environ_new actions.login(email) actions.register(self, name) response = self.get('/explorer/courses') # Assert if 'View course list' text is shown on my course page. assert_contains('View course list', response.body) # Clean up app_context. sites.ApplicationContext.get_environ = get_environ_old sites.reset_courses() def test_can_register_true(self): courses.Course.ENVIRON_TEST_OVERRIDES = { 'reg_form': {'can_register': True}} dom = self.parse_html_string(self.get('/explorer').body) item = dom.find('.//li[@class="gcb-explorer-list-item"]') self.assertEquals( 'Power Searching with Google', item.find('.//a[@class="gcb-explorer-course-title"]').text) # Registration button present self.assertIsNotNone(item.find('.//a[@href="/register"]')) def test_can_register_false(self): courses.Course.ENVIRON_TEST_OVERRIDES = { 'reg_form': {'can_register': False}} dom = self.parse_html_string(self.get('/explorer').body) item = dom.find('.//li[@class="gcb-explorer-list-item"]') self.assertEquals( 'Power Searching with Google', item.find('.//a[@class="gcb-explorer-course-title"]').text) # No registration button present self.assertIsNone(item.find('.//a[@href="/register"]')) class CourseExplorerDisabledTest(actions.TestBase): """Tests when course explorer is disabled.""" def get_auto_deploy(self): return False def test_anonymous_access(self): """Tests for disabled course explorer page.""" # disable the explorer config.Registry.test_overrides[ course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = False self.assertFalse(course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value) # check root URL's properly redirect to login response = self.get('/') assert_equals(response.status_int, 302) assert_contains( 'http://localhost/admin/welcome', response.location) response = self.get('/assets/img/your_logo_here.png') assert_equals(response.status_int, 302) assert_contains('accounts/Login', response.location) # check explorer pages are not accessible not_accessibles = [ '/explorer', '/explorer/courses', '/explorer/profile', '/explorer/assets/img/your_logo_here.png'] for not_accessible in not_accessibles: response = self.get(not_accessible, expect_errors=True) assert_equals(response.status_int, 404) # enable course explorer config.Registry.test_overrides[ course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True self.assertTrue(course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value) # check explorer pages are accessible accessibles = [ '/explorer', '/explorer/courses', '/explorer/assets/img/your_logo_here.png'] for accessible in accessibles: response = self.get(accessible, expect_errors=True) assert_equals(response.status_int, 200) # check student pages are not accessible response = self.get('/explorer/profile') assert_equals(response.status_int, 302) self.assertEqual('http://localhost/explorer', response.location) def test_student_access(self): # enable course explorer config.Registry.test_overrides[ course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True self.assertTrue(course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value) # check not being logged in response = self.get('/explorer') assert_contains('Explore Courses', response.body) assert_does_not_contain('My Courses', response.body) assert_does_not_contain('Site admin', response.body) # login and check logged in student perspective config.Registry.test_overrides[ sites.GCB_COURSES_CONFIG.name] = 'course:/:/' email = 'student' actions.login(email) response = self.get('/explorer') assert_contains('Explore Courses', response.body) assert_contains('My Courses', response.body) assert_does_not_contain('Site admin', response.body) def test_admin_access(self): # enable course explorer config.Registry.test_overrides[ course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True self.assertTrue(course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value) # check the admin site link actions.login('[email protected]', is_admin=True) response = self.get('/explorer') assert_contains('Site admin', response.body) class GlobalProfileTest(BaseExplorerTest): """Tests course_explorer module.""" def test_change_of_name(self): """Tests for a single available course.""" # This call should redirect to explorer page. response = self.get('/') assert_contains('/explorer', response.location) name = 'Test global profile page' email = '[email protected]' actions.login(email) # Test the explorer page. response = self.get('/explorer') assert_equals(response.status_int, 200) assert_contains('Register', response.body) # Test 'my courses' page when a student is enrolled in all courses. actions.register(self, name) # Test profile page. response = self.get('/explorer/profile') assert_contains('<td>%s</td>' % email, response.body) assert_contains('<td>%s</td>' % name, response.body) # Change the name now new_name = 'New global name' response.form.set('name', new_name) response = self.submit(response.form) assert_equals(response.status_int, 302) response = self.get('/explorer/profile') assert_contains('<td>%s</td>' % email, response.body) assert_contains('<td>%s</td>' % new_name, response.body) # Change name with bad xsrf token. response = self.get('/explorer/profile') assert_equals(response.status_int, 200) new_name = 'New Bad global name' response.form.set('name', new_name) response.form.set('xsrf_token', 'asdfsdf') response = response.form.submit(expect_errors=True) assert_equals(response.status_int, 403) # Change name with empty name shold fail. response = self.get('/explorer/profile') assert_equals(response.status_int, 200) new_name = '' response.form.set('name', new_name) response = response.form.submit(expect_errors=True) assert_equals(response.status_int, 400) # Change name with overlong name should fail for str. response = self.get('/explorer/profile') assert_equals(response.status_int, 200) new_name = 'a' * (student._STRING_PROPERTY_MAX_BYTES + 1) response.form.set('name', new_name) response = response.form.submit(expect_errors=True) assert_equals(response.status_int, 400) # Change name with overlong name should fail for unicode. response = self.get('/explorer/profile') assert_equals(response.status_int, 200) # \u03a3 == Sigma. len == 1 for unicode; 2 for utf-8 encoded str. new_name = u'\u03a3' + ('a' * (student._STRING_PROPERTY_MAX_BYTES - 1)) response.form.set('name', new_name) response = response.form.submit(expect_errors=True) assert_equals(response.status_int, 400)
""" scaling images """ from __future__ import print_function, unicode_literals, absolute_import, division import logging logger = logging.getLogger(__name__) import os import numpy as np import warnings from gputools import OCLArray, OCLImage, OCLProgram from gputools.core.ocltypes import cl_buffer_datatype_dict from gputools.utils import mat4_rotate, mat4_translate from ._abspath import abspath from mako.template import Template def affine(data, mat=np.identity(4), output_shape=None, mode="constant", interpolation="linear", res_g=None): """ affine transform data with matrix mat, which is the inverse coordinate transform matrix (similar to ndimage.affine_transform) Parameters ---------- data, ndarray or OCLImage 3d array to be transformed mat, ndarray or OCLArray the 4x4 inverse coordinate transform matrix (has to have type float32 if OCLArray) output_shape: tuple of ints shape of transformed array mode: string boundary mode, one of the following: 'constant' pads with zeros 'edge' pads with edge values 'wrap' pads with the repeated version of the input interpolation, string interpolation mode, one of the following 'linear' 'nearest' Returns ------- res: ndarray or openCL array transformed array (same shape as input) """ if data.ndim != 3: raise ValueError("input data has to be a 3d array!") interpolation_defines = {"linear": ["-D", "SAMPLER_FILTER=CLK_FILTER_LINEAR"], "nearest": ["-D", "SAMPLER_FILTER=CLK_FILTER_NEAREST"]} mode_defines = {"constant": ["-D", "SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP"], "wrap": ["-D", "SAMPLER_ADDRESS=CLK_ADDRESS_REPEAT"], "edge": ["-D", "SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP_TO_EDGE"] } if not interpolation in interpolation_defines: raise KeyError( "interpolation = '%s' not defined ,valid: %s" % (interpolation, list(interpolation_defines.keys()))) if not mode in mode_defines: raise KeyError("mode = '%s' not defined ,valid: %s" % (mode, list(mode_defines.keys()))) if output_shape is None: output_shape = data.shape if isinstance(data, OCLImage): d_im = data else: d_im = OCLImage.from_array(data.astype(np.float32, copy=False)) if res_g is None: res_g = OCLArray.empty(output_shape, np.float32) if isinstance(mat, OCLArray): mat_inv_g = mat else: mat_inv_g = OCLArray.from_array(mat.astype(np.float32, copy=False)) if not (mat_inv_g.shape == (4,4) and mat_inv_g.dtype.type == np.float32): raise ValueError("affine transformation matrix should be a (4,4) float32 matrix!") prog = OCLProgram(abspath("kernels/affine.cl") , build_options=interpolation_defines[interpolation] + mode_defines[mode]) prog.run_kernel("affine3", output_shape[::-1], None, d_im, res_g.data, mat_inv_g.data) if isinstance(data, OCLImage): return res_g else: return res_g.get() def shift(data, shift=(0, 0, 0), mode="constant", interpolation="linear"): """ translates 3d data by given amount Parameters ---------- data: ndarray 3d array shift : float or sequence The shift along the axes. If a float, `shift` is the same for each axis. If a sequence, `shift` should contain one value for each axis. mode: string boundary mode, one of the following: 'constant' pads with zeros 'edge' pads with edge values 'wrap' pads with the repeated version of the input interpolation, string interpolation mode, one of the following 'linear' 'nearest' Returns ------- res: ndarray shifted array (same shape as input) """ if np.isscalar(shift): shift = (shift,) * 3 if len(shift) != 3: raise ValueError("shift (%s) should be of length 3!") shift = -np.array(shift) return affine(data, mat4_translate(*shift), mode=mode, interpolation=interpolation) def rotate(data, axis=(1., 0, 0), angle=0., center=None, mode="constant", interpolation="linear"): """ rotates data around axis by a given angle Parameters ---------- data: ndarray 3d array axis: tuple axis to rotate by angle about axis = (x,y,z) angle: float center: tuple or None origin of rotation (cz,cy,cx) in pixels if None, center is the middle of data mode: string boundary mode, one of the following: 'constant' pads with zeros 'edge' pads with edge values 'wrap' pads with the repeated version of the input interpolation, string interpolation mode, one of the following 'linear' 'nearest' Returns ------- res: ndarray rotated array (same shape as input) """ if center is None: center = tuple([s // 2 for s in data.shape]) cx, cy, cz = center m = np.dot(mat4_translate(cx, cy, cz), np.dot(mat4_rotate(angle, *axis), mat4_translate(-cx, -cy, -cz))) m = np.linalg.inv(m) return affine(data, m, mode=mode, interpolation=interpolation) def map_coordinates(data, coordinates, interpolation="linear", mode='constant'): """ Map data to new coordinates by interpolation. The array of coordinates is used to find, for each point in the output, the corresponding coordinates in the input. should correspond to scipy.ndimage.map_coordinates Parameters ---------- data coordinates output interpolation mode cval prefilter Returns ------- """ if not (isinstance(data, np.ndarray) and data.ndim in (2, 3)): raise ValueError("input data has to be a 2d or 3d array!") coordinates = np.asarray(coordinates, np.int32) if not (coordinates.shape[0] == data.ndim): raise ValueError("coordinate has to be of shape (data.ndim,m) ") interpolation_defines = {"linear": ["-D", "SAMPLER_FILTER=CLK_FILTER_LINEAR"], "nearest": ["-D", "SAMPLER_FILTER=CLK_FILTER_NEAREST"]} mode_defines = {"constant": ["-D", "SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP"], "wrap": ["-D", "SAMPLER_ADDRESS=CLK_ADDRESS_REPEAT"], "edge": ["-D", "SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP_TO_EDGE"] } if not interpolation in interpolation_defines: raise KeyError( "interpolation = '%s' not defined ,valid: %s" % (interpolation, list(interpolation_defines.keys()))) if not mode in mode_defines: raise KeyError("mode = '%s' not defined ,valid: %s" % (mode, list(mode_defines.keys()))) if not data.dtype.type in cl_buffer_datatype_dict: raise KeyError("dtype %s not supported yet (%s)" % (data.dtype.type, tuple(cl_buffer_datatype_dict.keys()))) dtype_defines = ["-D", "DTYPE=%s" % cl_buffer_datatype_dict[data.dtype.type]] d_im = OCLImage.from_array(data) coordinates_g = OCLArray.from_array(coordinates.astype(np.float32, copy=False)) res_g = OCLArray.empty(coordinates.shape[1], data.dtype) prog = OCLProgram(abspath("kernels/map_coordinates.cl") , build_options=interpolation_defines[interpolation] + mode_defines[mode] + dtype_defines) kernel = "map_coordinates{ndim}".format(ndim=data.ndim) prog.run_kernel(kernel, (coordinates.shape[-1],), None, d_im, res_g.data, coordinates_g.data) return res_g.get() def geometric_transform(data, mapping = "c0,c1", output_shape=None, mode='constant', interpolation="linear"): """ Apply an arbitrary geometric transform. The given mapping function is used to find, for each point in the output, the corresponding coordinates in the input. The value of the input at those coordinates is determined by spline interpolation of the requested order. Parameters ---------- %(input)s mapping : {callable, scipy.LowLevelCallable} A callable object that accepts a tuple of length equal to the output array rank, and returns the corresponding input coordinates as a tuple of length equal to the input array rank. """ if not (isinstance(data, np.ndarray) and data.ndim in (2, 3)): raise ValueError("input data has to be a 2d or 3d array!") interpolation_defines = {"linear": ["-D", "SAMPLER_FILTER=CLK_FILTER_LINEAR"], "nearest": ["-D", "SAMPLER_FILTER=CLK_FILTER_NEAREST"]} mode_defines = {"constant": ["-D", "SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP"], "wrap": ["-D", "SAMPLER_ADDRESS=CLK_ADDRESS_REPEAT"], "edge": ["-D", "SAMPLER_ADDRESS=CLK_ADDRESS_CLAMP_TO_EDGE"] } if not interpolation in interpolation_defines: raise KeyError( "interpolation = '%s' not defined ,valid: %s" % (interpolation, list(interpolation_defines.keys()))) if not mode in mode_defines: raise KeyError("mode = '%s' not defined ,valid: %s" % (mode, list(mode_defines.keys()))) if not data.dtype.type in cl_buffer_datatype_dict: raise KeyError("dtype %s not supported yet (%s)" % (data.dtype.type, tuple(cl_buffer_datatype_dict.keys()))) dtype_defines = ["-D", "DTYPE={type}".format(type=cl_buffer_datatype_dict[data.dtype.type])] image_functions = {np.float32:"read_imagef", np.uint8: "read_imageui", np.uint16: "read_imageui", np.int32: "read_imagei"} image_read_defines = ["-D","READ_IMAGE=%s"%image_functions[data.dtype.type]] with open(abspath("kernels/geometric_transform.cl"), "r") as f: tpl = Template(f.read()) output_shape = tuple(output_shape) mappings = {"FUNC2": "c1,c0", "FUNC3": "c2,c1,c0"} mappings["FUNC%d" % data.ndim] = ",".join(reversed(mapping.split(","))) rendered = tpl.render(**mappings) d_im = OCLImage.from_array(data) res_g = OCLArray.empty(output_shape, data.dtype) prog = OCLProgram(src_str=rendered, build_options=interpolation_defines[interpolation] + mode_defines[mode] + dtype_defines+image_read_defines) kernel = "geometric_transform{ndim}".format(ndim=data.ndim) prog.run_kernel(kernel, output_shape[::-1], None, d_im, res_g.data) return res_g.get() if __name__ == '__main__': d = np.zeros((200, 200, 200), np.float32) d[20:-20, 20:-20, 20:-20] = 1. # res = translate(d, x = 10, y = 5, z= -10 ) res = rotate(d, center=(100, 100, 100), angle=.5)
""" terminal reporting of the full testing process. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os import sys import textwrap import pluggy import py import pytest from _pytest.main import EXIT_NOTESTSCOLLECTED from _pytest.terminal import _plugin_nameversions from _pytest.terminal import build_summary_stats_line from _pytest.terminal import getreportopt from _pytest.terminal import repr_pythonversion from _pytest.terminal import TerminalReporter DistInfo = collections.namedtuple("DistInfo", ["project_name", "version"]) class Option(object): def __init__(self, verbose=False, fulltrace=False): self.verbose = verbose self.fulltrace = fulltrace @property def args(self): values = [] if self.verbose: values.append("-v") if self.fulltrace: values.append("--fulltrace") return values @pytest.fixture( params=[ Option(verbose=False), Option(verbose=True), Option(verbose=-1), Option(fulltrace=True), ], ids=["default", "verbose", "quiet", "fulltrace"], ) def option(request): return request.param @pytest.mark.parametrize( "input,expected", [ ([DistInfo(project_name="test", version=1)], ["test-1"]), ([DistInfo(project_name="pytest-test", version=1)], ["test-1"]), ( [ DistInfo(project_name="test", version=1), DistInfo(project_name="test", version=1), ], ["test-1"], ), ], ids=["normal", "prefix-strip", "deduplicate"], ) def test_plugin_nameversion(input, expected): pluginlist = [(None, x) for x in input] result = _plugin_nameversions(pluginlist) assert result == expected class TestTerminal(object): def test_pass_skip_fail(self, testdir, option): testdir.makepyfile( """ import pytest def test_ok(): pass def test_skip(): pytest.skip("xx") def test_func(): assert 0 """ ) result = testdir.runpytest(*option.args) if option.verbose: result.stdout.fnmatch_lines( [ "*test_pass_skip_fail.py::test_ok PASS*", "*test_pass_skip_fail.py::test_skip SKIP*", "*test_pass_skip_fail.py::test_func FAIL*", ] ) else: result.stdout.fnmatch_lines(["*test_pass_skip_fail.py .sF*"]) result.stdout.fnmatch_lines( [" def test_func():", "> assert 0", "E assert 0"] ) def test_internalerror(self, testdir, linecomp): modcol = testdir.getmodulecol("def test_one(): pass") rep = TerminalReporter(modcol.config, file=linecomp.stringio) excinfo = pytest.raises(ValueError, "raise ValueError('hello')") rep.pytest_internalerror(excinfo.getrepr()) linecomp.assert_contains_lines(["INTERNALERROR> *ValueError*hello*"]) def test_writeline(self, testdir, linecomp): modcol = testdir.getmodulecol("def test_one(): pass") rep = TerminalReporter(modcol.config, file=linecomp.stringio) rep.write_fspath_result(modcol.nodeid, ".") rep.write_line("hello world") lines = linecomp.stringio.getvalue().split("\n") assert not lines[0] assert lines[1].endswith(modcol.name + " .") assert lines[2] == "hello world" def test_show_runtest_logstart(self, testdir, linecomp): item = testdir.getitem("def test_func(): pass") tr = TerminalReporter(item.config, file=linecomp.stringio) item.config.pluginmanager.register(tr) location = item.reportinfo() tr.config.hook.pytest_runtest_logstart( nodeid=item.nodeid, location=location, fspath=str(item.fspath) ) linecomp.assert_contains_lines(["*test_show_runtest_logstart.py*"]) def test_runtest_location_shown_before_test_starts(self, testdir): testdir.makepyfile( """ def test_1(): import time time.sleep(20) """ ) child = testdir.spawn_pytest("") child.expect(".*test_runtest_location.*py") child.sendeof() child.kill(15) def test_itemreport_subclasses_show_subclassed_file(self, testdir): testdir.makepyfile( test_p1=""" class BaseTests(object): def test_p1(self): pass class TestClass(BaseTests): pass """ ) p2 = testdir.makepyfile( test_p2=""" from test_p1 import BaseTests class TestMore(BaseTests): pass """ ) result = testdir.runpytest(p2) result.stdout.fnmatch_lines(["*test_p2.py .*", "*1 passed*"]) result = testdir.runpytest("-vv", p2) result.stdout.fnmatch_lines( ["*test_p2.py::TestMore::test_p1* <- *test_p1.py*PASSED*"] ) def test_itemreport_directclasses_not_shown_as_subclasses(self, testdir): a = testdir.mkpydir("a123") a.join("test_hello123.py").write( textwrap.dedent( """\ class TestClass(object): def test_method(self): pass """ ) ) result = testdir.runpytest("-vv") assert result.ret == 0 result.stdout.fnmatch_lines(["*a123/test_hello123.py*PASS*"]) assert " <- " not in result.stdout.str() def test_keyboard_interrupt(self, testdir, option): testdir.makepyfile( """ def test_foobar(): assert 0 def test_spamegg(): import py; pytest.skip('skip me please!') def test_interrupt_me(): raise KeyboardInterrupt # simulating the user """ ) result = testdir.runpytest(*option.args, no_reraise_ctrlc=True) result.stdout.fnmatch_lines( [ " def test_foobar():", "> assert 0", "E assert 0", "*_keyboard_interrupt.py:6: KeyboardInterrupt*", ] ) if option.fulltrace: result.stdout.fnmatch_lines( ["*raise KeyboardInterrupt # simulating the user*"] ) else: result.stdout.fnmatch_lines( ["(to show a full traceback on KeyboardInterrupt use --fulltrace)"] ) result.stdout.fnmatch_lines(["*KeyboardInterrupt*"]) def test_keyboard_in_sessionstart(self, testdir): testdir.makeconftest( """ def pytest_sessionstart(): raise KeyboardInterrupt """ ) testdir.makepyfile( """ def test_foobar(): pass """ ) result = testdir.runpytest(no_reraise_ctrlc=True) assert result.ret == 2 result.stdout.fnmatch_lines(["*KeyboardInterrupt*"]) def test_collect_single_item(self, testdir): """Use singular 'item' when reporting a single test item""" testdir.makepyfile( """ def test_foobar(): pass """ ) result = testdir.runpytest() result.stdout.fnmatch_lines(["collected 1 item"]) def test_rewrite(self, testdir, monkeypatch): config = testdir.parseconfig() f = py.io.TextIO() monkeypatch.setattr(f, "isatty", lambda *args: True) tr = TerminalReporter(config, f) tr._tw.fullwidth = 10 tr.write("hello") tr.rewrite("hey", erase=True) assert f.getvalue() == "hello" + "\r" + "hey" + (6 * " ") class TestCollectonly(object): def test_collectonly_basic(self, testdir): testdir.makepyfile( """ def test_func(): pass """ ) result = testdir.runpytest("--collect-only") result.stdout.fnmatch_lines( ["<Module 'test_collectonly_basic.py'>", " <Function 'test_func'>"] ) def test_collectonly_skipped_module(self, testdir): testdir.makepyfile( """ import pytest pytest.skip("hello") """ ) result = testdir.runpytest("--collect-only", "-rs") result.stdout.fnmatch_lines(["*ERROR collecting*"]) def test_collectonly_failed_module(self, testdir): testdir.makepyfile("""raise ValueError(0)""") result = testdir.runpytest("--collect-only") result.stdout.fnmatch_lines(["*raise ValueError*", "*1 error*"]) def test_collectonly_fatal(self, testdir): testdir.makeconftest( """ def pytest_collectstart(collector): assert 0, "urgs" """ ) result = testdir.runpytest("--collect-only") result.stdout.fnmatch_lines(["*INTERNAL*args*"]) assert result.ret == 3 def test_collectonly_simple(self, testdir): p = testdir.makepyfile( """ def test_func1(): pass class TestClass(object): def test_method(self): pass """ ) result = testdir.runpytest("--collect-only", p) # assert stderr.startswith("inserting into sys.path") assert result.ret == 0 result.stdout.fnmatch_lines( [ "*<Module '*.py'>", "* <Function 'test_func1'*>", "* <Class 'TestClass'>", # "* <Instance '()'>", "* <Function 'test_method'*>", ] ) def test_collectonly_error(self, testdir): p = testdir.makepyfile("import Errlkjqweqwe") result = testdir.runpytest("--collect-only", p) assert result.ret == 2 result.stdout.fnmatch_lines( textwrap.dedent( """\ *ERROR* *ImportError* *No module named *Errlk* *1 error* """ ).strip() ) def test_collectonly_missing_path(self, testdir): """this checks issue 115, failure in parseargs will cause session not to have the items attribute """ result = testdir.runpytest("--collect-only", "uhm_missing_path") assert result.ret == 4 result.stderr.fnmatch_lines(["*ERROR: file not found*"]) def test_collectonly_quiet(self, testdir): testdir.makepyfile("def test_foo(): pass") result = testdir.runpytest("--collect-only", "-q") result.stdout.fnmatch_lines(["*test_foo*"]) def test_collectonly_more_quiet(self, testdir): testdir.makepyfile(test_fun="def test_foo(): pass") result = testdir.runpytest("--collect-only", "-qq") result.stdout.fnmatch_lines(["*test_fun.py: 1*"]) def test_repr_python_version(monkeypatch): try: monkeypatch.setattr(sys, "version_info", (2, 5, 1, "final", 0)) assert repr_pythonversion() == "2.5.1-final-0" sys.version_info = x = (2, 3) assert repr_pythonversion() == str(x) finally: monkeypatch.undo() # do this early as pytest can get confused class TestFixtureReporting(object): def test_setup_fixture_error(self, testdir): testdir.makepyfile( """ def setup_function(function): print ("setup func") assert 0 def test_nada(): pass """ ) result = testdir.runpytest() result.stdout.fnmatch_lines( [ "*ERROR at setup of test_nada*", "*setup_function(function):*", "*setup func*", "*assert 0*", "*1 error*", ] ) assert result.ret != 0 def test_teardown_fixture_error(self, testdir): testdir.makepyfile( """ def test_nada(): pass def teardown_function(function): print ("teardown func") assert 0 """ ) result = testdir.runpytest() result.stdout.fnmatch_lines( [ "*ERROR at teardown*", "*teardown_function(function):*", "*assert 0*", "*Captured stdout*", "*teardown func*", "*1 passed*1 error*", ] ) def test_teardown_fixture_error_and_test_failure(self, testdir): testdir.makepyfile( """ def test_fail(): assert 0, "failingfunc" def teardown_function(function): print ("teardown func") assert False """ ) result = testdir.runpytest() result.stdout.fnmatch_lines( [ "*ERROR at teardown of test_fail*", "*teardown_function(function):*", "*assert False*", "*Captured stdout*", "*teardown func*", "*test_fail*", "*def test_fail():", "*failingfunc*", "*1 failed*1 error*", ] ) def test_setup_teardown_output_and_test_failure(self, testdir): """ Test for issue #442 """ testdir.makepyfile( """ def setup_function(function): print ("setup func") def test_fail(): assert 0, "failingfunc" def teardown_function(function): print ("teardown func") """ ) result = testdir.runpytest() result.stdout.fnmatch_lines( [ "*test_fail*", "*def test_fail():", "*failingfunc*", "*Captured stdout setup*", "*setup func*", "*Captured stdout teardown*", "*teardown func*", "*1 failed*", ] ) class TestTerminalFunctional(object): def test_deselected(self, testdir): testpath = testdir.makepyfile( """ def test_one(): pass def test_two(): pass def test_three(): pass """ ) result = testdir.runpytest("-k", "test_two:", testpath) result.stdout.fnmatch_lines( ["collected 3 items / 1 deselected", "*test_deselected.py ..*"] ) assert result.ret == 0 def test_show_deselected_items_using_markexpr_before_test_execution(self, testdir): testdir.makepyfile( test_show_deselected=""" import pytest @pytest.mark.foo def test_foobar(): pass @pytest.mark.bar def test_bar(): pass def test_pass(): pass """ ) result = testdir.runpytest("-m", "not foo") result.stdout.fnmatch_lines( [ "collected 3 items / 1 deselected", "*test_show_deselected.py ..*", "*= 2 passed, 1 deselected in * =*", ] ) assert "= 1 deselected =" not in result.stdout.str() assert result.ret == 0 def test_no_skip_summary_if_failure(self, testdir): testdir.makepyfile( """ import pytest def test_ok(): pass def test_fail(): assert 0 def test_skip(): pytest.skip("dontshow") """ ) result = testdir.runpytest() assert result.stdout.str().find("skip test summary") == -1 assert result.ret == 1 def test_passes(self, testdir): p1 = testdir.makepyfile( """ def test_passes(): pass class TestClass(object): def test_method(self): pass """ ) old = p1.dirpath().chdir() try: result = testdir.runpytest() finally: old.chdir() result.stdout.fnmatch_lines(["test_passes.py ..*", "* 2 pass*"]) assert result.ret == 0 def test_header_trailer_info(self, testdir): testdir.makepyfile( """ def test_passes(): pass """ ) result = testdir.runpytest() verinfo = ".".join(map(str, sys.version_info[:3])) result.stdout.fnmatch_lines( [ "*===== test session starts ====*", "platform %s -- Python %s*pytest-%s*py-%s*pluggy-%s" % ( sys.platform, verinfo, pytest.__version__, py.__version__, pluggy.__version__, ), "*test_header_trailer_info.py .*", "=* 1 passed*in *.[0-9][0-9] seconds *=", ] ) if pytest.config.pluginmanager.list_plugin_distinfo(): result.stdout.fnmatch_lines(["plugins: *"]) def test_showlocals(self, testdir): p1 = testdir.makepyfile( """ def test_showlocals(): x = 3 y = "x" * 5000 assert 0 """ ) result = testdir.runpytest(p1, "-l") result.stdout.fnmatch_lines( [ # "_ _ * Locals *", "x* = 3", "y* = 'xxxxxx*", ] ) def test_verbose_reporting(self, testdir, pytestconfig): p1 = testdir.makepyfile( """ import pytest def test_fail(): raise ValueError() def test_pass(): pass class TestClass(object): def test_skip(self): pytest.skip("hello") def test_gen(): def check(x): assert x == 1 yield check, 0 """ ) result = testdir.runpytest(p1, "-v") result.stdout.fnmatch_lines( [ "*test_verbose_reporting.py::test_fail *FAIL*", "*test_verbose_reporting.py::test_pass *PASS*", "*test_verbose_reporting.py::TestClass::test_skip *SKIP*", "*test_verbose_reporting.py::test_gen*0* *FAIL*", ] ) assert result.ret == 1 if not pytestconfig.pluginmanager.get_plugin("xdist"): pytest.skip("xdist plugin not installed") result = testdir.runpytest(p1, "-v", "-n 1") result.stdout.fnmatch_lines(["*FAIL*test_verbose_reporting.py::test_fail*"]) assert result.ret == 1 def test_quiet_reporting(self, testdir): p1 = testdir.makepyfile("def test_pass(): pass") result = testdir.runpytest(p1, "-q") s = result.stdout.str() assert "test session starts" not in s assert p1.basename not in s assert "===" not in s assert "passed" in s def test_more_quiet_reporting(self, testdir): p1 = testdir.makepyfile("def test_pass(): pass") result = testdir.runpytest(p1, "-qq") s = result.stdout.str() assert "test session starts" not in s assert p1.basename not in s assert "===" not in s assert "passed" not in s def test_report_collectionfinish_hook(self, testdir): testdir.makeconftest( """ def pytest_report_collectionfinish(config, startdir, items): return ['hello from hook: {0} items'.format(len(items))] """ ) testdir.makepyfile( """ import pytest @pytest.mark.parametrize('i', range(3)) def test(i): pass """ ) result = testdir.runpytest() result.stdout.fnmatch_lines(["collected 3 items", "hello from hook: 3 items"]) def test_fail_extra_reporting(testdir): testdir.makepyfile("def test_this(): assert 0") result = testdir.runpytest() assert "short test summary" not in result.stdout.str() result = testdir.runpytest("-rf") result.stdout.fnmatch_lines(["*test summary*", "FAIL*test_fail_extra_reporting*"]) def test_fail_reporting_on_pass(testdir): testdir.makepyfile("def test_this(): assert 1") result = testdir.runpytest("-rf") assert "short test summary" not in result.stdout.str() def test_pass_extra_reporting(testdir): testdir.makepyfile("def test_this(): assert 1") result = testdir.runpytest() assert "short test summary" not in result.stdout.str() result = testdir.runpytest("-rp") result.stdout.fnmatch_lines(["*test summary*", "PASS*test_pass_extra_reporting*"]) def test_pass_reporting_on_fail(testdir): testdir.makepyfile("def test_this(): assert 0") result = testdir.runpytest("-rp") assert "short test summary" not in result.stdout.str() def test_pass_output_reporting(testdir): testdir.makepyfile( """ def test_pass_has_output(): print("Four score and seven years ago...") def test_pass_no_output(): pass """ ) result = testdir.runpytest() s = result.stdout.str() assert "test_pass_has_output" not in s assert "Four score and seven years ago..." not in s assert "test_pass_no_output" not in s result = testdir.runpytest("-rP") result.stdout.fnmatch_lines( ["*test_pass_has_output*", "Four score and seven years ago..."] ) assert "test_pass_no_output" not in result.stdout.str() def test_color_yes(testdir): testdir.makepyfile("def test_this(): assert 1") result = testdir.runpytest("--color=yes") assert "test session starts" in result.stdout.str() assert "\x1b[1m" in result.stdout.str() def test_color_no(testdir): testdir.makepyfile("def test_this(): assert 1") result = testdir.runpytest("--color=no") assert "test session starts" in result.stdout.str() assert "\x1b[1m" not in result.stdout.str() @pytest.mark.parametrize("verbose", [True, False]) def test_color_yes_collection_on_non_atty(testdir, verbose): """skip collect progress report when working on non-terminals. #1397 """ testdir.makepyfile( """ import pytest @pytest.mark.parametrize('i', range(10)) def test_this(i): assert 1 """ ) args = ["--color=yes"] if verbose: args.append("-vv") result = testdir.runpytest(*args) assert "test session starts" in result.stdout.str() assert "\x1b[1m" in result.stdout.str() assert "collecting 10 items" not in result.stdout.str() if verbose: assert "collecting ..." in result.stdout.str() assert "collected 10 items" in result.stdout.str() def test_getreportopt(): class Config(object): class Option(object): reportchars = "" disable_warnings = True option = Option() config = Config() config.option.reportchars = "sf" assert getreportopt(config) == "sf" config.option.reportchars = "sfxw" assert getreportopt(config) == "sfx" config.option.reportchars = "sfx" config.option.disable_warnings = False assert getreportopt(config) == "sfxw" config.option.reportchars = "sfxw" config.option.disable_warnings = False assert getreportopt(config) == "sfxw" def test_terminalreporter_reportopt_addopts(testdir): testdir.makeini("[pytest]\naddopts=-rs") testdir.makepyfile( """ import pytest @pytest.fixture def tr(request): tr = request.config.pluginmanager.getplugin("terminalreporter") return tr def test_opt(tr): assert tr.hasopt('skipped') assert not tr.hasopt('qwe') """ ) result = testdir.runpytest() result.stdout.fnmatch_lines(["*1 passed*"]) def test_tbstyle_short(testdir): p = testdir.makepyfile( """ import pytest @pytest.fixture def arg(request): return 42 def test_opt(arg): x = 0 assert x """ ) result = testdir.runpytest("--tb=short") s = result.stdout.str() assert "arg = 42" not in s assert "x = 0" not in s result.stdout.fnmatch_lines(["*%s:8*" % p.basename, " assert x", "E assert*"]) result = testdir.runpytest() s = result.stdout.str() assert "x = 0" in s assert "assert x" in s def test_traceconfig(testdir, monkeypatch): result = testdir.runpytest("--traceconfig") result.stdout.fnmatch_lines(["*active plugins*"]) assert result.ret == EXIT_NOTESTSCOLLECTED class TestGenericReporting(object): """ this test class can be subclassed with a different option provider to run e.g. distributed tests. """ def test_collect_fail(self, testdir, option): testdir.makepyfile("import xyz\n") result = testdir.runpytest(*option.args) result.stdout.fnmatch_lines( ["ImportError while importing*", "*No module named *xyz*", "*1 error*"] ) def test_maxfailures(self, testdir, option): testdir.makepyfile( """ def test_1(): assert 0 def test_2(): assert 0 def test_3(): assert 0 """ ) result = testdir.runpytest("--maxfail=2", *option.args) result.stdout.fnmatch_lines( ["*def test_1():*", "*def test_2():*", "*2 failed*"] ) def test_tb_option(self, testdir, option): testdir.makepyfile( """ import pytest def g(): raise IndexError def test_func(): print (6*7) g() # --calling-- """ ) for tbopt in ["long", "short", "no"]: print("testing --tb=%s..." % tbopt) result = testdir.runpytest("--tb=%s" % tbopt) s = result.stdout.str() if tbopt == "long": assert "print (6*7)" in s else: assert "print (6*7)" not in s if tbopt != "no": assert "--calling--" in s assert "IndexError" in s else: assert "FAILURES" not in s assert "--calling--" not in s assert "IndexError" not in s def test_tb_crashline(self, testdir, option): p = testdir.makepyfile( """ import pytest def g(): raise IndexError def test_func1(): print (6*7) g() # --calling-- def test_func2(): assert 0, "hello" """ ) result = testdir.runpytest("--tb=line") bn = p.basename result.stdout.fnmatch_lines( ["*%s:3: IndexError*" % bn, "*%s:8: AssertionError: hello*" % bn] ) s = result.stdout.str() assert "def test_func2" not in s def test_pytest_report_header(self, testdir, option): testdir.makeconftest( """ def pytest_sessionstart(session): session.config._somevalue = 42 def pytest_report_header(config): return "hello: %s" % config._somevalue """ ) testdir.mkdir("a").join("conftest.py").write( """ def pytest_report_header(config, startdir): return ["line1", str(startdir)] """ ) result = testdir.runpytest("a") result.stdout.fnmatch_lines(["*hello: 42*", "line1", str(testdir.tmpdir)]) def test_show_capture(self, testdir): testdir.makepyfile( """ import sys import logging def test_one(): sys.stdout.write('!This is stdout!') sys.stderr.write('!This is stderr!') logging.warning('!This is a warning log msg!') assert False, 'Something failed' """ ) result = testdir.runpytest("--tb=short") result.stdout.fnmatch_lines( [ "!This is stdout!", "!This is stderr!", "*WARNING*!This is a warning log msg!", ] ) result = testdir.runpytest("--show-capture=all", "--tb=short") result.stdout.fnmatch_lines( [ "!This is stdout!", "!This is stderr!", "*WARNING*!This is a warning log msg!", ] ) stdout = testdir.runpytest("--show-capture=stdout", "--tb=short").stdout.str() assert "!This is stderr!" not in stdout assert "!This is stdout!" in stdout assert "!This is a warning log msg!" not in stdout stdout = testdir.runpytest("--show-capture=stderr", "--tb=short").stdout.str() assert "!This is stdout!" not in stdout assert "!This is stderr!" in stdout assert "!This is a warning log msg!" not in stdout stdout = testdir.runpytest("--show-capture=log", "--tb=short").stdout.str() assert "!This is stdout!" not in stdout assert "!This is stderr!" not in stdout assert "!This is a warning log msg!" in stdout stdout = testdir.runpytest("--show-capture=no", "--tb=short").stdout.str() assert "!This is stdout!" not in stdout assert "!This is stderr!" not in stdout assert "!This is a warning log msg!" not in stdout def test_show_capture_with_teardown_logs(self, testdir): """Ensure that the capturing of teardown logs honor --show-capture setting""" testdir.makepyfile( """ import logging import sys import pytest @pytest.fixture(scope="function", autouse="True") def hook_each_test(request): yield sys.stdout.write("!stdout!") sys.stderr.write("!stderr!") logging.warning("!log!") def test_func(): assert False """ ) result = testdir.runpytest("--show-capture=stdout", "--tb=short").stdout.str() assert "!stdout!" in result assert "!stderr!" not in result assert "!log!" not in result result = testdir.runpytest("--show-capture=stderr", "--tb=short").stdout.str() assert "!stdout!" not in result assert "!stderr!" in result assert "!log!" not in result result = testdir.runpytest("--show-capture=log", "--tb=short").stdout.str() assert "!stdout!" not in result assert "!stderr!" not in result assert "!log!" in result result = testdir.runpytest("--show-capture=no", "--tb=short").stdout.str() assert "!stdout!" not in result assert "!stderr!" not in result assert "!log!" not in result @pytest.mark.xfail("not hasattr(os, 'dup')") def test_fdopen_kept_alive_issue124(testdir): testdir.makepyfile( """ import os, sys k = [] def test_open_file_and_keep_alive(capfd): stdout = os.fdopen(1, 'w', 1) k.append(stdout) def test_close_kept_alive_file(): stdout = k.pop() stdout.close() """ ) result = testdir.runpytest() result.stdout.fnmatch_lines(["*2 passed*"]) def test_tbstyle_native_setup_error(testdir): testdir.makepyfile( """ import pytest @pytest.fixture def setup_error_fixture(): raise Exception("error in exception") def test_error_fixture(setup_error_fixture): pass """ ) result = testdir.runpytest("--tb=native") result.stdout.fnmatch_lines( ['*File *test_tbstyle_native_setup_error.py", line *, in setup_error_fixture*'] ) def test_terminal_summary(testdir): testdir.makeconftest( """ def pytest_terminal_summary(terminalreporter, exitstatus): w = terminalreporter w.section("hello") w.line("world") w.line("exitstatus: {0}".format(exitstatus)) """ ) result = testdir.runpytest() result.stdout.fnmatch_lines( """ *==== hello ====* world exitstatus: 5 """ ) @pytest.mark.filterwarnings("default") def test_terminal_summary_warnings_are_displayed(testdir): """Test that warnings emitted during pytest_terminal_summary are displayed. (#1305). """ testdir.makeconftest( """ import warnings def pytest_terminal_summary(terminalreporter): warnings.warn(UserWarning('internal warning')) """ ) result = testdir.runpytest() result.stdout.fnmatch_lines( ["*conftest.py:3:*internal warning", "*== 1 warnings in *"] ) assert "None" not in result.stdout.str() @pytest.mark.parametrize( "exp_color, exp_line, stats_arg", [ # The method under test only cares about the length of each # dict value, not the actual contents, so tuples of anything # suffice # Important statuses -- the highest priority of these always wins ("red", "1 failed", {"failed": (1,)}), ("red", "1 failed, 1 passed", {"failed": (1,), "passed": (1,)}), ("red", "1 error", {"error": (1,)}), ("red", "1 passed, 1 error", {"error": (1,), "passed": (1,)}), # (a status that's not known to the code) ("yellow", "1 weird", {"weird": (1,)}), ("yellow", "1 passed, 1 weird", {"weird": (1,), "passed": (1,)}), ("yellow", "1 warnings", {"warnings": (1,)}), ("yellow", "1 passed, 1 warnings", {"warnings": (1,), "passed": (1,)}), ("green", "5 passed", {"passed": (1, 2, 3, 4, 5)}), # "Boring" statuses. These have no effect on the color of the summary # line. Thus, if *every* test has a boring status, the summary line stays # at its default color, i.e. yellow, to warn the user that the test run # produced no useful information ("yellow", "1 skipped", {"skipped": (1,)}), ("green", "1 passed, 1 skipped", {"skipped": (1,), "passed": (1,)}), ("yellow", "1 deselected", {"deselected": (1,)}), ("green", "1 passed, 1 deselected", {"deselected": (1,), "passed": (1,)}), ("yellow", "1 xfailed", {"xfailed": (1,)}), ("green", "1 passed, 1 xfailed", {"xfailed": (1,), "passed": (1,)}), ("yellow", "1 xpassed", {"xpassed": (1,)}), ("green", "1 passed, 1 xpassed", {"xpassed": (1,), "passed": (1,)}), # Likewise if no tests were found at all ("yellow", "no tests ran", {}), # Test the empty-key special case ("yellow", "no tests ran", {"": (1,)}), ("green", "1 passed", {"": (1,), "passed": (1,)}), # A couple more complex combinations ( "red", "1 failed, 2 passed, 3 xfailed", {"passed": (1, 2), "failed": (1,), "xfailed": (1, 2, 3)}, ), ( "green", "1 passed, 2 skipped, 3 deselected, 2 xfailed", { "passed": (1,), "skipped": (1, 2), "deselected": (1, 2, 3), "xfailed": (1, 2), }, ), ], ) def test_summary_stats(exp_line, exp_color, stats_arg): print("Based on stats: %s" % stats_arg) print('Expect summary: "{}"; with color "{}"'.format(exp_line, exp_color)) (line, color) = build_summary_stats_line(stats_arg) print('Actually got: "{}"; with color "{}"'.format(line, color)) assert line == exp_line assert color == exp_color def test_no_trailing_whitespace_after_inifile_word(testdir): result = testdir.runpytest("") assert "inifile:\n" in result.stdout.str() testdir.makeini("[pytest]") result = testdir.runpytest("") assert "inifile: tox.ini\n" in result.stdout.str() class TestClassicOutputStyle(object): """Ensure classic output style works as expected (#3883)""" @pytest.fixture def test_files(self, testdir): testdir.makepyfile( **{ "test_one.py": "def test_one(): pass", "test_two.py": "def test_two(): assert 0", "sub/test_three.py": """ def test_three_1(): pass def test_three_2(): assert 0 def test_three_3(): pass """, } ) def test_normal_verbosity(self, testdir, test_files): result = testdir.runpytest("-o", "console_output_style=classic") result.stdout.fnmatch_lines( [ "test_one.py .", "test_two.py F", "sub{}test_three.py .F.".format(os.sep), "*2 failed, 3 passed in*", ] ) def test_verbose(self, testdir, test_files): result = testdir.runpytest("-o", "console_output_style=classic", "-v") result.stdout.fnmatch_lines( [ "test_one.py::test_one PASSED", "test_two.py::test_two FAILED", "sub{}test_three.py::test_three_1 PASSED".format(os.sep), "sub{}test_three.py::test_three_2 FAILED".format(os.sep), "sub{}test_three.py::test_three_3 PASSED".format(os.sep), "*2 failed, 3 passed in*", ] ) def test_quiet(self, testdir, test_files): result = testdir.runpytest("-o", "console_output_style=classic", "-q") result.stdout.fnmatch_lines([".F.F.", "*2 failed, 3 passed in*"]) class TestProgressOutputStyle(object): @pytest.fixture def many_tests_files(self, testdir): testdir.makepyfile( test_bar=""" import pytest @pytest.mark.parametrize('i', range(10)) def test_bar(i): pass """, test_foo=""" import pytest @pytest.mark.parametrize('i', range(5)) def test_foo(i): pass """, test_foobar=""" import pytest @pytest.mark.parametrize('i', range(5)) def test_foobar(i): pass """, ) def test_zero_tests_collected(self, testdir): """Some plugins (testmon for example) might issue pytest_runtest_logreport without any tests being actually collected (#2971).""" testdir.makeconftest( """ def pytest_collection_modifyitems(items, config): from _pytest.runner import CollectReport for node_id in ('nodeid1', 'nodeid2'): rep = CollectReport(node_id, 'passed', None, None) rep.when = 'passed' rep.duration = 0.1 config.hook.pytest_runtest_logreport(report=rep) """ ) output = testdir.runpytest() assert "ZeroDivisionError" not in output.stdout.str() output.stdout.fnmatch_lines(["=* 2 passed in *="]) def test_normal(self, many_tests_files, testdir): output = testdir.runpytest() output.stdout.re_match_lines( [ r"test_bar.py \.{10} \s+ \[ 50%\]", r"test_foo.py \.{5} \s+ \[ 75%\]", r"test_foobar.py \.{5} \s+ \[100%\]", ] ) def test_count(self, many_tests_files, testdir): testdir.makeini( """ [pytest] console_output_style = count """ ) output = testdir.runpytest() output.stdout.re_match_lines( [ r"test_bar.py \.{10} \s+ \[10/20\]", r"test_foo.py \.{5} \s+ \[15/20\]", r"test_foobar.py \.{5} \s+ \[20/20\]", ] ) def test_verbose(self, many_tests_files, testdir): output = testdir.runpytest("-v") output.stdout.re_match_lines( [ r"test_bar.py::test_bar\[0\] PASSED \s+ \[ 5%\]", r"test_foo.py::test_foo\[4\] PASSED \s+ \[ 75%\]", r"test_foobar.py::test_foobar\[4\] PASSED \s+ \[100%\]", ] ) def test_verbose_count(self, many_tests_files, testdir): testdir.makeini( """ [pytest] console_output_style = count """ ) output = testdir.runpytest("-v") output.stdout.re_match_lines( [ r"test_bar.py::test_bar\[0\] PASSED \s+ \[ 1/20\]", r"test_foo.py::test_foo\[4\] PASSED \s+ \[15/20\]", r"test_foobar.py::test_foobar\[4\] PASSED \s+ \[20/20\]", ] ) def test_xdist_normal(self, many_tests_files, testdir): pytest.importorskip("xdist") output = testdir.runpytest("-n2") output.stdout.re_match_lines([r"\.{20} \s+ \[100%\]"]) def test_xdist_normal_count(self, many_tests_files, testdir): pytest.importorskip("xdist") testdir.makeini( """ [pytest] console_output_style = count """ ) output = testdir.runpytest("-n2") output.stdout.re_match_lines([r"\.{20} \s+ \[20/20\]"]) def test_xdist_verbose(self, many_tests_files, testdir): pytest.importorskip("xdist") output = testdir.runpytest("-n2", "-v") output.stdout.re_match_lines_random( [ r"\[gw\d\] \[\s*\d+%\] PASSED test_bar.py::test_bar\[1\]", r"\[gw\d\] \[\s*\d+%\] PASSED test_foo.py::test_foo\[1\]", r"\[gw\d\] \[\s*\d+%\] PASSED test_foobar.py::test_foobar\[1\]", ] ) def test_capture_no(self, many_tests_files, testdir): output = testdir.runpytest("-s") output.stdout.re_match_lines( [r"test_bar.py \.{10}", r"test_foo.py \.{5}", r"test_foobar.py \.{5}"] ) output = testdir.runpytest("--capture=no") assert "%]" not in output.stdout.str() class TestProgressWithTeardown(object): """Ensure we show the correct percentages for tests that fail during teardown (#3088)""" @pytest.fixture def contest_with_teardown_fixture(self, testdir): testdir.makeconftest( """ import pytest @pytest.fixture def fail_teardown(): yield assert False """ ) @pytest.fixture def many_files(self, testdir, contest_with_teardown_fixture): testdir.makepyfile( test_bar=""" import pytest @pytest.mark.parametrize('i', range(5)) def test_bar(fail_teardown, i): pass """, test_foo=""" import pytest @pytest.mark.parametrize('i', range(15)) def test_foo(fail_teardown, i): pass """, ) def test_teardown_simple(self, testdir, contest_with_teardown_fixture): testdir.makepyfile( """ def test_foo(fail_teardown): pass """ ) output = testdir.runpytest() output.stdout.re_match_lines([r"test_teardown_simple.py \.E\s+\[100%\]"]) def test_teardown_with_test_also_failing( self, testdir, contest_with_teardown_fixture ): testdir.makepyfile( """ def test_foo(fail_teardown): assert False """ ) output = testdir.runpytest() output.stdout.re_match_lines( [r"test_teardown_with_test_also_failing.py FE\s+\[100%\]"] ) def test_teardown_many(self, testdir, many_files): output = testdir.runpytest() output.stdout.re_match_lines( [r"test_bar.py (\.E){5}\s+\[ 25%\]", r"test_foo.py (\.E){15}\s+\[100%\]"] ) def test_teardown_many_verbose(self, testdir, many_files): output = testdir.runpytest("-v") output.stdout.re_match_lines( [ r"test_bar.py::test_bar\[0\] PASSED\s+\[ 5%\]", r"test_bar.py::test_bar\[0\] ERROR\s+\[ 5%\]", r"test_bar.py::test_bar\[4\] PASSED\s+\[ 25%\]", r"test_bar.py::test_bar\[4\] ERROR\s+\[ 25%\]", ] ) def test_xdist_normal(self, many_files, testdir): pytest.importorskip("xdist") output = testdir.runpytest("-n2") output.stdout.re_match_lines([r"[\.E]{40} \s+ \[100%\]"])
from django.conf import settings from django.db import connection, router, transaction from django.db.backends import util from django.db.models import signals, get_model from django.db.models.fields import (AutoField, Field, IntegerField, PositiveIntegerField, PositiveSmallIntegerField, FieldDoesNotExist) from django.db.models.related import RelatedObject from django.db.models.query import QuerySet from django.db.models.query_utils import QueryWrapper from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _, string_concat, ungettext, ugettext from django.utils.functional import curry from django.core import exceptions from django import forms RECURSIVE_RELATIONSHIP_CONSTANT = 'self' pending_lookups = {} def add_lazy_relation(cls, field, relation, operation): """ Adds a lookup on ``cls`` when a related field is defined using a string, i.e.:: class MyModel(Model): fk = ForeignKey("AnotherModel") This string can be: * RECURSIVE_RELATIONSHIP_CONSTANT (i.e. "self") to indicate a recursive relation. * The name of a model (i.e "AnotherModel") to indicate another model in the same app. * An app-label and model name (i.e. "someapp.AnotherModel") to indicate another model in a different app. If the other model hasn't yet been loaded -- almost a given if you're using lazy relationships -- then the relation won't be set up until the class_prepared signal fires at the end of model initialization. operation is the work that must be performed once the relation can be resolved. """ # Check for recursive relations if relation == RECURSIVE_RELATIONSHIP_CONSTANT: app_label = cls._meta.app_label model_name = cls.__name__ else: # Look for an "app.Model" relation try: app_label, model_name = relation.split(".") except ValueError: # If we can't split, assume a model in current app app_label = cls._meta.app_label model_name = relation except AttributeError: # If it doesn't have a split it's actually a model class app_label = relation._meta.app_label model_name = relation._meta.object_name # Try to look up the related model, and if it's already loaded resolve the # string right away. If get_model returns None, it means that the related # model isn't loaded yet, so we need to pend the relation until the class # is prepared. model = get_model(app_label, model_name, False) if model: operation(field, model, cls) else: key = (app_label, model_name) value = (cls, field, operation) pending_lookups.setdefault(key, []).append(value) def do_pending_lookups(sender, **kwargs): """ Handle any pending relations to the sending model. Sent from class_prepared. """ key = (sender._meta.app_label, sender.__name__) for cls, field, operation in pending_lookups.pop(key, []): operation(field, sender, cls) signals.class_prepared.connect(do_pending_lookups) #HACK class RelatedField(object): def contribute_to_class(self, cls, name): sup = super(RelatedField, self) # Store the opts for related_query_name() self.opts = cls._meta if hasattr(sup, 'contribute_to_class'): sup.contribute_to_class(cls, name) if not cls._meta.abstract and self.rel.related_name: self.rel.related_name = self.rel.related_name % { 'class': cls.__name__.lower(), 'app_label': cls._meta.app_label.lower(), } other = self.rel.to if isinstance(other, basestring) or other._meta.pk is None: def resolve_related_class(field, model, cls): field.rel.to = model field.do_related_class(model, cls) add_lazy_relation(cls, self, other, resolve_related_class) else: self.do_related_class(other, cls) def set_attributes_from_rel(self): self.name = self.name or (self.rel.to._meta.object_name.lower() + '_' + self.rel.to._meta.pk.name) if self.verbose_name is None: self.verbose_name = self.rel.to._meta.verbose_name self.rel.field_name = self.rel.field_name or self.rel.to._meta.pk.name def do_related_class(self, other, cls): self.set_attributes_from_rel() self.related = RelatedObject(other, cls, self) if not cls._meta.abstract: self.contribute_to_related_class(other, self.related) def get_prep_lookup(self, lookup_type, value): if hasattr(value, 'prepare'): return value.prepare() if hasattr(value, '_prepare'): return value._prepare() # FIXME: lt and gt are explicitly allowed to make # get_(next/prev)_by_date work; other lookups are not allowed since that # gets messy pretty quick. This is a good candidate for some refactoring # in the future. if lookup_type in ['exact', 'gt', 'lt', 'gte', 'lte']: return self._pk_trace(value, 'get_prep_lookup', lookup_type) if lookup_type in ('range', 'in'): return [self._pk_trace(v, 'get_prep_lookup', lookup_type) for v in value] elif lookup_type == 'isnull': return [] raise TypeError("Related Field has invalid lookup: %s" % lookup_type) def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): if not prepared: value = self.get_prep_lookup(lookup_type, value) if hasattr(value, 'get_compiler'): value = value.get_compiler(connection=connection) if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'): # If the value has a relabel_aliases method, it will need to # be invoked before the final SQL is evaluated if hasattr(value, 'relabel_aliases'): return value if hasattr(value, 'as_sql'): sql, params = value.as_sql() else: sql, params = value._as_sql(connection=connection) return QueryWrapper(('(%s)' % sql), params) # FIXME: lt and gt are explicitly allowed to make # get_(next/prev)_by_date work; other lookups are not allowed since that # gets messy pretty quick. This is a good candidate for some refactoring # in the future. if lookup_type in ['exact', 'gt', 'lt', 'gte', 'lte']: return [self._pk_trace(value, 'get_db_prep_lookup', lookup_type, connection=connection, prepared=prepared)] if lookup_type in ('range', 'in'): return [self._pk_trace(v, 'get_db_prep_lookup', lookup_type, connection=connection, prepared=prepared) for v in value] elif lookup_type == 'isnull': return [] raise TypeError("Related Field has invalid lookup: %s" % lookup_type) def _pk_trace(self, value, prep_func, lookup_type, **kwargs): # Value may be a primary key, or an object held in a relation. # If it is an object, then we need to get the primary key value for # that object. In certain conditions (especially one-to-one relations), # the primary key may itself be an object - so we need to keep drilling # down until we hit a value that can be used for a comparison. v = value try: while True: v = getattr(v, v._meta.pk.name) except AttributeError: pass except exceptions.ObjectDoesNotExist: v = None field = self while field.rel: if hasattr(field.rel, 'field_name'): field = field.rel.to._meta.get_field(field.rel.field_name) else: field = field.rel.to._meta.pk if lookup_type in ('range', 'in'): v = [v] v = getattr(field, prep_func)(lookup_type, v, **kwargs) if isinstance(v, list): v = v[0] return v def related_query_name(self): # This method defines the name that can be used to identify this # related object in a table-spanning query. It uses the lower-cased # object_name by default, but this can be overridden with the # "related_name" option. return self.rel.related_name or self.opts.object_name.lower() class SingleRelatedObjectDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # a single "remote" value, on the class pointed to by a related field. # In the example "place.restaurant", the restaurant attribute is a # SingleRelatedObjectDescriptor instance. def __init__(self, related): self.related = related self.cache_name = related.get_cache_name() def __get__(self, instance, instance_type=None): if instance is None: return self try: return getattr(instance, self.cache_name) except AttributeError: params = {'%s__pk' % self.related.field.name: instance._get_pk_val()} db = router.db_for_read(self.related.model, instance=instance) rel_obj = self.related.model._base_manager.using(db).get(**params) setattr(instance, self.cache_name, rel_obj) return rel_obj def __set__(self, instance, value): if instance is None: raise AttributeError("%s must be accessed via instance" % self.related.opts.object_name) # The similarity of the code below to the code in # ReverseSingleRelatedObjectDescriptor is annoying, but there's a bunch # of small differences that would make a common base class convoluted. # If null=True, we can assign null here, but otherwise the value needs # to be an instance of the related class. if value is None and self.related.field.null == False: raise ValueError('Cannot assign None: "%s.%s" does not allow null values.' % (instance._meta.object_name, self.related.get_accessor_name())) elif value is not None and not isinstance(value, self.related.model): raise ValueError('Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (value, instance._meta.object_name, self.related.get_accessor_name(), self.related.opts.object_name)) elif value is not None: if instance._state.db is None: instance._state.db = router.db_for_write(instance.__class__, instance=value) elif value._state.db is None: value._state.db = router.db_for_write(value.__class__, instance=instance) elif value._state.db is not None and instance._state.db is not None: if not router.allow_relation(value, instance): raise ValueError('Cannot assign "%r": instance is on database "%s", value is on database "%s"' % (value, instance._state.db, value._state.db)) # Set the value of the related field to the value of the related object's related field setattr(value, self.related.field.attname, getattr(instance, self.related.field.rel.get_related_field().attname)) # Since we already know what the related object is, seed the related # object caches now, too. This avoids another db hit if you get the # object you just set. setattr(instance, self.cache_name, value) setattr(value, self.related.field.get_cache_name(), instance) class ReverseSingleRelatedObjectDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # a single "remote" value, on the class that defines the related field. # In the example "choice.poll", the poll attribute is a # ReverseSingleRelatedObjectDescriptor instance. def __init__(self, field_with_rel): self.field = field_with_rel def __get__(self, instance, instance_type=None): if instance is None: return self cache_name = self.field.get_cache_name() try: return getattr(instance, cache_name) except AttributeError: val = getattr(instance, self.field.attname) if val is None: # If NULL is an allowed value, return it. if self.field.null: return None raise self.field.rel.to.DoesNotExist other_field = self.field.rel.get_related_field() if other_field.rel: params = {'%s__pk' % self.field.rel.field_name: val} else: params = {'%s__exact' % self.field.rel.field_name: val} # If the related manager indicates that it should be used for # related fields, respect that. rel_mgr = self.field.rel.to._default_manager db = router.db_for_read(self.field.rel.to, instance=instance) if getattr(rel_mgr, 'use_for_related_fields', False): rel_obj = rel_mgr.using(db).get(**params) else: rel_obj = QuerySet(self.field.rel.to).using(db).get(**params) setattr(instance, cache_name, rel_obj) return rel_obj def __set__(self, instance, value): if instance is None: raise AttributeError("%s must be accessed via instance" % self._field.name) # If null=True, we can assign null here, but otherwise the value needs # to be an instance of the related class. if value is None and self.field.null == False: raise ValueError('Cannot assign None: "%s.%s" does not allow null values.' % (instance._meta.object_name, self.field.name)) elif value is not None and not isinstance(value, self.field.rel.to): raise ValueError('Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (value, instance._meta.object_name, self.field.name, self.field.rel.to._meta.object_name)) elif value is not None: if instance._state.db is None: instance._state.db = router.db_for_write(instance.__class__, instance=value) elif value._state.db is None: value._state.db = router.db_for_write(value.__class__, instance=instance) elif value._state.db is not None and instance._state.db is not None: if not router.allow_relation(value, instance): raise ValueError('Cannot assign "%r": instance is on database "%s", value is on database "%s"' % (value, instance._state.db, value._state.db)) # If we're setting the value of a OneToOneField to None, we need to clear # out the cache on any old related object. Otherwise, deleting the # previously-related object will also cause this object to be deleted, # which is wrong. if value is None: # Look up the previously-related object, which may still be available # since we've not yet cleared out the related field. # Use the cache directly, instead of the accessor; if we haven't # populated the cache, then we don't care - we're only accessing # the object to invalidate the accessor cache, so there's no # need to populate the cache just to expire it again. related = getattr(instance, self.field.get_cache_name(), None) # If we've got an old related object, we need to clear out its # cache. This cache also might not exist if the related object # hasn't been accessed yet. if related: cache_name = self.field.related.get_cache_name() try: delattr(related, cache_name) except AttributeError: pass # Set the value of the related field try: val = getattr(value, self.field.rel.get_related_field().attname) except AttributeError: val = None setattr(instance, self.field.attname, val) # Since we already know what the related object is, seed the related # object cache now, too. This avoids another db hit if you get the # object you just set. setattr(instance, self.field.get_cache_name(), value) class ForeignRelatedObjectsDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # multiple "remote" values and have a ForeignKey pointed at them by # some other model. In the example "poll.choice_set", the choice_set # attribute is a ForeignRelatedObjectsDescriptor instance. def __init__(self, related): self.related = related # RelatedObject instance def __get__(self, instance, instance_type=None): if instance is None: return self return self.create_manager(instance, self.related.model._default_manager.__class__) def __set__(self, instance, value): if instance is None: raise AttributeError("Manager must be accessed via instance") manager = self.__get__(instance) # If the foreign key can support nulls, then completely clear the related set. # Otherwise, just move the named objects into the set. if self.related.field.null: manager.clear() manager.add(*value) def delete_manager(self, instance): """ Returns a queryset based on the related model's base manager (rather than the default manager, as returned by __get__). Used by Model.delete(). """ return self.create_manager(instance, self.related.model._base_manager.__class__) def create_manager(self, instance, superclass): """ Creates the managers used by other methods (__get__() and delete()). """ rel_field = self.related.field rel_model = self.related.model class RelatedManager(superclass): def get_query_set(self): db = self._db or router.db_for_read(rel_model, instance=instance) return superclass.get_query_set(self).using(db).filter(**(self.core_filters)) def add(self, *objs): for obj in objs: if not isinstance(obj, self.model): raise TypeError("'%s' instance expected" % self.model._meta.object_name) setattr(obj, rel_field.name, instance) obj.save() add.alters_data = True def create(self, **kwargs): kwargs.update({rel_field.name: instance}) db = router.db_for_write(rel_model, instance=instance) return super(RelatedManager, self).using(db).create(**kwargs) create.alters_data = True def get_or_create(self, **kwargs): # Update kwargs with the related object that this # ForeignRelatedObjectsDescriptor knows about. kwargs.update({rel_field.name: instance}) db = router.db_for_write(rel_model, instance=instance) return super(RelatedManager, self).using(db).get_or_create(**kwargs) get_or_create.alters_data = True # remove() and clear() are only provided if the ForeignKey can have a value of null. if rel_field.null: def remove(self, *objs): val = getattr(instance, rel_field.rel.get_related_field().attname) for obj in objs: # Is obj actually part of this descriptor set? if getattr(obj, rel_field.attname) == val: setattr(obj, rel_field.name, None) obj.save() else: raise rel_field.rel.to.DoesNotExist("%r is not related to %r." % (obj, instance)) remove.alters_data = True def clear(self): for obj in self.all(): setattr(obj, rel_field.name, None) obj.save() clear.alters_data = True manager = RelatedManager() attname = rel_field.rel.get_related_field().name manager.core_filters = {'%s__%s' % (rel_field.name, attname): getattr(instance, attname)} manager.model = self.related.model return manager def create_many_related_manager(superclass, rel=False): """Creates a manager that subclasses 'superclass' (which is a Manager) and adds behavior for many-to-many related objects.""" through = rel.through class ManyRelatedManager(superclass): def __init__(self, model=None, core_filters=None, instance=None, symmetrical=None, join_table=None, source_field_name=None, target_field_name=None, reverse=False): super(ManyRelatedManager, self).__init__() self.core_filters = core_filters self.model = model self.symmetrical = symmetrical self.instance = instance self.source_field_name = source_field_name self.target_field_name = target_field_name self.through = through self._pk_val = self.instance.pk self.reverse = reverse if self._pk_val is None: raise ValueError("%r instance needs to have a primary key value before a many-to-many relationship can be used." % instance.__class__.__name__) def get_query_set(self): db = self._db or router.db_for_read(self.instance.__class__, instance=self.instance) return superclass.get_query_set(self).using(db)._next_is_sticky().filter(**(self.core_filters)) # If the ManyToMany relation has an intermediary model, # the add and remove methods do not exist. if rel.through._meta.auto_created: def add(self, *objs): self._add_items(self.source_field_name, self.target_field_name, *objs) # If this is a symmetrical m2m relation to self, add the mirror entry in the m2m table if self.symmetrical: self._add_items(self.target_field_name, self.source_field_name, *objs) add.alters_data = True def remove(self, *objs): self._remove_items(self.source_field_name, self.target_field_name, *objs) # If this is a symmetrical m2m relation to self, remove the mirror entry in the m2m table if self.symmetrical: self._remove_items(self.target_field_name, self.source_field_name, *objs) remove.alters_data = True def clear(self): self._clear_items(self.source_field_name) # If this is a symmetrical m2m relation to self, clear the mirror entry in the m2m table if self.symmetrical: self._clear_items(self.target_field_name) clear.alters_data = True def create(self, **kwargs): # This check needs to be done here, since we can't later remove this # from the method lookup table, as we do with add and remove. if not rel.through._meta.auto_created: opts = through._meta raise AttributeError("Cannot use create() on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)) db = router.db_for_write(self.instance.__class__, instance=self.instance) new_obj = super(ManyRelatedManager, self).using(db).create(**kwargs) self.add(new_obj) return new_obj create.alters_data = True def get_or_create(self, **kwargs): db = router.db_for_write(self.instance.__class__, instance=self.instance) obj, created = \ super(ManyRelatedManager, self).using(db).get_or_create(**kwargs) # We only need to add() if created because if we got an object back # from get() then the relationship already exists. if created: self.add(obj) return obj, created get_or_create.alters_data = True def _add_items(self, source_field_name, target_field_name, *objs): # join_table: name of the m2m link table # source_field_name: the PK fieldname in join_table for the source object # target_field_name: the PK fieldname in join_table for the target object # *objs - objects to add. Either object instances, or primary keys of object instances. # If there aren't any objects, there is nothing to do. from django.db.models import Model if objs: new_ids = set() for obj in objs: if isinstance(obj, self.model): if not router.allow_relation(obj, self.instance): raise ValueError('Cannot add "%r": instance is on database "%s", value is on database "%s"' % (obj, self.instance._state.db, obj._state.db)) new_ids.add(obj.pk) elif isinstance(obj, Model): raise TypeError("'%s' instance expected" % self.model._meta.object_name) else: new_ids.add(obj) db = router.db_for_write(self.through.__class__, instance=self.instance) vals = self.through._default_manager.using(db).values_list(target_field_name, flat=True) vals = vals.filter(**{ source_field_name: self._pk_val, '%s__in' % target_field_name: new_ids, }) new_ids = new_ids - set(vals) if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are inserting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action='pre_add', instance=self.instance, reverse=self.reverse, model=self.model, pk_set=new_ids) # Add the ones that aren't there already for obj_id in new_ids: self.through._default_manager.using(db).create(**{ '%s_id' % source_field_name: self._pk_val, '%s_id' % target_field_name: obj_id, }) if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are inserting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action='post_add', instance=self.instance, reverse=self.reverse, model=self.model, pk_set=new_ids) def _remove_items(self, source_field_name, target_field_name, *objs): # source_col_name: the PK colname in join_table for the source object # target_col_name: the PK colname in join_table for the target object # *objs - objects to remove # If there aren't any objects, there is nothing to do. if objs: # Check that all the objects are of the right type old_ids = set() for obj in objs: if isinstance(obj, self.model): old_ids.add(obj.pk) else: old_ids.add(obj) if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are deleting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action="pre_remove", instance=self.instance, reverse=self.reverse, model=self.model, pk_set=old_ids) # Remove the specified objects from the join table db = router.db_for_write(self.through.__class__, instance=self.instance) self.through._default_manager.using(db).filter(**{ source_field_name: self._pk_val, '%s__in' % target_field_name: old_ids }).delete() if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are deleting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action="post_remove", instance=self.instance, reverse=self.reverse, model=self.model, pk_set=old_ids) def _clear_items(self, source_field_name): # source_col_name: the PK colname in join_table for the source object if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are clearing the # duplicate data rows for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action="pre_clear", instance=self.instance, reverse=self.reverse, model=self.model, pk_set=None) db = router.db_for_write(self.through.__class__, instance=self.instance) self.through._default_manager.using(db).filter(**{ source_field_name: self._pk_val }).delete() if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are clearing the # duplicate data rows for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action="post_clear", instance=self.instance, reverse=self.reverse, model=self.model, pk_set=None) return ManyRelatedManager class ManyRelatedObjectsDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # multiple "remote" values and have a ManyToManyField pointed at them by # some other model (rather than having a ManyToManyField themselves). # In the example "publication.article_set", the article_set attribute is a # ManyRelatedObjectsDescriptor instance. def __init__(self, related): self.related = related # RelatedObject instance def __get__(self, instance, instance_type=None): if instance is None: return self # Dynamically create a class that subclasses the related # model's default manager. rel_model = self.related.model superclass = rel_model._default_manager.__class__ RelatedManager = create_many_related_manager(superclass, self.related.field.rel) manager = RelatedManager( model=rel_model, core_filters={'%s__pk' % self.related.field.name: instance._get_pk_val()}, instance=instance, symmetrical=False, source_field_name=self.related.field.m2m_reverse_field_name(), target_field_name=self.related.field.m2m_field_name(), reverse=True ) return manager def __set__(self, instance, value): if instance is None: raise AttributeError("Manager must be accessed via instance") if not self.related.field.rel.through._meta.auto_created: opts = self.related.field.rel.through._meta raise AttributeError("Cannot set values on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)) manager = self.__get__(instance) manager.clear() manager.add(*value) class ReverseManyRelatedObjectsDescriptor(object): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # multiple "remote" values and have a ManyToManyField defined in their # model (rather than having another model pointed *at* them). # In the example "article.publications", the publications attribute is a # ReverseManyRelatedObjectsDescriptor instance. def __init__(self, m2m_field): self.field = m2m_field def _through(self): # through is provided so that you have easy access to the through # model (Book.authors.through) for inlines, etc. This is done as # a property to ensure that the fully resolved value is returned. return self.field.rel.through through = property(_through) def __get__(self, instance, instance_type=None): if instance is None: return self # Dynamically create a class that subclasses the related # model's default manager. rel_model=self.field.rel.to superclass = rel_model._default_manager.__class__ RelatedManager = create_many_related_manager(superclass, self.field.rel) manager = RelatedManager( model=rel_model, core_filters={'%s__pk' % self.field.related_query_name(): instance._get_pk_val()}, instance=instance, symmetrical=self.field.rel.symmetrical, source_field_name=self.field.m2m_field_name(), target_field_name=self.field.m2m_reverse_field_name(), reverse=False ) return manager def __set__(self, instance, value): if instance is None: raise AttributeError("Manager must be accessed via instance") if not self.field.rel.through._meta.auto_created: opts = self.field.rel.through._meta raise AttributeError("Cannot set values on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)) manager = self.__get__(instance) manager.clear() manager.add(*value) class ManyToOneRel(object): def __init__(self, to, field_name, related_name=None, limit_choices_to=None, lookup_overrides=None, parent_link=False): try: to._meta except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "'to' must be either a model, a model name or the string %r" % RECURSIVE_RELATIONSHIP_CONSTANT self.to, self.field_name = to, field_name self.related_name = related_name if limit_choices_to is None: limit_choices_to = {} self.limit_choices_to = limit_choices_to self.lookup_overrides = lookup_overrides or {} self.multiple = True self.parent_link = parent_link def is_hidden(self): "Should the related object be hidden?" return self.related_name and self.related_name[-1] == '+' def get_related_field(self): """ Returns the Field in the 'to' object to which this relationship is tied. """ data = self.to._meta.get_field_by_name(self.field_name) if not data[2]: raise FieldDoesNotExist("No related field named '%s'" % self.field_name) return data[0] class OneToOneRel(ManyToOneRel): def __init__(self, to, field_name, related_name=None, limit_choices_to=None, lookup_overrides=None, parent_link=False): super(OneToOneRel, self).__init__(to, field_name, related_name=related_name, limit_choices_to=limit_choices_to, lookup_overrides=lookup_overrides, parent_link=parent_link) self.multiple = False class ManyToManyRel(object): def __init__(self, to, related_name=None, limit_choices_to=None, symmetrical=True, through=None): self.to = to self.related_name = related_name if limit_choices_to is None: limit_choices_to = {} self.limit_choices_to = limit_choices_to self.symmetrical = symmetrical self.multiple = True self.through = through def is_hidden(self): "Should the related object be hidden?" return self.related_name and self.related_name[-1] == '+' def get_related_field(self): """ Returns the field in the to' object to which this relationship is tied (this is always the primary key on the target model). Provided for symmetry with ManyToOneRel. """ return self.to._meta.pk class ForeignKey(RelatedField, Field): empty_strings_allowed = False default_error_messages = { 'invalid': _('Model %(model)s with pk %(pk)r does not exist.') } description = _("Foreign Key (type determined by related field)") def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs): try: to_name = to._meta.object_name.lower() except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) else: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) # For backwards compatibility purposes, we need to *try* and set # the to_field during FK construction. It won't be guaranteed to # be correct until contribute_to_class is called. Refs #12190. to_field = to_field or (to._meta.pk and to._meta.pk.name) kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = rel_class(to, to_field, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), lookup_overrides=kwargs.pop('lookup_overrides', None), parent_link=kwargs.pop('parent_link', False)) Field.__init__(self, **kwargs) self.db_index = True def validate(self, value, model_instance): if self.rel.parent_link: return super(ForeignKey, self).validate(value, model_instance) if value is None: return qs = self.rel.to._default_manager.filter(**{self.rel.field_name:value}) qs = qs.complex_filter(self.rel.limit_choices_to) if not qs.exists(): raise exceptions.ValidationError(self.error_messages['invalid'] % { 'model': self.rel.to._meta.verbose_name, 'pk': value}) def get_attname(self): return '%s_id' % self.name def get_validator_unique_lookup_type(self): return '%s__%s__exact' % (self.name, self.rel.get_related_field().name) def get_default(self): "Here we check if the default value is an object and return the to_field if so." field_default = super(ForeignKey, self).get_default() if isinstance(field_default, self.rel.to): return getattr(field_default, self.rel.get_related_field().attname) return field_default def get_db_prep_save(self, value, connection): if value == '' or value == None: return None else: return self.rel.get_related_field().get_db_prep_save(value, connection=connection) def value_to_string(self, obj): if not obj: # In required many-to-one fields with only one available choice, # select that one available choice. Note: For SelectFields # we have to check that the length of choices is *2*, not 1, # because SelectFields always have an initial "blank" value. if not self.blank and self.choices: choice_list = self.get_choices_default() if len(choice_list) == 2: return smart_unicode(choice_list[1][0]) return Field.value_to_string(self, obj) def contribute_to_class(self, cls, name): super(ForeignKey, self).contribute_to_class(cls, name) setattr(cls, self.name, ReverseSingleRelatedObjectDescriptor(self)) if isinstance(self.rel.to, basestring): target = self.rel.to else: target = self.rel.to._meta.db_table cls._meta.duplicate_targets[self.column] = (target, "o2m") def contribute_to_related_class(self, cls, related): # Internal FK's - i.e., those with a related name ending with '+' - # don't get a related descriptor. if not self.rel.is_hidden(): setattr(cls, related.get_accessor_name(), ForeignRelatedObjectsDescriptor(related)) if self.rel.field_name is None: self.rel.field_name = cls._meta.pk.name def formfield(self, **kwargs): db = kwargs.pop('using', None) defaults = { 'form_class': forms.ModelChoiceField, 'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to), 'to_field_name': self.rel.field_name, } defaults.update(kwargs) return super(ForeignKey, self).formfield(**defaults) def db_type(self, connection): # The database column type of a ForeignKey is the column type # of the field to which it points. An exception is if the ForeignKey # points to an AutoField/PositiveIntegerField/PositiveSmallIntegerField, # in which case the column type is simply that of an IntegerField. # If the database needs similar types for key fields however, the only # thing we can do is making AutoField an IntegerField. rel_field = self.rel.get_related_field() return rel_field.related_db_type(connection=connection) class OneToOneField(ForeignKey): """ A OneToOneField is essentially the same as a ForeignKey, with the exception that always carries a "unique" constraint with it and the reverse relation always returns the object pointed to (since there will only ever be one), rather than returning a list. """ description = _("One-to-one relationship") def __init__(self, to, to_field=None, **kwargs): kwargs['unique'] = True super(OneToOneField, self).__init__(to, to_field, OneToOneRel, **kwargs) def contribute_to_related_class(self, cls, related): setattr(cls, related.get_accessor_name(), SingleRelatedObjectDescriptor(related)) def formfield(self, **kwargs): if self.rel.parent_link: return None return super(OneToOneField, self).formfield(**kwargs) def save_form_data(self, instance, data): if isinstance(data, self.rel.to): setattr(instance, self.name, data) else: setattr(instance, self.attname, data) def create_many_to_many_intermediary_model(field, klass): from django.db import models managed = True if isinstance(field.rel.to, basestring) and field.rel.to != RECURSIVE_RELATIONSHIP_CONSTANT: to_model = field.rel.to to = to_model.split('.')[-1] def set_managed(field, model, cls): field.rel.through._meta.managed = model._meta.managed or cls._meta.managed add_lazy_relation(klass, field, to_model, set_managed) elif isinstance(field.rel.to, basestring): to = klass._meta.object_name to_model = klass managed = klass._meta.managed else: to = field.rel.to._meta.object_name to_model = field.rel.to managed = klass._meta.managed or to_model._meta.managed name = '%s_%s' % (klass._meta.object_name, field.name) if field.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to == klass._meta.object_name: from_ = 'from_%s' % to.lower() to = 'to_%s' % to.lower() else: from_ = klass._meta.object_name.lower() to = to.lower() meta = type('Meta', (object,), { 'db_table': field._get_m2m_db_table(klass._meta), 'managed': managed, 'auto_created': klass, 'app_label': klass._meta.app_label, 'unique_together': (from_, to), 'verbose_name': '%(from)s-%(to)s relationship' % {'from': from_, 'to': to}, 'verbose_name_plural': '%(from)s-%(to)s relationships' % {'from': from_, 'to': to}, }) # Construct and return the new class. return type(name, (models.Model,), { 'Meta': meta, '__module__': klass.__module__, from_: models.ForeignKey(klass, related_name='%s+' % name), to: models.ForeignKey(to_model, related_name='%s+' % name) }) class ManyToManyField(RelatedField, Field): description = _("Many-to-many relationship") def __init__(self, to, **kwargs): try: assert not to._meta.abstract, "%s cannot define a relation with abstract class %s" % (self.__class__.__name__, to._meta.object_name) except AttributeError: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) kwargs['verbose_name'] = kwargs.get('verbose_name', None) kwargs['rel'] = ManyToManyRel(to, related_name=kwargs.pop('related_name', None), limit_choices_to=kwargs.pop('limit_choices_to', None), symmetrical=kwargs.pop('symmetrical', to==RECURSIVE_RELATIONSHIP_CONSTANT), through=kwargs.pop('through', None)) self.db_table = kwargs.pop('db_table', None) if kwargs['rel'].through is not None: assert self.db_table is None, "Cannot specify a db_table if an intermediary model is used." Field.__init__(self, **kwargs) msg = _('Hold down "Control", or "Command" on a Mac, to select more than one.') self.help_text = string_concat(self.help_text, ' ', msg) def get_choices_default(self): return Field.get_choices(self, include_blank=False) def _get_m2m_db_table(self, opts): "Function that can be curried to provide the m2m table name for this relation" if self.rel.through is not None: return self.rel.through._meta.db_table elif self.db_table: return self.db_table else: return util.truncate_name('%s_%s' % (opts.db_table, self.name), connection.ops.max_name_length()) def _get_m2m_attr(self, related, attr): "Function that can be curried to provide the source accessor or DB column name for the m2m table" cache_attr = '_m2m_%s_cache' % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) for f in self.rel.through._meta.fields: if hasattr(f,'rel') and f.rel and f.rel.to == related.model: setattr(self, cache_attr, getattr(f, attr)) return getattr(self, cache_attr) def _get_m2m_reverse_attr(self, related, attr): "Function that can be curried to provide the related accessor or DB column name for the m2m table" cache_attr = '_m2m_reverse_%s_cache' % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) found = False for f in self.rel.through._meta.fields: if hasattr(f,'rel') and f.rel and f.rel.to == related.parent_model: if related.model == related.parent_model: # If this is an m2m-intermediate to self, # the first foreign key you find will be # the source column. Keep searching for # the second foreign key. if found: setattr(self, cache_attr, getattr(f, attr)) break else: found = True else: setattr(self, cache_attr, getattr(f, attr)) break return getattr(self, cache_attr) def isValidIDList(self, field_data, all_data): "Validates that the value is a valid list of foreign keys" mod = self.rel.to try: pks = map(int, field_data.split(',')) except ValueError: # the CommaSeparatedIntegerField validator will catch this error return objects = mod._default_manager.in_bulk(pks) if len(objects) != len(pks): badkeys = [k for k in pks if k not in objects] raise exceptions.ValidationError( ungettext("Please enter valid %(self)s IDs. The value %(value)r is invalid.", "Please enter valid %(self)s IDs. The values %(value)r are invalid.", len(badkeys)) % { 'self': self.verbose_name, 'value': len(badkeys) == 1 and badkeys[0] or tuple(badkeys), }) def value_to_string(self, obj): data = '' if obj: qs = getattr(obj, self.name).all() data = [instance._get_pk_val() for instance in qs] else: # In required many-to-many fields with only one available choice, # select that one available choice. if not self.blank: choices_list = self.get_choices_default() if len(choices_list) == 1: data = [choices_list[0][0]] return smart_unicode(data) def contribute_to_class(self, cls, name): # To support multiple relations to self, it's useful to have a non-None # related name on symmetrical relations for internal reasons. The # concept doesn't make a lot of sense externally ("you want me to # specify *what* on my non-reversible relation?!"), so we set it up # automatically. The funky name reduces the chance of an accidental # clash. if self.rel.symmetrical and (self.rel.to == "self" or self.rel.to == cls._meta.object_name): self.rel.related_name = "%s_rel_+" % name super(ManyToManyField, self).contribute_to_class(cls, name) # The intermediate m2m model is not auto created if: # 1) There is a manually specified intermediate, or # 2) The class owning the m2m field is abstract. if not self.rel.through and not cls._meta.abstract: self.rel.through = create_many_to_many_intermediary_model(self, cls) # Add the descriptor for the m2m relation setattr(cls, self.name, ReverseManyRelatedObjectsDescriptor(self)) # Set up the accessor for the m2m table name for the relation self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta) # Populate some necessary rel arguments so that cross-app relations # work correctly. if isinstance(self.rel.through, basestring): def resolve_through_model(field, model, cls): field.rel.through = model add_lazy_relation(cls, self, self.rel.through, resolve_through_model) if isinstance(self.rel.to, basestring): target = self.rel.to else: target = self.rel.to._meta.db_table cls._meta.duplicate_targets[self.column] = (target, "m2m") def contribute_to_related_class(self, cls, related): # Internal M2Ms (i.e., those with a related name ending with '+') # don't get a related descriptor. if not self.rel.is_hidden(): setattr(cls, related.get_accessor_name(), ManyRelatedObjectsDescriptor(related)) # Set up the accessors for the column names on the m2m table self.m2m_column_name = curry(self._get_m2m_attr, related, 'column') self.m2m_reverse_name = curry(self._get_m2m_reverse_attr, related, 'column') self.m2m_field_name = curry(self._get_m2m_attr, related, 'name') self.m2m_reverse_field_name = curry(self._get_m2m_reverse_attr, related, 'name') def set_attributes_from_rel(self): pass def value_from_object(self, obj): "Returns the value of this field in the given model instance." return getattr(obj, self.attname).all() def save_form_data(self, instance, data): setattr(instance, self.attname, data) def formfield(self, **kwargs): db = kwargs.pop('using', None) defaults = { 'form_class': forms.ModelMultipleChoiceField, 'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to) } defaults.update(kwargs) # If initial is passed in, it's a list of related objects, but the # MultipleChoiceField takes a list of IDs. if defaults.get('initial') is not None: initial = defaults['initial'] if callable(initial): initial = initial() defaults['initial'] = [i._get_pk_val() for i in initial] return super(ManyToManyField, self).formfield(**defaults) def db_type(self, connection): # A ManyToManyField is not represented by a single column, # so return None. return None
# -*- coding: utf-8 -*- # # Copyright (c) 2010, Monash e-Research Centre # (Monash University, Australia) # Copyright (c) 2010, VeRSI Consortium # (Victorian eResearch Strategic Initiative, Australia) # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the VeRSI, the VeRSI Consortium members, nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # """ test_models.py http://docs.djangoproject.com/en/dev/topics/testing/ .. moduleauthor:: Russell Sim <[email protected]> """ from django.test import TestCase class ModelTestCase(TestCase): urls = 'tardis.tardis_portal.tests.urls' def setUp(self): from django.contrib.auth.models import User user = 'tardis_user1' pwd = 'secret' email = '' self.user = User.objects.create_user(user, email, pwd) def test_experiment(self): from tardis.tardis_portal import models from django.conf import settings from os import path exp = models.Experiment(title='test exp1', institution_name='monash', created_by=self.user, ) exp.save() self.assertEqual(exp.title, 'test exp1') self.assertEqual(exp.url, None) self.assertEqual(exp.institution_name, 'monash') self.assertEqual(exp.approved, False) self.assertEqual(exp.handle, None) self.assertEqual(exp.created_by, self.user) self.assertEqual(exp.public, False) self.assertEqual(exp.get_absolute_url(), '/test/experiment/view/1/', exp.get_absolute_url() + ' != /test/experiment/view/1/') self.assertEqual(exp.get_or_create_directory(), path.join(settings.FILE_STORE_PATH, str(exp.id))) def test_authors(self): from tardis.tardis_portal import models exp = models.Experiment(title='test exp2', institution_name='monash', created_by=self.user, ) exp.save() models.Author_Experiment(experiment=exp, author='nigel', order=0).save() exp = models.Experiment(title='test exp1', institution_name='monash', created_by=self.user, ) exp.save() ae1 = models.Author_Experiment(experiment=exp, author='steve', order=100) ae1.save() ae2 = models.Author_Experiment(experiment=exp, author='russell', order=1) ae2.save() ae3 = models.Author_Experiment(experiment=exp, author='uli', order=50) ae3.save() authors = exp.author_experiment_set.all() # confirm that there are 2 authors self.assertEqual(len(authors), 3) self.assertTrue(ae1 in authors) self.assertTrue(ae2 in authors) self.assertTrue(ae3 == authors[1]) def test_datafile(self): from tardis.tardis_portal import models exp = models.Experiment(title='test exp1', institution_name='monash', approved=True, created_by=self.user, public=False, ) exp.save() dataset = models.Dataset(description="dataset description...", experiment=exp) dataset.save() df_file = models.Dataset_File(dataset=dataset, filename='file.txt', url='path/file.txt', ) df_file.save() self.assertEqual(df_file.filename, 'file.txt') self.assertEqual(df_file.url, 'path/file.txt') self.assertEqual(df_file.protocol, '') self.assertEqual(df_file.dataset, dataset) self.assertEqual(df_file.size, '') self.assertEqual(df_file.get_download_url(), '/test/download/datafile/1/') df_file = models.Dataset_File(dataset=dataset, filename='file1.txt', url='path/file1.txt', protocol='vbl', ) df_file.save() self.assertEqual(df_file.filename, 'file1.txt') self.assertEqual(df_file.url, 'path/file1.txt') self.assertEqual(df_file.protocol, 'vbl') self.assertEqual(df_file.dataset, dataset) self.assertEqual(df_file.size, '') self.assertEqual(df_file.get_download_url(), '/test/vbl/download/datafile/2/') df_file = models.Dataset_File(dataset=dataset, filename='file1.txt', url='http://localhost:8080/filestore/file1.txt', protocol='', ) df_file.save() self.assertEqual(df_file.filename, 'file1.txt') self.assertEqual(df_file.url, 'http://localhost:8080/filestore/file1.txt') self.assertEqual(df_file.protocol, '') self.assertEqual(df_file.dataset, dataset) self.assertEqual(df_file.size, '') self.assertEqual(df_file.get_download_url(), '/test/download/datafile/3/') # check conversion of b64encoded images back into files def test_parameter(self): from tardis.tardis_portal import models exp = models.Experiment(title='test exp1', institution_name='Australian Synchrotron', approved=True, created_by=self.user, public=True, ) exp.save() dataset = models.Dataset(description="dataset description", experiment=exp) dataset.save() df_file = models.Dataset_File(dataset=dataset, filename='file.txt', url='path/file.txt', ) df_file.save() df_schema = models.Schema(namespace='http://www.cern.ch/felzmann/schema1.xml', type=models.Schema.DATAFILE) df_schema.save() ds_schema = models.Schema(namespace='http://www.cern.ch/felzmann/schema2.xml', type=models.Schema.DATASET) ds_schema.save() exp_schema = models.Schema(namespace='http://www.cern.ch/felzmann/schema3.xml', type=models.Schema.EXPERIMENT) exp_schema.save() df_parname = models.ParameterName(schema=df_schema, name='name', full_name='full_name', units='image/jpg', data_type=models.ParameterName.FILENAME) df_parname.save() ds_parname = models.ParameterName(schema=ds_schema, name='name', full_name='full_name', units='image/jpg', data_type=models.ParameterName.FILENAME) ds_parname.save() exp_parname = models.ParameterName(schema=exp_schema, name='name', full_name='full_name', units='image/jpg', data_type=models.ParameterName.FILENAME) exp_parname.save() df_parset = models.DatafileParameterSet(schema=df_schema, dataset_file=df_file) df_parset.save() ds_parset = models.DatasetParameterSet(schema=ds_schema, dataset=dataset) ds_parset.save() exp_parset = models.ExperimentParameterSet(schema=exp_schema, experiment=exp) exp_parset.save() from base64 import b64encode from os import path from os import remove filename = path.join(path.dirname(__file__), 'test.jpg') df_parameter = models.DatafileParameter(name=df_parname, parameterset=df_parset, string_value=b64encode(open(filename).read())) df_parameter.save() ds_parameter = models.DatasetParameter(name=ds_parname, parameterset=ds_parset, string_value=b64encode(open(filename).read())) ds_parameter.save() exp_parameter = models.ExperimentParameter(name=exp_parname, parameterset=exp_parset, string_value=b64encode(open(filename).read())) exp_parameter.save() self.assertEqual("<img src='/test/DatafileImage/load/%i/' />" % df_parameter.id, df_parameter.get()) self.assertEqual("<img src='/test/DatasetImage/load/%i/' />" % ds_parameter.id, ds_parameter.get()) self.assertEqual("<img src='/test/ExperimentImage/load/%i/' />" % exp_parameter.id, exp_parameter.get()) remove(path.join(exp.get_or_create_directory(), df_parameter.string_value)) remove(path.join(exp.get_or_create_directory(), ds_parameter.string_value)) remove(path.join(exp.get_or_create_directory(), exp_parameter.string_value))
"""Kernel Principal Components Analysis""" # Author: Mathieu Blondel <[email protected]> # License: BSD 3 clause import numpy as np from scipy import linalg from ..base import BaseEstimator, TransformerMixin from ..exceptions import NotFittedError from ..metrics.pairwise import pairwise_kernels from ..preprocessing import KernelCenterer from ..utils import check_random_state from ..utils.arpack import eigsh from ..utils.validation import check_is_fitted class KernelPCA(BaseEstimator, TransformerMixin): """Kernel Principal component analysis (KPCA) Non-linear dimensionality reduction through the use of kernels (see :ref:`metrics`). Read more in the :ref:`User Guide <kernel_PCA>`. Parameters ---------- n_components: int or None Number of components. If None, all non-zero components are kept. kernel: "linear" | "poly" | "rbf" | "sigmoid" | "cosine" | "precomputed" Kernel. Default: "linear" degree : int, default=3 Degree for poly kernels. Ignored by other kernels. gamma : float, optional Kernel coefficient for rbf and poly kernels. Default: 1/n_features. Ignored by other kernels. coef0 : float, optional Independent term in poly and sigmoid kernels. Ignored by other kernels. kernel_params : mapping of string to any, optional Parameters (keyword arguments) and values for kernel passed as callable object. Ignored by other kernels. alpha: int Hyperparameter of the ridge regression that learns the inverse transform (when fit_inverse_transform=True). Default: 1.0 fit_inverse_transform: bool Learn the inverse transform for non-precomputed kernels. (i.e. learn to find the pre-image of a point) Default: False eigen_solver: string ['auto'|'dense'|'arpack'] Select eigensolver to use. If n_components is much less than the number of training samples, arpack may be more efficient than the dense eigensolver. tol: float convergence tolerance for arpack. Default: 0 (optimal value will be chosen by arpack) max_iter : int maximum number of iterations for arpack Default: None (optimal value will be chosen by arpack) remove_zero_eig : boolean, default=False If True, then all components with zero eigenvalues are removed, so that the number of components in the output may be < n_components (and sometimes even zero due to numerical instability). When n_components is None, this parameter is ignored and components with zero eigenvalues are removed regardless. random_state : int seed, RandomState instance, or None, default : None A pseudo random number generator used for the initialization of the residuals when eigen_solver == 'arpack'. n_jobs : int, optional (default = 1) The number of parallel jobs to run. If ``-1``, then the number of jobs is set to the number of CPU cores. Attributes ---------- lambdas_ : Eigenvalues of the centered kernel matrix alphas_ : Eigenvectors of the centered kernel matrix dual_coef_ : Inverse transform matrix X_transformed_fit_ : Projection of the fitted data on the kernel principal components References ---------- Kernel PCA was introduced in: Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999. Kernel principal component analysis. In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352. """ def __init__(self, n_components=None, kernel="linear", gamma=None, degree=3, coef0=1, kernel_params=None, alpha=1.0, fit_inverse_transform=False, eigen_solver='auto', tol=0, max_iter=None, remove_zero_eig=False, random_state=None, n_jobs=1): if fit_inverse_transform and kernel == 'precomputed': raise ValueError( "Cannot fit_inverse_transform with a precomputed kernel.") self.n_components = n_components self.kernel = kernel self.kernel_params = kernel_params self.gamma = gamma self.degree = degree self.coef0 = coef0 self.alpha = alpha self.fit_inverse_transform = fit_inverse_transform self.eigen_solver = eigen_solver self.remove_zero_eig = remove_zero_eig self.tol = tol self.max_iter = max_iter self._centerer = KernelCenterer() self.random_state = random_state self.n_jobs = n_jobs @property def _pairwise(self): return self.kernel == "precomputed" def _get_kernel(self, X, Y=None): if callable(self.kernel): params = self.kernel_params or {} else: params = {"gamma": self.gamma, "degree": self.degree, "coef0": self.coef0} return pairwise_kernels(X, Y, metric=self.kernel, filter_params=True, n_jobs=self.n_jobs, **params) def _fit_transform(self, K): """ Fit's using kernel K""" # center kernel K = self._centerer.fit_transform(K) if self.n_components is None: n_components = K.shape[0] else: n_components = min(K.shape[0], self.n_components) # compute eigenvectors if self.eigen_solver == 'auto': if K.shape[0] > 200 and n_components < 10: eigen_solver = 'arpack' else: eigen_solver = 'dense' else: eigen_solver = self.eigen_solver if eigen_solver == 'dense': self.lambdas_, self.alphas_ = linalg.eigh( K, eigvals=(K.shape[0] - n_components, K.shape[0] - 1)) elif eigen_solver == 'arpack': random_state = check_random_state(self.random_state) # initialize with [-1,1] as in ARPACK v0 = random_state.uniform(-1, 1, K.shape[0]) self.lambdas_, self.alphas_ = eigsh(K, n_components, which="LA", tol=self.tol, maxiter=self.max_iter, v0=v0) # sort eigenvectors in descending order indices = self.lambdas_.argsort()[::-1] self.lambdas_ = self.lambdas_[indices] self.alphas_ = self.alphas_[:, indices] # remove eigenvectors with a zero eigenvalue if self.remove_zero_eig or self.n_components is None: self.alphas_ = self.alphas_[:, self.lambdas_ > 0] self.lambdas_ = self.lambdas_[self.lambdas_ > 0] return K def _fit_inverse_transform(self, X_transformed, X): if hasattr(X, "tocsr"): raise NotImplementedError("Inverse transform not implemented for " "sparse matrices!") n_samples = X_transformed.shape[0] K = self._get_kernel(X_transformed) K.flat[::n_samples + 1] += self.alpha self.dual_coef_ = linalg.solve(K, X, sym_pos=True, overwrite_a=True) self.X_transformed_fit_ = X_transformed def fit(self, X, y=None): """Fit the model from data in X. Parameters ---------- X: array-like, shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. Returns ------- self : object Returns the instance itself. """ K = self._get_kernel(X) self._fit_transform(K) if self.fit_inverse_transform: sqrt_lambdas = np.diag(np.sqrt(self.lambdas_)) X_transformed = np.dot(self.alphas_, sqrt_lambdas) self._fit_inverse_transform(X_transformed, X) self.X_fit_ = X return self def fit_transform(self, X, y=None, **params): """Fit the model from data in X and transform X. Parameters ---------- X: array-like, shape (n_samples, n_features) Training vector, where n_samples in the number of samples and n_features is the number of features. Returns ------- X_new: array-like, shape (n_samples, n_components) """ self.fit(X, **params) X_transformed = self.alphas_ * np.sqrt(self.lambdas_) if self.fit_inverse_transform: self._fit_inverse_transform(X_transformed, X) return X_transformed def transform(self, X): """Transform X. Parameters ---------- X: array-like, shape (n_samples, n_features) Returns ------- X_new: array-like, shape (n_samples, n_components) """ check_is_fitted(self, 'X_fit_') K = self._centerer.transform(self._get_kernel(X, self.X_fit_)) return np.dot(K, self.alphas_ / np.sqrt(self.lambdas_)) def inverse_transform(self, X): """Transform X back to original space. Parameters ---------- X: array-like, shape (n_samples, n_components) Returns ------- X_new: array-like, shape (n_samples, n_features) References ---------- "Learning to Find Pre-Images", G BakIr et al, 2004. """ if not self.fit_inverse_transform: raise NotFittedError("The fit_inverse_transform parameter was not" " set to True when instantiating and hence " "the inverse transform is not available.") K = self._get_kernel(X, self.X_transformed_fit_) return np.dot(K, self.dual_coef_)
"""Define a config flow manager for AirVisual.""" import asyncio from pyairvisual import CloudAPI, NodeSamba from pyairvisual.errors import ( AirVisualError, InvalidKeyError, NodeProError, NotFoundError, ) import voluptuous as vol from homeassistant import config_entries from homeassistant.const import ( CONF_API_KEY, CONF_IP_ADDRESS, CONF_LATITUDE, CONF_LONGITUDE, CONF_PASSWORD, CONF_SHOW_ON_MAP, CONF_STATE, ) from homeassistant.core import callback from homeassistant.helpers import aiohttp_client, config_validation as cv from . import async_get_geography_id from .const import ( CONF_CITY, CONF_COUNTRY, CONF_INTEGRATION_TYPE, DOMAIN, INTEGRATION_TYPE_GEOGRAPHY_COORDS, INTEGRATION_TYPE_GEOGRAPHY_NAME, INTEGRATION_TYPE_NODE_PRO, LOGGER, ) API_KEY_DATA_SCHEMA = vol.Schema({vol.Required(CONF_API_KEY): cv.string}) GEOGRAPHY_NAME_SCHEMA = API_KEY_DATA_SCHEMA.extend( { vol.Required(CONF_CITY): cv.string, vol.Required(CONF_STATE): cv.string, vol.Required(CONF_COUNTRY): cv.string, } ) NODE_PRO_SCHEMA = vol.Schema( {vol.Required(CONF_IP_ADDRESS): str, vol.Required(CONF_PASSWORD): cv.string} ) PICK_INTEGRATION_TYPE_SCHEMA = vol.Schema( { vol.Required("type"): vol.In( [ INTEGRATION_TYPE_GEOGRAPHY_COORDS, INTEGRATION_TYPE_GEOGRAPHY_NAME, INTEGRATION_TYPE_NODE_PRO, ] ) } ) class AirVisualFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle an AirVisual config flow.""" VERSION = 2 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL def __init__(self): """Initialize the config flow.""" self._entry_data_for_reauth = None self._geo_id = None @property def geography_coords_schema(self): """Return the data schema for the cloud API.""" return API_KEY_DATA_SCHEMA.extend( { vol.Required( CONF_LATITUDE, default=self.hass.config.latitude ): cv.latitude, vol.Required( CONF_LONGITUDE, default=self.hass.config.longitude ): cv.longitude, } ) async def _async_finish_geography(self, user_input, integration_type): """Validate a Cloud API key.""" websession = aiohttp_client.async_get_clientsession(self.hass) cloud_api = CloudAPI(user_input[CONF_API_KEY], session=websession) # If this is the first (and only the first) time we've seen this API key, check # that it's valid: valid_keys = self.hass.data.setdefault("airvisual_checked_api_keys", set()) valid_keys_lock = self.hass.data.setdefault( "airvisual_checked_api_keys_lock", asyncio.Lock() ) if integration_type == INTEGRATION_TYPE_GEOGRAPHY_COORDS: coro = cloud_api.air_quality.nearest_city() error_schema = self.geography_coords_schema error_step = "geography_by_coords" else: coro = cloud_api.air_quality.city( user_input[CONF_CITY], user_input[CONF_STATE], user_input[CONF_COUNTRY] ) error_schema = GEOGRAPHY_NAME_SCHEMA error_step = "geography_by_name" async with valid_keys_lock: if user_input[CONF_API_KEY] not in valid_keys: try: await coro except InvalidKeyError: return self.async_show_form( step_id=error_step, data_schema=error_schema, errors={CONF_API_KEY: "invalid_api_key"}, ) except NotFoundError: return self.async_show_form( step_id=error_step, data_schema=error_schema, errors={CONF_CITY: "location_not_found"}, ) except AirVisualError as err: LOGGER.error(err) return self.async_show_form( step_id=error_step, data_schema=error_schema, errors={"base": "unknown"}, ) valid_keys.add(user_input[CONF_API_KEY]) existing_entry = await self.async_set_unique_id(self._geo_id) if existing_entry: self.hass.config_entries.async_update_entry(existing_entry, data=user_input) return self.async_abort(reason="reauth_successful") return self.async_create_entry( title=f"Cloud API ({self._geo_id})", data={**user_input, CONF_INTEGRATION_TYPE: integration_type}, ) async def _async_init_geography(self, user_input, integration_type): """Handle the initialization of the integration via the cloud API.""" self._geo_id = async_get_geography_id(user_input) await self._async_set_unique_id(self._geo_id) self._abort_if_unique_id_configured() return await self._async_finish_geography(user_input, integration_type) async def _async_set_unique_id(self, unique_id): """Set the unique ID of the config flow and abort if it already exists.""" await self.async_set_unique_id(unique_id) self._abort_if_unique_id_configured() @staticmethod @callback def async_get_options_flow(config_entry): """Define the config flow to handle options.""" return AirVisualOptionsFlowHandler(config_entry) async def async_step_geography_by_coords(self, user_input=None): """Handle the initialization of the cloud API based on latitude/longitude.""" if not user_input: return self.async_show_form( step_id="geography_by_coords", data_schema=self.geography_coords_schema ) return await self._async_init_geography( user_input, INTEGRATION_TYPE_GEOGRAPHY_COORDS ) async def async_step_geography_by_name(self, user_input=None): """Handle the initialization of the cloud API based on city/state/country.""" if not user_input: return self.async_show_form( step_id="geography_by_name", data_schema=GEOGRAPHY_NAME_SCHEMA ) return await self._async_init_geography( user_input, INTEGRATION_TYPE_GEOGRAPHY_NAME ) async def async_step_node_pro(self, user_input=None): """Handle the initialization of the integration with a Node/Pro.""" if not user_input: return self.async_show_form(step_id="node_pro", data_schema=NODE_PRO_SCHEMA) await self._async_set_unique_id(user_input[CONF_IP_ADDRESS]) node = NodeSamba(user_input[CONF_IP_ADDRESS], user_input[CONF_PASSWORD]) try: await node.async_connect() except NodeProError as err: LOGGER.error("Error connecting to Node/Pro unit: %s", err) return self.async_show_form( step_id="node_pro", data_schema=NODE_PRO_SCHEMA, errors={CONF_IP_ADDRESS: "cannot_connect"}, ) await node.async_disconnect() return self.async_create_entry( title=f"Node/Pro ({user_input[CONF_IP_ADDRESS]})", data={**user_input, CONF_INTEGRATION_TYPE: INTEGRATION_TYPE_NODE_PRO}, ) async def async_step_reauth(self, data): """Handle configuration by re-auth.""" self._entry_data_for_reauth = data self._geo_id = async_get_geography_id(data) return await self.async_step_reauth_confirm() async def async_step_reauth_confirm(self, user_input=None): """Handle re-auth completion.""" if not user_input: return self.async_show_form( step_id="reauth_confirm", data_schema=API_KEY_DATA_SCHEMA ) conf = {CONF_API_KEY: user_input[CONF_API_KEY], **self._entry_data_for_reauth} return await self._async_finish_geography( conf, self._entry_data_for_reauth[CONF_INTEGRATION_TYPE] ) async def async_step_user(self, user_input=None): """Handle the start of the config flow.""" if not user_input: return self.async_show_form( step_id="user", data_schema=PICK_INTEGRATION_TYPE_SCHEMA ) if user_input["type"] == INTEGRATION_TYPE_GEOGRAPHY_COORDS: return await self.async_step_geography_by_coords() if user_input["type"] == INTEGRATION_TYPE_GEOGRAPHY_NAME: return await self.async_step_geography_by_name() return await self.async_step_node_pro() class AirVisualOptionsFlowHandler(config_entries.OptionsFlow): """Handle an AirVisual options flow.""" def __init__(self, config_entry): """Initialize.""" self.config_entry = config_entry async def async_step_init(self, user_input=None): """Manage the options.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) return self.async_show_form( step_id="init", data_schema=vol.Schema( { vol.Required( CONF_SHOW_ON_MAP, default=self.config_entry.options.get(CONF_SHOW_ON_MAP), ): bool } ), )
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Class to represent a device.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.util.tf_export import tf_export _VALID_DEVICE_TYPES = frozenset({"CPU", "GPU", "TPU", "CUSTOM"}) # ============================================================================== # == Global Implementation Details ============================================= # ============================================================================== _STRING_TO_COMPONENTS_CACHE = {} _COMPONENTS_TO_STRING_CACHE = {} def _as_str_or_none(inp): return None if inp is None else str(inp) def _as_int_or_none(inp): return None if inp is None else int(inp) def _as_device_str_or_none(device_type): # For backwards compatibility only, we support lowercase variants of # cpu and gpu but turn them into uppercase here. if device_type in ("cpu", "gpu"): return device_type.upper() return _as_str_or_none(device_type) @tf_export("DeviceSpec", v1=[]) class DeviceSpecV2(object): """Represents a (possibly partial) specification for a TensorFlow device. `DeviceSpec`s are used throughout TensorFlow to describe where state is stored and computations occur. Using `DeviceSpec` allows you to parse device spec strings to verify their validity, merge them or compose them programmatically. Example: ```python # Place the operations on device "GPU:0" in the "ps" job. device_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0) with tf.device(device_spec.to_string()): # Both my_var and squared_var will be placed on /job:ps/device:GPU:0. my_var = tf.Variable(..., name="my_variable") squared_var = tf.square(my_var) ``` With eager execution disabled (by default in TensorFlow 1.x and by calling disable_eager_execution() in TensorFlow 2.x), the following syntax can be used: ```python tf.compat.v1.disable_eager_execution() # Same as previous device_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0) # No need of .to_string() method. with tf.device(device_spec): my_var = tf.Variable(..., name="my_variable") squared_var = tf.square(my_var) ``` If a `DeviceSpec` is partially specified, it will be merged with other `DeviceSpec`s according to the scope in which it is defined. `DeviceSpec` components defined in inner scopes take precedence over those defined in outer scopes. ```python gpu0_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0) with tf.device(DeviceSpec(job="train").to_string()): with tf.device(gpu0_spec.to_string()): # Nodes created here will be assigned to /job:ps/device:GPU:0. with tf.device(DeviceSpec(device_type="GPU", device_index=1).to_string()): # Nodes created here will be assigned to /job:train/device:GPU:1. ``` A `DeviceSpec` consists of 5 components -- each of which is optionally specified: * Job: The job name. * Replica: The replica index. * Task: The task index. * Device type: The device type string (e.g. "CPU" or "GPU"). * Device index: The device index. """ __slots__ = ("_job", "_replica", "_task", "_device_type", "_device_index", "_as_string", "_hash") def __init__(self, job=None, replica=None, task=None, device_type=None, device_index=None): """Create a new `DeviceSpec` object. Args: job: string. Optional job name. replica: int. Optional replica index. task: int. Optional task index. device_type: Optional device type string (e.g. "CPU" or "GPU") device_index: int. Optional device index. If left unspecified, device represents 'any' device_index. """ self._job = _as_str_or_none(job) self._replica = _as_int_or_none(replica) self._task = _as_int_or_none(task) self._device_type = _as_device_str_or_none(device_type) self._device_index = _as_int_or_none(device_index) self._as_string = self._components_to_string( job=self._job, replica=self._replica, task=self._task, device_type=self._device_type, device_index=self._device_index) self._hash = hash(self.to_string()) def to_string(self): """Return a string representation of this `DeviceSpec`. Returns: a string of the form /job:<name>/replica:<id>/task:<id>/device:<device_type>:<id>. """ return self._as_string @classmethod def from_string(cls, spec): """Construct a `DeviceSpec` from a string. Args: spec: a string of the form /job:<name>/replica:<id>/task:<id>/device:CPU:<id> or /job:<name>/replica:<id>/task:<id>/device:GPU:<id> as cpu and gpu are mutually exclusive. All entries are optional. Returns: A DeviceSpec. """ return cls(*cls._string_to_components(spec)) def parse_from_string(self, spec): """Parse a `DeviceSpec` name into its components. 2.x behavior change: In TensorFlow 1.x, this function mutates its own state and returns itself. In 2.x, DeviceSpecs are immutable, and this function will return a DeviceSpec which contains the spec. Recommended: ``` # my_spec and my_updated_spec are unrelated. my_spec = tf.DeviceSpec.from_string("/CPU:0") my_updated_spec = tf.DeviceSpec.from_string("/GPU:0") with tf.device(my_updated_spec): ... ``` Will work in 1.x and 2.x (though deprecated in 2.x): ``` my_spec = tf.DeviceSpec.from_string("/CPU:0") my_updated_spec = my_spec.parse_from_string("/GPU:0") with tf.device(my_updated_spec): ... ``` Will NOT work in 2.x: ``` my_spec = tf.DeviceSpec.from_string("/CPU:0") my_spec.parse_from_string("/GPU:0") # <== Will not update my_spec with tf.device(my_spec): ... ``` In general, `DeviceSpec.from_string` should completely replace `DeviceSpec.parse_from_string`, and `DeviceSpec.replace` should completely replace setting attributes directly. Args: spec: an optional string of the form /job:<name>/replica:<id>/task:<id>/device:CPU:<id> or /job:<name>/replica:<id>/task:<id>/device:GPU:<id> as cpu and gpu are mutually exclusive. All entries are optional. Returns: The `DeviceSpec`. Raises: ValueError: if the spec was not valid. """ return self.from_string(spec) def make_merged_spec(self, dev): """Returns a new DeviceSpec which incorporates `dev`. When combining specs, `dev` will take precidence over the current spec. So for instance: ``` first_spec = tf.DeviceSpec(job=0, device_type="CPU") second_spec = tf.DeviceSpec(device_type="GPU") combined_spec = first_spec.make_merged_spec(second_spec) ``` is equivalent to: ``` combined_spec = tf.DeviceSpec(job=0, device_type="GPU") ``` Args: dev: a `DeviceSpec` Returns: A new `DeviceSpec` which combines `self` and `dev` """ return self.__class__(*self._get_combined_properties(dev)) def replace(self, **kwargs): """Convenience method for making a new DeviceSpec by overriding fields. For instance: ``` my_spec = DeviceSpec=(job="my_job", device="CPU") my_updated_spec = my_spec.replace(device="GPU") my_other_spec = my_spec.replace(device=None) ``` Args: **kwargs: This method takes the same args as the DeviceSpec constructor Returns: A DeviceSpec with the fields specified in kwargs overridden. """ init_kwargs = dict( job=self.job, replica=self.replica, task=self.task, device_type=self.device_type, device_index=self.device_index) # Explicitly provided kwargs take precidence. init_kwargs.update(kwargs) return self.__class__(**init_kwargs) @property def job(self): return self._job @property def replica(self): return self._replica @property def task(self): return self._task @property def device_type(self): return self._device_type @property def device_index(self): return self._device_index def _get_combined_properties(self, dev): """Combine the current DeviceSpec with another DeviceSpec. The combination of DeviceSpecs is will give priority to dev. Args: dev: a `DeviceSpec` Returns: A tuple of (job, replica, task, device_type, device_index) which represents the combination of self and dev. """ return ( dev.job if dev.job is not None else self.job, dev.replica if dev.replica is not None else self.replica, dev.task if dev.task is not None else self.task, dev.device_type if dev.device_type is not None else self.device_type, dev.device_index if dev.device_index is not None else self.device_index, ) @staticmethod def _string_to_components(spec=None): """Stateless portion of device spec string parsing. Args: spec: An optional string specifying a device specification. Returns: The parsed components of `spec`. Note that the result of this function must go through attribute setters of DeviceSpec, and should therefore NOT be used directly. """ cached_result = _STRING_TO_COMPONENTS_CACHE.get(spec) if cached_result is not None: return cached_result raw_spec = spec # keep a copy of the original to update the cache job, replica, task, device_type, device_index = None, None, None, None, None spec = spec or "" splits = [x.split(":") for x in spec.split("/")] for y in splits: ly = len(y) if y: # NOTE(taylorrobie): these will go through setters later. if ly == 2 and y[0] == "job": job = y[1] elif ly == 2 and y[0] == "replica": replica = y[1] elif ly == 2 and y[0] == "task": task = y[1] elif ((ly == 1 or ly == 2) and (y[0].upper() in _VALID_DEVICE_TYPES)): if device_type is not None: raise ValueError("Cannot specify multiple device types: %s" % spec) device_type = y[0].upper() if ly == 2 and y[1] != "*": device_index = int(y[1]) elif ly == 3 and y[0] == "device": if device_type is not None: raise ValueError("Cannot specify multiple device types: %s" % spec) device_type = y[1] if y[2] != "*": device_index = int(y[2]) elif ly and y[0] != "": # pylint: disable=g-explicit-bool-comparison raise ValueError("Unknown attribute: '%s' in '%s'" % (y[0], spec)) output = (job, replica, task, device_type, device_index) _STRING_TO_COMPONENTS_CACHE[raw_spec] = output return output @staticmethod def _components_to_string(job, replica, task, device_type, device_index): """Stateless portion of `to_string` (separated to allow caching).""" key = (job, replica, task, device_type, device_index) cached_result = _COMPONENTS_TO_STRING_CACHE.get(key) if cached_result is not None: return cached_result output = [] if job is not None: output.append("/job:" + job) if replica is not None: output.append("/replica:" + str(replica)) if task is not None: output.append("/task:" + str(task)) if device_type is not None: device_index_string = "*" if device_index is not None: # Unlike the others, device_index is stored as an int. device_index_string = str(device_index) output.append("/device:%s:%s" % (device_type, device_index_string)) output = "".join(output) _COMPONENTS_TO_STRING_CACHE[key] = output return output def __eq__(self, other): """Checks if the `other` DeviceSpec is same as the current instance, eg have same value for all the internal fields. Args: other: Another DeviceSpec Returns: Return `True` if `other` is also a DeviceSpec instance and has same value as the current instance. Return `False` otherwise. """ return (isinstance(other, self.__class__) and self.to_string() == other.to_string()) def __hash__(self): return self._hash @tf_export(v1=["DeviceSpec"]) # pylint: disable=missing-docstring class DeviceSpecV1(DeviceSpecV2): __doc__ = DeviceSpecV2.__doc__ __slots__ = DeviceSpecV2.__slots__ @DeviceSpecV2.job.setter def job(self, job): self._job = _as_str_or_none(job) self._as_string, self._hash = None, None @DeviceSpecV2.replica.setter def replica(self, replica): self._replica = _as_int_or_none(replica) self._as_string, self._hash = None, None @DeviceSpecV2.task.setter def task(self, task): self._task = _as_int_or_none(task) self._as_string, self._hash = None, None @DeviceSpecV2.device_type.setter def device_type(self, device_type): self._device_type = _as_device_str_or_none(device_type) self._as_string, self._hash = None, None @DeviceSpecV2.device_index.setter def device_index(self, device_index): self._device_index = _as_int_or_none(device_index) self._as_string, self._hash = None, None def __hash__(self): if self._hash is None: self._hash = hash(self.to_string()) return self._hash def to_string(self): if self._as_string is None: self._as_string = self._components_to_string( job=self.job, replica=self.replica, task=self.task, device_type=self.device_type, device_index=self.device_index) return self._as_string def parse_from_string(self, spec): (self.job, self.replica, self.task, self.device_type, self.device_index ) = self._string_to_components(spec) return self def merge_from(self, dev): """Merge the properties of "dev" into this `DeviceSpec`. Note: Will be removed in TensorFlow 2.x since DeviceSpecs will become immutable. Args: dev: a `DeviceSpec`. """ (self.job, self.replica, self.task, self.device_type, self.device_index ) = self._get_combined_properties(dev) # Use parent class docstrings for public methods. to_string.__doc__ = DeviceSpecV2.to_string.__doc__ parse_from_string.__doc__ = DeviceSpecV2.parse_from_string.__doc__
import datetime import sys import logging from collections import Counter from pyevolve import GSimpleGA from pyevolve.G1DList import G1DList from pyevolve.Initializators import G1DBinaryStringInitializator t = datetime.time log = logging.getLogger(__name__) class Activity: ALL = {} def __init__(self, name, id, slots): self.name = name self.id = id self.slots = slots self.__class__.ALL[id] = self @classmethod def from_id(cls, id): return cls.ALL[id] class Member: def __init__(self, name, activities): self.name = name self.activities = activities class Family: ALL = {} def __init__(self, name, id, members): self.name = name self.id = id self.members = members self.__class__.ALL[id] = self def get_members(self): return self.members @classmethod def from_id(cls, id): return cls.ALL[id] @classmethod def get_all(cls): return cls.ALL.values() act1 = Activity(name="Activity1", id=0b000, slots={0b000: (t(9, 0), t(10, 0)), 0b001: (t(10, 15), t(11, 15))}) act2 = Activity(name="Activity2", id=0b001, slots={0b000: (t(9, 0), t(9, 25)), 0b001: (t(10, 0), t(10, 25))}) f1member1 = Member("Joe Blogs", [act1]) f1member2 = Member("Jane Blogs", [act1, act2]) f1 = Family("The Blogs", 0, [f1member1, f1member2]) f2member1 = Member("Fred Blue", [act2]) f2member2 = Member("Chloe Blue", [act2]) f2 = Family("The Blues", 1, [f2member1, f2member1]) f1member1 = Member("Joe Greans", [act1]) f1member2 = Member("Jane Greans", [act1, act2]) f3 = Family("The Greans", 2, [f1member1, f1member2]) f2member1 = Member("Fred Browns", [act2]) f2member2 = Member("Chloe Browns", [act2]) f4 = Family("The Browns", 3, [f2member1, f2member1]) def list_to_int(l): return int("".join(str(i) for i in l), 2) class Schedule(list): def __str__(self): out = [] for activity, slot, family1, family2 in self: out.append("{} {} {} {}".format( activity.name, slot, family1.name, family2.name )) return "\n".join(out) class Chromosome: def __init__(self, schedule): self.schedule = Schedule(schedule) def __str__(self): return str(self.schedule) def get_score(self): score = 0.0 #import pdb #pdb.set_trace() for family in Family.get_all(): for member in family.get_members(): for (activity, slot, family1, family2) in self.schedule: for fam in (family1, family2): if family.id == fam.id: if activity in member.activities: score += 1 family_pair_map = {} for (activity, slot, family1, family2) in self.schedule: if (family1, family2) in family_pair_map: score -= 0.5 else: family_pair_map[(family1, family2)] = 1 # A Family should not appear in a activity twice act_family_map = {} for activity, slot, family1, family2 in self.schedule: for fam in (family1, family2): if (activity.id in act_family_map and fam in act_family_map[activity.id]): score = 0 log.debug("Duplicate families") break else: act_family_map[activity.id] = {fam: 1} # Check if any activities / slots are listed more than once. c = Counter([(activity.id, slot) for activity, slot, family1, family2 in self.schedule]) if len([v for v in c.values() if v > 1]) > 0: log.debug("duplicate activity / slots {}".format(c)) score = 0 return score @classmethod def from_list(cls, l): schedule = [] i = 0 while i < len(l): schedule.append( (Activity.from_id(list_to_int(l[i:i+1])), list_to_int(l[i+1:i+2]), Family.from_id(list_to_int(l[i+2:i+4])), Family.from_id(list_to_int(l[i+4:i+6])))) i += 6 return cls(schedule) # class Genome(GenomeBase): # def __init__(self, length=4): # GenomeBase.__init__(self) # self.genomeString = [] # self.stringLength = length # self.initializator.set(Consts.CDefG1DBinaryStringInit) # self.mutator.set(Consts.CDefG1DBinaryStringMutator) # self.crossover.set(Consts.CDefG1DBinaryStringCrossover) # def getListSize(self): # return self.stringLength # def copy(self, g): # """ Copy genome to 'g' """ # GenomeBase.copy(self, g) # g.stringLength = self.stringLength # g.genomeString = self.genomeString[:] # def clone(self): # """ Return a new instace copy of the genome """ # newcopy = Genome(self.stringLength) # self.copy(newcopy) # return newcopy def eval_func(chromosome): c = Chromosome.from_list(chromosome.genomeList) return c.get_score() if __name__ == '__main__': #log.addHandler(logging.StreamHandler(stream=sys.stderr)) log.setLevel(logging.DEBUG) log.debug("Debug is on") genome = G1DList(6 * 4) genome.initializator.set(G1DBinaryStringInitializator) genome.evaluator.set(eval_func) ga = GSimpleGA.GSimpleGA(genome) ga.evolve(freq_stats=10) print Chromosome.from_list(ga.bestIndividual())
import os from distill.sessions import UnencryptedLocalSessionStorage try: import testtools as unittest except ImportError: import unittest import json from distill.decorators import before, after from distill.exceptions import HTTPNotFound, HTTPBadRequest, HTTPErrorResponse, HTTPInternalServerError from distill.application import Distill from distill.renderers import renderer, JSON from distill.response import Response from routes import Mapper try: from StringIO import StringIO except ImportError: from io import StringIO def do_before(request, response): response.headers['X-Before'] = 'true' def do_after(request, response): response.headers['X-After'] = 'true' @before(do_before) @after(do_after) @renderer('login.mako') def POST_home(request, response): return {'user': request.POST['user']} @before(do_before) @after(do_after) @renderer('site.mako') def GET_home(request, response): def callback(r, q): q.headers['X-Resp-Callback'] = 'True' request.add_response_callback(callback) return {} @renderer('prettyjson') def bad_request(request, response): return {'msg': "Well that was bad"} def userinfo(request, reponse): if request.method == 'POST': return HTTPErrorResponse("716 I am a teapot") class User(object): def __init__(self, user): self.user = user def json(self, request): return {'username': self.user} return User(request.matchdict['user']) def user(request, response): resp = Response(headers={'X-Test': 'Foobar'}) resp.body = "Hello world" return resp def internal_server_error(request, response): raise HTTPInternalServerError() def handle_ise(request, response): print(response.description) resp = Response() resp.body = "Whoops" return resp def create_bad_request(request, response): return HTTPBadRequest() class TestController(object): @renderer('prettyjson') @before(do_before) @after(do_after) def GET_home(self, request, response): return {'data': True} def edit_res(request, response): response.status = '719 I am not a teapot' response.body = 'Hello' exc_info = None class TestApplication(unittest.TestCase): def test_application(self): app = Distill(settings={ 'distill.document_root': os.path.abspath(os.path.join(os.path.dirname(__file__), 'res')), 'distill.sessions.directory': os.path.abspath(os.path.join(os.path.dirname(__file__), 'sess')) }, controllers={'testcontrollerinit': TestController} ) app.set_session_factory(UnencryptedLocalSessionStorage(app.settings)) app.add_renderer('prettyjson', JSON(indent=4)) app.add_controller('testcontroller', TestController) app.on_except(HTTPBadRequest, bad_request) app.on_except(HTTPInternalServerError, handle_ise) app.map_connect('home', '/', action=GET_home, conditions={"method": ["GET"]}) app.map_connect('home', '/', action=POST_home, conditions={"method": ["POST"]}) app.map_connect('badrequest', '/badrequest', action=create_bad_request) app.map_connect('userinfo', '/:user/userinfo', action=userinfo) app.map_connect('ise', '/internalservererror', action=internal_server_error) app.map_connect('homecontroller', '/controller', action='GET_home', controller='testcontroller') app.map_connect('homecontroller1', '/controllerinit', action='GET_home', controller='testcontrollerinit') app.map_connect('homecontroller2', '/controllerNA', action='GET_home', controller='nocontroller') app.map_connect('homecontroller3', '/actionNA', action='noaction', controller='testcontroller') app.map_connect('editresp', '/editresp', action=edit_res) app.map_connect('user', '/:user', action=user) resp, body = self.simulate_request(app, 'GET', '', None, '') self.assertIn('X-Before', resp.headers) self.assertIn('X-After', resp.headers) self.assertIn('X-Resp-Callback', resp.headers) self.assertRaises(HTTPNotFound, self.simulate_request, app, 'GET', '/foo/bar/baz', None, '') resp, body = self.simulate_request(app, 'GET', '/controller', None, '') self.assertIn('X-Before', resp.headers) self.assertIn('X-After', resp.headers) data = json.loads(body) self.assertTrue(data['data']) resp, body = self.simulate_request(app, 'GET', '/controllerinit', None, '') self.assertIn('X-Before', resp.headers) self.assertIn('X-After', resp.headers) data = json.loads(body) self.assertTrue(data['data']) self.assertRaises(HTTPNotFound, self.simulate_request, app, 'GET', '/controllerNA', None, '') self.assertRaises(HTTPNotFound, self.simulate_request, app, 'GET', '/actionNA', None, '') resp, body = self.simulate_request(app, 'GET', '/editresp', None, '') self.assertEqual(resp.status, '719 I am not a teapot') self.assertEqual(body, 'Hello') resp, body = self.simulate_request(app, 'GET', '/badrequest', None, '') data = json.loads(body) self.assertEqual(data['msg'], 'Well that was bad') self.assertEqual(resp.status, '400 Bad Request') resp, body = self.simulate_request(app, 'POST', '', 'foo=bar', 'user=Bar') self.assertEqual(body, 'Loggedin Bar') self.assertRaises(HTTPErrorResponse, self.simulate_request, app, 'POST', '/Foo/userinfo', None, '') resp, body = self.simulate_request(app, 'GET', '/Foo', None, '') self.assertIn('X-Test', resp.headers) self.assertEqual(body, 'Hello world') resp, body = self.simulate_request(app, 'GET', '/internalservererror', None, '') self.assertEqual(resp.status, '200 OK') def test_before_after(self): def test_before1(request, response): response.headers['X-Before1'] = 'true' def test_after1(request, response): response.headers['X-After1'] = 'true' def test_before2(request, response): response.headers['X-Before2'] = 'true' def test_after2(request, response): response.headers['X-After2'] = 'true' map_ = Mapper() map_.connect('userinfo', '/:user/userinfo', action=userinfo) map_.connect('ise', '/internalservererror', action=internal_server_error) app = Distill(rmap=map_) app.use(test_before1) app.use(test_before2) app.use(test_after1, before=False) app.use(test_after2, before=False) app.add_renderer('prettyjson', JSON(indent=4)) app.on_except(HTTPInternalServerError, handle_ise) resp, body = self.simulate_request(app, 'GET', '/Dreae/userinfo', None, '') self.assertIn('X-Before1', resp.headers) self.assertEqual(resp.headers['X-Before1'], 'true') self.assertIn('X-After1', resp.headers) self.assertEqual(resp.headers['X-After1'], 'true') self.assertIn('X-Before2', resp.headers) self.assertEqual(resp.headers['X-Before2'], 'true') self.assertIn('X-After2', resp.headers) self.assertEqual(resp.headers['X-After2'], 'true') self.assertRaises(HTTPErrorResponse, self.simulate_request, app, 'POST', '/Foo/userinfo', None, '') resp, body = self.simulate_request(app, 'GET', '/internalservererror', None, '') self.assertEqual(resp.status, '200 OK') @staticmethod def simulate_request(app, method, path, querystring, body): fake_env = {'wsgi.input': StringIO(body), 'wsgi.errors': None, 'wsgi.url_scheme': 'https', 'CONTENT_LENGTH': len(body), 'PATH_INFO': path, 'SERVER_PORT': '8080', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'HTTP_X_H_Test': 'Foobar', 'HTTP_CONTENT_TYPE': 'application/x-www-form-urlencoded', 'QUERY_STRING': querystring, 'HTTP_HOST': 'foobar.baz:8080', 'SERVER_NAME': 'foobar.baz', 'HTTP_FOO': 'bar', 'SCRIPT_NAME': '/some/script/dir', 'REQUEST_METHOD': method} resp = Response() def start_response(status, headers, exc_info_=None): resp.status = status resp.headers = dict(headers) global exc_info exc_info = exc_info_ body = app(fake_env, start_response) if exc_info: raise exc_info[0](exc_info[1]) # No traceback because python3 body = body[0] return resp, body.decode('utf-8') if __name__ == '__main__': unittest.main()
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Internal utilities for `LinearOperator` classes.""" import numpy as np from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.module import module from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import linalg_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables as variables_module from tensorflow.python.util import nest ################################################################################ # To make more friendly for TF2. ################################################################################ def convert_nonref_to_tensor(value, dtype=None, dtype_hint=None, name=None): """Converts the given `value` to a `Tensor` if input is nonreference type. This function converts Python objects of various types to `Tensor` objects except if the input has nonreference semantics. Reference semantics are characterized by `is_ref` and is any object which is a `tf.Variable` or instance of `tf.Module`. This function accepts any input which `tf.convert_to_tensor` would also. Note: This function diverges from default Numpy behavior for `float` and `string` types when `None` is present in a Python list or scalar. Rather than silently converting `None` values, an error will be thrown. Args: value: An object whose type has a registered `Tensor` conversion function. dtype: Optional element type for the returned tensor. If missing, the type is inferred from the type of `value`. dtype_hint: Optional element type for the returned tensor, used when dtype is None. In some cases, a caller may not have a dtype in mind when converting to a tensor, so dtype_hint can be used as a soft preference. If the conversion to `dtype_hint` is not possible, this argument has no effect. name: Optional name to use if a new `Tensor` is created. Returns: tensor: A `Tensor` based on `value`. Raises: TypeError: If no conversion function is registered for `value` to `dtype`. RuntimeError: If a registered conversion function returns an invalid value. ValueError: If the `value` is a tensor not of given `dtype` in graph mode. #### Examples: ```python x = tf.Variable(0.) y = convert_nonref_to_tensor(x) x is y # ==> True x = tf.constant(0.) y = convert_nonref_to_tensor(x) x is y # ==> True x = np.array(0.) y = convert_nonref_to_tensor(x) x is y # ==> False tf.is_tensor(y) # ==> True x = tfp.util.DeferredTensor(13.37, lambda x: x) y = convert_nonref_to_tensor(x) x is y # ==> True tf.is_tensor(y) # ==> False tf.equal(y, 13.37) # ==> True ``` """ # We explicitly do not use a tf.name_scope to avoid graph clutter. if value is None: return None if is_ref(value): if dtype is None: return value dtype_base = base_dtype(dtype) value_dtype_base = base_dtype(value.dtype) if dtype_base != value_dtype_base: raise TypeError( f"Argument `value` must be of dtype `{dtype_name(dtype_base)}` " f"Received: `{dtype_name(value_dtype_base)}`.") return value return ops.convert_to_tensor_v2_with_dispatch( value, dtype=dtype, dtype_hint=dtype_hint, name=name) def base_dtype(dtype): """Returns a non-reference `dtype` based on this `dtype`.""" dtype = dtypes.as_dtype(dtype) if hasattr(dtype, "base_dtype"): return dtype.base_dtype return dtype def dtype_name(dtype): """Returns the string name for this `dtype`.""" dtype = dtypes.as_dtype(dtype) if hasattr(dtype, "name"): return dtype.name if hasattr(dtype, "__name__"): return dtype.__name__ return str(dtype) def check_dtype(arg, dtype): """Check that arg.dtype == self.dtype.""" if arg.dtype.base_dtype != dtype: raise TypeError( f"Expected argument to have dtype {dtype}. Found: {arg.dtype} in " f"tensor {arg}.") def is_ref(x): """Evaluates if the object has reference semantics. An object is deemed "reference" if it is a `tf.Variable` instance or is derived from a `tf.Module` with `dtype` and `shape` properties. Args: x: Any object. Returns: is_ref: Python `bool` indicating input is has nonreference semantics, i.e., is a `tf.Variable` or a `tf.Module` with `dtype` and `shape` properties. """ return ( # Note: we check that tf.Variable is a class because we might be using a # different backend other than TF. isinstance(x, variables_module.Variable) or (isinstance(x, module.Module) and hasattr(x, "dtype") and hasattr(x, "shape"))) def assert_not_ref_type(x, arg_name): if is_ref(x): raise TypeError( f"Argument {arg_name} cannot be reference type. Found: {type(x)}.") ################################################################################ # Asserts. ################################################################################ def assert_no_entries_with_modulus_zero( x, message=None, name="assert_no_entries_with_modulus_zero"): """Returns `Op` that asserts Tensor `x` has no entries with modulus zero. Args: x: Numeric `Tensor`, real, integer, or complex. message: A string message to prepend to failure message. name: A name to give this `Op`. Returns: An `Op` that asserts `x` has no entries with modulus zero. """ with ops.name_scope(name, values=[x]): x = ops.convert_to_tensor_v2_with_dispatch(x, name="x") dtype = x.dtype.base_dtype should_be_nonzero = math_ops.abs(x) zero = ops.convert_to_tensor_v2_with_dispatch(0, dtype=dtype.real_dtype) return check_ops.assert_less(zero, should_be_nonzero, message=message) def assert_zero_imag_part(x, message=None, name="assert_zero_imag_part"): """Returns `Op` that asserts Tensor `x` has no non-zero imaginary parts. Args: x: Numeric `Tensor`, real, integer, or complex. message: A string message to prepend to failure message. name: A name to give this `Op`. Returns: An `Op` that asserts `x` has no entries with modulus zero. """ with ops.name_scope(name, values=[x]): x = ops.convert_to_tensor_v2_with_dispatch(x, name="x") dtype = x.dtype.base_dtype if dtype.is_floating: return control_flow_ops.no_op() zero = ops.convert_to_tensor_v2_with_dispatch(0, dtype=dtype.real_dtype) return check_ops.assert_equal(zero, math_ops.imag(x), message=message) def assert_compatible_matrix_dimensions(operator, x): """Assert that an argument to solve/matmul has proper domain dimension. If `operator.shape[-2:] = [M, N]`, and `x.shape[-2:] = [Q, R]`, then `operator.matmul(x)` is defined only if `N = Q`. This `Op` returns an `Assert` that "fires" if this is not the case. Static checks are already done by the base class `LinearOperator`. Args: operator: `LinearOperator`. x: `Tensor`. Returns: `Assert` `Op`. """ # Static checks are done in the base class. Only tensor asserts here. assert_same_dd = check_ops.assert_equal( array_ops.shape(x)[-2], operator.domain_dimension_tensor(), # This error message made to look similar to error raised by static check # in the base class. message=("Dimensions are not compatible. " "shape[-2] of argument to be the same as this operator")) return assert_same_dd def assert_is_batch_matrix(tensor): """Static assert that `tensor` has rank `2` or higher.""" sh = tensor.shape if sh.ndims is not None and sh.ndims < 2: raise ValueError( f"Expected [batch] matrix to have at least two dimensions. Found: " f"{tensor}.") def shape_tensor(shape, name=None): """Convert Tensor using default type, unless empty list or tuple.""" # Works just like random_ops._ShapeTensor. if isinstance(shape, (tuple, list)) and not shape: dtype = dtypes.int32 else: dtype = None return ops.convert_to_tensor_v2_with_dispatch(shape, dtype=dtype, name=name) ################################################################################ # Broadcasting versions of common linear algebra functions. # TODO(b/77519145) Do this more efficiently in some special cases. ################################################################################ def broadcast_matrix_batch_dims(batch_matrices, name=None): """Broadcast leading dimensions of zero or more [batch] matrices. Example broadcasting one batch dim of two simple matrices. ```python x = [[1, 2], [3, 4]] # Shape [2, 2], no batch dims y = [[[1]]] # Shape [1, 1, 1], 1 batch dim of shape [1] x_bc, y_bc = broadcast_matrix_batch_dims([x, y]) x_bc ==> [[[1, 2], [3, 4]]] # Shape [1, 2, 2], 1 batch dim of shape [1]. y_bc ==> same as y ``` Example broadcasting many batch dims ```python x = tf.random.normal(shape=(2, 3, 1, 4, 4)) y = tf.random.normal(shape=(1, 3, 2, 5, 5)) x_bc, y_bc = broadcast_matrix_batch_dims([x, y]) x_bc.shape ==> (2, 3, 2, 4, 4) y_bc.shape ==> (2, 3, 2, 5, 5) ``` Args: batch_matrices: Iterable of `Tensor`s, each having two or more dimensions. name: A string name to prepend to created ops. Returns: bcast_matrices: List of `Tensor`s, with `bcast_matrices[i]` containing the values from `batch_matrices[i]`, with possibly broadcast batch dims. Raises: ValueError: If any input `Tensor` is statically determined to have less than two dimensions. """ with ops.name_scope( name or "broadcast_matrix_batch_dims", values=batch_matrices): check_ops.assert_proper_iterable(batch_matrices) batch_matrices = list(batch_matrices) for i, mat in enumerate(batch_matrices): batch_matrices[i] = ops.convert_to_tensor_v2_with_dispatch(mat) assert_is_batch_matrix(batch_matrices[i]) if len(batch_matrices) < 2: return batch_matrices # Try static broadcasting. # bcast_batch_shape is the broadcast batch shape of ALL matrices. # E.g. if batch_matrices = [x, y], with # x.shape = [2, j, k] (batch shape = [2]) # y.shape = [3, 1, l, m] (batch shape = [3, 1]) # ==> bcast_batch_shape = [3, 2] bcast_batch_shape = batch_matrices[0].shape[:-2] for mat in batch_matrices[1:]: bcast_batch_shape = array_ops.broadcast_static_shape( bcast_batch_shape, mat.shape[:-2]) if bcast_batch_shape.is_fully_defined(): for i, mat in enumerate(batch_matrices): if mat.shape[:-2] != bcast_batch_shape: bcast_shape = array_ops.concat( [bcast_batch_shape.as_list(), array_ops.shape(mat)[-2:]], axis=0) batch_matrices[i] = array_ops.broadcast_to(mat, bcast_shape) return batch_matrices # Since static didn't work, do dynamic, which always copies data. bcast_batch_shape = array_ops.shape(batch_matrices[0])[:-2] for mat in batch_matrices[1:]: bcast_batch_shape = array_ops.broadcast_dynamic_shape( bcast_batch_shape, array_ops.shape(mat)[:-2]) for i, mat in enumerate(batch_matrices): batch_matrices[i] = array_ops.broadcast_to( mat, array_ops.concat( [bcast_batch_shape, array_ops.shape(mat)[-2:]], axis=0)) return batch_matrices def matrix_solve_with_broadcast(matrix, rhs, adjoint=False, name=None): """Solve systems of linear equations.""" with ops.name_scope(name, "MatrixSolveWithBroadcast", [matrix, rhs]): matrix = ops.convert_to_tensor_v2_with_dispatch(matrix, name="matrix") rhs = ops.convert_to_tensor_v2_with_dispatch( rhs, name="rhs", dtype=matrix.dtype) # If either matrix/rhs has extra dims, we can reshape to get rid of them. matrix, rhs, reshape_inv, still_need_to_transpose = _reshape_for_efficiency( matrix, rhs, adjoint_a=adjoint) # This will broadcast by brute force if we still need to. matrix, rhs = broadcast_matrix_batch_dims([matrix, rhs]) solution = linalg_ops.matrix_solve( matrix, rhs, adjoint=adjoint and still_need_to_transpose) return reshape_inv(solution) def _reshape_for_efficiency(a, b, transpose_a=False, transpose_b=False, adjoint_a=False, adjoint_b=False): """Maybe reshape a, b, and return an inverse map. For matmul/solve.""" def identity(x): return x # At this point, we have not taken transpose/adjoint of a/b. still_need_to_transpose = True if a.shape.ndims is None or b.shape.ndims is None: return a, b, identity, still_need_to_transpose # This could be handled in the future, but seems less common. if a.shape.ndims >= b.shape.ndims: return a, b, identity, still_need_to_transpose # From now on, we might modify b, but will not modify a. # Suppose: # a.shape = C + [m, n], b.shape = # b.shape = S + C + [n, r] b_extra_ndims = b.shape.ndims - a.shape.ndims # b_extra_sh = S, b_main_sh = C + [n, r] b_extra_sh = array_ops.shape(b)[:b_extra_ndims] b_main_sh = array_ops.shape(b)[b_extra_ndims:] # No reason to flip unless the extra dims of b are big enough. Why? # Assume adjoint/transpose = False. Then... # By not flipping, we have to replicate a to shape # b_extra_sh + a.shape, # which could use extra memory. But in all cases, the final output has shape # b_extra_sh + a.shape[:-1] + [b.shape[-1]] # So we only end up creating a larger object if the end dim of b is smaller # than the end dim of a. This often happens, e.g. if b was a vector that was # expanded to a matrix (by appending a singleton). # Since adjoint/transpose may not be False, we must make adjustments here. # The dim of b that holds the multiple equations. a_domain_sz_ = a.shape[-2 if adjoint_a or transpose_a else -1] b_eq_sz_ = b.shape[-2 if adjoint_b or transpose_b else -1] b_extra_sz_ = ( np.prod(b.shape[:b_extra_ndims].as_list()) if b.shape[:b_extra_ndims].is_fully_defined() else None) if (a_domain_sz_ is not None and b_eq_sz_ is not None and b_extra_sz_ is not None): if b_extra_sz_ < 2 or a_domain_sz_ <= b_eq_sz_: return a, b, identity, still_need_to_transpose # At this point, we're flipping for sure! # Any transposes/adjoints will happen here explicitly, rather than in calling # code. Why? To avoid having to write separate complex code for each case. if adjoint_a: a = array_ops.matrix_transpose(a, conjugate=True) elif transpose_a: a = array_ops.matrix_transpose(a, conjugate=False) if adjoint_b: b = array_ops.matrix_transpose(b, conjugate=True) elif transpose_a: b = array_ops.matrix_transpose(b, conjugate=False) still_need_to_transpose = False # Recompute shapes, since the transpose/adjoint may have changed them. b_extra_sh = array_ops.shape(b)[:b_extra_ndims] b_main_sh = array_ops.shape(b)[b_extra_ndims:] # Permutation to put the extra dims at the end. perm = ( np.concatenate( (np.arange(b_extra_ndims, b.shape.ndims), np.arange(0, b_extra_ndims)), 0)) b_extra_on_end = array_ops.transpose(b, perm=perm) # Now squash this end into one long dim. b_squashed_end = array_ops.reshape( b_extra_on_end, array_ops.concat((b_main_sh[:-1], [-1]), 0)) def reshape_inv(y): # Expand the extra dims hanging off the end, "b_extra_sh". # Note we use y_sh[:-1] + [b_main_sh[-1]] rather than b_main_sh, because y # Could have different batch dims than a and b, because of broadcasting. y_extra_shape = array_ops.concat( (array_ops.shape(y)[:-1], [b_main_sh[-1]], b_extra_sh), 0) y_extra_on_end = array_ops.reshape(y, y_extra_shape) inverse_perm = np.argsort(perm) return array_ops.transpose(y_extra_on_end, perm=inverse_perm) return a, b_squashed_end, reshape_inv, still_need_to_transpose ################################################################################ # Helpers for hints. ################################################################################ def use_operator_or_provided_hint_unless_contradicting( operator, hint_attr_name, provided_hint_value, message): """Get combined hint in the case where operator.hint should equal hint. Args: operator: LinearOperator that a meta-operator was initialized with. hint_attr_name: String name for the attribute. provided_hint_value: Bool or None. Value passed by user in initialization. message: Error message to print if hints contradict. Returns: True, False, or None. Raises: ValueError: If hints contradict. """ op_hint = getattr(operator, hint_attr_name) # pylint: disable=g-bool-id-comparison if op_hint is False and provided_hint_value: raise ValueError(message) if op_hint and provided_hint_value is False: raise ValueError(message) if op_hint or provided_hint_value: return True if op_hint is False or provided_hint_value is False: return False # pylint: enable=g-bool-id-comparison return None ################################################################################ # Utilities for blockwise operators. ################################################################################ def arg_is_blockwise(block_dimensions, arg, arg_split_dim): """Detect if input should be interpreted as a list of blocks.""" # Tuples and lists of length equal to the number of operators may be # blockwise. if (isinstance(arg, (tuple, list)) and len(arg) == len(block_dimensions)): # If the elements of the iterable are not nested, interpret the input as # blockwise. if not any(nest.is_nested(x) for x in arg): return True else: arg_dims = [ops.convert_to_tensor_v2_with_dispatch( x).shape[arg_split_dim] for x in arg] self_dims = [dim.value for dim in block_dimensions] # If none of the operator dimensions are known, interpret the input as # blockwise if its matching dimensions are unequal. if all(self_d is None for self_d in self_dims): # A nested tuple/list with a single outermost element is not blockwise if len(arg_dims) == 1: return False elif any(dim != arg_dims[0] for dim in arg_dims): return True else: raise ValueError( "Parsing of the input structure is ambiguous. Please input " "a blockwise iterable of `Tensor`s or a single `Tensor`.") # If input dimensions equal the respective (known) blockwise operator # dimensions, then the input is blockwise. if all(self_d == arg_d or self_d is None for self_d, arg_d in zip(self_dims, arg_dims)): return True # If input dimensions equals are all equal, and are greater than or equal # to the sum of the known operator dimensions, interpret the input as # blockwise. # input is not blockwise. self_dim = sum(self_d for self_d in self_dims if self_d is not None) if all(s == arg_dims[0] for s in arg_dims) and arg_dims[0] >= self_dim: return False # If none of these conditions is met, the input shape is mismatched. raise ValueError("Input dimension does not match operator dimension.") else: return False def split_arg_into_blocks(block_dims, block_dims_fn, arg, axis=-1): """Split `x` into blocks matching `operators`'s `domain_dimension`. Specifically, if we have a blockwise lower-triangular matrix, with block sizes along the diagonal `[M_j, M_j] j = 0,1,2..J`, this method splits `arg` on `axis` into `J` tensors, whose shape at `axis` is `M_j`. Args: block_dims: Iterable of `TensorShapes`. block_dims_fn: Callable returning an iterable of `Tensor`s. arg: `Tensor`. `arg` is split into `J` tensors. axis: Python `Integer` representing the axis to split `arg` on. Returns: A list of `Tensor`s. """ block_sizes = [dim.value for dim in block_dims] if any(d is None for d in block_sizes): block_sizes = block_dims_fn() return array_ops.split(arg, block_sizes, axis=axis)
# Copyright 2020 gRPC 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. import functools import json import logging import subprocess import time from typing import List, Optional, Tuple from kubernetes import client from kubernetes import utils import kubernetes.config # TODO(sergiitk): replace with tenacity import retrying logger = logging.getLogger(__name__) # Type aliases V1Deployment = client.V1Deployment V1ServiceAccount = client.V1ServiceAccount V1Pod = client.V1Pod V1PodList = client.V1PodList V1Service = client.V1Service V1Namespace = client.V1Namespace ApiException = client.ApiException def simple_resource_get(func): def wrap_not_found_return_none(*args, **kwargs): try: return func(*args, **kwargs) except client.ApiException as e: if e.status == 404: # Ignore 404 return None raise return wrap_not_found_return_none def label_dict_to_selector(labels: dict) -> str: return ','.join(f'{k}=={v}' for k, v in labels.items()) class KubernetesApiManager: def __init__(self, context): self.context = context self.client = self._cached_api_client_for_context(context) self.apps = client.AppsV1Api(self.client) self.core = client.CoreV1Api(self.client) def close(self): self.client.close() @classmethod @functools.lru_cache(None) def _cached_api_client_for_context(cls, context: str) -> client.ApiClient: client_instance = kubernetes.config.new_client_from_config( context=context) logger.info('Using kubernetes context "%s", active host: %s', context, client_instance.configuration.host) return client_instance class PortForwardingError(Exception): """Error forwarding port""" class KubernetesNamespace: NEG_STATUS_META = 'cloud.google.com/neg-status' PORT_FORWARD_LOCAL_ADDRESS: str = '127.0.0.1' DELETE_GRACE_PERIOD_SEC: int = 5 WAIT_SHORT_TIMEOUT_SEC: int = 60 WAIT_SHORT_SLEEP_SEC: int = 1 WAIT_MEDIUM_TIMEOUT_SEC: int = 5 * 60 WAIT_MEDIUM_SLEEP_SEC: int = 10 WAIT_LONG_TIMEOUT_SEC: int = 10 * 60 WAIT_LONG_SLEEP_SEC: int = 30 def __init__(self, api: KubernetesApiManager, name: str): self.name = name self.api = api def apply_manifest(self, manifest): return utils.create_from_dict(self.api.client, manifest, namespace=self.name) @simple_resource_get def get_service(self, name) -> V1Service: return self.api.core.read_namespaced_service(name, self.name) @simple_resource_get def get_service_account(self, name) -> V1Service: return self.api.core.read_namespaced_service_account(name, self.name) def delete_service(self, name, grace_period_seconds=DELETE_GRACE_PERIOD_SEC): self.api.core.delete_namespaced_service( name=name, namespace=self.name, body=client.V1DeleteOptions( propagation_policy='Foreground', grace_period_seconds=grace_period_seconds)) def delete_service_account(self, name, grace_period_seconds=DELETE_GRACE_PERIOD_SEC): self.api.core.delete_namespaced_service_account( name=name, namespace=self.name, body=client.V1DeleteOptions( propagation_policy='Foreground', grace_period_seconds=grace_period_seconds)) @simple_resource_get def get(self) -> V1Namespace: return self.api.core.read_namespace(self.name) def delete(self, grace_period_seconds=DELETE_GRACE_PERIOD_SEC): self.api.core.delete_namespace( name=self.name, body=client.V1DeleteOptions( propagation_policy='Foreground', grace_period_seconds=grace_period_seconds)) def wait_for_service_deleted(self, name: str, timeout_sec=WAIT_SHORT_TIMEOUT_SEC, wait_sec=WAIT_SHORT_SLEEP_SEC): @retrying.retry(retry_on_result=lambda r: r is not None, stop_max_delay=timeout_sec * 1000, wait_fixed=wait_sec * 1000) def _wait_for_deleted_service_with_retry(): service = self.get_service(name) if service is not None: logger.debug('Waiting for service %s to be deleted', service.metadata.name) return service _wait_for_deleted_service_with_retry() def wait_for_service_account_deleted(self, name: str, timeout_sec=WAIT_SHORT_TIMEOUT_SEC, wait_sec=WAIT_SHORT_SLEEP_SEC): @retrying.retry(retry_on_result=lambda r: r is not None, stop_max_delay=timeout_sec * 1000, wait_fixed=wait_sec * 1000) def _wait_for_deleted_service_account_with_retry(): service_account = self.get_service_account(name) if service_account is not None: logger.debug('Waiting for service account %s to be deleted', service_account.metadata.name) return service_account _wait_for_deleted_service_account_with_retry() def wait_for_namespace_deleted(self, timeout_sec=WAIT_LONG_TIMEOUT_SEC, wait_sec=WAIT_LONG_SLEEP_SEC): @retrying.retry(retry_on_result=lambda r: r is not None, stop_max_delay=timeout_sec * 1000, wait_fixed=wait_sec * 1000) def _wait_for_deleted_namespace_with_retry(): namespace = self.get() if namespace is not None: logger.debug('Waiting for namespace %s to be deleted', namespace.metadata.name) return namespace _wait_for_deleted_namespace_with_retry() def wait_for_service_neg(self, name: str, timeout_sec=WAIT_SHORT_TIMEOUT_SEC, wait_sec=WAIT_SHORT_SLEEP_SEC): @retrying.retry(retry_on_result=lambda r: not r, stop_max_delay=timeout_sec * 1000, wait_fixed=wait_sec * 1000) def _wait_for_service_neg(): service = self.get_service(name) if self.NEG_STATUS_META not in service.metadata.annotations: logger.debug('Waiting for service %s NEG', service.metadata.name) return False return True _wait_for_service_neg() def get_service_neg(self, service_name: str, service_port: int) -> Tuple[str, List[str]]: service = self.get_service(service_name) neg_info: dict = json.loads( service.metadata.annotations[self.NEG_STATUS_META]) neg_name: str = neg_info['network_endpoint_groups'][str(service_port)] neg_zones: List[str] = neg_info['zones'] return neg_name, neg_zones @simple_resource_get def get_deployment(self, name) -> V1Deployment: return self.api.apps.read_namespaced_deployment(name, self.name) def delete_deployment(self, name, grace_period_seconds=DELETE_GRACE_PERIOD_SEC): self.api.apps.delete_namespaced_deployment( name=name, namespace=self.name, body=client.V1DeleteOptions( propagation_policy='Foreground', grace_period_seconds=grace_period_seconds)) def list_deployment_pods(self, deployment: V1Deployment) -> List[V1Pod]: # V1LabelSelector.match_expressions not supported at the moment return self.list_pods_with_labels(deployment.spec.selector.match_labels) def wait_for_deployment_available_replicas( self, name, count=1, timeout_sec=WAIT_MEDIUM_TIMEOUT_SEC, wait_sec=WAIT_MEDIUM_SLEEP_SEC): @retrying.retry( retry_on_result=lambda r: not self._replicas_available(r, count), stop_max_delay=timeout_sec * 1000, wait_fixed=wait_sec * 1000) def _wait_for_deployment_available_replicas(): deployment = self.get_deployment(name) logger.debug( 'Waiting for deployment %s to have %s available ' 'replicas, current count %s', deployment.metadata.name, count, deployment.status.available_replicas) return deployment _wait_for_deployment_available_replicas() def wait_for_deployment_deleted(self, deployment_name: str, timeout_sec=WAIT_MEDIUM_TIMEOUT_SEC, wait_sec=WAIT_MEDIUM_SLEEP_SEC): @retrying.retry(retry_on_result=lambda r: r is not None, stop_max_delay=timeout_sec * 1000, wait_fixed=wait_sec * 1000) def _wait_for_deleted_deployment_with_retry(): deployment = self.get_deployment(deployment_name) if deployment is not None: logger.debug( 'Waiting for deployment %s to be deleted. ' 'Non-terminated replicas: %s', deployment.metadata.name, deployment.status.replicas) return deployment _wait_for_deleted_deployment_with_retry() def list_pods_with_labels(self, labels: dict) -> List[V1Pod]: pod_list: V1PodList = self.api.core.list_namespaced_pod( self.name, label_selector=label_dict_to_selector(labels)) return pod_list.items def get_pod(self, name) -> client.V1Pod: return self.api.core.read_namespaced_pod(name, self.name) def wait_for_pod_started(self, pod_name, timeout_sec=WAIT_SHORT_TIMEOUT_SEC, wait_sec=WAIT_SHORT_SLEEP_SEC): @retrying.retry(retry_on_result=lambda r: not self._pod_started(r), stop_max_delay=timeout_sec * 1000, wait_fixed=wait_sec * 1000) def _wait_for_pod_started(): pod = self.get_pod(pod_name) logger.debug('Waiting for pod %s to start, current phase: %s', pod.metadata.name, pod.status.phase) return pod _wait_for_pod_started() def port_forward_pod( self, pod: V1Pod, remote_port: int, local_port: Optional[int] = None, local_address: Optional[str] = None, ) -> subprocess.Popen: """Experimental""" local_address = local_address or self.PORT_FORWARD_LOCAL_ADDRESS local_port = local_port or remote_port cmd = [ "kubectl", "--context", self.api.context, "--namespace", self.name, "port-forward", "--address", local_address, f"pod/{pod.metadata.name}", f"{local_port}:{remote_port}" ] pf = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) # Wait for stdout line indicating successful start. expected = (f"Forwarding from {local_address}:{local_port}" f" -> {remote_port}") try: while True: time.sleep(0.05) output = pf.stdout.readline().strip() if not output: return_code = pf.poll() if return_code is not None: errors = [error for error in pf.stdout.readlines()] raise PortForwardingError( 'Error forwarding port, kubectl return ' f'code {return_code}, output {errors}') elif output != expected: raise PortForwardingError( f'Error forwarding port, unexpected output {output}') else: logger.info(output) break except Exception: self.port_forward_stop(pf) raise # TODO(sergiitk): return new PortForwarder object return pf @staticmethod def port_forward_stop(pf): logger.info('Shutting down port forwarding, pid %s', pf.pid) pf.kill() stdout, _stderr = pf.communicate(timeout=5) logger.info('Port forwarding stopped') logger.debug('Port forwarding remaining stdout: %s', stdout) @staticmethod def _pod_started(pod: V1Pod): return pod.status.phase not in ('Pending', 'Unknown') @staticmethod def _replicas_available(deployment, count): return (deployment is not None and deployment.status.available_replicas is not None and deployment.status.available_replicas >= count)
import pylab as pyl from astLib import astStats from sklearn.metrics import median_absolute_error, mean_squared_error import h5py as hdf from matplotlib.ticker import AutoMinorLocator def calc_err(pred, true): return (pred - true) / true golden_mean = (pyl.sqrt(5.) - 1.0) / 2.0 f = pyl.figure(1, figsize=(10, 10 * golden_mean)) ax1 = pyl.subplot2grid((3, 4), (0, 0), rowspan=2) ax2 = pyl.subplot2grid((3, 4), (0, 1), rowspan=2, sharex=ax1) ax3 = pyl.subplot2grid((3, 4), (0, 2), rowspan=2, sharex=ax1, sharey=ax2) ax4 = pyl.subplot2grid((3, 4), (0, 3), rowspan=2, sharex=ax1, sharey=ax2) # now for the bottom bits ax1s = pyl.subplot2grid((3, 4), (2, 0)) ax2s = pyl.subplot2grid((3, 4), (2, 1), sharex=ax1s) ax3s = pyl.subplot2grid((3, 4), (2, 2), sharex=ax1s, sharey=ax2s) ax4s = pyl.subplot2grid((3, 4), (2, 3), sharex=ax1s, sharey=ax2s) ax2.set_yticklabels([]) ax1.set_xticklabels([]) ax2s.set_yticklabels([]) # add minor ticks to the bottom ax1s.yaxis.set_minor_locator(AutoMinorLocator()) ax2s.yaxis.set_minor_locator(AutoMinorLocator()) ### Perfect ### ############### #with hdf.File('./targetedPerfect_Probmasses.hdf5', 'r') as f: with hdf.File('./targetedPerfect_Probmasses_realisticOnly.hdf5', 'r') as f: dset = f[list(f.keys())[0]] perfect = dset['M200c', 'MASS', 'Prob_pred_1d', 'Prob_pred_2d', 'Prob_pred_3d'] # filter bad values mask = ((perfect['Prob_pred_1d'] == 0) | (perfect['Prob_pred_2d'] == 0) | (perfect['Prob_pred_3d'] == 0)) perfect = perfect[~mask] ### Targeted ### ################ with hdf.File('./targetedRealistic_Probmasses.hdf5', 'r') as f: dset = f[list(f.keys())[0]] target = dset['M200c', 'MASS', 'Prob_pred_1d', 'Prob_pred_2d', 'Prob_pred_3d'] # filter bad values mask = ((target['Prob_pred_1d'] == 0) | (target['Prob_pred_2d'] == 0) | (target['Prob_pred_3d'] == 0)) target = target[~mask] ### Survey ### ############## with hdf.File('./surveyCompleteRealistic_Probmasses.hdf5', 'r') as f: dset = f[list(f.keys())[0]] survey = dset['M200c', 'MASS', 'Prob_pred_1d', 'Prob_pred_2d', 'Prob_pred_3d'] # filter bad values mask = ((survey['Prob_pred_1d'] == 0) | (survey['Prob_pred_2d'] == 0) | (survey['Prob_pred_3d'] == 0)) survey = survey[~mask] # plot one to one lines ax1.plot([12, 15.5], [12, 15.5], c='k', zorder=0) ax2.plot([12, 15.5], [12, 15.5], c='k', zorder=0) ax3.plot([12, 15.5], [12, 15.5], c='k', zorder=0) ax4.plot([12, 15.5], [12, 15.5], c='k', zorder=0) ax1s.axhline(0, zorder=0) ax2s.axhline(0, zorder=0) ax3s.axhline(0, zorder=0) ax4s.axhline(0, zorder=0) # now for the plotting ################### #### Power Law #### ################### for d, c, style, zo in zip([target, survey, perfect], ['#7A68A6', '#188487', '#e24a33'], ['-', '--', '-.'], [1, 2, 0]): print('power law') y_ = astStats.runningStatistic( pyl.log10(d['M200c']), pyl.log10(d['MASS']), pyl.percentile, binNumber=20, q=[16, 50, 84]) quants = pyl.array(y_[1]) ax1.plot(y_[0], quants[:, 1], style, c=c, zorder=zo) if not c == '#e24a33': ax1.fill_between(y_[0], quants[:, 2], quants[:, 0], facecolor=c, alpha=0.3, edgecolor=c) err = calc_err(d['MASS'], d['M200c']) y_ = astStats.runningStatistic( pyl.log10(d['M200c']), err, pyl.percentile, binNumber=20, q=[16, 50, 84]) quants = pyl.array(y_[1]) ax1s.plot(y_[0], quants[:, 1], style, c=c, zorder=zo) if not c == '#e24a33': ax1s.fill_between(y_[0], quants[:, 2], quants[:, 0], facecolor=c, alpha=0.3, edgecolor=c) print('MAE', median_absolute_error( pyl.log10(d['M200c']), pyl.log10(d['MASS']))) print('RMSE', pyl.sqrt(mean_squared_error( pyl.log10(d['M200c']), pyl.log10(d['MASS'])))) ############ #### 1d #### ############ print('1d') y_ = astStats.runningStatistic( pyl.log10(d['M200c']), d['Prob_pred_1d'], pyl.percentile, binNumber=20, q=[16, 50, 84]) quants = pyl.array(y_[1]) ax2.plot(y_[0], quants[:, 1], style, c=c, zorder=zo) if not c == '#e24a33': ax2.fill_between(y_[0], quants[:, 2], quants[:, 0], facecolor=c, alpha=0.4, edgecolor=c) err = calc_err(10**d['Prob_pred_1d'], d['M200c']) y_ = astStats.runningStatistic( pyl.log10(d['M200c']), err, pyl.percentile, binNumber=20, q=[16, 50, 84]) quants = pyl.array(y_[1]) ax2s.plot(y_[0], quants[:, 1], style, c=c, zorder=zo) if not c == '#e24a33': ax2s.fill_between(y_[0], quants[:, 2], quants[:, 0], facecolor=c, alpha=0.4, edgecolor=c) print('MAE', median_absolute_error( pyl.log10(d['M200c']), d['Prob_pred_1d'])) print('RMSE', pyl.sqrt(mean_squared_error( pyl.log10(d['M200c']), d['Prob_pred_1d']))) ############# #### 2d ##### ############# print('2d') y_ = astStats.runningStatistic( pyl.log10(d['M200c']), d['Prob_pred_2d'], pyl.percentile, binNumber=20, q=[16, 50, 84]) quants = pyl.array(y_[1]) ax3.plot(y_[0], quants[:, 1], style, c=c, zorder=zo) if not c == '#e24a33': ax3.fill_between(y_[0], quants[:, 2], quants[:, 0], facecolor=c, alpha=0.4, edgecolor=c) err = calc_err(10**d['Prob_pred_2d'], d['M200c']) y_ = astStats.runningStatistic( pyl.log10(d['M200c']), err, pyl.percentile, binNumber=20, q=[16, 50, 84]) quants = pyl.array(y_[1]) ax3s.plot(y_[0], quants[:, 1], style, c=c, zorder=zo) if not c == '#e24a33': ax3s.fill_between(y_[0], quants[:, 2], quants[:, 0], facecolor=c, alpha=0.4, edgecolor=c) print('MAE', median_absolute_error( pyl.log10(d['M200c']), d['Prob_pred_2d'])) print('RMSE', pyl.sqrt(mean_squared_error( pyl.log10(d['M200c']), d['Prob_pred_2d']))) ############## ##### 3d ##### ############## print('3d') y_ = astStats.runningStatistic( pyl.log10(d['M200c']), d['Prob_pred_3d'], pyl.percentile, binNumber=20, q=[16, 50, 84]) quants = pyl.array(y_[1]) ax4.plot(y_[0], quants[:, 1], style, c=c, zorder=zo) if not c == '#e24a33': ax4.fill_between(y_[0], quants[:, 2], quants[:, 0], facecolor=c, alpha=0.4, edgecolor=c) err = calc_err(10**d['Prob_pred_3d'], d['M200c']) y_ = astStats.runningStatistic( pyl.log10(d['M200c']), err, pyl.percentile, binNumber=20, q=[16, 50, 84]) quants = pyl.array(y_[1]) ax4s.plot(y_[0], quants[:, 1], style, c=c, zorder=zo) if not c == '#e24a33': ax4s.fill_between(y_[0], quants[:, 2], quants[:, 0], facecolor=c, alpha=0.4, edgecolor=c) print('MAE', median_absolute_error( pyl.log10(d['M200c']), d['Prob_pred_3d'])) print('RMSE', pyl.sqrt(mean_squared_error( pyl.log10(d['M200c']), d['Prob_pred_3d']))) ### Add Legend ### ################## line1 = pyl.Line2D([], [], ls='-', color='#7A68A6') line2 = pyl.Line2D([], [], ls='--', color='#188487') line3 = pyl.Line2D([], [], ls='-.', color='#e24a33') ax1.legend((line3, line1, line2), ('Perfect', 'Targeted', 'Survey'), loc=2) #### tweak #### ax1.set_xticks([12, 13, 14, 15]) ax2.set_xticks([12, 13, 14, 15]) ax2s.set_xticks([12, 13, 14, 15]) ax1s.set_yticks([-0.5, 0, 0.5]) ax2s.set_yticks([-0.5, 0, 0.5]) ax2.set_ylim(12, 15.5) ax2.set_xlim(11.5, 15.5) ax2s.set_ylim(-1, 1) ax2s.set_xlim(11.5, 15.5) ax1.set_ylim(ax2.get_ylim()) ax1.set_xlim(ax2.get_xlim()) ax1s.set_ylim(ax2s.get_ylim()) ax1s.set_xlim(ax2s.get_xlim()) ax1.set_ylabel('Log $M_{pred}$ ($M_{\odot}$)') ax1s.set_ylabel('$\epsilon$') ax1s.set_xlabel('Log $M_{200c}$ ($M_{\odot}$)', fontsize=18) ax2s.set_xlabel('Log $M_{200c}$ ($M_{\odot}$)', fontsize=18) ax3s.set_xlabel('Log $M_{200c}$ ($M_{\odot}$)', fontsize=18) ax4s.set_xlabel('Log $M_{200c}$ ($M_{\odot}$)', fontsize=18) ax1.text(14, 12.25, 'Power Law', fontsize=18, horizontalalignment='center', fontweight='medium') ax2.text(14, 12.25, '$Prob_{\sigma}$', fontsize=18, horizontalalignment='center', fontweight='medium') ax3.text(14, 12.25, '$Prob_{\sigma, z}$', fontsize=18, horizontalalignment='center', fontweight='medium') ax4.text(14, 12.25, '$Prob_{\sigma, z, Ngal}$', fontsize=18, horizontalalignment='center', fontweight='medium') pyl.show()
import logging from datetime import datetime from typing import Any, Dict, List, Optional, Tuple from urllib.parse import urljoin from django.http import HttpRequest, HttpResponse from zerver.decorator import webhook_view from zerver.lib.exceptions import UnsupportedWebhookEventType from zerver.lib.request import REQ, has_request_variables from zerver.lib.response import json_success from zerver.lib.webhooks.common import check_send_webhook_message from zerver.models import UserProfile DEPRECATED_EXCEPTION_MESSAGE_TEMPLATE = """ New [issue]({url}) (level: {level}): ``` quote {message} ``` """ MESSAGE_EVENT_TEMPLATE = """ **New message event:** [{title}]({web_link}) ```quote **level:** {level} **timestamp:** {datetime} ``` """ EXCEPTION_EVENT_TEMPLATE = """ **New exception:** [{title}]({web_link}) ```quote **level:** {level} **timestamp:** {datetime} **filename:** {filename} ``` """ EXCEPTION_EVENT_TEMPLATE_WITH_TRACEBACK = ( EXCEPTION_EVENT_TEMPLATE + """ Traceback: ```{syntax_highlight_as} {pre_context}---> {context_line}{post_context}\ ``` """ ) # Because of the \n added at the end of each context element, # this will actually look better in the traceback. ISSUE_CREATED_MESSAGE_TEMPLATE = """ **New issue created:** {title} ```quote **level:** {level} **timestamp:** {datetime} **assignee:** {assignee} ``` """ ISSUE_ASSIGNED_MESSAGE_TEMPLATE = """ Issue **{title}** has now been assigned to **{assignee}** by **{actor}**. """ ISSUE_RESOLVED_MESSAGE_TEMPLATE = """ Issue **{title}** was marked as resolved by **{actor}**. """ ISSUE_IGNORED_MESSAGE_TEMPLATE = """ Issue **{title}** was ignored by **{actor}**. """ # Maps "platform" name provided by Sentry to the Pygments lexer name syntax_highlight_as_map = { "go": "go", "java": "java", "javascript": "javascript", "node": "javascript", "python": "python3", } def convert_lines_to_traceback_string(lines: Optional[List[str]]) -> str: traceback = "" if lines is not None: for line in lines: if line == "": traceback += "\n" else: traceback += f" {line}\n" return traceback def handle_event_payload(event: Dict[str, Any]) -> Tuple[str, str]: """Handle either an exception type event or a message type event payload.""" # We shouldn't support the officially deprecated Raven series of SDKs. if int(event["version"]) < 7: raise UnsupportedWebhookEventType("Raven SDK") subject = event["title"] platform_name = event["platform"] syntax_highlight_as = syntax_highlight_as_map.get(platform_name, "") if syntax_highlight_as == "": # nocoverage logging.info("Unknown Sentry platform: %s", platform_name) context = { "title": subject, "level": event["level"], "web_link": event["web_url"], "datetime": event["datetime"].split(".")[0].replace("T", " "), } if "exception" in event: # The event was triggered by a sentry.capture_exception() call # (in the Python Sentry SDK) or something similar. filename = event["metadata"].get("filename", None) stacktrace = None for value in reversed(event["exception"]["values"]): if "stacktrace" in value: stacktrace = value["stacktrace"] break if stacktrace and filename: exception_frame = None for frame in reversed(stacktrace["frames"]): if frame.get("filename", None) == filename: exception_frame = frame break if exception_frame and "context_line" in exception_frame: pre_context = convert_lines_to_traceback_string( exception_frame.get("pre_context", None) ) context_line = exception_frame["context_line"] + "\n" post_context = convert_lines_to_traceback_string( exception_frame.get("post_context", None) ) context.update( syntax_highlight_as=syntax_highlight_as, filename=filename, pre_context=pre_context, context_line=context_line, post_context=post_context, ) body = EXCEPTION_EVENT_TEMPLATE_WITH_TRACEBACK.format(**context) return (subject, body) context.update(filename=filename) # nocoverage body = EXCEPTION_EVENT_TEMPLATE.format(**context) # nocoverage return (subject, body) # nocoverage elif "logentry" in event: # The event was triggered by a sentry.capture_message() call # (in the Python Sentry SDK) or something similar. body = MESSAGE_EVENT_TEMPLATE.format(**context) else: raise UnsupportedWebhookEventType("unknown-event type") return (subject, body) def handle_issue_payload( action: str, issue: Dict[str, Any], actor: Dict[str, Any] ) -> Tuple[str, str]: """Handle either an issue type event.""" subject = issue["title"] datetime = issue["lastSeen"].split(".")[0].replace("T", " ") if issue["assignedTo"]: if issue["assignedTo"]["type"] == "team": assignee = "team {}".format(issue["assignedTo"]["name"]) else: assignee = issue["assignedTo"]["name"] else: assignee = "No one" if action == "created": context = { "title": subject, "level": issue["level"], "datetime": datetime, "assignee": assignee, } body = ISSUE_CREATED_MESSAGE_TEMPLATE.format(**context) elif action == "resolved": context = { "title": subject, "actor": actor["name"], } body = ISSUE_RESOLVED_MESSAGE_TEMPLATE.format(**context) elif action == "assigned": context = { "title": subject, "assignee": assignee, "actor": actor["name"], } body = ISSUE_ASSIGNED_MESSAGE_TEMPLATE.format(**context) elif action == "ignored": context = { "title": subject, "actor": actor["name"], } body = ISSUE_IGNORED_MESSAGE_TEMPLATE.format(**context) else: raise UnsupportedWebhookEventType("unknown-issue-action type") return (subject, body) def handle_deprecated_payload(payload: Dict[str, Any]) -> Tuple[str, str]: subject = "{}".format(payload.get("project_name")) body = DEPRECATED_EXCEPTION_MESSAGE_TEMPLATE.format( level=payload["level"].upper(), url=payload.get("url"), message=payload.get("message"), ) return (subject, body) def transform_webhook_payload(payload: Dict[str, Any]) -> Optional[Dict[str, Any]]: """Attempt to use webhook payload for the notification. When the integration is configured as a webhook, instead of being added as an internal integration, the payload is slightly different, but has all the required information for sending a notification. We transform this payload to look like the payload from a "properly configured" integration. """ event = payload.get("event", {}) # deprecated payloads don't have event_id event_id = event.get("event_id") if not event_id: return None event_path = f"events/{event_id}/" event["web_url"] = urljoin(payload["url"], event_path) timestamp = event.get("timestamp", event["received"]) event["datetime"] = datetime.fromtimestamp(timestamp).isoformat() return payload @webhook_view("Sentry") @has_request_variables def api_sentry_webhook( request: HttpRequest, user_profile: UserProfile, payload: Dict[str, Any] = REQ(argument_type="body"), ) -> HttpResponse: data = payload.get("data", None) if data is None: data = transform_webhook_payload(payload) # We currently support two types of payloads: events and issues. if data: if "event" in data: subject, body = handle_event_payload(data["event"]) elif "issue" in data: subject, body = handle_issue_payload(payload["action"], data["issue"], payload["actor"]) else: raise UnsupportedWebhookEventType(str(list(data.keys()))) else: subject, body = handle_deprecated_payload(payload) check_send_webhook_message(request, user_profile, subject, body) return json_success()
# Copyright 2011 Andrew Bogott for the Wikimedia Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import datetime import webob from nova.api.openstack.compute.contrib import flavor_access from nova.api.openstack.compute.contrib import flavormanage from nova.compute import flavors from nova import context from nova import db from nova import exception from nova.openstack.common import jsonutils from nova import test from nova.tests.api.openstack import fakes def fake_get_flavor_by_flavor_id(flavorid, ctxt=None, read_deleted='yes'): if flavorid == 'failtest': raise exception.NotFound("Not found sucka!") elif not str(flavorid) == '1234': raise Exception("This test expects flavorid 1234, not %s" % flavorid) if read_deleted != 'no': raise test.TestingException("Should not be reading deleted") return { 'root_gb': 1, 'ephemeral_gb': 1, 'name': u'frob', 'deleted': False, 'created_at': datetime.datetime(2012, 1, 19, 18, 49, 30, 877329), 'updated_at': None, 'memory_mb': 256, 'vcpus': 1, 'flavorid': flavorid, 'swap': 0, 'rxtx_factor': 1.0, 'extra_specs': {}, 'deleted_at': None, 'vcpu_weight': None, 'id': 7, 'is_public': True, 'disabled': False, } def fake_destroy(flavorname): pass def fake_create(context, kwargs): flavorid = kwargs.get('flavorid') if flavorid is None: flavorid = 1234 newflavor = {'flavorid': flavorid} newflavor["name"] = kwargs.get('name') newflavor["memory_mb"] = int(kwargs.get('memory_mb')) newflavor["vcpus"] = int(kwargs.get('vcpus')) newflavor["root_gb"] = int(kwargs.get('root_gb')) newflavor["ephemeral_gb"] = int(kwargs.get('ephemeral_gb')) newflavor["swap"] = kwargs.get('swap') newflavor["rxtx_factor"] = float(kwargs.get('rxtx_factor')) newflavor["is_public"] = bool(kwargs.get('is_public')) return newflavor class FlavorManageTest(test.NoDBTestCase): def setUp(self): super(FlavorManageTest, self).setUp() self.stubs.Set(flavors, "get_flavor_by_flavor_id", fake_get_flavor_by_flavor_id) self.stubs.Set(flavors, "destroy", fake_destroy) self.stubs.Set(db, "flavor_create", fake_create) self.flags( osapi_compute_extension=[ 'nova.api.openstack.compute.contrib.select_extensions'], osapi_compute_ext_list=['Flavormanage', 'Flavorextradata', 'Flavor_access', 'Flavor_rxtx', 'Flavor_swap']) self.controller = flavormanage.FlavorManageController() self.app = fakes.wsgi_app(init_only=('flavors',)) def test_delete(self): req = fakes.HTTPRequest.blank('/v2/123/flavors/1234') res = self.controller._delete(req, 1234) self.assertEqual(res.status_int, 202) # subsequent delete should fail self.assertRaises(webob.exc.HTTPNotFound, self.controller._delete, req, "failtest") def test_create(self): expected = { "flavor": { "name": "azAZ09. -_", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "id": unicode('1234'), "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True, } } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) body = jsonutils.loads(res.body) for key in expected["flavor"]: self.assertEqual(body["flavor"][key], expected["flavor"][key]) def test_create_invalid_name(self): self.stubs.UnsetAll() expected = { "flavor": { "name": "bad !@#!$% name", 'id': "1", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True, } } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) self.assertEqual(res.status_code, 400) def test_create_flavor_name_is_whitespace(self): request_dict = { "flavor": { "name": " ", 'id': "12345", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True, } } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(request_dict) res = req.get_response(self.app) self.assertEqual(res.status_code, 400) def test_create_flavor_name_with_leading_trailing_whitespace(self): request_dict = { "flavor": { "name": " test ", 'id': "12345", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True, } } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(request_dict) res = req.get_response(self.app) self.assertEqual(res.status_code, 200) body = jsonutils.loads(res.body) self.assertEqual("test", body["flavor"]["name"]) def test_create_public_default(self): flavor = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "id": 1234, "swap": 512, "rxtx_factor": 1, } } expected = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "id": unicode(1234), "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True, } } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(flavor) res = req.get_response(self.app) body = jsonutils.loads(res.body) for key in expected["flavor"]: self.assertEqual(body["flavor"][key], expected["flavor"][key]) def test_create_without_flavorid(self): expected = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True, } } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) body = jsonutils.loads(res.body) for key in expected["flavor"]: self.assertEqual(body["flavor"][key], expected["flavor"][key]) def test_create_without_flavorname(self): expected = { "flavor": { "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True, } } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) self.assertEqual(res.status_int, 400) def test_create_empty_body(self): self.stubs.UnsetAll() expected = { "flavor": {} } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) self.assertEqual(res.status_code, 400) def test_create_no_body(self): self.stubs.UnsetAll() expected = {} url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) self.assertEqual(res.status_code, 400) def test_create_invalid_format_body(self): self.stubs.UnsetAll() expected = { "flavor": [] } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) self.assertEqual(res.status_code, 400) def test_create_invalid_flavorid(self): self.stubs.UnsetAll() expected = { "flavor": { "name": "test", 'id': "!@#!$#!$^#&^$&", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True, } } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) self.assertEqual(res.status_code, 400) def test_create_check_flavor_id_length(self): self.stubs.UnsetAll() MAX_LENGTH = 255 expected = { "flavor": { "name": "test", 'id': "a" * (MAX_LENGTH + 1), "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True, } } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) self.assertEqual(res.status_code, 400) def test_create_with_leading_trailing_whitespaces_in_flavor_id(self): self.stubs.UnsetAll() expected = { "flavor": { "name": "test", 'id': " bad_id ", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True, } } url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) self.assertEqual(res.status_code, 400) def test_flavor_exists_exception_returns_409(self): expected = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "id": 1235, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True, } } def fake_create(name, memory_mb, vcpus, root_gb, ephemeral_gb, flavorid, swap, rxtx_factor, is_public): raise exception.FlavorExists(name=name) self.stubs.Set(flavors, "create", fake_create) url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) self.assertEqual(res.status_int, 409) def test_invalid_memory_mb(self): """Check negative and decimal number can't be accepted.""" self.stubs.UnsetAll() self.assertRaises(exception.InvalidInput, flavors.create, "abc", -512, 2, 1, 1, 1234, 512, 1, True) self.assertRaises(exception.InvalidInput, flavors.create, "abcd", 512.2, 2, 1, 1, 1234, 512, 1, True) self.assertRaises(exception.InvalidInput, flavors.create, "abcde", None, 2, 1, 1, 1234, 512, 1, True) self.assertRaises(exception.InvalidInput, flavors.create, "abcdef", 512, 2, None, 1, 1234, 512, 1, True) self.assertRaises(exception.InvalidInput, flavors.create, "abcdef", "test_memory_mb", 2, None, 1, 1234, 512, 1, True) class FakeRequest(object): environ = {"nova.context": context.get_admin_context()} class PrivateFlavorManageTest(test.TestCase): def setUp(self): super(PrivateFlavorManageTest, self).setUp() # self.stubs.Set(flavors, # "get_flavor_by_flavor_id", # fake_get_flavor_by_flavor_id) # self.stubs.Set(flavors, "destroy", fake_destroy) # self.stubs.Set(flavors, "create", fake_create) self.flags( osapi_compute_extension=[ 'nova.api.openstack.compute.contrib.select_extensions'], osapi_compute_ext_list=['Flavormanage', 'Flavorextradata', 'Flavor_access', 'Flavor_rxtx', 'Flavor_swap']) self.controller = flavormanage.FlavorManageController() self.flavor_access_controller = flavor_access.FlavorAccessController() self.app = fakes.wsgi_app(init_only=('flavors',)) def test_create_private_flavor_should_not_grant_flavor_access(self): expected = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": False } } ctxt = context.RequestContext('fake', 'fake', is_admin=True, auth_token=True) self.app = fakes.wsgi_app(init_only=('flavors',), fake_auth_context=ctxt) url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) body = jsonutils.loads(res.body) for key in expected["flavor"]: self.assertEqual(body["flavor"][key], expected["flavor"][key]) flavor_access_body = self.flavor_access_controller.index( FakeRequest(), body["flavor"]["id"]) expected_flavor_access_body = { "tenant_id": "%s" % ctxt.project_id, "flavor_id": "%s" % body["flavor"]["id"] } self.assertNotIn(expected_flavor_access_body, flavor_access_body["flavor_access"]) def test_create_public_flavor_should_not_create_flavor_access(self): expected = { "flavor": { "name": "test", "ram": 512, "vcpus": 2, "disk": 1, "OS-FLV-EXT-DATA:ephemeral": 1, "swap": 512, "rxtx_factor": 1, "os-flavor-access:is_public": True } } ctxt = context.RequestContext('fake', 'fake', is_admin=True, auth_token=True) self.app = fakes.wsgi_app(init_only=('flavors',), fake_auth_context=ctxt) self.mox.StubOutWithMock(flavors, "add_flavor_access") self.mox.ReplayAll() url = '/v2/fake/flavors' req = webob.Request.blank(url) req.headers['Content-Type'] = 'application/json' req.method = 'POST' req.body = jsonutils.dumps(expected) res = req.get_response(self.app) body = jsonutils.loads(res.body) for key in expected["flavor"]: self.assertEqual(body["flavor"][key], expected["flavor"][key])
#!/usr/bin/env python # # Copyright 2010 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # """Shared resources for handlers.""" import base64 import datetime import logging import os import time from google.appengine.ext import db from google.appengine.ext import deferred from google.appengine.api import memcache from google.appengine import runtime from google.appengine.runtime import apiproxy_errors from simian.mac import models from simian.mac import common from simian.mac.munki import plist as plist_module from simian.mac.common import gae_util from simian.mac.common import util CLIENT_ID_FIELDS = { 'uuid': str, 'owner': str, 'hostname': str, 'serial': str, 'config_track': str, 'track': str, 'site': str, 'office': str, 'os_version': str, 'client_version': str, 'on_corp': bool, 'last_notified_datetime': str, 'uptime': float, 'root_disk_free': int, 'user_disk_free': int, 'applesus': bool, 'runtype': str, } CONNECTION_DATETIMES_LIMIT = 10 CONNECTION_DATES_LIMIT = 30 # If the datastore goes write-only, delay a write for x seconds: DATASTORE_NOWRITE_DELAY = 60 # Panic mode prefix for key names in KeyValueCache PANIC_MODE_PREFIX = 'panic_mode_' # Panic mode which disables all packages PANIC_MODE_NO_PACKAGES = 'no_packages' PANIC_MODES = [PANIC_MODE_NO_PACKAGES] FLASH_PLUGIN_NAME = 'flashplugin' FLASH_PLUGIN_DEBUG_NAME = 'flash_player_debug' # Apple Software Update pkgs_to_install text format. APPLESUS_PKGS_TO_INSTALL_FORMAT = 'AppleSUS: %s' # Serial numbers for which first connection de-duplication should be skipped. DUPE_SERIAL_NUMBER_EXCEPTIONS = [ 'SystemSerialNumb', 'System Serial#', 'Not Available', None] class Error(Exception): """Base Error.""" class ComputerNotFoundError(Error): """Computer could not be found.""" class ManifestNotFoundError(Error): """Manifest requested was not found.""" class ManifestDisabledError(Error): """Disable manifest was requested.""" def _SaveFirstConnection(client_id, computer): """Function to save first connection of a given client. Args: client_id: dict client id. computer: models.Computer entity. """ #logging.debug('Saving first connection for: %s' % client_id) e = models.FirstClientConnection(key_name=client_id['uuid']) e.computer = computer e.owner = client_id['owner'] e.hostname = client_id['hostname'] e.office = client_id['office'] e.site = client_id['site'] e.put() # Set older computers with the same serial number as inactive. if computer.serial not in DUPE_SERIAL_NUMBER_EXCEPTIONS: for dupe in models.Computer.AllActive().filter('serial =', computer.serial): # skip over the new client. if dupe.uuid == computer.uuid: continue # if the dupe is clearly older, mark as inactive. if dupe.preflight_datetime < computer.preflight_datetime: dupe.active = False dupe.put(update_active=False) def LogClientConnection( event, client_id, user_settings=None, pkgs_to_install=None, apple_updates_to_install=None, ip_address=None, report_feedback=None, computer=None, delay=0): """Logs a host checkin to Simian. Args: event: str name of the event that prompted a client connection log. client_id: dict client id with fields: uuid, hostname, owner. user_settings: optional dict of user settings. pkgs_to_install: optional list of string packages remaining to install. apple_updates_to_install: optional list of string Apple updates remaining to install. ip_address: str IP address of the connection. report_feedback: dict ReportFeedback commands sent to the client. computer: optional models.Computer object. delay: int. if > 0, LogClientConnection call is deferred this many seconds. """ #logging.debug( # ('LogClientConnection(%s, %s, user_settings? %s, pkgs_to_install: %s, ' # 'ip_address: %s, delay=%s)'), # event, client_id, user_settings not in [None, {}], pkgs_to_install, # ip_address, delay) if delay: #logging.debug('Delaying LogClientConnection call %s seconds', delay) now_str = datetime.datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S') deferred_name = 'log-client-conn-%s-%s' % (client_id['uuid'], now_str) deferred.defer( LogClientConnection, event, client_id, user_settings=user_settings, pkgs_to_install=pkgs_to_install, ip_address=ip_address, apple_updates_to_install=apple_updates_to_install, report_feedback=report_feedback, _name=deferred_name, _countdown=delay) return if not client_id['uuid']: logging.warning('LogClientConnection: uuid is unknown, skipping log') return def __UpdateComputerEntity( event, _client_id, _user_settings, _pkgs_to_install, _apple_updates_to_install, _ip_address, _report_feedback, c=None): """Update the computer entity, or create a new one if it doesn't exists.""" now = datetime.datetime.utcnow() is_new_client = False if c is None: c = models.Computer.get_by_key_name(_client_id['uuid']) if c is None: # First time this client has connected. c = models.Computer(key_name=_client_id['uuid']) is_new_client = True c.uuid = _client_id['uuid'] c.hostname = _client_id['hostname'] c.serial= _client_id['serial'] c.owner = _client_id['owner'] c.track = _client_id['track'] c.site = _client_id['site'] c.office = _client_id['office'] c.config_track = _client_id['config_track'] c.client_version = _client_id['client_version'] c.os_version = _client_id['os_version'] c.uptime = _client_id['uptime'] c.root_disk_free = _client_id['root_disk_free'] c.user_disk_free = _client_id['user_disk_free'] c.runtype = _client_id['runtype'] c.ip_address = _ip_address last_notified_datetime = _client_id['last_notified_datetime'] if last_notified_datetime: # might be None try: last_notified_datetime = datetime.datetime.strptime( last_notified_datetime, '%Y-%m-%d %H:%M:%S') # timestamp is UTC. c.last_notified_datetime = last_notified_datetime except ValueError: # non-standard datetime sent. logging.warning( 'Non-standard last_notified_datetime: %s', last_notified_datetime) # Update event specific (preflight vs postflight) report values. if event == 'preflight': c.preflight_datetime = now if _client_id['on_corp'] == True: c.last_on_corp_preflight_datetime = now # Increment the number of preflight connections since the last successful # postflight, but only if the current connection is not going to exit due # to report feedback (WWAN, GoGo InFlight, etc.) if not _report_feedback or not _report_feedback.get('exit'): if c.preflight_count_since_postflight is not None: c.preflight_count_since_postflight += 1 else: c.preflight_count_since_postflight = 1 elif event == 'postflight': c.preflight_count_since_postflight = 0 c.postflight_datetime = now # Update pkgs_to_install. if _pkgs_to_install: c.pkgs_to_install = _pkgs_to_install c.all_pkgs_installed = False else: c.pkgs_to_install = [] c.all_pkgs_installed = True # Update all_apple_updates_installed and add Apple updates to # pkgs_to_install. It's important that this code block comes after # all_pkgs_installed is updated above, to ensure that all_pkgs_installed # is only considers Munki updates, ignoring Apple updates added below. # NOTE: if there are any pending Munki updates then we simply assume # there are also pending Apple Updates, even though we cannot be sure # due to the fact that Munki only checks for Apple Updates if all regular # updates are installed if not pkgs_to_install and not _apple_updates_to_install: c.all_apple_updates_installed = True else: c.all_apple_updates_installed = False # For now, let's store Munki and Apple Update pending installs together, # using APPLESUS_PKGS_TO_INSTALL_FORMAT to format the text as desired. for update in _apple_updates_to_install: c.pkgs_to_install.append(APPLESUS_PKGS_TO_INSTALL_FORMAT % update) # Keep the last CONNECTION_DATETIMES_LIMIT connection datetimes. if len(c.connection_datetimes) == CONNECTION_DATETIMES_LIMIT: c.connection_datetimes.pop(0) c.connection_datetimes.append(now) # Increase on_corp/off_corp count appropriately. if _client_id['on_corp'] == True: c.connections_on_corp = (c.connections_on_corp or 0) + 1 elif _client_id['on_corp'] == False: c.connections_off_corp = (c.connections_off_corp or 0) + 1 # Keep the last CONNECTION_DATES_LIMIT connection dates # (with time = 00:00:00) # Use newly created datetime.time object to set time to 00:00:00 now_date = datetime.datetime.combine(now, datetime.time()) if now_date not in c.connection_dates: if len(c.connection_dates) == CONNECTION_DATES_LIMIT: c.connection_dates.pop(0) c.connection_dates.append(now_date) else: logging.warning('Unknown event value: %s', event) c.put() if is_new_client: # Queue welcome email to be sent. #logging.debug('Deferring _SaveFirstConnection....') deferred.defer( _SaveFirstConnection, client_id=_client_id, computer=c, _countdown=300, _queue='first') try: db.run_in_transaction( __UpdateComputerEntity, event, client_id, user_settings, pkgs_to_install, apple_updates_to_install, ip_address, report_feedback, c=computer) except (db.Error, apiproxy_errors.Error, runtime.DeadlineExceededError) as e: logging.warning( 'LogClientConnection put() error %s: %s', e.__class__.__name__, str(e)) LogClientConnection( event, client_id, user_settings, pkgs_to_install, apple_updates_to_install, ip_address, report_feedback, delay=DATASTORE_NOWRITE_DELAY) def WriteClientLog(model, uuid, **kwargs): """Writes a ClientLog entry. Args: model: db.Model to write to. uuid: str uuid of client. kwargs: property/value pairs to write to the model; uuid not allowed. Returns: models.Computer instance which is this client """ if 'uuid' in kwargs: #logging.debug('WriteClientLog: Deleting uuid from kwargs') del(kwargs['uuid']) uuid = common.SanitizeUUID(uuid) if 'computer' not in kwargs: kwargs['computer'] = models.Computer.get_by_key_name(uuid) l = model(uuid=uuid, **kwargs) try: l.put() except (db.Error, apiproxy_errors.Error, runtime.DeadlineExceededError): logging.warning('WriteClientLog put() failure; deferring...') now_str = datetime.datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S') deferred_name = 'write-client-log-%s-%s' % (uuid, now_str) deferred.defer( WriteClientLog, model, uuid, _name=deferred_name, _countdown=5, **kwargs) return kwargs['computer'] def WriteBrokenClient(uuid, reason, details): """Saves a BrokenClient entity to Datastore for the given UUID. Args: uuid: str, uuid of client. reason: str, short description of broken state the client is reporting. details: str, details or debugging output of the broken report. """ # If the details string contains facter output, parse it. facts = {} lines = details.splitlines() for line in lines: try: (key, unused_sep, value) = line.split(' ', 2) except ValueError: continue # current line was not facter, continue. value = value.strip() facts[key] = value # Update the existing, or create a new ComputerClientBroken entity. uuid = common.SanitizeUUID(uuid) bc = models.ComputerClientBroken.get_or_insert(uuid) bc.broken_datetimes.append(datetime.datetime.utcnow()) bc.reason = reason bc.details = details bc.fixed = False # Previously fixed computers will show up again. bc.hostname = facts.get('hostname', '') bc.owner = facts.get('primary_user', '') bc.serial = facts.get('sp_serial_number', '') bc.uuid = uuid bc.put() def WriteComputerMSULog(uuid, details): """Write log details from MSU GUI into ComputerMSULog model. Args: uuid: str, computer uuid to update details: dict like = { 'event': str, 'something_happened', 'source': str, 'MSU' or 'user', 'user': str, 'username', 'time': int, epoch seconds, 'desc': str, 'additional descriptive text', } """ uuid = common.SanitizeUUID(uuid) key = '%s_%s_%s' % (uuid, details['source'], details['event']) c = models.ComputerMSULog(key_name=key) c.uuid = uuid c.event = details['event'] c.source = details['source'] c.user = details['user'] c.desc = details['desc'] try: mtime = util.Datetime.utcfromtimestamp(details.get('time', None)) except ValueError, e: logging.warning('Ignoring msu_log time; %s' % str(e)) mtime = datetime.datetime.utcnow() except util.EpochExtremeFutureValueError, e: logging.warning('Ignoring msu_log time; %s' % str(e)) mtime = datetime.datetime.utcnow() except util.EpochValueError: mtime = datetime.datetime.utcnow() if c.mtime is None or mtime > c.mtime: c.mtime = mtime c.put() def GetBoolValueFromString(s): """Returns True for true/1 strings, and False for false/0, None otherwise.""" if s and s.lower() == 'true' or s == '1': return True elif s and s.lower() == 'false' or s == '0': return False else: return None def KeyValueStringToDict(s, delimiter='|'): """Parses a key=value string with delimiter and returns a dict. Args: s: string with key=value pairs. delimiter: delimiter char(s) to parse the string with. Returns: dictionary of key value pairs. 'None' converted to None. """ d = {} pairs = s.split(delimiter) for pair in pairs: try: key, value = pair.split('=', 1) if not value or value == 'None': value = None # Convert empty strings to None. d[key] = value except ValueError: logging.debug('Ignoring invalid key/value pair: %s', pair) return d def ParseClientId(client_id, uuid=None): """Splits a client id string and converts all key/value pairs to a dict. Also, this truncates string values to 500 characters. Args: client_id: string client id with "|" as delimiter. uuid: optional string uuid to override the uuid in client_id. Returns: Dict. Client id string "foo=bar|key=|one=1" yields {'foo': 'bar', 'key': None, 'one': '1'}. """ if client_id and client_id.find('\n') > -1: logging.warning( 'ParseClientId: client_id has newline: %s', base64.b64encode(client_id)) client_id = client_id.replace('\n', '_') # Convert str input to unicode. if type(client_id) is str: try: client_id = client_id.decode('utf-8') except UnicodeDecodeError: client_id = client_id.decode('utf-8', 'replace') logging.warning('UnicodeDecodeError on client_id: %s', client_id) out = KeyValueStringToDict(client_id) # If any required fields were not present in the client id string, add them. # Also cast all values to their defined output types. for field, value_type in CLIENT_ID_FIELDS.iteritems(): if field not in out or out[field] is None: out[field] = None elif value_type is bool: out[field] = GetBoolValueFromString(out[field]) elif value_type is str: # truncate str fields to 500 characters, the StringProperty limit. out[field] = out[field][:500] else: try: out[field] = value_type(out[field]) except ValueError: logging.warning( 'Error casting client id %s to defined type: %s', field, out[field]) out[field] = None if out['track'] not in common.TRACKS: if out['track'] is not None: logging.warning('Invalid track requested: %s', out['track']) out['track'] = common.DEFAULT_TRACK if uuid: out['uuid'] = common.SanitizeUUID(uuid) return out def IsPanicMode(mode): """Returns True if panic mode, False if not. Args: mode: str Returns: True or False """ if mode not in PANIC_MODES: raise ValueError(mode) m = models.KeyValueCache.MemcacheWrappedGet( '%s%s' % (PANIC_MODE_PREFIX, mode)) if m: return True else: return False def SetPanicMode(mode, enabled): """Set a panic mode on or off. Args: mode: str, mode to set enabled: bool, to enable or disable the mode """ if mode not in PANIC_MODES: raise ValueError(mode) q = models.KeyValueCache.get_by_key_name('%s%s' % (PANIC_MODE_PREFIX, mode)) if enabled: if not q: q = models.KeyValueCache(key_name='%s%s' % (PANIC_MODE_PREFIX, mode)) q.text_value = '1' q.put() else: if q: q.delete() models.KeyValueCache.ResetMemcacheWrap('%s%s' % (PANIC_MODE_PREFIX, mode)) def IsPanicModeNoPackages(): """Returns True if in no package delivery mode.""" return IsPanicMode(PANIC_MODE_NO_PACKAGES) def SetPanicModeNoPackages(enabled): """Enable or disable no packages panic mode. Args: enabled: bool, to enable or disable the mode """ SetPanicMode(PANIC_MODE_NO_PACKAGES, enabled) def GetComputerManifest(uuid=None, client_id=None, packagemap=False): """For a computer uuid or client_id, return the current manifest. Args: uuid: str, computer uuid OR client_id: dict, client_id packagemap: bool, default False, whether to return packagemap or not Returns: if packagemap, dict = { 'plist': plist.MunkiManifestPlist instance, 'packagemap': { # if packagemap == True 'Firefox': 'Firefox-3.x.x.x.dmg', }, } if not packagemap, str, manifest plist Raises: ValueError: error in type of arguments supplied to this method ComputerNotFoundError: computer cannot be found for uuid ManifestNotFoundError: manifest requested is invalid (not found) ManifestDisabledError: manifest requested is disabled """ if client_id is None and uuid is None: raise ValueError('uuid or client_id must be supplied') if client_id is not None: if type(client_id) is not dict: raise ValueError('client_id must be dict') uuid = client_id.get('uuid') user_settings = None if uuid is not None: c = models.Computer.get_by_key_name(uuid) if not c: raise ComputerNotFoundError user_settings = c.user_settings client_id = { 'uuid': uuid, 'owner': c.owner, 'hostname': c.hostname, 'serial': c.serial, 'config_track': c.config_track, 'track': c.track, 'site': c.site, 'office': c.office, 'os_version': c.os_version, 'client_version': c.client_version, # TODO(user): Fix this; it may not be accurate. 'on_corp': c.connections_on_corp > c.connections_off_corp, 'last_notified_datetime': c.last_notified_datetime, 'uptime': None, 'root_disk_free': None, 'user_disk_free': None, } # Step 1: Obtain a manifest for this uuid. manifest_plist_xml = None if IsPanicModeNoPackages(): manifest_plist_xml = '%s%s' % ( plist_module.PLIST_HEAD, plist_module.PLIST_FOOT) else: manifest_name = client_id['track'] m = models.Manifest.MemcacheWrappedGet(manifest_name) if not m: raise ManifestNotFoundError(manifest_name) elif not m.enabled: raise ManifestDisabledError(manifest_name) manifest_plist_xml = GenerateDynamicManifest( m.plist, client_id, user_settings=user_settings) if not manifest_plist_xml: raise ManifestNotFoundError(manifest_name) # Step 1: Return now with xml if packagemap not requested. if not packagemap: return manifest_plist_xml # Step 2: Build lookup table from PackageName to PackageName-VersionNumber # for packages found in catalogs used by the client. manifest_plist = plist_module.MunkiManifestPlist(manifest_plist_xml) manifest_plist.Parse() catalogs = manifest_plist['catalogs'] packages = {} query = models.PackageInfo.all() for p in query: display_name = p.plist.get('display_name', None) or p.plist.get('name') display_name = display_name.strip() version = p.plist.get('version', '') packages[p.name] = '%s-%s' % (display_name, version) return { 'plist': manifest_plist, 'packagemap': packages, } def _ModifyList(l, value): """Adds or removes a value from a list. Args: l: list to modify. value: str value; "foo" to add or "-foo" to remove "foo". """ if value.startswith('-'): try: l.remove(value[1:]) except ValueError: pass # item is already not a member of the list, so ignore error. else: l.append(value) def GenerateDynamicManifest(plist, client_id, user_settings=None): """Generate a dynamic manifest based on a the various client_id fields. Args: plist: str XML or plist_module.ApplePlist object, manifest to start with. client_id: dict client_id parsed by common.ParseClientId. user_settings: dict UserSettings as defined in Simian client. Returns: str XML manifest with any custom modifications based on the client_id. """ # TODO(user): This function is getting out of control and needs refactoring. manifest_changed = False manifest = client_id['track'] site_mods = models.SiteManifestModification.MemcacheWrappedGetAllFilter( (('site =', client_id['site']),)) os_version_mods = \ models.OSVersionManifestModification.MemcacheWrappedGetAllFilter( (('os_version =', client_id['os_version']),)) owner_mods = models.OwnerManifestModification.MemcacheWrappedGetAllFilter( (('owner =', client_id['owner']),)) uuid_mods = models.UuidManifestModification.MemcacheWrappedGetAllFilter( (('uuid =', client_id['uuid']),)) tag_mods = [] if client_id['uuid']: # not set if viewing a base manifest. computer_key = models.db.Key.from_path('Computer', client_id['uuid']) computer_tags = models.Tag.GetAllTagNamesForKey(computer_key) if computer_tags: # NOTE(user): if we feel most computers will have tags, it might make # sense to regularly fetch and cache all mods. for tag in computer_tags: t = (('tag_key_name =', tag),) tag_mods.extend( models.TagManifestModification.MemcacheWrappedGetAllFilter(t)) def __ApplyModifications(manifest, mod, plist): """Applies a manifest modification if the manifest matches mod manifest. NOTE(user): if mod.manifests is empty or None, mod is made to any manifest. """ plist_xml = None if type(plist) is str: plist_xml = plist if not mod.enabled: return # return it the mod is disabled elif mod.manifests and manifest not in mod.manifests: return # return if the desired manifest is not in the mod manifests. #logging.debug( # 'Applying manifest mod: %s %s', mod.install_types, mod.value) for install_type in mod.install_types: plist_module.UpdateIterable( plist, install_type, mod.value, default=[], op=_ModifyList) if site_mods or owner_mods or os_version_mods or uuid_mods or tag_mods: manifest_changed = True if type(plist) is str: plist = plist_module.MunkiManifestPlist(plist) plist.Parse() for mod in site_mods: __ApplyModifications(manifest, mod, plist) for mod in os_version_mods: __ApplyModifications(manifest, mod, plist) for mod in owner_mods: __ApplyModifications(manifest, mod, plist) for mod in uuid_mods: __ApplyModifications(manifest, mod, plist) for mod in tag_mods: __ApplyModifications(manifest, mod, plist) if user_settings: flash_developer = user_settings.get('FlashDeveloper', False) block_packages = user_settings.get('BlockPackages', []) # If plist is not parsed yet and modifications are required, parse it. if (flash_developer or block_packages) and type(plist) is str: if type(plist) is str: plist = plist_module.MunkiManifestPlist(plist) plist.Parse() # If FlashDeveloper is True, replace the regular flash plugin with the # debug version in managed_updates. if flash_developer: manifest_changed = True plist[common.MANAGED_UPDATES].append(FLASH_PLUGIN_DEBUG_NAME) try: plist[common.MANAGED_UPDATES].remove(FLASH_PLUGIN_NAME) except ValueError: pass # FLASH_PLUGIN_NAME was not in managed_updates to begin with. # Look for each block package in each install type, remove if found. for block_package in block_packages: for install_type in common.INSTALL_TYPES: if block_package in plist.get(install_type, []): manifest_changed = True plist[install_type].remove(block_package) #logging.debug( # 'Removed BlockPackage from %s: %s', block_package, install_type) if type(plist) is str: return plist else: return plist.GetXml()
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Calculate what workon packages have changed since the last build. A workon package is treated as changed if any of the below are true: 1) The package is not installed. 2) A file exists in the associated repository which has a newer modification time than the installed package. 3) The source ebuild has a newer modification time than the installed package. Some caveats: - We do not look at eclasses. This replicates the existing behavior of the commit queue, which also does not look at eclass changes. - We do not try to fallback to the non-workon package if the local tree is unmodified. This is probably a good thing, since developers who are "working on" a package want to compile it locally. - Portage only stores the time that a package finished building, so we aren't able to detect when users modify source code during builds. """ from __future__ import print_function import errno import logging import multiprocessing import optparse import os try: import Queue except ImportError: # Python-3 renamed to "queue". We still use Queue to avoid collisions # with naming variables as "queue". Maybe we'll transition at some point. # pylint: disable=F0401 import queue as Queue from chromite.cbuildbot import constants from chromite.lib import cros_build_lib from chromite.lib import git from chromite.lib import osutils from chromite.lib import parallel from chromite.lib import portage_util class WorkonProjectsMonitor(object): """Class for monitoring the last modification time of workon projects. Members: _tasks: A list of the (project, path) pairs to check. _result_queue: A queue. When GetProjectModificationTimes is called, (project, mtime) tuples are pushed onto the end of this queue. """ def __init__(self, projects): """Create a new object for checking what projects were modified and when. Args: projects: A list of the project names we are interested in monitoring. """ manifest = git.ManifestCheckout.Cached(constants.SOURCE_ROOT) self._tasks = [] for project in set(projects).intersection(manifest.checkouts_by_name): for checkout in manifest.FindCheckouts(project): self._tasks.append((project, checkout.GetPath(absolute=True))) self._result_queue = multiprocessing.Queue(len(self._tasks)) def _EnqueueProjectModificationTime(self, project, path): """Calculate the last time that this project was modified, and enqueue it. Args: project: The project to look at. path: The path associated with the specified project. """ if os.path.isdir(path): self._result_queue.put((project, self._LastModificationTime(path))) def _LastModificationTime(self, path): """Calculate the last time a directory subtree was modified. Args: path: Directory to look at. """ cmd = 'find . -name .git -prune -o -printf "%T@\n" | sort -nr | head -n1' ret = cros_build_lib.RunCommand(cmd, cwd=path, shell=True, print_cmd=False, capture_output=True) return float(ret.output) if ret.output else 0 def GetProjectModificationTimes(self): """Get the last modification time of each specified project. Returns: A dictionary mapping project names to last modification times. """ task = self._EnqueueProjectModificationTime parallel.RunTasksInProcessPool(task, self._tasks) # Create a dictionary mapping project names to last modification times. # All of the workon projects are already stored in the queue, so we can # retrieve them all without waiting any longer. mtimes = {} while True: try: project, mtime = self._result_queue.get_nowait() except Queue.Empty: break mtimes[project] = mtime return mtimes class WorkonPackageInfo(object): """Class for getting information about workon packages. Members: cp: The package name (e.g. chromeos-base/power_manager). mtime: The modification time of the installed package. project: The project associated with the installed package. src_ebuild_mtime: The modification time of the source ebuild. """ def __init__(self, cp, mtime, projects, src_ebuild_mtime): self.cp = cp self.pkg_mtime = int(mtime) self.projects = projects self.src_ebuild_mtime = src_ebuild_mtime def ListWorkonPackages(board, host, all_opt=False): """List the packages that are currently being worked on. Args: board: The board to look at. If host is True, this should be set to None. host: Whether to look at workon packages for the host. all_opt: Pass --all to cros_workon. For testing purposes. """ cmd = [os.path.join(constants.CROSUTILS_DIR, 'cros_workon'), 'list'] cmd.extend(['--host'] if host else ['--board', board]) if all_opt: cmd.append('--all') result = cros_build_lib.RunCommand(cmd, print_cmd=False, capture_output=True) return result.output.split() def ListWorkonPackagesInfo(board, host): """Find the specified workon packages for the specified board. Args: board: The board to look at. If host is True, this should be set to None. host: Whether to look at workon packages for the host. Returns: A list of unique packages being worked on. """ # Import portage late so that this script can be imported outside the chroot. # pylint: disable=F0401 import portage.const packages = ListWorkonPackages(board, host) if not packages: return [] results = {} install_root = cros_build_lib.GetSysroot(board=board) vdb_path = os.path.join(install_root, portage.const.VDB_PATH) buildroot, both = constants.SOURCE_ROOT, constants.BOTH_OVERLAYS for overlay in portage_util.FindOverlays(both, board, buildroot): for filename, projects in portage_util.GetWorkonProjectMap(overlay, packages): # chromeos-base/power_manager/power_manager-9999 # cp = chromeos-base/power_manager # cpv = chromeos-base/power_manager-9999 category, pn, p = portage_util.SplitEbuildPath(filename) cp = '%s/%s' % (category, pn) cpv = '%s/%s' % (category, p) # Get the time the package finished building. TODO(build): Teach Portage # to store the time the package started building and use that here. pkg_mtime_file = os.path.join(vdb_path, cpv, 'BUILD_TIME') try: pkg_mtime = int(osutils.ReadFile(pkg_mtime_file)) except EnvironmentError as ex: if ex.errno != errno.ENOENT: raise pkg_mtime = 0 # Get the modificaton time of the ebuild in the overlay. src_ebuild_mtime = os.lstat(os.path.join(overlay, filename)).st_mtime # Write info into the results dictionary, overwriting any previous # values. This ensures that overlays override appropriately. results[cp] = WorkonPackageInfo(cp, pkg_mtime, projects, src_ebuild_mtime) return results.values() def ListModifiedWorkonPackages(board, host): """List the workon packages that need to be rebuilt. Args: board: The board to look at. If host is True, this should be set to None. host: Whether to look at workon packages for the host. """ packages = ListWorkonPackagesInfo(board, host) if packages: projects = [] for info in packages: projects.extend(info.projects) mtimes = WorkonProjectsMonitor(projects).GetProjectModificationTimes() for info in packages: mtime = int(max([mtimes.get(p, 0) for p in info.projects] + [info.src_ebuild_mtime])) if mtime >= info.pkg_mtime: yield info.cp def _ParseArguments(argv): parser = optparse.OptionParser(usage='USAGE: %prog [options]') parser.add_option('--board', default=None, dest='board', help='Board name') parser.add_option('--host', default=False, dest='host', action='store_true', help='Look at host packages instead of board packages') flags, remaining_arguments = parser.parse_args(argv) if not flags.board and not flags.host: parser.print_help() cros_build_lib.Die('--board or --host is required') if flags.board is not None and flags.host: parser.print_help() cros_build_lib.Die('--board and --host are mutually exclusive') if remaining_arguments: parser.print_help() cros_build_lib.Die('Invalid arguments') return flags def main(argv): logging.getLogger().setLevel(logging.INFO) flags = _ParseArguments(argv) modified = ListModifiedWorkonPackages(flags.board, flags.host) print(' '.join(sorted(modified)))
# program template for Spaceship import simplegui import math import random # globals for user interface WIDTH = 800 HEIGHT = 600 score = 0 lives = 3 time = 0.5 class ImageInfo: def __init__(self, center, size, radius = 0, lifespan = None, animated = False): self.center = center self.size = size self.radius = radius if lifespan: self.lifespan = lifespan else: self.lifespan = float('inf') self.animated = animated def get_center(self): return self.center def get_size(self): return self.size def get_radius(self): return self.radius def get_lifespan(self): return self.lifespan def get_animated(self): return self.animated # art assets created by Kim Lathrop, may be freely re-used in non-commercial projects, please credit Kim # debris images - debris1_brown.png, debris2_brown.png, debris3_brown.png, debris4_brown.png # debris1_blue.png, debris2_blue.png, debris3_blue.png, debris4_blue.png, debris_blend.png debris_info = ImageInfo([320, 240], [640, 480]) debris_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/debris2_blue.png") # nebula images - nebula_brown.png, nebula_blue.png nebula_info = ImageInfo([400, 300], [800, 600]) nebula_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/nebula_blue.f2014.png") # splash image splash_info = ImageInfo([200, 150], [400, 300]) splash_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/splash.png") # ship image ship_info = ImageInfo([45, 45], [90, 90], 35) ship_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/double_ship.png") # missile image - shot1.png, shot2.png, shot3.png missile_info = ImageInfo([5,5], [10, 10], 3, 50) missile_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/shot2.png") # asteroid images - asteroid_blue.png, asteroid_brown.png, asteroid_blend.png asteroid_info = ImageInfo([45, 45], [90, 90], 40) asteroid_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blue.png") # animated explosion - explosion_orange.png, explosion_blue.png, explosion_blue2.png, explosion_alpha.png explosion_info = ImageInfo([64, 64], [128, 128], 17, 24, True) explosion_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/explosion_alpha.png") # sound assets purchased from sounddogs.com, please do not redistribute soundtrack = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/soundtrack.mp3") missile_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/missile.mp3") missile_sound.set_volume(.5) ship_thrust_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/thrust.mp3") explosion_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/explosion.mp3") # helper functions to handle transformations def angle_to_vector(ang): return [math.cos(ang), math.sin(ang)] def dist(p,q): return math.sqrt((p[0] - q[0]) ** 2+(p[1] - q[1]) ** 2) # Ship class class Ship: def __init__(self, pos, vel, angle, image, info): self.pos = [pos[0],pos[1]] self.vel = [vel[0],vel[1]] self.thrust = False self.angle = angle self.angle_vel = 0 self.image = image self.image_center = info.get_center() self.image_size = info.get_size() self.radius = info.get_radius() def draw(self,canvas): if self.thrust: canvas.draw_image(self.image, (self.image_center[0] + self.image_size[1], self.image_center[1]), self.image_size, self.pos, self.image_size, self.angle) else: canvas.draw_image(self.image, self.image_center, self.image_size, self.pos, self.image_size, self.angle) def update(self): self.angle += self.angle_vel self.pos[0] = (self.pos[0] + self.vel[0]) % WIDTH self.pos[1] = (self.pos[1] + self.vel[1]) % HEIGHT if self.thrust: self.vel[0] += angle_to_vector(self.angle)[0] * 0.1 self.vel[1] += angle_to_vector(self.angle)[1] * 0.1 self.vel[0] *= 0.99 self.vel[1] *= 0.99 def turn_right(self): self.angle_vel += 0.03 def turn_left(self): self.angle_vel -= 0.03 def turn_on_thrusters(self, thrusters_on): self.thrust = thrusters_on if thrusters_on: ship_thrust_sound.rewind() ship_thrust_sound.play() else: ship_thrust_sound.pause() def shoot(self): global a_missile forward = angle_to_vector(self.angle) missile_pos = (self.pos[0] + self.radius * forward[0], self.pos[1] + self.radius * forward[1]) missile_vel = (self.vel[0] + 5 * forward[0], self.vel[1] + 5 * forward[1]) a_missile = Sprite(missile_pos, missile_vel, self.angle, 0, missile_image, missile_info, missile_sound) # Sprite class class Sprite: def __init__(self, pos, vel, ang, ang_vel, image, info, sound = None): self.pos = [pos[0],pos[1]] self.vel = [vel[0],vel[1]] self.angle = ang self.angle_vel = ang_vel self.image = image self.image_center = info.get_center() self.image_size = info.get_size() self.radius = info.get_radius() self.lifespan = info.get_lifespan() self.animated = info.get_animated() self.age = 0 if sound: sound.rewind() sound.play() def draw(self, canvas): canvas.draw_image(self.image, self.image_center, self.image_size, self.pos, self.image_size, self.angle) def update(self): self.angle += self.angle_vel self.pos[0] = (self.pos[0] + self.vel[0]) % WIDTH self.pos[1] = (self.pos[1] + self.vel[1]) % HEIGHT def draw(canvas): global time # animiate background time += 1 wtime = (time / 4) % WIDTH center = debris_info.get_center() size = debris_info.get_size() canvas.draw_image(nebula_image, nebula_info.get_center(), nebula_info.get_size(), [WIDTH / 2, HEIGHT / 2], [WIDTH, HEIGHT]) canvas.draw_image(debris_image, center, size, (wtime - WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT)) canvas.draw_image(debris_image, center, size, (wtime + WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT)) # draw ship and sprites my_ship.draw(canvas) a_rock.draw(canvas) a_missile.draw(canvas) # update ship and sprites my_ship.update() a_rock.update() a_missile.update() #user interface canvas.draw_text('Lives:', (35,50), 32, "White") canvas.draw_text(str(lives), (60,90), 32, "White") canvas.draw_text('Score:', (680,50), 32, "White") canvas.draw_text(str(score), (705,90), 32, "White") # timer handler that spawns a rock def rock_spawner(): global a_rock rock_pos = [random.randrange(WIDTH), random.randrange(HEIGHT)] rock_vel = [random.random(), random.random()] rock_ang_vel = random.random() * 0.2 - 0.1 a_rock = Sprite(rock_pos, rock_vel, 0, rock_ang_vel, asteroid_image, asteroid_info) def key_down(key): global angle_vel, thrust if key == simplegui.KEY_MAP['up']: my_ship.turn_on_thrusters(True) elif key == simplegui.KEY_MAP['right']: my_ship.turn_right() elif key == simplegui.KEY_MAP['left']: my_ship.turn_left() elif key == simplegui.KEY_MAP['space']: my_ship.shoot() def key_up(key): global angle_vel, thrust if key == simplegui.KEY_MAP['up']: my_ship.turn_on_thrusters(False) elif key == simplegui.KEY_MAP['right']: my_ship.turn_left() elif key == simplegui.KEY_MAP['left']: my_ship.turn_right() # initialize frame frame = simplegui.create_frame("Asteroids", WIDTH, HEIGHT) # initialize ship and two sprites my_ship = Ship([WIDTH / 2, HEIGHT / 2], [0, 0], 0, ship_image, ship_info) a_rock = Sprite([WIDTH / 3, HEIGHT / 3], [1, 1], 0, 0, asteroid_image, asteroid_info) a_missile = Sprite([2 * WIDTH / 3, 2 * HEIGHT / 3], [-1,1], 0, 0, missile_image, missile_info, missile_sound) # register handlers frame.set_draw_handler(draw) frame.set_keydown_handler(key_down) frame.set_keyup_handler(key_up) timer = simplegui.create_timer(1000.0, rock_spawner) # get things rolling timer.start() frame.start()
# Copyright 2010 Jacob Kaplan-Moss # Copyright 2011 OpenStack Foundation # Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Base utilities to build API operation managers and objects on top of. """ import abc import copy import functools import warnings from oslo_utils import strutils import six from six.moves import urllib from keystoneclient import auth from keystoneclient import exceptions from keystoneclient.i18n import _ def getid(obj): """Return id if argument is a Resource. Abstracts the common pattern of allowing both an object or an object's ID (UUID) as a parameter when dealing with relationships. """ try: if obj.uuid: return obj.uuid except AttributeError: pass try: return obj.id except AttributeError: return obj def filter_none(**kwargs): """Remove any entries from a dictionary where the value is None.""" return dict((k, v) for k, v in six.iteritems(kwargs) if v is not None) def filter_kwargs(f): @functools.wraps(f) def func(*args, **kwargs): new_kwargs = {} for key, ref in six.iteritems(kwargs): if ref is None: # drop null values continue id_value = getid(ref) if id_value != ref: # If an object with an id was passed, then use the id, e.g.: # user: user(id=1) becomes user_id: 1 key = '%s_id' % key new_kwargs[key] = id_value return f(*args, **new_kwargs) return func class Manager(object): """Basic manager type providing common operations. Managers interact with a particular type of API (servers, flavors, images, etc.) and provide CRUD operations for them. :param client: instance of BaseClient descendant for HTTP requests """ resource_class = None def __init__(self, client): super(Manager, self).__init__() self.client = client @property def api(self): """The client. .. warning:: This property is deprecated as of the 1.7.0 release in favor of :meth:`client` and may be removed in the 2.0.0 release. """ warnings.warn( 'api is deprecated as of the 1.7.0 release in favor of client and ' 'may be removed in the 2.0.0 release', DeprecationWarning) return self.client def _list(self, url, response_key, obj_class=None, body=None, **kwargs): """List the collection. :param url: a partial URL, e.g., '/servers' :param response_key: the key to be looked up in response dictionary, e.g., 'servers' :param obj_class: class for constructing the returned objects (self.resource_class will be used by default) :param body: data that will be encoded as JSON and passed in POST request (GET will be sent by default) :param kwargs: Additional arguments will be passed to the request. """ if body: resp, body = self.client.post(url, body=body, **kwargs) else: resp, body = self.client.get(url, **kwargs) if obj_class is None: obj_class = self.resource_class data = body[response_key] # NOTE(ja): keystone returns values as list as {'values': [ ... ]} # unlike other services which just return the list... try: data = data['values'] except (KeyError, TypeError): pass return [obj_class(self, res, loaded=True) for res in data if res] def _get(self, url, response_key, **kwargs): """Get an object from collection. :param url: a partial URL, e.g., '/servers' :param response_key: the key to be looked up in response dictionary, e.g., 'server' :param kwargs: Additional arguments will be passed to the request. """ resp, body = self.client.get(url, **kwargs) return self.resource_class(self, body[response_key], loaded=True) def _head(self, url, **kwargs): """Retrieve request headers for an object. :param url: a partial URL, e.g., '/servers' :param kwargs: Additional arguments will be passed to the request. """ resp, body = self.client.head(url, **kwargs) return resp.status_code == 204 def _create(self, url, body, response_key, return_raw=False, **kwargs): """Deprecated. Use `_post` instead. """ return self._post(url, body, response_key, return_raw, **kwargs) def _post(self, url, body, response_key, return_raw=False, **kwargs): """Create an object. :param url: a partial URL, e.g., '/servers' :param body: data that will be encoded as JSON and passed in POST request (GET will be sent by default) :param response_key: the key to be looked up in response dictionary, e.g., 'servers' :param return_raw: flag to force returning raw JSON instead of Python object of self.resource_class :param kwargs: Additional arguments will be passed to the request. """ resp, body = self.client.post(url, body=body, **kwargs) if return_raw: return body[response_key] return self.resource_class(self, body[response_key]) def _put(self, url, body=None, response_key=None, **kwargs): """Update an object with PUT method. :param url: a partial URL, e.g., '/servers' :param body: data that will be encoded as JSON and passed in POST request (GET will be sent by default) :param response_key: the key to be looked up in response dictionary, e.g., 'servers' :param kwargs: Additional arguments will be passed to the request. """ resp, body = self.client.put(url, body=body, **kwargs) # PUT requests may not return a body if body is not None: if response_key is not None: return self.resource_class(self, body[response_key]) else: return self.resource_class(self, body) def _patch(self, url, body=None, response_key=None, **kwargs): """Update an object with PATCH method. :param url: a partial URL, e.g., '/servers' :param body: data that will be encoded as JSON and passed in POST request (GET will be sent by default) :param response_key: the key to be looked up in response dictionary, e.g., 'servers' :param kwargs: Additional arguments will be passed to the request. """ resp, body = self.client.patch(url, body=body, **kwargs) if response_key is not None: return self.resource_class(self, body[response_key]) else: return self.resource_class(self, body) def _delete(self, url, **kwargs): """Delete an object. :param url: a partial URL, e.g., '/servers/my-server' :param kwargs: Additional arguments will be passed to the request. """ return self.client.delete(url, **kwargs) def _update(self, url, body=None, response_key=None, method="PUT", **kwargs): methods = {"PUT": self.client.put, "POST": self.client.post, "PATCH": self.client.patch} try: resp, body = methods[method](url, body=body, **kwargs) except KeyError: raise exceptions.ClientException(_("Invalid update method: %s") % method) # PUT requests may not return a body if body: return self.resource_class(self, body[response_key]) @six.add_metaclass(abc.ABCMeta) class ManagerWithFind(Manager): """Manager with additional `find()`/`findall()` methods.""" @abc.abstractmethod def list(self): pass def find(self, **kwargs): """Find a single item with attributes matching ``**kwargs``. This isn't very efficient: it loads the entire list then filters on the Python side. """ rl = self.findall(**kwargs) num = len(rl) if num == 0: msg = _("No %(name)s matching %(kwargs)s.") % { 'name': self.resource_class.__name__, 'kwargs': kwargs} raise exceptions.NotFound(404, msg) elif num > 1: raise exceptions.NoUniqueMatch else: return rl[0] def findall(self, **kwargs): """Find all items with attributes matching ``**kwargs``. This isn't very efficient: it loads the entire list then filters on the Python side. """ found = [] searches = kwargs.items() for obj in self.list(): try: if all(getattr(obj, attr) == value for (attr, value) in searches): found.append(obj) except AttributeError: continue return found class CrudManager(Manager): """Base manager class for manipulating Keystone entities. Children of this class are expected to define a `collection_key` and `key`. - `collection_key`: Usually a plural noun by convention (e.g. `entities`); used to refer collections in both URL's (e.g. `/v3/entities`) and JSON objects containing a list of member resources (e.g. `{'entities': [{}, {}, {}]}`). - `key`: Usually a singular noun by convention (e.g. `entity`); used to refer to an individual member of the collection. """ collection_key = None key = None base_url = None def build_url(self, dict_args_in_out=None): """Builds a resource URL for the given kwargs. Given an example collection where `collection_key = 'entities'` and `key = 'entity'`, the following URL's could be generated. By default, the URL will represent a collection of entities, e.g.:: /entities If kwargs contains an `entity_id`, then the URL will represent a specific member, e.g.:: /entities/{entity_id} If a `base_url` is provided, the generated URL will be appended to it. If a 'tail' is provided, it will be appended to the end of the URL. """ if dict_args_in_out is None: dict_args_in_out = {} url = dict_args_in_out.pop('base_url', None) or self.base_url or '' url += '/%s' % self.collection_key # do we have a specific entity? entity_id = dict_args_in_out.pop('%s_id' % self.key, None) if entity_id is not None: url += '/%s' % entity_id if dict_args_in_out.get('tail'): url += dict_args_in_out['tail'] return url @filter_kwargs def create(self, **kwargs): url = self.build_url(dict_args_in_out=kwargs) return self._create( url, {self.key: kwargs}, self.key) @filter_kwargs def get(self, **kwargs): return self._get( self.build_url(dict_args_in_out=kwargs), self.key) @filter_kwargs def head(self, **kwargs): return self._head(self.build_url(dict_args_in_out=kwargs)) def _build_query(self, params): return '?%s' % urllib.parse.urlencode(params) if params else '' def build_key_only_query(self, params_list): """Builds a query that does not include values, just keys. The Identity API has some calls that define queries without values, this can not be accomplished by using urllib.parse.urlencode(). This method builds a query using only the keys. """ return '?%s' % '&'.join(params_list) if params_list else '' @filter_kwargs def list(self, fallback_to_auth=False, **kwargs): if 'id' in kwargs.keys(): # Ensure that users are not trying to call things like # ``domains.list(id='default')`` when they should have used # ``[domains.get(domain_id='default')]`` instead. Keystone supports # ``GET /v3/domains/{domain_id}``, not ``GET # /v3/domains?id={domain_id}``. raise TypeError( _("list() got an unexpected keyword argument 'id'. To " "retrieve a single object using a globally unique " "identifier, try using get() instead.")) url = self.build_url(dict_args_in_out=kwargs) try: query = self._build_query(kwargs) url_query = '%(url)s%(query)s' % {'url': url, 'query': query} return self._list( url_query, self.collection_key) except exceptions.EmptyCatalog: if fallback_to_auth: return self._list( url_query, self.collection_key, endpoint_filter={'interface': auth.AUTH_INTERFACE}) else: raise @filter_kwargs def put(self, **kwargs): return self._update( self.build_url(dict_args_in_out=kwargs), method='PUT') @filter_kwargs def update(self, **kwargs): url = self.build_url(dict_args_in_out=kwargs) return self._update( url, {self.key: kwargs}, self.key, method='PATCH') @filter_kwargs def delete(self, **kwargs): return self._delete( self.build_url(dict_args_in_out=kwargs)) @filter_kwargs def find(self, **kwargs): """Find a single item with attributes matching ``**kwargs``.""" url = self.build_url(dict_args_in_out=kwargs) query = self._build_query(kwargs) rl = self._list( '%(url)s%(query)s' % { 'url': url, 'query': query, }, self.collection_key) num = len(rl) if num == 0: msg = _("No %(name)s matching %(kwargs)s.") % { 'name': self.resource_class.__name__, 'kwargs': kwargs} raise exceptions.NotFound(404, msg) elif num > 1: raise exceptions.NoUniqueMatch else: return rl[0] class Resource(object): """Base class for OpenStack resources (tenant, user, etc.). This is pretty much just a bag for attributes. """ HUMAN_ID = False NAME_ATTR = 'name' def __init__(self, manager, info, loaded=False): """Populate and bind to a manager. :param manager: BaseManager object :param info: dictionary representing resource attributes :param loaded: prevent lazy-loading if set to True """ self.manager = manager self._info = info self._add_details(info) self._loaded = loaded def __repr__(self): reprkeys = sorted(k for k in self.__dict__.keys() if k[0] != '_' and k != 'manager') info = ", ".join("%s=%s" % (k, getattr(self, k)) for k in reprkeys) return "<%s %s>" % (self.__class__.__name__, info) @property def human_id(self): """Human-readable ID which can be used for bash completion. """ if self.HUMAN_ID: name = getattr(self, self.NAME_ATTR, None) if name is not None: return strutils.to_slug(name) return None def _add_details(self, info): for (k, v) in six.iteritems(info): try: setattr(self, k, v) self._info[k] = v except AttributeError: # In this case we already defined the attribute on the class pass def __getattr__(self, k): if k not in self.__dict__: # NOTE(bcwaldon): disallow lazy-loading if already loaded once if not self.is_loaded(): self.get() return self.__getattr__(k) raise AttributeError(k) else: return self.__dict__[k] def get(self): """Support for lazy loading details. Some clients, such as novaclient have the option to lazy load the details, details which can be loaded with this function. """ # set_loaded() first ... so if we have to bail, we know we tried. self.set_loaded(True) if not hasattr(self.manager, 'get'): return new = self.manager.get(self.id) if new: self._add_details(new._info) self._add_details( {'x_request_id': self.manager.client.last_request_id}) def __eq__(self, other): if not isinstance(other, Resource): return NotImplemented # two resources of different types are not equal if not isinstance(other, self.__class__): return False if hasattr(self, 'id') and hasattr(other, 'id'): return self.id == other.id return self._info == other._info def is_loaded(self): return self._loaded def set_loaded(self, val): self._loaded = val def to_dict(self): return copy.deepcopy(self._info) def delete(self): return self.manager.delete(self)
"""Test spherical harmonic models and the tools associated with those models""" import numpy as np import numpy.linalg as npl from nose.tools import assert_equal, assert_raises, assert_true from numpy.testing import assert_array_equal, assert_array_almost_equal import numpy.testing as npt from scipy.special import sph_harm as sph_harm_sp from dipy.core.sphere import hemi_icosahedron from dipy.core.gradients import gradient_table from dipy.sims.voxel import single_tensor from dipy.direction.peaks import peak_directions from dipy.reconst.shm import sf_to_sh, sh_to_sf from dipy.reconst.interpolate import NearestNeighborInterpolator from dipy.sims.voxel import multi_tensor_odf from dipy.data import mrtrix_spherical_functions from dipy.reconst import odf from dipy.reconst.shm import (real_sph_harm, real_sym_sh_basis, real_sym_sh_mrtrix, sph_harm_ind_list, order_from_ncoef, OpdtModel, normalize_data, hat, lcr_matrix, smooth_pinv, bootstrap_data_array, bootstrap_data_voxel, ResidualBootstrapWrapper, CsaOdfModel, QballModel, SphHarmFit, spherical_harmonics, anisotropic_power, calculate_max_order) def test_order_from_ncoeff(): """ """ # Just try some out: for sh_order in [2, 4, 6, 8, 12, 24]: m, n = sph_harm_ind_list(sh_order) n_coef = m.shape[0] npt.assert_equal(order_from_ncoef(n_coef), sh_order) def test_sph_harm_ind_list(): m_list, n_list = sph_harm_ind_list(8) assert_equal(m_list.shape, n_list.shape) assert_equal(m_list.shape, (45,)) assert_true(np.all(np.abs(m_list) <= n_list)) assert_array_equal(n_list % 2, 0) assert_raises(ValueError, sph_harm_ind_list, 1) def test_real_sph_harm(): # Tests derived from tables in # http://en.wikipedia.org/wiki/Table_of_spherical_harmonics # where real spherical harmonic $Y^m_n$ is defined to be: # Real($Y^m_n$) * sqrt(2) if m > 0 # $Y^m_n$ if m == 0 # Imag($Y^m_n$) * sqrt(2) if m < 0 rsh = real_sph_harm pi = np.pi exp = np.exp sqrt = np.sqrt sin = np.sin cos = np.cos assert_array_almost_equal(rsh(0, 0, 0, 0), 0.5 / sqrt(pi)) assert_array_almost_equal(rsh(-2, 2, pi / 5, pi / 3), 0.25 * sqrt(15. / (2. * pi)) * (sin(pi / 5.)) ** 2. * cos(0 + 2. * pi / 3) * sqrt(2)) assert_array_almost_equal(rsh(2, 2, pi / 5, pi / 3), -1 * 0.25 * sqrt(15. / (2. * pi)) * (sin(pi / 5.)) ** 2. * sin(0 - 2. * pi / 3) * sqrt(2)) assert_array_almost_equal(rsh(-2, 2, pi / 2, pi), 0.25 * sqrt(15 / (2. * pi)) * cos(2. * pi) * sin(pi / 2.) ** 2. * sqrt(2)) assert_array_almost_equal(rsh(2, 4, pi / 3., pi / 4.), -1 * (3. / 8.) * sqrt(5. / (2. * pi)) * sin(0 - 2. * pi / 4.) * sin(pi / 3.) ** 2. * (7. * cos(pi / 3.) ** 2. - 1) * sqrt(2)) assert_array_almost_equal(rsh(-4, 4, pi / 6., pi / 8.), (3. / 16.) * sqrt(35. / (2. * pi)) * cos(0 + 4. * pi / 8.) * sin(pi / 6.) ** 4. * sqrt(2)) assert_array_almost_equal(rsh(4, 4, pi / 6., pi / 8.), -1 * (3. / 16.) * sqrt(35. / (2. * pi)) * sin(0 - 4. * pi / 8.) * sin(pi / 6.) ** 4. * sqrt(2)) aa = np.ones((3, 1, 1, 1)) bb = np.ones((1, 4, 1, 1)) cc = np.ones((1, 1, 5, 1)) dd = np.ones((1, 1, 1, 6)) assert_equal(rsh(aa, bb, cc, dd).shape, (3, 4, 5, 6)) def test_real_sym_sh_mrtrix(): coef, expected, sphere = mrtrix_spherical_functions() basis, m, n = real_sym_sh_mrtrix(8, sphere.theta, sphere.phi) func = np.dot(coef, basis.T) assert_array_almost_equal(func, expected, 4) def test_real_sym_sh_basis(): # This test should do for now # The mrtrix basis should be the same as re-ordering and re-scaling the # fibernav basis new_order = [0, 5, 4, 3, 2, 1, 14, 13, 12, 11, 10, 9, 8, 7, 6] sphere = hemi_icosahedron.subdivide(2) basis, m, n = real_sym_sh_mrtrix(4, sphere.theta, sphere.phi) expected = basis[:, new_order] expected *= np.where(m == 0, 1., np.sqrt(2)) fibernav_basis, m, n = real_sym_sh_basis(4, sphere.theta, sphere.phi) assert_array_almost_equal(fibernav_basis, expected) def test_smooth_pinv(): hemi = hemi_icosahedron.subdivide(2) m, n = sph_harm_ind_list(4) B = real_sph_harm(m, n, hemi.theta[:, None], hemi.phi[:, None]) L = np.zeros(len(m)) C = smooth_pinv(B, L) D = np.dot(npl.inv(np.dot(B.T, B)), B.T) assert_array_almost_equal(C, D) L = n * (n + 1) * .05 C = smooth_pinv(B, L) L = np.diag(L) D = np.dot(npl.inv(np.dot(B.T, B) + L * L), B.T) assert_array_almost_equal(C, D) L = np.arange(len(n)) * .05 C = smooth_pinv(B, L) L = np.diag(L) D = np.dot(npl.inv(np.dot(B.T, B) + L * L), B.T) assert_array_almost_equal(C, D) def test_normalize_data(): sig = np.arange(1, 66)[::-1] where_b0 = np.zeros(65, 'bool') where_b0[0] = True d = normalize_data(sig, where_b0, 1) assert_raises(ValueError, normalize_data, sig, where_b0, out=sig) norm_sig = normalize_data(sig, where_b0, min_signal=1) assert_array_almost_equal(norm_sig, sig / 65.) norm_sig = normalize_data(sig, where_b0, min_signal=5) assert_array_almost_equal(norm_sig[-5:], 5 / 65.) where_b0[[0, 1]] = [True, True] norm_sig = normalize_data(sig, where_b0, min_signal=1) assert_array_almost_equal(norm_sig, sig / 64.5) norm_sig = normalize_data(sig, where_b0, min_signal=5) assert_array_almost_equal(norm_sig[-5:], 5 / 64.5) sig = sig * np.ones((2, 3, 1)) where_b0[[0, 1]] = [True, False] norm_sig = normalize_data(sig, where_b0, min_signal=1) assert_array_almost_equal(norm_sig, sig / 65.) norm_sig = normalize_data(sig, where_b0, min_signal=5) assert_array_almost_equal(norm_sig[..., -5:], 5 / 65.) where_b0[[0, 1]] = [True, True] norm_sig = normalize_data(sig, where_b0, min_signal=1) assert_array_almost_equal(norm_sig, sig / 64.5) norm_sig = normalize_data(sig, where_b0, min_signal=5) assert_array_almost_equal(norm_sig[..., -5:], 5 / 64.5) def make_fake_signal(): hemisphere = hemi_icosahedron.subdivide(2) bvecs = np.concatenate(([[0, 0, 0]], hemisphere.vertices)) bvals = np.zeros(len(bvecs)) + 2000 bvals[0] = 0 gtab = gradient_table(bvals, bvecs) evals = np.array([[2.1, .2, .2], [.2, 2.1, .2]]) * 10 ** -3 evecs0 = np.eye(3) sq3 = np.sqrt(3) / 2. evecs1 = np.array([[sq3, .5, 0], [.5, sq3, 0], [0, 0, 1.]]) evecs1 = evecs0 a = evecs0[0] b = evecs1[1] S1 = single_tensor(gtab, .55, evals[0], evecs0) S2 = single_tensor(gtab, .45, evals[1], evecs1) return S1 + S2, gtab, np.vstack([a, b]) class TestQballModel(object): model = QballModel def test_single_voxel_fit(self): signal, gtab, expected = make_fake_signal() sphere = hemi_icosahedron.subdivide(4) model = self.model(gtab, sh_order=4, min_signal=1e-5, assume_normed=True) fit = model.fit(signal) odf = fit.odf(sphere) assert_equal(odf.shape, sphere.phi.shape) directions, _, _ = peak_directions(odf, sphere) # Check the same number of directions n = len(expected) assert_equal(len(directions), n) # Check directions are unit vectors cos_similarity = (directions * directions).sum(-1) assert_array_almost_equal(cos_similarity, np.ones(n)) # Check the directions == expected or -expected cos_similarity = (directions * expected).sum(-1) assert_array_almost_equal(abs(cos_similarity), np.ones(n)) # Test normalize data model = self.model(gtab, sh_order=4, min_signal=1e-5, assume_normed=False) fit = model.fit(signal * 5) odf_with_norm = fit.odf(sphere) assert_array_almost_equal(odf, odf_with_norm) def test_mulit_voxel_fit(self): signal, gtab, expected = make_fake_signal() sphere = hemi_icosahedron nd_signal = np.vstack([signal, signal]) model = self.model(gtab, sh_order=4, min_signal=1e-5, assume_normed=True) fit = model.fit(nd_signal) odf = fit.odf(sphere) assert_equal(odf.shape, (2,) + sphere.phi.shape) # Test fitting with mask, where mask is False odf should be 0 fit = model.fit(nd_signal, mask=[False, True]) odf = fit.odf(sphere) assert_array_equal(odf[0], 0.) def test_sh_order(self): signal, gtab, expected = make_fake_signal() model = self.model(gtab, sh_order=4, min_signal=1e-5) assert_equal(model.B.shape[1], 15) assert_equal(max(model.n), 4) model = self.model(gtab, sh_order=6, min_signal=1e-5) assert_equal(model.B.shape[1], 28) assert_equal(max(model.n), 6) def test_gfa(self): signal, gtab, expected = make_fake_signal() signal = np.ones((2, 3, 4, 1)) * signal sphere = hemi_icosahedron.subdivide(3) model = self.model(gtab, 6, min_signal=1e-5) fit = model.fit(signal) gfa_shm = fit.gfa gfa_odf = odf.gfa(fit.odf(sphere)) assert_array_almost_equal(gfa_shm, gfa_odf, 3) # gfa should be 0 if all coefficients are 0 (masked areas) mask = np.zeros(signal.shape[:-1]) fit = model.fit(signal, mask) assert_array_equal(fit.gfa, 0) def test_SphHarmFit(): coef = np.zeros((3, 4, 5, 45)) mask = np.zeros((3, 4, 5), dtype=bool) fit = SphHarmFit(None, coef, mask) item = fit[0, 0, 0] assert_equal(item.shape, ()) slice = fit[0] assert_equal(slice.shape, (4, 5)) slice = fit[:, :, 0] assert_equal(slice.shape, (3, 4)) class TestOpdtModel(TestQballModel): model = OpdtModel class TestCsaOdfModel(TestQballModel): model = CsaOdfModel def test_hat_and_lcr(): hemi = hemi_icosahedron.subdivide(3) m, n = sph_harm_ind_list(8) B = real_sph_harm(m, n, hemi.theta[:, None], hemi.phi[:, None]) H = hat(B) B_hat = np.dot(H, B) assert_array_almost_equal(B, B_hat) R = lcr_matrix(H) d = np.arange(len(hemi.theta)) r = d - np.dot(H, d) lev = np.sqrt(1 - H.diagonal()) r /= lev r -= r.mean() r2 = np.dot(R, d) assert_array_almost_equal(r, r2) r3 = np.dot(d, R.T) assert_array_almost_equal(r, r3) def test_bootstrap_array(): B = np.array([[4, 5, 7, 4, 2.], [4, 6, 2, 3, 6.]]) H = hat(B.T) R = np.zeros((5, 5)) d = np.arange(1, 6) dhat = np.dot(H, d) assert_array_almost_equal(bootstrap_data_voxel(dhat, H, R), dhat) assert_array_almost_equal(bootstrap_data_array(dhat, H, R), dhat) H = np.zeros((5, 5)) def test_ResidualBootstrapWrapper(): B = np.array([[4, 5, 7, 4, 2.], [4, 6, 2, 3, 6.]]) B = B.T H = hat(B) d = np.arange(10) / 8. d.shape = (2, 5) dhat = np.dot(d, H) signal_object = NearestNeighborInterpolator(dhat, (1,)) ms = .2 where_dwi = np.ones(len(H), dtype=bool) boot_obj = ResidualBootstrapWrapper(signal_object, B, where_dwi, ms) assert_array_almost_equal(boot_obj[0], dhat[0].clip(ms, 1)) assert_array_almost_equal(boot_obj[1], dhat[1].clip(ms, 1)) dhat = np.column_stack([[.6, .7], dhat]) signal_object = NearestNeighborInterpolator(dhat, (1,)) where_dwi = np.concatenate([[False], where_dwi]) boot_obj = ResidualBootstrapWrapper(signal_object, B, where_dwi, ms) assert_array_almost_equal(boot_obj[0], dhat[0].clip(ms, 1)) assert_array_almost_equal(boot_obj[1], dhat[1].clip(ms, 1)) def test_sf_to_sh(): # Subdividing a hemi_icosahedron twice produces 81 unique points, which # is more than enough to fit a order 8 (45 coefficients) spherical harmonic sphere = hemi_icosahedron.subdivide(2) mevals = np.array(([0.0015, 0.0003, 0.0003], [0.0015, 0.0003, 0.0003])) angles = [(0, 0), (90, 0)] odf = multi_tensor_odf(sphere.vertices, mevals, angles, [50, 50]) # 1D case with the 3 bases functions odf_sh = sf_to_sh(odf, sphere, 8) odf2 = sh_to_sf(odf_sh, sphere, 8) assert_array_almost_equal(odf, odf2, 2) odf_sh = sf_to_sh(odf, sphere, 8, "mrtrix") odf2 = sh_to_sf(odf_sh, sphere, 8, "mrtrix") assert_array_almost_equal(odf, odf2, 2) odf_sh = sf_to_sh(odf, sphere, 8, "fibernav") odf2 = sh_to_sf(odf_sh, sphere, 8, "fibernav") assert_array_almost_equal(odf, odf2, 2) # 2D case odf2d = np.vstack((odf2, odf)) odf2d_sh = sf_to_sh(odf2d, sphere, 8) odf2d_sf = sh_to_sf(odf2d_sh, sphere, 8) assert_array_almost_equal(odf2d, odf2d_sf, 2) def test_faster_sph_harm(): sh_order = 8 m, n = sph_harm_ind_list(sh_order) theta = np.array([1.61491146, 0.76661665, 0.11976141, 1.20198246, 1.74066314, 1.5925956 , 2.13022055, 0.50332859, 1.19868988, 0.78440679, 0.50686938, 0.51739718, 1.80342999, 0.73778957, 2.28559395, 1.29569064, 1.86877091, 0.39239191, 0.54043037, 1.61263047, 0.72695314, 1.90527318, 1.58186125, 0.23130073, 2.51695237, 0.99835604, 1.2883426 , 0.48114057, 1.50079318, 1.07978624, 1.9798903 , 2.36616966, 2.49233299, 2.13116602, 1.36801518, 1.32932608, 0.95926683, 1.070349 , 0.76355762, 2.07148422, 1.50113501, 1.49823314, 0.89248164, 0.22187079, 1.53805373, 1.9765295 , 1.13361568, 1.04908355, 1.68737368, 1.91732452, 1.01937457, 1.45839 , 0.49641525, 0.29087155, 0.52824641, 1.29875871, 1.81023541, 1.17030475, 2.24953206, 1.20280498, 0.76399964, 2.16109722, 0.79780421, 0.87154509]) phi = np.array([-1.5889514 , -3.11092733, -0.61328674, -2.4485381 , 2.88058822, 2.02165946, -1.99783366, 2.71235211, 1.41577992, -2.29413676, -2.24565773, -1.55548635, 2.59318232, -1.84672472, -2.33710739, 2.12111948, 1.87523722, -1.05206575, -2.85381987, -2.22808984, 2.3202034 , -2.19004474, -1.90358372, 2.14818373, 3.1030696 , -2.86620183, -2.19860123, -0.45468447, -3.0034923 , 1.73345011, -2.51716288, 2.49961525, -2.68782986, 2.69699056, 1.78566133, -1.59119705, -2.53378963, -2.02476738, 1.36924987, 2.17600517, 2.38117241, 2.99021511, -1.4218007 , -2.44016802, -2.52868164, 3.01531658, 2.50093627, -1.70745826, -2.7863931 , -2.97359741, 2.17039906, 2.68424643, 1.77896086, 0.45476215, 0.99734418, -2.73107896, 2.28815009, 2.86276506, 3.09450274, -3.09857384, -1.06955885, -2.83826831, 1.81932195, 2.81296654]) sh = spherical_harmonics(m, n, theta[:, None], phi[:, None]) sh2 = sph_harm_sp(m, n, theta[:, None], phi[:, None]) assert_array_almost_equal(sh, sh2, 8) def test_anisotropic_power(): for n_coeffs in [6, 15, 28, 45, 66, 91]: for norm_factor in [0.0005, 0.00001]: # Create some really simple cases: coeffs = np.ones((3, n_coeffs)) max_order = calculate_max_order(coeffs.shape[-1]) # For the case where all coeffs == 1, the ap is simply log of the # number of even orders up to the maximal order: analytic = (np.log(len(range(2, max_order + 2, 2))) - np.log(norm_factor)) answers = [analytic] * 3 apvals = anisotropic_power(coeffs, norm_factor=norm_factor) assert_array_almost_equal(apvals, answers) # Test that this works for single voxel arrays as well: assert_array_almost_equal( anisotropic_power(coeffs[1], norm_factor=norm_factor), answers[1]) def test_calculate_max_order(): """Based on the table in: http://jdtournier.github.io/mrtrix-0.2/tractography/preprocess.html """ orders = [2, 4, 6, 8, 10, 12] n_coeffs = [6, 15, 28, 45, 66, 91] for o, n in zip(orders, n_coeffs): assert_equal(calculate_max_order(n), o) if __name__ == "__main__": import nose nose.runmodule()
import mock import os import unittest import testutils from bin.commands import settings class TestSettings(unittest.TestCase): @mock.patch('bin.commands.utils.directories.is_git_repository') @mock.patch('bin.commands.utils.messages.error') def test__validateConfig_valid_notLocal(self, mock_error, mock_isgitrepository): # when settings._validate_config('global') # then mock_isgitrepository.assert_not_called() mock_error.assert_not_called() @mock.patch('bin.commands.utils.directories.is_git_repository') @mock.patch('bin.commands.utils.messages.error') def test__validateConfig_valid_localButIsGitRepository(self, mock_error, mock_isgitrepository): # given mock_isgitrepository.return_value = True # when settings._validate_config('local') # then mock_isgitrepository.assert_called_once() mock_error.assert_not_called() @mock.patch('bin.commands.utils.directories.is_git_repository') @mock.patch('bin.commands.utils.messages.error') @mock.patch('os.getcwd', return_value='/working/dir') def test__validateConfig_invalid(self, mock_getcwd, mock_error, mock_isgitrepository): # given directory = '/cur/dir' mock_isgitrepository.return_value = False mock_getcwd.return_value = directory # mock_error.side_effect = [None, testutils.and_exit] # when try: settings._validate_config('local') # self.fail('expected to exit but did not') # pragma: no cover except SystemExit: pass # then mock_isgitrepository.assert_called_once() mock_error.assert_has_calls([ mock.call('{0!r} is not a git repository'.format(directory), exit_=False), mock.call("'local' does not apply") ]) mock_getcwd.assert_called_once() def test__prettyFormatConfigs(self): # given config_map = { 'settings.keys.key1': 'value1', 'settings.key2': 'value2', 'settings.key3': 'value3' } # when formatted = settings._pretty_format_configs(config_map) # then self.assertEqual(os.linesep.join(formatted), '''[settings "keys"] key1 = value1 [settings] key3 = value3 key2 = value2''') @mock.patch('bin.commands.utils.execute.stdout') @mock.patch('bin.commands.utils.messages.info') def test__dryDestroySection(self, mock_info, mock_stdout): # given config = 'local' section = 'section_name' keys = ('test.k1=v1', 'test.k2=v2') mock_stdout.return_value = os.linesep.join(keys) + os.linesep # when settings._dry_destroy_section(config, section) # then mock_stdout.assert_called_once_with( ('git', 'settings', 'list', '--format', 'compact', '--{}'.format(config), section) ) mock_info.assert_has_calls([ mock.call('Would be deleted from {}: {}'.format(config, keys[0])), mock.call('Would be deleted from {}: {}'.format(config, keys[1])) ]) class TestSettingsList(unittest.TestCase): def setUp(self): # store private methods so they can be restored after tests that mock them self._validate_config = settings._validate_config self._pretty_format_configs = settings._pretty_format_configs def tearDown(self): settings._validate_config = self._validate_config settings._pretty_format_configs = self._pretty_format_configs @mock.patch('bin.commands.settings._validate_config') @mock.patch('bin.commands.utils.execute.check_output') def test_list(self, mock_checkoutput, mock_validateconfig): # given config_values = ['section.key1=value1', 'section.key2=value2'] mock_checkoutput.return_value = '\x00'.join(config_values).replace('=', os.linesep) + '\x00' # when actual_values = settings.list_() # then self.assertEqual(sorted(actual_values.splitlines()), config_values) mock_validateconfig.assert_called_once() mock_checkoutput.assert_called_once_with(['git', 'config', '--list', '--null']) @mock.patch('bin.commands.settings._validate_config') @mock.patch('bin.commands.utils.execute.check_output') def test_list_withOverrides(self, mock_checkoutput, mock_validateconfig): # given config_values = ['section.key1=override1', 'section.key2=value2'] config_values_with_overrides = ['section.key1=value1'] + config_values mock_checkoutput.return_value = '\x00'.join(config_values_with_overrides).replace('=', os.linesep) + '\x00' # when actual_values = settings.list_() # then self.assertEqual(sorted(actual_values.splitlines()), config_values) mock_validateconfig.assert_called_once() mock_checkoutput.assert_called_once_with(['git', 'config', '--list', '--null']) @mock.patch('bin.commands.settings._validate_config') @mock.patch('os.path.exists', return_value=True) @mock.patch('bin.commands.utils.execute.check_output') def test_list_withFile(self, mock_checkoutput, mock_exists, mock_validateconfig): # given file_path = '/file/path' config_values = ['section.key1=value1', 'section.key2=value2'] mock_checkoutput.return_value = '\x00'.join(config_values).replace('=', os.linesep) + '\x00' # when actual_values = settings.list_(config='file', file_=file_path) # then self.assertEqual(sorted(actual_values.splitlines()), config_values) mock_validateconfig.assert_called_once() mock_exists.assert_called_once_with(file_path) mock_checkoutput.assert_called_once_with(['git', 'config', '--list', '--null', '--file', file_path]) @mock.patch('bin.commands.settings._validate_config') @mock.patch('os.path.exists', return_value=False) @mock.patch('bin.commands.utils.messages.error', side_effect=testutils.and_exit) def test_list_withFile_filesDoesNotExist(self, mock_error, mock_exists, mock_validateconfig): # given unknown_file = 'unknown_file' # when try: settings.list_(config='file', file_=unknown_file) self.fail('expected to exit but did not') # pragma: no cover except SystemExit: pass # then mock_validateconfig.assert_called_once() mock_error.assert_called_once_with('no such file {!r}'.format(unknown_file)) @mock.patch('bin.commands.settings._validate_config') @mock.patch('bin.commands.utils.execute.stdout') def test_list_withConfig(self, mock_stdout, mock_validateconfig): # given config_values = ['section.key1=value1', 'section.key2=value2'] mock_stdout.return_value = '\x00'.join(config_values).replace('=', os.linesep) + '\x00' # when actual_values = settings.list_(config='global') # then self.assertEqual(sorted(actual_values.splitlines()), config_values) mock_validateconfig.assert_called_once() mock_stdout.assert_called_once_with(['git', 'config', '--list', '--null', '--global']) @mock.patch('bin.commands.settings._validate_config') @mock.patch('bin.commands.utils.execute.stdout') def test_list_noConfigsFound(self, mock_stdout, mock_validateconfig): # given mock_stdout.return_value = '' # when actual_values = settings.list_(config='system') # then self.assertFalse(actual_values) mock_validateconfig.assert_called_once() mock_stdout.assert_called_once_with(['git', 'config', '--list', '--null', '--system']) @mock.patch('bin.commands.settings._validate_config') @mock.patch('bin.commands.utils.execute.check_output') def test_list_withSection(self, mock_checkoutput, mock_validateconfig): # given config_values = ['section.key1=value1', 'section.key2=value2'] mock_checkoutput.return_value = '\x00'.join(config_values + ['section2.k=v']).replace('=', os.linesep) + '\x00' # when actual_values = settings.list_(section='section') # then self.assertEqual(sorted(actual_values.splitlines()), config_values) mock_validateconfig.assert_called_once() mock_checkoutput.assert_called_once_with(['git', 'config', '--list', '--null']) @mock.patch('bin.commands.settings._validate_config') @mock.patch('bin.commands.utils.execute.check_output') def test_list_count(self, mock_checkoutput, mock_validateconfig): # given config_values = ['section.key1=value1', 'section.key2=value2'] mock_checkoutput.return_value = '\x00'.join(config_values).replace('=', os.linesep) + '\x00' # when actual_count = settings.list_(count=True) # then self.assertEqual(actual_count, '2') mock_validateconfig.assert_called_once() mock_checkoutput.assert_called_once_with(['git', 'config', '--list', '--null']) @mock.patch('bin.commands.settings._validate_config') @mock.patch('bin.commands.utils.execute.check_output') def test_list_keysOnly(self, mock_checkoutput, mock_validateconfig): # given config_values = ['section.key1=value1', 'section.key2=value2'] mock_checkoutput.return_value = '\x00'.join(config_values).replace('=', os.linesep) + '\x00' # when actual_values = settings.list_(limit_to='keys') # then self.assertEqual(sorted(actual_values.splitlines()), ['key1', 'key2']) mock_validateconfig.assert_called_once() mock_checkoutput.assert_called_once_with(['git', 'config', '--list', '--null']) @mock.patch('bin.commands.settings._validate_config') @mock.patch('bin.commands.utils.execute.check_output') def test_list_sectionsOnly(self, mock_checkoutput, mock_validateconfig): # given config_values = ['section.key1=value1', 'section.key2=value2', 'section2.key1=value1'] mock_checkoutput.return_value = '\x00'.join(config_values).replace('=', os.linesep) + '\x00' # when actual_values = settings.list_(limit_to='sections') # then self.assertEqual(sorted(actual_values.splitlines()), ['section', 'section2']) mock_validateconfig.assert_called_once() mock_checkoutput.assert_called_once_with(['git', 'config', '--list', '--null']) @mock.patch('bin.commands.settings._validate_config') @mock.patch('bin.commands.settings._pretty_format_configs') @mock.patch('bin.commands.utils.execute.check_output') def test_list_prettyFormat(self, mock_checkoutput, mock_prettyformatconfig, mock_validateconfig): # given config_values = ['section.keys.key1=value1', 'section.keys.key2=value2', 'sec.key=value'] mock_checkoutput.return_value = '\x00'.join(config_values).replace('=', os.linesep) + '\x00' format_result = ['formatted results'] mock_prettyformatconfig.return_value = format_result # when pretty_output = settings.list_(format_='pretty') # then self.assertEqual(pretty_output, format_result[0]) mock_validateconfig.assert_called_once() mock_checkoutput.assert_called_once_with(['git', 'config', '--list', '--null']) class TestSettingsDestroy(unittest.TestCase): def setUp(self): # store private methods so they can be restored after tests that mock them self._dry_destroy_section = settings._dry_destroy_section def tearDown(self): settings._dry_destroy_section = self._dry_destroy_section @mock.patch('bin.commands.utils.directories.is_git_repository', return_value=True) @mock.patch('bin.commands.utils.execute.swallow') def test_destroy_hasLocal(self, mock_swallow, mock_isgitrepository): # given section = 'section_name' dry_run = False # when settings.destroy(section, dry_run) # then mock_isgitrepository.assert_called_once() mock_swallow.assert_has_calls([ mock.call(('git', 'config', '--local', '--remove-section', section)), mock.call(('git', 'config', '--global', '--remove-section', section)), mock.call(('git', 'config', '--system', '--remove-section', section)) ]) @mock.patch('bin.commands.utils.directories.is_git_repository', return_value=False) @mock.patch('bin.commands.utils.execute.swallow') def test_destroy_noLocal(self, mock_swallow, mock_isgitrepository): # given section = 'section_name' dry_run = False # when settings.destroy(section, dry_run) # then mock_isgitrepository.assert_called_once() mock_swallow.assert_has_calls([ mock.call(('git', 'config', '--global', '--remove-section', section)), mock.call(('git', 'config', '--system', '--remove-section', section)) ]) @mock.patch('bin.commands.utils.directories.is_git_repository', return_value=True) @mock.patch('bin.commands.settings._dry_destroy_section') def test_destroy_dryRun_hasLocal(self, mock_drydestroysection, mock_isgitrepository): # given section = 'section_name' dry_run = True # when settings.destroy(section, dry_run) # then mock_isgitrepository.assert_called_once() mock_drydestroysection.assert_has_calls([ mock.call('local', section), mock.call('global', section), mock.call('system', section) ]) @mock.patch('bin.commands.utils.directories.is_git_repository', return_value=False) @mock.patch('bin.commands.settings._dry_destroy_section') def test_destroy_dryRun_noLocal(self, mock_drydestroysection, mock_isgitrepository): # given section = 'section_name' dry_run = True # when settings.destroy(section, dry_run) # then mock_isgitrepository.assert_called_once() mock_drydestroysection.assert_has_calls([ mock.call('global', section), mock.call('system', section) ])
import curses from curses import cbreak, echo, endwin, initscr, nocbreak, noecho import logging from os import chdir, environ, getcwd from subprocess import check_output, CalledProcessError, Popen, PIPE from time import sleep from threading import Thread from queue import Queue class History: def __init__(self): self.__commands = [] self.__selectedIndex = 0 def add(self, command): self.__commands.append(command) self.__selectedIndex = len(self.__commands) def previous(self): if self.__selectedIndex - 1 >= 0: self.__selectedIndex -= 1 return self.__commands[self.__selectedIndex] return None def next(self): if self.__selectedIndex + 1 < len(self.__commands): self.__selectedIndex += 1 return self.__commands[self.__selectedIndex] return None def last(self): if len(self.__commands) != 0: return self.__commands[-1] return None class ExitCalledException(Exception): pass class Shell: def __init__(self): self.__initEnvironment() self.__initConfig() self.__initHistory() self.__initLogging() self.__initWindow() self.__jobs = [] logging.info("Starting writer...") self.writer = Shell.Writer(self.__window) self.writer.start() def __initConfig(self): self.__config = {} self.__resetPrompt() def __initEnvironment(self): self.__environment = {} self.__environment["HOME"] = environ.get("HOME") self.__environment["PWD"] = environ.get("PWD") def __initHistory(self): self.history = History() def __initLogging(self): with open("debug.log", "w"): pass logging.basicConfig(filename="debug.log", level=logging.DEBUG) def __resetPrompt(self): prompt = "{0} $".format(self.__environment["PWD"]) self.__config["PROMPT"] = prompt.replace( self.__environment["HOME"], "~") def __initWindow(self): self.__window = initscr() noecho() cbreak() self.__window.keypad(True) self.__window.scrollok(True) self.__window.idlok(1) def __deinitWriter(self): logging.info("Stopping writer...") self.writer.stop() self.writer.join() def __deinitWindow(self): logging.info("Destructing window...") nocbreak() self.__window.keypad(False) echo() endwin() def run(self): try: while True: self.writer.add("\r{0}".format(self.__config["PROMPT"])) self.__fetch() self.__execute() except Exception as e: logging.info(e) finally: self.__deinitWriter() self.__deinitWindow() logging.info("Application closing.") def __fetch(self): command = "" while True: # FIXME: KeyboardInterrupt results in chr() arg out of range? try: character = self.__window.getch() if character == curses.KEY_ENTER or character == 10: if len(command.strip()) != 0: command += "\n" break else: self.writer.add("\n") elif character == curses.KEY_BACKSPACE: command = command[0:-1] elif character == curses.KEY_UP: temp = self.history.previous() if temp is not None: command = temp elif character == curses.KEY_DOWN: temp = self.history.next() if temp is not None: command = temp else: command += chr(character) self.writer.add("\r{0}{1}".format( self.__config["PROMPT"], command)) except KeyboardInterrupt: pass self.writer.add("\n") self.history.add(command.strip()) def __execute(self): command = self.history.last().split() command = self.__replaceEnvironmentVars(command) logging.info("Executing: {0}".format(command)) if command[0] == "exit": self.__exit() elif command[0] == "cd": if len(command) == 2: self.__changeDir(command[1]) else: self.writer.add("cd: Need directory as argument.\n") else: try: pipe = Popen(command, stdout=PIPE) output = pipe.communicate()[0] self.writer.add(output.decode("utf-8")) except FileNotFoundError: self.writer.add( "Command not found: {0}\n".format(command[0])) except KeyboardInterrupt: pass def __replaceEnvironmentVars(self, command): for i, t in enumerate(command): if t.startswith("$"): logging.info("Found env variable.") value = self.__environment.get(t[1:len(t)]) logging.info("Value: {0}".format(value)) if value != None: logging.info("Replaced {0} with {1}.".format(t, value)) command[i] = value return command def __exit(self): raise ExitCalledException("Exit called by user.") def __changeDir(self, path): try: path = path.replace("~", self.__environment["HOME"]) chdir(path) self.__environment["PWD"] = getcwd() self.__resetPrompt() except OSError: self.writer.add( "cd: Invalid path. Did not change directory.\n") class Writer(Thread): class Cursor: def __init__(self, x=0, y=0): self.x = x self.y = y def move(self, x, y): self.x = x self.y = y def reset(self): self.x = 0 def left(self): self.x -= 1 def right(self): self.x += 1 def up(self): self.y -= 1 def down(self): self.y += 1 def __init__(self, window): super(Shell.Writer, self).__init__() self.__cursor = Shell.Writer.Cursor(0, 0) self.__stopCalled = False self.__queue = Queue() self.__window = window def add(self, message): if message is not None: self.__queue.put(message) def run(self): while not self.__stopCalled: if not self.__queue.empty(): message = self.__queue.get() self.__print(message) self.__window.move(self.__cursor.y, self.__cursor.x) self.__window.refresh() sleep(0.1) def stop(self): self.__stopCalled = True def __print(self, message): height, _ = self.__window.getmaxyx() for character in message: if character == "\n": self.__cursor.reset() if self.__cursor.y + 1 >= height: self.__window.scroll(1) else: self.__cursor.down() elif character == "\r": self.__cursor.reset() self.__window.move(self.__cursor.y, self.__cursor.x) self.__window.clrtoeol() else: self.__window.addch( self.__cursor.y, self.__cursor.x, character) self.__cursor.right() if __name__ == "__main__": sh = Shell() sh.run()
"""Tests for 1-Wire config flow.""" from unittest.mock import patch from pyownet import protocol from homeassistant.components.onewire.const import ( CONF_MOUNT_DIR, CONF_TYPE_OWSERVER, CONF_TYPE_SYSBUS, DEFAULT_SYSBUS_MOUNT_DIR, DOMAIN, ) from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TYPE from homeassistant.data_entry_flow import ( RESULT_TYPE_ABORT, RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_FORM, ) from . import setup_onewire_owserver_integration, setup_onewire_sysbus_integration async def test_user_owserver(hass): """Test OWServer user flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] == RESULT_TYPE_FORM assert not result["errors"] result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_TYPE: CONF_TYPE_OWSERVER}, ) assert result["type"] == RESULT_TYPE_FORM assert result["step_id"] == "owserver" assert not result["errors"] # Invalid server with patch( "homeassistant.components.onewire.onewirehub.protocol.proxy", side_effect=protocol.ConnError, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_HOST: "1.2.3.4", CONF_PORT: 1234}, ) assert result["type"] == RESULT_TYPE_FORM assert result["step_id"] == "owserver" assert result["errors"] == {"base": "cannot_connect"} # Valid server with patch("homeassistant.components.onewire.onewirehub.protocol.proxy",), patch( "homeassistant.components.onewire.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_HOST: "1.2.3.4", CONF_PORT: 1234}, ) assert result["type"] == RESULT_TYPE_CREATE_ENTRY assert result["title"] == "1.2.3.4" assert result["data"] == { CONF_TYPE: CONF_TYPE_OWSERVER, CONF_HOST: "1.2.3.4", CONF_PORT: 1234, } await hass.async_block_till_done() assert len(mock_setup_entry.mock_calls) == 1 async def test_user_owserver_duplicate(hass): """Test OWServer flow.""" with patch( "homeassistant.components.onewire.async_setup_entry", return_value=True, ) as mock_setup_entry: await setup_onewire_owserver_integration(hass) assert len(hass.config_entries.async_entries(DOMAIN)) == 1 result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] == RESULT_TYPE_FORM assert not result["errors"] result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_TYPE: CONF_TYPE_OWSERVER}, ) assert result["type"] == RESULT_TYPE_FORM assert result["step_id"] == "owserver" assert not result["errors"] # Duplicate server result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_HOST: "1.2.3.4", CONF_PORT: 1234}, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "already_configured" await hass.async_block_till_done() assert len(mock_setup_entry.mock_calls) == 1 async def test_user_sysbus(hass): """Test SysBus flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] == RESULT_TYPE_FORM assert not result["errors"] result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_TYPE: CONF_TYPE_SYSBUS}, ) assert result["type"] == RESULT_TYPE_FORM assert result["step_id"] == "mount_dir" assert not result["errors"] # Invalid path with patch( "homeassistant.components.onewire.onewirehub.os.path.isdir", return_value=False, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_MOUNT_DIR: "/sys/bus/invalid_directory"}, ) assert result["type"] == RESULT_TYPE_FORM assert result["step_id"] == "mount_dir" assert result["errors"] == {"base": "invalid_path"} # Valid path with patch( "homeassistant.components.onewire.onewirehub.os.path.isdir", return_value=True, ), patch( "homeassistant.components.onewire.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_MOUNT_DIR: "/sys/bus/directory"}, ) assert result["type"] == RESULT_TYPE_CREATE_ENTRY assert result["title"] == "/sys/bus/directory" assert result["data"] == { CONF_TYPE: CONF_TYPE_SYSBUS, CONF_MOUNT_DIR: "/sys/bus/directory", } await hass.async_block_till_done() assert len(mock_setup_entry.mock_calls) == 1 async def test_user_sysbus_duplicate(hass): """Test SysBus duplicate flow.""" with patch( "homeassistant.components.onewire.async_setup_entry", return_value=True, ) as mock_setup_entry: await setup_onewire_sysbus_integration(hass) assert len(hass.config_entries.async_entries(DOMAIN)) == 1 result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] == RESULT_TYPE_FORM assert not result["errors"] result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_TYPE: CONF_TYPE_SYSBUS}, ) assert result["type"] == RESULT_TYPE_FORM assert result["step_id"] == "mount_dir" assert not result["errors"] # Valid path with patch( "homeassistant.components.onewire.onewirehub.os.path.isdir", return_value=True, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_MOUNT_DIR: DEFAULT_SYSBUS_MOUNT_DIR}, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "already_configured" await hass.async_block_till_done() assert len(mock_setup_entry.mock_calls) == 1
# Copyright 2020 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. """AWS Credentials and AWS Signature V4 Request Signer. This module provides credentials to access Google Cloud resources from Amazon Web Services (AWS) workloads. These credentials are recommended over the use of service account credentials in AWS as they do not involve the management of long-live service account private keys. AWS Credentials are initialized using external_account arguments which are typically loaded from the external credentials JSON file. Unlike other Credentials that can be initialized with a list of explicit arguments, secrets or credentials, external account clients use the environment and hints/guidelines provided by the external_account JSON file to retrieve credentials and exchange them for Google access tokens. This module also provides a basic implementation of the `AWS Signature Version 4`_ request signing algorithm. AWS Credentials use serialized signed requests to the `AWS STS GetCallerIdentity`_ API that can be exchanged for Google access tokens via the GCP STS endpoint. .. _AWS Signature Version 4: https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html .. _AWS STS GetCallerIdentity: https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html """ import hashlib import hmac import io import json import os import posixpath import re try: from urllib.parse import urljoin # Python 2.7 compatibility except ImportError: # pragma: NO COVER from urlparse import urljoin from six.moves import http_client from six.moves import urllib from google.auth import _helpers from google.auth import environment_vars from google.auth import exceptions from google.auth import external_account # AWS Signature Version 4 signing algorithm identifier. _AWS_ALGORITHM = "AWS4-HMAC-SHA256" # The termination string for the AWS credential scope value as defined in # https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html _AWS_REQUEST_TYPE = "aws4_request" # The AWS authorization header name for the security session token if available. _AWS_SECURITY_TOKEN_HEADER = "x-amz-security-token" # The AWS authorization header name for the auto-generated date. _AWS_DATE_HEADER = "x-amz-date" class RequestSigner(object): """Implements an AWS request signer based on the AWS Signature Version 4 signing process. https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html """ def __init__(self, region_name): """Instantiates an AWS request signer used to compute authenticated signed requests to AWS APIs based on the AWS Signature Version 4 signing process. Args: region_name (str): The AWS region to use. """ self._region_name = region_name def get_request_options( self, aws_security_credentials, url, method, request_payload="", additional_headers={}, ): """Generates the signed request for the provided HTTP request for calling an AWS API. This follows the steps described at: https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html Args: aws_security_credentials (Mapping[str, str]): A dictionary containing the AWS security credentials. url (str): The AWS service URL containing the canonical URI and query string. method (str): The HTTP method used to call this API. request_payload (Optional[str]): The optional request payload if available. additional_headers (Optional[Mapping[str, str]]): The optional additional headers needed for the requested AWS API. Returns: Mapping[str, str]: The AWS signed request dictionary object. """ # Get AWS credentials. access_key = aws_security_credentials.get("access_key_id") secret_key = aws_security_credentials.get("secret_access_key") security_token = aws_security_credentials.get("security_token") additional_headers = additional_headers or {} uri = urllib.parse.urlparse(url) # Normalize the URL path. This is needed for the canonical_uri. # os.path.normpath can't be used since it normalizes "/" paths # to "\\" in Windows OS. normalized_uri = urllib.parse.urlparse( urljoin(url, posixpath.normpath(uri.path)) ) # Validate provided URL. if not uri.hostname or uri.scheme != "https": raise ValueError("Invalid AWS service URL") header_map = _generate_authentication_header_map( host=uri.hostname, canonical_uri=normalized_uri.path or "/", canonical_querystring=_get_canonical_querystring(uri.query), method=method, region=self._region_name, access_key=access_key, secret_key=secret_key, security_token=security_token, request_payload=request_payload, additional_headers=additional_headers, ) headers = { "Authorization": header_map.get("authorization_header"), "host": uri.hostname, } # Add x-amz-date if available. if "amz_date" in header_map: headers[_AWS_DATE_HEADER] = header_map.get("amz_date") # Append additional optional headers, eg. X-Amz-Target, Content-Type, etc. for key in additional_headers: headers[key] = additional_headers[key] # Add session token if available. if security_token is not None: headers[_AWS_SECURITY_TOKEN_HEADER] = security_token signed_request = {"url": url, "method": method, "headers": headers} if request_payload: signed_request["data"] = request_payload return signed_request def _get_canonical_querystring(query): """Generates the canonical query string given a raw query string. Logic is based on https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html Args: query (str): The raw query string. Returns: str: The canonical query string. """ # Parse raw query string. querystring = urllib.parse.parse_qs(query) querystring_encoded_map = {} for key in querystring: quote_key = urllib.parse.quote(key, safe="-_.~") # URI encode key. querystring_encoded_map[quote_key] = [] for item in querystring[key]: # For each key, URI encode all values for that key. querystring_encoded_map[quote_key].append( urllib.parse.quote(item, safe="-_.~") ) # Sort values for each key. querystring_encoded_map[quote_key].sort() # Sort keys. sorted_keys = list(querystring_encoded_map.keys()) sorted_keys.sort() # Reconstruct the query string. Preserve keys with multiple values. querystring_encoded_pairs = [] for key in sorted_keys: for item in querystring_encoded_map[key]: querystring_encoded_pairs.append("{}={}".format(key, item)) return "&".join(querystring_encoded_pairs) def _sign(key, msg): """Creates the HMAC-SHA256 hash of the provided message using the provided key. Args: key (str): The HMAC-SHA256 key to use. msg (str): The message to hash. Returns: str: The computed hash bytes. """ return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest() def _get_signing_key(key, date_stamp, region_name, service_name): """Calculates the signing key used to calculate the signature for AWS Signature Version 4 based on: https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html Args: key (str): The AWS secret access key. date_stamp (str): The '%Y%m%d' date format. region_name (str): The AWS region. service_name (str): The AWS service name, eg. sts. Returns: str: The signing key bytes. """ k_date = _sign(("AWS4" + key).encode("utf-8"), date_stamp) k_region = _sign(k_date, region_name) k_service = _sign(k_region, service_name) k_signing = _sign(k_service, "aws4_request") return k_signing def _generate_authentication_header_map( host, canonical_uri, canonical_querystring, method, region, access_key, secret_key, security_token, request_payload="", additional_headers={}, ): """Generates the authentication header map needed for generating the AWS Signature Version 4 signed request. Args: host (str): The AWS service URL hostname. canonical_uri (str): The AWS service URL path name. canonical_querystring (str): The AWS service URL query string. method (str): The HTTP method used to call this API. region (str): The AWS region. access_key (str): The AWS access key ID. secret_key (str): The AWS secret access key. security_token (Optional[str]): The AWS security session token. This is available for temporary sessions. request_payload (Optional[str]): The optional request payload if available. additional_headers (Optional[Mapping[str, str]]): The optional additional headers needed for the requested AWS API. Returns: Mapping[str, str]: The AWS authentication header dictionary object. This contains the x-amz-date and authorization header information. """ # iam.amazonaws.com host => iam service. # sts.us-east-2.amazonaws.com host => sts service. service_name = host.split(".")[0] current_time = _helpers.utcnow() amz_date = current_time.strftime("%Y%m%dT%H%M%SZ") date_stamp = current_time.strftime("%Y%m%d") # Change all additional headers to be lower case. full_headers = {} for key in additional_headers: full_headers[key.lower()] = additional_headers[key] # Add AWS session token if available. if security_token is not None: full_headers[_AWS_SECURITY_TOKEN_HEADER] = security_token # Required headers full_headers["host"] = host # Do not use generated x-amz-date if the date header is provided. # Previously the date was not fixed with x-amz- and could be provided # manually. # https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req if "date" not in full_headers: full_headers[_AWS_DATE_HEADER] = amz_date # Header keys need to be sorted alphabetically. canonical_headers = "" header_keys = list(full_headers.keys()) header_keys.sort() for key in header_keys: canonical_headers = "{}{}:{}\n".format( canonical_headers, key, full_headers[key] ) signed_headers = ";".join(header_keys) payload_hash = hashlib.sha256((request_payload or "").encode("utf-8")).hexdigest() # https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html canonical_request = "{}\n{}\n{}\n{}\n{}\n{}".format( method, canonical_uri, canonical_querystring, canonical_headers, signed_headers, payload_hash, ) credential_scope = "{}/{}/{}/{}".format( date_stamp, region, service_name, _AWS_REQUEST_TYPE ) # https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html string_to_sign = "{}\n{}\n{}\n{}".format( _AWS_ALGORITHM, amz_date, credential_scope, hashlib.sha256(canonical_request.encode("utf-8")).hexdigest(), ) # https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html signing_key = _get_signing_key(secret_key, date_stamp, region, service_name) signature = hmac.new( signing_key, string_to_sign.encode("utf-8"), hashlib.sha256 ).hexdigest() # https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html authorization_header = "{} Credential={}/{}, SignedHeaders={}, Signature={}".format( _AWS_ALGORITHM, access_key, credential_scope, signed_headers, signature ) authentication_header = {"authorization_header": authorization_header} # Do not use generated x-amz-date if the date header is provided. if "date" not in full_headers: authentication_header["amz_date"] = amz_date return authentication_header class Credentials(external_account.Credentials): """AWS external account credentials. This is used to exchange serialized AWS signature v4 signed requests to AWS STS GetCallerIdentity service for Google access tokens. """ def __init__( self, audience, subject_token_type, token_url, credential_source=None, service_account_impersonation_url=None, client_id=None, client_secret=None, quota_project_id=None, scopes=None, default_scopes=None, ): """Instantiates an AWS workload external account credentials object. Args: audience (str): The STS audience field. subject_token_type (str): The subject token type. token_url (str): The STS endpoint URL. credential_source (Mapping): The credential source dictionary used to provide instructions on how to retrieve external credential to be exchanged for Google access tokens. service_account_impersonation_url (Optional[str]): The optional service account impersonation getAccessToken URL. client_id (Optional[str]): The optional client ID. client_secret (Optional[str]): The optional client secret. quota_project_id (Optional[str]): The optional quota project ID. scopes (Optional[Sequence[str]]): Optional scopes to request during the authorization grant. default_scopes (Optional[Sequence[str]]): Default scopes passed by a Google client library. Use 'scopes' for user-defined scopes. Raises: google.auth.exceptions.RefreshError: If an error is encountered during access token retrieval logic. ValueError: For invalid parameters. .. note:: Typically one of the helper constructors :meth:`from_file` or :meth:`from_info` are used instead of calling the constructor directly. """ super(Credentials, self).__init__( audience=audience, subject_token_type=subject_token_type, token_url=token_url, credential_source=credential_source, service_account_impersonation_url=service_account_impersonation_url, client_id=client_id, client_secret=client_secret, quota_project_id=quota_project_id, scopes=scopes, default_scopes=default_scopes, ) credential_source = credential_source or {} self._environment_id = credential_source.get("environment_id") or "" self._region_url = credential_source.get("region_url") self._security_credentials_url = credential_source.get("url") self._cred_verification_url = credential_source.get( "regional_cred_verification_url" ) self._region = None self._request_signer = None self._target_resource = audience # Get the environment ID. Currently, only one version supported (v1). matches = re.match(r"^(aws)([\d]+)$", self._environment_id) if matches: env_id, env_version = matches.groups() else: env_id, env_version = (None, None) if env_id != "aws" or self._cred_verification_url is None: raise ValueError("No valid AWS 'credential_source' provided") elif int(env_version or "") != 1: raise ValueError( "aws version '{}' is not supported in the current build.".format( env_version ) ) def retrieve_subject_token(self, request): """Retrieves the subject token using the credential_source object. The subject token is a serialized `AWS GetCallerIdentity signed request`_. The logic is summarized as: Retrieve the AWS region from the AWS_REGION or AWS_DEFAULT_REGION environment variable or from the AWS metadata server availability-zone if not found in the environment variable. Check AWS credentials in environment variables. If not found, retrieve from the AWS metadata server security-credentials endpoint. When retrieving AWS credentials from the metadata server security-credentials endpoint, the AWS role needs to be determined by calling the security-credentials endpoint without any argument. Then the credentials can be retrieved via: security-credentials/role_name Generate the signed request to AWS STS GetCallerIdentity action. Inject x-goog-cloud-target-resource into header and serialize the signed request. This will be the subject-token to pass to GCP STS. .. _AWS GetCallerIdentity signed request: https://cloud.google.com/iam/docs/access-resources-aws#exchange-token Args: request (google.auth.transport.Request): A callable used to make HTTP requests. Returns: str: The retrieved subject token. """ # Initialize the request signer if not yet initialized after determining # the current AWS region. if self._request_signer is None: self._region = self._get_region(request, self._region_url) self._request_signer = RequestSigner(self._region) # Retrieve the AWS security credentials needed to generate the signed # request. aws_security_credentials = self._get_security_credentials(request) # Generate the signed request to AWS STS GetCallerIdentity API. # Use the required regional endpoint. Otherwise, the request will fail. request_options = self._request_signer.get_request_options( aws_security_credentials, self._cred_verification_url.replace("{region}", self._region), "POST", ) # The GCP STS endpoint expects the headers to be formatted as: # [ # {key: 'x-amz-date', value: '...'}, # {key: 'Authorization', value: '...'}, # ... # ] # And then serialized as: # quote(json.dumps({ # url: '...', # method: 'POST', # headers: [{key: 'x-amz-date', value: '...'}, ...] # })) request_headers = request_options.get("headers") # The full, canonical resource name of the workload identity pool # provider, with or without the HTTPS prefix. # Including this header as part of the signature is recommended to # ensure data integrity. request_headers["x-goog-cloud-target-resource"] = self._target_resource # Serialize AWS signed request. # Keeping inner keys in sorted order makes testing easier for Python # versions <=3.5 as the stringified JSON string would have a predictable # key order. aws_signed_req = {} aws_signed_req["url"] = request_options.get("url") aws_signed_req["method"] = request_options.get("method") aws_signed_req["headers"] = [] # Reformat header to GCP STS expected format. for key in sorted(request_headers.keys()): aws_signed_req["headers"].append( {"key": key, "value": request_headers[key]} ) return urllib.parse.quote( json.dumps(aws_signed_req, separators=(",", ":"), sort_keys=True) ) def _get_region(self, request, url): """Retrieves the current AWS region from either the AWS_REGION or AWS_DEFAULT_REGION environment variable or from the AWS metadata server. Args: request (google.auth.transport.Request): A callable used to make HTTP requests. url (str): The AWS metadata server region URL. Returns: str: The current AWS region. Raises: google.auth.exceptions.RefreshError: If an error occurs while retrieving the AWS region. """ # The AWS metadata server is not available in some AWS environments # such as AWS lambda. Instead, it is available via environment # variable. env_aws_region = os.environ.get(environment_vars.AWS_REGION) if env_aws_region is not None: return env_aws_region env_aws_region = os.environ.get(environment_vars.AWS_DEFAULT_REGION) if env_aws_region is not None: return env_aws_region if not self._region_url: raise exceptions.RefreshError("Unable to determine AWS region") response = request(url=self._region_url, method="GET") # Support both string and bytes type response.data. response_body = ( response.data.decode("utf-8") if hasattr(response.data, "decode") else response.data ) if response.status != 200: raise exceptions.RefreshError( "Unable to retrieve AWS region", response_body ) # This endpoint will return the region in format: us-east-2b. # Only the us-east-2 part should be used. return response_body[:-1] def _get_security_credentials(self, request): """Retrieves the AWS security credentials required for signing AWS requests from either the AWS security credentials environment variables or from the AWS metadata server. Args: request (google.auth.transport.Request): A callable used to make HTTP requests. Returns: Mapping[str, str]: The AWS security credentials dictionary object. Raises: google.auth.exceptions.RefreshError: If an error occurs while retrieving the AWS security credentials. """ # Check environment variables for permanent credentials first. # https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html env_aws_access_key_id = os.environ.get(environment_vars.AWS_ACCESS_KEY_ID) env_aws_secret_access_key = os.environ.get( environment_vars.AWS_SECRET_ACCESS_KEY ) # This is normally not available for permanent credentials. env_aws_session_token = os.environ.get(environment_vars.AWS_SESSION_TOKEN) if env_aws_access_key_id and env_aws_secret_access_key: return { "access_key_id": env_aws_access_key_id, "secret_access_key": env_aws_secret_access_key, "security_token": env_aws_session_token, } # Get role name. role_name = self._get_metadata_role_name(request) # Get security credentials. credentials = self._get_metadata_security_credentials(request, role_name) return { "access_key_id": credentials.get("AccessKeyId"), "secret_access_key": credentials.get("SecretAccessKey"), "security_token": credentials.get("Token"), } def _get_metadata_security_credentials(self, request, role_name): """Retrieves the AWS security credentials required for signing AWS requests from the AWS metadata server. Args: request (google.auth.transport.Request): A callable used to make HTTP requests. role_name (str): The AWS role name required by the AWS metadata server security_credentials endpoint in order to return the credentials. Returns: Mapping[str, str]: The AWS metadata server security credentials response. Raises: google.auth.exceptions.RefreshError: If an error occurs while retrieving the AWS security credentials. """ headers = {"Content-Type": "application/json"} response = request( url="{}/{}".format(self._security_credentials_url, role_name), method="GET", headers=headers, ) # support both string and bytes type response.data response_body = ( response.data.decode("utf-8") if hasattr(response.data, "decode") else response.data ) if response.status != http_client.OK: raise exceptions.RefreshError( "Unable to retrieve AWS security credentials", response_body ) credentials_response = json.loads(response_body) return credentials_response def _get_metadata_role_name(self, request): """Retrieves the AWS role currently attached to the current AWS workload by querying the AWS metadata server. This is needed for the AWS metadata server security credentials endpoint in order to retrieve the AWS security credentials needed to sign requests to AWS APIs. Args: request (google.auth.transport.Request): A callable used to make HTTP requests. Returns: str: The AWS role name. Raises: google.auth.exceptions.RefreshError: If an error occurs while retrieving the AWS role name. """ if self._security_credentials_url is None: raise exceptions.RefreshError( "Unable to determine the AWS metadata server security credentials endpoint" ) response = request(url=self._security_credentials_url, method="GET") # support both string and bytes type response.data response_body = ( response.data.decode("utf-8") if hasattr(response.data, "decode") else response.data ) if response.status != http_client.OK: raise exceptions.RefreshError( "Unable to retrieve AWS role name", response_body ) return response_body @classmethod def from_info(cls, info, **kwargs): """Creates an AWS Credentials instance from parsed external account info. Args: info (Mapping[str, str]): The AWS external account info in Google format. kwargs: Additional arguments to pass to the constructor. Returns: google.auth.aws.Credentials: The constructed credentials. Raises: ValueError: For invalid parameters. """ return cls( audience=info.get("audience"), subject_token_type=info.get("subject_token_type"), token_url=info.get("token_url"), service_account_impersonation_url=info.get( "service_account_impersonation_url" ), client_id=info.get("client_id"), client_secret=info.get("client_secret"), credential_source=info.get("credential_source"), quota_project_id=info.get("quota_project_id"), **kwargs ) @classmethod def from_file(cls, filename, **kwargs): """Creates an AWS Credentials instance from an external account json file. Args: filename (str): The path to the AWS external account json file. kwargs: Additional arguments to pass to the constructor. Returns: google.auth.aws.Credentials: The constructed credentials. """ with io.open(filename, "r", encoding="utf-8") as json_file: data = json.load(json_file) return cls.from_info(data, **kwargs)
""" MP4 Parser based on: http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf @author: Alastair McCormack @license: MIT License """ import bitstring from datetime import datetime from collections import namedtuple import logging import six log = logging.getLogger(__name__) #log.addHandler(logging.NullHandler()) log.setLevel(logging.WARN) class MixinDictRepr(object): def __repr__(self, *args, **kwargs): return "{class_name} : {content!r} ".format(class_name=self.__class__.__name__, content=self.__dict__) class MixinMinimalRepr(object): """ A minimal representaion when the payload could be large """ def __repr__(self, *args, **kwargs): return "{class_name} : {content!r} ".format(class_name=self.__class__.__name__, content=self.__dict__.keys()) class FragmentRunTableBox(MixinDictRepr): pass class UnImplementedBox(MixinDictRepr): type = "na" pass class MovieFragmentBox(MixinDictRepr): type = "moof" class BootStrapInfoBox(MixinDictRepr): type = "abst" @property def current_media_time(self): return self._current_media_time @current_media_time.setter def current_media_time(self, epoch_timestamp): """ Takes a timestamp arg and saves it as datetime """ self._current_media_time = datetime.utcfromtimestamp(epoch_timestamp/float(self.time_scale)) class FragmentRandomAccessBox(MixinDictRepr): """ aka afra """ type = "afra" FragmentRandomAccessBoxEntry = namedtuple("FragmentRandomAccessBoxEntry", ["time", "offset"]) FragmentRandomAccessBoxGlobalEntry = namedtuple("FragmentRandomAccessBoxGlobalEntry", ["time", "segment_number", "fragment_number", "afra_offset", "sample_offset"]) pass class SegmentRunTable(MixinDictRepr): type = "asrt" SegmentRunTableEntry = namedtuple('SegmentRunTableEntry', ["first_segment", "fragments_per_segment"]) pass class FragmentRunTable(MixinDictRepr): type = "afrt" class FragmentRunTableEntry( namedtuple('FragmentRunTableEntry', ["first_fragment", "first_fragment_timestamp", "fragment_duration", "discontinuity_indicator"]) ): DI_END_OF_PRESENTATION = 0 DI_NUMBERING = 1 DI_TIMESTAMP = 2 DI_TIMESTAMP_AND_NUMBER = 3 def __eq__(self, other): if self.first_fragment == other.first_fragment and \ self.first_fragment_timestamp == other.first_fragment_timestamp and \ self.fragment_duration == other.fragment_duration and \ self.discontinuity_indicator == other.discontinuity_indicator: return True def __repr__(self, *args, **kwargs): return str(self.__dict__) class MediaDataBox(MixinMinimalRepr): """ aka mdat """ type = "mdat" class MovieFragmentHeader(MixinDictRepr): type = "mfhd" class ProtectionSystemSpecificHeader(MixinDictRepr): type = "pssh" BoxHeader = namedtuple( "BoxHeader", ["box_size", "box_type", "header_size"] ) class F4VParser(object): @classmethod def parse(cls, filename=None, bytes_input=None, file_input=None, offset_bytes=0, headers_only=False): """ Parse an MP4 file or bytes into boxes :param filename: filename of mp4 file. :type filename: str. :param bytes_input: bytes of mp4 file. :type bytes_input: bytes / Python 2.x str. :param offset_bytes: start parsing at offset. :type offset_bytes: int. :param headers_only: Ignore data and return just headers. Useful when data is cut short :type: headers_only: boolean :return: BMFF Boxes or Headers """ box_lookup = { BootStrapInfoBox.type: cls._parse_abst, FragmentRandomAccessBox.type: cls._parse_afra, MediaDataBox.type: cls._parse_mdat, MovieFragmentBox.type: cls._parse_moof, MovieFragmentHeader.type: cls._parse_mfhd, ProtectionSystemSpecificHeader.type: cls._parse_pssh } if filename: bs = bitstring.ConstBitStream(filename=filename, offset=offset_bytes * 8) elif bytes_input: bs = bitstring.ConstBitStream(bytes=bytes_input, offset=offset_bytes * 8) else: bs = bitstring.ConstBitStream(auto=file_input, offset=offset_bytes * 8) log.debug("Starting parse") log.debug("Size is %d bits", bs.len) while bs.pos < bs.len: log.debug("Byte pos before header: %d relative to (%d)", bs.bytepos, offset_bytes) log.debug("Reading header") try: header = cls._read_box_header(bs) except bitstring.ReadError as e: log.error("Premature end of data while reading box header") raise log.debug("Header type: %s", header.box_type) log.debug("Byte pos after header: %d relative to (%d)", bs.bytepos, offset_bytes) if headers_only: yield header # move pointer to next header if possible try: bs.bytepos += header.box_size except ValueError: log.warning("Premature end of data") raise else: # Get parser method for header type parse_function = box_lookup.get(header.box_type, cls._parse_unimplemented) try: yield parse_function(bs, header) except ValueError as e: log.error("Premature end of data") raise @classmethod def _is_mp4(cls, parser): try: for box in parser: return True except ValueError: return False @classmethod def is_mp4_s(cls, bytes_input): """ Is bytes_input the contents of an MP4 file :param bytes_input: str/bytes to check. :type bytes_input: str/bytes. :return: """ parser = cls.parse(bytes_input=bytes_input, headers_only=True) return cls._is_mp4(parser) @classmethod def is_mp4(cls, file_input): """ Checks input if it's an MP4 file :param input: Filename or file object :type input: str, file :param state: Current state to be in. :type state: bool. :returns: bool. :raises: AttributeError, KeyError """ if hasattr(file_input, "read"): parser = cls.parse(file_input=file_input, headers_only=True) else: parser = cls.parse(filename=file_input, headers_only=True) return cls._is_mp4(parser) @staticmethod def _read_string(bs): """ read UTF8 null terminated string """ result = bs.readto('0x00', bytealigned=True).bytes.decode("utf-8")[:-1] return result if result else None @classmethod def _read_count_and_string_table(cls, bs): """ Read a count then return the strings in a list """ result = [] entry_count = bs.read("uint:8") for _ in six.range(0, entry_count): result.append( cls._read_string(bs) ) return result @staticmethod def _read_box_header(bs): header_start_pos = bs.bytepos size, box_type = bs.readlist("uint:32, bytes:4") # box_type should be an ASCII string. Decode as UTF-8 in case try: box_type = box_type.decode('utf-8') except UnicodeDecodeError: # we'll leave as bytes instead pass # if size == 1, then this is an extended size type. # Therefore read the next 64 bits as size if size == 1: size = bs.read("uint:64") header_end_pos = bs.bytepos header_size = header_end_pos - header_start_pos return BoxHeader(box_size=size-header_size, box_type=box_type, header_size=header_size) @staticmethod def _parse_unimplemented(bs, header): ui = UnImplementedBox() ui.header = header bs.bytepos += header.box_size return ui @classmethod def _parse_afra(cls, bs, header): afra = FragmentRandomAccessBox() afra.header = header # read the entire box in case there's padding afra_bs = bs.read(header.box_size * 8) # skip Version and Flags afra_bs.pos += 8 + 24 long_ids, long_offsets, global_entries, afra.time_scale, local_entry_count = \ afra_bs.readlist("bool, bool, bool, pad:5, uint:32, uint:32") if long_ids: id_bs_type = "uint:32" else: id_bs_type = "uint:16" if long_offsets: offset_bs_type = "uint:64" else: offset_bs_type = "uint:32" log.debug("local_access_entries entry count: %s", local_entry_count) afra.local_access_entries = [] for _ in six.range(0, local_entry_count): time = cls._parse_time_field(afra_bs, afra.time_scale) offset = afra_bs.read(offset_bs_type) afra_entry = \ FragmentRandomAccessBox.FragmentRandomAccessBoxEntry(time=time, offset=offset) afra.local_access_entries.append(afra_entry) afra.global_access_entries = [] if global_entries: global_entry_count = afra_bs.read("uint:32") log.debug("global_access_entries entry count: %s", global_entry_count) for _ in six.range(0, global_entry_count): time = cls._parse_time_field(afra_bs, afra.time_scale) segment_number = afra_bs.read(id_bs_type) fragment_number = afra_bs.read(id_bs_type) afra_offset = afra_bs.read(offset_bs_type) sample_offset = afra_bs.read(offset_bs_type) afra_global_entry = \ FragmentRandomAccessBox.FragmentRandomAccessBoxGlobalEntry( time=time, segment_number=segment_number, fragment_number=fragment_number, afra_offset=afra_offset, sample_offset=sample_offset) afra.global_access_entries.append(afra_global_entry) return afra @classmethod def _parse_moof(cls, bootstrap_bs, header): moof = MovieFragmentBox() moof.header = header box_bs = bootstrap_bs.read(moof.header.box_size * 8) for child_box in cls.parse(bytes_input=box_bs.bytes): setattr(moof, child_box.type, child_box) return moof @classmethod def _parse_mfhd(cls, bootstrap_bs, header): mfhd = MovieFragmentHeader() mfhd.header = header box_bs = bootstrap_bs.read(mfhd.header.box_size * 8) return mfhd @staticmethod def _parse_pssh(bootstrap_bs, header): pssh = ProtectionSystemSpecificHeader() pssh.header = header box_bs = bootstrap_bs.read(pssh.header.box_size * 8) # Payload appears to be 8 bytes in. pssh.payload = box_bs.bytes[8:] return pssh @classmethod def _parse_abst(cls, bootstrap_bs, header): abst = BootStrapInfoBox() abst.header = header box_bs = bootstrap_bs.read(abst.header.box_size * 8) abst.version, abst.profile_raw, abst.live, abst.update, \ abst.time_scale, abst.current_media_time, abst.smpte_timecode_offset = \ box_bs.readlist("""pad:8, pad:24, uint:32, uint:2, bool, bool, pad:4, uint:32, uint:64, uint:64""") abst.movie_identifier = cls._read_string(box_bs) abst.server_entry_table = cls._read_count_and_string_table(box_bs) abst.quality_entry_table = cls._read_count_and_string_table(box_bs) abst.drm_data = cls._read_string(box_bs) abst.meta_data = cls._read_string(box_bs) abst.segment_run_tables = [] segment_count = box_bs.read("uint:8") log.debug("segment_count: %d" % segment_count) for _ in six.range(0, segment_count): abst.segment_run_tables.append( cls._parse_asrt(box_bs) ) abst.fragment_tables = [] fragment_count = box_bs.read("uint:8") log.debug("fragment_count: %d" % fragment_count) for _ in xrange(0, fragment_count): abst.fragment_tables.append( cls._parse_afrt(box_bs) ) log.debug("Finished parsing abst") return abst @classmethod def _parse_asrt(cls, box_bs): """ Parse asrt / Segment Run Table Box """ asrt = SegmentRunTable() asrt.header = cls._read_box_header(box_bs) # read the entire box in case there's padding asrt_bs_box = box_bs.read(asrt.header.box_size * 8) asrt_bs_box.pos += 8 update_flag = asrt_bs_box.read("uint:24") asrt.update = True if update_flag == 1 else False asrt.quality_segment_url_modifiers = cls._read_count_and_string_table(asrt_bs_box) asrt.segment_run_table_entries = [] segment_count = asrt_bs_box.read("uint:32") for _ in six.range(0, segment_count): first_segment = asrt_bs_box.read("uint:32") fragments_per_segment = asrt_bs_box.read("uint:32") asrt.segment_run_table_entries.append( SegmentRunTable.SegmentRunTableEntry(first_segment=first_segment, fragments_per_segment=fragments_per_segment) ) return asrt @classmethod def _parse_afrt(cls, box_bs): """ Parse afrt / Fragment Run Table Box """ afrt = FragmentRunTable() afrt.header = cls._read_box_header(box_bs) # read the entire box in case there's padding afrt_bs_box = box_bs.read(afrt.header.box_size * 8) afrt_bs_box.pos += 8 update_flag = afrt_bs_box.read("uint:24") afrt.update = True if update_flag == 1 else False afrt.time_scale = afrt_bs_box.read("uint:32") afrt.quality_fragment_url_modifiers = cls._read_count_and_string_table(afrt_bs_box) fragment_count = afrt_bs_box.read("uint:32") afrt.fragments = [] for _ in six.range(0, fragment_count): first_fragment = afrt_bs_box.read("uint:32") first_fragment_timestamp_raw = afrt_bs_box.read("uint:64") try: first_fragment_timestamp = datetime.utcfromtimestamp(first_fragment_timestamp_raw/float(afrt.time_scale)) except ValueError: # Elemental sometimes create odd timestamps first_fragment_timestamp = None fragment_duration = afrt_bs_box.read("uint:32") if fragment_duration == 0: discontinuity_indicator = afrt_bs_box.read("uint:8") else: discontinuity_indicator = None frte = FragmentRunTable.FragmentRunTableEntry(first_fragment=first_fragment, first_fragment_timestamp=first_fragment_timestamp, fragment_duration=fragment_duration, discontinuity_indicator=discontinuity_indicator) afrt.fragments.append(frte) return afrt @staticmethod def _parse_mdat(box_bs, header): """ Parse afrt / Fragment Run Table Box """ mdat = MediaDataBox() mdat.header = header mdat.payload = box_bs.read(mdat.header.box_size * 8).bytes return mdat @staticmethod def _parse_time_field(bs, scale): timestamp = bs.read("uint:64") return datetime.utcfromtimestamp(timestamp / float(scale) )
# This file is part of the bapsflib package, a Python toolkit for the # BaPSF group at UCLA. # # http://plasma.physics.ucla.edu/ # # Copyright 2017-2018 Erik T. Everson and contributors # # License: Standard 3-clause BSD; see "LICENSES/LICENSE.txt" for full # license terms and contributor agreement. # """ Module containing the main `~bapsflib._hdf.utils.hdfreadcontrols.HDFReadControls` class. """ __all__ = ["HDFReadControls"] import copy import h5py import numpy as np import os import time from functools import reduce from typing import Any, Dict, Iterable, List, Tuple, Union from warnings import warn from bapsflib._hdf.maps.controls.templates import ( HDFMapControlCLTemplate, HDFMapControlTemplate, ) from .file import File from .helpers import ( build_shotnum_dset_relation, condition_controls, condition_shotnum, do_shotnum_intersection, ) # define type aliases ControlMap = Union[HDFMapControlTemplate, HDFMapControlCLTemplate] ControlsType = Union[str, Iterable[Union[str, Tuple[str, Any]]]] IndexDict = Dict[str, np.ndarray] class HDFReadControls(np.ndarray): """ Reads control device data from the HDF5 file. This class constructs and returns a structured numpy array. The data in the array is grouped into two categories: #. shot numbers which are contained in the :code:`'shotnum'` field #. control device data which is represented by the remaining fields in the numpy array. These field names are polymorphic and are defined by the control device mapping class. Data that is not shot number specific is stored in the :attr:`info` attribute. .. note:: * It is assumed that control data is always extracted with the intent of being matched to digitizer data. * Only one control for each :class:`~bapsflib._hdf.maps.controls.types.ConType` can be specified at a time. * It is assumed that there is only ONE dataset associated with each control device configuration. * If multiple device configurations are saved in the same HDF5 dataset (common in the :ibf:`'Waveform'` control device), then it is assumed that the configuration writing order is consistent for all recorded shot numbers. That is, if *'config1'*, *'config2'*, and *'config3'* are recorded in that order for shot number 1, then that order is preserved for all recorded shot numbers. """ __example_doc__ = """ :Example: Here the control device :code:`'Waveform'` is used as a basic example: >>> # open HDF5 file >>> f = bapsflib.lapd.File('test.hdf5') >>> >>> # read control data >>> # - this is equivalent to >>> # f.read_control(['Waveform', 'config01']) >>> data = HDFReadControls(f, ['Waveform', 'config01']) >>> data.dtype dtype([('shotnum', '<u4'), ('command', '<U18')]) >>> >>> # display shot numbers >>> data['shotnum'] array([ 1, 2, 3, ..., 6158, 6159, 6160], dtype=uint32) >>> >>> # show 'command' values for shot numbers 1 to 2 >>> data['command'][0:2:] array(['FREQ 50000.000000', 'FREQ 50000.000000'], dtype='<U18') """ def __new__( cls, hdf_file: File, controls: ControlsType, shotnum=slice(None), intersection_set=True, **kwargs, ): """ :param hdf_file: HDF5 file object :param controls: a list indicating the desired control device names and their configuration name (if more than one configuration exists) :type controls: Union[str, Iterable[str, Tuple[str, Any]]] :param shotnum: HDF5 file shot number(s) indicating data entries to be extracted :type shotnum: Union[int, List[int], slice, numpy.ndarray] :param bool intersection_set: :code:`True` (DEFAULT) will force the returned shot numbers to be the intersection of :data:`shotnum` and the shot numbers contained in each control device dataset. :code:`False` will return the union instead of the intersection Behavior of :data:`shotnum` and :data:`intersection_set`: * :data:`shotnum` indexing starts at 1 * Any :data:`shotnum` values :code:`<= 0` will be thrown out * If :code:`intersection_set=True`, then only data corresponding to shot numbers that are specified in :data:`shotnum` and are in all control datasets will be returned * If :code:`intersection_set=False`, then the returned array will have entries for all shot numbers specified in :data:`shotnum` but entries that correspond to control datasets that do not have the specified shot number will be given a NULL value of :code:`-99999`, :code:`0`, :code:`numpy.nan`, or :code:`''`, depending on the :code:`numpy.dtype`. """ # initialize timing tt = [] if "timeit" in kwargs: # pragma: no cover timeit = kwargs["timeit"] if timeit: tt.append(time.time()) else: timeit = False else: timeit = False # ---- Condition `hdf_file` ---- # - `hdf_file` is a lapd.File object # if not isinstance(hdf_file, File): raise TypeError( f"`hdf_file` is NOT type `{File.__module__}.{File.__qualname__}`" ) # print execution timing if timeit: # pragma: no cover tt.append(time.time()) print(f"tt - hdf_file conditioning: {(tt[-1] - tt[-2]) * 1.0e3} ms") # ---- Examine file map object ---- # grab instance of _fmap _fmap = hdf_file.file_map # Check for non-empty controls if not bool(_fmap.controls): raise ValueError("There are no control devices in the HDF5 file.") # ---- Condition 'controls' Argument ---- # - some calling routines (such as, lapd.File.read_data) # already properly condition 'controls', so passing a keyword # 'assume_controls_conditioned' allows for a bypass of # conditioning here # try: # check if `controls` was already conditioned if not kwargs["assume_controls_conditioned"]: controls = condition_controls(hdf_file, controls) except KeyError: controls = condition_controls(hdf_file, controls) # print execution timing if timeit: # pragma: no cover tt.append(time.time()) print(f"tt - condition controls: {(tt[-1] - tt[-2]) * 1.0e3} ms") # ---- Condition shotnum ---- # shotnum -- global HDF5 file shot number # ~ this is the parameter used to link values between # datasets # # Through conditioning the following are (re-)defined: # index -- row index of the control dataset(s) # ~ numpy.ndarray # ~ dtype = np.integer # ~ shape = (len(controls), num_of_indices) # # shotnum -- global HDF5 shot numbers # ~ index at 1 # ~ will be a filtered version of input kwarg shotnum # based on intersection_set # ~ numpy.ndarray # ~ dtype = np.uint32 # ~ shape = (sn_size, ) # # sni -- bool array for providing a one-to-one mapping # between shotnum and index # ~ shotnum[sni] = cdset[index, shotnumkey] # ~ numpy.ndarray # ~ dtype = np.bool # ~ shape = (len(controls), sn_size) # ~ np.count_nonzero(arr[0,...]) = num_of_indices # # - Indexing behavior: (depends on intersection_set) # # ~ shotnum # * intersection_set = True # > the returned array will only contain shot numbers that # are in the intersection of shotnum and all the # specified control device datasets # # * intersection_set = False # > the returned array will contain all shot numbers # specified by shotnum (>= 1) # > if a dataset does not included a shot number contained # in shotnum, then its entry in the returned array will # be given a NULL value depending on the dtype # # Gather control datasets and associated shot number field names # - things needed to perform the conditioning cdset_dict = {} # type: Dict[str, h5py.Dataset] shotnumkey_dict = {} # type: Dict[str, str] for control in controls: # control name (cname) and configuration name (cconfn) cname = control[0] cconfn = control[1] # gather control datasets and shotnumkey's cmap = _fmap.controls[cname] cdset_path = cmap.configs[cconfn]["dset paths"][0] cdset_dict[cname] = hdf_file.get(cdset_path) shotnumkey = cmap.configs[cconfn]["shotnum"]["dset field"][0] shotnumkey_dict[cname] = shotnumkey # perform `shotnum` conditioning # - `shotnum` is returned as a numpy array shotnum = condition_shotnum(shotnum, cdset_dict, shotnumkey_dict) # ---- Build `index` and `sni` arrays for each dataset ---- # # - Satisfies the condition: # # shotnum[sni] = dset[index, shotnumkey] # # Notes: # 1. every entry in `index_dict` and `sni_dict` will be a numpy # array # 2. all entries in `index_dict` and `sni_dict` are build with # respect to shotnum # index_dict = {} # type: IndexDict sni_dict = {} # type: IndexDict for control in controls: # control name (cname) and configuration name (cconfn) cname = control[0] cconfn = control[1] cmap = _fmap.controls[cname] # build `index` and `sni` for each dataset index_dict[cname], sni_dict[cname] = build_shotnum_dset_relation( shotnum, cdset_dict[cname], shotnumkey_dict[cname], cmap, cconfn ) # re-filter `index`, `shotnum`, and `sni` if intersection_set # requested if intersection_set: shotnum, sni_dict, index_dict = do_shotnum_intersection( shotnum, sni_dict, index_dict ) # print execution timing if timeit: # pragma: no cover tt.append(time.time()) print(f"tt - condition shotnum: {(tt[-1] - tt[-2]) * 1.0e3} ms") # ---- Build obj ---- # Define dtype and shape for numpy array shape = shotnum.shape dtype = [("shotnum", np.uint32, 1)] for control in controls: # control name (cname) and configuration name (cconfn) cname = control[0] cconfn = control[1] # add fields cconfig = _fmap.controls[cname].configs[cconfn] for field_name, fconfig in cconfig["state values"].items(): dtype.append( ( field_name, fconfig["dtype"], fconfig["shape"], ) ) # print execution timing if timeit: # pragma: no cover tt.append(time.time()) print(f"tt - define dtype: {(tt[-1] - tt[-2]) * 1.0e3} ms") # Initialize Control Data data = np.empty(shape, dtype=dtype) data["shotnum"] = shotnum # print execution timing if timeit: # pragma: no cover tt.append(time.time()) print(f"tt - initialize data np.ndarray: {(tt[-1] - tt[-2]) * 1.0e3} ms") # Assign Control Data to Numpy array for control in controls: # control name (cname) and configuration name (cconfn) cname = control[0] cconfn = control[1] # get control dataset cmap = _fmap.controls[cname] cconfig = cmap.configs[cconfn] cdset = cdset_dict[cname] sni = sni_dict[cname] index = index_dict[cname].tolist() # type: List # populate control data array # 1. scan over numpy fields # 2. scan over the dset fields that will fill the numpy # fields # 3. split between a command list fill or a direct fill # 4. NaN fill if intersection_set = False # for nf_name, fconfig in cconfig["state values"].items(): # nf_name = the numpy field name # fconfig = the mapping dictionary for nf_name # for npi, df_name in enumerate(fconfig["dset field"]): # df_name # the dset field name that will fill the numpy # field # npi # the index of the numpy array corresponding to # nf_name that df_name will fill # # assign data if cmap.has_command_list: # command list fill # get command list cl = fconfig["command list"] # retrieve the array of command indices ci_arr = cdset[index, df_name] # assign command values to data for ci, command in enumerate(cl): # Order of operations # 1. find where command index (ci) is in the # command index array (ci_arr) # 2. construct a new sni for ci # 3. fill data # # find where ci is in ci_arr ii = np.where(ci_arr == ci, True, False) # construct new sni sni_for_ci = np.zeros(sni.shape, dtype=bool) sni_for_ci[np.where(sni)[0][ii]] = True # assign values data[nf_name][sni_for_ci] = command else: # direct fill (NO command list) try: arr = cdset[index, df_name] except ValueError as err: mlist = [1] + list(data.dtype[nf_name].shape) size = reduce(lambda x, y: x * y, mlist) dtype = data.dtype[nf_name].base if df_name == "": # a mapping module gives an empty string # '' when the dataset does not have a # necessary field but you want the read # out to still function # - e.g. 'xyz' but the dataset only # contains values fo 'x' and 'z' # (the NI_XZ module) # # create zero array arr = np.zeros((len(index),), dtype=dtype) elif size > 1: # expected field df_name is missing but # belongs to an array warn( f"Dataset missing field '{df_name}', applying " f"NaN fill to to data array" ) arr = np.zeros((len(index),), dtype=dtype) # NaN fill if np.issubdtype(dtype, np.signedinteger): # any signed-integer # unsigned has a 0 fill arr[:] = -99999 elif np.issubdtype(dtype, np.floating): # any float type arr[:] = np.nan elif np.issubdtype(dtype, np.flexible): # string, unicode, void # np.zero satisfies this pass else: # pragma: no cover # no real NaN concept exists # - this shouldn't happen though warn( f"dtype ({dtype}) of {nf_name} has no NaN " f"concept...no NaN fill done" ) else: # expected field df_name is missing raise err if data.dtype[nf_name].shape != (): # field contains an array (e.g. 'xyz') # data[nf_name][sni, npi] = \ # cdset[index, df_name] data[nf_name][sni, npi] = arr else: # field is a constant # data[nf_name][sni] = \ # cdset[index, df_name] data[nf_name][sni] = arr # handle NaN fill if not intersection_set: # overhead sni_not = np.logical_not(sni) dtype = data.dtype[nf_name].base # if data.dtype[nf_name].shape != (): ii = np.s_[sni_not, npi] else: ii = np.s_[sni_not] # NaN fill if np.issubdtype(dtype, np.signedinteger): data[nf_name][ii] = -99999 elif np.issubdtype(dtype, np.unsignedinteger): data[nf_name][ii] = 0 elif np.issubdtype(dtype, np.floating): # any float type data[nf_name][ii] = np.nan elif np.issubdtype(dtype, np.flexible): # string, unicode, void data[nf_name][ii] = "" else: # no real NaN concept exists # - this shouldn't happen though warn( f"dtype ({dtype}) of {nf_name} has no NaN concept" f"...no NaN fill done" ) # print execution timing if timeit: # pragma: no cover tt.append(time.time()) print(f"tt - fill data - {cname}: {(tt[-1] - tt[-2]) * 1.0e3} ms") # print execution timing if timeit: # pragma: no cover n_controls = len(controls) tt.append(time.time()) print( f"tt - fill data array: {(tt[-1] - tt[-n_controls - 2]) * 1.0e3} ms " f"(intersection_set={intersection_set})" ) # -- Define `obj` ---- obj = data.view(cls) # -- Populate `_info` ---- # initialize `_info` obj._info = { "source file": os.path.abspath(hdf_file.filename), "controls": {}, "probe name": None, "port": (None, None), } # add control meta-info for control in controls: # control name (cname) and configuration name (cconfn) cname = control[0] cconfn = control[1] # get control dataset cmap = _fmap.controls[cname] cconfig = cmap.configs[cconfn] # type: dict # populate obj._info["controls"][cname] = { "device group path": cmap.info["group path"], "device dataset path": cconfig["dset paths"][0], "contype": cmap.contype, "configuration name": cconfn, } for key, val in cconfig.items(): if key not in ["dset paths", "shotnum", "state values"]: obj._info["controls"][cname][key] = copy.deepcopy(val) # print execution timing if timeit: # pragma: no cover tt.append(time.time()) print(f"tt - total execution time: {(tt[-1] - tt[0]) * 1.0e3} ms") # return obj return obj def __array_finalize__(self, obj): # This should only be True during explicit construction # if obj is None: if obj is None or obj.__class__ is np.ndarray: return # Define info attribute # (for view casting and new from template) self._info = getattr( obj, "_info", { "source file": None, "controls": None, "probe name": None, "port": (None, None), }, ) @property def info(self) -> dict: """A dictionary of meta-info for the control device.""" return self._info # add example to __new__ docstring HDFReadControls.__new__.__doc__ += "\n" for line in HDFReadControls.__example_doc__.splitlines(): HDFReadControls.__new__.__doc__ += f" {line}\n"
# Copyright (C) 2015-2021 Regents of the University of California # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implements a real-time UDP-based logging system that user scripts can use for debugging.""" import json import logging import logging.handlers import os import os.path import socketserver as SocketServer import threading from toil.batchSystems.options import getPublicIP from toil.statsAndLogging import set_log_level logger = logging.getLogger(__name__) class LoggingDatagramHandler(SocketServer.BaseRequestHandler): """ Receive logging messages from the jobs and display them on the leader. Uses bare JSON message encoding. """ def handle(self): """ Handle a single message. SocketServer takes care of splitting out the messages. Messages are JSON-encoded logging module records. """ # Unpack the data from the request data, socket = self.request try: # Parse it as JSON message_attrs = json.loads(data.decode('utf-8')) # Fluff it up into a proper logging record record = logging.makeLogRecord(message_attrs) if isinstance(record.args, list): # Going through JSON turned tuples into lists. Lazy formatting # means this might have happened to all the arguments. We need # to fix this at least for the root list of format string # arguments, or formatting will fail # # TODO: Protect the arguments better by actually pickling # instead of using JSON? # # TODO: Format the message on the sending side? record.args = tuple(record.args) except: # Complain someone is sending us bad logging data logging.error("Malformed log message from {}".format(self.client_address[0])) else: # Log level filtering should have been done on the remote end. The handle() method # skips it on this end. logger.handle(record) class JSONDatagramHandler(logging.handlers.DatagramHandler): """ Send logging records over UDP serialized as JSON. They have to fit in a single UDP datagram, so don't try to log more than 64kb at once. """ def makePickle(self, record): """ Actually, encode the record as bare JSON instead. """ return json.dumps(record.__dict__).encode('utf-8') class RealtimeLoggerMetaclass(type): """ Metaclass for RealtimeLogger that lets you do things like RealtimeLogger.warning(), RealtimeLogger.info(), etc. """ def __getattr__(self, name): """ If a real attribute can't be found, try one of the logging methods on the actual logger object. """ return getattr(self.getLogger(), name) class RealtimeLogger(metaclass=RealtimeLoggerMetaclass): """ Provides a logger that logs over UDP to the leader. To use in a Toil job, do: >>> from toil.realtimeLogger import RealtimeLogger >>> RealtimeLogger.info("This logging message goes straight to the leader") That's all a user of Toil would need to do. On the leader, Job.Runner.startToil() automatically starts the UDP server by using an instance of this class as a context manager. """ # The names of all environment variables used by this class are prefixed with this string envPrefix = "TOIL_RT_LOGGING_" # Avoid duplicating the default level everywhere defaultLevel = 'INFO' # State maintained on server and client lock = threading.RLock() # Server-side state # The leader keeps a server and thread loggingServer = None serverThread = None initialized = 0 # Client-side state logger = None @classmethod def _startLeader(cls, batchSystem, level=defaultLevel): with cls.lock: if cls.initialized == 0: cls.initialized += 1 if level: logger.info('Starting real-time logging.') # Start up the logging server cls.loggingServer = SocketServer.ThreadingUDPServer( server_address=('0.0.0.0', 0), RequestHandlerClass=LoggingDatagramHandler) # Set up a thread to do all the serving in the background and exit when we do cls.serverThread = threading.Thread(target=cls.loggingServer.serve_forever) cls.serverThread.daemon = True cls.serverThread.start() # Set options for logging in the environment so they get sent out to jobs ip = getPublicIP() port = cls.loggingServer.server_address[1] def _setEnv(name, value): name = cls.envPrefix + name os.environ[name] = value batchSystem.setEnv(name) _setEnv('ADDRESS', '%s:%i' % (ip, port)) _setEnv('LEVEL', level) else: logger.debug('Real-time logging disabled') else: if level: logger.warning('Ignoring nested request to start real-time logging') @classmethod def _stopLeader(cls): """ Stop the server on the leader. """ with cls.lock: assert cls.initialized > 0 cls.initialized -= 1 if cls.initialized == 0: if cls.loggingServer: logger.info('Stopping real-time logging server.') cls.loggingServer.shutdown() cls.loggingServer = None if cls.serverThread: logger.info('Joining real-time logging server thread.') cls.serverThread.join() cls.serverThread = None for k in list(os.environ.keys()): if k.startswith(cls.envPrefix): os.environ.pop(k) @classmethod def getLogger(cls): """ Get the logger that logs real-time to the leader. Note that if the returned logger is used on the leader, you will see the message twice, since it still goes to the normal log handlers, too. """ # Only do the setup once, so we don't add a handler every time we log. Use a lock to do # so safely even if we're being called in different threads. Use double-checked locking # to reduce the overhead introduced by the lock. if cls.logger is None: with cls.lock: if cls.logger is None: cls.logger = logging.getLogger('toil-rt') try: level = os.environ[cls.envPrefix + 'LEVEL'] except KeyError: # There is no server running on the leader, so suppress most log messages # and skip the UDP stuff. cls.logger.setLevel(logging.CRITICAL) else: # Adopt the logging level set on the leader. set_log_level(level, cls.logger) try: address = os.environ[cls.envPrefix + 'ADDRESS'] except KeyError: pass else: # We know where to send messages to, so send them. host, port = address.split(':') cls.logger.addHandler(JSONDatagramHandler(host, int(port))) return cls.logger def __init__(self, batchSystem, level=defaultLevel): """ A context manager that starts up the UDP server. Should only be invoked on the leader. Python logging should have already been configured. This method takes an optional log level, as a string level name, from the set supported by bioio. If the level is None, False or the empty string, real-time logging will be disabled, i.e. no UDP server will be started on the leader and log messages will be suppressed on the workers. Note that this is different from passing level='OFF', which is equivalent to level='CRITICAL' and does not disable the server. """ super().__init__() self.__level = level self.__batchSystem = batchSystem def __enter__(self): RealtimeLogger._startLeader(self.__batchSystem, level=self.__level) # noinspection PyUnusedLocal def __exit__(self, exc_type, exc_val, exc_tb): RealtimeLogger._stopLeader()
# -*- coding: utf-8 -*- """Module containing various line searches. Line searches are at the heart of many optimizers. After finding a suitable search direction (e.g. the steepest descent direction) we are left with a one-dimensional optimization problem, which can then be solved by a line search. """ # TODO: this module needs lots of pep8 love. import itertools import scipy.optimize import numpy as np import scipy as sp class LineSearch(object): def __init__(self, wrt): self.wrt = wrt def search(self, direction, initialization, args=None, kwargs=None): raise NotImplemented() class BackTrack(LineSearch): """Class implementing a back tracking line search. The idea is to jump to a starting step length :math:`t` and then shrink that step length by multiplying it with :math:`\\gamma` until we improve upon the loss. At most ``max_iter`` attempts will be done. If the largest absolut value of a component of the step falls below ``tolerance``, we stop as well. In both cases, a step length of 0 is returned. To not possibly iterate forever, the field `tolerance` holds a small value (1E-20 per default). As soon as the absolute value of every component of the step (direction multiplied with the scalar from `schedule`) is less than `tolerance`, we stop. Attributes ---------- wrt : array_like Parameters over which the optimization is done. f : Callable Objective function. decay : float Factor to multiply trials for the step length with. tolerance : float Minimum absolute value of a component of the step without stopping the line search. """ def __init__(self, wrt, f, decay=0.9, max_iter=float('inf'), tolerance=1E-20): """Create BackTrack object. Parameters ---------- wrt : array_like Parameters over which the optimization is done. f : Callable Objective function. decay : float Factor to multiply trials for the step length with. max_iter : int, optional, default infinity Number of step lengths to try. tolerance : float Minimum absolute value of a component of the step without stopping the line search. """ super(BackTrack, self).__init__(wrt) self.f = f self.max_iter = max_iter self.decay = decay self.tolerance = tolerance def search(self, direction, initialization=1, args=None, kwargs=None, loss0=None): """Return a step length ``t`` given a search direction. Perform the line search along a direction. Search will start at ``initialization`` and assume that the loss is ``loss0`` at ``t == 0``. Parameters ---------- direction : array_like Has to be of the same size as .wrt. Points along that direction will tried out to reduce the loss. initialization : float First attempt for a step size. Will be reduced by a factor of ``.decay`` afterwards. args : list, optional, default: None list of optional arguments for ``.f``. kwargs : dictionary, optional, default: None list of optional keyword arguments for ``.f``. loss0 : float, optional Loss at the current parameters. Will be calculated of not given. """ args = [] if args is None else args kwargs = {} if kwargs is None else kwargs # Recalculate the current loss if it has not been given. if loss0 is None: loss0 = self.f(self.wrt, *args, **kwargs) # Try out every point in the schedule until a reduction has been found. schedule = (self.decay ** i * initialization for i in itertools.count()) for i, s in enumerate(schedule): if i + 1 >= self.max_iter: break step = initialization * s * direction if abs(step).max() < self.tolerance: # If the step is too short, just return 0. break candidate = self.wrt + step loss = self.f(candidate, *args, **kwargs) if -(loss0 - loss) < 0: # We check here for negative improvement to also not continue in # the case of NaNs. return s return 0 class StrongWolfeBackTrack(BackTrack): """Class implementing a back tracking line search that finds points satisfying the Strong Wolfe conditions. The idea is to jump to a starting step length :math:`t` and then shrink that step length by multiplying it with :math:`\\gamma` until the strong Wolfe conditions are satisfied. That is the Armijo rule .. math:: f(\\theta_t+ \\alpha_t d_t) & \\leq f(\\theta)+ c_1 \\alpha_t d_t^T f'(\\theta), and the curvature condition .. math:: \\big|d_k^TTf('\\theta_t+\\alpha_t d_t)\\big| & \\leq c_2 \\big|d_t^T f'(\\theta_t)\\big|. At most ``max_iter`` attempts will be done. If the largest absolut value of a component of the step falls below ``tolerance``, we stop as well. In both cases, a step length of 0 is returned. To not possibly iterate forever, the field `tolerance` holds a small value (1E-20 per default). As soon as the absolute value of every component of the step (direction multiplied with the scalar from `schedule`) is less than `tolerance`, we stop. Attributes ---------- wrt : array_like Parameters over which the optimization is done. f : Callable Objective function. decay : float Factor to multiply trials for the step length with. tolerance : float Minimum absolute value of a component of the step without stopping the line search. c1 : float Constant in the strong Wolfe conditions. c2 : float Constant in the strong Wolfe conditions. """ def __init__(self, wrt, f, fprime, decay=None, c1=1E-4, c2=.9, tolerance=1E-20): """Create StrongWolfeBackTrack object. Parameters ---------- wrt : array_like Parameters over which the optimization is done. f : Callable Objective function. decay : float Factor to multiply trials for the step length with. tolerance : float Minimum absolute value of a component of the step without stopping the line search. """ super(StrongWolfeBackTrack, self).__init__(wrt, f, decay, tolerance) self.fprime = fprime self.c1 = c1 self.c2 = c2 def search(self, direction, args, kwargs, loss0=None): # TODO: respect initialization # Recalculate the current loss if it has not been given. if loss0 is None: loss0 = self.f(self.wrt, *args, **kwargs) self.grad = grad0 = self.fprime(self.wrt, *args, **kwargs) dir_dot_grad0 = scipy.inner(direction, grad0) # Try out every point in the schedule until one satisfying strong Wolfe # conditions has been found. for s in self.schedule: step = s * direction if abs(step.max()) < self.tolerance: # If the step is too short, stop trying. break candidate = self.wrt + step loss = self.f(candidate, *args, **kwargs) # Wolfe 1 if loss <= loss0 + self.c1 * s * dir_dot_grad0: grad = self.fprime(candidate, *args, **kwargs) dir_dot_grad = scipy.inner(direction, grad) # Wolfe 2 if abs(dir_dot_grad) <= self.c2 * abs(dir_dot_grad0): self.grad = grad return s return 0.0 class ScipyLineSearch(LineSearch): """Wrapper around the scipy line search.""" def __init__(self, wrt, f, fprime): super(ScipyLineSearch, self).__init__(wrt) self.f = f self.fprime = fprime def search(self, direction, args, kwargs): if kwargs: raise ValueError('keyword arguments not supported') gfk = self.fprime(self.wrt, *args) return scipy.optimize.line_search( self.f, self.fprime, self.wrt, direction, gfk, args=args)[0] class WolfeLineSearch(LineSearch): """Port of Mark Schmidt's line search.""" def __init__(self, wrt, f, fprime, c1=1E-4, c2=0.9, maxiter=25, min_step_length=1E-9, typ=4): super(WolfeLineSearch, self).__init__(wrt) self.f = f self.fprime = fprime self.c1 = c1 self.c2 = c2 self.maxiter = maxiter self.min_step_length = min_step_length self.typ = typ # TODO: find better API for this self.first_try = True def search(self, direction, initialization=None, args=None, kwargs=None, loss0=None): args = args if args is not None else () kwargs = kwargs if kwargs is not None else {} loss0 = self.f(self.wrt, *args, **kwargs) if loss0 is None else loss0 grad0 = self.fprime(self.wrt, *args, **kwargs) direct_deriv0 = scipy.inner(grad0, direction) f = lambda x: (self.f(x, *args, **kwargs), self.fprime(x, *args, **kwargs)) if self.first_try: self.first_try = False t = min(1, 1 / sum(abs(grad0))) else: t = initialization if initialization is not None else 1 step, fstep, fprimestep, n_evals = wolfe_line_search( self.wrt, t, direction, loss0, grad0, direct_deriv0, self.c1, self.c2, self.typ, self.maxiter, self.min_step_length, f) self.val = fstep self.grad = fprimestep return step def polyinterp(points, xminBound=None, xmaxBound=None): """ Minimum of interpolating polynomial based on function and derivative values. Note: doPlot from minFunc missing!!! """ nPoints = points.shape[0] order = np.sum(np.isreal(points[:, 1:3])) - 1 # Code for most common case: # - cubic interpolation of 2 points # w/ function and derivative values for both # - no xminBound/xmaxBound if nPoints == 2 and order == 3 and xminBound is None and xmaxBound is None: # Solution in this case (where x2 is the farthest point): # d1 = g1 + g2 - 3*(f1-f2)/(x1-x2); # d2 = sqrt(d1^2 - g1*g2); # minPos = x2 - (x2 - x1)*((g2 + d2 - d1)/(g2 - g1 + 2*d2)); # t_new = min(max(minPos,x1),x2); minVal = np.min(points[:, 0]) minPos = np.argmin(points[:, 0]) notMinPos = 1 - minPos x1 = points[minPos, 0] x2 = points[notMinPos, 0] g1 = points[minPos, 2] g2 = points[notMinPos, 2] f1 = points[minPos, 1] f2 = points[notMinPos, 1] d1 = g1 + g2 - 3 * (f1 - f2) / (x1 - x2) d2 = sp.sqrt(d1 ** 2 - g1 * g2) if np.isreal(d2): t = points[notMinPos, 0] -\ (points[notMinPos, 0] - points[minPos, 0]) * \ ( (points[notMinPos, 2] + d2 - d1) / (points[notMinPos, 2] - points[minPos, 2] + 2 * d2) ) minPos = np.minimum( np.maximum(t, points[minPos, 0]), points[notMinPos, 0]) else: minPos = np.mean(points[:, 0]) # fmin is not returned here return minPos, None # # xmin = np.min(points[:, 0]) xmax = np.max(points[:, 0]) # Compute Bouns of Interpolation Area if xminBound is None: xminBound = xmin if xmaxBound is None: xmaxBound = xmax # # # Collect constraints for parameter estimation A = np.zeros((2 * nPoints, order + 1)) b = np.zeros((2 * nPoints, 1)) # Constraints based on available function values for i in range(points.shape[0]): if np.isreal(points[i, 1]): A[i] = [points[i, 0] ** (order - j) for j in xrange(order + 1)] b[i] = points[i, 1] points[i, 0], points[i, 1] # Constraints based on available derivatives for i, p in enumerate(points[:, 2]): if np.isreal(p): A[nPoints + i] = [(order - j + 1) * points[i, 0] ** (order - j) for j in xrange(1, order + 1)] + [0] b[nPoints + i] = points[i, 2] # # Find interpolating polynomial params = np.linalg.lstsq(A, b)[0].flatten() # Compute critical points dParams = [(order - j) * params[j] for j in xrange(order)] cp = [xminBound, xmaxBound] + list(points[:, 0]) if not np.any(np.isinf(dParams)): cp += list(np.roots(dParams)) # Test critical points fmin = np.inf # Default to bisection if no critical points are valid minPos = (xminBound + xmaxBound) / 2. for x in cp: if np.isreal(x) and x >= xminBound and x <= xmaxBound: fx = np.polyval(params, x) if np.isreal(fx) and fx <= fmin: minPos = x fmin = fx return minPos, fmin def mixedExtrap(x0, f0, g0, x1, f1, g1, minStep, maxStep): """ From minFunc, without switches doPlot and debug. """ alpha_c, _ = polyinterp( points=np.array([[x0, f0, g0], [x1, f1, g1]]), xminBound=minStep, xmaxBound=maxStep) # alpha_s, _ = polyinterp( points=np.array([[x0, f0, g0], [x1, 1j, g1]]), xminBound=minStep, xmaxBound=maxStep) if alpha_c > minStep and abs(alpha_c - x1) < abs(alpha_s - x1): # Cubic Extrapolation t = alpha_c else: # Secant Extrapolation t = alpha_s return t def isLegal(v): """ Do exactly that. """ return not (np.any(np.iscomplex(v)) or np.any(np.isnan(v)) or np.any(np.isinf(v))) def armijobacktrack(x, t, d, f, fr, g, gtd, c1, LS, tolX, funObj): """ Backtracking linesearch satisfying Armijo condition. From minFunc. Missing: doPlot, saveHessianComp, varargin -> varargin are passed to funObj as parameters, need to be put in here!!!! Hessian at initial guess is _not_ returned Check again with minFunc!!! x: starting location t: initial step size d: descent direction f: function value at starting location fr: reference function value (usually funObj(x)) gtd: directional derivative at starting location c1: sufficient decrease parameter debug: display debugging information LS: type of interpolation tolX: minimum allowable step length funObj: objective function varargin: parameters of objective function Outputs: t: step length f_new: function value at x+t*d g_new: gradient value at x+t*d funEvals: number function evaluations performed by line search """ # Evaluate objective and gradient at initial step # Hessian part missing here! f_new, g_new = funObj(x + t * d) funEvals = 1 while f_new > fr + c1 * t * gtd or not isLegal(f_new): # A comment here will be nice! temp = t # this could be nicer, if idea how to work out 'LS' if LS == 0 or not isLegal(f_new): # Backtrack with fixed backtracing rate t = 0.5 * t elif LS == 2 and isLegal(g_new): # Backtrack with cubic interpolation with derivative t, _ = polyinterp( np.array([[0, f, gtd], [t, f_new, np.dot(g_new, d)]])) elif funEvals < 2 or not isLegal(f_prev): # Backtracking with quadratic interpolation # (no derivatives at new point available) t, _ = polyinterp(np.array([[0, f, gtd], [t, f_new, 1j]])) else: # Backtracking with cubin interpolation # (no derviatives at new point available) t, _ = polyinterp( np.array([[0, f, gtd], [t, f_new, 1j], [t_prev, f_prev, 1j]])) # # Adjust if change in t is too small ... if t < 1e-3 * temp: t = 1e-3 * temp # or too large elif t > 0.6 * temp: t = 0.6 * temp f_prev = f_new t_prev = temp # Missing part: call return Hessian f_new, g_new = funObj(x + t*d) # funEvals += 1 # Check if step size has become too small if np.sum(np.abs(t*d)) <= tolX: # Backtracking line search failed -> maybe some print out? t = 0 f_new = f g_new = g break # Missing: evaluate at new point # x_new = x + t*d # Hessian is missing here! return t, x_new, f_new, g_new, funEvals def mixedInterp(bracket, bracketFval, bracketGval, d, Tpos, oldLOval, oldLOFval, oldLOGval): """ From minFunc, without switches for doPlot and debug """ # This needs a check!! # # In particular this next line! nonTpos = 1 - Tpos # And these three lines .... gtdT = np.dot(bracketGval[Tpos], d) gtdNonT = np.dot(bracketGval[nonTpos], d) oldLOgtd = np.dot(oldLOGval, d) # if bracketFval[Tpos] > oldLOFval: # A comment here would be nice ... alpha_c, _ = polyinterp(np.array([[oldLOval, oldLOFval, oldLOgtd],\ [bracket[Tpos], bracketFval[Tpos], gtdT]])) # alpha_q, _ = polyinterp(np.array([[oldLOval, oldLOFval, oldLOgtd],\ [bracket[Tpos], bracketFval[Tpos], 1j]])) if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval): # Cubic Interpolation t = alpha_c else: # Mixed Quad/Cubic Interpolation t = (alpha_q + alpha_c)/2. elif np.dot(gtdT, oldLOgtd) < 0: # A comment here would be nice ... alpha_c, _ = polyinterp(np.array([[oldLOval, oldLOFval, oldLOgtd],\ [bracket[Tpos], bracketFval[Tpos], gtdT]])) # alpha_s, _ = polyinterp(np.array([[oldLOval, oldLOFval, oldLOgtd],\ [bracket[Tpos], 1j, gtdT]])) if abs(alpha_c - bracket[Tpos]) >= abs(alpha_s - bracket[Tpos]): # Cubic Interpolation t = alpha_c else: # Quad Interpolation t = alpha_s elif abs(gtdT) <= abs(oldLOgtd): alpha_c, _ = polyinterp(np.array([[oldLOval, oldLOFval, oldLOgtd],\ [bracket[Tpos], bracketFval[Tpos], gtdT]]),\ np.min(bracket), np.max(bracket)) # alpha_s, _ = polyinterp(np.array([[oldLOval, 1j, oldLOgtd],\ [bracket[Tpos], bracketFval[Tpos], gtdT]]),\ np.min(bracket), np.max(bracket)) # if (alpha_c > min(bracket)) and (alpha_c < max(bracket)): if abs(alpha_c - bracket[Tpos]) < abs(alpha_s - bracket[Tpos]): # Bounded Cubic Extrapolation t = alpha_c else: # Bounded Secant Extrapolation t = alpha_s else: # Bounded Secant Extrapolation t = alpha_s if bracket[Tpos] > oldLOval: t = min(bracket[Tpos] + 0.66*(bracket[nonTpos] - bracket[Tpos]), t) else: t = max(bracket[Tpos] + 0.66*(bracket[nonTpos] - bracket[Tpos]), t) else: t, _ = polyinterp( np.array([[bracket[nonTpos], bracketFval[nonTpos], gtdNonT], [bracket[Tpos], bracketFval[Tpos], gtdT]])) return t def wolfe_line_search(x, t, d, f, g, gtd, c1, c2, LS, maxLS, tolX, funObj): """ Bracketing Line Search to Satisfy Wolfe Conditions From minFunc. Missing!!! debug, doPlot, saveHessian, varargin Inputs: x: starting location t: initial step size d: descent direction f: function value at starting location g: gradient at starting location gtd: directional derivative at starting location c1: sufficient decrease parameter c2: curvature parameter debug: display debugging information LS: type of interpolation maxLS: maximum number of iterations tolX: minimum allowable step length doPlot: do a graphical display of interpolation funObj: objective function varargin: parameters of objective function Outputs: t: step length f_new: function value at x+t*d g_new: gradient value at x+t*d funEvals: number function evaluations performed by line search NOT: H: Hessian at initial guess (only computed if requested """ #Evaluate the Objective and Gradient at the Initial Step f_new, g_new = funObj(x+t*d) funEvals = 1 gtd_new = np.dot(g_new, d) # Bracket an intervail containing a point # satisfying the wolfe criteria LSiter = 0 t_prev = 0 f_prev = f g_prev = g gtd_prev = gtd done = False while LSiter < maxLS: # Bracketing phase if not isLegal(f_new) or not isLegal(g_new): t = (t + t_prev)/2. # missing: if 0 in minFunc!! # # Extrapolated into illegal region, switching # to Armijo line search # no Hessian is computed!! t, x_new, f_new, g_new, _fevals = armijobacktrack( x, t, d, f, f, g, gtd, c1, max(0, min(LS-2, 2)), tolX, funObj) funEvals += _fevals return t, f_new, g_new, funEvals # if (f_new > f + c1*t*gtd) or (LSiter > 1 and f_new >= f_prev): bracket = [t_prev, t] bracketFval = [f_prev, f_new] # check here: two gradients next to each other, in columns bracketGval = np.array([g_prev, g_new]) break elif abs(gtd_new) <= -c2*gtd: bracket = np.array([t]) bracketFval = np.array([f_new]) bracketGval = np.array([g_new]) done = True break elif gtd_new >= 0: bracket = [t_prev, t] bracketFval = [f_prev, f_new] # check here (again), see above bracketGval = np.array([g_prev, g_new]) break temp = t_prev t_prev = t minStep = t + 0.01*(t-temp) maxStep = t*10 # if LS == 3: # Extending Braket t = maxStep elif LS == 4: # Cubic Extrapolation t, _ = polyinterp(np.array([[temp, f_prev, gtd_prev],\ [t, f_new, gtd_new]]), minStep, maxStep) else: t = mixedExtrap(temp, f_prev, gtd_prev, t, f_new, gtd_new, minStep, maxStep) # f_prev = f_new g_prev = g_new gtd_prev = gtd_new # # no saveHessian stuff!!! f_new, g_new = funObj(x + t*d) funEvals += 1 gtd_new = np.inner(g_new, d) LSiter += 1 # while .... # if LSiter == maxLS: bracket = [0, t] bracketFval = [f, f_new] # check here, same again! bracketGval = np.array([g, g_new]) # Zoom Phase: # We now either have point satisfying the criteria # or a bracket surrounding a point satisfying the criteria. # Refine the bracket until we find a point satifying the criteria. # insufProgress = False # Next line needs a check!!!!! Tpos = 1 LOposRemoved = False while not done and LSiter < maxLS: # Find high and low points in the bracket # check here, axees needed?? f_LO = np.min(bracketFval) LOpos = np.argmin(bracketFval) HIpos = 1 - LOpos # # Compute new trial value if LS == 3 or not isLegal(bracketFval) or not isLegal(bracketGval): # Bisecting t = np.mean(bracket) elif LS == 4: # Grad cubic interpolation t, _ = polyinterp( np.array( [[bracket[0], bracketFval[0], np.dot(bracketGval[0], d)], [bracket[1], bracketFval[1], np.dot(bracketGval[1], d)]])) else: # Mixed case # Is this correct ??????? nonTpos = 1 - Tpos if not LOposRemoved: oldLOval = bracket[nonTpos] oldLOFval = bracketFval[nonTpos] oldLOGval = bracketGval[nonTpos] t = mixedInterp( bracket, bracketFval, bracketGval, d, Tpos, oldLOval, oldLOFval, oldLOGval) # # Test that we are making sufficient progress bracket_min = min(bracket) bracket_max = max(bracket) if min(bracket_max - t, t - bracket_min) / (bracket_max - bracket_min) < 0.1: # Interpolation close to boundary if insufProgress or (t >= np.max(bracket)) or (t <= np.min(bracket)): # Evaluating at 0.1 away from boundary if np.abs(t - np.max(bracket)) < np.abs(t - np.min(bracket)): t = np.max(bracket) - 0.1 * (np.max(bracket) - np.min(bracket)) else: t = np.min(bracket) + 0.1 * (np.max(bracket) - np.min(bracket)) insufProgress = False # else: insufProgress = True # else: insufProgress = False # Evaluate new point # no Hessian! t = scipy.real(t) f_new, g_new = funObj(x + t * d) funEvals += 1 gtd_new = np.dot(g_new, d) LSiter += 1 if f_new > f + c1 * t * gtd or f_new >= f_LO: # Armijo condition not satisfied or # not lower than lowest point bracket[HIpos] = t bracketFval[HIpos] = f_new bracketGval[HIpos] = g_new Tpos = HIpos else: if np.abs(gtd_new) <= -c2 * gtd: # Wolfe conditions satisfied done = True elif gtd_new * (bracket[HIpos] - bracket[LOpos]) >= 0: # old HI becomes new LO bracket[HIpos] = bracket[LOpos] bracketFval[HIpos] = bracketFval[LOpos] bracketGval[HIpos] = bracketGval[LOpos] if LS == 5: # LO Pos is being removed LOposRemoved = True oldLOval = bracket[LOpos] oldLOFval = bracketFval[LOpos] oldLOGval = bracketGval[LOpos] # # New point becomes new LO bracket[LOpos] = t bracketFval[LOpos] = f_new bracketGval[LOpos] = g_new Tpos = LOpos if not done and np.abs(bracket[0] - bracket[1]) * gtd_new < tolX: # Line search can not make further progress break # while ... # TODO a comment here maybe nice if LSiter == maxLS: # could give info: # Line Search exceeded maximum line search iterations # TODO: what to do here? pass # # check if axes necessary? f_LO = np.min(bracketFval) LOpos = np.argmin(bracketFval) t = bracket[LOpos] f_new = bracketFval[LOpos] g_new = bracketGval[LOpos] # missing Hessain evaluation return t, f_new, g_new, funEvals
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nicira Networks, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # @author: Dan Wendlandt, Nicira, Inc # import netaddr import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.orm import exc from sqlalchemy.sql import expression as expr from quantum.api.rpc.agentnotifiers import l3_rpc_agent_api from quantum.api.v2 import attributes from quantum.common import constants as l3_constants from quantum.common import exceptions as q_exc from quantum.db import db_base_plugin_v2 from quantum.db import model_base from quantum.db import models_v2 from quantum.extensions import l3 from quantum.openstack.common import log as logging from quantum.openstack.common.notifier import api as notifier_api from quantum.openstack.common import uuidutils from quantum import policy LOG = logging.getLogger(__name__) DEVICE_OWNER_ROUTER_INTF = l3_constants.DEVICE_OWNER_ROUTER_INTF DEVICE_OWNER_ROUTER_GW = l3_constants.DEVICE_OWNER_ROUTER_GW DEVICE_OWNER_FLOATINGIP = l3_constants.DEVICE_OWNER_FLOATINGIP # Maps API field to DB column # API parameter name and Database column names may differ. # Useful to keep the filtering between API and Database. API_TO_DB_COLUMN_MAP = {'port_id': 'fixed_port_id'} class Router(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): """Represents a v2 quantum router.""" name = sa.Column(sa.String(255)) status = sa.Column(sa.String(16)) admin_state_up = sa.Column(sa.Boolean) gw_port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id')) gw_port = orm.relationship(models_v2.Port) class ExternalNetwork(model_base.BASEV2): network_id = sa.Column(sa.String(36), sa.ForeignKey('networks.id', ondelete="CASCADE"), primary_key=True) class FloatingIP(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant): """Represents a floating IP address. This IP address may or many not be allocated to a tenant, and may or may not be associated with an internal port/ip address/router. """ floating_ip_address = sa.Column(sa.String(64), nullable=False) floating_network_id = sa.Column(sa.String(36), nullable=False) floating_port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id'), nullable=False) fixed_port_id = sa.Column(sa.String(36), sa.ForeignKey('ports.id')) fixed_ip_address = sa.Column(sa.String(64)) router_id = sa.Column(sa.String(36), sa.ForeignKey('routers.id')) class L3_NAT_db_mixin(l3.RouterPluginBase): """Mixin class to add L3/NAT router methods to db_plugin_base_v2.""" def _network_model_hook(self, context, original_model, query): query = query.outerjoin(ExternalNetwork, (original_model.id == ExternalNetwork.network_id)) return query def _network_filter_hook(self, context, original_model, conditions): if conditions is not None and not hasattr(conditions, '__iter__'): conditions = (conditions, ) # Apply the external network filter only in non-admin context if not context.is_admin and hasattr(original_model, 'tenant_id'): conditions = expr.or_(ExternalNetwork.network_id != expr.null(), *conditions) return conditions def _network_result_filter_hook(self, query, filters): vals = filters and filters.get('router:external', []) if not vals: return query if vals[0]: return query.filter((ExternalNetwork.network_id != expr.null())) return query.filter((ExternalNetwork.network_id == expr.null())) # TODO(salvatore-orlando): Perform this operation without explicitly # referring to db_base_plugin_v2, as plugins that do not extend from it # might exist in the future db_base_plugin_v2.QuantumDbPluginV2.register_model_query_hook( models_v2.Network, "external_net", _network_model_hook, _network_filter_hook, _network_result_filter_hook) def _get_router(self, context, id): try: router = self._get_by_id(context, Router, id) except exc.NoResultFound: raise l3.RouterNotFound(router_id=id) except exc.MultipleResultsFound: LOG.error(_('Multiple routers match for %s'), id) raise l3.RouterNotFound(router_id=id) return router def _make_router_dict(self, router, fields=None): res = {'id': router['id'], 'name': router['name'], 'tenant_id': router['tenant_id'], 'admin_state_up': router['admin_state_up'], 'status': router['status'], 'external_gateway_info': None, 'gw_port_id': router['gw_port_id']} if router['gw_port_id']: nw_id = router.gw_port['network_id'] res['external_gateway_info'] = {'network_id': nw_id} return self._fields(res, fields) def create_router(self, context, router): r = router['router'] has_gw_info = False if 'external_gateway_info' in r: has_gw_info = True gw_info = r['external_gateway_info'] del r['external_gateway_info'] tenant_id = self._get_tenant_id_for_create(context, r) with context.session.begin(subtransactions=True): # pre-generate id so it will be available when # configuring external gw port router_db = Router(id=uuidutils.generate_uuid(), tenant_id=tenant_id, name=r['name'], admin_state_up=r['admin_state_up'], status="ACTIVE") context.session.add(router_db) if has_gw_info: self._update_router_gw_info(context, router_db['id'], gw_info) return self._make_router_dict(router_db) def update_router(self, context, id, router): r = router['router'] has_gw_info = False if 'external_gateway_info' in r: has_gw_info = True gw_info = r['external_gateway_info'] del r['external_gateway_info'] with context.session.begin(subtransactions=True): if has_gw_info: self._update_router_gw_info(context, id, gw_info) router_db = self._get_router(context, id) # Ensure we actually have something to update if r.keys(): router_db.update(r) routers = self.get_sync_data(context.elevated(), [router_db['id']]) l3_rpc_agent_api.L3AgentNotify.routers_updated(context, routers) return self._make_router_dict(router_db) def _update_router_gw_info(self, context, router_id, info): # TODO(salvatore-orlando): guarantee atomic behavior also across # operations that span beyond the model classes handled by this # class (e.g.: delete_port) router = self._get_router(context, router_id) gw_port = router.gw_port network_id = info.get('network_id', None) if info else None if network_id: self._get_network(context, network_id) if not self._network_is_external(context, network_id): msg = _("Network %s is not a valid external " "network") % network_id raise q_exc.BadRequest(resource='router', msg=msg) # figure out if we need to delete existing port if gw_port and gw_port['network_id'] != network_id: fip_count = self.get_floatingips_count(context.elevated(), {'router_id': [router_id]}) if fip_count: raise l3.RouterExternalGatewayInUseByFloatingIp( router_id=router_id, net_id=gw_port['network_id']) with context.session.begin(subtransactions=True): router.gw_port = None context.session.add(router) self.delete_port(context.elevated(), gw_port['id'], l3_port_check=False) if network_id is not None and (gw_port is None or gw_port['network_id'] != network_id): subnets = self._get_subnets_by_network(context, network_id) for subnet in subnets: self._check_for_dup_router_subnet(context, router_id, network_id, subnet['id'], subnet['cidr']) # Port has no 'tenant-id', as it is hidden from user gw_port = self.create_port(context.elevated(), { 'port': {'tenant_id': '', # intentionally not set 'network_id': network_id, 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'fixed_ips': attributes.ATTR_NOT_SPECIFIED, 'device_id': router_id, 'device_owner': DEVICE_OWNER_ROUTER_GW, 'admin_state_up': True, 'name': ''}}) if not gw_port['fixed_ips']: self.delete_port(context.elevated(), gw_port['id'], l3_port_check=False) msg = (_('No IPs available for external network %s') % network_id) raise q_exc.BadRequest(resource='router', msg=msg) with context.session.begin(subtransactions=True): router.gw_port = self._get_port(context.elevated(), gw_port['id']) context.session.add(router) def delete_router(self, context, id): with context.session.begin(subtransactions=True): router = self._get_router(context, id) # Ensure that the router is not used fips = self.get_floatingips_count(context.elevated(), filters={'router_id': [id]}) if fips: raise l3.RouterInUse(router_id=id) device_filter = {'device_id': [id], 'device_owner': [DEVICE_OWNER_ROUTER_INTF]} ports = self.get_ports_count(context.elevated(), filters=device_filter) if ports: raise l3.RouterInUse(router_id=id) # delete any gw port device_filter = {'device_id': [id], 'device_owner': [DEVICE_OWNER_ROUTER_GW]} ports = self.get_ports(context.elevated(), filters=device_filter) if ports: self._delete_port(context.elevated(), ports[0]['id']) context.session.delete(router) l3_rpc_agent_api.L3AgentNotify.router_deleted(context, id) def get_router(self, context, id, fields=None): router = self._get_router(context, id) return self._make_router_dict(router, fields) def get_routers(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): marker_obj = self._get_marker_obj(context, 'router', limit, marker) return self._get_collection(context, Router, self._make_router_dict, filters=filters, fields=fields, sorts=sorts, limit=limit, marker_obj=marker_obj, page_reverse=page_reverse) def get_routers_count(self, context, filters=None): return self._get_collection_count(context, Router, filters=filters) def _check_for_dup_router_subnet(self, context, router_id, network_id, subnet_id, subnet_cidr): try: rport_qry = context.session.query(models_v2.Port) rports = rport_qry.filter_by(device_id=router_id) # its possible these ports on on the same network, but # different subnet new_ipnet = netaddr.IPNetwork(subnet_cidr) for p in rports: for ip in p['fixed_ips']: if ip['subnet_id'] == subnet_id: msg = (_("Router already has a port on subnet %s") % subnet_id) raise q_exc.BadRequest(resource='router', msg=msg) sub_id = ip['subnet_id'] cidr = self._get_subnet(context.elevated(), sub_id)['cidr'] ipnet = netaddr.IPNetwork(cidr) match1 = netaddr.all_matching_cidrs(new_ipnet, [cidr]) match2 = netaddr.all_matching_cidrs(ipnet, [subnet_cidr]) if match1 or match2: data = {'subnet_cidr': subnet_cidr, 'subnet_id': subnet_id, 'cidr': cidr, 'sub_id': sub_id} msg = (_("Cidr %(subnet_cidr)s of subnet " "%(subnet_id)s overlaps with cidr %(cidr)s " "of subnet %(sub_id)s") % data) raise q_exc.BadRequest(resource='router', msg=msg) except exc.NoResultFound: pass def add_router_interface(self, context, router_id, interface_info): if not interface_info: msg = _("Either subnet_id or port_id must be specified") raise q_exc.BadRequest(resource='router', msg=msg) if 'port_id' in interface_info: if 'subnet_id' in interface_info: msg = _("Cannot specify both subnet-id and port-id") raise q_exc.BadRequest(resource='router', msg=msg) port = self._get_port(context, interface_info['port_id']) if port['device_id']: raise q_exc.PortInUse(net_id=port['network_id'], port_id=port['id'], device_id=port['device_id']) fixed_ips = [ip for ip in port['fixed_ips']] if len(fixed_ips) != 1: msg = _('Router port must have exactly one fixed IP') raise q_exc.BadRequest(resource='router', msg=msg) subnet_id = fixed_ips[0]['subnet_id'] subnet = self._get_subnet(context, subnet_id) self._check_for_dup_router_subnet(context, router_id, port['network_id'], subnet['id'], subnet['cidr']) port.update({'device_id': router_id, 'device_owner': DEVICE_OWNER_ROUTER_INTF}) elif 'subnet_id' in interface_info: subnet_id = interface_info['subnet_id'] subnet = self._get_subnet(context, subnet_id) # Ensure the subnet has a gateway if not subnet['gateway_ip']: msg = _('Subnet for router interface must have a gateway IP') raise q_exc.BadRequest(resource='router', msg=msg) self._check_for_dup_router_subnet(context, router_id, subnet['network_id'], subnet_id, subnet['cidr']) fixed_ip = {'ip_address': subnet['gateway_ip'], 'subnet_id': subnet['id']} port = self.create_port(context, { 'port': {'tenant_id': subnet['tenant_id'], 'network_id': subnet['network_id'], 'fixed_ips': [fixed_ip], 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'admin_state_up': True, 'device_id': router_id, 'device_owner': DEVICE_OWNER_ROUTER_INTF, 'name': ''}}) routers = self.get_sync_data(context.elevated(), [router_id]) l3_rpc_agent_api.L3AgentNotify.routers_updated( context, routers, 'add_router_interface', {'network_id': port['network_id'], 'subnet_id': subnet_id}) info = {'id': router_id, 'tenant_id': subnet['tenant_id'], 'port_id': port['id'], 'subnet_id': port['fixed_ips'][0]['subnet_id']} notifier_api.notify(context, notifier_api.publisher_id('network'), 'router.interface.create', notifier_api.CONF.default_notification_level, {'router.interface': info}) return info def _confirm_router_interface_not_in_use(self, context, router_id, subnet_id): subnet_db = self._get_subnet(context, subnet_id) subnet_cidr = netaddr.IPNetwork(subnet_db['cidr']) fip_qry = context.session.query(FloatingIP) for fip_db in fip_qry.filter_by(router_id=router_id): if netaddr.IPAddress(fip_db['fixed_ip_address']) in subnet_cidr: raise l3.RouterInterfaceInUseByFloatingIP( router_id=router_id, subnet_id=subnet_id) def remove_router_interface(self, context, router_id, interface_info): if not interface_info: msg = _("Either subnet_id or port_id must be specified") raise q_exc.BadRequest(resource='router', msg=msg) if 'port_id' in interface_info: port_id = interface_info['port_id'] port_db = self._get_port(context, port_id) if not (port_db['device_owner'] == DEVICE_OWNER_ROUTER_INTF and port_db['device_id'] == router_id): raise l3.RouterInterfaceNotFound(router_id=router_id, port_id=port_id) if 'subnet_id' in interface_info: port_subnet_id = port_db['fixed_ips'][0]['subnet_id'] if port_subnet_id != interface_info['subnet_id']: raise q_exc.SubnetMismatchForPort( port_id=port_id, subnet_id=interface_info['subnet_id']) subnet_id = port_db['fixed_ips'][0]['subnet_id'] subnet = self._get_subnet(context, subnet_id) self._confirm_router_interface_not_in_use( context, router_id, subnet_id) _network_id = port_db['network_id'] self.delete_port(context, port_db['id'], l3_port_check=False) elif 'subnet_id' in interface_info: subnet_id = interface_info['subnet_id'] self._confirm_router_interface_not_in_use(context, router_id, subnet_id) subnet = self._get_subnet(context, subnet_id) found = False try: rport_qry = context.session.query(models_v2.Port) ports = rport_qry.filter_by( device_id=router_id, device_owner=DEVICE_OWNER_ROUTER_INTF, network_id=subnet['network_id']) for p in ports: if p['fixed_ips'][0]['subnet_id'] == subnet_id: port_id = p['id'] _network_id = p['network_id'] self.delete_port(context, p['id'], l3_port_check=False) found = True break except exc.NoResultFound: pass if not found: raise l3.RouterInterfaceNotFoundForSubnet(router_id=router_id, subnet_id=subnet_id) routers = self.get_sync_data(context.elevated(), [router_id]) l3_rpc_agent_api.L3AgentNotify.routers_updated( context, routers, 'remove_router_interface', {'network_id': _network_id, 'subnet_id': subnet_id}) info = {'id': router_id, 'tenant_id': subnet['tenant_id'], 'port_id': port_id, 'subnet_id': subnet_id} notifier_api.notify(context, notifier_api.publisher_id('network'), 'router.interface.delete', notifier_api.CONF.default_notification_level, {'router.interface': info}) return info def _get_floatingip(self, context, id): try: floatingip = self._get_by_id(context, FloatingIP, id) except exc.NoResultFound: raise l3.FloatingIPNotFound(floatingip_id=id) except exc.MultipleResultsFound: LOG.error(_('Multiple floating ips match for %s'), id) raise l3.FloatingIPNotFound(floatingip_id=id) return floatingip def _make_floatingip_dict(self, floatingip, fields=None): res = {'id': floatingip['id'], 'tenant_id': floatingip['tenant_id'], 'floating_ip_address': floatingip['floating_ip_address'], 'floating_network_id': floatingip['floating_network_id'], 'router_id': floatingip['router_id'], 'port_id': floatingip['fixed_port_id'], 'fixed_ip_address': floatingip['fixed_ip_address']} return self._fields(res, fields) def _get_router_for_floatingip(self, context, internal_port, internal_subnet_id, external_network_id): subnet_db = self._get_subnet(context, internal_subnet_id) if not subnet_db['gateway_ip']: msg = (_('Cannot add floating IP to port on subnet %s ' 'which has no gateway_ip') % internal_subnet_id) raise q_exc.BadRequest(resource='floatingip', msg=msg) # find router interface ports on this network router_intf_qry = context.session.query(models_v2.Port) router_intf_ports = router_intf_qry.filter_by( network_id=internal_port['network_id'], device_owner=DEVICE_OWNER_ROUTER_INTF) for intf_p in router_intf_ports: if intf_p['fixed_ips'][0]['subnet_id'] == internal_subnet_id: router_id = intf_p['device_id'] router_gw_qry = context.session.query(models_v2.Port) has_gw_port = router_gw_qry.filter_by( network_id=external_network_id, device_id=router_id, device_owner=DEVICE_OWNER_ROUTER_GW).count() if has_gw_port: return router_id raise l3.ExternalGatewayForFloatingIPNotFound( subnet_id=internal_subnet_id, external_network_id=external_network_id, port_id=internal_port['id']) def get_assoc_data(self, context, fip, floating_network_id): """Determine/extract data associated with the internal port. When a floating IP is associated with an internal port, we need to extract/determine some data associated with the internal port, including the internal_ip_address, and router_id. We also need to confirm that this internal port is owned by the tenant who owns the floating IP. """ internal_port = self._get_port(context, fip['port_id']) if not internal_port['tenant_id'] == fip['tenant_id']: port_id = fip['port_id'] if 'id' in fip: floatingip_id = fip['id'] data = {'port_id': port_id, 'floatingip_id': floatingip_id} msg = (_('Port %(port_id)s is associated with a different ' 'tenant than Floating IP %(floatingip_id)s and ' 'therefore cannot be bound.') % data) else: msg = (_('Cannnot create floating IP and bind it to ' 'Port %s, since that port is owned by a ' 'different tenant.') % port_id) raise q_exc.BadRequest(resource='floatingip', msg=msg) internal_subnet_id = None if 'fixed_ip_address' in fip and fip['fixed_ip_address']: internal_ip_address = fip['fixed_ip_address'] for ip in internal_port['fixed_ips']: if ip['ip_address'] == internal_ip_address: internal_subnet_id = ip['subnet_id'] if not internal_subnet_id: msg = (_('Port %(id)s does not have fixed ip %(address)s') % {'id': internal_port['id'], 'address': internal_ip_address}) raise q_exc.BadRequest(resource='floatingip', msg=msg) else: ips = [ip['ip_address'] for ip in internal_port['fixed_ips']] if not ips: msg = (_('Cannot add floating IP to port %s that has' 'no fixed IP addresses') % internal_port['id']) raise q_exc.BadRequest(resource='floatingip', msg=msg) if len(ips) > 1: msg = (_('Port %s has multiple fixed IPs. Must provide' ' a specific IP when assigning a floating IP') % internal_port['id']) raise q_exc.BadRequest(resource='floatingip', msg=msg) internal_ip_address = internal_port['fixed_ips'][0]['ip_address'] internal_subnet_id = internal_port['fixed_ips'][0]['subnet_id'] router_id = self._get_router_for_floatingip(context, internal_port, internal_subnet_id, floating_network_id) # confirm that this router has a floating # ip enabled gateway with support for this floating IP network try: port_qry = context.elevated().session.query(models_v2.Port) port_qry.filter_by( network_id=floating_network_id, device_id=router_id, device_owner=DEVICE_OWNER_ROUTER_GW).one() except exc.NoResultFound: raise l3.ExternalGatewayForFloatingIPNotFound( subnet_id=internal_subnet_id, port_id=internal_port['id']) return (fip['port_id'], internal_ip_address, router_id) def _update_fip_assoc(self, context, fip, floatingip_db, external_port): port_id = internal_ip_address = router_id = None if (('fixed_ip_address' in fip and fip['fixed_ip_address']) and not ('port_id' in fip and fip['port_id'])): msg = _("fixed_ip_address cannot be specified without a port_id") raise q_exc.BadRequest(resource='floatingip', msg=msg) if 'port_id' in fip and fip['port_id']: port_id, internal_ip_address, router_id = self.get_assoc_data( context, fip, floatingip_db['floating_network_id']) fip_qry = context.session.query(FloatingIP) try: fip_qry.filter_by( fixed_port_id=fip['port_id'], floating_network_id=floatingip_db['floating_network_id'], fixed_ip_address=internal_ip_address).one() raise l3.FloatingIPPortAlreadyAssociated( port_id=fip['port_id'], fip_id=floatingip_db['id'], floating_ip_address=floatingip_db['floating_ip_address'], fixed_ip=internal_ip_address, net_id=floatingip_db['floating_network_id']) except exc.NoResultFound: pass floatingip_db.update({'fixed_ip_address': internal_ip_address, 'fixed_port_id': port_id, 'router_id': router_id}) def create_floatingip(self, context, floatingip): fip = floatingip['floatingip'] tenant_id = self._get_tenant_id_for_create(context, fip) fip_id = uuidutils.generate_uuid() f_net_id = fip['floating_network_id'] if not self._network_is_external(context, f_net_id): msg = _("Network %s is not a valid external network") % f_net_id raise q_exc.BadRequest(resource='floatingip', msg=msg) try: with context.session.begin(subtransactions=True): # This external port is never exposed to the tenant. # it is used purely for internal system and admin use when # managing floating IPs. external_port = self.create_port(context.elevated(), { 'port': {'tenant_id': '', # tenant intentionally not set 'network_id': f_net_id, 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'fixed_ips': attributes.ATTR_NOT_SPECIFIED, 'admin_state_up': True, 'device_id': fip_id, 'device_owner': DEVICE_OWNER_FLOATINGIP, 'name': ''}}) # Ensure IP addresses are allocated on external port if not external_port['fixed_ips']: msg = _("Unable to find any IP address on external " "network") raise q_exc.BadRequest(resource='floatingip', msg=msg) floating_fixed_ip = external_port['fixed_ips'][0] floating_ip_address = floating_fixed_ip['ip_address'] floatingip_db = FloatingIP( id=fip_id, tenant_id=tenant_id, floating_network_id=fip['floating_network_id'], floating_ip_address=floating_ip_address, floating_port_id=external_port['id']) fip['tenant_id'] = tenant_id # Update association with internal port # and define external IP address self._update_fip_assoc(context, fip, floatingip_db, external_port) context.session.add(floatingip_db) # TODO(salvatore-orlando): Avoid broad catch # Maybe by introducing base class for L3 exceptions except q_exc.BadRequest: LOG.exception(_("Unable to create Floating ip due to a " "malformed request")) raise except Exception: LOG.exception(_("Floating IP association failed")) raise router_id = floatingip_db['router_id'] if router_id: routers = self.get_sync_data(context.elevated(), [router_id]) l3_rpc_agent_api.L3AgentNotify.routers_updated(context, routers, 'create_floatingip') return self._make_floatingip_dict(floatingip_db) def update_floatingip(self, context, id, floatingip): fip = floatingip['floatingip'] with context.session.begin(subtransactions=True): floatingip_db = self._get_floatingip(context, id) fip['tenant_id'] = floatingip_db['tenant_id'] fip['id'] = id fip_port_id = floatingip_db['floating_port_id'] before_router_id = floatingip_db['router_id'] self._update_fip_assoc(context, fip, floatingip_db, self.get_port(context.elevated(), fip_port_id)) router_ids = [] if before_router_id: router_ids.append(before_router_id) router_id = floatingip_db['router_id'] if router_id and router_id != before_router_id: router_ids.append(router_id) if router_ids: routers = self.get_sync_data(context.elevated(), router_ids) l3_rpc_agent_api.L3AgentNotify.routers_updated(context, routers, 'update_floatingip') return self._make_floatingip_dict(floatingip_db) def delete_floatingip(self, context, id): floatingip = self._get_floatingip(context, id) router_id = floatingip['router_id'] with context.session.begin(subtransactions=True): context.session.delete(floatingip) self.delete_port(context.elevated(), floatingip['floating_port_id'], l3_port_check=False) if router_id: routers = self.get_sync_data(context.elevated(), [router_id]) l3_rpc_agent_api.L3AgentNotify.routers_updated(context, routers, 'delete_floatingip') def get_floatingip(self, context, id, fields=None): floatingip = self._get_floatingip(context, id) return self._make_floatingip_dict(floatingip, fields) def get_floatingips(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): marker_obj = self._get_marker_obj(context, 'floatingip', limit, marker) if filters is not None: for key, val in API_TO_DB_COLUMN_MAP.iteritems(): if key in filters: filters[val] = filters.pop(key) return self._get_collection(context, FloatingIP, self._make_floatingip_dict, filters=filters, fields=fields, sorts=sorts, limit=limit, marker_obj=marker_obj, page_reverse=page_reverse) def get_floatingips_count(self, context, filters=None): return self._get_collection_count(context, FloatingIP, filters=filters) def prevent_l3_port_deletion(self, context, port_id): """Checks to make sure a port is allowed to be deleted. Raises an exception if this is not the case. This should be called by any plugin when the API requests the deletion of a port, since some ports for L3 are not intended to be deleted directly via a DELETE to /ports, but rather via other API calls that perform the proper deletion checks. """ port_db = self._get_port(context, port_id) if port_db['device_owner'] in [DEVICE_OWNER_ROUTER_INTF, DEVICE_OWNER_ROUTER_GW, DEVICE_OWNER_FLOATINGIP]: # Raise port in use only if the port has IP addresses # Otherwise it's a stale port that can be removed fixed_ips = port_db['fixed_ips'].all() if fixed_ips: raise l3.L3PortInUse(port_id=port_id, device_owner=port_db['device_owner']) else: LOG.debug(_("Port %(port_id)s has owner %(port_owner)s, but " "no IP address, so it can be deleted"), {'port_id': port_db['id'], 'port_owner': port_db['device_owner']}) def disassociate_floatingips(self, context, port_id): with context.session.begin(subtransactions=True): try: fip_qry = context.session.query(FloatingIP) floating_ip = fip_qry.filter_by(fixed_port_id=port_id).one() router_id = floating_ip['router_id'] floating_ip.update({'fixed_port_id': None, 'fixed_ip_address': None, 'router_id': None}) except exc.NoResultFound: return except exc.MultipleResultsFound: # should never happen raise Exception(_('Multiple floating IPs found for port %s') % port_id) if router_id: routers = self.get_sync_data(context.elevated(), [router_id]) l3_rpc_agent_api.L3AgentNotify.routers_updated(context, routers) def _check_l3_view_auth(self, context, network): return policy.check(context, "extension:router:view", network) def _network_is_external(self, context, net_id): try: context.session.query(ExternalNetwork).filter_by( network_id=net_id).one() return True except exc.NoResultFound: return False def _extend_network_dict_l3(self, context, network): if self._check_l3_view_auth(context, network): network[l3.EXTERNAL] = self._network_is_external( context, network['id']) def _process_l3_create(self, context, net_data, net_id): external = net_data.get(l3.EXTERNAL) external_set = attributes.is_attr_set(external) if not external_set: return if external: # expects to be called within a plugin's session context.session.add(ExternalNetwork(network_id=net_id)) def _process_l3_update(self, context, net_data, net_id): new_value = net_data.get(l3.EXTERNAL) if not attributes.is_attr_set(new_value): return existing_value = self._network_is_external(context, net_id) if existing_value == new_value: return if new_value: context.session.add(ExternalNetwork(network_id=net_id)) else: # must make sure we do not have any external gateway ports # (and thus, possible floating IPs) on this network before # allow it to be update to external=False port = context.session.query(models_v2.Port).filter_by( device_owner=DEVICE_OWNER_ROUTER_GW, network_id=net_id).first() if port: raise l3.ExternalNetworkInUse(net_id=net_id) context.session.query(ExternalNetwork).filter_by( network_id=net_id).delete() def _filter_nets_l3(self, context, nets, filters): vals = filters and filters.get('router:external', []) if not vals: return nets ext_nets = set(en['network_id'] for en in context.session.query(ExternalNetwork)) if vals[0]: return [n for n in nets if n['id'] in ext_nets] else: return [n for n in nets if n['id'] not in ext_nets] def _get_sync_routers(self, context, router_ids=None, active=None): """Query routers and their gw ports for l3 agent. Query routers with the router_ids. The gateway ports, if any, will be queried too. l3 agent has an option to deal with only one router id. In addition, when we need to notify the agent the data about only one router (when modification of router, its interfaces, gw_port and floatingips), we will have router_ids. @param router_ids: the list of router ids which we want to query. if it is None, all of routers will be queried. @return: a list of dicted routers with dicted gw_port populated if any """ filters = {'id': router_ids} if router_ids else {} if active is not None: filters['admin_state_up'] = [active] router_dicts = self.get_routers(context, filters=filters) gw_port_ids = [] if not router_dicts: return [] for router_dict in router_dicts: gw_port_id = router_dict['gw_port_id'] if gw_port_id: gw_port_ids.append(gw_port_id) gw_ports = [] if gw_port_ids: gw_ports = self.get_sync_gw_ports(context, gw_port_ids) gw_port_id_gw_port_dict = {} for gw_port in gw_ports: gw_port_id_gw_port_dict[gw_port['id']] = gw_port for router_dict in router_dicts: gw_port_id = router_dict['gw_port_id'] if gw_port_id: router_dict['gw_port'] = gw_port_id_gw_port_dict[gw_port_id] return router_dicts def _get_sync_floating_ips(self, context, router_ids): """Query floating_ips that relate to list of router_ids.""" if not router_ids: return [] return self.get_floatingips(context, {'router_id': router_ids}) def get_sync_gw_ports(self, context, gw_port_ids): if not gw_port_ids: return [] filters = {'id': gw_port_ids} gw_ports = self.get_ports(context, filters) if gw_ports: self._populate_subnet_for_ports(context, gw_ports) return gw_ports def get_sync_interfaces(self, context, router_ids, device_owner=DEVICE_OWNER_ROUTER_INTF): """Query router interfaces that relate to list of router_ids.""" if not router_ids: return [] filters = {'device_id': router_ids, 'device_owner': [device_owner]} interfaces = self.get_ports(context, filters) if interfaces: self._populate_subnet_for_ports(context, interfaces) return interfaces def _populate_subnet_for_ports(self, context, ports): """Populate ports with subnet. These ports already have fixed_ips populated. """ if not ports: return subnet_id_ports_dict = {} for port in ports: fixed_ips = port.get('fixed_ips', []) if len(fixed_ips) > 1: LOG.info(_("Ignoring multiple IPs on router port %s"), port['id']) continue elif not fixed_ips: # Skip ports without IPs, which can occur if a subnet # attached to a router is deleted LOG.info(_("Skipping port %s as no IP is configure on it"), port['id']) continue fixed_ip = fixed_ips[0] my_ports = subnet_id_ports_dict.get(fixed_ip['subnet_id'], []) my_ports.append(port) subnet_id_ports_dict[fixed_ip['subnet_id']] = my_ports if not subnet_id_ports_dict: return filters = {'id': subnet_id_ports_dict.keys()} fields = ['id', 'cidr', 'gateway_ip'] subnet_dicts = self.get_subnets(context, filters, fields) for subnet_dict in subnet_dicts: ports = subnet_id_ports_dict.get(subnet_dict['id'], []) for port in ports: # TODO(gongysh) stash the subnet into fixed_ips # to make the payload smaller. port['subnet'] = {'id': subnet_dict['id'], 'cidr': subnet_dict['cidr'], 'gateway_ip': subnet_dict['gateway_ip']} def _process_sync_data(self, routers, interfaces, floating_ips): routers_dict = {} for router in routers: routers_dict[router['id']] = router for floating_ip in floating_ips: router = routers_dict.get(floating_ip['router_id']) if router: router_floatingips = router.get(l3_constants.FLOATINGIP_KEY, []) router_floatingips.append(floating_ip) router[l3_constants.FLOATINGIP_KEY] = router_floatingips for interface in interfaces: router = routers_dict.get(interface['device_id']) if router: router_interfaces = router.get(l3_constants.INTERFACE_KEY, []) router_interfaces.append(interface) router[l3_constants.INTERFACE_KEY] = router_interfaces return routers_dict.values() def get_sync_data(self, context, router_ids=None, active=None): """Query routers and their related floating_ips, interfaces.""" with context.session.begin(subtransactions=True): routers = self._get_sync_routers(context, router_ids=router_ids, active=active) router_ids = [router['id'] for router in routers] floating_ips = self._get_sync_floating_ips(context, router_ids) interfaces = self.get_sync_interfaces(context, router_ids) return self._process_sync_data(routers, interfaces, floating_ips) def get_external_network_id(self, context): nets = self.get_networks(context, {'router:external': [True]}) if len(nets) > 1: raise q_exc.TooManyExternalNetworks() else: return nets[0]['id'] if nets else None
# Poloniex API wrapper tested on Python 2.7.6 & 3.4.3 # https://github.com/s4w3d0ff/python-poloniex # BTC: 1A7K4kgXLSSzvDRjvoGwomvhrNU4CKezEp # TODO: # [x] PEP8ish # [ ] Add better logger access # [x] Improve logging output # [ ] Add Push Api application wrapper # # Copyright (C) 2016 https://github.com/s4w3d0ff # # 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 2 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, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # python 2 try: from urllib import urlencode as _urlencode str = unicode # python 3 except: from urllib.parse import urlencode as _urlencode from datetime import datetime from functools import wraps as _wraps from hashlib import sha512 as _sha512 from hmac import new as _new from itertools import chain as _chain from json import loads as _loads from time import sleep from requests import get as _get from requests import post as _post from ..exceptions import * # local from .coach import Coach from ..utils import Logger # # logger # logger = logging.getLogger(__name__) # logger = Logger retryDelays = (0, 2, 5, 5, 5, 5, 30, 30, 30) # Possible Commands PUBLIC_COMMANDS = [ 'returnTicker', 'return24hVolume', 'returnOrderBook', 'marketTradeHist', 'returnChartData', 'returnCurrencies', 'returnLoanOrders'] PRIVATE_COMMANDS = [ 'returnBalances', 'returnCompleteBalances', 'returnDepositAddresses', 'generateNewAddress', 'returnDepositsWithdrawals', 'returnOpenOrders', 'returnTradeHistory', 'returnAvailableAccountBalances', 'returnTradableBalances', 'returnOpenLoanOffers', 'returnOrderTrades', 'returnActiveLoans', 'returnLendingHistory', 'createLoanOffer', 'cancelLoanOffer', 'toggleAutoRenew', 'buy', 'sell', 'cancelOrder', 'moveOrder', 'withdraw', 'returnFeeInfo', 'transferBalance', 'returnMarginAccountSummary', 'marginBuy', 'marginSell', 'getMarginPosition', 'closeMarginPosition'] # class ExchangeError(Exception): # """ Exception for handling poloniex api errors """ # pass class Poloniex(object): """The Poloniex Object!""" def __init__( self, key=False, secret=False, timeout=None, coach=None, jsonNums=False): """ key = str api key supplied by Poloniex secret = str secret hash supplied by Poloniex timeout = int time in sec to wait for an api response (otherwise 'requests.exceptions.Timeout' is raised) coach = bool to indicate if the api coach should be used jsonNums = datatype to use when parsing json ints and floats # Time Placeholders: (MONTH == 30*DAYS) self.MINUTE, self.HOUR, self.DAY, self.WEEK, self.MONTH, self.YEAR """ # set logger and coach self.coach = coach if not self.coach: self.coach = Coach() # create nonce self._nonce = int("{:.6f}".format(datetime.utcnow().timestamp()).replace('.', '')) # json number datatypes self.jsonNums = jsonNums # grab keys, set timeout self.key, self.secret, self.timeout = key, secret, timeout # set time labels self.MINUTE, self.HOUR, self.DAY = 60, 60 * 60, 60 * 60 * 24 self.WEEK, self.MONTH = self.DAY * 7, self.DAY * 30 self.YEAR = self.DAY * 365 # -----------------Meat and Potatos--------------------------------------- def _retry(func): """ retry decorator """ @_wraps(func) def retrying(*args, **kwargs): problems = [] for delay in _chain(retryDelays, [None]): try: # attempt call return func(*args, **kwargs) # we need to try again except RequestException as problem: problems.append(problem) if delay is None: Logger.debug(func, problems) raise MaxRetriesException( 'retryDelays exhausted ' + str(problem)) else: # log exception and wait Logger.debug(func, problem) Logger.info(func, "-- delaying for %ds" % delay) sleep(delay) return retrying @_retry def __call__(self, command, args={}): """ Main Api Function - encodes and sends <command> with optional [args] to Poloniex api - raises 'poloniex.ExchangeError' if an api key or secret is missing (and the command is 'private'), if the <command> is not valid, or if an error is returned from poloniex.com - returns decoded json api message """ # get command type cmdType = self._checkCmd(command) # pass the command args['command'] = command payload = {} # add timeout payload['timeout'] = self.timeout # private? if cmdType == 'Private': payload['url'] = 'https://poloniex.com/tradingApi' # wait for coach if self.coach: self.coach.wait() # set nonce args['nonce'] = self.nonce # add args to payload payload['data'] = args # sign data with our Secret sign = _new( self.secret.encode('utf-8'), _urlencode(args).encode('utf-8'), _sha512) # add headers to payload payload['headers'] = {'Sign': sign.hexdigest(), 'Key': self.key} # send the call ret = _post(**payload) # return data return self._handleReturned(ret.text) # public? if cmdType == 'Public': # encode url payload['url'] = 'https://poloniex.com/public?' + _urlencode(args) # wait for coach if self.coach: self.coach.wait() # send the call ret = _get(**payload) # return data return self._handleReturned(ret.text) @property def nonce(self): """ Increments the nonce""" self._nonce += 33 return self._nonce @nonce.setter def nonce(self, nonce): self._nonce = nonce def _checkCmd(self, command): """ Returns if the command is private of public, raises ExchangeError if command is not found """ global PUBLIC_COMMANDS, PRIVATE_COMMANDS if command in PRIVATE_COMMANDS: # check for keys if not self.key or not self.secret: raise ExchangeError("An Api Key and Secret needed!") return 'Private' if command in PUBLIC_COMMANDS: return 'Public' raise ExchangeError("Invalid Command!: %s" % command) def _handleReturned(self, data): """ Handles returned data from poloniex""" try: if not self.jsonNums: out = _loads(data, parse_float=str) else: out = _loads(data, parse_float=self.jsonNums, parse_int=self.jsonNums) except: Logger.debug(Poloniex._handleReturned, data) raise ExchangeError('Invalid json response returned') # check if poloniex returned an error if 'error' in out: # update nonce if we fell behind if "Nonce must be greater" in out['error']: self._nonce = int( out['error'].split('.')[0].split()[-1]) # raise RequestException so we try again raise RequestException('ExchangeError ' + out['error']) # conncetion timeout from poloniex if "please try again" in out['error'].lower(): # raise RequestException so we try again raise RequestException('ExchangeError ' + out['error']) # raise other poloniex errors, ending retry loop else: raise ExchangeError(out['error']) return out # --PUBLIC COMMANDS------------------------------------------------------- def returnTicker(self): """ Returns the ticker for all markets. """ return self.__call__('returnTicker') def return24hVolume(self): """ Returns the 24-hour volume for all markets, plus totals for primary currencies. """ return self.__call__('return24hVolume') def returnOrderBook(self, currencyPair='all', depth=20): """ Returns the order book for a given market as well as a sequence number for use with the Push API and an indicator specifying whether the market is frozen. (defaults to 'all' markets, at a 'depth' of 20 orders) """ return self.__call__('returnOrderBook', { 'currencyPair': str(currencyPair).upper(), 'depth': str(depth) }) @_retry def marketTradeHist(self, currencyPair, start=False, end=False): """ Returns the past 200 trades for a given market, or up to 50,000 trades between a range specified in UNIX timestamps by the "start" and "end" parameters. """ if self.coach: self.coach.wait() args = {'command': 'returnTradeHistory', 'currencyPair': str(currencyPair).upper()} if start: args['start'] = start if end: args['end'] = end ret = _get( 'https://poloniex.com/public?' + _urlencode(args), timeout=self.timeout) # decode json return self._handleReturned(ret.text) def returnChartData(self, currencyPair, period=False, start=False, end=False): """ Returns candlestick chart data. Parameters are "currencyPair", "period" (candlestick period in seconds; valid values are 300, 900, 1800, 7200, 14400, and 86400), "start", and "end". "Start" and "end" are given in UNIX timestamp format and used to specify the date range for the data returned (default date range is start='1 day ago' to end='now') """ if period not in [300, 900, 1800, 7200, 14400, 86400]: raise ExchangeError("%s invalid candle period" % str(period)) if not start: start = datetime.utcnow().timestamp() - self.DAY if not end: end = datetime.utcnow().timestamp() return self.__call__('returnChartData', { 'currencyPair': str(currencyPair).upper(), 'period': str(period), 'start': str(start), 'end': str(end) }) def returnCurrencies(self): """ Returns information about all currencies. """ return self.__call__('returnCurrencies') def returnLoanOrders(self, currency): """ Returns the list of loan offers and demands for a given currency, specified by the "currency" parameter """ return self.__call__('returnLoanOrders', { 'currency': str(currency).upper()}) # --PRIVATE COMMANDS------------------------------------------------------ def returnBalances(self): """ Returns all of your available balances.""" return self.__call__('returnBalances') def returnCompleteBalances(self, account='all'): """ Returns all of your balances, including available balance, balance on orders, and the estimated BTC value of your balance. By default, this call is limited to your exchange account; set the "account" parameter to "all" to include your margin and lending accounts. """ return self.__call__('returnCompleteBalances', {'account': str(account)}) def returnDepositAddresses(self): """ Returns all of your deposit addresses. """ return self.__call__('returnDepositAddresses') def generateNewAddress(self, currency): """ Generates a new deposit address for the currency specified by the "currency" parameter. """ return self.__call__('generateNewAddress', { 'currency': currency}) def returnDepositsWithdrawals(self, start=False, end=False): """ Returns your deposit and withdrawal history within a range, specified by the "start" and "end" parameters, both of which should be given as UNIX timestamps. (defaults to 1 month)""" if not start: start = datetime.utcnow().timestamp() - self.MONTH if not end: end = datetime.utcnow().timestamp() args = {'start': str(start), 'end': str(end)} return self.__call__('returnDepositsWithdrawals', args) def returnOpenOrders(self, currencyPair='all'): """ Returns your open orders for a given market, specified by the "currencyPair" parameter, e.g. "BTC_XCP". Set "currencyPair" to "all" to return open orders for all markets. """ return self.__call__('returnOpenOrders', { 'currencyPair': str(currencyPair).upper()}) def returnTradeHistory(self, currencyPair='all', start=False, end=False): """ Returns your trade history for a given market, specified by the "currencyPair" parameter. You may specify "all" as the currencyPair to receive your trade history for all markets. You may optionally specify a range via "start" and/or "end" POST parameters, given in UNIX timestamp format; if you do not specify a range, it will be limited to one day. """ args = {'currencyPair': str(currencyPair).upper()} if start: args['start'] = start if end: args['end'] = end return self.__call__('returnTradeHistory', args) def returnOrderTrades(self, orderNumber): """ Returns all trades involving a given order, specified by the "orderNumber" parameter. If no trades for the order have occurred or you specify an order that does not belong to you, you will receive an error. """ return self.__call__('returnOrderTrades', { 'orderNumber': str(orderNumber)}) def buy(self, currencyPair, rate, amount, orderType=False): """ Places a limit buy order in a given market. Required parameters are "currencyPair", "rate", and "amount". You may optionally set "orderType" to "fillOrKill", "immediateOrCancel" or "postOnly". A fill-or-kill order will either fill in its entirety or be completely aborted. An immediate-or-cancel order can be partially or completely filled, but any portion of the order that cannot be filled immediately will be canceled rather than left on the order book. A post-only order will only be placed if no portion of it fills immediately; this guarantees you will never pay the taker fee on any part of the order that fills. If successful, the method will return the order number. """ args = { 'currencyPair': str(currencyPair).upper(), 'rate': str(rate), 'amount': str(amount), } # order type specified? if orderType: possTypes = ['fillOrKill', 'immediateOrCancel', 'postOnly'] # check type if not orderType in possTypes: raise ExchangeError('Invalid orderType') args[orderType] = 1 return self.__call__('buy', args) def sell(self, currencyPair, rate, amount, orderType=False): """ Places a sell order in a given market. Parameters and output are the same as for the buy method. """ args = { 'currencyPair': str(currencyPair).upper(), 'rate': str(rate), 'amount': str(amount), } # order type specified? if orderType: possTypes = ['fillOrKill', 'immediateOrCancel', 'postOnly'] # check type if not orderType in possTypes: raise ExchangeError('Invalid orderType') args[orderType] = 1 return self.__call__('sell', args) def cancelOrder(self, orderNumber): """ Cancels an order you have placed in a given market. Required parameter is "orderNumber". """ return self.__call__('cancelOrder', {'orderNumber': str(orderNumber)}) def moveOrder(self, orderNumber, rate, amount=False, orderType=False): """ Cancels an order and places a new one of the same type in a single atomic transaction, meaning either both operations will succeed or both will fail. Required parameters are "orderNumber" and "rate"; you may optionally specify "amount" if you wish to change the amount of the new order. "postOnly" or "immediateOrCancel" may be specified as the "orderType" param for exchange orders, but will have no effect on margin orders. """ args = { 'orderNumber': str(orderNumber), 'rate': str(rate) } if amount: args['amount'] = str(amount) # order type specified? if orderType: possTypes = ['immediateOrCancel', 'postOnly'] # check type if not orderType in possTypes: raise ExchangeError('Invalid orderType: %s' % str(orderType)) args[orderType] = 1 return self.__call__('moveOrder', args) def withdraw(self, currency, amount, address, paymentId=False): """ Immediately places a withdrawal for a given currency, with no email confirmation. In order to use this method, the withdrawal privilege must be enabled for your API key. Required parameters are "currency", "amount", and "address". For XMR withdrawals, you may optionally specify "paymentId". """ args = { 'currency': str(currency).upper(), 'amount': str(amount), 'address': str(address) } if paymentId: args['paymentId'] = str(paymentId) return self.__call__('withdraw', args) def returnFeeInfo(self): """ If you are enrolled in the maker-taker fee schedule, returns your current trading fees and trailing 30-day volume in BTC. This information is updated once every 24 hours. """ return self.__call__('returnFeeInfo') def returnAvailableAccountBalances(self, account=False): """ Returns your balances sorted by account. You may optionally specify the "account" parameter if you wish to fetch only the balances of one account. Please note that balances in your margin account may not be accessible if you have any open margin positions or orders. """ if account: return self.__call__('returnAvailableAccountBalances', {'account': account}) return self.__call__('returnAvailableAccountBalances') def returnTradableBalances(self): """ Returns your current tradable balances for each currency in each market for which margin trading is enabled. Please note that these balances may vary continually with market conditions. """ return self.__call__('returnTradableBalances') def transferBalance(self, currency, amount, fromAccount, toAccount, confirmed=False): """ Transfers funds from one account to another (e.g. from your exchange account to your margin account). Required parameters are "currency", "amount", "fromAccount", and "toAccount" """ args = { 'currency': str(currency).upper(), 'amount': str(amount), 'fromAccount': str(fromAccount), 'toAccount': str(toAccount) } if confirmed: args['confirmed'] = 1 return self.__call__('transferBalance', args) def returnMarginAccountSummary(self): """ Returns a summary of your entire margin account. This is the same information you will find in the Margin Account section of the Margin Trading page, under the Markets list """ return self.__call__('returnMarginAccountSummary') def marginBuy(self, currencyPair, rate, amount, lendingRate=2): """ Places a margin buy order in a given market. Required parameters are "currencyPair", "rate", and "amount". You may optionally specify a maximum lending rate using the "lendingRate" parameter (defaults to 2). If successful, the method will return the order number and any trades immediately resulting from your order. """ return self.__call__('marginBuy', { 'currencyPair': str(currencyPair).upper(), 'rate': str(rate), 'amount': str(amount), 'lendingRate': str(lendingRate) }) def marginSell(self, currencyPair, rate, amount, lendingRate=2): """ Places a margin sell order in a given market. Parameters and output are the same as for the marginBuy method. """ return self.__call__('marginSell', { 'currencyPair': str(currencyPair).upper(), 'rate': str(rate), 'amount': str(amount), 'lendingRate': str(lendingRate) }) def getMarginPosition(self, currencyPair='all'): """ Returns information about your margin position in a given market, specified by the "currencyPair" parameter. You may set "currencyPair" to "all" if you wish to fetch all of your margin positions at once. If you have no margin position in the specified market, "type" will be set to "none". "liquidationPrice" is an estimate, and does not necessarily represent the price at which an actual forced liquidation will occur. If you have no liquidation price, the value will be -1. (defaults to 'all')""" return self.__call__('getMarginPosition', { 'currencyPair': str(currencyPair).upper()}) def closeMarginPosition(self, currencyPair): """ Closes your margin position in a given market (specified by the "currencyPair" parameter) using a market order. This call will also return success if you do not have an open position in the specified market. """ return self.__call__( 'closeMarginPosition', {'currencyPair': str(currencyPair).upper()}) def createLoanOffer(self, currency, amount, lendingRate, autoRenew=0, duration=2): """ Creates a loan offer for a given currency. Required parameters are "currency", "amount", "lendingRate", "duration" (num of days, defaults to 2), "autoRenew" (0 or 1, defaults to 0 'off'). """ return self.__call__('createLoanOffer', { 'currency': str(currency).upper(), 'amount': str(amount), 'duration': str(duration), 'autoRenew': str(autoRenew), 'lendingRate': str(lendingRate) }) def cancelLoanOffer(self, orderNumber): """ Cancels a loan offer specified by the "orderNumber" parameter. """ return self.__call__( 'cancelLoanOffer', {'orderNumber': str(orderNumber)}) def returnOpenLoanOffers(self): """ Returns your open loan offers for each currency. """ return self.__call__('returnOpenLoanOffers') def returnActiveLoans(self): """ Returns your active loans for each currency.""" return self.__call__('returnActiveLoans') def returnLendingHistory(self, start=False, end=False, limit=False): """ Returns your lending history within a time range specified by the "start" and "end" parameters as UNIX timestamps. "limit" may also be specified to limit the number of rows returned. (defaults to the last months history)""" if not start: start = datetime.utcnow().timestamp() - self.MONTH if not end: end = datetime.utcnow().timestamp() args = {'start': str(start), 'end': str(end)} if limit: args['limit'] = str(limit) return self.__call__('returnLendingHistory', args) def toggleAutoRenew(self, orderNumber): """ Toggles the autoRenew setting on an active loan, specified by the "orderNumber" parameter. If successful, "message" will indicate the new autoRenew setting. """ return self.__call__( 'toggleAutoRenew', {'orderNumber': str(orderNumber)})
from __future__ import print_function import itertools import numba.unittest_support as unittest from numba.controlflow import CFGraph, ControlFlowAnalysis from numba.compiler import compile_isolated, Flags from numba import types, errors from numba.bytecode import FunctionIdentity, ByteCode from numba.utils import IS_PY3 from .support import TestCase, tag enable_pyobj_flags = Flags() enable_pyobj_flags.set("enable_pyobject") forceobj_flags = Flags() forceobj_flags.set("force_pyobject") no_pyobj_flags = Flags() no_pyobj_flags.set("nrt") def for_loop_usecase1(x, y): result = 0 for i in range(x): result += i return result def for_loop_usecase2(x, y): result = 0 for i, j in enumerate(range(x, y, -1)): result += i * j return result def for_loop_usecase3(x, y): result = 0 lst = [x, y] for i in lst: result += i return result def for_loop_usecase4(x, y): result = 0 for i in range(10): for j in range(10): result += 1 return result def for_loop_usecase5(x, y): result = 0 for i in range(x): result += 1 if result > y: break return result def for_loop_usecase6(x, y): result = 0 for i in range(x): if i > y: continue result += 1 return result def for_loop_usecase7(x, y): for i in range(x): x = 0 for j in range(x): return 1 else: pass return 0 def for_loop_usecase8(x, y): result = 0 for i in range(x, y, y - x + 1): result += 1 return result def for_loop_usecase9(x, y): z = 0 for i in range(x): x = 0 for j in range(x): if j == x / 2: z += j break else: z += y return z def for_loop_usecase10(x, y): for i in range(x): if i == y: z = y break else: z = i * 2 return z def while_loop_usecase1(x, y): result = 0 i = 0 while i < x: result += i i += 1 return result def while_loop_usecase2(x, y): result = 0 while result != x: result += 1 return result def while_loop_usecase3(x, y): result = 0 i = 0 j = 0 while i < x: while j < y: result += i + j i += 1 j += 1 return result def while_loop_usecase4(x, y): result = 0 while True: result += 1 if result > x: break return result def while_loop_usecase5(x, y): result = 0 while result < x: if result > y: result += 2 continue result += 1 return result def ifelse_usecase1(x, y): if x > 0: pass elif y > 0: pass else: pass return True def ifelse_usecase2(x, y): if x > y: return 1 elif x == 0 or y == 0: return 2 else: return 3 def ifelse_usecase3(x, y): if x > 0: if y > 0: return 1 elif y < 0: return 1 else: return 0 elif x < 0: return 1 else: return 0 def ifelse_usecase4(x, y): if x == y: return 1 def ternary_ifelse_usecase1(x, y): return True if x > y else False def double_infinite_loop(x, y): L = x i = y while True: while True: if i == L - 1: break i += 1 i += 1 if i >= L: break return i, L def try_except_usecase(): try: pass except Exception: pass class TestFlowControl(TestCase): def run_test(self, pyfunc, x_operands, y_operands, flags=enable_pyobj_flags): cr = compile_isolated(pyfunc, (types.intp, types.intp), flags=flags) cfunc = cr.entry_point for x, y in itertools.product(x_operands, y_operands): pyerr = None cerr = None try: pyres = pyfunc(x, y) except Exception as e: pyerr = e try: cres = cfunc(x, y) except Exception as e: if pyerr is None: raise cerr = e self.assertEqual(type(pyerr), type(cerr)) else: if pyerr is not None: self.fail("Invalid for pure-python but numba works\n" + pyerr) self.assertEqual(pyres, cres) def test_for_loop1(self, flags=enable_pyobj_flags): self.run_test(for_loop_usecase1, [-10, 0, 10], [0], flags=flags) @tag('important') def test_for_loop1_npm(self): self.test_for_loop1(flags=no_pyobj_flags) def test_for_loop2(self, flags=enable_pyobj_flags): self.run_test(for_loop_usecase2, [-10, 0, 10], [-10, 0, 10], flags=flags) @tag('important') def test_for_loop2_npm(self): self.test_for_loop2(flags=no_pyobj_flags) def test_for_loop3(self, flags=enable_pyobj_flags): """ List requires pyobject """ self.run_test(for_loop_usecase3, [1], [2], flags=flags) def test_for_loop3_npm(self): self.test_for_loop3(flags=no_pyobj_flags) def test_for_loop4(self, flags=enable_pyobj_flags): self.run_test(for_loop_usecase4, [10], [10], flags=flags) @tag('important') def test_for_loop4_npm(self): self.test_for_loop4(flags=no_pyobj_flags) def test_for_loop5(self, flags=enable_pyobj_flags): self.run_test(for_loop_usecase5, [100], [50], flags=flags) @tag('important') def test_for_loop5_npm(self): self.test_for_loop5(flags=no_pyobj_flags) def test_for_loop6(self, flags=enable_pyobj_flags): self.run_test(for_loop_usecase6, [100], [50], flags=flags) @tag('important') def test_for_loop6_npm(self): self.test_for_loop6(flags=no_pyobj_flags) def test_for_loop7(self, flags=enable_pyobj_flags): self.run_test(for_loop_usecase7, [5], [0], flags=flags) @tag('important') def test_for_loop7_npm(self): self.test_for_loop7(flags=no_pyobj_flags) def test_for_loop8(self, flags=enable_pyobj_flags): self.run_test(for_loop_usecase8, [0, 1], [0, 2, 10], flags=flags) @tag('important') def test_for_loop8_npm(self): self.test_for_loop8(flags=no_pyobj_flags) def test_for_loop9(self, flags=enable_pyobj_flags): self.run_test(for_loop_usecase9, [0, 1], [0, 2, 10], flags=flags) @tag('important') def test_for_loop9_npm(self): self.test_for_loop9(flags=no_pyobj_flags) def test_for_loop10(self, flags=enable_pyobj_flags): self.run_test(for_loop_usecase10, [5], [2, 7], flags=flags) @tag('important') def test_for_loop10_npm(self): self.test_for_loop10(flags=no_pyobj_flags) def test_while_loop1(self, flags=enable_pyobj_flags): self.run_test(while_loop_usecase1, [10], [0], flags=flags) def test_while_loop1_npm(self): self.test_while_loop1(flags=no_pyobj_flags) def test_while_loop2(self, flags=enable_pyobj_flags): self.run_test(while_loop_usecase2, [10], [0], flags=flags) def test_while_loop2_npm(self): self.test_while_loop2(flags=no_pyobj_flags) def test_while_loop3(self, flags=enable_pyobj_flags): self.run_test(while_loop_usecase3, [10], [10], flags=flags) @tag('important') def test_while_loop3_npm(self): self.test_while_loop3(flags=no_pyobj_flags) def test_while_loop4(self, flags=enable_pyobj_flags): self.run_test(while_loop_usecase4, [10], [0], flags=flags) @tag('important') def test_while_loop4_npm(self): self.test_while_loop4(flags=no_pyobj_flags) def test_while_loop5(self, flags=enable_pyobj_flags): self.run_test(while_loop_usecase5, [0, 5, 10], [0, 5, 10], flags=flags) @tag('important') def test_while_loop5_npm(self): self.test_while_loop5(flags=no_pyobj_flags) def test_ifelse1(self, flags=enable_pyobj_flags): self.run_test(ifelse_usecase1, [-1, 0, 1], [-1, 0, 1], flags=flags) def test_ifelse1_npm(self): self.test_ifelse1(flags=no_pyobj_flags) def test_ifelse2(self, flags=enable_pyobj_flags): self.run_test(ifelse_usecase2, [-1, 0, 1], [-1, 0, 1], flags=flags) @tag('important') def test_ifelse2_npm(self): self.test_ifelse2(flags=no_pyobj_flags) def test_ifelse3(self, flags=enable_pyobj_flags): self.run_test(ifelse_usecase3, [-1, 0, 1], [-1, 0, 1], flags=flags) @tag('important') def test_ifelse3_npm(self): self.test_ifelse3(flags=no_pyobj_flags) def test_ifelse4(self, flags=enable_pyobj_flags): self.run_test(ifelse_usecase4, [-1, 0, 1], [-1, 0, 1], flags=flags) @tag('important') def test_ifelse4_npm(self): self.test_ifelse4(flags=no_pyobj_flags) def test_ternary_ifelse1(self, flags=enable_pyobj_flags): self.run_test(ternary_ifelse_usecase1, [-1, 0, 1], [-1, 0, 1], flags=flags) @tag('important') def test_ternary_ifelse1_npm(self): self.test_ternary_ifelse1(flags=no_pyobj_flags) def test_double_infinite_loop(self, flags=enable_pyobj_flags): self.run_test(double_infinite_loop, [10], [0], flags=flags) def test_double_infinite_loop_npm(self): self.test_double_infinite_loop(flags=no_pyobj_flags) def test_try_except_raises(self): pyfunc = try_except_usecase for f in [no_pyobj_flags, enable_pyobj_flags]: with self.assertRaises(errors.UnsupportedError) as e: compile_isolated(pyfunc, (), flags=f) msg = "Use of unsupported opcode (SETUP_EXCEPT) found" self.assertIn(msg, str(e.exception)) class TestCFGraph(TestCase): """ Test the numba.controlflow.CFGraph class. """ def from_adj_list(self, d, entry_point=0): """ Build a CFGraph class from a dict of adjacency lists. """ g = CFGraph() # Need to add all nodes before adding edges for node in d: g.add_node(node) for node, dests in d.items(): for dest in dests: g.add_edge(node, dest) return g def loopless1(self): """ A simple CFG corresponding to the following code structure: c = (... if ... else ...) + ... return b + c """ g = self.from_adj_list({0: [18, 12], 12: [21], 18: [21], 21: []}) g.set_entry_point(0) g.process() return g def loopless1_dead_nodes(self): """ Same as loopless1(), but with added dead blocks (some of them in a loop). """ g = self.from_adj_list( {0: [18, 12], 12: [21], 18: [21], 21: [], 91: [12, 0], 92: [91, 93], 93: [92], 94: [], }) g.set_entry_point(0) g.process() return g def loopless2(self): """ A loopless CFG corresponding to the following code structure: c = (... if ... else ...) + ... if c: return ... else: return ... Note there are two exit points, and the entry point has been changed to a non-zero value. """ g = self.from_adj_list( {99: [18, 12], 12: [21], 18: [21], 21: [42, 34], 34: [], 42: []}) g.set_entry_point(99) g.process() return g def multiple_loops(self): """ A CFG with multiple nested loops: for y in b: for x in a: # This loop has two back edges if b: continue else: continue for z in c: if z: return ... """ g = self.from_adj_list({0: [7], 7: [10, 60], 10: [13], 13: [20], 20: [56, 23], 23: [32, 44], 32: [20], 44: [20], 56: [57], 57: [7], 60: [61], 61: [68], 68: [87, 71], 71: [80, 68], 80: [], 87: [88], 88: []} ) g.set_entry_point(0) g.process() return g def multiple_exits(self): """ A CFG with three loop exits, one of which is also a function exit point, and another function exit point: for x in a: if a: return b elif b: break return c """ g = self.from_adj_list( {0: [7], 7: [10, 36], 10: [19, 23], 19: [], 23: [29, 7], 29: [37], 36: [37], 37: [] }) g.set_entry_point(0) g.process() return g def infinite_loop1(self): """ A CFG with a infinite loop and an alternate exit point: if c: return while True: if a: ... else: ... """ g = self.from_adj_list( {0: [10, 6], 6: [], 10: [13], 13: [26, 19], 19: [13], 26: [13]}) g.set_entry_point(0) g.process() return g def infinite_loop2(self): """ A CFG with no exit point at all: while True: if a: ... else: ... """ g = self.from_adj_list({0: [3], 3: [16, 9], 9: [3], 16: [3]}) g.set_entry_point(0) g.process() return g def test_simple_properties(self): g = self.loopless1() self.assertEqual(sorted(g.successors(0)), [(12, None), (18, None)]) self.assertEqual(sorted(g.successors(21)), []) self.assertEqual(sorted(g.predecessors(0)), []) self.assertEqual(sorted(g.predecessors(21)), [(12, None), (18, None)]) def test_exit_points(self): g = self.loopless1() self.assertEqual(sorted(g.exit_points()), [21]) g = self.loopless1_dead_nodes() self.assertEqual(sorted(g.exit_points()), [21]) g = self.loopless2() self.assertEqual(sorted(g.exit_points()), [34, 42]) g = self.multiple_loops() self.assertEqual(sorted(g.exit_points()), [80, 88]) g = self.infinite_loop1() self.assertEqual(sorted(g.exit_points()), [6]) g = self.infinite_loop2() self.assertEqual(sorted(g.exit_points()), []) g = self.multiple_exits() self.assertEqual(sorted(g.exit_points()), [19, 37]) def test_dead_nodes(self): g = self.loopless1() self.assertEqual(len(g.dead_nodes()), 0) self.assertEqual(sorted(g.nodes()), [0, 12, 18, 21]) g = self.loopless2() self.assertEqual(len(g.dead_nodes()), 0) self.assertEqual(sorted(g.nodes()), [12, 18, 21, 34, 42, 99]) g = self.multiple_loops() self.assertEqual(len(g.dead_nodes()), 0) g = self.infinite_loop1() self.assertEqual(len(g.dead_nodes()), 0) g = self.multiple_exits() self.assertEqual(len(g.dead_nodes()), 0) # Only this example has dead nodes g = self.loopless1_dead_nodes() self.assertEqual(sorted(g.dead_nodes()), [91, 92, 93, 94]) self.assertEqual(sorted(g.nodes()), [0, 12, 18, 21]) def test_descendents(self): g = self.loopless2() d = g.descendents(34) self.assertEqual(sorted(d), []) d = g.descendents(42) self.assertEqual(sorted(d), []) d = g.descendents(21) self.assertEqual(sorted(d), [34, 42]) d = g.descendents(99) self.assertEqual(sorted(d), [12, 18, 21, 34, 42]) g = self.infinite_loop1() d = g.descendents(26) self.assertEqual(sorted(d), []) d = g.descendents(19) self.assertEqual(sorted(d), []) d = g.descendents(13) self.assertEqual(sorted(d), [19, 26]) d = g.descendents(10) self.assertEqual(sorted(d), [13, 19, 26]) d = g.descendents(6) self.assertEqual(sorted(d), []) d = g.descendents(0) self.assertEqual(sorted(d), [6, 10, 13, 19, 26]) def test_topo_order(self): g = self.loopless1() self.assertIn(g.topo_order(), ([0, 12, 18, 21], [0, 18, 12, 21])) g = self.loopless2() self.assertIn(g.topo_order(), ([99, 18, 12, 21, 34, 42], [99, 12, 18, 21, 34, 42])) g = self.infinite_loop2() self.assertIn(g.topo_order(), ([0, 3, 9, 16], [0, 3, 16, 9])) g = self.infinite_loop1() self.assertIn(g.topo_order(), ([0, 6, 10, 13, 19, 26], [0, 6, 10, 13, 26, 19], [0, 10, 13, 19, 26, 6], [0, 10, 13, 26, 19, 6])) def test_topo_sort(self): def check_topo_sort(nodes, expected): self.assertIn(list(g.topo_sort(nodes)), expected) self.assertIn(list(g.topo_sort(nodes[::-1])), expected) self.assertIn(list(g.topo_sort(nodes, reverse=True))[::-1], expected) self.assertIn(list(g.topo_sort(nodes[::-1], reverse=True))[::-1], expected) self.random.shuffle(nodes) self.assertIn(list(g.topo_sort(nodes)), expected) self.assertIn(list(g.topo_sort(nodes, reverse=True))[::-1], expected) g = self.loopless2() check_topo_sort([21, 99, 12, 34], ([99, 12, 21, 34],)) # NOTE: topo_sort() is not stable check_topo_sort([18, 12, 42, 99], ([99, 12, 18, 42], [99, 18, 12, 42])) g = self.multiple_exits() check_topo_sort([19, 10, 7, 36], ([7, 10, 19, 36], [7, 10, 36, 19], [7, 36, 10, 19])) def check_dominators(self, got, expected): self.assertEqual(sorted(got), sorted(expected)) for node in sorted(got): self.assertEqual(sorted(got[node]), sorted(expected[node]), "mismatch for %r" % (node,)) def test_dominators_loopless(self): def eq_(d, l): self.assertEqual(sorted(doms[d]), l) for g in [self.loopless1(), self.loopless1_dead_nodes()]: doms = g.dominators() eq_(0, [0]) eq_(12, [0, 12]) eq_(18, [0, 18]) eq_(21, [0, 21]) g = self.loopless2() doms = g.dominators() eq_(99, [99]) eq_(12, [12, 99]) eq_(18, [18, 99]) eq_(21, [21, 99]) eq_(34, [21, 34, 99]) eq_(42, [21, 42, 99]) def test_dominators_loops(self): g = self.multiple_exits() doms = g.dominators() self.check_dominators(doms, {0: [0], 7: [0, 7], 10: [0, 7, 10], 19: [0, 7, 10, 19], 23: [0, 7, 10, 23], 29: [0, 7, 10, 23, 29], 36: [0, 7, 36], 37: [0, 7, 37], }) g = self.multiple_loops() doms = g.dominators() self.check_dominators(doms, {0: [0], 7: [0, 7], 10: [0, 10, 7], 13: [0, 10, 13, 7], 20: [0, 10, 20, 13, 7], 23: [0, 20, 23, 7, 10, 13], 32: [32, 0, 20, 23, 7, 10, 13], 44: [0, 20, 23, 7, 10, 44, 13], 56: [0, 20, 7, 56, 10, 13], 57: [0, 20, 7, 56, 57, 10, 13], 60: [0, 60, 7], 61: [0, 60, 61, 7], 68: [0, 68, 60, 61, 7], 71: [0, 68, 71, 7, 60, 61], 80: [80, 0, 68, 71, 7, 60, 61], 87: [0, 68, 87, 7, 60, 61], 88: [0, 68, 87, 88, 7, 60, 61] }) g = self.infinite_loop1() doms = g.dominators() self.check_dominators(doms, {0: [0], 6: [0, 6], 10: [0, 10], 13: [0, 10, 13], 19: [0, 10, 19, 13], 26: [0, 10, 13, 26], }) def test_post_dominators_loopless(self): def eq_(d, l): self.assertEqual(sorted(doms[d]), l) for g in [self.loopless1(), self.loopless1_dead_nodes()]: doms = g.post_dominators() eq_(0, [0, 21]) eq_(12, [12, 21]) eq_(18, [18, 21]) eq_(21, [21]) g = self.loopless2() doms = g.post_dominators() eq_(34, [34]) eq_(42, [42]) eq_(21, [21]) eq_(18, [18, 21]) eq_(12, [12, 21]) eq_(99, [21, 99]) def test_post_dominators_loops(self): g = self.multiple_exits() doms = g.post_dominators() self.check_dominators(doms, {0: [0, 7], 7: [7], 10: [10], 19: [19], 23: [23], 29: [29, 37], 36: [36, 37], 37: [37], }) g = self.multiple_loops() doms = g.post_dominators() self.check_dominators(doms, {0: [0, 60, 68, 61, 7], 7: [60, 68, 61, 7], 10: [68, 7, 10, 13, 20, 56, 57, 60, 61], 13: [68, 7, 13, 20, 56, 57, 60, 61], 20: [20, 68, 7, 56, 57, 60, 61], 23: [68, 7, 20, 23, 56, 57, 60, 61], 32: [32, 68, 7, 20, 56, 57, 60, 61], 44: [68, 7, 44, 20, 56, 57, 60, 61], 56: [68, 7, 56, 57, 60, 61], 57: [57, 60, 68, 61, 7], 60: [60, 68, 61], 61: [68, 61], 68: [68], 71: [71], 80: [80], 87: [88, 87], 88: [88] }) def test_post_dominators_infinite_loops(self): # Post-dominators with infinite loops need special care # (the ordinary algorithm won't work). g = self.infinite_loop1() doms = g.post_dominators() self.check_dominators(doms, {0: [0], 6: [6], 10: [10, 13], 13: [13], 19: [19], 26: [26], }) g = self.infinite_loop2() doms = g.post_dominators() self.check_dominators(doms, {0: [0, 3], 3: [3], 9: [9], 16: [16], }) def test_dominator_tree(self): def check(graph, expected): domtree = graph.dominator_tree() self.assertEqual(domtree, expected) check(self.loopless1(), {0: {12, 18, 21}, 12: set(), 18: set(), 21: set()}) check(self.loopless2(), {12: set(), 18: set(), 21: {34, 42}, 34: set(), 42: set(), 99: {18, 12, 21}}) check(self.loopless1_dead_nodes(), {0: {12, 18, 21}, 12: set(), 18: set(), 21: set()}) check(self.multiple_loops(), {0: {7}, 7: {10, 60}, 60: {61}, 61: {68}, 68: {71, 87}, 87: {88}, 88: set(), 71: {80}, 80: set(), 10: {13}, 13: {20}, 20: {56, 23}, 23: {32, 44}, 44: set(), 32: set(), 56: {57}, 57: set()}) check(self.multiple_exits(), {0: {7}, 7: {10, 36, 37}, 36: set(), 10: {19, 23}, 23: {29}, 29: set(), 37: set(), 19: set()}) check(self.infinite_loop1(), {0: {10, 6}, 6: set(), 10: {13}, 13: {26, 19}, 19: set(), 26: set()}) check(self.infinite_loop2(), {0: {3}, 3: {16, 9}, 9: set(), 16: set()}) def test_immediate_dominators(self): def check(graph, expected): idoms = graph.immediate_dominators() self.assertEqual(idoms, expected) check(self.loopless1(), {0: 0, 12: 0, 18: 0, 21: 0}) check(self.loopless2(), {18: 99, 12: 99, 21: 99, 42: 21, 34: 21, 99: 99}) check(self.loopless1_dead_nodes(), {0: 0, 12: 0, 18: 0, 21: 0}) check(self.multiple_loops(), {0: 0, 7: 0, 10: 7, 13: 10, 20: 13, 23: 20, 32: 23, 44: 23, 56: 20, 57: 56, 60: 7, 61: 60, 68: 61, 71: 68, 80: 71, 87: 68, 88: 87}) check(self.multiple_exits(), {0:0, 7: 0, 10: 7, 19: 10, 23: 10, 29: 23, 36: 7, 37: 7}) check(self.infinite_loop1(), {0: 0, 6: 0, 10: 0, 13: 10, 19: 13, 26: 13}) check(self.infinite_loop2(), {0: 0, 3: 0, 9: 3, 16: 3}) def test_dominance_frontier(self): def check(graph, expected): df = graph.dominance_frontier() self.assertEqual(df, expected) check(self.loopless1(), {0: set(), 12: {21}, 18: {21}, 21: set()}) check(self.loopless2(), {18: {21}, 12: {21}, 21: set(), 42: set(), 34: set(), 99: set()}) check(self.loopless1_dead_nodes(), {0: set(), 12: {21}, 18: {21}, 21: set()}) check(self.multiple_loops(), {0: set(), 7: {7}, 10: {7}, 13: {7}, 20: {20, 7}, 23: {20}, 32: {20}, 44: {20}, 56: {7}, 57: {7}, 60: set(), 61: set(), 68: {68}, 71: {68}, 80: set(), 87: set(), 88: set()}) check(self.multiple_exits(), {0: set(), 7: {7}, 10: {37, 7}, 19: set(), 23: {37, 7}, 29: {37}, 36: {37}, 37: set()}) check(self.infinite_loop1(), {0: set(), 6: set(), 10: set(), 13: {13}, 19: {13}, 26: {13}}) check(self.infinite_loop2(), {0: set(), 3: {3}, 9: {3}, 16: {3}}) def test_backbone_loopless(self): for g in [self.loopless1(), self.loopless1_dead_nodes()]: self.assertEqual(sorted(g.backbone()), [0, 21]) g = self.loopless2() self.assertEqual(sorted(g.backbone()), [21, 99]) def test_backbone_loops(self): g = self.multiple_loops() self.assertEqual(sorted(g.backbone()), [0, 7, 60, 61, 68]) g = self.infinite_loop1() self.assertEqual(sorted(g.backbone()), [0]) g = self.infinite_loop2() self.assertEqual(sorted(g.backbone()), [0, 3]) def test_loops(self): for g in [self.loopless1(), self.loopless1_dead_nodes(), self.loopless2()]: self.assertEqual(len(g.loops()), 0) g = self.multiple_loops() # Loop headers self.assertEqual(sorted(g.loops()), [7, 20, 68]) outer1 = g.loops()[7] inner1 = g.loops()[20] outer2 = g.loops()[68] self.assertEqual(outer1.header, 7) self.assertEqual(sorted(outer1.entries), [0]) self.assertEqual(sorted(outer1.exits), [60]) self.assertEqual(sorted(outer1.body), [7, 10, 13, 20, 23, 32, 44, 56, 57]) self.assertEqual(inner1.header, 20) self.assertEqual(sorted(inner1.entries), [13]) self.assertEqual(sorted(inner1.exits), [56]) self.assertEqual(sorted(inner1.body), [20, 23, 32, 44]) self.assertEqual(outer2.header, 68) self.assertEqual(sorted(outer2.entries), [61]) self.assertEqual(sorted(outer2.exits), [80, 87]) self.assertEqual(sorted(outer2.body), [68, 71]) for node in [0, 60, 61, 80, 87, 88]: self.assertEqual(g.in_loops(node), []) for node in [7, 10, 13, 56, 57]: self.assertEqual(g.in_loops(node), [outer1]) for node in [20, 23, 32, 44]: self.assertEqual(g.in_loops(node), [inner1, outer1]) for node in [68, 71]: self.assertEqual(g.in_loops(node), [outer2]) g = self.infinite_loop1() # Loop headers self.assertEqual(sorted(g.loops()), [13]) loop = g.loops()[13] self.assertEqual(loop.header, 13) self.assertEqual(sorted(loop.entries), [10]) self.assertEqual(sorted(loop.exits), []) self.assertEqual(sorted(loop.body), [13, 19, 26]) for node in [0, 6, 10]: self.assertEqual(g.in_loops(node), []) for node in [13, 19, 26]: self.assertEqual(g.in_loops(node), [loop]) g = self.infinite_loop2() # Loop headers self.assertEqual(sorted(g.loops()), [3]) loop = g.loops()[3] self.assertEqual(loop.header, 3) self.assertEqual(sorted(loop.entries), [0]) self.assertEqual(sorted(loop.exits), []) self.assertEqual(sorted(loop.body), [3, 9, 16]) for node in [0]: self.assertEqual(g.in_loops(node), []) for node in [3, 9, 16]: self.assertEqual(g.in_loops(node), [loop]) g = self.multiple_exits() # Loop headers self.assertEqual(sorted(g.loops()), [7]) loop = g.loops()[7] self.assertEqual(loop.header, 7) self.assertEqual(sorted(loop.entries), [0]) self.assertEqual(sorted(loop.exits), [19, 29, 36]) self.assertEqual(sorted(loop.body), [7, 10, 23]) for node in [0, 19, 29, 36]: self.assertEqual(g.in_loops(node), []) for node in [7, 10, 23]: self.assertEqual(g.in_loops(node), [loop]) class TestRealCodeDomFront(TestCase): """Test IDOM and DOMFRONT computation on real python bytecode. Note: there will be less testing on IDOM (esp in loop) because of the extra blocks inserted by the interpreter. But, testing on DOMFRONT (which depends on IDOM) is easier. Testing is done by associating names to basicblock by using globals of the pattern "SET_BLOCK_<name>", which are scanned by `.get_cfa_and_namedblocks` into *namedblocks* dictionary. That way, we can check that a block of a certain name is a IDOM or DOMFRONT of another named block. """ def cfa(self, bc): cfa = ControlFlowAnalysis(bc) cfa.run() return cfa def get_cfa_and_namedblocks(self, fn): fid = FunctionIdentity.from_function(fn) bc = ByteCode(func_id=fid) cfa = self.cfa(bc) namedblocks = self._scan_namedblocks(bc, cfa) #### To debug, uncomment below # print(bc.dump()) # print("IDOMS") # for k, v in sorted(cfa.graph.immediate_dominators().items()): # print('{} -> {}'.format(k, v)) # print("DOMFRONT") # for k, vs in sorted(cfa.graph.dominance_frontier().items()): # print('{} -> {}'.format(k, vs)) # print(namedblocks) # cfa.graph.render_dot().view() return cfa, namedblocks def _scan_namedblocks(self, bc, cfa): """Scan namedblocks as denoted by a LOAD_GLOBAL bytecode referring to global variables with the pattern "SET_BLOCK_<name>", where "<name>" would be the name for the current block. """ namedblocks = {} blocks = sorted([x.offset for x in cfa.iterblocks()]) prefix = 'SET_BLOCK_' for inst in bc: # Find LOAD_GLOBAL that refers to "SET_BLOCK_<name>" if inst.opname == 'LOAD_GLOBAL': gv = bc.co_names[inst.arg] if gv.startswith(prefix): name = gv[len(prefix):] # Find the block where this instruction resides for s, e in zip(blocks, blocks[1:] + [blocks[-1] + 1]): if s <= inst.offset < e: break else: raise AssertionError('unreachable loop') blkno = s namedblocks[name] = blkno return namedblocks def test_loop(self): def foo(n): c = 0 SET_BLOCK_A # noqa: F821 i = 0 while SET_BLOCK_B0: # noqa: F821 SET_BLOCK_B1 # noqa: F821 c += 1 i += 1 SET_BLOCK_C # noqa: F821 return c cfa, blkpts = self.get_cfa_and_namedblocks(foo) idoms = cfa.graph.immediate_dominators() self.assertEqual(blkpts['B0'], idoms[blkpts['B1']]) domfront = cfa.graph.dominance_frontier() self.assertFalse(domfront[blkpts['A']]) self.assertFalse(domfront[blkpts['C']]) self.assertEqual({blkpts['B0']}, domfront[blkpts['B1']]) def test_loop_nested_and_break(self): def foo(n): SET_BLOCK_A # noqa: F821 while SET_BLOCK_B0: # noqa: F821 SET_BLOCK_B1 # noqa: F821 while SET_BLOCK_C0: # noqa: F821 SET_BLOCK_C1 # noqa: F821 if SET_BLOCK_D0: # noqa: F821 SET_BLOCK_D1 # noqa: F821 break elif n: SET_BLOCK_D2 # noqa: F821 SET_BLOCK_E # noqa: F821 SET_BLOCK_F # noqa: F821 SET_BLOCK_G # noqa: F821 cfa, blkpts = self.get_cfa_and_namedblocks(foo) idoms = cfa.graph.immediate_dominators() self.assertEqual(blkpts['D0'], blkpts['C1']) self.assertEqual(blkpts['C0'], idoms[blkpts['C1']]) domfront = cfa.graph.dominance_frontier() self.assertFalse(domfront[blkpts['A']]) self.assertFalse(domfront[blkpts['G']]) self.assertEqual({blkpts['B0']}, domfront[blkpts['B1']]) # 2 domfront members for C1 # C0 because of the loop; F because of the break. self.assertEqual({blkpts['C0'], blkpts['F']}, domfront[blkpts['C1']]) self.assertEqual({blkpts['F']}, domfront[blkpts['D1']]) self.assertEqual({blkpts['E']}, domfront[blkpts['D2']]) self.assertEqual({blkpts['C0']}, domfront[blkpts['E']]) self.assertEqual({blkpts['B0']}, domfront[blkpts['F']]) self.assertEqual({blkpts['B0']}, domfront[blkpts['B0']]) def test_if_else(self): def foo(a, b): c = 0 SET_BLOCK_A # noqa: F821 if a < b: SET_BLOCK_B # noqa: F821 c = 1 elif SET_BLOCK_C0: # noqa: F821 SET_BLOCK_C1 # noqa: F821 c = 2 else: SET_BLOCK_D # noqa: F821 c = 3 SET_BLOCK_E # noqa: F821 if a % b == 0: SET_BLOCK_F # noqa: F821 c += 1 SET_BLOCK_G # noqa: F821 return c cfa, blkpts = self.get_cfa_and_namedblocks(foo) idoms = cfa.graph.immediate_dominators() self.assertEqual(blkpts['A'], idoms[blkpts['B']]) self.assertEqual(blkpts['A'], idoms[blkpts['C0']]) self.assertEqual(blkpts['C0'], idoms[blkpts['C1']]) self.assertEqual(blkpts['C0'], idoms[blkpts['D']]) self.assertEqual(blkpts['A'], idoms[blkpts['E']]) self.assertEqual(blkpts['E'], idoms[blkpts['F']]) self.assertEqual(blkpts['E'], idoms[blkpts['G']]) domfront = cfa.graph.dominance_frontier() self.assertFalse(domfront[blkpts['A']]) self.assertFalse(domfront[blkpts['E']]) self.assertFalse(domfront[blkpts['G']]) self.assertEqual({blkpts['E']}, domfront[blkpts['B']]) self.assertEqual({blkpts['E']}, domfront[blkpts['C0']]) self.assertEqual({blkpts['E']}, domfront[blkpts['C1']]) self.assertEqual({blkpts['E']}, domfront[blkpts['D']]) self.assertEqual({blkpts['G']}, domfront[blkpts['F']]) def test_if_else_nested(self): def foo(): if SET_BLOCK_A0: # noqa: F821 SET_BLOCK_A1 # noqa: F821 if SET_BLOCK_B0: # noqa: F821 SET_BLOCK_B1 # noqa: F821 a = 0 else: if SET_BLOCK_C0: # noqa: F821 SET_BLOCK_C1 # noqa: F821 a = 1 else: SET_BLOCK_C2 # noqa: F821 a = 2 SET_BLOCK_D # noqa: F821 SET_BLOCK_E # noqa: F821 SET_BLOCK_F # noqa: F821 return a cfa, blkpts = self.get_cfa_and_namedblocks(foo) idoms = cfa.graph.immediate_dominators() self.assertEqual(blkpts['A0'], idoms[blkpts['A1']]) self.assertEqual(blkpts['A1'], idoms[blkpts['B1']]) self.assertEqual(blkpts['A1'], idoms[blkpts['C0']]) self.assertEqual(blkpts['C0'], idoms[blkpts['D']]) self.assertEqual(blkpts['A1'], idoms[blkpts['E']]) self.assertEqual(blkpts['A0'], idoms[blkpts['F']]) domfront = cfa.graph.dominance_frontier() self.assertFalse(domfront[blkpts['A0']]) self.assertFalse(domfront[blkpts['F']]) self.assertEqual({blkpts['E']}, domfront[blkpts['B1']]) self.assertEqual({blkpts['D']}, domfront[blkpts['C1']]) self.assertEqual({blkpts['E']}, domfront[blkpts['D']]) self.assertEqual({blkpts['F']}, domfront[blkpts['E']]) def test_infinite_loop(self): def foo(): SET_BLOCK_A # noqa: F821 while True: # infinite loop if SET_BLOCK_B: # noqa: F821 SET_BLOCK_C # noqa: F821 return SET_BLOCK_D # noqa: F821 SET_BLOCK_E # noqa: F821 # Whether infinite loop (i.g. while True) are optimized out. infinite_loop_opt_out = bool(IS_PY3) cfa, blkpts = self.get_cfa_and_namedblocks(foo) idoms = cfa.graph.immediate_dominators() if infinite_loop_opt_out: self.assertNotIn(blkpts['E'], idoms) self.assertEqual(blkpts['B'], idoms[blkpts['C']]) self.assertEqual(blkpts['B'], idoms[blkpts['D']]) domfront = cfa.graph.dominance_frontier() if infinite_loop_opt_out: self.assertNotIn(blkpts['E'], domfront) self.assertFalse(domfront[blkpts['A']]) self.assertFalse(domfront[blkpts['C']]) if infinite_loop_opt_out: self.assertEqual({blkpts['B']}, domfront[blkpts['B']]) self.assertEqual({blkpts['B']}, domfront[blkpts['D']]) if __name__ == '__main__': unittest.main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Invoke tasks. To run a task, run ``$ invoke <COMMAND>``. To see a list of commands, run ``$ invoke --list``. """ import os import sys import json import platform import subprocess import logging import sqlite3 import invoke from invoke import Collection from website import settings from .utils import pip_install, bin_prefix try: from tasks import local # noqa except ImportError: print('No tasks/local.py file found. ' 'Did you remember to copy local-dist.py to local.py?') logging.getLogger('invoke').setLevel(logging.CRITICAL) # gets the root path for all the scripts that rely on it HERE = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) WHEELHOUSE_PATH = os.environ.get('WHEELHOUSE') NO_TESTS_COLLECTED = 5 ns = Collection() try: from tasks import local as local_tasks ns.add_collection(Collection.from_module(local_tasks), name='local') except ImportError: pass try: from admin import tasks as admin_tasks ns.add_collection(Collection.from_module(admin_tasks), name='admin') except ImportError: pass def task(*args, **kwargs): """Behaves the same way as invoke.task. Adds the task to the root namespace. """ if len(args) == 1 and callable(args[0]): new_task = invoke.task(args[0]) ns.add_task(new_task) return new_task def decorator(f): new_task = invoke.task(f, *args, **kwargs) ns.add_task(new_task) return new_task return decorator @task def server(ctx, host=None, port=5000, debug=True, gitlogs=False): """Run the app server.""" if os.environ.get('WERKZEUG_RUN_MAIN') == 'true' or not debug: if os.environ.get('WEB_REMOTE_DEBUG', None): import pydevd # e.g. '127.0.0.1:5678' remote_parts = os.environ.get('WEB_REMOTE_DEBUG').split(':') pydevd.settrace(remote_parts[0], port=int(remote_parts[1]), suspend=False, stdoutToServer=True, stderrToServer=True) if gitlogs: git_logs(ctx) from website.app import init_app os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings' app = init_app(set_backends=True, routes=True) settings.API_SERVER_PORT = port else: from framework.flask import app context = None if settings.SECURE_MODE: context = (settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY) app.run(host=host, port=port, debug=debug, threaded=debug, extra_files=[settings.ASSET_HASH_PATH], ssl_context=context) @task def git_logs(ctx, branch=None): from scripts.meta import gatherer gatherer.main(branch=branch) @task def apiserver(ctx, port=8000, wait=True, autoreload=True, host='127.0.0.1', pty=True): """Run the API server.""" env = os.environ.copy() cmd = 'DJANGO_SETTINGS_MODULE=api.base.settings {} manage.py runserver {}:{} --nothreading'\ .format(sys.executable, host, port) if not autoreload: cmd += ' --noreload' if settings.SECURE_MODE: cmd = cmd.replace('runserver', 'runsslserver') cmd += ' --certificate {} --key {}'.format(settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY) if wait: return ctx.run(cmd, echo=True, pty=pty) from subprocess import Popen return Popen(cmd, shell=True, env=env) @task def adminserver(ctx, port=8001, host='127.0.0.1', pty=True): """Run the Admin server.""" env = 'DJANGO_SETTINGS_MODULE="admin.base.settings"' cmd = '{} python3 manage.py runserver {}:{} --nothreading'.format(env, host, port) if settings.SECURE_MODE: cmd = cmd.replace('runserver', 'runsslserver') cmd += ' --certificate {} --key {}'.format(settings.OSF_SERVER_CERT, settings.OSF_SERVER_KEY) ctx.run(cmd, echo=True, pty=pty) @task def shell(ctx, transaction=True, print_sql=False, notebook=False): cmd = 'DJANGO_SETTINGS_MODULE="api.base.settings" python3 manage.py osf_shell' if notebook: cmd += ' --notebook' if not transaction: cmd += ' --no-transaction' return ctx.run(cmd, pty=True, echo=True) @task def sharejs(ctx, host=None, port=None, db_url=None, cors_allow_origin=None): """Start a local ShareJS server.""" if host: os.environ['SHAREJS_SERVER_HOST'] = host if port: os.environ['SHAREJS_SERVER_PORT'] = port if db_url: os.environ['SHAREJS_DB_URL'] = db_url if cors_allow_origin: os.environ['SHAREJS_CORS_ALLOW_ORIGIN'] = cors_allow_origin if settings.SENTRY_DSN: os.environ['SHAREJS_SENTRY_DSN'] = settings.SENTRY_DSN share_server = os.path.join(settings.ADDON_PATH, 'wiki', 'shareServer.js') ctx.run('node {0}'.format(share_server)) @task(aliases=['celery']) def celery_worker(ctx, level='debug', hostname=None, beat=False, queues=None, concurrency=None, max_tasks_per_child=None): """Run the Celery process.""" os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings' cmd = 'celery worker -A framework.celery_tasks -Ofair -l {0}'.format(level) if hostname: cmd = cmd + ' --hostname={}'.format(hostname) # beat sets up a cron like scheduler, refer to website/settings if beat: cmd = cmd + ' --beat' if queues: cmd = cmd + ' --queues={}'.format(queues) if concurrency: cmd = cmd + ' --concurrency={}'.format(concurrency) if max_tasks_per_child: cmd = cmd + ' --maxtasksperchild={}'.format(max_tasks_per_child) ctx.run(bin_prefix(cmd), pty=True) @task(aliases=['beat']) def celery_beat(ctx, level='debug', schedule=None): """Run the Celery process.""" os.environ['DJANGO_SETTINGS_MODULE'] = 'api.base.settings' # beat sets up a cron like scheduler, refer to website/settings cmd = 'celery beat -A framework.celery_tasks -l {0} --pidfile='.format(level) if schedule: cmd = cmd + ' --schedule={}'.format(schedule) ctx.run(bin_prefix(cmd), pty=True) @task def migrate_search(ctx, delete=True, remove=False, index=settings.ELASTIC_INDEX): """Migrate the search-enabled models.""" from website.app import init_app init_app(routes=False, set_backends=False) from website.search_migration.migrate import migrate # NOTE: Silence the warning: # "InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised." SILENT_LOGGERS = ['py.warnings'] for logger in SILENT_LOGGERS: logging.getLogger(logger).setLevel(logging.ERROR) migrate(delete, remove=remove, index=index) @task def rebuild_search(ctx): """Delete and recreate the index for elasticsearch""" from website.app import init_app import requests from website import settings init_app(routes=False, set_backends=True) if not settings.ELASTIC_URI.startswith('http'): protocol = 'http://' if settings.DEBUG_MODE else 'https://' else: protocol = '' url = '{protocol}{uri}/{index}'.format( protocol=protocol, uri=settings.ELASTIC_URI.rstrip('/'), index=settings.ELASTIC_INDEX, ) print('Deleting index {}'.format(settings.ELASTIC_INDEX)) print('----- DELETE {}*'.format(url)) requests.delete(url + '*') print('Creating index {}'.format(settings.ELASTIC_INDEX)) print('----- PUT {}'.format(url)) requests.put(url) migrate_search(ctx, delete=False) @task def mailserver(ctx, port=1025): """Run a SMTP test server.""" cmd = 'python3 -m smtpd -n -c DebuggingServer localhost:{port}'.format(port=port) ctx.run(bin_prefix(cmd), pty=True) @task def syntax(ctx): """Use pre-commit to run formatters and linters.""" ctx.run('pre-commit run --all-files --show-diff-on-failure', echo=True) @task(aliases=['req']) def requirements(ctx, base=False, addons=False, release=False, dev=False, all=False): """Install python dependencies. Examples: inv requirements inv requirements --all You should use --all for updating your developement environment. --all will install (in order): addons, dev and the base requirements. By default, base requirements will run. However, if any set of addons, release, or dev are chosen, base will have to be mentioned explicitly in order to run. This is to remain compatible with previous usages. Release requirements will prevent dev, and base from running. """ if all: base = True addons = True dev = True if not(addons or dev): base = True if release or addons: addon_requirements(ctx) # "release" takes precedence if release: req_file = os.path.join(HERE, 'requirements', 'release.txt') ctx.run( pip_install(req_file), echo=True ) else: if dev: # then dev requirements req_file = os.path.join(HERE, 'requirements', 'dev.txt') ctx.run( pip_install(req_file), echo=True ) if base: # then base requirements req_file = os.path.join(HERE, 'requirements.txt') ctx.run( pip_install(req_file), echo=True ) # fix URITemplate name conflict h/t @github ctx.run('pip3 uninstall uritemplate.py --yes || true') ctx.run('pip3 install --no-cache-dir uritemplate.py==0.3.0') @task def test_module(ctx, module=None, numprocesses=None, nocapture=False, params=None, coverage=False, testmon=False): """Helper for running tests. """ from past.builtins import basestring os.environ['DJANGO_SETTINGS_MODULE'] = 'osf_tests.settings' import pytest if not numprocesses: from multiprocessing import cpu_count numprocesses = cpu_count() numprocesses = int(numprocesses) # NOTE: Subprocess to compensate for lack of thread safety in the httpretty module. # https://github.com/gabrielfalcao/HTTPretty/issues/209#issue-54090252 args = [] if coverage: args.extend([ '--cov-report', 'term-missing', '--cov', 'admin', '--cov', 'addons', '--cov', 'api', '--cov', 'framework', '--cov', 'osf', '--cov', 'website', ]) if not nocapture: args += ['-s'] if numprocesses > 1: args += ['-n {}'.format(numprocesses), '--max-slave-restart=0'] modules = [module] if isinstance(module, basestring) else module args.extend(modules) if testmon: args.extend(['--testmon']) if params: params = [params] if isinstance(params, basestring) else params args.extend(params) retcode = pytest.main(args) # exit code 5 is all tests skipped which is the same as passing with testmon sys.exit(0 if retcode == NO_TESTS_COLLECTED else retcode) OSF_TESTS = [ 'osf_tests', ] WEBSITE_TESTS = [ 'tests', ] API_TESTS1 = [ 'api_tests/draft_registrations', 'api_tests/draft_nodes', 'api_tests/identifiers', 'api_tests/institutions', 'api_tests/licenses', 'api_tests/logs', 'api_tests/schemas', 'api_tests/providers', 'api_tests/preprints', 'api_tests/registrations', 'api_tests/registries_moderation', 'api_tests/users', ] API_TESTS2 = [ 'api_tests/chronos', 'api_tests/meetings', 'api_tests/metrics', 'api_tests/nodes', 'api_tests/osf_groups', 'api_tests/requests', 'api_tests/schema_responses', 'api_tests/subscriptions', 'api_tests/waffle', 'api_tests/wb', ] API_TESTS3 = [ 'api_tests/actions', 'api_tests/addons_tests', 'api_tests/alerts', 'api_tests/applications', 'api_tests/banners', 'api_tests/base', 'api_tests/collections', 'api_tests/comments', 'api_tests/crossref', 'api_tests/files', 'api_tests/guids', 'api_tests/reviews', 'api_tests/regions', 'api_tests/search', 'api_tests/scopes', 'api_tests/subjects', 'api_tests/taxonomies', 'api_tests/test', 'api_tests/tokens', 'api_tests/view_only_links', 'api_tests/share', 'api_tests/wikis', ] ADDON_TESTS = [ 'addons', ] ADMIN_TESTS = [ 'admin_tests', ] @task def test_osf(ctx, numprocesses=None, coverage=False, testmon=False): """Run the OSF test suite.""" print('Testing modules "{}"'.format(OSF_TESTS)) test_module(ctx, module=OSF_TESTS, numprocesses=numprocesses, coverage=coverage, testmon=testmon) @task def test_website(ctx, numprocesses=None, coverage=False, testmon=False): """Run the old test suite.""" print('Testing modules "{}"'.format(WEBSITE_TESTS)) test_module(ctx, module=WEBSITE_TESTS, numprocesses=numprocesses, coverage=coverage, testmon=testmon) @task def test_api1(ctx, numprocesses=None, coverage=False, testmon=False): """Run the API test suite.""" print('Testing modules "{}"'.format(API_TESTS1 + ADMIN_TESTS)) test_module(ctx, module=API_TESTS1 + ADMIN_TESTS, numprocesses=numprocesses, coverage=coverage, testmon=testmon) @task def test_api2(ctx, numprocesses=None, coverage=False, testmon=False): """Run the API test suite.""" print('Testing modules "{}"'.format(API_TESTS2)) test_module(ctx, module=API_TESTS2, numprocesses=numprocesses, coverage=coverage, testmon=testmon) @task def test_api3(ctx, numprocesses=None, coverage=False, testmon=False): """Run the API test suite.""" print('Testing modules "{}"'.format(API_TESTS3 + OSF_TESTS)) # NOTE: There may be some concurrency issues with ES test_module(ctx, module=API_TESTS3 + OSF_TESTS, numprocesses=numprocesses, coverage=coverage, testmon=testmon) @task def test_admin(ctx, numprocesses=None, coverage=False, testmon=False): """Run the Admin test suite.""" print('Testing module "admin_tests"') test_module(ctx, module=ADMIN_TESTS, numprocesses=numprocesses, coverage=coverage, testmon=testmon) @task def test_addons(ctx, numprocesses=None, coverage=False, testmon=False): """Run all the tests in the addons directory. """ print('Testing modules "{}"'.format(ADDON_TESTS)) test_module(ctx, module=ADDON_TESTS, numprocesses=numprocesses, coverage=coverage, testmon=testmon) @task def test(ctx, all=False, lint=False): """ Run unit tests: OSF (always), plus addons and syntax checks (optional) """ if lint: syntax(ctx) test_website(ctx) # /tests test_api1(ctx) test_api2(ctx) test_api3(ctx) # also /osf_tests if all: test_addons(ctx) # TODO: Enable admin tests test_admin(ctx) @task def remove_failures_from_testmon(ctx, db_path=None): conn = sqlite3.connect(db_path) tests_decached = conn.execute("delete from node where result <> '{}'").rowcount ctx.run('echo {} failures purged from travis cache'.format(tests_decached)) @task def travis_setup(ctx): ctx.run('npm install -g bower', echo=True) with open('package.json', 'r') as fobj: package_json = json.load(fobj) ctx.run('npm install @centerforopenscience/list-of-licenses@{}'.format(package_json['dependencies']['@centerforopenscience/list-of-licenses']), echo=True) with open('bower.json', 'r') as fobj: bower_json = json.load(fobj) ctx.run('bower install {}'.format(bower_json['dependencies']['styles']), echo=True) @task def test_travis_addons(ctx, numprocesses=None, coverage=False, testmon=False): """ Run half of the tests to help travis go faster. """ #travis_setup(ctx) syntax(ctx) test_addons(ctx, numprocesses=numprocesses, coverage=coverage, testmon=testmon) @task def test_travis_website(ctx, numprocesses=None, coverage=False, testmon=False): """ Run other half of the tests to help travis go faster. """ #travis_setup(ctx) test_website(ctx, numprocesses=numprocesses, coverage=coverage, testmon=testmon) @task def test_travis_api1_and_js(ctx, numprocesses=None, coverage=False, testmon=False): #travis_setup(ctx) test_api1(ctx, numprocesses=numprocesses, coverage=coverage, testmon=testmon) @task def test_travis_api2(ctx, numprocesses=None, coverage=False, testmon=False): #travis_setup(ctx) test_api2(ctx, numprocesses=numprocesses, coverage=coverage, testmon=testmon) @task def test_travis_api3_and_osf(ctx, numprocesses=None, coverage=False, testmon=False): #travis_setup(ctx) test_api3(ctx, numprocesses=numprocesses, coverage=coverage, testmon=testmon) @task def wheelhouse(ctx, addons=False, release=False, dev=False, pty=True): """Build wheels for python dependencies. Examples: inv wheelhouse --dev inv wheelhouse --addons inv wheelhouse --release """ if release or addons: for directory in os.listdir(settings.ADDON_PATH): path = os.path.join(settings.ADDON_PATH, directory) if os.path.isdir(path): req_file = os.path.join(path, 'requirements.txt') if os.path.exists(req_file): cmd = ('pip3 wheel --find-links={} -r {} --wheel-dir={} ').format(WHEELHOUSE_PATH, req_file, WHEELHOUSE_PATH) ctx.run(cmd, pty=pty) if release: req_file = os.path.join(HERE, 'requirements', 'release.txt') elif dev: req_file = os.path.join(HERE, 'requirements', 'dev.txt') else: req_file = os.path.join(HERE, 'requirements.txt') cmd = 'pip3 wheel --find-links={} -r {} --wheel-dir={} '.format(WHEELHOUSE_PATH, req_file, WHEELHOUSE_PATH) ctx.run(cmd, pty=pty) @task def addon_requirements(ctx): """Install all addon requirements.""" for directory in os.listdir(settings.ADDON_PATH): path = os.path.join(settings.ADDON_PATH, directory) requirements_file = os.path.join(path, 'requirements.txt') if os.path.isdir(path) and os.path.isfile(requirements_file): print('Installing requirements for {0}'.format(directory)) ctx.run( pip_install(requirements_file), echo=True ) print('Finished installing addon requirements') @task def travis_addon_settings(ctx): for directory in os.listdir(settings.ADDON_PATH): path = os.path.join(settings.ADDON_PATH, directory, 'settings') if os.path.isdir(path): try: open(os.path.join(path, 'local-travis.py')) ctx.run('cp {path}/local-travis.py {path}/local.py'.format(path=path)) except IOError: pass @task def copy_addon_settings(ctx): for directory in os.listdir(settings.ADDON_PATH): path = os.path.join(settings.ADDON_PATH, directory, 'settings') if os.path.isdir(path) and not os.path.isfile(os.path.join(path, 'local.py')): try: open(os.path.join(path, 'local-dist.py')) ctx.run('cp {path}/local-dist.py {path}/local.py'.format(path=path)) except IOError: pass @task def copy_settings(ctx, addons=False): # Website settings if not os.path.isfile('website/settings/local.py'): print('Creating local.py file') ctx.run('cp website/settings/local-dist.py website/settings/local.py') # Addon settings if addons: copy_addon_settings(ctx) @task(aliases=['bower']) def bower_install(ctx): print('Installing bower-managed packages') bower_bin = os.path.join(HERE, 'node_modules', '.bin', 'bower') ctx.run('{} prune --allow-root'.format(bower_bin), echo=True) ctx.run('{} install --allow-root'.format(bower_bin), echo=True) @task def docker_init(ctx): """Initial docker setup""" print('You will be asked for your sudo password to continue...') if platform.system() == 'Darwin': # Mac OSX ctx.run('sudo ifconfig lo0 alias 192.168.168.167') else: print('Your system is not recognized, you will have to setup docker manually') def ensure_docker_env_setup(ctx): if hasattr(os.environ, 'DOCKER_ENV_SETUP') and os.environ['DOCKER_ENV_SETUP'] == '1': pass else: os.environ['WEB_REMOTE_DEBUG'] = '192.168.168.167:11000' os.environ['API_REMOTE_DEBUG'] = '192.168.168.167:12000' os.environ['WORKER_REMOTE_DEBUG'] = '192.168.168.167:13000' os.environ['DOCKER_ENV_SETUP'] = '1' docker_init(ctx) @task def docker_requirements(ctx): ensure_docker_env_setup(ctx) ctx.run('docker-compose up requirements requirements_mfr requirements_wb') @task def docker_appservices(ctx): ensure_docker_env_setup(ctx) ctx.run('docker-compose up assets fakecas elasticsearch tokumx postgres') @task def docker_osf(ctx): ensure_docker_env_setup(ctx) ctx.run('docker-compose up mfr wb web api') @task def clear_sessions(ctx, months=1, dry_run=False): from website.app import init_app init_app(routes=False, set_backends=True) from scripts import clear_sessions clear_sessions.clear_sessions_relative(months=months, dry_run=dry_run) # Release tasks @task def hotfix(ctx, name, finish=False, push=False): """Rename hotfix branch to hotfix/<next-patch-version> and optionally finish hotfix. """ print('Checking out master to calculate curent version') ctx.run('git checkout master') latest_version = latest_tag_info()['current_version'] print('Current version is: {}'.format(latest_version)) major, minor, patch = latest_version.split('.') next_patch_version = '.'.join([major, minor, str(int(patch) + 1)]) print('Bumping to next patch version: {}'.format(next_patch_version)) print('Renaming branch...') new_branch_name = 'hotfix/{}'.format(next_patch_version) ctx.run('git checkout {}'.format(name), echo=True) ctx.run('git branch -m {}'.format(new_branch_name), echo=True) if finish: ctx.run('git flow hotfix finish {}'.format(next_patch_version), echo=True, pty=True) if push: ctx.run('git push --follow-tags origin master', echo=True) ctx.run('git push origin develop', echo=True) @task def feature(ctx, name, finish=False, push=False): """Rename the current branch to a feature branch and optionally finish it.""" print('Renaming branch...') ctx.run('git branch -m feature/{}'.format(name), echo=True) if finish: ctx.run('git flow feature finish {}'.format(name), echo=True) if push: ctx.run('git push origin develop', echo=True) # Adapted from bumpversion def latest_tag_info(): try: # git-describe doesn't update the git-index, so we do that # subprocess.check_output(["git", "update-index", "--refresh"]) # get info about the latest tag in git describe_out = subprocess.check_output([ 'git', 'describe', '--dirty', '--tags', '--long', '--abbrev=40' ], stderr=subprocess.STDOUT ).decode().split('-') except subprocess.CalledProcessError as err: raise err # logger.warn("Error when running git describe") return {} info = {} if describe_out[-1].strip() == 'dirty': info['dirty'] = True describe_out.pop() info['commit_sha'] = describe_out.pop().lstrip('g') info['distance_to_latest_tag'] = int(describe_out.pop()) info['current_version'] = describe_out.pop().lstrip('v') # assert type(info["current_version"]) == str assert 0 == len(describe_out) return info # Tasks for generating and bundling SSL certificates # See http://cosdev.readthedocs.org/en/latest/osf/ops.html for details @task def generate_key(ctx, domain, bits=2048): cmd = 'openssl genrsa -des3 -out {0}.key {1}'.format(domain, bits) ctx.run(cmd) @task def generate_key_nopass(ctx, domain): cmd = 'openssl rsa -in {domain}.key -out {domain}.key.nopass'.format( domain=domain ) ctx.run(cmd) @task def generate_csr(ctx, domain): cmd = 'openssl req -new -key {domain}.key.nopass -out {domain}.csr'.format( domain=domain ) ctx.run(cmd) @task def request_ssl_cert(ctx, domain): """Generate a key, a key with password removed, and a signing request for the specified domain. Usage: > invoke request_ssl_cert pizza.osf.io """ generate_key(ctx, domain) generate_key_nopass(ctx, domain) generate_csr(ctx, domain) @task def bundle_certs(ctx, domain, cert_path): """Concatenate certificates from NameCheap in the correct order. Certificate files must be in the same directory. """ cert_files = [ '{0}.crt'.format(domain), 'COMODORSADomainValidationSecureServerCA.crt', 'COMODORSAAddTrustCA.crt', 'AddTrustExternalCARoot.crt', ] certs = ' '.join( os.path.join(cert_path, cert_file) for cert_file in cert_files ) cmd = 'cat {certs} > {domain}.bundle.crt'.format( certs=certs, domain=domain, ) ctx.run(cmd) @task def clean_assets(ctx): """Remove built JS files.""" public_path = os.path.join(HERE, 'website', 'static', 'public') js_path = os.path.join(public_path, 'js') ctx.run('rm -rf {0}'.format(js_path), echo=True) @task(aliases=['pack']) def webpack(ctx, clean=False, watch=False, dev=False, colors=False): """Build static assets with webpack.""" if clean: clean_assets(ctx) args = ['yarn run webpack-{}'.format('dev' if dev else 'prod')] args += ['--progress'] if watch: args += ['--watch'] if colors: args += ['--colors'] command = ' '.join(args) ctx.run(command, echo=True) @task() def build_js_config_files(ctx): from website import settings print('Building JS config files...') with open(os.path.join(settings.STATIC_FOLDER, 'built', 'nodeCategories.json'), 'w') as fp: json.dump(settings.NODE_CATEGORY_MAP, fp) print('...Done.') @task() def assets(ctx, dev=False, watch=False, colors=False): """Install and build static assets.""" command = 'yarn install --frozen-lockfile' if not dev: command += ' --production' ctx.run(command, echo=True) bower_install(ctx) build_js_config_files(ctx) # Always set clean=False to prevent possible mistakes # on prod webpack(ctx, clean=False, watch=watch, dev=dev, colors=colors) @task def generate_self_signed(ctx, domain): """Generate self-signed SSL key and certificate. """ cmd = ( 'openssl req -x509 -nodes -days 365 -newkey rsa:2048' ' -keyout {0}.key -out {0}.crt' ).format(domain) ctx.run(cmd) @task def update_citation_styles(ctx): from scripts import parse_citation_styles total = parse_citation_styles.main() print('Parsed {} styles'.format(total)) @task def clean(ctx, verbose=False): ctx.run('find . -name "*.pyc" -delete', echo=True) @task(default=True) def usage(ctx): ctx.run('invoke --list') ### Maintenance Tasks ### @task def set_maintenance(ctx, message='', level=1, start=None, end=None): from website.app import setup_django setup_django() from website.maintenance import set_maintenance """Display maintenance notice across OSF applications (incl. preprints, registries, etc.) start - Start time for the maintenance period end - End time for the mainteance period NOTE: If no start or end values are provided, default to starting now and ending 24 hours from now. message - Message to display. If omitted, will be: "The site will undergo maintenance between <localized start time> and <localized end time>. Thank you for your patience." level - Severity level. Modifies the color of the displayed notice. Must be one of 1 (info), 2 (warning), 3 (danger). Examples: invoke set_maintenance --start 2016-03-16T15:41:00-04:00 --end 2016-03-16T15:42:00-04:00 invoke set_maintenance --message 'The OSF is experiencing issues connecting to a 3rd party service' --level 2 --start 2016-03-16T15:41:00-04:00 --end 2016-03-16T15:42:00-04:00 """ state = set_maintenance(message, level, start, end) print('Maintenance notice up {} to {}.'.format(state['start'], state['end'])) @task def unset_maintenance(ctx): from website.app import setup_django setup_django() from website.maintenance import unset_maintenance print('Taking down maintenance notice...') unset_maintenance() print('...Done.')
#!/usr/bin/env python ''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from stacks.utils.RMFTestCase import * import json from mock.mock import MagicMock, patch from resource_management.libraries.script.script import Script from resource_management.core import shell import itertools from resource_management.core.exceptions import Fail import resource_management.libraries.functions.mounted_dirs_helper from resource_management.libraries.functions import conf_select @patch.object(resource_management.libraries.functions, 'check_process_status', new = MagicMock()) @patch.object(Script, 'format_package_name', new = MagicMock()) @patch.object(conf_select, "get_hadoop_conf_dir", new=MagicMock(return_value="/usr/hdp/current/hadoop-client/conf")) class TestDatanode(RMFTestCase): COMMON_SERVICES_PACKAGE_DIR = "HDFS/2.1.0.2.0/package" STACK_VERSION = "2.0.6" CONFIG_OVERRIDES = {"serviceName":"HDFS", "role":"DATANODE"} def test_configure_default(self): self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "configure", config_file = "default.json", stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES ) self.assert_configure_default() self.assertNoMoreResources() def test_start_default(self): self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "start", config_file = "default.json", stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES ) self.assert_configure_default() self.assertResourceCalled('Directory', '/var/run/hadoop', owner = 'hdfs', group = 'hadoop', mode = 0755 ) self.assertResourceCalled('Directory', '/var/run/hadoop/hdfs', owner = 'hdfs', group = 'hadoop', create_parents = True, ) self.assertResourceCalled('Directory', '/var/log/hadoop/hdfs', owner = 'hdfs', group = 'hadoop', create_parents = True, ) self.assertResourceCalled('File', '/var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid', action = ['delete'], not_if = "ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E test -f /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid && ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E pgrep -F /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid", ) self.assertResourceCalled('Execute', "ambari-sudo.sh su hdfs -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]ulimit -c unlimited ; /usr/lib/hadoop/sbin/hadoop-daemon.sh --config /usr/hdp/current/hadoop-client/conf start datanode'", environment = {'HADOOP_LIBEXEC_DIR': '/usr/lib/hadoop/libexec'}, not_if = "ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E test -f /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid && ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E pgrep -F /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid", ) self.assertNoMoreResources() @patch('time.sleep') @patch("os.path.exists", new = MagicMock(return_value=False)) @patch("resource_management.core.shell.checked_call") def test_stop_default(self, checked_call_mock, time_mock): def side_effect(arg): if '-D ipc.client.connect.max.retries=5 -D ipc.client.connect.retry.interval=1000 -getDatanodeInfo' in arg : raise Fail() return checked_call_mock.side_effect = side_effect self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "stop", config_file = "default.json", stack_version = self.STACK_VERSION, checked_call_mocks = side_effect, target = RMFTestCase.TARGET_COMMON_SERVICES ) self.assertResourceCalled('Execute', "ambari-sudo.sh su hdfs -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]ulimit -c unlimited ; /usr/lib/hadoop/sbin/hadoop-daemon.sh --config /usr/hdp/current/hadoop-client/conf stop datanode'", environment = {'HADOOP_LIBEXEC_DIR': '/usr/lib/hadoop/libexec'}, only_if = "ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E test -f /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid && ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E pgrep -F /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid") self.assertResourceCalled('File', '/var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid', action = ['delete']) self.assertNoMoreResources() def test_configure_secured(self): self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "configure", config_file = "secured.json", stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES ) self.assert_configure_secured() self.assertNoMoreResources() def test_start_secured(self): self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "start", config_file = "secured.json", stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES ) self.assert_configure_secured() self.assertResourceCalled('Directory', '/var/run/hadoop', owner = 'hdfs', group = 'hadoop', mode = 0755 ) self.assertResourceCalled('Directory', '/var/run/hadoop/hdfs', owner = 'hdfs', group = 'hadoop', create_parents = True, ) self.assertResourceCalled('Directory', '/var/log/hadoop/hdfs', owner = 'hdfs', group = 'hadoop', create_parents = True, ) self.assertResourceCalled('File', '/var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid', action = ['delete'], not_if = "ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E test -f /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid && ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E pgrep -F /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid", ) self.assertResourceCalled('Execute', 'ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E /usr/lib/hadoop/sbin/hadoop-daemon.sh --config /usr/hdp/current/hadoop-client/conf start datanode', environment = {'HADOOP_LIBEXEC_DIR': '/usr/lib/hadoop/libexec'}, not_if = "ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E test -f /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid && ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E pgrep -F /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid", ) self.assertNoMoreResources() def test_start_secured_HDP22_root(self): config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/secured.json" with open(config_file, "r") as f: secured_json = json.load(f) secured_json['hostLevelParams']['stack_version']= '2.2' self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "start", config_dict = secured_json, stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES ) self.assert_configure_secured("2.3", snappy_enabled=False) self.assertResourceCalled('Directory', '/var/run/hadoop', owner = 'hdfs', group = 'hadoop', mode = 0755 ) self.assertResourceCalled('Directory', '/var/run/hadoop/hdfs', owner = 'hdfs', group = 'hadoop', create_parents = True, ) self.assertResourceCalled('Directory', '/var/log/hadoop/hdfs', owner = 'hdfs', group = 'hadoop', create_parents = True, ) self.assertResourceCalled('File', '/var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid', action = ['delete'], not_if = "ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E test -f /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid && ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E pgrep -F /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid", ) self.assertResourceCalled('Execute', 'ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E /usr/hdp/2.1.0.0-1234/hadoop/sbin/hadoop-daemon.sh --config /usr/hdp/current/hadoop-client/conf start datanode', environment = {'HADOOP_LIBEXEC_DIR': '/usr/hdp/2.1.0.0-1234/hadoop/libexec'}, not_if = "ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E test -f /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid && ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E pgrep -F /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid", ) self.assertNoMoreResources() def test_start_secured_HDP22_non_root_https_only(self): config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/secured.json" with open(config_file, "r") as f: secured_json = json.load(f) secured_json['hostLevelParams']['stack_version']= '2.2' secured_json['configurations']['hdfs-site']['dfs.http.policy']= 'HTTPS_ONLY' secured_json['configurations']['hdfs-site']['dfs.datanode.address']= '0.0.0.0:10000' secured_json['configurations']['hdfs-site']['dfs.datanode.https.address']= '0.0.0.0:50000' self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "start", config_dict = secured_json, stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES ) self.assert_configure_secured("2.3", snappy_enabled=False) self.assertResourceCalled('Directory', '/var/run/hadoop', owner = 'hdfs', group = 'hadoop', mode = 0755 ) self.assertResourceCalled('Directory', '/var/run/hadoop/hdfs', owner = 'hdfs', group = 'hadoop', create_parents = True, ) self.assertResourceCalled('Directory', '/var/log/hadoop/hdfs', owner = 'hdfs', group = 'hadoop', create_parents = True, ) self.assertResourceCalled('File', '/var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid', action = ['delete'], not_if = "ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E test -f /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid && ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E pgrep -F /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid", ) self.assertResourceCalled('Execute', "ambari-sudo.sh su hdfs -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]ulimit -c unlimited ; /usr/hdp/2.1.0.0-1234/hadoop/sbin/hadoop-daemon.sh --config /usr/hdp/current/hadoop-client/conf start datanode'", environment = {'HADOOP_LIBEXEC_DIR': '/usr/hdp/2.1.0.0-1234/hadoop/libexec'}, not_if = "ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E test -f /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid && ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E pgrep -F /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid", ) self.assertNoMoreResources() @patch('time.sleep') @patch("os.path.exists", new = MagicMock(return_value=False)) @patch("resource_management.core.shell.checked_call") def test_stop_secured(self, checked_call_mock, time_mock): def side_effect(arg): if '-D ipc.client.connect.max.retries=5 -D ipc.client.connect.retry.interval=1000 -getDatanodeInfo' in arg : raise Fail() return checked_call_mock.side_effect = side_effect self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "stop", config_file = "secured.json", stack_version = self.STACK_VERSION, checked_call_mocks = side_effect, target = RMFTestCase.TARGET_COMMON_SERVICES ) self.assertResourceCalled('Execute', 'ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E /usr/lib/hadoop/sbin/hadoop-daemon.sh --config /usr/hdp/current/hadoop-client/conf stop datanode', environment = {'HADOOP_LIBEXEC_DIR': '/usr/lib/hadoop/libexec'}, only_if = "ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E test -f /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid && ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E pgrep -F /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid") self.assertResourceCalled('File', '/var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid', action = ['delete']) self.assertNoMoreResources() @patch('time.sleep') @patch("os.path.exists", new = MagicMock(return_value=False)) @patch("resource_management.core.shell.checked_call") def test_stop_secured_HDP22_root(self, checked_call_mock, time_mock): def side_effect(arg): if '-D ipc.client.connect.max.retries=5 -D ipc.client.connect.retry.interval=1000 -getDatanodeInfo' in arg : raise Fail() return checked_call_mock.side_effect = side_effect config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/secured.json" with open(config_file, "r") as f: secured_json = json.load(f) secured_json['hostLevelParams']['stack_version']= '2.2' self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "stop", config_dict = secured_json, stack_version = self.STACK_VERSION, checked_call_mocks = side_effect, target = RMFTestCase.TARGET_COMMON_SERVICES ) self.assertResourceCalled('Execute', 'ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E /usr/hdp/2.1.0.0-1234/hadoop/sbin/hadoop-daemon.sh --config /usr/hdp/current/hadoop-client/conf stop datanode', environment = {'HADOOP_LIBEXEC_DIR': '/usr/hdp/2.1.0.0-1234/hadoop/libexec'}, only_if = "ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E test -f /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid && ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E pgrep -F /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid") self.assertResourceCalled('File', '/var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid', action = ['delete']) self.assertNoMoreResources() @patch('time.sleep') @patch("os.path.exists", new = MagicMock(return_value=False)) @patch("resource_management.core.shell.checked_call") def test_stop_secured_HDP22_non_root_https_only(self, checked_call_mock, time_mock): def side_effect(arg): if '-D ipc.client.connect.max.retries=5 -D ipc.client.connect.retry.interval=1000 -getDatanodeInfo' in arg : raise Fail() return checked_call_mock.side_effect = side_effect config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/secured.json" with open(config_file, "r") as f: secured_json = json.load(f) secured_json['hostLevelParams']['stack_version']= '2.2' secured_json['configurations']['hdfs-site']['dfs.http.policy']= 'HTTPS_ONLY' secured_json['configurations']['hdfs-site']['dfs.datanode.address']= '0.0.0.0:10000' secured_json['configurations']['hdfs-site']['dfs.datanode.https.address']= '0.0.0.0:50000' self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "stop", config_dict = secured_json, stack_version = self.STACK_VERSION, checked_call_mocks = side_effect, target = RMFTestCase.TARGET_COMMON_SERVICES ) self.assertResourceCalled('Execute', "ambari-sudo.sh su hdfs -l -s /bin/bash -c '[RMF_EXPORT_PLACEHOLDER]ulimit -c unlimited ; /usr/hdp/2.1.0.0-1234/hadoop/sbin/hadoop-daemon.sh --config /usr/hdp/current/hadoop-client/conf stop datanode'", environment = {'HADOOP_LIBEXEC_DIR': '/usr/hdp/2.1.0.0-1234/hadoop/libexec'}, only_if = "ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E test -f /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid && ambari-sudo.sh [RMF_ENV_PLACEHOLDER] -H -E pgrep -F /var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid") self.assertResourceCalled('File', '/var/run/hadoop/hdfs/hadoop-hdfs-datanode.pid', action = ['delete']) self.assertNoMoreResources() def assert_configure_default(self): self.assertResourceCalled('Directory', '/usr/lib/hadoop/lib/native/Linux-i386-32', create_parents = True, ) self.assertResourceCalled('Directory', '/usr/lib/hadoop/lib/native/Linux-amd64-64', create_parents = True, ) self.assertResourceCalled('Link', '/usr/lib/hadoop/lib/native/Linux-i386-32/libsnappy.so', to = '/usr/lib/hadoop/lib/libsnappy.so', ) self.assertResourceCalled('Link', '/usr/lib/hadoop/lib/native/Linux-amd64-64/libsnappy.so', to = '/usr/lib/hadoop/lib64/libsnappy.so', ) self.assertResourceCalled('Directory', '/etc/security/limits.d', owner = 'root', group = 'root', create_parents = True, ) self.assertResourceCalled('File', '/etc/security/limits.d/hdfs.conf', content = Template('hdfs.conf.j2'), owner = 'root', group = 'root', mode = 0644, ) self.assertResourceCalled('XmlConfig', 'hdfs-site.xml', owner = 'hdfs', group = 'hadoop', conf_dir = '/usr/hdp/current/hadoop-client/conf', configurations = self.getConfig()['configurations']['hdfs-site'], configuration_attributes = self.getConfig()['configuration_attributes']['hdfs-site'] ) self.assertResourceCalled('XmlConfig', 'core-site.xml', owner = 'hdfs', group = 'hadoop', conf_dir = '/usr/hdp/current/hadoop-client/conf', configurations = self.getConfig()['configurations']['core-site'], configuration_attributes = self.getConfig()['configuration_attributes']['core-site'], mode = 0644 ) self.assertResourceCalled('File', '/usr/hdp/current/hadoop-client/conf/slaves', content = Template('slaves.j2'), owner = 'hdfs', ) self.assertResourceCalled('Directory', '/var/lib/hadoop-hdfs', owner = 'hdfs', group = 'hadoop', mode = 0751, create_parents = True, ) self.assertResourceCalled('Directory', '/var/lib/ambari-agent/data/datanode', mode = 0755, create_parents = True ) self.assertResourceCalled('Directory', '/hadoop/hdfs/data', owner = 'hdfs', ignore_failures = True, group = 'hadoop', mode = 0750, create_parents = True, cd_access='a' ) content = resource_management.libraries.functions.mounted_dirs_helper.DIR_TO_MOUNT_HEADER self.assertResourceCalled('File', '/var/lib/ambari-agent/data/datanode/dfs_data_dir_mount.hist', owner = 'hdfs', group = 'hadoop', mode = 0644, content = content ) def assert_configure_secured(self, stackVersion=STACK_VERSION, snappy_enabled=True): conf_dir = '/usr/hdp/current/hadoop-client/conf' if stackVersion != self.STACK_VERSION: conf_dir = '/usr/hdp/current/hadoop-client/conf' if snappy_enabled: self.assertResourceCalled('Directory', '/usr/lib/hadoop/lib/native/Linux-i386-32', create_parents = True, ) self.assertResourceCalled('Directory', '/usr/lib/hadoop/lib/native/Linux-amd64-64', create_parents = True, ) self.assertResourceCalled('Link', '/usr/lib/hadoop/lib/native/Linux-i386-32/libsnappy.so', to = '/usr/lib/hadoop/lib/libsnappy.so', ) self.assertResourceCalled('Link', '/usr/lib/hadoop/lib/native/Linux-amd64-64/libsnappy.so', to = '/usr/lib/hadoop/lib64/libsnappy.so', ) self.assertResourceCalled('Directory', '/etc/security/limits.d', owner = 'root', group = 'root', create_parents = True, ) self.assertResourceCalled('File', '/etc/security/limits.d/hdfs.conf', content = Template('hdfs.conf.j2'), owner = 'root', group = 'root', mode = 0644, ) self.assertResourceCalled('File', conf_dir + '/hdfs_dn_jaas.conf', content = Template('hdfs_dn_jaas.conf.j2'), owner = 'hdfs', group = 'hadoop', ) self.assertResourceCalled('File', conf_dir + '/hdfs_nn_jaas.conf', content = Template('hdfs_nn_jaas.conf.j2'), owner = 'hdfs', group = 'hadoop', ) self.assertResourceCalled('XmlConfig', 'hdfs-site.xml', owner = 'hdfs', group = 'hadoop', conf_dir = conf_dir, configurations = self.getConfig()['configurations']['hdfs-site'], configuration_attributes = self.getConfig()['configuration_attributes']['hdfs-site'] ) self.assertResourceCalled('XmlConfig', 'core-site.xml', owner = 'hdfs', group = 'hadoop', conf_dir = conf_dir, configurations = self.getConfig()['configurations']['core-site'], configuration_attributes = self.getConfig()['configuration_attributes']['core-site'], mode = 0644 ) self.assertResourceCalled('File', conf_dir + '/slaves', content = Template('slaves.j2'), owner = 'root', ) self.assertResourceCalled('Directory', '/var/lib/hadoop-hdfs', owner = 'hdfs', group = 'hadoop', mode = 0751, create_parents = True, ) self.assertResourceCalled('Directory', '/var/lib/ambari-agent/data/datanode', mode = 0755, create_parents = True ) self.assertResourceCalled('Directory', '/hadoop/hdfs/data', owner = 'hdfs', ignore_failures = True, group = 'hadoop', mode = 0750, create_parents = True, cd_access='a' ) content = resource_management.libraries.functions.mounted_dirs_helper.DIR_TO_MOUNT_HEADER self.assertResourceCalled('File', '/var/lib/ambari-agent/data/datanode/dfs_data_dir_mount.hist', owner = 'hdfs', group = 'hadoop', mode = 0644, content = content ) def test_pre_upgrade_restart(self): config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/default.json" with open(config_file, "r") as f: json_content = json.load(f) version = '2.2.1.0-3242' json_content['commandParams']['version'] = version self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "pre_upgrade_restart", config_dict = json_content, config_overrides = self.CONFIG_OVERRIDES, stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES) self.assertResourceCalled('Execute', ('ambari-python-wrap', '/usr/bin/hdp-select', 'set', 'hadoop-hdfs-datanode', version), sudo=True,) self.assertNoMoreResources() @patch("resource_management.core.shell.call") def test_pre_upgrade_restart_23(self, call_mock): config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/default.json" with open(config_file, "r") as f: json_content = json.load(f) version = '2.3.0.0-1234' json_content['commandParams']['version'] = version mocks_dict = {} self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "pre_upgrade_restart", config_dict = json_content, config_overrides = self.CONFIG_OVERRIDES, stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES, mocks_dict = mocks_dict) self.assertResourceCalled('Execute', ('ambari-python-wrap', '/usr/bin/hdp-select', 'set', 'hadoop-hdfs-datanode', version), sudo=True,) self.assertNoMoreResources() @patch("socket.gethostbyname") @patch('time.sleep') def test_post_upgrade_restart(self, time_mock, socket_gethostbyname_mock): shell_call_output = """ Live datanodes (2): Name: 192.168.64.102:50010 (c6401.ambari.apache.org) Hostname: c6401.ambari.apache.org Decommission Status : Normal Configured Capacity: 524208947200 (488.21 GB) DFS Used: 193069056 (184.13 MB) Non DFS Used: 29264986112 (27.26 GB) DFS Remaining: 494750892032 (460.77 GB) DFS Used%: 0.04% DFS Remaining%: 94.38% Configured Cache Capacity: 0 (0 B) Cache Used: 0 (0 B) Cache Remaining: 0 (0 B) Cache Used%: 100.00% Cache Remaining%: 0.00% Xceivers: 2 Last contact: Fri Dec 12 20:47:21 UTC 2014 """ mocks_dict = {} socket_gethostbyname_mock.return_value = "test_host" self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "post_upgrade_restart", config_file = "default.json", stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES, call_mocks = [(0, shell_call_output)], mocks_dict = mocks_dict ) self.assertTrue(mocks_dict['call'].called) self.assertEqual(mocks_dict['call'].call_count,1) @patch("socket.gethostbyname") @patch('time.sleep') def test_post_upgrade_restart_datanode_not_ready(self, time_mock, socket_gethostbyname_mock): mocks_dict = {} socket_gethostbyname_mock.return_value = "test_host" try: self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "post_upgrade_restart", config_file = "default.json", stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES, call_mocks = [(0, 'There are no DataNodes here!')] * 30, mocks_dict = mocks_dict ) self.fail('Missing DataNode should have caused a failure') except Fail,fail: self.assertTrue(mocks_dict['call'].called) self.assertEqual(mocks_dict['call'].call_count,30) @patch("socket.gethostbyname") @patch('time.sleep') def test_post_upgrade_restart_bad_returncode(self, time_mock, socket_gethostbyname_mock): try: mocks_dict = {} socket_gethostbyname_mock.return_value = "test_host" self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "post_upgrade_restart", config_file = "default.json", stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES, call_mocks = [(1, 'some')] * 30, mocks_dict = mocks_dict ) self.fail('Invalid return code should cause a failure') except Fail,fail: self.assertTrue(mocks_dict['call'].called) self.assertEqual(mocks_dict['call'].call_count,30) @patch("resource_management.core.shell.call") @patch('time.sleep') def test_stop_during_upgrade_not_shutdown(self, time_mock, call_mock): config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/default.json" call_mock_side_effects = [(0, ""), ] call_mock.side_effects = call_mock_side_effects with open(config_file, "r") as f: json_content = json.load(f) version = '2.2.1.0-3242' json_content['commandParams']['version'] = version mocks_dict={} try: self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "stop", config_dict = json_content, stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES, call_mocks = call_mock_side_effects, checked_call_mocks=itertools.cycle([(0, "OK.")]), mocks_dict = mocks_dict, command_args=["rolling"]) raise Fail("Expected a fail since datanode didn't report a shutdown") except Exception, err: expected_message = "DataNode has not yet deregistered from the NameNode..." if str(err.message) != expected_message: self.fail("Expected this exception to be thrown. " + expected_message + ". Got this instead, " + str(err.message)) self.assertEquals( ('hdfs dfsadmin -fs hdfs://c6401.ambari.apache.org:8020 -D ipc.client.connect.max.retries=5 -D ipc.client.connect.retry.interval=1000 -getDatanodeInfo 0.0.0.0:8010'), mocks_dict['checked_call'].call_args_list[0][0][0]) @patch("resource_management.core.shell.call") @patch('time.sleep') def test_stop_during_upgrade_not_shutdown_ha(self, time_mock, call_mock): config_file = self.get_src_folder()+"/test/python/stacks/2.0.6/configs/ha_default.json" call_mock_side_effects = [(0, ""), ] call_mock.side_effects = call_mock_side_effects with open(config_file, "r") as f: json_content = json.load(f) version = '2.2.1.0-3242' json_content['commandParams']['version'] = version mocks_dict={} try: self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts/datanode.py", classname = "DataNode", command = "stop", config_dict = json_content, stack_version = self.STACK_VERSION, target = RMFTestCase.TARGET_COMMON_SERVICES, call_mocks = call_mock_side_effects, checked_call_mocks=itertools.cycle([(0, "OK.")]), mocks_dict = mocks_dict, command_args=["rolling"]) raise Fail("Expected a fail since datanode didn't report a shutdown") except Exception, err: expected_message = "DataNode has not yet deregistered from the NameNode..." if str(err.message) != expected_message: self.fail("Expected this exception to be thrown. " + expected_message + ". Got this instead, " + str(err.message)) self.assertEquals( ('hdfs dfsadmin -fs hdfs://ns1 -D ipc.client.connect.max.retries=5 -D ipc.client.connect.retry.interval=1000 -getDatanodeInfo 0.0.0.0:8010'), mocks_dict['checked_call'].call_args_list[0][0][0])
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Train an Auxiliary Classifier Generative Adversarial Network (ACGAN) on the MNIST dataset. See https://arxiv.org/abs/1610.09585 for more details. You should start to see reasonable images after ~5 epochs, and good images by ~15 epochs. You should use a GPU, as the convolution-heavy operations are very slow on the CPU. Prefer the TensorFlow backend if you plan on iterating, as the compilation time can be a blocker using Theano. Timings: Hardware | Backend | Time / Epoch ------------------------------------------- CPU | TF | 3 hrs Titan X (maxwell) | TF | 4 min Titan X (maxwell) | TH | 7 min Consult https://github.com/lukedeo/keras-acgan for more information and example output """ from __future__ import print_function from collections import defaultdict try: import cPickle as pickle except ImportError: import pickle from PIL import Image # from six.moves import range import os os.environ['KERAS_BACKEND']='tensorflow' import keras.backend as K K.set_image_dim_ordering('th') from keras.datasets import mnist from keras.layers import Input, Dense, Reshape, Flatten, Embedding, merge, Dropout from keras.layers.advanced_activations import LeakyReLU from keras.layers.convolutional import UpSampling2D, Convolution2D from keras.models import Sequential, Model from keras.optimizers import Adam from keras.utils.generic_utils import Progbar import numpy as np np.random.seed(1337) def build_generator(latent_size): # we will map a pair of (z, L), where z is a latent vector and L is a # label drawn from P_c, to image space (..., 1, 28, 28) cnn = Sequential() cnn.add(Dense(1024, input_dim=latent_size, activation='relu')) cnn.add(Dense(128 * 7 * 7, activation='relu')) cnn.add(Reshape((128, 7, 7))) # upsample to (..., 14, 14) cnn.add(UpSampling2D(size=(2, 2))) cnn.add(Convolution2D(256, 5, 5, border_mode='same', activation='relu', init='glorot_normal')) # upsample to (..., 28, 28) cnn.add(UpSampling2D(size=(2, 2))) cnn.add(Convolution2D(128, 5, 5, border_mode='same', activation='relu', init='glorot_normal')) # take a channel axis reduction cnn.add(Convolution2D(1, 2, 2, border_mode='same', activation='tanh', init='glorot_normal')) # this is the z space commonly refered to in GAN papers latent = Input(shape=(latent_size, )) # this will be our label image_class = Input(shape=(1,), dtype='int32') # 10 classes in MNIST cls = Flatten()(Embedding(10, latent_size, init='glorot_normal')(image_class)) # hadamard product between z-space and a class conditional embedding h = merge([latent, cls], mode='mul') fake_image = cnn(h) return Model(input=[latent, image_class], output=fake_image) def build_discriminator(): # build a relatively standard conv net, with LeakyReLUs as suggested in # the reference paper cnn = Sequential() cnn.add(Convolution2D(32, 3, 3, border_mode='same', subsample=(2, 2), input_shape=(1, 28, 28))) cnn.add(LeakyReLU()) cnn.add(Dropout(0.3)) cnn.add(Convolution2D(64, 3, 3, border_mode='same', subsample=(1, 1))) cnn.add(LeakyReLU()) cnn.add(Dropout(0.3)) cnn.add(Convolution2D(128, 3, 3, border_mode='same', subsample=(2, 2))) cnn.add(LeakyReLU()) cnn.add(Dropout(0.3)) cnn.add(Convolution2D(256, 3, 3, border_mode='same', subsample=(1, 1))) cnn.add(LeakyReLU()) cnn.add(Dropout(0.3)) cnn.add(Flatten()) image = Input(shape=(1, 28, 28)) features = cnn(image) # first output (name=generation) is whether or not the discriminator # thinks the image that is being shown is fake, and the second output # (name=auxiliary) is the class that the discriminator thinks the image # belongs to. fake = Dense(1, activation='sigmoid', name='generation')(features) aux = Dense(10, activation='softmax', name='auxiliary')(features) return Model(input=image, output=[fake, aux]) if __name__ == '__main__': # batch and latent size taken from the paper nb_epochs = 50 batch_size = 100 latent_size = 100 # Adam parameters suggested in https://arxiv.org/abs/1511.06434 adam_lr = 0.0002 adam_beta_1 = 0.5 # build the discriminator discriminator = build_discriminator() discriminator.compile( optimizer=Adam(lr=adam_lr, beta_1=adam_beta_1), loss=['binary_crossentropy', 'sparse_categorical_crossentropy'] ) # build the generator generator = build_generator(latent_size) generator.compile(optimizer=Adam(lr=adam_lr, beta_1=adam_beta_1), loss='binary_crossentropy') latent = Input(shape=(latent_size, )) image_class = Input(shape=(1,), dtype='int32') # get a fake image fake = generator([latent, image_class]) # we only want to be able to train generation for the combined model discriminator.trainable = False fake, aux = discriminator(fake) combined = Model(input=[latent, image_class], output=[fake, aux]) combined.compile( optimizer=Adam(lr=adam_lr, beta_1=adam_beta_1), loss=['binary_crossentropy', 'sparse_categorical_crossentropy'] ) # get our mnist data, and force it to be of shape (..., 1, 28, 28) with # range [-1, 1] (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = (X_train.astype(np.float32) - 127.5) / 127.5 X_train = np.expand_dims(X_train, axis=1) X_test = (X_test.astype(np.float32) - 127.5) / 127.5 X_test = np.expand_dims(X_test, axis=1) nb_train, nb_test = X_train.shape[0], X_test.shape[0] train_history = defaultdict(list) test_history = defaultdict(list) for epoch in range(nb_epochs): print('Epoch {} of {}'.format(epoch + 1, nb_epochs)) nb_batches = int(X_train.shape[0] / batch_size) progress_bar = Progbar(target=nb_batches) epoch_gen_loss = [] epoch_disc_loss = [] for index in range(nb_batches): progress_bar.update(index) # generate a new batch of noise noise = np.random.uniform(-1, 1, (batch_size, latent_size)) # get a batch of real images image_batch = X_train[index * batch_size:(index + 1) * batch_size] label_batch = y_train[index * batch_size:(index + 1) * batch_size] # sample some labels from p_c sampled_labels = np.random.randint(0, 10, batch_size) # generate a batch of fake images, using the generated labels as a # conditioner. We reshape the sampled labels to be # (batch_size, 1) so that we can feed them into the embedding # layer as a length one sequence generated_images = generator.predict( [noise, sampled_labels.reshape((-1, 1))], verbose=0) X = np.concatenate((image_batch, generated_images)) y = np.array([1] * batch_size + [0] * batch_size) aux_y = np.concatenate((label_batch, sampled_labels), axis=0) # see if the discriminator can figure itself out... epoch_disc_loss.append(discriminator.train_on_batch(X, [y, aux_y])) # make new noise. we generate 2 * batch size here such that we have # the generator optimize over an identical number of images as the # discriminator noise = np.random.uniform(-1, 1, (2 * batch_size, latent_size)) sampled_labels = np.random.randint(0, 10, 2 * batch_size) # we want to train the genrator to trick the discriminator # For the generator, we want all the {fake, not-fake} labels to say # not-fake trick = np.ones(2 * batch_size) epoch_gen_loss.append(combined.train_on_batch( [noise, sampled_labels.reshape((-1, 1))], [trick, sampled_labels])) print('\nTesting for epoch {}:'.format(epoch + 1)) # evaluate the testing loss here # generate a new batch of noise noise = np.random.uniform(-1, 1, (nb_test, latent_size)) # sample some labels from p_c and generate images from them sampled_labels = np.random.randint(0, 10, nb_test) generated_images = generator.predict( [noise, sampled_labels.reshape((-1, 1))], verbose=False) X = np.concatenate((X_test, generated_images)) y = np.array([1] * nb_test + [0] * nb_test) aux_y = np.concatenate((y_test, sampled_labels), axis=0) # see if the discriminator can figure itself out... discriminator_test_loss = discriminator.evaluate( X, [y, aux_y], verbose=False) discriminator_train_loss = np.mean(np.array(epoch_disc_loss), axis=0) # make new noise noise = np.random.uniform(-1, 1, (2 * nb_test, latent_size)) sampled_labels = np.random.randint(0, 10, 2 * nb_test) trick = np.ones(2 * nb_test) generator_test_loss = combined.evaluate( [noise, sampled_labels.reshape((-1, 1))], [trick, sampled_labels], verbose=False) generator_train_loss = np.mean(np.array(epoch_gen_loss), axis=0) # generate an epoch report on performance train_history['generator'].append(generator_train_loss) train_history['discriminator'].append(discriminator_train_loss) test_history['generator'].append(generator_test_loss) test_history['discriminator'].append(discriminator_test_loss) print('{0:<22s} | {1:4s} | {2:15s} | {3:5s}'.format( 'component', *discriminator.metrics_names)) print('-' * 65) ROW_FMT = '{0:<22s} | {1:<4.2f} | {2:<15.2f} | {3:<5.2f}' print(ROW_FMT.format('generator (train)', *train_history['generator'][-1])) print(ROW_FMT.format('generator (test)', *test_history['generator'][-1])) print(ROW_FMT.format('discriminator (train)', *train_history['discriminator'][-1])) print(ROW_FMT.format('discriminator (test)', *test_history['discriminator'][-1])) # save weights every epoch generator.save_weights( 'params_generator_epoch_{0:03d}.hdf5'.format(epoch), True) discriminator.save_weights( 'params_discriminator_epoch_{0:03d}.hdf5'.format(epoch), True) # generate some digits to display noise = np.random.uniform(-1, 1, (100, latent_size)) sampled_labels = np.array([ [i] * 10 for i in range(10) ]).reshape(-1, 1) # get a batch to display generated_images = generator.predict( [noise, sampled_labels], verbose=0) # arrange them into a grid img = (np.concatenate([r.reshape(-1, 28) for r in np.split(generated_images, 10) ], axis=-1) * 127.5 + 127.5).astype(np.uint8) Image.fromarray(img).save( 'plot_epoch_{0:03d}_generated.png'.format(epoch)) pickle.dump({'train': train_history, 'test': test_history}, open('acgan-history.pkl', 'wb'))
from __future__ import unicode_literals import re from django.template import Library from django.template.loader import get_template from django.utils import six from django.utils.encoding import force_text try: from django.template.base import TemplateDoesNotExist except ImportError: from django.template.exceptions import TemplateDoesNotExist from ..loaders import get_silhouette from ..utils import normalize register = Library() def silhouette_tag(tag_name): """ Register a class as a template tag. The class must be initialised with a context, and object and keyword arguments, and implement __enter__, __exit__ and render """ def register_tag(silhouette_class): def tag(context, obj, **kwargs): silhouette = silhouette_class(context, obj, **kwargs) with silhouette as context: return silhouette.render(context) register.simple_tag(tag, True, tag_name) return silhouette_class return register_tag class BaseSilhouette(object): """ Base class for Silhouette Renderers """ PATH_CONTEXT_KEY = 'silhouette_path' THEME_CONTEXT_KEY = 'silhouette_theme' def __init__(self, context, obj, template=None, theme=None, path=None, **kwargs): self.context = context self.obj = obj self.path_override = path or context.get(self.PATH_CONTEXT_KEY, None) self.theme_override = theme or context.get(self.THEME_CONTEXT_KEY, None) self.template_override = template self.kwargs = kwargs def __enter__(self): scope = {self.PATH_CONTEXT_KEY: self.path_override, self.THEME_CONTEXT_KEY: self.theme_override} scope.update(self.get_extra_context()) self.context.update(scope) return self.context def __exit__(self, *args, **kwargs): self.context.pop() @property def template_type(self): """ Template type to use when loading the tag template. It corresponds to a key in silhouette.settings.PATTERNS. """ return normalize(type(self).__name__) @property def template(self): """ Load a template based on the object's template_type or template_override. """ if self.template_override: return get_template(self.template_override) return get_silhouette(self.obj, self.template_type, path=self.path_override, theme=self.theme_override) def merge_attrs(self, *holders): """ Merge html attributes from different holders. CSS classes are concatenated and all other attributes are overridden with the rightmost holders taking precedence over the leftmost holders. """ attrs = {} classes = [] for holder in holders: if 'class' in holder: classes.append(holder['class']) attrs.update({k: v for k, v in six.iteritems(holder) if v is not None}) if classes: attrs['class'] = ' '.join(set(' '.join([cls.strip() for cls in classes if cls is not None]).split(' '))) return attrs def build_attrs(self, attrs, *prefixes): """ Nest html attributes by prefix. Non prefixed attributes fall under the default "attrs" key """ if not prefixes: return {'attrs': attrs} split_attrs = {'attrs': {}} for key, value in six.iteritems(attrs): match = re.match("^({})_".format("|".join(re.escape(p) for p in prefixes)), key) if match: parent_key, nested_key = "{}_attrs".format(key[:match.end() - 1]), key[match.end():] if parent_key not in split_attrs: split_attrs[parent_key] = {} split_attrs[parent_key][nested_key] = value else: split_attrs['attrs'][key] = value return split_attrs def cascaded_attrs(self, prefix, context=None): """ Retrieve cascaded attributes for prefix from context """ context = context or self.context return context.get("{}_attrs".format(prefix), {}) def render(self, context): """ Render template using context """ return self.template.render(context) def get_extra_context(self): # pragma: no cover """ Extra variables for context that are added before rendering and removed after rendering """ raise NotImplementedError() class BaseFormSilhouette(BaseSilhouette): """ Base class for Form Silhouette Renderers """ @property def form(self): return self.obj def get_extra_context(self): return {'form': self.form} @silhouette_tag("silhouette") class Form(BaseFormSilhouette): def get_extra_context(self): ctx = super(Form, self).get_extra_context() ctx.update(self.build_attrs(self.kwargs, 'errors', 'media', 'controls', 'fields')) return ctx @silhouette_tag("form_fields") class FormFields(BaseFormSilhouette): def get_extra_context(self): ctx = super(FormFields, self).get_extra_context() ctx.update(self.build_attrs(self.merge_attrs(self.cascaded_attrs('fields'), self.kwargs))) return ctx @silhouette_tag("form_errors") class FormErrors(BaseFormSilhouette): def get_extra_context(self): ctx = super(FormErrors, self).get_extra_context() ctx.update(self.build_attrs(self.merge_attrs(self.cascaded_attrs('errors'), self.kwargs))) return ctx def render(self, context): try: return super(FormErrors, self).render(context) except TemplateDoesNotExist: return force_text(self.form.non_field_errors()) @silhouette_tag("form_controls") class FormControls(BaseFormSilhouette): def get_extra_context(self): ctx = super(FormControls, self).get_extra_context() attrs = self.merge_attrs(self.cascaded_attrs('controls'), self.kwargs) non_attrs = {'contents': attrs.pop('contents', None)} ctx.update(non_attrs) ctx.update(self.build_attrs(attrs)) return ctx def render(self, context): try: return super(FormControls, self).render(context) except TemplateDoesNotExist: return "" @silhouette_tag("form_media") class FormMedia(BaseFormSilhouette): def get_extra_context(self): ctx = super(FormMedia, self).get_extra_context() ctx.update(self.build_attrs(self.merge_attrs(self.cascaded_attrs('media'), self.kwargs))) return ctx def render(self, context): try: return super(FormMedia, self).render(context) except TemplateDoesNotExist: return force_text(self.obj.media) class BaseFormsetSilhouette(BaseSilhouette): """ Base class for Formset Silhouette Renderers """ @property def formset(self): return self.obj def get_extra_context(self): return {'formset': self.formset} @silhouette_tag("formset") class Formset(BaseFormsetSilhouette): def get_extra_context(self): ctx = super(Formset, self).get_extra_context() ctx.update(self.build_attrs(self.kwargs, 'errors', 'fields')) return ctx @silhouette_tag("formset_errors") class FormsetErrors(BaseFormsetSilhouette): def get_extra_context(self): ctx = super(FormsetErrors, self).get_extra_context() ctx.update(self.build_attrs(self.merge_attrs(self.cascaded_attrs('errors'), self.kwargs))) return ctx class BaseFieldSilhouette(BaseSilhouette): """ Base class for Field Silhouette Renderers """ @property def bound_field(self): return self.obj def get_extra_context(self): return {'field': self.bound_field} def __enter__(self): context = super(BaseFieldSilhouette, self).__enter__() self.widget_original_attrs = self.bound_field.field.widget.attrs self.bound_field.field.widget.attrs = self.get_widget_attrs_for_scope(context) return context def __exit__(self, *args, **kwargs): self.bound_field.field.widget.attrs = self.widget_original_attrs super(BaseFieldSilhouette, self).__exit__(*args, **kwargs) def get_widget_attrs_for_scope(self, context): # pragma: nocover """ Widget attributes for the current scope, as some widget attributes affect attributes of other elements (e.g. label "for" uses the widget's id). """ raise NotImplementedError() @silhouette_tag("field") class Field(BaseFieldSilhouette): def get_widget_attrs_for_scope(self, context): return self.merge_attrs(self.bound_field.field.widget.attrs, self.cascaded_attrs('widget', context)) def get_extra_context(self): ctx = super(Field, self).get_extra_context() ctx.update(self.build_attrs(self.merge_attrs(self.kwargs), 'label', 'widget', 'errors', 'help_text')) return ctx @silhouette_tag("field_widget") class FieldWidget(BaseFieldSilhouette): def get_widget_attrs_for_scope(self, context): return context.get('attrs', {}) def get_extra_context(self): ctx = super(FieldWidget, self).get_extra_context() ctx.update(self.build_attrs(self.merge_attrs(self.bound_field.field.widget.attrs, self.cascaded_attrs('widget'), self.kwargs))) return ctx def render(self, context): try: return super(FieldWidget, self).render(context) except TemplateDoesNotExist: return self.bound_field.as_widget() @silhouette_tag("field_label") class FieldLabel(BaseFieldSilhouette): def get_widget_attrs_for_scope(self, context): return self.merge_attrs(self.bound_field.field.widget.attrs, {'id': context.get('attrs', {}).get('for', None)}) def get_extra_context(self): ctx = super(FieldLabel, self).get_extra_context() attrs = self.merge_attrs(self.cascaded_attrs('label'), self.kwargs) non_attrs = {'contents': attrs.pop('contents', None), 'suffix': attrs.pop('suffix', None)} ctx.update(non_attrs) ctx.update(self.build_attrs(attrs)) return ctx def render(self, context): try: return super(FieldLabel, self).render(context) except TemplateDoesNotExist: return self.bound_field.label_tag(contents=context.get('contents'), attrs=context.get('attrs'), label_suffix=context.get('suffix')) @silhouette_tag("field_help_text") class FieldHelpText(BaseFieldSilhouette): def get_widget_attrs_for_scope(self, context): return self.bound_field.field.widget.attrs def get_extra_context(self): ctx = super(FieldHelpText, self).get_extra_context() attrs = self.merge_attrs(self.cascaded_attrs('help_text'), self.kwargs) non_attrs = {'contents': attrs.pop('contents', None)} ctx.update(non_attrs) ctx.update(self.build_attrs(attrs)) return ctx def render(self, context): try: return super(FieldHelpText, self).render(context) except TemplateDoesNotExist: return context.get('contents') or self.bound_field.help_text @silhouette_tag("field_errors") class FieldErrors(BaseFieldSilhouette): def get_widget_attrs_for_scope(self, context): return self.bound_field.field.widget.attrs def get_extra_context(self): ctx = super(FieldErrors, self).get_extra_context() ctx.update(self.build_attrs(self.merge_attrs(self.cascaded_attrs('errors'), self.kwargs))) return ctx def render(self, context): try: return super(FieldErrors, self).render(context) except TemplateDoesNotExist: return force_text(self.bound_field.errors)
import mock import libvirt import difflib import unittest from see.context.resources import lxc def compare(text1, text2): """Utility function for comparing text and returining differences.""" diff = difflib.ndiff(text1.splitlines(True), text2.splitlines(True)) return '\n' + '\n'.join(diff) class DomainXMLTest(unittest.TestCase): def test_domain_xml(self): """LXC XML with no network and no filesystem.""" config = """<domain></domain>""" expected = """<domain><name>foo</name><uuid>foo</uuid><devices /></domain>""" results = lxc.domain_xml('foo', config, []) self.assertEqual(results, expected, compare(results, expected)) def test_domain_xml_filesystem(self): """LXC XML with filesystem.""" config = """<domain></domain>""" expected = """<domain><name>foo</name><uuid>foo</uuid><devices><filesystem type="mount">""" +\ """<source dir="foo" /><target dir="bar" /></filesystem></devices></domain>""" results = lxc.domain_xml('foo', config, [('foo', 'bar')]) self.assertEqual(results, expected, compare(results, expected)) def test_domain_xml_modifies(self): """LXC Fields are modified if existing.""" config = """<domain><name>bar</name><uuid>bar</uuid></domain>""" expected = """<domain><name>foo</name><uuid>foo</uuid><devices><filesystem type="mount">""" +\ """<source dir="foo" /><target dir="bar" /></filesystem></devices></domain>""" results = lxc.domain_xml('foo', config, [('foo', 'bar')]) self.assertEqual(results, expected, compare(results, expected)) def test_domain_xml_network(self): """LXC XML with network fields are modified if existing.""" config = """<domain></domain>""" expected = """<domain><name>foo</name><uuid>foo</uuid><devices><filesystem type="mount">""" +\ """<source dir="foo" /><target dir="bar" /></filesystem><interface type="network">""" +\ """<source network="foo" /></interface></devices></domain>""" results = lxc.domain_xml('foo', config, [('foo', 'bar')], network_name='foo') self.assertEqual(results, expected, compare(results, expected)) def test_domain_xml_network_modifies(self): """LXC XML with network.""" config = """<domain><devices><interface type="network">""" +\ """<source network="bar"/></interface></devices></domain>""" expected = """<domain><devices><interface type="network"><source network="foo" /></interface>""" +\ """<filesystem type="mount"><source dir="foo" /><target dir="bar" /></filesystem>""" +\ """</devices><name>foo</name><uuid>foo</uuid></domain>""" results = lxc.domain_xml('foo', config, [('foo', 'bar')], network_name='foo') self.assertEqual(results, expected, compare(results, expected)) class DomainCreateTest(unittest.TestCase): def test_create(self): """LXC Create with no network and no filesystem.""" xml = """<domain></domain>""" expected = """<domain><name>foo</name><uuid>foo</uuid><devices /></domain>""" hypervisor = mock.Mock() hypervisor.listNetworks.return_value = [] with mock.patch('see.context.resources.lxc.open', mock.mock_open(read_data=xml), create=True): lxc.domain_create(hypervisor, 'foo', {'configuration': '/foo'}) results = hypervisor.defineXML.call_args_list[0][0][0] self.assertEqual(results, expected, compare(results, expected)) def test_create_filesystem(self): """LXC Create with single filesystem.""" xml = """<domain></domain>""" expected = """<domain><name>foo</name><uuid>foo</uuid><devices><filesystem type="mount">""" +\ """<source dir="/bar/foo" /><target dir="/baz" /></filesystem></devices></domain>""" hypervisor = mock.Mock() hypervisor.listNetworks.return_value = [] with mock.patch('see.context.resources.lxc.open', mock.mock_open(read_data=xml), create=True): with mock.patch('see.context.resources.lxc.os.makedirs'): lxc.domain_create(hypervisor, 'foo', {'configuration': '/foo', 'filesystem': {'source_path': '/bar', 'target_path': '/baz'}}) results = hypervisor.defineXML.call_args_list[0][0][0] self.assertEqual(results, expected, compare(results, expected)) def test_create_filesystems(self): """LXC Create with multiple filesystem.""" xml = """<domain></domain>""" expected = """<domain><name>foo</name><uuid>foo</uuid><devices><filesystem type="mount">""" +\ """<source dir="/bar/foo" /><target dir="/baz" /></filesystem><filesystem type="mount">""" +\ """<source dir="/dead/foo" /><target dir="/beef" /></filesystem></devices></domain>""" hypervisor = mock.Mock() hypervisor.listNetworks.return_value = [] with mock.patch('see.context.resources.lxc.open', mock.mock_open(read_data=xml), create=True): with mock.patch('see.context.resources.lxc.os.makedirs'): lxc.domain_create(hypervisor, 'foo', {'configuration': '/foo', 'filesystem': [{'source_path': '/bar', 'target_path': '/baz'}, {'source_path': '/dead', 'target_path': '/beef'}]}) results = hypervisor.defineXML.call_args_list[0][0][0] self.assertEqual(results, expected, compare(results, expected)) def test_create_network(self): """LXC Create with network.""" xml = """<domain></domain>""" expected = """<domain><name>foo</name><uuid>foo</uuid><devices><filesystem type="mount">""" +\ """<source dir="/bar/foo" /><target dir="/baz" /></filesystem><interface type="network">""" +\ """<source network="foo" /></interface></devices></domain>""" hypervisor = mock.Mock() hypervisor.listNetworks.return_value = [] with mock.patch('see.context.resources.lxc.open', mock.mock_open(read_data=xml), create=True): with mock.patch('see.context.resources.lxc.os.makedirs'): lxc.domain_create(hypervisor, 'foo', {'configuration': '/foo', 'filesystem': {'source_path': '/bar', 'target_path': '/baz'}}, network_name='foo') results = hypervisor.defineXML.call_args_list[0][0][0] self.assertEqual(results, expected, compare(results, expected)) class DomainDelete(unittest.TestCase): def test_delete_destroy(self): """LXC Domain is destroyed if active.""" domain = mock.Mock() logger = mock.Mock() domain.isActive.return_value = True lxc.domain_delete(domain, logger, None) self.assertTrue(domain.destroy.called) def test_delete_destroy_error(self): """LXC Domain destroy raises error.""" domain = mock.Mock() logger = mock.Mock() domain.isActive.return_value = True domain.destroy.side_effect = libvirt.libvirtError("BOOM") lxc.domain_delete(domain, logger, None) self.assertTrue(domain.undefine.called) def test_delete_undefine(self): """LXC Domain is undefined.""" domain = mock.Mock() logger = mock.Mock() domain.isActive.return_value = False lxc.domain_delete(domain, logger, None) self.assertTrue(domain.undefine.called) @mock.patch('see.context.resources.lxc.os.path.exists') def test_delete_undefine_error(self, os_mock): """LXC Domain undefine raises error.""" domain = mock.Mock() logger = mock.Mock() domain.isActive.return_value = False domain.undefine.side_effect = libvirt.libvirtError("BOOM") lxc.domain_delete(domain, logger, '/foo/bar/baz') self.assertTrue(os_mock.called) @mock.patch('see.context.resources.lxc.shutil.rmtree') @mock.patch('see.context.resources.lxc.os.path.exists') def test_delete_filesystem(self, os_mock, rm_mock): """LXC Domain is undefined.""" domain = mock.Mock() logger = mock.Mock() domain.isActive.return_value = False os_mock.return_value = True lxc.domain_delete(domain, logger, 'foo/bar/baz') rm_mock.assert_called_with('foo/bar/baz') @mock.patch('see.context.resources.lxc.network') class ResourcesTest(unittest.TestCase): @mock.patch('see.context.resources.lxc.libvirt') @mock.patch('see.context.resources.lxc.domain_create') def test_allocate_default(self, create_mock, libvirt_mock, network_mock): """LXC Resources allocator with no extra value.""" network_mock.lookup.return_value = None resources = lxc.LXCResources('foo', {'domain': 'bar'}) resources.allocate() libvirt_mock.open.assert_called_with('lxc:///') create_mock.assert_called_with(resources.hypervisor, 'foo', 'bar', network_name=None) @mock.patch('see.context.resources.lxc.libvirt') @mock.patch('see.context.resources.lxc.domain_create') def test_allocate_hypervisor(self, create_mock, libvirt_mock, network_mock): """LXC Resources allocator with hypervisor.""" network_mock.lookup.return_value = None resources = lxc.LXCResources('foo', {'domain': 'bar', 'hypervisor': 'baz'}) resources.allocate() libvirt_mock.open.assert_called_with('baz') create_mock.assert_called_with(resources.hypervisor, 'foo', 'bar', network_name=None) @mock.patch('see.context.resources.lxc.libvirt') @mock.patch('see.context.resources.lxc.domain_create') def test_allocate_network(self, create_mock, libvirt_mock, network_mock): """LXC Resources allocator with network.""" network = mock.Mock() network.name.return_value = 'baz' network_mock.lookup = mock.Mock() network_mock.create.return_value = network resources = lxc.LXCResources('foo', {'domain': 'bar', 'network': 'baz', 'disk': {'image': '/foo/bar'}}) resources.allocate() network_mock.create.assert_called_with(resources.hypervisor, 'foo', 'baz') create_mock.assert_called_with(resources.hypervisor, 'foo', 'bar', network_name='baz') @mock.patch('see.context.resources.lxc.libvirt') @mock.patch('see.context.resources.lxc.domain_create') def test_allocate_fail(self, create_mock, libvirt_mock, network_mock): """LXC network is destroyed on allocation fail.""" network = mock.Mock() network.name.return_value = 'baz' network_mock.lookup = mock.Mock() network_mock.create.return_value = network resources = lxc.LXCResources('foo', {'domain': 'bar', 'network': 'baz', 'disk': {'image': '/foo/bar'}}) create_mock.side_effect = libvirt.libvirtError('BOOM') with self.assertRaises(libvirt.libvirtError): resources.allocate() resources.deallocate() network_mock.delete.assert_called_with(resources.network) @mock.patch('see.context.resources.lxc.domain_delete') def test_deallocate_no_creation(self, delete_mock, network_mock): """LXC Resources are released on deallocate. Network not created""" resources = lxc.LXCResources('foo', {'domain': 'bar'}) resources._domain = mock.Mock() resources._network = mock.Mock() resources._hypervisor = mock.Mock() resources.deallocate() delete_mock.assert_called_with(resources.domain, mock.ANY, None) self.assertFalse(network_mock.delete.called) self.assertTrue(resources._hypervisor.close.called) @mock.patch('see.context.resources.lxc.domain_delete') def test_deallocate_creation(self, delete_mock, network_mock): """LXC Resources are released on deallocate. Network created""" resources = lxc.LXCResources('foo', {'domain': 'bar', 'network': {}}) resources._domain = mock.Mock() resources._network = mock.Mock() resources._hypervisor = mock.Mock() resources.deallocate() delete_mock.assert_called_with(resources.domain, mock.ANY, None) network_mock.delete.assert_called_with(resources.network) self.assertTrue(resources._hypervisor.close.called) @mock.patch('see.context.resources.lxc.domain_delete') def test_deallocate_filesystem(self, delete_mock, network_mock): """LXC Shared folder is cleaned up.""" resources = lxc.LXCResources('foo', {'domain': 'bar', 'filesystem': {'source_path': '/bar', 'target_path': '/baz'}}) resources._domain = mock.Mock() resources._network = mock.Mock() resources._hypervisor = mock.Mock() resources.deallocate() delete_mock.assert_called_with(resources.domain, mock.ANY, '/bar/foo')
import asyncio from aiohttp import web from aiohttp.web_exceptions import HTTPBadRequest, HTTPNoContent import virtool.http.routes import virtool.otus.db import virtool.otus.isolates import virtool.otus.sequences import virtool.references.db import virtool.validators from virtool.api.response import InsufficientRights, NotFound, json_response from virtool.db.transforms import apply_transforms from virtool.history.db import LIST_PROJECTION from virtool.http.schema import schema from virtool.otus.utils import evaluate_changes, find_isolate from virtool.users.db import AttachUserTransform from virtool.utils import base_processor SCHEMA_VALIDATOR = { "type": "list", "check_with": virtool.validators.has_unique_segment_names, "schema": { "type": "dict", "allow_unknown": False, "schema": { "name": {"type": "string", "required": True}, "required": {"type": "boolean", "default": True}, "molecule": { "type": "string", "default": "", "allowed": ["", "ssDNA", "dsDNA", "ssRNA", "ssRNA+", "ssRNA-", "dsRNA"], }, }, }, } routes = virtool.http.routes.Routes() @routes.get("/otus/{otu_id}.fa") @routes.jobs_api.get("/otus/{otu_id}.fa") async def download_otu(req): """ Download a FASTA file containing the sequences for all isolates in a single Virtool otu. """ db = req.app["db"] otu_id = req.match_info["otu_id"] if not await db.otus.count_documents({"_id": otu_id}): raise NotFound("OTU not found") filename, fasta = await virtool.otus.db.generate_otu_fasta(db, otu_id) return web.Response( text=fasta, headers={"Content-Disposition": f"attachment; filename={filename}"} ) @routes.get("/otus") async def find(req): """ Find otus. """ db = req.app["db"] term = req["query"].get("find") verified = req["query"].get("verified") names = req["query"].get("names", False) data = await virtool.otus.db.find(db, names, term, req["query"], verified) return json_response(data) @routes.get("/otus/{otu_id}") async def get(req): """ Get a complete otu document. Joins the otu document with its associated sequence documents. """ db = req.app["db"] otu_id = req.match_info["otu_id"] complete = await virtool.otus.db.join_and_format(db, otu_id) if not complete: raise NotFound() return json_response(complete) @routes.post("/refs/{ref_id}/otus") @schema( { "name": { "type": "string", "coerce": virtool.validators.strip, "empty": False, "required": True, }, "abbreviation": { "type": "string", "coerce": virtool.validators.strip, "default": "", }, "schema": SCHEMA_VALIDATOR, } ) async def create(req): """ Add a new otu to the collection. Checks to make sure the supplied otu name and abbreviation are not already in use in the collection. Any errors are sent back to the client. """ db = req.app["db"] data = req["data"] ref_id = req.match_info["ref_id"] reference = await db.references.find_one(ref_id, ["groups", "users"]) if reference is None: raise NotFound() if not await virtool.references.db.check_right(req, reference, "modify_otu"): raise InsufficientRights() name = data["name"].strip() abbreviation = data["abbreviation"].strip() # Check if either the name or abbreviation are already in use. Send a ``400`` if # they are. message = await virtool.otus.db.check_name_and_abbreviation( db, ref_id, name, abbreviation ) if message: raise HTTPBadRequest(text=message) document = await asyncio.shield( virtool.otus.db.create_otu( req.app, ref_id, name, abbreviation, req["client"].user_id ) ) headers = {"Location": "/otus/" + document["id"]} return json_response(document, status=201, headers=headers) @routes.patch("/otus/{otu_id}") @schema( { "name": {"type": "string", "coerce": virtool.validators.strip, "empty": False}, "abbreviation": {"type": "string", "coerce": virtool.validators.strip}, "schema": SCHEMA_VALIDATOR, } ) async def edit(req): """ Edit an existing OTU. Checks to make sure the supplied OTU name and abbreviation are not already in use in the collection. """ db = req.app["db"] data = req["data"] otu_id = req.match_info["otu_id"] # Get existing complete otu record, at the same time ensuring it exists. Send a # ``404`` if not. document = await db.otus.find_one( otu_id, ["abbreviation", "name", "reference", "schema"] ) if not document: raise NotFound() ref_id = document["reference"]["id"] if not await virtool.references.db.check_right(req, ref_id, "modify_otu"): raise InsufficientRights() name, abbreviation, otu_schema = evaluate_changes(data, document) # Send ``200`` with the existing otu record if no change will be made. if name is None and abbreviation is None and otu_schema is None: return json_response(await virtool.otus.db.join_and_format(db, otu_id)) # Make sure new name or abbreviation are not already in use. message = await virtool.otus.db.check_name_and_abbreviation( db, ref_id, name, abbreviation ) if message: raise HTTPBadRequest(text=message) document = await asyncio.shield( virtool.otus.db.edit( req.app, otu_id, name, abbreviation, otu_schema, req["client"].user_id ) ) return json_response(document) @routes.delete("/otus/{otu_id}") async def remove(req): """ Remove an OTU document and its associated sequence documents. """ db = req.app["db"] otu_id = req.match_info["otu_id"] document = await db.otus.find_one(otu_id, ["reference"]) if document is None: raise NotFound() if not await virtool.references.db.check_right( req, document["reference"]["id"], "modify_otu" ): raise InsufficientRights() await asyncio.shield(virtool.otus.db.remove(req.app, otu_id, req["client"].user_id)) return web.Response(status=204) @routes.get("/otus/{otu_id}/isolates") async def list_isolates(req): """ Return a list of isolate records for a given otu. """ db = req.app["db"] otu_id = req.match_info["otu_id"] document = await virtool.otus.db.join_and_format(db, otu_id) if not document: raise NotFound() return json_response(document["isolates"]) @routes.get("/otus/{otu_id}/isolates/{isolate_id}") async def get_isolate(req): """ Get a complete specific isolate sub-document, including its sequences. """ db = req.app["db"] otu_id = req.match_info["otu_id"] isolate_id = req.match_info["isolate_id"] document = await db.otus.find_one( {"_id": otu_id, "isolates.id": isolate_id}, ["isolates"] ) if not document: raise NotFound() isolate = dict(find_isolate(document["isolates"], isolate_id), sequences=[]) cursor = db.sequences.find( {"otu_id": otu_id, "isolate_id": isolate_id}, {"otu_id": False, "isolate_id": False}, ) async for sequence in cursor: sequence["id"] = sequence.pop("_id") isolate["sequences"].append(sequence) return json_response(isolate) @routes.post("/otus/{otu_id}/isolates") @schema( { "source_type": { "type": "string", "coerce": virtool.validators.strip, "default": "", }, "source_name": { "type": "string", "coerce": virtool.validators.strip, "default": "", }, "default": {"type": "boolean", "default": False}, } ) async def add_isolate(req): """ Add a new isolate to a otu. """ db = req.app["db"] data = req["data"] otu_id = req.match_info["otu_id"] document = await db.otus.find_one(otu_id, ["reference"]) if not document: raise NotFound() if not await virtool.references.db.check_right( req, document["reference"]["id"], "modify_otu" ): raise InsufficientRights() # All source types are stored in lower case. data["source_type"] = data["source_type"].lower() if not await virtool.references.db.check_source_type( db, document["reference"]["id"], data["source_type"] ): raise HTTPBadRequest(text="Source type is not allowed") isolate = await asyncio.shield( virtool.otus.isolates.add(req.app, otu_id, data, req["client"].user_id) ) headers = {"Location": f"/otus/{otu_id}/isolates/{isolate['id']}"} return json_response(isolate, status=201, headers=headers) @routes.patch("/otus/{otu_id}/isolates/{isolate_id}") @schema( { "source_type": { "type": "string", "coerce": virtool.validators.strip, }, "source_name": { "type": "string", "coerce": virtool.validators.strip, }, } ) async def edit_isolate(req): """ Edit an existing isolate. """ db = req.app["db"] data = req["data"] otu_id = req.match_info["otu_id"] isolate_id = req.match_info["isolate_id"] document = await db.otus.find_one({"_id": otu_id, "isolates.id": isolate_id}) if not document: raise NotFound() ref_id = document["reference"]["id"] if not await virtool.references.db.check_right(req, ref_id, "modify_otu"): raise InsufficientRights() # All source types are stored in lower case. if "source_type" in data: data["source_type"] = data["source_type"].lower() if not await virtool.references.db.check_source_type( db, ref_id, data["source_type"] ): raise HTTPBadRequest(text="Source type is not allowed") isolate = await asyncio.shield( virtool.otus.isolates.edit( req.app, otu_id, isolate_id, data, req["client"].user_id ) ) return json_response(isolate, status=200) @routes.put("/otus/{otu_id}/isolates/{isolate_id}/default") async def set_as_default(req): """ Set an isolate as default. """ db = req.app["db"] otu_id = req.match_info["otu_id"] isolate_id = req.match_info["isolate_id"] document = await db.otus.find_one( {"_id": otu_id, "isolates.id": isolate_id}, ["reference"] ) if not document: raise NotFound() if not await virtool.references.db.check_right( req, document["reference"]["id"], "modify_otu" ): raise InsufficientRights() isolate = await asyncio.shield( virtool.otus.isolates.set_default( req.app, otu_id, isolate_id, req["client"].user_id ) ) return json_response(isolate) @routes.delete("/otus/{otu_id}/isolates/{isolate_id}") async def remove_isolate(req): """ Remove an isolate and its sequences from a otu. """ db = req.app["db"] otu_id = req.match_info["otu_id"] isolate_id = req.match_info["isolate_id"] document = await db.otus.find_one( {"_id": otu_id, "isolates.id": isolate_id}, ["reference"] ) if not document: raise NotFound() if not await virtool.references.db.check_right( req, document["reference"]["id"], "modify_otu" ): raise InsufficientRights() await asyncio.shield( virtool.otus.isolates.remove(req.app, otu_id, isolate_id, req["client"].user_id) ) raise HTTPNoContent @routes.get("/otus/{otu_id}/isolates/{isolate_id}/sequences") async def list_sequences(req): db = req.app["db"] otu_id = req.match_info["otu_id"] isolate_id = req.match_info["isolate_id"] if not await db.otus.count_documents({"_id": otu_id, "isolates.id": isolate_id}): raise NotFound() projection = list(virtool.otus.db.SEQUENCE_PROJECTION) projection.remove("otu_id") projection.remove("isolate_id") cursor = db.sequences.find({"otu_id": otu_id, "isolate_id": isolate_id}, projection) return json_response([base_processor(d) async for d in cursor]) @routes.get("/otus/{otu_id}/isolates/{isolate_id}/sequences/{sequence_id}") async def get_sequence(req): """ Get a single sequence document by its ``accession`. """ db = req.app["db"] otu_id = req.match_info["otu_id"] isolate_id = req.match_info["isolate_id"] sequence_id = req.match_info["sequence_id"] sequence = await virtool.otus.sequences.get(db, otu_id, isolate_id, sequence_id) if sequence is None: raise NotFound() return json_response(sequence) @routes.post("/otus/{otu_id}/isolates/{isolate_id}/sequences") @schema( { "accession": { "type": "string", "coerce": virtool.validators.strip, "empty": False, "required": True, }, "definition": { "type": "string", "coerce": virtool.validators.strip, "empty": False, "required": True, }, "host": { "type": "string", "coerce": virtool.validators.strip, }, "segment": { "type": "string", }, "sequence": { "type": "string", "coerce": virtool.validators.strip, "empty": False, "required": True, }, "target": {"type": "string"}, } ) async def create_sequence(req): """ Create a new sequence record for the given isolate. """ db = req.app["db"] data = req["data"] otu_id = req.match_info["otu_id"] isolate_id = req.match_info["isolate_id"] document = await db.otus.find_one( {"_id": otu_id, "isolates.id": isolate_id}, ["reference", "schema"] ) if not document: raise NotFound() ref_id = document["reference"]["id"] if not await virtool.references.db.check_right(req, ref_id, "modify_otu"): raise InsufficientRights() message = await virtool.otus.sequences.check_segment_or_target( db, otu_id, isolate_id, None, ref_id, data ) if message: raise HTTPBadRequest(text=message) sequence_document = await asyncio.shield( virtool.otus.sequences.create( req.app, ref_id, otu_id, isolate_id, data, req["client"].user_id ) ) sequence_id = sequence_document["id"] headers = { "Location": f"/otus/{otu_id}/isolates/{isolate_id}/sequences/{sequence_id}" } return json_response(sequence_document, status=201, headers=headers) @routes.patch("/otus/{otu_id}/isolates/{isolate_id}/sequences/{sequence_id}") @schema( { "accession": { "type": "string", "coerce": virtool.validators.strip, "empty": False, }, "host": {"type": "string", "coerce": virtool.validators.strip}, "definition": { "type": "string", "coerce": virtool.validators.strip, "empty": False, }, "segment": {"type": "string"}, "sequence": { "type": "string", "coerce": virtool.validators.strip, "empty": False, }, "target": {"type": "string"}, } ) async def edit_sequence(req): db = req.app["db"] data = req["data"] otu_id = req.match_info["otu_id"] isolate_id = req.match_info["isolate_id"] sequence_id = req.match_info["sequence_id"] document = await db.otus.find_one( {"_id": otu_id, "isolates.id": isolate_id}, ["reference", "segment"] ) if not document or not await db.sequences.count_documents({"_id": sequence_id}): raise NotFound() if not await virtool.references.db.check_right( req, document["reference"]["id"], "modify_otu" ): raise InsufficientRights() message = await virtool.otus.sequences.check_segment_or_target( db, otu_id, isolate_id, sequence_id, document["reference"]["id"], data ) if message: raise HTTPBadRequest(text=message) sequence_document = await asyncio.shield( virtool.otus.sequences.edit( req.app, otu_id, isolate_id, sequence_id, data, req["client"].user_id ) ) return json_response(sequence_document) @routes.delete("/otus/{otu_id}/isolates/{isolate_id}/sequences/{sequence_id}") async def remove_sequence(req): """ Remove a sequence from an isolate. """ db = req.app["db"] otu_id = req.match_info["otu_id"] isolate_id = req.match_info["isolate_id"] sequence_id = req.match_info["sequence_id"] if not await db.sequences.count_documents({"_id": sequence_id}): raise NotFound() document = await db.otus.find_one( {"_id": otu_id, "isolates.id": isolate_id}, ["reference"] ) if document is None: raise NotFound() if not await virtool.references.db.check_right( req, document["reference"]["id"], "modify_otu" ): raise InsufficientRights() await asyncio.shield( virtool.otus.sequences.remove( req.app, otu_id, isolate_id, sequence_id, req["client"].user_id ) ) raise HTTPNoContent @routes.get("/otus/{otu_id}/history") async def list_history(req): db = req.app["db"] otu_id = req.match_info["otu_id"] if not await db.otus.count_documents({"_id": otu_id}): raise NotFound() documents = await db.history.find( {"otu.id": otu_id}, projection=LIST_PROJECTION ).to_list(None) return json_response( await apply_transforms(documents, [AttachUserTransform(db, ignore_errors=True)]) )
from datetime import datetime import operator import os import re import string import random from django import template from django.conf import settings from django.template import Template from django.template.loader import render_to_string from django.template.defaultfilters import truncatewords_html, stringfilter from django.template.loader_tags import do_include from django.template import Library from django.utils.safestring import mark_safe from hydeengine.file_system import File, Folder marker_start = "<!-- Hyde::%s::Begin -->" marker_end = "<!-- Hyde::%s::End -->" current_referrer = 'current_referrer' register = Library() class HydeContextNode(template.Node): def __init__(self): pass def render(self, context): return "" @register.tag(name="hyde") def hyde_context(parser, token): return HydeContextNode() @register.tag(name="excerpt") def excerpt(parser, token): nodelist = parser.parse(('endexcerpt',)) parser.delete_first_token() return BracketNode("Excerpt", nodelist) @register.tag(name="article") def article(parser, token): nodelist = parser.parse(('endarticle',)) parser.delete_first_token() return BracketNode("Article", nodelist) @register.tag(name="refer") def refer_page(parser, token): bits = token.contents.split() if (len(bits) < 5 or bits[1] != 'to' or bits[3] != 'as'): raise TemplateSyntaxError("Syntax: 'refer to _page_path_ as _namespace_'") return ReferNode(bits[2], bits[4]) @register.tag(name="reference") def reference(parser, token): bits = token.contents.split() if len(bits) < 2: raise TemplateSyntaxError("Syntax: 'reference _variable_'") nodelist = parser.parse(('endreference',)) parser.delete_first_token() return ReferenceNode(bits[1], nodelist) class ReferNode(template.Node): def __init__(self, path, namespace): self.path = path self.namespace = namespace def render(self, context): original_page = context['page'] self.path = original_page.node.folder.child(self.path.strip('"')) context.push() context[current_referrer] = {'namespace': self.namespace} context['page'] = original_page.node.find_resource(File(self.path)) render_to_string(str(self.path), context) var = context[current_referrer] context.pop() context[self.namespace] = var return '' class ReferenceNode(template.Node): def __init__(self, variable, nodelist): self.variable = variable self.nodelist = nodelist def render(self, context): rendered_string = self.nodelist.render(context) if current_referrer in context and context[current_referrer]: context[current_referrer][self.variable] = rendered_string return rendered_string class BracketNode(template.Node): def __init__(self, marker, nodelist): self.nodelist = nodelist self.marker = marker def render(self, context): rendered_string = self.nodelist.render(context) return marker_start % self.marker +\ rendered_string + \ marker_end % self.marker class LatestExcerptNode(template.Node): def __init__(self, path, words=50): self.path = path self.words = words def render(self, context): sitemap_node = None self.path = self.path.render(context).strip('"') sitemap_node = context["site"].find_node(Folder(self.path)) if not sitemap_node: sitemap_node = context["site"] def later(page1, page2): return (page1, page2)[page2.created > page1.created] page = reduce(later, sitemap_node.walk_pages()) rendered = None rendered = render_to_string(str(page), context) excerpt_start = marker_start % "Excerpt" excerpt_end = marker_end % "Excerpt" start = rendered.find(excerpt_start) if not start == -1: context["latest_excerpt_url"] = page.url context["latest_excerpt_title"] = page.title start = start + len(excerpt_start) end = rendered.find(excerpt_end, start) return truncatewords_html(rendered[start:end], self.words) else: return "" class RecentPostsNode(template.Node): def __init__(self, var='recent_posts', count=5, node=None, categories=None): self.var = var self.count = count self.node = node self.categories = categories def render(self, context): if not self.node: self.node = context['site'] else: self.node = self.node.resolve(context) if not self.count == 5: self.count = self.count.render(context) if not self.var == 'recent_posts': self.var = self.var.render(context) category_filter = None randomize = False if self.categories == '?': randomize = True elif self.categories is not None: category_filter = re.compile(self.categories) if (not hasattr(self.node, 'complete_page_list') or not self.node.complete_page_list): complete_page_list = sorted( self.node.walk_pages(), key=operator.attrgetter("created"), reverse=True) complete_page_list = filter(lambda page: page.display_in_list, complete_page_list) self.node.complete_page_list = complete_page_list if category_filter is None: posts = self.node.complete_page_list if randomize: random.shuffle(posts) context[self.var] = posts[:int(self.count)] else: posts = filter(lambda page: page.display_in_list and \ reduce(lambda c1,c2: c1 or category_filter.match(c2) is not None, \ hasattr(page, 'categories') and page.categories or [], False), self.node.complete_page_list) context[self.var] = posts[:int(self.count)] return '' @register.tag(name="recent_posts") def recent_posts(parser, token): tokens = token.split_contents() count = 5 node = None categories = None var = 'recent_posts' if len(tokens) > 1: var = Template(tokens[1]) if len(tokens) > 2: count = Template(tokens[2]) if len(tokens) > 3: node = parser.compile_filter(tokens[3]) if len(tokens) > 4: categories = tokens[4] return RecentPostsNode(var, count, node, categories) @register.tag(name="latest_excerpt") def latest_excerpt(parser, token): tokens = token.split_contents() path = None words = 50 if len(tokens) > 1: path = Template(tokens[1]) if len(tokens) > 2: words = int(tokens[2]) return LatestExcerptNode(path, words) @register.tag(name="render_excerpt") def render_excerpt(parser, token): tokens = token.split_contents() path = None words = 50 if len(tokens) > 1: path = parser.compile_filter(tokens[1]) if len(tokens) > 2: words = int(tokens[2]) return RenderExcerptNode(path, words) @register.tag(name="render_article") def render_article(parser, token): tokens = token.split_contents() path = None if len(tokens) > 1: path = parser.compile_filter(tokens[1]) return RenderArticleNode(path) class RenderExcerptNode(template.Node): def __init__(self, page, words=50): self.page = page self.words = words def render(self, context): page = self.page.resolve(context) context["excerpt_url"] = page.url context["excerpt_title"] = page.title rendered = get_bracketed_content(context, page, "Excerpt") return truncatewords_html(rendered, self.words) class RenderArticleNode(template.Node): def __init__(self, page): self.page = page def render(self, context): page = self.page.resolve(context) return get_bracketed_content(context, page, "Article") def get_bracketed_content(context, page, marker): rendered = None original_page = context['page'] context['page'] = page rendered = render_to_string(str(page), context) context['page'] = original_page bracket_start = marker_start % marker bracket_end = marker_end % marker start = rendered.find(bracket_start) if not start == -1: start = start + len(bracket_start) end = rendered.find(bracket_end, start) return rendered[start:end] return "" def hyde_thumbnail(url): postfix = getattr(settings, 'THUMBNAIL_FILENAME_POSTFIX', '-thumb') path, ext = url.rsplit('.', 1) return ''.join([path, postfix, '.', ext]) register.filter(stringfilter(hyde_thumbnail)) @register.filter def value_for_key(dictionary, key): if not dictionary: return "" if not dictionary.has_key(key): return "" value = dictionary[key] return value @register.filter def xmldatetime(dt): if not dt: dt = datetime.now() zprefix = "Z" tz = dt.strftime("%z") if tz: zprefix = tz[:3] + ":" + tz[3:] return dt.strftime("%Y-%m-%dT%H:%M:%S") + zprefix @register.filter def remove_date_prefix(slug, sep="-"): expr = sep.join([r"\d{2,4}"] * 3 + ["(.*)"]) match = re.match(expr, slug) if not match: return slug else: return match.group(0) @register.filter def unslugify(slug): words = slug.replace("_", " ").\ replace("-", " ").\ replace(".", "").split() return ' '.join(map(lambda str: str.capitalize(), words)) @register.tag(name="hyde_listing_page_rewrite_rules") def hyde_listing_page_rewrite_rules(parser, token): """Prints the Apache Mod_Rewrite RewriteRules for clean urls for pages in LISTING_PAGE_NAMES. These rules are designed to be placed in a .htaccess file; they have not been tested inside of httpd.conf This only generates RewriteRules; it does not enable url rewriting or set RewriteBase. """ return RenderHydeListingPageRewriteRulesNode() LPN_REWRITE_RULE = string.Template(\ r""" RewriteCond %{REQUEST_FILENAME}/${name}.html -f RewriteRule ^(.*) $1/${name}.html """ ) class RenderHydeListingPageRewriteRulesNode(template.Node): def render(self, context): if not settings.LISTING_PAGE_NAMES: return '' rules = [] # For LISTING_PAGE_NAMES listings for name in settings.LISTING_PAGE_NAMES: rules.append(LPN_REWRITE_RULE.safe_substitute( \ {'name': name})) return \ "### BEGIN GENERATED REWRITE RULES ####\n" \ + ''.join(rules) \ + "\n#### END GENERATED REWRITE RULES ####" class IncludeTextNode(template.Node): def __init__(self, include_node): self.include_node = include_node def render(self, context): try: import markdown import typogrify except ImportError: print u"`includetext` requires Markdown and Typogrify." raise output = self.include_node.render(context) output = markdown.markdown(output) output = typogrify.typogrify(output) return output @register.tag(name="includetext") def includetext(parser, token): return IncludeTextNode(do_include(parser, token)) class RecentResourcesNode(template.Node): def __init__(self, tag_name, count=0, page='page', var_name='resources'): self.tag_name = tag_name self.count = int(count) self.page = template.Variable(page) self.var_name = var_name def render(self, context): page = self.page.resolve(context) resources = page is not None and page.node.media or [] if self.count: resources = resources[:self.count] context[self.var_name] = resources return '' @register.tag(name='recent_resources') def recent_resources(parser, token): args = list(token.split_contents()) kwargs = {} if len(args) >= 3 and args[-2] == 'as': kwargs['var_name'] = args.pop(-1) args.pop(-1) return RecentResourcesNode(*args, **kwargs) class RenderNode(template.Node): def __init__(self, template_path, node_list=None, data=None): self.template_path = template_path self.node_list = node_list self.data = data def render(self, context): if self.node_list: text = self.node_list.render(context) import yaml self.data = yaml.load(text) else: self.data = self.data.resolve(context) context.push() context['data'] = self.data out = render_to_string(self.template_path, context) context.pop() return out @register.tag(name='render') def render(parser, token): bits = token.contents.split() if len(bits) < 2: raise TemplateSyntaxError("Syntax: {% render _template_ %}YAML{% endrender %}'") if ((len(bits) > 2 and len(bits) < 4) or (len(bits) == 4 and bits[2] != "with")): raise TemplateSyntaxError("Syntax: {% render _template_ with var_data %}'") template_path = bits[1] nodelist = None data = None if (len(bits) == 2): nodelist = parser.parse(('endrender',)) parser.delete_first_token() else: data = template.Variable(bits[3]) return RenderNode(template_path, node_list=nodelist, data=data)
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for normalization layers.""" import numpy as np from tensorflow.python import keras from tensorflow.python.keras import combinations from tensorflow.python.keras import keras_parameterized from tensorflow.python.keras import testing_utils from tensorflow.python.keras.layers.normalization import layer_normalization from tensorflow.python.ops import gradient_checker_v2 from tensorflow.python.ops import math_ops from tensorflow.python.platform import test from tensorflow.python.training import gradient_descent def _run_layernorm_correctness_test(layer, dtype='float32'): model = keras.models.Sequential() model.add(keras.layers.Lambda(lambda x: math_ops.cast(x, dtype='float16'))) norm = layer(input_shape=(2, 2, 2), dtype=dtype) model.add(norm) model.compile( loss='mse', optimizer=gradient_descent.GradientDescentOptimizer(0.01), run_eagerly=testing_utils.should_run_eagerly()) # centered on 5.0, variance 10.0 x = (np.random.normal(loc=5.0, scale=10.0, size=(1000, 2, 2, 2)) .astype(dtype)) model.fit(x, x, epochs=4, verbose=0) out = model.predict(x) out -= keras.backend.eval(norm.beta) out /= keras.backend.eval(norm.gamma) np.testing.assert_allclose(out.mean(), 0.0, atol=1e-1) np.testing.assert_allclose(out.std(), 1.0, atol=1e-1) class LayerNormalizationTest(keras_parameterized.TestCase): @keras_parameterized.run_all_keras_modes def test_basic_layernorm(self): testing_utils.layer_test( keras.layers.LayerNormalization, kwargs={ 'gamma_regularizer': keras.regularizers.l2(0.01), 'beta_regularizer': keras.regularizers.l2(0.01) }, input_shape=(3, 4, 2)) testing_utils.layer_test( keras.layers.LayerNormalization, kwargs={ 'gamma_initializer': 'ones', 'beta_initializer': 'ones', }, input_shape=(3, 4, 2)) testing_utils.layer_test( keras.layers.LayerNormalization, kwargs={'scale': False, 'center': False}, input_shape=(3, 3)) testing_utils.layer_test( keras.layers.LayerNormalization, kwargs={'axis': (-3, -2, -1)}, input_shape=(2, 8, 8, 3)) @keras_parameterized.run_all_keras_modes def test_non_fused_layernorm(self): testing_utils.layer_test( keras.layers.LayerNormalization, kwargs={'axis': -2}, input_shape=(3, 4, 2)) testing_utils.layer_test( keras.layers.LayerNormalization, kwargs={'axis': (-3, -2)}, input_shape=(2, 8, 8, 3)) testing_utils.layer_test( keras.layers.LayerNormalization, kwargs={'axis': (-3, -1)}, input_shape=(2, 8, 8, 3)) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_layernorm_weights(self): layer = keras.layers.LayerNormalization(scale=False, center=False) layer.build((None, 3, 4)) self.assertEqual(len(layer.trainable_weights), 0) self.assertEqual(len(layer.weights), 0) layer = keras.layers.LayerNormalization() layer.build((None, 3, 4)) self.assertEqual(len(layer.trainable_weights), 2) self.assertEqual(len(layer.weights), 2) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_layernorm_regularization(self): layer = keras.layers.LayerNormalization( gamma_regularizer='l1', beta_regularizer='l1') layer.build((None, 3, 4)) self.assertEqual(len(layer.losses), 2) max_norm = keras.constraints.max_norm layer = keras.layers.LayerNormalization( gamma_constraint=max_norm, beta_constraint=max_norm) layer.build((None, 3, 4)) self.assertEqual(layer.gamma.constraint, max_norm) self.assertEqual(layer.beta.constraint, max_norm) @keras_parameterized.run_all_keras_modes def test_layernorm_convnet_channel_last(self): model = keras.models.Sequential() norm = keras.layers.LayerNormalization(input_shape=(4, 4, 3)) model.add(norm) model.compile( loss='mse', optimizer=gradient_descent.GradientDescentOptimizer(0.01), run_eagerly=testing_utils.should_run_eagerly()) # centered on 5.0, variance 10.0 x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 4, 4, 3)) model.fit(x, x, epochs=4, verbose=0) out = model.predict(x) out -= np.reshape(keras.backend.eval(norm.beta), (1, 1, 1, 3)) out /= np.reshape(keras.backend.eval(norm.gamma), (1, 1, 1, 3)) np.testing.assert_allclose(np.mean(out, axis=(0, 1, 2)), 0.0, atol=1e-1) np.testing.assert_allclose(np.std(out, axis=(0, 1, 2)), 1.0, atol=1e-1) @keras_parameterized.run_all_keras_modes def test_layernorm_correctness(self): _run_layernorm_correctness_test( layer_normalization.LayerNormalization, dtype='float32') @keras_parameterized.run_all_keras_modes def test_layernorm_mixed_precision(self): _run_layernorm_correctness_test( layer_normalization.LayerNormalization, dtype='float16') @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def testIncorrectAxisType(self): with self.assertRaisesRegex(TypeError, r'Expected an int or a list/tuple of ints'): _ = layer_normalization.LayerNormalization(axis={'axis': -1}) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def testInvalidAxis(self): with self.assertRaisesRegex(ValueError, r'Invalid axis: 3'): layer_norm = layer_normalization.LayerNormalization(axis=3) layer_norm.build(input_shape=(2, 2, 2)) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def testDuplicateAxis(self): with self.assertRaisesRegex(ValueError, r'Duplicate axis:'): layer_norm = layer_normalization.LayerNormalization(axis=[-1, -1]) layer_norm.build(input_shape=(2, 2, 2)) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def testFusedAttr(self): layer_norm = layer_normalization.LayerNormalization(axis=[-2, -1]) layer_norm.build(input_shape=(2, 2, 2)) self.assertEqual(layer_norm._fused, True) class LayerNormalizationNumericsTest(keras_parameterized.TestCase): """Tests LayerNormalization has correct and numerically stable outputs.""" def _expected_layer_norm(self, x, beta, gamma, batch_input_shape, axis, epsilon): """Returns the layer norm, which is computed using NumPy.""" broadcast_shape = [batch_input_shape[i] if i in axis else 1 for i in range(len(batch_input_shape))] mean = np.mean(x, axis=axis, keepdims=True) var = np.var(x, axis=axis, keepdims=True) expected = (x - mean) / np.sqrt(var + epsilon) expected *= np.reshape(gamma, broadcast_shape) expected += np.reshape(beta, broadcast_shape) return expected def _test_forward_pass(self, batch_input_shape, axis, fp64_tol=1e-14, fp32_tol=1e-6, fp16_tol=1e-2): """Tests the forward pass of layer layer_normalization. Args: batch_input_shape: The input shape that will be used to test, including the batch dimension. axis: A list of axises to normalize. Will be passed to the `axis` argument of Layerlayer_normalization. fp64_tol: The relative and absolute tolerance for float64. fp32_tol: The relative and absolute tolerance for float32. fp16_tol: The relative and absolute tolerance for float16. """ param_shape = [batch_input_shape[i] for i in axis] param_elems = 1 for dim in param_shape: param_elems *= dim beta = np.arange(param_elems, dtype='float64').reshape(param_shape) gamma = np.arange(1, param_elems + 1, dtype='float64').reshape(param_shape) x = np.random.normal(size=batch_input_shape) for epsilon in 1e-12, 1e-3: expected = self._expected_layer_norm(x, beta, gamma, batch_input_shape, axis, epsilon) for dtype in 'float64', 'float32', 'float16': norm = layer_normalization.LayerNormalization( axis=axis, dtype=dtype, batch_input_shape=batch_input_shape, epsilon=epsilon, beta_initializer=keras.initializers.constant(beta), gamma_initializer=keras.initializers.constant(gamma)) y = norm(keras.backend.cast(x, dtype)) actual = keras.backend.eval(y) if dtype == 'float64': tol = fp64_tol elif dtype == 'float32': tol = fp32_tol else: assert dtype == 'float16' tol = fp16_tol # We use absolute tolerances in addition to relative tolerances, because # some of the values are very close to zero. self.assertAllClose(expected, actual, rtol=tol, atol=tol) @combinations.generate(combinations.combine(mode=['graph', 'eager'])) def test_forward(self): # For numeric stability, we ensure the axis's dimension(s) have at least 4 # elements. self._test_forward_pass((4, 3), (0,)) self._test_forward_pass((3, 4), (1,)) self._test_forward_pass((4, 3, 2), (0,)) self._test_forward_pass((2, 4, 2), (1,)) self._test_forward_pass((2, 3, 4), (2,), fp16_tol=5e-2) self._test_forward_pass((2, 3, 2), (0, 2)) self._test_forward_pass((2, 2, 2, 2), (1, 3)) self._test_forward_pass((2, 2, 2, 2), (2, 3)) self._test_forward_pass((2, 3, 4, 5), (3,)) def _test_backward_pass(self, batch_input_shape, axis, fp64_tol=1e-5, fp32_tol=1e-5, fp16_tol=2e-2): """Tests the backwards pass of layer layer_normalization. Args: batch_input_shape: The input shape that will be used to test, including the batch dimension. axis: A list of axises to normalize. Will be passed to the `axis` argument of Layerlayer_normalization. fp64_tol: The relative and absolute tolerance for float64. fp32_tol: The relative and absolute tolerance for float32. fp16_tol: The relative and absolute tolerance for float16. """ param_shape = [batch_input_shape[i] for i in axis] param_elems = 1 for dim in param_shape: param_elems *= dim beta = np.arange(param_elems, dtype='float64').reshape(param_shape) gamma = np.arange(1, param_elems + 1, dtype='float64').reshape(param_shape) x = np.random.normal(size=batch_input_shape) for epsilon in 1e-12, 1e-3: # Float64 must come first in this list, as we use the float64 numerical # gradients to compare to the float32 and float16 symbolic gradients as # well. Computing float32/float16 numerical gradients is too numerically # unstable. for dtype in 'float64', 'float32', 'float16': norm = layer_normalization.LayerNormalization( axis=axis, dtype=dtype, batch_input_shape=batch_input_shape, epsilon=epsilon, beta_initializer=keras.initializers.constant(beta), gamma_initializer=keras.initializers.constant(gamma)) norm.build(x.shape) # pylint: disable=cell-var-from-loop def forward_fn(x, beta, gamma): # We must monkey-patch the attributes of `norm` with the function # arguments, so that the gradient checker will properly compute their # gradients. The gradient checker computes gradients with respect to # the input arguments of `f`. with test.mock.patch.object(norm, 'beta', beta): with test.mock.patch.object(norm, 'gamma', gamma): return norm(x) # pylint: enable=cell-var-from-loop results = gradient_checker_v2.compute_gradient( forward_fn, [keras.backend.cast(x, dtype), norm.beta, norm.gamma]) ([x_grad_t, beta_grad_t, gamma_grad_t], [x_grad_n, beta_grad_n, gamma_grad_n]) = results if dtype == 'float64': # We use the float64 numeric gradients as the reference, to compare # against the symbolic gradients for all dtypes. x_grad_ref = x_grad_n beta_grad_ref = beta_grad_n gamma_grad_ref = gamma_grad_n tol = fp64_tol elif dtype == 'float32': tol = fp32_tol else: assert dtype == 'float16' tol = fp16_tol # We use absolute tolerances in addition to relative tolerances, because # some of the values are very close to zero. self.assertAllClose(x_grad_t, x_grad_ref, rtol=tol, atol=tol) self.assertAllClose(beta_grad_t, beta_grad_ref, rtol=tol, atol=tol) self.assertAllClose(gamma_grad_t, gamma_grad_ref, rtol=tol, atol=tol) # The gradient_checker_v2 does not work properly with LayerNorm in graph mode. @testing_utils.run_v2_only def test_backward(self): # For numeric stability, we ensure the axis's dimension(s) have at least 4 # elements. self._test_backward_pass((4, 3), (0,)) self._test_backward_pass((2, 4, 2), (1,)) self._test_backward_pass((2, 3, 4), (2,)) self._test_backward_pass((2, 3, 2), (0, 2), fp64_tol=5e-4, fp32_tol=5e-4) self._test_backward_pass((2, 2, 2, 2), (1, 3)) self._test_backward_pass((2, 2, 2, 2), (2, 3)) if __name__ == '__main__': test.main()
import datetime import mock from rdr_service import clock from rdr_service.dao.genomics_dao import GenomicSetDao, GenomicSetMemberDao from rdr_service.dao.participant_dao import ParticipantDao from rdr_service.dao.participant_summary_dao import ParticipantSummaryDao from rdr_service.genomic.validation import validate_and_update_genomic_set_by_id from rdr_service.model.genomics import ( GenomicSet, GenomicSetMember, ) from rdr_service.model.participant import Participant from rdr_service.participant_enums import SampleStatus, WithdrawalStatus from rdr_service.genomic_enums import GenomicSetStatus, GenomicSetMemberStatus, GenomicValidationFlag from tests.helpers.unittest_base import BaseTestCase class GenomicSetValidationBaseTestCase(BaseTestCase): def setUp(self): super(GenomicSetValidationBaseTestCase, self).setUp() self.participant_dao = ParticipantDao() self.summary_dao = ParticipantSummaryDao() self.genomic_set_dao = GenomicSetDao() self.genomic_member_dao = GenomicSetMemberDao() self._participant_i = 0 self.setup_data() def setup_data(self): pass def make_participant(self, **kwargs): """ Make a participant with custom settings. default should create a valid participant. """ i = self._participant_i self._participant_i += 1 participant = Participant(participantId=i, biobankId=i, **kwargs) self.participant_dao.insert(participant) return participant def make_summary(self, participant, **override_kwargs): """ Make a summary with custom settings. default should create a valid summary. """ valid_kwargs = dict( participantId=participant.participantId, biobankId=participant.biobankId, withdrawalStatus=participant.withdrawalStatus, dateOfBirth=datetime.datetime(2000, 1, 1), firstName="foo", lastName="bar", zipCode="12345", sampleStatus1ED04=SampleStatus.RECEIVED, sampleStatus1SAL2=SampleStatus.RECEIVED, samplesToIsolateDNA=SampleStatus.RECEIVED, consentForStudyEnrollmentTime=datetime.datetime(2019, 1, 1), participantOrigin='example' ) kwargs = dict(valid_kwargs, **override_kwargs) summary = self.data_generator._participant_summary_with_defaults(**kwargs) self.summary_dao.insert(summary) return summary def make_genomic_set(self, **override_kwargs): """ Make a genomic set with custom settings. default should create a valid set. """ valid_kwargs = dict( genomicSetName="foo", genomicSetCriteria="something", genomicSetVersion=1, genomicSetStatus=GenomicSetStatus.UNSET, ) kwargs = dict(valid_kwargs, **override_kwargs) genomic_set = GenomicSet(**kwargs) self.genomic_set_dao.insert(genomic_set) return genomic_set def make_genomic_member(self, genomic_set, participant, **override_kwargs): """ Make a genomic member with custom settings. default should create a valid member. """ valid_kwargs = dict( genomicSetId=genomic_set.id, participantId=participant.participantId, sexAtBirth="F", biobankId=participant.biobankId, ) kwargs = dict(valid_kwargs, **override_kwargs) member = GenomicSetMember(**kwargs) self.genomic_member_dao.insert(member) return member # TODO: represent in new test suite class GenomicSetMemberValidationTestCase(GenomicSetValidationBaseTestCase): def test_test_defaults_are_valid(self): participant = self.make_participant() self.make_summary(participant) genomic_set = self.make_genomic_set() member = self.make_genomic_member(genomic_set, participant) validate_and_update_genomic_set_by_id(genomic_set.id) current_member = self.genomic_member_dao.get(member.id) self.assertEqual(current_member.validationStatus, GenomicSetMemberStatus.VALID) current_set = self.genomic_set_dao.get(genomic_set.id) self.assertEqual(current_set.genomicSetStatus, GenomicSetStatus.VALID) def test_duplicate(self): participant = self.make_participant() self.make_summary(participant) genomic_set_a = self.make_genomic_set(genomicSetName="A", genomicSetStatus=GenomicSetStatus.VALID) self.make_genomic_member(genomic_set_a, participant) genomic_set_b = self.make_genomic_set(genomicSetName="B") member_b = self.make_genomic_member(genomic_set_b, participant) validate_and_update_genomic_set_by_id(genomic_set_b.id) current_member = self.genomic_member_dao.get(member_b.id) self.assertEqual(current_member.validationStatus, GenomicSetMemberStatus.VALID) current_set = self.genomic_set_dao.get(genomic_set_b.id) self.assertEqual(current_set.genomicSetStatus, GenomicSetStatus.VALID) def test_consent(self): participant = self.make_participant() self.make_summary(participant, consentForStudyEnrollmentTime=datetime.datetime(2017, 1, 1)) genomic_set = self.make_genomic_set() member = self.make_genomic_member(genomic_set, participant) validate_and_update_genomic_set_by_id(genomic_set.id) current_member = self.genomic_member_dao.get(member.id) self.assertEqual(current_member.validationStatus, GenomicSetMemberStatus.INVALID) self.assertIn(GenomicValidationFlag.INVALID_CONSENT, current_member.validationFlags) current_set = self.genomic_set_dao.get(genomic_set.id) self.assertEqual(current_set.genomicSetStatus, GenomicSetStatus.INVALID) def test_consent_null(self): participant = self.make_participant() self.make_summary(participant, consentForStudyEnrollmentTime=None) genomic_set = self.make_genomic_set() member = self.make_genomic_member(genomic_set, participant) validate_and_update_genomic_set_by_id(genomic_set.id) current_member = self.genomic_member_dao.get(member.id) self.assertEqual(current_member.validationStatus, GenomicSetMemberStatus.INVALID) self.assertIn(GenomicValidationFlag.INVALID_CONSENT, current_member.validationFlags) current_set = self.genomic_set_dao.get(genomic_set.id) self.assertEqual(current_set.genomicSetStatus, GenomicSetStatus.INVALID) def test_withdrawn(self): participant = self.make_participant(withdrawalStatus=WithdrawalStatus.NO_USE) self.make_summary(participant) genomic_set = self.make_genomic_set() member = self.make_genomic_member(genomic_set, participant) validate_and_update_genomic_set_by_id(genomic_set.id) current_member = self.genomic_member_dao.get(member.id) self.assertEqual(current_member.validationStatus, GenomicSetMemberStatus.INVALID) self.assertIn(GenomicValidationFlag.INVALID_WITHDRAW_STATUS, current_member.validationFlags) current_set = self.genomic_set_dao.get(genomic_set.id) self.assertEqual(current_set.genomicSetStatus, GenomicSetStatus.INVALID) def test_sexatbirth(self): participant = self.make_participant() self.make_summary(participant) genomic_set = self.make_genomic_set() member = self.make_genomic_member(genomic_set, participant, sexAtBirth="foo") validate_and_update_genomic_set_by_id(genomic_set.id) current_member = self.genomic_member_dao.get(member.id) self.assertEqual(current_member.validationStatus, GenomicSetMemberStatus.INVALID) self.assertIn(GenomicValidationFlag.INVALID_SEX_AT_BIRTH, current_member.validationFlags) current_set = self.genomic_set_dao.get(genomic_set.id) self.assertEqual(current_set.genomicSetStatus, GenomicSetStatus.INVALID) def test_age(self): now = datetime.datetime(2019, 1, 1) valid_date_of_birth = datetime.datetime(now.year - 18, now.month, now.day) invalid_date_of_birth = datetime.datetime(now.year - 17, now.month, now.day) participant_a = self.make_participant() self.make_summary(participant_a, dateOfBirth=valid_date_of_birth) participant_b = self.make_participant() self.make_summary(participant_b, dateOfBirth=invalid_date_of_birth) genomic_set = self.make_genomic_set() member_a = self.make_genomic_member(genomic_set, participant_a) member_b = self.make_genomic_member(genomic_set, participant_b) with clock.FakeClock(datetime.datetime(2019, 1, 1)): validate_and_update_genomic_set_by_id(genomic_set.id) current_member_a = self.genomic_member_dao.get(member_a.id) current_member_b = self.genomic_member_dao.get(member_b.id) self.assertEqual(current_member_a.validationStatus, GenomicSetMemberStatus.VALID) self.assertEqual(current_member_b.validationStatus, GenomicSetMemberStatus.INVALID) self.assertIn(GenomicValidationFlag.INVALID_AGE, current_member_b.validationFlags) current_set = self.genomic_set_dao.get(genomic_set.id) self.assertEqual(current_set.genomicSetStatus, GenomicSetStatus.INVALID) def test_biobank_status(self): def make_member(genomic_set, **summary_kwargs): participant = self.make_participant() self.make_summary(participant, **summary_kwargs) return self.make_genomic_member(genomic_set, participant) kwargs_with_expected_status_and_flags = [ ( { "sampleStatus1ED04": SampleStatus.UNSET, "sampleStatus1SAL2": SampleStatus.UNSET, "samplesToIsolateDNA": SampleStatus.UNSET, }, GenomicSetMemberStatus.INVALID, [GenomicValidationFlag.INVALID_BIOBANK_ORDER], ), ( { "sampleStatus1ED04": SampleStatus.RECEIVED, "sampleStatus1SAL2": SampleStatus.UNSET, "samplesToIsolateDNA": SampleStatus.UNSET, }, GenomicSetMemberStatus.INVALID, [GenomicValidationFlag.INVALID_BIOBANK_ORDER], ), ( { "sampleStatus1ED04": SampleStatus.UNSET, "sampleStatus1SAL2": SampleStatus.RECEIVED, "samplesToIsolateDNA": SampleStatus.UNSET, }, GenomicSetMemberStatus.INVALID, [GenomicValidationFlag.INVALID_BIOBANK_ORDER], ), ( { "sampleStatus1ED04": SampleStatus.UNSET, "sampleStatus1SAL2": SampleStatus.UNSET, "samplesToIsolateDNA": SampleStatus.RECEIVED, }, GenomicSetMemberStatus.INVALID, [GenomicValidationFlag.INVALID_BIOBANK_ORDER], ), ( { "sampleStatus1ED04": SampleStatus.RECEIVED, "sampleStatus1SAL2": SampleStatus.UNSET, "samplesToIsolateDNA": SampleStatus.RECEIVED, }, GenomicSetMemberStatus.VALID, [], ), ( { "sampleStatus1ED04": SampleStatus.UNSET, "sampleStatus1SAL2": SampleStatus.RECEIVED, "samplesToIsolateDNA": SampleStatus.RECEIVED, }, GenomicSetMemberStatus.VALID, [], ), ] genomic_set = self.make_genomic_set() runs = [ (make_member(genomic_set, **kwargs), kwargs, status, flags) for kwargs, status, flags in kwargs_with_expected_status_and_flags ] validate_and_update_genomic_set_by_id(genomic_set.id) for member, kwargs, expected_status, expected_flags in runs: current_member = self.genomic_member_dao.get(member.id) self.assertEqual(current_member.validationStatus, expected_status) for flag in expected_flags: self.assertIn(flag, current_member.validationFlags) current_set = self.genomic_set_dao.get(genomic_set.id) self.assertEqual(current_set.genomicSetStatus, GenomicSetStatus.INVALID) def test_ny_zip_code(self): participant_a = self.make_participant() self.make_summary(participant_a, zipCode=None) participant_b = self.make_participant() self.make_summary(participant_b, zipCode="") participant_c = self.make_participant() self.make_summary(participant_c, zipCode="12345") genomic_set = self.make_genomic_set() member_a = self.make_genomic_member(genomic_set, participant_a) member_b = self.make_genomic_member(genomic_set, participant_b) member_c = self.make_genomic_member(genomic_set, participant_c) with clock.FakeClock(datetime.datetime(2019, 1, 1)): validate_and_update_genomic_set_by_id(genomic_set.id) current_member_a = self.genomic_member_dao.get(member_a.id) current_member_b = self.genomic_member_dao.get(member_b.id) current_member_c = self.genomic_member_dao.get(member_c.id) self.assertEqual(current_member_a.validationStatus, GenomicSetMemberStatus.INVALID) self.assertIn(GenomicValidationFlag.INVALID_NY_ZIPCODE, current_member_a.validationFlags) self.assertEqual(current_member_b.validationStatus, GenomicSetMemberStatus.INVALID) self.assertIn(GenomicValidationFlag.INVALID_NY_ZIPCODE, current_member_a.validationFlags) self.assertEqual(current_member_c.validationStatus, GenomicSetMemberStatus.VALID) current_set = self.genomic_set_dao.get(genomic_set.id) self.assertEqual(current_set.genomicSetStatus, GenomicSetStatus.INVALID) class GenomicSetValidationSafetyTestCase(GenomicSetValidationBaseTestCase): def test_transaction(self): participant = self.make_participant() self.make_summary(participant) genomic_set = self.make_genomic_set() member = self.make_genomic_member(genomic_set, participant) with mock.patch("rdr_service.genomic.validation.GenomicSetDao.update_with_session") as mocked_set_update: mocked_set_update.side_effect = Exception("baz") with clock.FakeClock(datetime.datetime(2019, 1, 1)): with self.assertRaises(Exception): validate_and_update_genomic_set_by_id(genomic_set.id) current_member = self.genomic_member_dao.get(member.id) self.assertEqual(current_member.validationStatus, None) current_set = self.genomic_set_dao.get(genomic_set.id) self.assertEqual(current_set.genomicSetStatus, None) def test_invalid_does_not_update_validated_time(self): participant = self.make_participant(withdrawalStatus=WithdrawalStatus.NO_USE) self.make_summary(participant) genomic_set = self.make_genomic_set() member = self.make_genomic_member(genomic_set, participant) validate_and_update_genomic_set_by_id(genomic_set.id) current_member = self.genomic_member_dao.get(member.id) self.assertEqual(current_member.validatedTime, None) current_set = self.genomic_set_dao.get(genomic_set.id) self.assertEqual(current_set.validatedTime, None) def test_valid_does_update_validated_time(self): participant = self.make_participant() self.make_summary(participant) genomic_set = self.make_genomic_set() member = self.make_genomic_member(genomic_set, participant) now = datetime.datetime(2019, 1, 1) with clock.FakeClock(now): validate_and_update_genomic_set_by_id(genomic_set.id) current_member = self.genomic_member_dao.get(member.id) self.assertEqual(current_member.validatedTime, now) current_set = self.genomic_set_dao.get(genomic_set.id) self.assertEqual(current_set.validatedTime, now)
""" block56.py class Sprite Block Arrow Warp function buildUserBlocks wipe """ import pygame import interface56 import scroller56 import dinosInSpace import radar56 import soundFx56 import math import bounceMask class Block(pygame.sprite.Sprite): """ superclass for objects that can be placed """ OFFSCREEN = (-100,-100) minSpeed = dinosInSpace.Game.getMinSpeed() canRecoverThis = None # any obj that is eligible for recovery, if any canRotateThis = None # arrow obj that is eligible for rotation, if any canLinkThis = None # warp obj that is eligible for opening link, if any canEndLinkThis = None # warp obj that is eligible for closing link, if any activeGroup = pygame.sprite.RenderUpdates() # all active (on screen) blocks blockGroup = pygame.sprite.RenderUpdates() # all blocks, for radar def __init__(self): """ initiate pygame's sprite class """ pygame.sprite.Sprite.__init__(self) self.active = False Block.blockGroup.add(self) def update(self): self.checkActions() if self.active: self.setSpeed() @staticmethod def wipe(): Block.OFFSCREEN = (-100,-100) Block.minSpeed = dinosInSpace.Game.getMinSpeed() Block.canRecoverThis = None Block.canRotateThis = None Block.canLinkThis = None Block.canEndLinkThis = None Block.activeGroup = pygame.sprite.RenderUpdates() Block.blockGroup = pygame.sprite.RenderUpdates() @staticmethod def getBlockGroup(): return Block.blockGroup def setSpeed(self): """ set speed from Scroller """ xSpeedRatio, ySpeedRatio = scroller56.Scroller.speedData dx = xSpeedRatio * Block.minSpeed dy = ySpeedRatio * Block.minSpeed self.rect.centerx += dx self.rect.centery += dy def setRect(self): self.rect = self.image.get_rect() self.rect.center = Block.OFFSCREEN def checkActions(self): """ handle recovery / arrow rotation request from user """ if not Block.canRecoverThis: # make sure no other obj ready for recovery if not Block.canRotateThis: if not Block.canLinkThis: if not Block.canEndLinkThis: if self.rect.colliderect(interface56.Cursor.theCursor.rect): # cursor is over self if interface56.Cursor.isRecover: # pressing recover key Block.canRecoverThis = self # make self the item ready for recovery elif interface56.Cursor.canRotate: if self.CLASS == "Arrow": Block.canRotateThis = self # make self the item ready for rotation elif interface56.Cursor.canLink: if self.CLASS == "Warp": Block.canLinkThis = self # make self item ready for opening link elif interface56.Cursor.isLinking: if self.CLASS == "Warp": Block.canEndLinkThis = self # make self item ready for closing link if Block.canRecoverThis == self: # if self is ready for recovery (should ONLY BE 1) if self.rect.colliderect(interface56.Cursor.theCursor.rect): # cursor is over self if not interface56.Cursor.isRecover: # not pressing recover key Block.canRecoverThis = None else: # cursor is not over self Block.canRecoverThis = None elif Block.canRotateThis == self: if not self.rect.colliderect(interface56.Cursor.theCursor.rect) \ or interface56.Cursor.isRecover: Block.canRotateThis = None elif Block.canLinkThis == self: if not self.rect.colliderect(interface56.Cursor.theCursor.rect) \ or interface56.Cursor.isRecover: Block.canLinkThis = None elif Block.canEndLinkThis == self: if not self.rect.colliderect(interface56.Cursor.theCursor.rect) \ or interface56.Cursor.isRecover: Block.canEndLinkThis = None def placeMe(self, mousePos): """ place object on screen where user clicks, make active """ self.rect.center = mousePos self.image = self.original self.active = True Block.activeGroup.add(self) if self.CLASS == "Arrow": self.facing = interface56.Cursor.getArrowGlyphFacing() if self.facing == 1: pass elif self.facing == 2: self.image = pygame.transform.rotate(self.image, -90) elif self.facing == 3: self.image = pygame.transform.rotate(self.image, -180) elif self.facing == 4: self.image = pygame.transform.rotate(self.image, -270) def hideMe(self): """ hide object offscreen, make inactive """ self.rect.center = Block.OFFSCREEN self.active = False Block.activeGroup.remove(self) if self.CLASS == "Arrow": self.facing = 1 elif self.CLASS == "Warp": if self.linkedWarp: self.resetAll(True) else: self.resetAll(False) class Arrow(Block): """ child of placementObject - red for now """ colors = None arrowGroup = pygame.sprite.RenderUpdates() maskGroup = pygame.sprite.Group() def __init__(self, objColor): Block.__init__(self) self.CLASS = "Arrow" self.facing = 1 self.colorIndex = self.setColor(objColor) # color att and colorIndex self.loadImages() # load images and set self.setRect() Arrow.arrowGroup.add(self) self.bounceMask = bounceMask.BounceMask(self) Arrow.maskGroup.add(self.bounceMask) def flashBounceMask(self): self.bounceMask.flash() @staticmethod def wipe(): Arrow.arrowGroup = pygame.sprite.RenderUpdates() Arrow.maskGroup = pygame.sprite.Group() @staticmethod def reqRotate(): """ request to rotate 90 deg """ obj = Block.canRotateThis if obj: obj.facing += 1 # 1-North, 2-East, 3-South, 4-West if obj.facing > 4: obj.facing = 1 soundFx56.GameSoundManager.registerSound("rotate") # play sound obj.image = pygame.transform.rotate(obj.image, -90) def setColor(self, objColor): self.objColor = objColor # green, blue, red, yellow if objColor == "green": colorIndex = 0 elif objColor == "blue": colorIndex = 1 elif objColor == "red": colorIndex = 2 elif objColor == "yellow": colorIndex = 3 else: colorIndex = 4 # grey return colorIndex def loadImages(self): """ multiple colors """ if not Arrow.colors: Arrow.colors = [] for i in range(5): imageFile = "nArrow" + str(i + 1) + ".png" # generate a unique file name image = dinosInSpace.loadImage(imageFile, "2X", (0,0)) Arrow.colors.append(image) self.image = Arrow.colors[self.colorIndex] self.original = self.image.copy() class Warp(Block): """ blocks that warps dinos """ defaultImage = None # surface warpReadyImage = None # surface NUMFRAMES = 24 # frames in active animation SEQFRAMES = 11 # frames in opening / closing animation PAIRS = ["A", "B", "C", "D", "E"] # all unique warps imagePairDict = {} # { 1 : [framesInList, framesOutList, inUse=False], etc... } readyForLink = None # obj - hold ready during link ready period transferInFrames = None # frames to transfer to new enter state transferSeqFrames = None # seq frames to transfer to new enter state warpGroup = pygame.sprite.RenderUpdates() def __init__(self): Block.__init__(self) self.CLASS = "Warp" self.setDefaultImage() self.state = "default" self.setImagePairs() self.rect = self.image.get_rect() self.rect.center = Block.OFFSCREEN self.warpNumIndex = None self.linkedWarp = None self.activeFrames = None # list of frames, depending on pair assignment self.seqFrames = None # list of frames for opening / closing sequence self.currentFrameSet = None # current set of frames to animate self.frame = 0 Warp.warpGroup.add(self) def update(self): Block.update(self) if self.state == "enter" or self.state == "exit" or self.state == "default": if self.currentFrameSet: self.changeFrame(self.currentFrameSet) @staticmethod def wipe(): Warp.readyForLink = None Warp.transferInFrames = None Warp.transferSeqFrames = None Warp.warpGroup = pygame.sprite.RenderUpdates() for i in Warp.imagePairDict: Warp.imagePairDict[i][2] = False @staticmethod def getImagePair(): """ return inFramesList, outFramesList, imagePairDict key """ for i in Warp.imagePairDict: if not Warp.imagePairDict[i][2]: inFramesList = Warp.imagePairDict[i][0] outFramesList = Warp.imagePairDict[i][1] inSeqList = Warp.imagePairDict[i][3] outSeqList = Warp.imagePairDict[i][4] Warp.imagePairDict[i][2] = True break return inFramesList, outFramesList, inSeqList, outSeqList, i @staticmethod def resetImagePair(i): """ make image pair avaliable for future use """ if i: Warp.imagePairDict[i][2] = False @staticmethod def reqInitLink(): """ setState 'ready' for warp """ canLinkThis = Block.canLinkThis if canLinkThis: soundFx56.GameSoundManager.registerSound("chain") if canLinkThis.linkedWarp: canLinkThis.linkedWarp.setState("default") canLinkThis.setState("ready") interface56.Cursor.reqLink() Tracer.activate(canLinkThis) @staticmethod def reqMakeLink(): """ setState 'enter' and 'exit' for warps """ canEndLink = Block.canEndLinkThis if canEndLink: if Warp.readyForLink != canEndLink: soundFx56.GameSoundManager.registerSound("openWarp") if canEndLink.linkedWarp: canEndLink.linkedWarp.setState("default") canEndLink.setState("exit") interface56.Cursor.breakLink() else: interface56.Cursor.breakLink() Warp.readyForLink.resetAll(False) def getCenter(self): return self.rect.center def changeFrame(self, frameSet): if frameSet == "active": if self.frame + 1 > len(self.activeFrames): self.frame = 0 self.image = self.activeFrames[self.frame] self.frame += 1 elif frameSet == "open": self.image = self.seqFrames[self.frame] self.frame += 1 if self.frame + 1 > (len(self.seqFrames) - 1): self.frame = 0 self.currentFrameSet = "active" elif frameSet == "close": if self.frame < 0: self.frame = 0 self.image = Warp.defaultImage self.currentFrameSet = None else: self.image = self.seqFrames[self.frame] self. frame -= 1 def setDefaultImage(self): """ set Warp.defaultImage, Warp.warpReadyImage, self.image, self.original """ if not Warp.defaultImage: image = dinosInSpace.loadImage("warpClosed.png", (100,100), (0,0)) image2 = dinosInSpace.loadImage("warpReady.png", (100,100), (0,0)) Warp.defaultImage = image Warp.warpReadyImage = image2 self.image = Warp.defaultImage self.original = self.image def setImagePairs(self): """ set Warp.imagePairDict, the unique letter warp pairs """ if not Warp.imagePairDict: dictKey = 1 for i in Warp.PAIRS: inFramesList = [] outFramesList = [] inSeqList = [] outSeqList = [] prefix = "000" for j in range(Warp.NUMFRAMES): imgInFile = "warpOpenIn" + i + str(j) + ".png" imgOutFile = "warpOpenOut" + i + str(j) + ".png" imgIn = dinosInSpace.loadImage(imgInFile, (100,100), (0,0)) imgOut = dinosInSpace.loadImage(imgOutFile, (100,100), (0,0)) inFramesList.append(imgIn) outFramesList.append(imgOut) for k in range(Warp.SEQFRAMES): if k > 9: prefix = "00" inSeqFile = "warpInSeq" + i + prefix + str(k) + ".png" outSeqFile = "warpOutSeq" + i + prefix + str(k) + ".png" imgInSeq = dinosInSpace.loadImage(inSeqFile, (100,100), (0,0)) imgOutSeq = dinosInSpace.loadImage(outSeqFile, (100,100), (0,0)) inSeqList.append(imgInSeq) outSeqList.append(imgOutSeq) Warp.imagePairDict[dictKey] = [inFramesList, outFramesList, False, inSeqList, outSeqList] dictKey += 1 def resetAll(self, animate): """ setStates of linked warps to 'default' """ if self.linkedWarp: if animate: self.linkedWarp.setState("default") else: Warp.resetImagePair(self.linkedWarp.warpNumIndex) self.linkedWarp.state = "default" self.linkedWarp.setWarpNumIndex(None) self.linkedWarp.image = Warp.defaultImage self.linkedWarp.currentFrameSet = None self.linkedWarp = None if animate: self.setState("default") else: Warp.resetImagePair(self.warpNumIndex) self.state = "default" self.setWarpNumIndex(None) self.image = Warp.defaultImage self.currentFrameSet = None self.linkedWarp = None Warp.readyForLink = None def setState(self, state): """ set self.state, self.image """ self.state = state if state == "default": Warp.resetImagePair(self.warpNumIndex) self.setWarpNumIndex(None) self.linkedWarp = None self.currentFrameSet = "close" self.frame = Warp.SEQFRAMES - 1 elif state == "ready": Warp.readyForLink = self self.linkedWarp = None self.image = Warp.warpReadyImage elif state == "enter": self.activeFrames = Warp.transferInFrames self.seqFrames = Warp.transferSeqFrames self.currentFrameSet = "open" self.frame = 0 elif state == "exit": inFramesList, outFramesList, inSeqList, outSeqList, i = Warp.getImagePair() self.setWarpNumIndex(i) Warp.transferInFrames = inFramesList Warp.transferSeqFrames = inSeqList Warp.readyForLink.setState("enter") Warp.readyForLink.setLinkedWarp(self) Warp.readyForLink.setWarpNumIndex(i) self.setLinkedWarp(Warp.readyForLink) Warp.readyForLink = None self.activeFrames = outFramesList self.seqFrames = outSeqList self.currentFrameSet = "open" self.frame = 0 def setWarpNumIndex(self, i): self.warpNumIndex = i def setLinkedWarp(self, w): self.linkedWarp = w class Tracer(pygame.sprite.Sprite): """ Line from warp to cursor """ traceFrom = None tracerGroup = pygame.sprite.RenderUpdates() color = (255,122,66) size = 1 def __init__(self): pygame.sprite.Sprite.__init__(self) self.clearImage() Tracer.tracerGroup.add(self) def update(self): if Tracer.traceFrom: if interface56.Cursor.isLinking: self.tracePath() else: Tracer.traceFrom = None self.clearImage() @staticmethod def wipe(): Tracer.traceFrom = None Tracer.tracerGroup = pygame.sprite.RenderUpdates() @staticmethod def activate(traceFrom): Tracer.traceFrom = traceFrom def tracePath(self): """ draw a line from warp to cursor """ abs = math.fabs mouseX, mouseY = pygame.mouse.get_pos() traceX, traceY = Tracer.traceFrom.rect.center w = abs(mouseX - traceX) h = abs(mouseY - traceY) if w < 3: w = 3 if h < 3: h = 3 self.image = pygame.Surface((w, h)) self.image.fill((255,255,255)) transparent = self.image.get_at((0,0)) self.image.set_colorkey(transparent, pygame.RLEACCEL) self.rect = self.image.get_rect() imgW = self.image.get_width() imgH = self.image.get_height() c = Tracer.color s = Tracer.size if mouseX >= traceX and mouseY <= traceY: self.rect.bottomleft = (traceX, traceY) pygame.draw.line(self.image, c, (0, imgH), (imgW, 0), s) elif mouseX >= traceX and mouseY >= traceY: self.rect.topleft = (traceX, traceY) pygame.draw.line(self.image, c, (0, 0), (imgW, imgH), s) elif mouseX <= traceX and mouseY <= traceY: self.rect.bottomright = (traceX, traceY) pygame.draw.line(self.image, c, (imgW, imgH), (0, 0), s) elif mouseX <= traceX and mouseY >= traceY: self.rect.topright = (traceX, traceY) pygame.draw.line(self.image, c, (imgW, 0), (0, imgH), s) def clearImage(self): self.image = pygame.Surface((2,2)) self.rect = self.image.get_rect() def buildUserBlocks(game, keyList): """ Block instances created here """ allChannels = [] arrowGroup = pygame.sprite.RenderUpdates() for k in keyList: channelList = [] objType = k[0] objColor = k[1] numToMake = k[2] for num in range(numToMake): if objType == "arrow": # make arrow block newObj = Arrow(objColor) channelList.append(newObj) arrowGroup.add(newObj) if objType == "warp": # make warp block newObj = Warp() channelList.append(newObj) allChannels.append(channelList) game.addGroup(Arrow.arrowGroup) game.addGroup(Arrow.maskGroup) game.addGroup(Warp.warpGroup) # pass data to other objects interface56.ItemMenu.assignData(allChannels) interface56.Cursor.setBlockData(allChannels, arrowGroup) def wipe(): Block.wipe() Arrow.wipe() Warp.wipe() Tracer.wipe() if __name__ == "__main__": print "module for import only"
import json import os import tempfile from django.contrib.auth.models import User from django.template.defaultfilters import slugify from django.test import ( TestCase as BaseTestCase, Client as BaseClient ) import factory from django_nose.tools import assert_equal from factory import LazyAttribute, Sequence, SubFactory, SelfAttribute from factory.django import DjangoModelFactory from mock import patch from pontoon.base.models import ( ChangedEntityLocale, Entity, Locale, Project, ProjectLocale, Repository, Resource, TranslatedResource, Subpage, Translation, TranslationMemoryEntry ) class PontoonClient(BaseClient): """Useful helper methods that can be used in tests.""" def ajax_post(self, url, params): """Send data to the ajax-type view.""" return self.post(url, params, HTTP_X_REQUESTED_WITH='XMLHttpRequest') class TestCase(BaseTestCase): client_class = PontoonClient def patch(self, *args, **kwargs): """ Wrapper around mock.patch that automatically cleans up the patch in the test cleanup phase. """ patch_obj = patch(*args, **kwargs) self.addCleanup(patch_obj.stop) return patch_obj.start() def patch_object(self, *args, **kwargs): """ Wrapper around mock.patch.object that automatically cleans up the patch in the test cleanup phase. """ patch_obj = patch.object(*args, **kwargs) self.addCleanup(patch_obj.stop) return patch_obj.start() class UserFactory(DjangoModelFactory): username = Sequence(lambda n: 'test%s' % n) email = Sequence(lambda n: 'test%[email protected]' % n) class Meta: model = User class ProjectFactory(DjangoModelFactory): name = Sequence(lambda n: 'Project {0}'.format(n)) slug = LazyAttribute(lambda p: slugify(p.name)) links = False class Meta: model = Project @factory.post_generation def locales(self, create, extracted, **kwargs): if not create: return if extracted: for locale in extracted: ProjectLocaleFactory.create(project=self, locale=locale) @factory.post_generation def repositories(self, create, extracted, **kwargs): if not create: return if extracted is not None: for repository in extracted: self.repositories.add(repository) else: # Default to a single valid repo. self.repositories.add(RepositoryFactory.build(), bulk=False) class ProjectLocaleFactory(DjangoModelFactory): class Meta: model = ProjectLocale class RepositoryFactory(DjangoModelFactory): project = SubFactory(ProjectFactory) type = 'git' url = Sequence(lambda n: 'https://example.com/url_{0}.git'.format(n)) class Meta: model = Repository class ResourceFactory(DjangoModelFactory): project = SubFactory(ProjectFactory) path = '/fake/path.po' format = 'po' total_strings = 1 class Meta: model = Resource class LocaleFactory(DjangoModelFactory): code = Sequence(lambda n: 'en-{0}'.format(n)) name = Sequence(lambda n: 'English #{0}'.format(n)) class Meta: model = Locale class EntityFactory(DjangoModelFactory): resource = SubFactory(ResourceFactory) string = Sequence(lambda n: 'string {0}'.format(n)) class Meta: model = Entity class PluralEntityFactory(DjangoModelFactory): resource = SubFactory(ResourceFactory) string = Sequence(lambda n: 'string {0}'.format(n)) string_plural = Sequence(lambda n: 'string plural {0}'.format(n)) class Meta: model = Entity class ChangedEntityLocaleFactory(DjangoModelFactory): entity = SubFactory(EntityFactory) locale = SubFactory(LocaleFactory) class Meta: model = ChangedEntityLocale class TranslationFactory(DjangoModelFactory): entity = SubFactory(EntityFactory) locale = SubFactory(LocaleFactory) string = Sequence(lambda n: 'translation {0}'.format(n)) user = SubFactory(UserFactory) class Meta: model = Translation class IdenticalTranslationFactory(TranslationFactory): entity = SubFactory(EntityFactory, string=SelfAttribute('..string')) class TranslationMemoryFactory(DjangoModelFactory): source = Sequence(lambda n: 'source {0}'.format(n)) target = Sequence(lambda n: 'target {0}'.format(n)) entity = SubFactory(EntityFactory, string=SelfAttribute('..source')) locale = SubFactory(LocaleFactory) class Meta: model = TranslationMemoryEntry class TranslatedResourceFactory(DjangoModelFactory): resource = SubFactory(ResourceFactory) locale = SubFactory(LocaleFactory) class Meta: model = TranslatedResource class SubpageFactory(DjangoModelFactory): project = SubFactory(ProjectFactory) name = Sequence(lambda n: 'subpage {0}'.format(n)) class Meta: model = Subpage @factory.post_generation def resources(self, create, extracted, **kwargs): if not create: return if extracted: for resource in extracted: self.resources.add(resource) def assert_redirects(response, expected_url, status_code=302, host=None, secure=False): """ Assert that the given response redirects to the expected URL. The main difference between this and TestCase.assertRedirects is that this version doesn't follow the redirect. """ if host is None: host = '{}://{}'.format('https' if secure else 'http', host or 'testserver') assert_equal(response.status_code, status_code) assert_equal(response['Location'], host + expected_url) def assert_attributes_equal(original, **expected_attrs): """ Assert that the given object has attributes matching the given values. """ if not expected_attrs: raise ValueError('Expected some attributes to check.') for key, value in expected_attrs.items(): original_value = getattr(original, key) assert_equal( original_value, value, ('Attribute `{key}` does not match: {original_value} != {value}' .format(key=key, original_value=original_value, value=value)), ) class NOT(object): """ A helper class that compares equal to everything except its given values. >>> mock_function('foobarbaz') >>> mock_function.assert_called_with(NOT('fizzbarboff')) # Passes >>> mock_function.assert_called_with(NOT('foobarbaz')) # Fails """ def __init__(self, *values): self.values = values def __eq__(self, other): return other not in self.values def __ne__(self, other): return other in self.values def __repr__(self): return '<NOT %r>' % self.values class CONTAINS(object): """ Helper class that is considered equal to any object that contains elements the elements passed to it. Used mostly in conjunction with Mock.assert_called_with to test if a string argument contains certain substrings: >>> mock_function('foobarbaz') >>> mock_function.assert_called_with(CONTAINS('bar')) # Passes """ def __init__(self, *args): self.items = args def __eq__(self, other): return all(item in other for item in self.items) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return '<CONTAINS {0}>'.format(','.join(repr(item) for item in self.items)) def create_tempfile(contents): """ Create a temporary file with the given contents, and return the path to the created file. """ fd, path = tempfile.mkstemp() with os.fdopen(fd, 'w') as f: f.write(contents) return path def assert_json(response, expected_obj): """ Checks if response contains a expected json object. """ assert_equal(json.loads(response.content), expected_obj)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2010-2011 OpenStack, 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. import unittest2 as unittest from keystone.test.functional import common class ServicesTest(common.FunctionalTestCase): def setUp(self, *args, **kwargs): super(ServicesTest, self).setUp(*args, **kwargs) def tearDown(self, *args, **kwargs): super(ServicesTest, self).tearDown(*args, **kwargs) class GetServicesTest(ServicesTest): def test_get_services_using_keystone_admin_token_json(self): services = self.list_services(assert_status=200).\ json['OS-KSADM:services'] self.assertTrue(len(services)) def test_get_services_using_keystone_admin_token_xml(self): r = self.list_services(assert_status=200, headers={ 'Accept': 'application/xml'}) self.assertEqual(r.xml.tag, "{%s}services" % self.xmlns_ksadm) services = r.xml.findall("{%s}service" % self.xmlns_ksadm) self.assertTrue(len(services)) def test_get_services_using_service_admin_token(self): self.admin_token = self.service_admin_token services = self.list_services(assert_status=200).\ json['OS-KSADM:services'] self.assertTrue(len(services)) def test_get_services_using_service_admin_token_xml(self): self.admin_token = self.service_admin_token r = self.get_services(assert_status=200, headers={ 'Accept': 'application/xml'}) self.assertEqual(r.xml.tag, "{%s}services" % self.xmlns_ksadm) services = r.xml.findall("{%s}service" % self.xmlns_ksadm) self.assertTrue(len(services)) def test_get_services_using_disabled_token(self): self.admin_token = self.disabled_admin_token self.list_services(assert_status=403) def test_get_services_using_missing_token(self): self.admin_token = '' self.list_services(assert_status=401) def test_get_services_using_expired_token(self): self.admin_token = self.expired_admin_token self.list_services(assert_status=403) def test_get_services_using_invalid_token(self): self.admin_token = common.unique_str() self.list_services(assert_status=401) class GetServiceTest(ServicesTest): def setUp(self, *args, **kwargs): super(ServicesTest, self).setUp(*args, **kwargs) self.service = self.create_service().json['OS-KSADM:service'] def test_service_get_json(self): service = self.fetch_service(service_id=self.service['id'], assert_status=200).json['OS-KSADM:service'] self.assertIsNotNone(service['id']) self.assertIsNotNone(service['description']) def test_service_get_xml(self): service = self.fetch_service(service_id=self.service['id'], assert_status=200, headers={'Accept': 'application/xml'}).xml self.assertEqual(service.tag, '{%s}service' % self.xmlns_ksadm) self.assertIsNotNone(service.get('id')) self.assertIsNotNone(service.get('description')) def test_get_service_using_disabled_token(self): self.admin_token = self.disabled_admin_token self.fetch_service(service_id=self.service['id'], assert_status=403) def test_get_service_using_missing_token(self): self.admin_token = '' self.fetch_service(service_id=self.service['id'], assert_status=401) def test_get_service_using_expired_token(self): self.admin_token = self.expired_admin_token self.fetch_service(service_id=self.service['id'], assert_status=403) def test_get_service_using_invalid_token(self): self.admin_token = common.unique_str() self.fetch_service(service_id=self.service['id'], assert_status=401) class GetServiceByNameTest(ServicesTest): def setUp(self, *args, **kwargs): super(GetServiceByNameTest, self).setUp(*args, **kwargs) self.service = self.create_service().json['OS-KSADM:service'] def test_service_get_json(self): service = self.fetch_service_by_name(service_name=self.service['name'], assert_status=200).json['OS-KSADM:service'] self.assertIsNotNone(service['id']) self.assertIsNotNone(service['name']) self.assertIsNotNone(service['description']) def test_service_get_xml(self): service = self.fetch_service_by_name(service_name=self.service['name'], assert_status=200, headers={'Accept': 'application/xml'}).xml self.assertEqual(service.tag, '{%s}service' % self.xmlns_ksadm) self.assertIsNotNone(service.get('id')) self.assertIsNotNone(service.get('name')) self.assertIsNotNone(service.get('description')) def test_get_service_using_disabled_token(self): self.admin_token = self.disabled_admin_token self.fetch_service_by_name( service_name=self.service['name'], assert_status=403) def test_get_service_using_missing_token(self): self.admin_token = '' self.fetch_service_by_name( service_name=self.service['name'], assert_status=401) def test_get_service_using_expired_token(self): self.admin_token = self.expired_admin_token self.fetch_service_by_name( service_name=self.service['name'], assert_status=403) def test_get_service_using_invalid_token(self): self.admin_token = common.unique_str() self.fetch_service_by_name( service_name=self.service['name'], assert_status=401) class CreateServiceTest(ServicesTest): def test_service_create_json(self): name = common.unique_str() type = common.unique_str() description = common.unique_str() service = self.create_service(service_name=name, service_type=type, service_description=description, assert_status=201).json['OS-KSADM:service'] self.assertIsNotNone(service.get('id')) self.assertEqual(name, service.get('name')) self.assertEqual(type, service.get('type')) self.assertEqual(description, service.get('description')) def test_service_create_xml(self): name = common.unique_str() type = common.unique_str() description = common.unique_str() data = ('<?xml version="1.0" encoding="UTF-8"?> ' '<service xmlns="%s" name="%s" type="%s" description="%s"/>') % ( self.xmlns_ksadm, name, type, description) r = self.post_service(as_xml=data, assert_status=201) self.assertEqual(r.xml.tag, "{%s}service" % self.xmlns_ksadm) self.assertIsNotNone(r.xml.get('id')) self.assertEqual(name, r.xml.get('name')) self.assertEqual(type, r.xml.get('type')) self.assertEqual(description, r.xml.get('description')) def test_service_create_duplicate_json(self): service_name = common.unique_str() self.create_service(service_name=service_name, assert_status=201) self.create_service(service_name=service_name, assert_status=409) def test_service_create_using_expired_token(self): self.admin_token = self.expired_admin_token self.create_service(assert_status=403) def test_service_create_using_disabled_token(self): self.admin_token = self.disabled_admin_token self.create_service(assert_status=403) def test_service_create_json_using_missing_token(self): self.admin_token = '' self.create_service(assert_status=401) def test_service_create_json_using_invalid_token(self): self.admin_token = common.unique_str() self.create_service(assert_status=401) class DeleteServiceTest(ServicesTest): def setUp(self, *args, **kwargs): super(DeleteServiceTest, self).setUp(*args, **kwargs) self.service = self.create_service().json['OS-KSADM:service'] def test_service_delete(self): self.remove_service(self.service['id'], assert_status=204) self.get_service(self.service['id'], assert_status=404) def test_delete_service_with_dependencies(self): role_id = self.service['name'] + ':' + common.unique_str() role = self.create_role(role_id, service_id=self.service['id'], assert_status=201).json['role'] tenant = self.create_tenant().json['tenant'] user = self.create_user(tenant_id=tenant['id']).json['user'] self.grant_role_to_user(user['id'], role['id'], tenant['id']) self.create_endpoint_template(name=self.service['name'], type=self.service['type']) self.remove_service(self.service['id'], assert_status=204) def test_service_delete_json_using_expired_token(self): self.admin_token = self.expired_admin_token self.remove_service(self.service['id'], assert_status=403) def test_service_delete_json_using_disabled_token(self): self.admin_token = self.disabled_admin_token self.remove_service(self.service['id'], assert_status=403) def test_service_delete_json_using_missing_token(self): self.admin_token = '' self.remove_service(self.service['id'], assert_status=401) def test_service_delete_json_using_invalid_token(self): self.admin_token = common.unique_str() self.remove_service(self.service['id'], assert_status=401) if __name__ == '__main__': unittest.main()
from util import * from google.protobuf import text_format import convnet_config_pb2 def ChooseEdge(edge_proto): if edge_proto.edge_type == convnet_config_pb2.Edge.CONVOLUTIONAL: return ConvEdge(edge_proto) elif edge_proto.edge_type == convnet_config_pb2.Edge.CONV_ONETOONE: return ConvOneToOneEdge(edge_proto) elif edge_proto.edge_type == convnet_config_pb2.Edge.FC: return FCEdge(edge_proto) elif edge_proto.edge_type == convnet_config_pb2.Edge.MAXPOOL: return MaxPoolEdge(edge_proto) elif edge_proto.edge_type == convnet_config_pb2.Edge.RESPONSE_NORM: return ResponseNormEdge(edge_proto) else: raise Exception('Edge type not implemented.') def CreateConvDesc(edge_proto): return cm.GetConvDesc(1, 1, edge_proto.kernel_size, edge_proto.kernel_size, edge_proto.stride, edge_proto.stride, edge_proto.padding, edge_proto.padding) class Edge(object): def __init__(self, edge_proto): self.source_name_ = edge_proto.source self.dest_name_ = edge_proto.dest self.num_modules_y_ = 1 self.num_modules_x_ = 1 self.name_ = '%s:%s' % (self.source_name_, self.dest_name_) def SetSource(self, l): self.source_ = l self.num_input_channels_ = l.GetNumChannels() def SetDest(self, l): self.dest_ = l self.num_output_channels_ = l.GetNumChannels() def GetSourceName(self): return self.source_name_ def GetDestName(self): return self.dest_name_ def GetSource(self): return self.source_ def GetDest(self): return self.dest_ def SetImageSize(self, image_size_y, image_size_x): self.image_size_y_ = image_size_y self.image_size_x_ = image_size_x self.num_modules_y_ = 1 self.num_modules_x_ = 1 def GetNumModules(self): return self.num_modules_y_, self.num_modules_x_ def AllocateMemory(self): pass def LoadParams(self, f): pass def ComputeUp(self, input_layer, output_layer, overwrite): pass class EdgeWithWeight(Edge): def __init__(self, edge_proto): super(EdgeWithWeight, self).__init__(edge_proto) self.weights_ = None self.bias_ = None def LoadParams(self, f): w_name = '%s:weight' % self.name_ w = f[w_name].value.T assert self.weights_.shape == w.shape, "Shape mismatch %s %s %s" % (w_name, self.weights_.shape, w.shape) self.weights_.overwrite(w) b_name = '%s:bias' % self.name_ b = f[b_name].value.reshape(1, -1) assert self.bias_.shape == b.shape, "Shape mismatch %s" % (b_name, self.bias_.shape, b.shape) self.bias_.overwrite(b) class ConvEdge(EdgeWithWeight): def __init__(self, edge_proto): super(ConvEdge, self).__init__(edge_proto) self.conv_desc_ = CreateConvDesc(edge_proto) self.shared_bias_ = edge_proto.shared_bias def SetImageSize(self, image_size_y, image_size_x): self.conv_desc_.num_input_channels = self.num_input_channels_ self.conv_desc_.num_output_channels = self.num_output_channels_ self.image_size_y_ = image_size_y self.image_size_x_ = image_size_x self.num_modules_y_, self.num_modules_x_ = cm.GetOutputShape(image_size_y, image_size_x, self.conv_desc_) def AllocateMemory(self): input_size = self.conv_desc_.kernel_size_x * self.conv_desc_.kernel_size_y * self.num_input_channels_ if self.shared_bias_: bias_locs = 1 else: bias_locs = self.num_modules_y_ * self.num_modules_x_ if self.weights_ is not None: self.weights_.free_device_memory() if self.bias_ is not None: self.bias_.free_device_memory() self.weights_ = cm.empty((self.num_output_channels_, input_size)) self.bias_ = cm.empty((1, self.num_output_channels_ * bias_locs)) self.weights_.set_shape4d( (self.num_output_channels_, self.conv_desc_.kernel_size_x, self.conv_desc_.kernel_size_y, self.num_input_channels_)) def ComputeUp(self, input_layer, output_layer, overwrite): scale_targets = 0 if overwrite else 1 w = self.weights_ b = self.bias_ input_state = input_layer.GetState() output_state = output_layer.GetState() batch_size = input_state.shape[0] cc_gemm.convUp(input_state, w, output_state, self.conv_desc_, scale_targets) if self.shared_bias_: output_state.reshape((-1, self.num_output_channels_)) output_state.add_row_vec(b) if self.shared_bias_: output_state.reshape((batch_size, -1)) class MaxPoolEdge(Edge): def __init__(self, edge_proto): super(MaxPoolEdge, self).__init__(edge_proto) self.conv_desc_ = CreateConvDesc(edge_proto) def SetImageSize(self, image_size_y, image_size_x): self.conv_desc_.num_input_channels = self.num_input_channels_ self.conv_desc_.num_output_channels = self.num_output_channels_ self.image_size_y_ = image_size_y self.image_size_x_ = image_size_x self.num_modules_y_, self.num_modules_x_ = cm.GetOutputShape(image_size_y, image_size_x, self.conv_desc_) def ComputeUp(self, input_layer, output_layer, overwrite): input_state = input_layer.GetState() output_state = output_layer.GetState() cc_gemm.MaxPool(input_state, output_state, self.conv_desc_) class ResponseNormEdge(Edge): def __init__(self, edge_proto): super(ResponseNormEdge, self).__init__(edge_proto) self.num_filters_response_norm_ = 0 self.blocked_ = edge_proto.response_norm_in_blocks self.add_scale_ = edge_proto.add_scale self.pow_scale_ = edge_proto.pow_scale self.frac_ = edge_proto.frac_of_filters_response_norm def SetImageSize(self, image_size_y, image_size_x): self.image_size_y_ = image_size_y self.image_size_x_ = image_size_x self.num_modules_y_ = image_size_y self.num_modules_x_ = image_size_x self.num_filters_response_norm_ = int(self.frac_ * self.num_input_channels_) def ComputeUp(self, input_layer, output_layer, overwrite): input_state = input_layer.GetState() output_state = output_layer.GetState() cc_gemm.ResponseNormCrossMap( input_state, output_state, self.num_filters_response_norm_, self.add_scale_, self.pow_scale_, self.blocked_) class FCEdge(EdgeWithWeight): def __init__(self, edge_proto): super(FCEdge, self).__init__(edge_proto) def AllocateMemory(self): input_size = self.image_size_x_ * self.image_size_y_ * self.num_input_channels_ self.weights_ = cm.empty((self.num_output_channels_, input_size)) self.bias_ = cm.empty((1, self.num_output_channels_)) def ComputeUp(self, input_layer, output_layer, overwrite): scale_targets = 0 if overwrite else 1 input_state = input_layer.GetState() output_state = output_layer.GetState() w = self.weights_ b = self.bias_ cm.dot(input_state, w.T, target=output_state, scale_targets=scale_targets) output_state.add_row_vec(b) class ConvOneToOneEdge(EdgeWithWeight): def __init__(self, edge_proto): super(ConvOneToOneEdge, self).__init__(edge_proto) def SetImageSize(self, image_size_y, image_size_x): self.image_size_y_ = image_size_y self.image_size_x_ = image_size_x self.num_modules_y_ = image_size_y self.num_modules_x_ = image_size_x def AllocateMemory(self): self.weights_ = cm.empty((self.num_output_channels_, self.num_input_channels_)) self.bias_ = cm.empty((1, self.num_output_channels_)) def ComputeUp(self, input_layer, output_layer, overwrite): scale_targets = 0 if overwrite else 1 w = self.weights_ b = self.bias_ input_state = input_layer.GetState() output_state = output_layer.GetState() batch_size = input_state.shape[0] input_state.reshape((-1, self.num_input_channels_)) output_state.reshape((-1, self.num_output_channels_)) cm.dot(input_state, w.T, target=output_state, scale_targets=scale_targets) output_state.add_row_vec(b) input_state.reshape((batch_size, -1)) output_state.reshape((batch_size, -1))
# subprocess - Subprocesses with accessible I/O streams # # For more information about this module, see PEP 324. # # This module should remain compatible with Python 2.2, see PEP 291. # # Copyright (c) 2003-2005 by Peter Astrand <[email protected]> # # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/2.4/license for licensing details. r"""subprocess - Subprocesses with accessible I/O streams This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, like: os.system os.spawn* os.popen* popen2.* commands.* Information about how the subprocess module can be used to replace these modules and functions can be found below. Using the subprocess module =========================== This module defines one class called Popen: class Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0): Arguments are: args should be a string, or a sequence of program arguments. The program to execute is normally the first item in the args sequence or string, but can be explicitly set by using the executable argument. On UNIX, with shell=False (default): In this case, the Popen class uses os.execvp() to execute the child program. args should normally be a sequence. A string will be treated as a sequence with the string as the only item (the program to execute). On UNIX, with shell=True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments. On Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline method. Please note that not all MS Windows applications interpret the command line the same way: The list2cmdline is designed for applications using the same rules as the MS C runtime. bufsize, if given, has the same meaning as the corresponding argument to the built-in open() function: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. A negative bufsize means to use the system default, which usually means fully buffered. The default value for bufsize is 0 (unbuffered). stdin, stdout and stderr specify the executed programs' standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With None, no redirection will occur; the child's file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout. If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. if shell is true, the specified command will be executed through the shell. If cwd is not None, the current directory will be changed to cwd before the child is executed. If env is not None, it defines the environment variables for the new process. If universal_newlines is true, the file objects stdout and stderr are opened as a text files, but lines may be terminated by any of '\n', the Unix end-of-line convention, '\r', the Macintosh convention or '\r\n', the Windows convention. All of these external representations are seen as '\n' by the Python program. Note: This feature is only available if Python is built with universal newline support (the default). Also, the newlines attribute of the file objects stdout, stdin and stderr are not updated by the communicate() method. The startupinfo and creationflags, if given, will be passed to the underlying CreateProcess() function. They can specify things such as appearance of the main window and priority for the new process. (Windows only) This module also defines two shortcut functions: call(*popenargs, **kwargs): Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) check_call(*popenargs, **kwargs): Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example: check_call(["ls", "-l"]) Exceptions ---------- Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent. Additionally, the exception object will have one extra attribute called 'child_traceback', which is a string containing traceback information from the childs point of view. The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSErrors. A ValueError will be raised if Popen is called with invalid arguments. check_call() will raise CalledProcessError, if the called process returns a non-zero return code. Security -------- Unlike some other popen functions, this implementation will never call /bin/sh implicitly. This means that all characters, including shell metacharacters, can safely be passed to child processes. Popen objects ============= Instances of the Popen class have the following methods: poll() Check if child process has terminated. Returns returncode attribute. wait() Wait for child process to terminate. Returns returncode attribute. communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr). Note: The data read is buffered in memory, so do not use this method if the data size is large or unlimited. The following attributes are also available: stdin If the stdin argument is PIPE, this attribute is a file object that provides input to the child process. Otherwise, it is None. stdout If the stdout argument is PIPE, this attribute is a file object that provides output from the child process. Otherwise, it is None. stderr If the stderr argument is PIPE, this attribute is file object that provides error output from the child process. Otherwise, it is None. pid The process ID of the child process. returncode The child return code. A None value indicates that the process hasn't terminated yet. A negative value -N indicates that the child was terminated by signal N (UNIX only). Replacing older functions with the subprocess module ==================================================== In this section, "a ==> b" means that b can be used as a replacement for a. Note: All functions in this section fail (more or less) silently if the executed program cannot be found; this module raises an OSError exception. In the following examples, we assume that the subprocess module is imported with "from subprocess import *". Replacing /bin/sh shell backquote --------------------------------- output=`mycmd myarg` ==> output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] Replacing shell pipe line ------------------------- output=`dmesg | grep hda` ==> p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] Replacing os.system() --------------------- sts = os.system("mycmd" + " myarg") ==> p = Popen("mycmd" + " myarg", shell=True) pid, sts = os.waitpid(p.pid, 0) Note: * Calling the program through the shell is usually not required. * It's easier to look at the returncode attribute than the exitstatus. A more real-world example would look like this: try: retcode = call("mycmd" + " myarg", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e Replacing os.spawn* ------------------- P_NOWAIT example: pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") ==> pid = Popen(["/bin/mycmd", "myarg"]).pid P_WAIT example: retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg") ==> retcode = call(["/bin/mycmd", "myarg"]) Vector example: os.spawnvp(os.P_NOWAIT, path, args) ==> Popen([path] + args[1:]) Environment example: os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env) ==> Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}) Replacing os.popen* ------------------- pipe = os.popen(cmd, mode='r', bufsize) ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout pipe = os.popen(cmd, mode='w', bufsize) ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdin, child_stdout) = (p.stdin, p.stdout) (child_stdin, child_stdout, child_stderr) = os.popen3(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) (child_stdin, child_stdout, child_stderr) = (p.stdin, p.stdout, p.stderr) (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) Replacing popen2.* ------------------ Note: If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) ==> p = Popen(["somestring"], shell=True, bufsize=bufsize stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) ==> p = Popen(["mycmd", "myarg"], bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen, except that: * subprocess.Popen raises an exception if the execution fails * the capturestderr argument is replaced with the stderr argument. * stdin=PIPE and stdout=PIPE must be specified. * popen2 closes all filedescriptors by default, but you have to specify close_fds=True with subprocess.Popen. """ import sys mswindows = (sys.platform == "win32") import os import types import traceback # Exception classes used by this module. class CalledProcessError(Exception): """This exception is raised when a process run by check_call() returns a non-zero exit status. The exit status will be stored in the returncode attribute.""" def __init__(self, returncode, cmd): self.returncode = returncode self.cmd = cmd def __str__(self): return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) if mswindows: import threading import msvcrt if 0: # <-- change this to use pywin32 instead of the _subprocess driver import pywintypes from win32api import GetStdHandle, STD_INPUT_HANDLE, \ STD_OUTPUT_HANDLE, STD_ERROR_HANDLE from win32api import GetCurrentProcess, DuplicateHandle, \ GetModuleFileName, GetVersion from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE from win32pipe import CreatePipe from win32process import CreateProcess, STARTUPINFO, \ GetExitCodeProcess, STARTF_USESTDHANDLES, \ STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0 else: from _subprocess import * class STARTUPINFO: dwFlags = 0 hStdInput = None hStdOutput = None hStdError = None wShowWindow = 0 class pywintypes: error = IOError else: import select import errno import fcntl import pickle __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"] try: MAXFD = os.sysconf("SC_OPEN_MAX") except: MAXFD = 256 # True/False does not exist on 2.2.0 try: False except NameError: False = 0 True = 1 _active = [] def _cleanup(): for inst in _active[:]: if inst.poll(_deadstate=sys.maxint) >= 0: try: _active.remove(inst) except ValueError: # This can happen if two threads create a new Popen instance. # It's harmless that it was already removed, so ignore. pass PIPE = -1 STDOUT = -2 def call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) """ return Popen(*popenargs, **kwargs).wait() def check_call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example: check_call(["ls", "-l"]) """ retcode = call(*popenargs, **kwargs) cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] if retcode: raise CalledProcessError(retcode, cmd) return retcode def list2cmdline(seq): """ Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime: 1) Arguments are delimited by white space, which is either a space or a tab. 2) A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. 3) A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark. 4) Backslashes are interpreted literally, unless they immediately precede a double quotation mark. 5) If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3. """ # See # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp result = [] needquote = False for arg in seq: bs_buf = [] # Add a space to separate this argument from the others if result: result.append(' ') needquote = (" " in arg) or ("\t" in arg) or arg == "" if needquote: result.append('"') for c in arg: if c == '\\': # Don't know if we need to double yet. bs_buf.append(c) elif c == '"': # Double backspaces. result.append('\\' * len(bs_buf)*2) bs_buf = [] result.append('\\"') else: # Normal char if bs_buf: result.extend(bs_buf) bs_buf = [] result.append(c) # Add remaining backspaces, if any. if bs_buf: result.extend(bs_buf) if needquote: result.extend(bs_buf) result.append('"') return ''.join(result) class Popen(object): def __init__(self, args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0): """Create new Popen instance.""" _cleanup() self._child_created = False if not isinstance(bufsize, (int, long)): raise TypeError("bufsize must be an integer") if mswindows: if preexec_fn is not None: raise ValueError("preexec_fn is not supported on Windows " "platforms") if close_fds: raise ValueError("close_fds is not supported on Windows " "platforms") else: # POSIX if startupinfo is not None: raise ValueError("startupinfo is only supported on Windows " "platforms") if creationflags != 0: raise ValueError("creationflags is only supported on Windows " "platforms") self.stdin = None self.stdout = None self.stderr = None self.pid = None self.returncode = None self.universal_newlines = universal_newlines # Input and output objects. The general principle is like # this: # # Parent Child # ------ ----- # p2cwrite ---stdin---> p2cread # c2pread <--stdout--- c2pwrite # errread <--stderr--- errwrite # # On POSIX, the child objects are file descriptors. On # Windows, these are Windows file handles. The parent objects # are file descriptors on both platforms. The parent objects # are None when not using PIPEs. The child objects are None # when not redirecting. (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr) self._execute_child(args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) # On Windows, you cannot just redirect one or two handles: You # either have to redirect all three or none. If the subprocess # user has only redirected one or two handles, we are # automatically creating PIPEs for the rest. We should close # these after the process is started. See bug #1124861. if mswindows: if stdin is None and p2cwrite is not None: os.close(p2cwrite) p2cwrite = None if stdout is None and c2pread is not None: os.close(c2pread) c2pread = None if stderr is None and errread is not None: os.close(errread) errread = None if p2cwrite: self.stdin = os.fdopen(p2cwrite, 'wb', bufsize) if c2pread: if universal_newlines: self.stdout = os.fdopen(c2pread, 'rU', bufsize) else: self.stdout = os.fdopen(c2pread, 'rb', bufsize) if errread: if universal_newlines: self.stderr = os.fdopen(errread, 'rU', bufsize) else: self.stderr = os.fdopen(errread, 'rb', bufsize) def _translate_newlines(self, data): data = data.replace("\r\n", "\n") data = data.replace("\r", "\n") return data def __del__(self): if not self._child_created: # We didn't get to successfully create a child process. return # In case the child hasn't been waited on, check if it's done. self.poll(_deadstate=sys.maxint) if self.returncode is None and _active is not None: # Child is still running, keep us alive until we can wait on it. _active.append(self) def communicate(self, input=None): """Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).""" # Optimization: If we are only using one pipe, or no pipe at # all, using select() or threads is unnecessary. if [self.stdin, self.stdout, self.stderr].count(None) >= 2: stdout = None stderr = None if self.stdin: if input: self.stdin.write(input) self.stdin.close() elif self.stdout: stdout = self.stdout.read() elif self.stderr: stderr = self.stderr.read() self.wait() return (stdout, stderr) return self._communicate(input) if mswindows: # # Windows methods # def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin is None and stdout is None and stderr is None: return (None, None, None, None, None, None) p2cread, p2cwrite = None, None c2pread, c2pwrite = None, None errread, errwrite = None, None if stdin is None: p2cread = GetStdHandle(STD_INPUT_HANDLE) if p2cread is not None: pass elif stdin is None or stdin == PIPE: p2cread, p2cwrite = CreatePipe(None, 0) # Detach and turn into fd p2cwrite = p2cwrite.Detach() p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0) elif isinstance(stdin, int): p2cread = msvcrt.get_osfhandle(stdin) else: # Assuming file-like object p2cread = msvcrt.get_osfhandle(stdin.fileno()) p2cread = self._make_inheritable(p2cread) if stdout is None: c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE) if c2pwrite is not None: pass elif stdout is None or stdout == PIPE: c2pread, c2pwrite = CreatePipe(None, 0) # Detach and turn into fd c2pread = c2pread.Detach() c2pread = msvcrt.open_osfhandle(c2pread, 0) elif isinstance(stdout, int): c2pwrite = msvcrt.get_osfhandle(stdout) else: # Assuming file-like object c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) c2pwrite = self._make_inheritable(c2pwrite) if stderr is None: errwrite = GetStdHandle(STD_ERROR_HANDLE) if errwrite is not None: pass elif stderr is None or stderr == PIPE: errread, errwrite = CreatePipe(None, 0) # Detach and turn into fd errread = errread.Detach() errread = msvcrt.open_osfhandle(errread, 0) elif stderr == STDOUT: errwrite = c2pwrite elif isinstance(stderr, int): errwrite = msvcrt.get_osfhandle(stderr) else: # Assuming file-like object errwrite = msvcrt.get_osfhandle(stderr.fileno()) errwrite = self._make_inheritable(errwrite) return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) def _make_inheritable(self, handle): """Return a duplicate of handle, which is inheritable""" return DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), 0, 1, DUPLICATE_SAME_ACCESS) def _find_w9xpopen(self): """Find and return absolut path to w9xpopen.exe""" w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), "w9xpopen.exe") if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embedding # situation - see if we can locate it in sys.exec_prefix w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), "w9xpopen.exe") if not os.path.exists(w9xpopen): raise RuntimeError("Cannot locate w9xpopen.exe, which is " "needed for Popen to work with your " "shell or platform.") return w9xpopen def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (MS Windows version)""" if not isinstance(args, types.StringTypes): args = list2cmdline(args) # Process startup details if startupinfo is None: startupinfo = STARTUPINFO() if None not in (p2cread, c2pwrite, errwrite): startupinfo.dwFlags |= STARTF_USESTDHANDLES startupinfo.hStdInput = p2cread startupinfo.hStdOutput = c2pwrite startupinfo.hStdError = errwrite if shell: startupinfo.dwFlags |= STARTF_USESHOWWINDOW startupinfo.wShowWindow = SW_HIDE comspec = os.environ.get("COMSPEC", "cmd.exe") args = comspec + " /c " + args if (GetVersion() >= 0x80000000L or os.path.basename(comspec).lower() == "command.com"): # Win9x, or using command.com on NT. We need to # use the w9xpopen intermediate program. For more # information, see KB Q150956 # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp) w9xpopen = self._find_w9xpopen() args = '"%s" %s' % (w9xpopen, args) # Not passing CREATE_NEW_CONSOLE has been known to # cause random failures on win9x. Specifically a # dialog: "Your program accessed mem currently in # use at xxx" and a hopeful warning about the # stability of your system. Cost is Ctrl+C wont # kill children. creationflags |= CREATE_NEW_CONSOLE # Start the process try: hp, ht, pid, tid = CreateProcess(executable, args, # no special security None, None, # must inherit handles to pass std # handles 1, creationflags, env, cwd, startupinfo) except pywintypes.error, e: # Translate pywintypes.error to WindowsError, which is # a subclass of OSError. FIXME: We should really # translate errno using _sys_errlist (or simliar), but # how can this be done from Python? raise WindowsError(*e.args) # Retain the process handle, but close the thread handle self._child_created = True self._handle = hp self.pid = pid ht.Close() # Child is launched. Close the parent's copy of those pipe # handles that only the child should have open. You need # to make sure that no handles to the write end of the # output pipe are maintained in this process or else the # pipe will not close when the child process exits and the # ReadFile will hang. if p2cread is not None: p2cread.Close() if c2pwrite is not None: c2pwrite.Close() if errwrite is not None: errwrite.Close() def poll(self, _deadstate=None): """Check if child process has terminated. Returns returncode attribute.""" if self.returncode is None: if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0: self.returncode = GetExitCodeProcess(self._handle) return self.returncode def wait(self): """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode is None: obj = WaitForSingleObject(self._handle, INFINITE) self.returncode = GetExitCodeProcess(self._handle) return self.returncode def _readerthread(self, fh, buffer): buffer.append(fh.read()) def _communicate(self, input): stdout = None # Return stderr = None # Return if self.stdout: stdout = [] stdout_thread = threading.Thread(target=self._readerthread, args=(self.stdout, stdout)) stdout_thread.setDaemon(True) stdout_thread.start() if self.stderr: stderr = [] stderr_thread = threading.Thread(target=self._readerthread, args=(self.stderr, stderr)) stderr_thread.setDaemon(True) stderr_thread.start() if self.stdin: if input is not None: self.stdin.write(input) self.stdin.close() if self.stdout: stdout_thread.join() if self.stderr: stderr_thread.join() # All data exchanged. Translate lists into strings. if stdout is not None: stdout = stdout[0] if stderr is not None: stderr = stderr[0] # Translate newlines, if requested. We cannot let the file # object do the translation: It is based on stdio, which is # impossible to combine with select (unless forcing no # buffering). if self.universal_newlines and hasattr(file, 'newlines'): if stdout: stdout = self._translate_newlines(stdout) if stderr: stderr = self._translate_newlines(stderr) self.wait() return (stdout, stderr) else: # # POSIX methods # def _get_handles(self, stdin, stdout, stderr): """Construct and return tupel with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ p2cread, p2cwrite = None, None c2pread, c2pwrite = None, None errread, errwrite = None, None if stdin is None: pass elif stdin == PIPE: p2cread, p2cwrite = os.pipe() elif isinstance(stdin, int): p2cread = stdin else: # Assuming file-like object p2cread = stdin.fileno() if stdout is None: pass elif stdout == PIPE: c2pread, c2pwrite = os.pipe() elif isinstance(stdout, int): c2pwrite = stdout else: # Assuming file-like object c2pwrite = stdout.fileno() if stderr is None: pass elif stderr == PIPE: errread, errwrite = os.pipe() elif stderr == STDOUT: errwrite = c2pwrite elif isinstance(stderr, int): errwrite = stderr else: # Assuming file-like object errwrite = stderr.fileno() return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) def _set_cloexec_flag(self, fd): try: cloexec_flag = fcntl.FD_CLOEXEC except AttributeError: cloexec_flag = 1 old = fcntl.fcntl(fd, fcntl.F_GETFD) fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag) def _close_fds(self, but): for i in xrange(3, MAXFD): if i == but: continue try: os.close(i) except: pass def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite): """Execute program (POSIX version)""" if isinstance(args, types.StringTypes): args = [args] else: args = list(args) if shell: args = ["/bin/sh", "-c"] + args if executable is None: executable = args[0] # For transferring possible exec failure from child to parent # The first char specifies the exception type: 0 means # OSError, 1 means some other error. errpipe_read, errpipe_write = os.pipe() self._set_cloexec_flag(errpipe_write) self.pid = os.fork() self._child_created = True if self.pid == 0: # Child try: # Close parent's pipe ends if p2cwrite: os.close(p2cwrite) if c2pread: os.close(c2pread) if errread: os.close(errread) os.close(errpipe_read) # Dup fds for child if p2cread: os.dup2(p2cread, 0) if c2pwrite: os.dup2(c2pwrite, 1) if errwrite: os.dup2(errwrite, 2) # Close pipe fds. Make sure we don't close the same # fd more than once, or standard fds. if p2cread and p2cread not in (0,): os.close(p2cread) if c2pwrite and c2pwrite not in (p2cread, 1): os.close(c2pwrite) if errwrite and errwrite not in (p2cread, c2pwrite, 2): os.close(errwrite) # Close all other fds, if asked for if close_fds: self._close_fds(but=errpipe_write) if cwd is not None: os.chdir(cwd) if preexec_fn: apply(preexec_fn) if env is None: os.execvp(executable, args) else: os.execvpe(executable, args, env) except: exc_type, exc_value, tb = sys.exc_info() # Save the traceback and attach it to the exception object exc_lines = traceback.format_exception(exc_type, exc_value, tb) exc_value.child_traceback = ''.join(exc_lines) os.write(errpipe_write, pickle.dumps(exc_value)) # This exitcode won't be reported to applications, so it # really doesn't matter what we return. os._exit(255) # Parent os.close(errpipe_write) if p2cread and p2cwrite: os.close(p2cread) if c2pwrite and c2pread: os.close(c2pwrite) if errwrite and errread: os.close(errwrite) # Wait for exec to fail or succeed; possibly raising exception data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB os.close(errpipe_read) if data != "": os.waitpid(self.pid, 0) child_exception = pickle.loads(data) raise child_exception def _handle_exitstatus(self, sts): if os.WIFSIGNALED(sts): self.returncode = -os.WTERMSIG(sts) elif os.WIFEXITED(sts): self.returncode = os.WEXITSTATUS(sts) else: # Should never happen raise RuntimeError("Unknown child exit status!") def poll(self, _deadstate=None): """Check if child process has terminated. Returns returncode attribute.""" if self.returncode is None: try: pid, sts = os.waitpid(self.pid, os.WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) except os.error: if _deadstate is not None: self.returncode = _deadstate return self.returncode def wait(self): """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode is None: pid, sts = os.waitpid(self.pid, 0) self._handle_exitstatus(sts) return self.returncode def _communicate(self, input): read_set = [] write_set = [] stdout = None # Return stderr = None # Return if self.stdin: # Flush stdio buffer. This might block, if the user has # been writing to .stdin in an uncontrolled fashion. self.stdin.flush() if input: write_set.append(self.stdin) else: self.stdin.close() if self.stdout: read_set.append(self.stdout) stdout = [] if self.stderr: read_set.append(self.stderr) stderr = [] input_offset = 0 while read_set or write_set: rlist, wlist, xlist = select.select(read_set, write_set, []) if self.stdin in wlist: # When select has indicated that the file is writable, # we can write up to PIPE_BUF bytes without risk # blocking. POSIX defines PIPE_BUF >= 512 bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512)) input_offset += bytes_written if input_offset >= len(input): self.stdin.close() write_set.remove(self.stdin) if self.stdout in rlist: data = os.read(self.stdout.fileno(), 1024) if data == "": self.stdout.close() read_set.remove(self.stdout) stdout.append(data) if self.stderr in rlist: data = os.read(self.stderr.fileno(), 1024) if data == "": self.stderr.close() read_set.remove(self.stderr) stderr.append(data) # All data exchanged. Translate lists into strings. if stdout is not None: stdout = ''.join(stdout) if stderr is not None: stderr = ''.join(stderr) # Translate newlines, if requested. We cannot let the file # object do the translation: It is based on stdio, which is # impossible to combine with select (unless forcing no # buffering). if self.universal_newlines and hasattr(file, 'newlines'): if stdout: stdout = self._translate_newlines(stdout) if stderr: stderr = self._translate_newlines(stderr) self.wait() return (stdout, stderr) def _demo_posix(): # # Example 1: Simple redirection: Get process list # plist = Popen(["ps"], stdout=PIPE).communicate()[0] print "Process list:" print plist # # Example 2: Change uid before executing child # if os.getuid() == 0: p = Popen(["id"], preexec_fn=lambda: os.setuid(100)) p.wait() # # Example 3: Connecting several subprocesses # print "Looking for 'hda'..." p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) print repr(p2.communicate()[0]) # # Example 4: Catch execution error # print print "Trying a weird file..." try: print Popen(["/this/path/does/not/exist"]).communicate() except OSError, e: if e.errno == errno.ENOENT: print "The file didn't exist. I thought so..." print "Child traceback:" print e.child_traceback else: print "Error", e.errno else: print >>sys.stderr, "Gosh. No error." def _demo_windows(): # # Example 1: Connecting several subprocesses # print "Looking for 'PROMPT' in set output..." p1 = Popen("set", stdout=PIPE, shell=True) p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE) print repr(p2.communicate()[0]) # # Example 2: Simple execution of program # print "Executing calc..." p = Popen("calc") p.wait() if __name__ == "__main__": if mswindows: _demo_windows() else: _demo_posix()
__doc__="""An experimental SVG renderer for the ReportLab graphics framework. This will create SVG code from the ReportLab Graphics API (RLG). To read existing SVG code and convert it into ReportLab graphics objects download the svglib module here: http://python.net/~gherman/#svglib """ import math, string, types, sys, os from types import StringType from operator import getitem from reportlab.pdfbase.pdfmetrics import stringWidth # for font info from reportlab.lib.utils import fp_str from reportlab.lib.colors import black from reportlab.graphics.renderbase import StateTracker, getStateDelta, Renderer, renderScaledDrawing from reportlab.graphics.shapes import STATE_DEFAULTS, Path, UserNode from reportlab.graphics.shapes import * # (only for test0) from reportlab import rl_config from reportlab.lib.utils import getStringIO from xml.dom import getDOMImplementation ### some constants ### sin = math.sin cos = math.cos pi = math.pi LINE_STYLES = 'stroke-width stroke-linecap stroke fill stroke-dasharray' TEXT_STYLES = 'font-family font-size' ### top-level user function ### def drawToString(d, showBoundary=rl_config.showBoundary): "Returns a SVG as a string in memory, without touching the disk" s = getStringIO() drawToFile(d, s, showBoundary=showBoundary) return s.getvalue() def drawToFile(d, fn, showBoundary=rl_config.showBoundary): d = renderScaledDrawing(d) c = SVGCanvas((d.width, d.height)) draw(d, c, 0, 0, showBoundary=showBoundary) c.save(fn) def draw(drawing, canvas, x=0, y=0, showBoundary=rl_config.showBoundary): """As it says.""" r = _SVGRenderer() r.draw(renderScaledDrawing(drawing), canvas, x, y, showBoundary=showBoundary) ### helper functions ### def _pointsFromList(L): """ given a list of coordinates [x0, y0, x1, y1....] produce a list of points [(x0,y0), (y1,y0),....] """ P=[] for i in range(0,len(L), 2): P.append((L[i], L[i+1])) return P def transformNode(doc, newTag, node=None, **attrDict): """Transform a DOM node into new node and copy selected attributes. Creates a new DOM node with tag name 'newTag' for document 'doc' and copies selected attributes from an existing 'node' as provided in 'attrDict'. The source 'node' can be None. Attribute values will be converted to strings. E.g. n = transformNode(doc, "node1", x="0", y="1") -> DOM node for <node1 x="0" y="1"/> n = transformNode(doc, "node1", x=0, y=1+1) -> DOM node for <node1 x="0" y="2"/> n = transformNode(doc, "node1", node0, x="x0", y="x0", zoo=bar()) -> DOM node for <node1 x="[node0.x0]" y="[node0.y0]" zoo="[bar()]"/> """ newNode = doc.createElement(newTag) for newAttr, attr in attrDict.items(): sattr = str(attr) if not node: newNode.setAttribute(newAttr, sattr) else: attrVal = node.getAttribute(sattr) newNode.setAttribute(newAttr, attrVal or sattr) return newNode ### classes ### class SVGCanvas: def __init__(self, size=(300,300)): self.verbose = 0 self.width, self.height = self.size = size # self.height = size[1] self.code = [] self.style = {} self.path = '' self._strokeColor = self._fillColor = self._lineWidth = \ self._font = self._fontSize = self._lineCap = \ self._lineJoin = self._color = None implementation = getDOMImplementation('minidom') self.doc = implementation.createDocument(None, "svg", None) self.svg = self.doc.documentElement self.svg.setAttribute("width", str(size[0])) self.svg.setAttribute("height", str(self.height)) #these suggested by Tim Roberts self.svg.setAttribute("xmlns", "http://www.w3.org/2000/svg") self.svg.setAttribute("xmlns:link", "http://www.w3.org/1999/xlink") self.svg.setAttribute("version", "1.0") self.svg.setAttribute("baseProfile", "full") title = self.doc.createElement('title') text = self.doc.createTextNode('...') title.appendChild(text) self.svg.appendChild(title) desc = self.doc.createElement('desc') text = self.doc.createTextNode('...') desc.appendChild(text) self.svg.appendChild(desc) self.setFont(STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize']) self.setStrokeColor(STATE_DEFAULTS['strokeColor']) self.setLineCap(2) self.setLineJoin(0) self.setLineWidth(1) # Add a rectangular clipping path identical to view area. clipPath = transformNode(self.doc, "clipPath", id="clip") clipRect = transformNode(self.doc, "rect", x=0, y=0, width=self.width, height=self.height) clipPath.appendChild(clipRect) self.svg.appendChild(clipPath) self.groupTree = transformNode(self.doc, "g", id="group", transform="scale(1,-1) translate(0,-%d)" % self.height, style="clip-path: url(#clip)") self.svg.appendChild(self.groupTree) self.currGroup = self.groupTree def save(self, f=None): if type(f) is StringType: file = open(f, 'w') else: file = f file.write("""\ <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20000303 Stylable//EN" "http://www.w3.org/TR/2000/03/WD-SVG-20000303/DTD/svg-20000303-stylable.dtd" >\n""") # use = self.doc.createElement('use') # use.setAttribute("xlink:href", "#group") # use.setAttribute("transform", "scale(1, -1)") # self.svg.appendChild(use) result = self.svg.toprettyxml(indent=" ") file.write(result) if file is not f: file.close() ### helpers ### def NOTUSED_stringWidth(self, s, font=None, fontSize=None): """Return the logical width of the string if it were drawn in the current font (defaults to self.font). """ font = font or self._font fontSize = fontSize or self._fontSize return stringWidth(s, font, fontSize) def _formatStyle(self, include=''): str = '' include = string.split(include) keys = self.style.keys() if include: #2.1-safe version of the line below follows: #keys = filter(lambda k: k in include, keys) tmp = [] for word in keys: if word in include: tmp.append(word) keys = tmp items = [] for k in keys: items.append((k, self.style[k])) items = map(lambda i: "%s: %s"%(i[0], i[1]), items) str = string.join(items, '; ') + ';' return str def _escape(self, s): """ return a copy of string s with special characters in postscript strings escaped with backslashes. Have not handled characters that are converted normally in python strings i.e. \\n -> newline """ str = string.replace(s, chr(0x5C), r'\\' ) str = string.replace(str, '(', '\(' ) str = string.replace(str, ')', '\)') return str def _genArcCode(self, x1, y1, x2, y2, startAng, extent): """Calculate the path for an arc inscribed in rectangle defined by (x1,y1),(x2,y2).""" return #calculate semi-minor and semi-major axes of ellipse xScale = abs((x2-x1)/2.0) yScale = abs((y2-y1)/2.0) #calculate centre of ellipse x, y = (x1+x2)/2.0, (y1+y2)/2.0 codeline = 'matrix currentmatrix %s %s translate %s %s scale 0 0 1 %s %s %s setmatrix' if extent >= 0: arc='arc' else: arc='arcn' data = (x,y, xScale, yScale, startAng, startAng+extent, arc) return codeline % data def _fillAndStroke(self, code, clip=0): path = transformNode(self.doc, "path", d=self.path, style=self._formatStyle(LINE_STYLES)) self.currGroup.appendChild(path) self.path = '' return """ if self._fillColor or self._strokeColor or clip: self.code.extend(code) if self._fillColor: if self._strokeColor or clip: self.code.append("gsave") self.setColor(self._fillColor) self.code.append("eofill") if self._strokeColor or clip: self.code.append("grestore") if self._strokeColor != None: if clip: self.code.append("gsave") self.setColor(self._strokeColor) self.code.append("stroke") if clip: self.code.append("grestore") if clip: self.code.append("clip") self.code.append("newpath") """ ### styles ### def setLineCap(self, v): vals = {0:'butt', 1:'round', 2:'square'} if self._lineCap != v: self._lineCap = v self.style['stroke-linecap'] = vals[v] def setLineJoin(self, v): vals = {0:'miter', 1:'round', 2:'bevel'} if self._lineJoin != v: self._lineJoin = v self.style['stroke-linecap'] = vals[v] def setDash(self, array=[], phase=0): """Two notations. Pass two numbers, or an array and phase.""" join = string.join if type(array) in (types.IntType, types.FloatType): self.style['stroke-dasharray'] = join(map(str, ([array, phase])), ', ') elif type(array) in (types.ListType, types.TupleType) and len(array) > 0: assert phase >= 0, "phase is a length in user space" self.style['stroke-dasharray'] = join(map(str, (array+[phase])), ', ') def setStrokeColor(self, color): self._strokeColor = color self.setColor(color) if color == None: self.style['stroke'] = 'none' else: r, g, b = color.red, color.green, color.blue self.style['stroke'] = 'rgb(%d%%,%d%%,%d%%)' % (r*100, g*100, b*100) def setColor(self, color): if self._color != color: self._color = color def setFillColor(self, color): self._fillColor = color self.setColor(color) if color == None: self.style['fill'] = 'none' else: r, g, b = color.red, color.green, color.blue self.style['fill'] = 'rgb(%d%%,%d%%,%d%%)' % (r*100, g*100, b*100) def setLineWidth(self, width): if width != self._lineWidth: self._lineWidth = width self.style['stroke-width'] = width def setFont(self, font, fontSize): if self._font != font or self._fontSize != fontSize: self._font, self._fontSize = (font, fontSize) self.style['font-family'] = font self.style['font-size'] = fontSize ### shapes ### def rect(self, x1,y1, x2,y2, rx=8, ry=8): "Draw a rectangle between x1,y1 and x2,y2." if self.verbose: print "+++ SVGCanvas.rect" rect = transformNode(self.doc, "rect", x=x1, y=y1, width=x2-x1, height=y2-y1, style=self._formatStyle(LINE_STYLES)) self.currGroup.appendChild(rect) def roundRect(self, x1,y1, x2,y2, rx=8, ry=8): """Draw a rounded rectangle between x1,y1 and x2,y2. Corners inset as ellipses with x-radius rx and y-radius ry. These should have x1<x2, y1<y2, rx>0, and ry>0. """ rect = transformNode(self.doc, "rect", x=x1, y=y1, width=x2-x1, height=y2-y1, rx=rx, ry=ry, style=self._formatStyle(LINE_STYLES)) self.currGroup.appendChild(rect) def drawString(self, s, x, y, angle=0): if self.verbose: print "+++ SVGCanvas.drawString" if self._fillColor != None: self.setColor(self._fillColor) s = self._escape(s) st = self._formatStyle(TEXT_STYLES) if angle != 0: st = st + " rotate(%f %f %f);" % (angle, x, y) st = st + " fill: %s;" % self.style['fill'] text = transformNode(self.doc, "text", x=x, y=y, style=st, transform="translate(0,%d) scale(1,-1)" % (2*y)) content = self.doc.createTextNode(s) text.appendChild(content) self.currGroup.appendChild(text) def drawCentredString(self, s, x, y, angle=0,text_anchor='middle'): if self.verbose: print "+++ SVGCanvas.drawCentredString" if self._fillColor != None: if not text_anchor in ['start', 'inherited']: textLen = stringWidth(s,self._font,self._fontSize) if text_anchor=='end': x -= textLen elif text_anchor=='middle': x -= textLen/2. else: raise ValueError, 'bad value for text_anchor ' + str(text_anchor) self.drawString(x,y,text,angle=angle) def drawRightString(self, text, x, y, angle=0): self.drawCentredString(text,x,y,angle=angle,text_anchor='end') def comment(self, data): "Add a comment." comment = self.doc.createComment(data) # self.currGroup.appendChild(comment) def drawImage(self, image, x1, y1, x2=None, y2=None): pass def line(self, x1, y1, x2, y2): if self._strokeColor != None: if 0: # something is wrong with line in my SVG viewer... line = transformNode(self.doc, "line", x=x1, y=y1, x2=x2, y2=y2, style=self._formatStyle(LINE_STYLES)) self.currGroup.appendChild(line) path = transformNode(self.doc, "path", d="M %f,%f L %f,%f Z" % (x1,y1,x2,y2), style=self._formatStyle(LINE_STYLES)) self.currGroup.appendChild(path) def ellipse(self, x1, y1, x2, y2): """Draw an orthogonal ellipse inscribed within the rectangle x1,y1,x2,y2. These should have x1<x2 and y1<y2. """ ellipse = transformNode(self.doc, "ellipse", cx=(x1+x2)/2.0, cy=(y1+y2)/2.0, rx=(x2-x1)/2.0, ry=(y2-y1)/2.0, style=self._formatStyle(LINE_STYLES)) self.currGroup.appendChild(ellipse) def circle(self, xc, yc, r): circle = transformNode(self.doc, "circle", cx=xc, cy=yc, r=r, style=self._formatStyle(LINE_STYLES)) self.currGroup.appendChild(circle) def drawCurve(self, x1, y1, x2, y2, x3, y3, x4, y4, closed=0): pass return codeline = '%s m %s curveto' data = (fp_str(x1, y1), fp_str(x2, y2, x3, y3, x4, y4)) if self._fillColor != None: self.setColor(self._fillColor) self.code.append((codeline % data) + ' eofill') if self._strokeColor != None: self.setColor(self._strokeColor) self.code.append((codeline % data) + ((closed and ' closepath') or '') + ' stroke') def drawArc(self, x1,y1, x2,y2, startAng=0, extent=360, fromcenter=0): """Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2. Starting at startAng degrees and covering extent degrees. Angles start with 0 to the right (+x) and increase counter-clockwise. These should have x1<x2 and y1<y2. """ cx, cy = (x1+x2)/2.0, (y1+y2)/2.0 rx, ry = (x2-x1)/2.0, (y2-y1)/2.0 mx = rx * cos(startAng*pi/180) + cx my = ry * sin(startAng*pi/180) + cy ax = rx * cos((startAng+extent)*pi/180) + cx ay = ry * sin((startAng+extent)*pi/180) + cy str = '' if fromcenter: str = str + "M %f, %f L %f, %f " % (cx, cy, ax, ay) if fromcenter: str = str + "A %f, %f %d %d %d %f, %f " % \ (rx, ry, 0, extent>=180, 0, mx, my) else: str = str + "M %f, %f A %f, %f %d %d %d %f, %f Z " % \ (mx, my, rx, ry, 0, extent>=180, 0, mx, my) if fromcenter: str = str + "L %f, %f Z " % (cx, cy) path = transformNode(self.doc, "path", d=str, style=self._formatStyle()) self.currGroup.appendChild(path) def polygon(self, points, closed=0): assert len(points) >= 2, 'Polygon must have 2 or more points' if self._strokeColor != None: self.setColor(self._strokeColor) pairs = [] for i in xrange(len(points)): pairs.append("%f %f" % (points[i])) pts = string.join(pairs, ', ') polyline = transformNode(self.doc, "polygon", points=pts, style=self._formatStyle(LINE_STYLES)) self.currGroup.appendChild(polyline) # self._fillAndStroke(polyCode) def lines(self, lineList, color=None, width=None): # print "### lineList", lineList return if self._strokeColor != None: self._setColor(self._strokeColor) codeline = '%s m %s l stroke' for line in lineList: self.code.append(codeline % (fp_str(line[0]), fp_str(line[1]))) def polyLine(self, points): assert len(points) >= 1, 'Polyline must have 1 or more points' if self._strokeColor != None: self.setColor(self._strokeColor) pairs = [] for i in xrange(len(points)): pairs.append("%f %f" % (points[i])) pts = string.join(pairs, ', ') polyline = transformNode(self.doc, "polyline", points=pts, style=self._formatStyle(LINE_STYLES)) self.currGroup.appendChild(polyline) ### groups ### def startGroup(self): if self.verbose: print "+++ begin SVGCanvas.startGroup" currGroup, group = self.currGroup, transformNode(self.doc, "g", transform="") currGroup.appendChild(group) self.currGroup = group if self.verbose: print "+++ end SVGCanvas.startGroup" return currGroup def endGroup(self,currGroup): if self.verbose: print "+++ begin SVGCanvas.endGroup" self.currGroup = currGroup if self.verbose: print "+++ end SVGCanvas.endGroup" def transform(self, a, b, c, d, e, f): if self.verbose: print "!!! begin SVGCanvas.transform", a, b, c, d, e, f tr = self.currGroup.getAttribute("transform") t = 'matrix(%f, %f, %f, %f, %f, %f)' % (a,b,c,d,e,f) if (a, b, c, d, e, f) != (1, 0, 0, 1, 0, 0): self.currGroup.setAttribute("transform", "%s %s" % (tr, t)) def translate(self, x, y): # probably never used print "!!! begin SVGCanvas.translate" return tr = self.currGroup.getAttribute("transform") t = 'translate(%f, %f)' % (x, y) self.currGroup.setAttribute("transform", "%s %s" % (tr, t)) def scale(self, x, y): # probably never used print "!!! begin SVGCanvas.scale" return tr = self.groups[-1].getAttribute("transform") t = 'scale(%f, %f)' % (x, y) self.currGroup.setAttribute("transform", "%s %s" % (tr, t)) ### paths ### def moveTo(self, x, y): self.path = self.path + 'M %f %f ' % (x, y) def lineTo(self, x, y): self.path = self.path + 'L %f %f ' % (x, y) def curveTo(self, x1, y1, x2, y2, x3, y3): self.path = self.path + 'C %f %f %f %f %f %f ' % (x1, y1, x2, y2, x3, y3) def closePath(self): self.path = self.path + 'Z ' def saveState(self): pass def restoreState(self): pass class _SVGRenderer(Renderer): """This draws onto an SVG document. """ def __init__(self): self._tracker = StateTracker() self.verbose = 0 def drawNode(self, node): """This is the recursive method called for each node in the tree. """ if self.verbose: print "### begin _SVGRenderer.drawNode" self._canvas.comment('begin node %s'%`node`) color = self._canvas._color if not (isinstance(node, Path) and node.isClipPath): pass # self._canvas.saveState() #apply state changes deltas = getStateDelta(node) self._tracker.push(deltas) self.applyStateChanges(deltas, {}) #draw the object, or recurse self.drawNodeDispatcher(node) rDeltas = self._tracker.pop() if not (isinstance(node, Path) and node.isClipPath): pass # self._canvas.restoreState() self._canvas.comment('end node %s'%`node`) self._canvas._color = color #restore things we might have lost (without actually doing anything). for k, v in rDeltas.items(): if self._restores.has_key(k): setattr(self._canvas,self._restores[k],v) if self.verbose: print "### end _SVGRenderer.drawNode" _restores = {'strokeColor':'_strokeColor','strokeWidth': '_lineWidth','strokeLineCap':'_lineCap', 'strokeLineJoin':'_lineJoin','fillColor':'_fillColor','fontName':'_font', 'fontSize':'_fontSize'} def drawGroup(self, group): if self.verbose: print "### begin _SVGRenderer.drawGroup" currGroup = self._canvas.startGroup() a, b, c, d, e, f = self._tracker.getState()['transform'] for childNode in group.getContents(): if isinstance(childNode, UserNode): node2 = childNode.provideNode() else: node2 = childNode self.drawNode(node2) self._canvas.transform(a, b, c, d, e, f) self._canvas.endGroup(currGroup) if self.verbose: print "### end _SVGRenderer.drawGroup" def drawRect(self, rect): if rect.rx == rect.ry == 0: #plain old rectangle self._canvas.rect( rect.x, rect.y, rect.x+rect.width, rect.y+rect.height) else: #cheat and assume ry = rx; better to generalize #pdfgen roundRect function. TODO self._canvas.roundRect( rect.x, rect.y, rect.x+rect.width, rect.y+rect.height, rect.rx, rect.ry ) def drawString(self, stringObj): if self._canvas._fillColor: S = self._tracker.getState() text_anchor, x, y, text = S['textAnchor'], stringObj.x, stringObj.y, stringObj.text if not text_anchor in ['start', 'inherited']: font, fontSize = S['fontName'], S['fontSize'] textLen = stringWidth(text, font,fontSize) if text_anchor=='end': x = x-textLen elif text_anchor=='middle': x = x - textLen/2 else: raise ValueError, 'bad value for text_anchor ' + str(text_anchor) self._canvas.drawString(text,x,y) def drawLine(self, line): if self._canvas._strokeColor: self._canvas.line(line.x1, line.y1, line.x2, line.y2) def drawCircle(self, circle): self._canvas.circle( circle.cx, circle.cy, circle.r) def drawWedge(self, wedge): centerx, centery, radius, startangledegrees, endangledegrees = \ wedge.centerx, wedge.centery, wedge.radius, wedge.startangledegrees, wedge.endangledegrees yradius = wedge.yradius or wedge.radius (x1, y1) = (centerx-radius, centery-yradius) (x2, y2) = (centerx+radius, centery+yradius) extent = endangledegrees - startangledegrees self._canvas.drawArc(x1, y1, x2, y2, startangledegrees, extent, fromcenter=1) def drawPolyLine(self, p): if self._canvas._strokeColor: self._canvas.polyLine(_pointsFromList(p.points)) def drawEllipse(self, ellipse): #need to convert to pdfgen's bounding box representation x1 = ellipse.cx - ellipse.rx x2 = ellipse.cx + ellipse.rx y1 = ellipse.cy - ellipse.ry y2 = ellipse.cy + ellipse.ry self._canvas.ellipse(x1,y1,x2,y2) def drawPolygon(self, p): self._canvas.polygon(_pointsFromList(p.points), closed=1) def drawPath(self, path): # print "### drawPath", path.points from reportlab.graphics.shapes import _renderPath c = self._canvas drawFuncs = (c.moveTo, c.lineTo, c.curveTo, c.closePath) isClosed = _renderPath(path, drawFuncs) if not isClosed: c._fillColor = None c._fillAndStroke([], clip=path.isClipPath) def applyStateChanges(self, delta, newState): """This takes a set of states, and outputs the operators needed to set those properties""" for key, value in delta.items(): if key == 'transform': pass #self._canvas.transform(value[0], value[1], value[2], value[3], value[4], value[5]) elif key == 'strokeColor': self._canvas.setStrokeColor(value) elif key == 'strokeWidth': self._canvas.setLineWidth(value) elif key == 'strokeLineCap': #0,1,2 self._canvas.setLineCap(value) elif key == 'strokeLineJoin': self._canvas.setLineJoin(value) elif key == 'strokeDashArray': if value: self._canvas.setDash(value) else: self._canvas.setDash() elif key == 'fillColor': self._canvas.setFillColor(value) elif key in ['fontSize', 'fontName']: fontname = delta.get('fontName', self._canvas._font) fontsize = delta.get('fontSize', self._canvas._fontSize) self._canvas.setFont(fontname, fontsize) def test0(outdir='svgout'): # print all drawings and their doc strings from the test # file if not os.path.isdir(outdir): os.mkdir(outdir) #grab all drawings from the test module from reportlab.graphics import testshapes drawings = [] for funcname in dir(testshapes): #if funcname[0:11] == 'getDrawing2': # print 'hacked to only show drawing 2' if funcname[0:10] == 'getDrawing': drawing = eval('testshapes.' + funcname + '()') docstring = eval('testshapes.' + funcname + '.__doc__') drawings.append((drawing, docstring)) # return i = 0 for (d, docstring) in drawings: filename = outdir + os.sep + 'renderSVG_%d.svg' % i drawToFile(d, filename) # print 'saved', filename i = i + 1 def test1(): from reportlab.graphics.testshapes import getDrawing01 d = getDrawing01() drawToFile(d, "svgout/test.svg") def test2(): from reportlab.lib.corp import RL_CorpLogo from reportlab.graphics.shapes import Drawing rl = RL_CorpLogo() d = Drawing(rl.width,rl.height) d.add(rl) drawToFile(d, "svgout/corplogo.svg") if __name__=='__main__': test0() test1() test2()
# 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 # # https://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. """Build and test configuration file. Assumes ``nox >= 2018.9.14`` is installed. """ import os import pathlib import shutil import nox LOCAL_DEPS = ("google-api-core", "google-cloud-core") NOX_DIR = os.path.abspath(os.path.dirname(__file__)) DEFAULT_INTERPRETER = "3.8" ALL_INTERPRETERS = ("2.7", "3.6", "3.7", "3.8", "3.9", "3.10") PY3_INTERPRETERS = ("3.6", "3.7", "3.8", "3.9", "3.10") MAJOR_INTERPRETERS = ("2.7", "3.8") CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() BLACK_VERSION = "black==20.8b1" def get_path(*names): return os.path.join(NOX_DIR, *names) @nox.session(py=ALL_INTERPRETERS) def unit(session): constraints_path = str( CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" ) # Install all dependencies. session.install("pytest", "pytest-cov") session.install("mock") session.install("google-cloud-testutils", "-c", constraints_path) session.install("-e", ".", "-c", constraints_path) # This variable is used to skip coverage by Python version session.env["PY_VERSION"] = session.python[0] # Run py.test against the unit tests. run_args = ["pytest"] if session.posargs: run_args.extend(session.posargs) else: run_args.extend( [ "--cov=google.cloud.ndb", "--cov=unit", "--cov-append", "--cov-config", get_path(".coveragerc"), "--cov-report=term-missing", ] ) run_args.append(get_path("tests", "unit")) session.run(*run_args) # Do not run cover session for Python 2, or it will fail if not session.posargs and session.python[0] != "2": session.notify("cover") @nox.session(py=DEFAULT_INTERPRETER) def cover(session): # Install all dependencies. session.install("coverage") # Run coverage report. session.run("coverage", "report", "--fail-under=100", "--show-missing") # Erase cached coverage data. session.run("coverage", "erase") def run_black(session, use_check=False): args = ["black"] if use_check: args.append("--check") args.extend( [ get_path("docs"), get_path("noxfile.py"), get_path("google"), get_path("tests"), ] ) session.run(*args) @nox.session(py=DEFAULT_INTERPRETER) def lint(session): """Run linters. Returns a failure if the linters find linting errors or sufficiently serious code quality issues. """ session.install("flake8", BLACK_VERSION) run_black(session, use_check=True) session.run("flake8", "google", "tests") @nox.session(py=DEFAULT_INTERPRETER) def blacken(session): # Install all dependencies. session.install(BLACK_VERSION) # Run ``black``. run_black(session) @nox.session(py=DEFAULT_INTERPRETER) def docs(session): """Build the docs for this library.""" session.install("-e", ".") session.install( "Sphinx==4.0.1", "alabaster", "recommonmark", "sphinxcontrib.spelling" ) shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) session.run( "sphinx-build", "-W", # warnings as errors "-T", # show full traceback on exception "-N", # no colors "-b", "html", "-d", os.path.join("docs", "_build", "doctrees", ""), os.path.join("docs", ""), os.path.join("docs", "_build", "html", ""), ) @nox.session(py=DEFAULT_INTERPRETER) def doctest(session): # Install all dependencies. session.install("Sphinx==4.0.1") session.install("sphinxcontrib.spelling") session.install(".") # Run the script for building docs and running doctests. run_args = [ "sphinx-build", "-W", "-b", "doctest", "-d", get_path("docs", "_build", "doctrees"), get_path("docs"), get_path("docs", "_build", "doctest"), ] session.run(*run_args) @nox.session(py=MAJOR_INTERPRETERS) def system(session): """Run the system test suite.""" constraints_path = str( CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" ) system_test_path = get_path("tests", "system.py") system_test_folder_path = os.path.join("tests", "system") # Sanity check: Only run tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable") system_test_exists = os.path.exists(system_test_path) system_test_folder_exists = os.path.exists(system_test_folder_path) # Sanity check: only run tests if found. if not system_test_exists and not system_test_folder_exists: session.skip("System tests were not found") # Use pre-release gRPC for system tests. session.install("--pre", "grpcio") # Install all test dependencies, then install this package into the # virtualenv's dist-packages. session.install("pytest") session.install("mock") session.install("google-cloud-testutils") for local_dep in LOCAL_DEPS: session.install(local_dep) session.install("-e", ".", "-c", constraints_path) # Run py.test against the system tests. if system_test_exists: session.run("py.test", "--quiet", system_test_path, *session.posargs) if system_test_folder_exists: session.run("py.test", "--quiet", system_test_folder_path, *session.posargs)
#!/usr/bin/python # # Copyright (C) 2007 SIOS Technology, 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. """Contains objects used with Google Apps.""" __author__ = '[email protected] (Takashi MATSUO)' import atom import gdata # XML namespaces which are often used in Google Apps entity. APPS_NAMESPACE = 'http://schemas.google.com/apps/2006' APPS_TEMPLATE = '{http://schemas.google.com/apps/2006}%s' class EmailList(atom.AtomBase): """The Google Apps EmailList element""" _tag = 'emailList' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailListFromString(xml_string): return atom.CreateClassFromXMLString(EmailList, xml_string) class Who(atom.AtomBase): """The Google Apps Who element""" _tag = 'who' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['email'] = 'email' def __init__(self, rel=None, email=None, extension_elements=None, extension_attributes=None, text=None): self.rel = rel self.email = email self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def WhoFromString(xml_string): return atom.CreateClassFromXMLString(Who, xml_string) class Login(atom.AtomBase): """The Google Apps Login element""" _tag = 'login' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['userName'] = 'user_name' _attributes['password'] = 'password' _attributes['suspended'] = 'suspended' _attributes['admin'] = 'admin' _attributes['changePasswordAtNextLogin'] = 'change_password' _attributes['agreedToTerms'] = 'agreed_to_terms' _attributes['ipWhitelisted'] = 'ip_whitelisted' _attributes['hashFunctionName'] = 'hash_function_name' def __init__(self, user_name=None, password=None, suspended=None, ip_whitelisted=None, hash_function_name=None, admin=None, change_password=None, agreed_to_terms=None, extension_elements=None, extension_attributes=None, text=None): self.user_name = user_name self.password = password self.suspended = suspended self.admin = admin self.change_password = change_password self.agreed_to_terms = agreed_to_terms self.ip_whitelisted = ip_whitelisted self.hash_function_name = hash_function_name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def LoginFromString(xml_string): return atom.CreateClassFromXMLString(Login, xml_string) class Quota(atom.AtomBase): """The Google Apps Quota element""" _tag = 'quota' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['limit'] = 'limit' def __init__(self, limit=None, extension_elements=None, extension_attributes=None, text=None): self.limit = limit self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def QuotaFromString(xml_string): return atom.CreateClassFromXMLString(Quota, xml_string) class Name(atom.AtomBase): """The Google Apps Name element""" _tag = 'name' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['familyName'] = 'family_name' _attributes['givenName'] = 'given_name' def __init__(self, family_name=None, given_name=None, extension_elements=None, extension_attributes=None, text=None): self.family_name = family_name self.given_name = given_name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NameFromString(xml_string): return atom.CreateClassFromXMLString(Name, xml_string) class Nickname(atom.AtomBase): """The Google Apps Nickname element""" _tag = 'nickname' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NicknameFromString(xml_string): return atom.CreateClassFromXMLString(Nickname, xml_string) class NicknameEntry(gdata.GDataEntry): """A Google Apps flavor of an Atom Entry for Nickname""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}login' % APPS_NAMESPACE] = ('login', Login) _children['{%s}nickname' % APPS_NAMESPACE] = ('nickname', Nickname) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, login=None, nickname=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.login = login self.nickname = nickname self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NicknameEntryFromString(xml_string): return atom.CreateClassFromXMLString(NicknameEntry, xml_string) class NicknameFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps Nickname feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [NicknameEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def NicknameFeedFromString(xml_string): return atom.CreateClassFromXMLString(NicknameFeed, xml_string) class UserEntry(gdata.GDataEntry): """A Google Apps flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}login' % APPS_NAMESPACE] = ('login', Login) _children['{%s}name' % APPS_NAMESPACE] = ('name', Name) _children['{%s}quota' % APPS_NAMESPACE] = ('quota', Quota) # This child may already be defined in GDataEntry, confirm before removing. _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', [gdata.FeedLink]) _children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, login=None, name=None, quota=None, who=None, feed_link=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.login = login self.name = name self.quota = quota self.who = who self.feed_link = feed_link or [] self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def UserEntryFromString(xml_string): return atom.CreateClassFromXMLString(UserEntry, xml_string) class UserFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps User feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [UserEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def UserFeedFromString(xml_string): return atom.CreateClassFromXMLString(UserFeed, xml_string) class EmailListEntry(gdata.GDataEntry): """A Google Apps EmailList flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}emailList' % APPS_NAMESPACE] = ('email_list', EmailList) # Might be able to remove this _children entry. _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', [gdata.FeedLink]) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, email_list=None, feed_link=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.email_list = email_list self.feed_link = feed_link or [] self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailListEntryFromString(xml_string): return atom.CreateClassFromXMLString(EmailListEntry, xml_string) class EmailListFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps EmailList feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [EmailListEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def EmailListFeedFromString(xml_string): return atom.CreateClassFromXMLString(EmailListFeed, xml_string) class EmailListRecipientEntry(gdata.GDataEntry): """A Google Apps EmailListRecipient flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, who=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.who = who self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailListRecipientEntryFromString(xml_string): return atom.CreateClassFromXMLString(EmailListRecipientEntry, xml_string) class EmailListRecipientFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps EmailListRecipient feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [EmailListRecipientEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def EmailListRecipientFeedFromString(xml_string): return atom.CreateClassFromXMLString(EmailListRecipientFeed, xml_string) class Property(atom.AtomBase): """The Google Apps Property element""" _tag = 'property' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' _attributes['value'] = 'value' def __init__(self, name=None, value=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def PropertyFromString(xml_string): return atom.CreateClassFromXMLString(Property, xml_string) class PropertyEntry(gdata.GDataEntry): """A Google Apps Property flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}property' % APPS_NAMESPACE] = ('property', [Property]) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, property=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.property = property self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def PropertyEntryFromString(xml_string): return atom.CreateClassFromXMLString(PropertyEntry, xml_string)
# Copyright (C) 2001 Python Software Foundation # Author: [email protected] (Barry Warsaw) """Classes to generate plain text from a message object tree. """ import time import re import random from types import ListType, StringType from cStringIO import StringIO # Intrapackage imports import Message import Errors EMPTYSTRING = '' SEMISPACE = '; ' BAR = '|' UNDERSCORE = '_' NL = '\n' NLTAB = '\n\t' SEMINLTAB = ';\n\t' SPACE8 = ' ' * 8 fcre = re.compile(r'^From ', re.MULTILINE) class Generator: """Generates output from a Message object tree. This basic generator writes the message to the given file object as plain text. """ # # Public interface # def __init__(self, outfp, mangle_from_=1, maxheaderlen=78): """Create the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when true, escapes From_ lines in the body of the message by putting a `>' in front of them. Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer (in characters, with tabs expanded to 8 spaces), than maxheaderlen, the header will be broken on semicolons and continued as per RFC 2822. If no semicolon is found, then the header is left alone. Set to zero to disable wrapping headers. Default is 78, as recommended (but not required by RFC 2822. """ self._fp = outfp self._mangle_from_ = mangle_from_ self.__first = 1 self.__maxheaderlen = maxheaderlen def write(self, s): # Just delegate to the file object self._fp.write(s) def __call__(self, msg, unixfrom=0): """Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is 0 to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. """ if unixfrom: ufrom = msg.get_unixfrom() if not ufrom: ufrom = 'From nobody ' + time.ctime(time.time()) print >> self._fp, ufrom self._write(msg) # # Protected interface - undocumented ;/ # def _write(self, msg): # We can't write the headers yet because of the following scenario: # say a multipart message includes the boundary string somewhere in # its body. We'd have to calculate the new boundary /before/ we write # the headers so that we can write the correct Content-Type: # parameter. # # The way we do this, so as to make the _handle_*() methods simpler, # is to cache any subpart writes into a StringIO. The we write the # headers and the StringIO contents. That way, subpart handlers can # Do The Right Thing, and can still modify the Content-Type: header if # necessary. oldfp = self._fp try: self._fp = sfp = StringIO() self._dispatch(msg) finally: self._fp = oldfp # Write the headers. First we see if the message object wants to # handle that itself. If not, we'll do it generically. meth = getattr(msg, '_write_headers', None) if meth is None: self._write_headers(msg) else: meth(self) self._fp.write(sfp.getvalue()) def _dispatch(self, msg): # Get the Content-Type: for the message, then try to dispatch to # self._handle_maintype_subtype(). If there's no handler for the full # MIME type, then dispatch to self._handle_maintype(). If that's # missing too, then dispatch to self._writeBody(). ctype = msg.get_type() if ctype is None: # No Content-Type: header so try the default handler self._writeBody(msg) else: # We do have a Content-Type: header. specific = UNDERSCORE.join(ctype.split('/')).replace('-', '_') meth = getattr(self, '_handle_' + specific, None) if meth is None: generic = msg.get_main_type().replace('-', '_') meth = getattr(self, '_handle_' + generic, None) if meth is None: meth = self._writeBody meth(msg) # # Default handlers # def _write_headers(self, msg): for h, v in msg.items(): # We only write the MIME-Version: header for the outermost # container message. Unfortunately, we can't use same technique # as for the Unix-From above because we don't know when # MIME-Version: will occur. if h.lower() == 'mime-version' and not self.__first: continue # RFC 2822 says that lines SHOULD be no more than maxheaderlen # characters wide, so we're well within our rights to split long # headers. text = '%s: %s' % (h, v) if self.__maxheaderlen > 0 and len(text) > self.__maxheaderlen: text = self._split_header(text) print >> self._fp, text # A blank line always separates headers from body print >> self._fp def _split_header(self, text): maxheaderlen = self.__maxheaderlen # Find out whether any lines in the header are really longer than # maxheaderlen characters wide. There could be continuation lines # that actually shorten it. Also, replace hard tabs with 8 spaces. lines = [s.replace('\t', SPACE8) for s in text.split('\n')] for line in lines: if len(line) > maxheaderlen: break else: # No line was actually longer than maxheaderlen characters, so # just return the original unchanged. return text rtn = [] for line in text.split('\n'): # Short lines can remain unchanged if len(line.replace('\t', SPACE8)) <= maxheaderlen: rtn.append(line) SEMINLTAB.join(rtn) else: oldlen = len(text) # Try to break the line on semicolons, but if that doesn't # work, try to split on folding whitespace. while len(text) > maxheaderlen: i = text.rfind(';', 0, maxheaderlen) if i < 0: break rtn.append(text[:i]) text = text[i+1:].lstrip() if len(text) <> oldlen: # Splitting on semis worked rtn.append(text) return SEMINLTAB.join(rtn) # Splitting on semis didn't help, so try to split on # whitespace. parts = re.split(r'(\s+)', text) # Watch out though for "Header: longnonsplittableline" if parts[0].endswith(':') and len(parts) == 3: return text first = parts.pop(0) sublines = [first] acc = len(first) while parts: len0 = len(parts[0]) len1 = len(parts[1]) if acc + len0 + len1 < maxheaderlen: sublines.append(parts.pop(0)) sublines.append(parts.pop(0)) acc += len0 + len1 else: # Split it here, but don't forget to ignore the # next whitespace-only part rtn.append(EMPTYSTRING.join(sublines)) del parts[0] first = parts.pop(0) sublines = [first] acc = len(first) rtn.append(EMPTYSTRING.join(sublines)) return NLTAB.join(rtn) # # Handlers for writing types and subtypes # def _handle_text(self, msg): payload = msg.get_payload() if payload is None: return if not isinstance(payload, StringType): raise TypeError, 'string payload expected: %s' % type(payload) if self._mangle_from_: payload = fcre.sub('>From ', payload) self._fp.write(payload) # Default body handler _writeBody = _handle_text def _handle_multipart(self, msg, isdigest=0): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] for part in msg.get_payload(): s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g(part, unixfrom=0) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary if isdigest: print >> self._fp # Join and write the individual parts joiner = '\n--' + boundary + '\n' if isdigest: # multipart/digest types effectively add an extra newline between # the boundary and the body part. joiner += '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue) def _handle_multipart_digest(self, msg): self._handle_multipart(msg, isdigest=1) def _handle_message_delivery_status(self, msg): # We can't just write the headers directly to self's file object # because this will leave an extra newline between the last header # block and the boundary. Sigh. blocks = [] for part in msg.get_payload(): s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) g(part, unixfrom=0) text = s.getvalue() lines = text.split('\n') # Strip off the unnecessary trailing empty line if lines and lines[-1] == '': blocks.append(NL.join(lines[:-1])) else: blocks.append(text) # Now join all the blocks with an empty line. This has the lovely # effect of separating each block with an empty line, but not adding # an extra one after the last one. self._fp.write(NL.join(blocks)) def _handle_message(self, msg): s = StringIO() g = self.__class__(s, self._mangle_from_, self.__maxheaderlen) # A message/rfc822 should contain a scalar payload which is another # Message object. Extract that object, stringify it, and write that # out. g(msg.get_payload(), unixfrom=0) self._fp.write(s.getvalue()) class DecodedGenerator(Generator): """Generator a text representation of a message. Like the Generator base class, except that non-text parts are substituted with a format string representing the part. """ def __init__(self, outfp, mangle_from_=1, maxheaderlen=78, fmt=None): """Like Generator.__init__() except that an additional optional argument is allowed. Walks through all subparts of a message. If the subpart is of main type `text', then it prints the decoded payload of the subpart. Otherwise, fmt is a format string that is used instead of the message payload. fmt is expanded with the following keywords (in %(keyword)s format): type : Full MIME type of the non-text part maintype : Main MIME type of the non-text part subtype : Sub-MIME type of the non-text part filename : Filename of the non-text part description: Description associated with the non-text part encoding : Content transfer encoding of the non-text part The default value for fmt is None, meaning [Non-text (%(type)s) part of message omitted, filename %(filename)s] """ Generator.__init__(self, outfp, mangle_from_, maxheaderlen) if fmt is None: fmt = ('[Non-text (%(type)s) part of message omitted, ' 'filename %(filename)s]') self._fmt = fmt def _dispatch(self, msg): for part in msg.walk(): maintype = part.get_main_type('text') if maintype == 'text': print >> self, part.get_payload(decode=1) elif maintype == 'multipart': # Just skip this pass else: print >> self, self._fmt % { 'type' : part.get_type('[no MIME type]'), 'maintype' : part.get_main_type('[no main MIME type]'), 'subtype' : part.get_subtype('[no sub-MIME type]'), 'filename' : part.get_filename('[no filename]'), 'description': part.get('Content-Description', '[no description]'), 'encoding' : part.get('Content-Transfer-Encoding', '[no encoding]'), } # Helper def _make_boundary(self, text=None): # Craft a random boundary. If text is given, ensure that the chosen # boundary doesn't appear in the text. boundary = ('=' * 15) + repr(random.random()).split('.')[1] + '==' if text is None: return boundary b = boundary counter = 0 while 1: cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE) if not cre.search(text): break b = boundary + '.' + str(counter) counter += 1 return b
"""Support for displaying weather info from Ecobee API.""" from datetime import datetime from pyecobee.const import ECOBEE_STATE_UNKNOWN from homeassistant.components.weather import ( ATTR_FORECAST_CONDITION, ATTR_FORECAST_TEMP, ATTR_FORECAST_TEMP_LOW, ATTR_FORECAST_TIME, ATTR_FORECAST_WIND_BEARING, ATTR_FORECAST_WIND_SPEED, WeatherEntity, ) from homeassistant.const import TEMP_FAHRENHEIT from .const import ( _LOGGER, DOMAIN, ECOBEE_MODEL_TO_NAME, ECOBEE_WEATHER_SYMBOL_TO_HASS, MANUFACTURER, ) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the ecobee weather platform.""" data = hass.data[DOMAIN] dev = [] for index in range(len(data.ecobee.thermostats)): thermostat = data.ecobee.get_thermostat(index) if "weather" in thermostat: dev.append(EcobeeWeather(data, thermostat["name"], index)) async_add_entities(dev, True) class EcobeeWeather(WeatherEntity): """Representation of Ecobee weather data.""" def __init__(self, data, name, index): """Initialize the Ecobee weather platform.""" self.data = data self._name = name self._index = index self.weather = None def get_forecast(self, index, param): """Retrieve forecast parameter.""" try: forecast = self.weather["forecasts"][index] return forecast[param] except (ValueError, IndexError, KeyError): raise ValueError @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self): """Return a unique identifier for the weather platform.""" return self.data.ecobee.get_thermostat(self._index)["identifier"] @property def device_info(self): """Return device information for the ecobee weather platform.""" thermostat = self.data.ecobee.get_thermostat(self._index) try: model = f"{ECOBEE_MODEL_TO_NAME[thermostat['modelNumber']]} Thermostat" except KeyError: _LOGGER.error( "Model number for ecobee thermostat %s not recognized. " "Please visit this link and provide the following information: " "https://github.com/home-assistant/home-assistant/issues/27172 " "Unrecognized model number: %s", thermostat["name"], thermostat["modelNumber"], ) return None return { "identifiers": {(DOMAIN, thermostat["identifier"])}, "name": self.name, "manufacturer": MANUFACTURER, "model": model, } @property def condition(self): """Return the current condition.""" try: return ECOBEE_WEATHER_SYMBOL_TO_HASS[self.get_forecast(0, "weatherSymbol")] except ValueError: return None @property def temperature(self): """Return the temperature.""" try: return float(self.get_forecast(0, "temperature")) / 10 except ValueError: return None @property def temperature_unit(self): """Return the unit of measurement.""" return TEMP_FAHRENHEIT @property def pressure(self): """Return the pressure.""" try: return int(self.get_forecast(0, "pressure")) except ValueError: return None @property def humidity(self): """Return the humidity.""" try: return int(self.get_forecast(0, "relativeHumidity")) except ValueError: return None @property def visibility(self): """Return the visibility.""" try: return int(self.get_forecast(0, "visibility")) / 1000 except ValueError: return None @property def wind_speed(self): """Return the wind speed.""" try: return int(self.get_forecast(0, "windSpeed")) except ValueError: return None @property def wind_bearing(self): """Return the wind direction.""" try: return int(self.get_forecast(0, "windBearing")) except ValueError: return None @property def attribution(self): """Return the attribution.""" if not self.weather: return None station = self.weather.get("weatherStation", "UNKNOWN") time = self.weather.get("timestamp", "UNKNOWN") return f"Ecobee weather provided by {station} at {time} UTC" @property def forecast(self): """Return the forecast array.""" if "forecasts" not in self.weather: return None forecasts = [] for day in range(1, 5): forecast = _process_forecast(self.weather["forecasts"][day]) if forecast is None: continue forecasts.append(forecast) if forecasts: return forecasts return None async def async_update(self): """Get the latest weather data.""" await self.data.update() thermostat = self.data.ecobee.get_thermostat(self._index) self.weather = thermostat.get("weather") def _process_forecast(json): """Process a single ecobee API forecast to return expected values.""" forecast = {} try: forecast[ATTR_FORECAST_TIME] = datetime.strptime( json["dateTime"], "%Y-%m-%d %H:%M:%S" ).isoformat() forecast[ATTR_FORECAST_CONDITION] = ECOBEE_WEATHER_SYMBOL_TO_HASS[ json["weatherSymbol"] ] if json["tempHigh"] != ECOBEE_STATE_UNKNOWN: forecast[ATTR_FORECAST_TEMP] = float(json["tempHigh"]) / 10 if json["tempLow"] != ECOBEE_STATE_UNKNOWN: forecast[ATTR_FORECAST_TEMP_LOW] = float(json["tempLow"]) / 10 if json["windBearing"] != ECOBEE_STATE_UNKNOWN: forecast[ATTR_FORECAST_WIND_BEARING] = int(json["windBearing"]) if json["windSpeed"] != ECOBEE_STATE_UNKNOWN: forecast[ATTR_FORECAST_WIND_SPEED] = int(json["windSpeed"]) except (ValueError, IndexError, KeyError): return None if forecast: return forecast return None
__author__ = "Andre Merzky, Ashley Z, Ole Weidner" __copyright__ = "Copyright 2012-2013, The SAGA Project" __license__ = "MIT" # TODO: Create function to check for all the iRODS error codes and give # a better error readout? # TODO: Look into feasibility of having this access remote resources # if there isn't a local iRODS install # (this may be extremely difficult...) # TODO: Add debug output for -all- icommands showing how they are executed # IE "[DEBUG] Executing: ils -l /mydir/" # TODO: Implement resource package and use it to grab resource information # TODO: Implement Andre's changes in the iRODS adaptors! # TODO: One shell per adaptor in the future? """iRODS replica adaptor implementation Uses icommands commandline tools """ __author__ = "Ashley Zebrowski" __copyright__ = "Copyright 2012-2013, Ashley Zebrowski" __license__ = "MIT" import os import pwd import sys import time import string import errno import saga.url import saga.adaptors.base import saga.adaptors.cpi.replica import saga.utils.pty_shell import saga.utils.misc import shutil import saga.namespace as ns #from saga.utils.cmdlinewrapper import CommandLineWrapper SYNC_CALL = saga.adaptors.cpi.decorators.SYNC_CALL ASYNC_CALL = saga.adaptors.cpi.decorators.ASYNC_CALL ############################################################################### # adaptor info # _ADAPTOR_NAME = 'saga.adaptor.replica.irods' _ADAPTOR_SCHEMAS = ['irods'] _ADAPTOR_OPTIONS = [] _ADAPTOR_CAPABILITIES = {} _ADAPTOR_DOC = { 'name' : _ADAPTOR_NAME, 'cfg_options' : _ADAPTOR_OPTIONS, 'capabilities' : _ADAPTOR_CAPABILITIES, 'description' : 'The iRODS replica adaptor.', 'details' : """This adaptor interacts with the iRODS data management system, by using the iRODS command line tools.""", "example" : "examples/replica/irods/irods_test.py", 'schemas' : {'irods' : 'irods schema' }, } _ADAPTOR_INFO = { 'name' : _ADAPTOR_NAME, 'version' : 'v0.1', 'schemas' : _ADAPTOR_SCHEMAS, 'cpis' : [{ 'type' : 'saga.replica.LogicalDirectory', 'class' : 'IRODSDirectory' }, { 'type' : 'saga.replica.LogicalFile', 'class' : 'IRODSFile' } ] } class irods_logical_entry: '''class to hold info on an iRODS logical file or directory ''' def __init__(self): self.name = "undefined" self.locations = [] self.size = 1234567899 self.owner = "undefined" self.date = "1/1/1111" self.is_directory = False def __str__(self): return str(self.name + " " + \ "/".join(self.locations) + " " + \ str(self.size) + " " + \ self.owner + " " + \ self.date + " " + \ str(self.is_directory)) class irods_resource_entry: '''class to hold info on an iRODS resource ''' # Resources (not groups) as retreived from ilsresc -l look like the following: # # resource name: BNL_ATLAS_2_FTP # resc id: 16214 # zone: osg # type: MSS universal driver # class: compound # location: gw014k1.fnal.gov # vault: /data/cache/BNL_ATLAS_2_FTPplaceholder # free space: # status: up # info: # comment: # create time: 01343055975: 2012-07-23.09:06:15 # modify time: 01347480717: 2012-09-12.14:11:57 # ---- # Resource groups look like this (shortened): # # resource group: osgGridFtpGroup # Includes resource: NWICG_NotreDame_FTP # Includes resource: UCSDT2-B_FTP # Includes resource: UFlorida-SSERCA_FTP # Includes resource: cinvestav_FTP # Includes resource: SPRACE_FTP # Includes resource: NYSGRID_CORNELL_NYS1_FTP # Includes resource: Nebraska_FTP # ----- # ---------------------------------------------------------------- # # def __init__ (self): # are we a resource group? self.is_resource_group = False # individual resource-specific properties self.name = None self.zone = None self.type = None self.resource_class = None self.location = None self.vault = None self.free_space = None self.status = None self.info = None self.comment = None self.create_time = None self.modify_time = None # resource group-specific properties self.group_members = [] ############################################################################### # The adaptor class class Adaptor (saga.adaptors.base.Base): """ This is the actual adaptor class, which gets loaded by SAGA (i.e. by the SAGA engine), and which registers the CPI implementation classes which provide the adaptor's functionality. """ # ---------------------------------------------------------------- # # def __init__ (self) : saga.adaptors.base.Base.__init__ (self, _ADAPTOR_INFO, _ADAPTOR_OPTIONS) def sanity_check (self) : try: # temporarily silence logger lvl = self._logger.getEffectiveLevel () self._logger.setLevel (saga.utils.logger.ERROR) # open a temporary shell self.shell = saga.utils.pty_shell.PTYShell (saga.url.Url("ssh://localhost"), logger = self._logger) # run ils, see if we get any errors -- if so, fail the # sanity check rc, _, _ = self.shell.run_sync("ils") if rc != 0: raise Exception("sanity check error") except Exception, ex: raise saga.NoSuccess ("Could not run iRODS/ils. Check iRODS" "environment and certificates (%s)" % ex) finally : # re-enable logger self._logger.setLevel (lvl) # try ienv or imiscsvrinfo later? ( check for error messages ) # ---------------------------------------------------------------- # # def irods_get_directory_listing (self, irods_dir, wrapper) : '''Function takes an iRODS logical directory as an argument, and returns a list of irods_logical_entry instances containing information on files/directories found in the directory argument. It uses the commandline tool ils. :param self: reference to adaptor which called this function :param dir: iRODS directory we want to get a listing of :param wrapper: the wrapper we will make our iRODS commands with ''' result = [] try: cw = wrapper # execute the ils -L command returncode, out, _ = cw.run_sync ("ils -L %s" % irods_dir) # make sure we ran ok if returncode != 0: raise saga.NoSuccess ("Could not open directory %s, errorcode %s: %s"\ % (irods_dir, str(cw_result.returncode), out)) # strip extra linebreaks from stdout, make a list from the linebreaks that # remain, skip first entry which just tells us the current directory for item in out.strip().split("\n"): # if we are listing a directory or remote resource file location i.e. # [azebro1@gw68]$ ils -L /osg/home/azebro1 # /osg/home/azebro1: # azebro1 1 UFlorida-SSERCA_FTP 12 2012-11-14.09:55 & irods-test.txt # /data/cache/UFlorida-SSERCA_FTPplaceholder/home/azebro1/irods-test.txt osgGridFtpGroup # then we want to ignore that entry (not using it for now) if item.strip().startswith("/"): continue # remove whitespace item = item.strip() # entry for file or directory dir_entry = irods_logical_entry() # if we have a directory here if item.startswith("C- "): dir_entry.name = item[3:] dir_entry.is_directory = True # if we have a file here else: # ils -L output looks like this after you split it: # 0 1 2 3 4 5 6 # ['azebro1', '1', 'UFlorida-SSERCA_FTP', '12', '2012-11-14.09:55', '&', 'irods-test.txt'] # not sure what 1 and 5 are ... dir_entry.owner = item.split()[0] dir_entry.locations = [item.split()[2]] dir_entry.size = item.split()[3] dir_entry.date = item.split()[4] dir_entry.name = item.split()[6] result.append(dir_entry) # merge all entries on the list with duplicate filenames into a # single entry with one filename and multiple resource locations final_list = [] for item in result: if item.name in [i.name for i in final_list]: # duplicate name, merge this entry with the previous one for final_list_item in final_list: if final_list_item.name == item.name: final_list_item.locations.append(item.locations[0]) else: final_list.append(item) return final_list except Exception, e: raise saga.NoSuccess ("Couldn't get directory listing: %s %s " % e) return result # ---------------------------------------------------------------- # # def irods_get_resource_listing(self): ''' Return a list of irods resources and resource groups with information stored in irods_resource_entry format. It uses commandline tool ilsresc -l :param self: reference to adaptor which called this function ''' result = [] try: cw = CommandLineWrapper() cw.open() # execute the ilsresc -l command cw_result = cw.run_sync("ilsresc -l") # make sure we ran ok if cw_result.returncode != 0: raise Exception("Could not obtain list of resources with ilsresc -l") # convert our command's stdout to a list of text lines cw_result_list = cw_result.stdout.strip().split("\n") # list of resource entries we will save our results to result = [] # while loop instead of for loop so we can mutate the list # as we iterate while cw_result_list: entry = irods_resource_entry() # get our next line from the FRONT of the list line = cw_result_list.pop(0) # check to see if this is the beginning of a # singular resource entry if line.startswith("resource name: "): # singular resource entry output from ilsresc -l # LINE NUMBERS AND PADDING ADDED # ex. actual output, line 0 starts like "resource name" # 0 resource name: BNL_ATLAS_2_FTP # 1 resc id: 16214 # 2 zone: osg # 3 type: MSS universal driver # 4 class: compound # 5 location: gw014k1.fnal.gov # 6 vault: /data/cache/BNL_ATLAS_2_FTPplaceholder # 7 free space: # 8 status: up # 9 info: # 10 comment: # 11 create time: 01343055975: 2012-07-23.09:06:15 # 12 modify time: 01347480717: 2012-09-12.14:11:57 # 13 ---- entry.name = line[len("resource name: "):].strip() entry.is_resource_group = False # TODO: SAVE ALL THE OTHER INFO for i in range(13): cw_result_list.pop(0) #add our resource to the list result.append(entry) # check to see if this is an entry for a resource group elif line.startswith("resource group: "): entry.name = line[len("resource group: "):].strip() entry.is_resource_group = True # continue processing ilsresc -l results until we # are at the end of the resource group information # ----- is not printed if there are no further entries # so we have to make sure to check we don't pop off # an empty stack too # # TODO: ACTUALLY SAVE THE LIST OF RESOURCES IN A RESOURCE GROUP while len(cw_result_list)>0 and (not line.startswith("-----")): line=cw_result_list.pop(0) result.append(entry) # for some reason, we're at a line which we have # no idea how to handle this is bad -- throw an error else: raise saga.NoSuccess ("Error parsing iRODS ilsresc -l information!") return result except Exception, e: raise saga.NoSuccess ("Couldn't get resource listing: %s " % (str(e))) ############################################################################### # # logical_directory adaptor class # class IRODSDirectory (saga.adaptors.cpi.replica.LogicalDirectory) : # ---------------------------------------------------------------- # # def __init__ (self, api, adaptor) : self._cpi_base = super (IRODSDirectory, self) self._cpi_base.__init__ (api, adaptor) self.name = None self.size = None self.owner = None self.date = None self.shell = saga.utils.pty_shell.PTYShell (saga.url.Url("ssh://localhost")) def __del__ (self): self._logger.debug("Deconstructor for iRODS directory") self.shell.close() # ---------------------------------------------------------------- # # @SYNC_CALL def init_instance (self, adaptor_state, url, flags, session) : self._url = url self._flags = flags self._session = session self._init_check () return self # ---------------------------------------------------------------- # # @ASYNC_CALL def init_instance_async (self, adaptor_state, url, flags, session, ttype) : self._url = url self._flags = flags self._session = session self._init_check () t = saga.task.Task () t._set_result (saga.replica.LogicalDirectory( url, flags, session, _adaptor_name=_ADAPTOR_NAME)) t._set_state (saga.task.DONE) return t # ---------------------------------------------------------------- # # def _init_check (self) : url = self._url flags = self._flags if url.host != "localhost": raise saga.BadParameter._log(self._logger, "iRODS adaptor does NOT" " currently support accessing remote" " hosts via URLs. To access the" " iRODS environment currently" " established on the local" " machine, please use localhost" " as your hostname.") # ---------------------------------------------------------------- # # @SYNC_CALL def get_url (self) : return self._url # ---------------------------------------------------------------- # # @SYNC_CALL def open (self, url, flags) : if not url.scheme and not url.host : url = saga.url.Url (str(self._url) + '/' + str(url)) f = saga.replica.LogicalFile (url, flags, self._session, _adaptor_name=_ADAPTOR_NAME) return f # ---------------------------------------------------------------- # # @SYNC_CALL def make_dir (self, path, flags) : #complete_path = dir_obj._url.path complete_path = saga.Url(path).get_path() self._logger.debug("TEST: Attempting to make directory at: %s" % complete_path) #attempt to run iRODS mkdir command try: returncode, out, _ = self.shell.run_sync("imkdir %s" % complete_path) if returncode != 0: raise saga.NoSuccess ("Could not create directory %s, errorcode %s: %s"\ % (complete_path, str(returncode), out)) except Exception, ex: # did the directory already exist? if "CATALOG_ALREADY_HAS_ITEM_BY_THAT_NAME" in str(ex): raise saga.AlreadyExists ("Directory already exists.") # couldn't create for unspecificed reason raise saga.NoSuccess ("Couldn't create directory. %s" % ex) return # ---------------------------------------------------------------- # # @SYNC_CALL def remove (self, path, flags) : '''This method is called upon logicaldir.remove() ''' complete_path = saga.Url(path).get_path() self._logger.debug("Attempting to remove directory at: %s" % complete_path) try: self._logger.debug("Executing: irm -r %s" % complete_path) returncode, out, _ = self.shell.run_sync("irm -r %s" % complete_path) if returncode != 0: raise saga.NoSuccess ("Could not remove directory %s, errorcode %s: %s"\ % (complete_path, str(returncode), out)) except Exception, ex: # was there no directory to delete? if "does not exist" in str(ex): raise saga.DoesNotExist ("Directory %s does not exist." % (complete_path) ) # couldn't delete for unspecificed reason raise saga.NoSuccess ("Couldn't delete directory %s because %s"\ % (complete_path, ex)) return # ---------------------------------------------------------------- # # @SYNC_CALL def list (self, npat, flags) : #TODO: Make this use the irods_get_directory_listing complete_path = self._url.path result = [] self._logger.debug("Attempting to get directory listing for logical" "path %s" % complete_path) try: returncode, out, _ = self.shell.run_sync("ils %s" % complete_path) if returncode != 0: raise Exception("Could not open directory") # strip extra linebreaks from stdout, make a list w/ linebreaks, # skip first entry which tells us the current directory for item in out.strip().split("\n")[1:]: item = item.strip() if item.startswith("C- "): #result.append("dir " + item[3:]) result.append(item[3:]) else: #result.append("file " +item) result.append(item) except Exception, ex: raise saga.NoSuccess ("Couldn't list directory: %s " % (str(ex))) return result ###################################################################### # # logical_file adaptor class # class IRODSFile (saga.adaptors.cpi.replica.LogicalFile) : # ---------------------------------------------------------------- # # def __init__ (self, api, adaptor) : self._cpi_base = super (IRODSFile, self) self._cpi_base.__init__ (api, adaptor) self.name = None self.locations = [] self.size = None self.owner = None self.date = None self.is_directory = False self.shell = saga.utils.pty_shell.PTYShell (saga.url.Url("ssh://localhost")) # TODO: "stat" the file def __del__ (self): self._logger.debug("Deconstructor for iRODS file") self.shell.close() # ---------------------------------------------------------------- # # @SYNC_CALL def init_instance (self, adaptor_state, url, flags, session) : self._url = url self._flags = flags self._session = session self._init_check () return self # ---------------------------------------------------------------- # # @ASYNC_CALL def init_instance_async (self, adaptor_state, url, flags, session, ttype) : self._url = url self._flags = flags self._session = session self._init_check () t = saga.task.Task () t._set_result (saga.replica.LogicalFile (url, flags, session, _adaptor_name=_ADAPTOR_NAME)) t._set_state (saga.task.DONE) return t # ---------------------------------------------------------------- # # def _init_check (self) : url = self._url flags = self._flags if url.port : raise saga.BadParameter ("Cannot handle url %s (has fragment)" % url) if url.query : raise saga.BadParameter ("Cannot handle url %s (has query)" % url) if url.username : raise saga.BadParameter ("Cannot handle url %s (has username)" % url) if url.password : raise saga.BadParameter ("Cannot handle url %s (has password)" % url) self._path = url.path path = url.path # ---------------------------------------------------------------- # # @SYNC_CALL def get_url (self) : return self._url # ---------------------------------------------------------------- # # @ASYNC_CALL def get_url_async (self, ttype) : t = saga.task.Task () t._set_state = saga.task.DONE t._set_result = self._url return t # ---------------------------------------------------------------- # # @SYNC_CALL def copy_self (self, target, flags) : tgt_url = saga.url.Url (target) tgt = tgt_url.path src = self._url.path if tgt_url.schema : if not tgt_url.schema.lower () in _ADAPTOR_SCHEMAS : raise saga.BadParameter ("Cannot handle url schema for %s" % target) if tgt[0] != '/' : tgt = "%s/%s" % (os.path.dirname (src), tgt) print " copy %s %s" % (self._url, tgt) shutil.copy2 (src, tgt) # ---------------------------------------------------------------- # # @SYNC_CALL def list_locations (self) : '''This method is called upon logicaldir.list_locations() ''' #return a list of all replica locations for a file path = self._url.get_path() self._logger.debug("Attempting to get a list of replica locations for %s" % path) listing = self._adaptor.irods_get_directory_listing(path, self.shell) return listing[0].locations # ---------------------------------------------------------------- # # @SYNC_CALL def get_size_self (self) : '''This method is called upon logicaldir.get_size() ''' return self.size # ---------------------------------------------------------------- # # @SYNC_CALL def remove_location(self, location): '''This method is called upon logicaldir.remove_locations() ''' raise saga.NotImplemented._log (self._logger, "Not implemented") return # ---------------------------------------------------------------- # # @SYNC_CALL def replicate (self, target, flags): '''This method is called upon logicaldir.replicate() ''' #path to file we are replicating on iRODS complete_path = self._url.get_path() #TODO: Verify Correctness in the way the resource is grabbed query = saga.Url(target).get_query() resource = query.split("=")[1] self._logger.debug("Attempting to replicate logical file %s to " "resource/resource group %s" % (complete_path, resource)) try: self._logger.debug("Executing: irepl -R %s %s" % (resource, complete_path) ) returncode, out, _ = self.shell.run_sync("irepl -R %s %s" % (resource, complete_path) ) if returncode != 0: raise Exception("Could not replicate logical file %s to resource/resource group %s, errorcode %s: %s"\ % (complete_path, resource, str(cw_result.returncode), out)) except Exception, ex: raise saga.NoSuccess._log (self._logger, "Couldn't replicate file. %s" % ex) return # ---------------------------------------------------------------- # # TODO: This is COMPLETELY untested, as it is unsupported on the only iRODS # machine I have access to. @SYNC_CALL def move_self (self, target, flags) : '''This method is called upon logicaldir.move() ''' #path to file we are moving on iRODS source_path = self._url.get_path() dest_path = saga.Url(target).get_path() self._logger.debug("Attempting to move logical file %s to location %s" % (source_path, dest_path)) try: returncode, out, _ = self.shell.run_sync("imv %s %s" % (source_path, dest_path) ) if errorcode != 0: raise saga.NoSuccess ("Could not move logical file %s to location %s, errorcode %s: %s"\ % (source_path, dest_path, str(errorcode), out)) except Exception, ex: raise saga.NoSuccess ("Couldn't move file. %s" % ex) return # ---------------------------------------------------------------- # # def add_location (self, name, ttype) : '''This method is called upon logicaldir.add_location() ''' # TODO: REMOVE UPLOAD CALL/MERGE INTO HERE IF SUPERFLUOUS self.upload(name, None, None) ###################################################################### ## @SYNC_CALL def remove_self (self, flags) : '''This method is called upon logicalfile.remove() ''' complete_path = self._url.get_path() self._logger.debug("Attempting to remove file at: %s" % complete_path) try: returncode, out, _ = self.shell.run_sync("irm %s" % complete_path) if returncode != 0: raise saga.NoSuccess ("Could not remove file %s, errorcode %s: %s"\ % (complete_path, str(returncode), out)) except Exception, ex: # couldn't delete for unspecificed reason raise saga.NoSuccess ("Couldn't delete file %s %s" % (complete_path, ex)) return ###################################################################### ## # # From a convo with Andre M... # # So, if you want to have a logical file in that logical dir, you would create it: # myfile = mydir.open (irods.tar.gz, saga.replica.Create | # saga.replica.ReadWrite) # and then upload # myfile.upload ("file://home/ashley/my/local/filesystem/irods.tar.gz") # OR (revised) # myfile.upload("file://home/ashley/my/local/filesystem/irods.tar.gz", # "irods://.../?resource=host3") # @SYNC_CALL def upload (self, source, target, flags) : '''Uploads a file from the LOCAL, PHYSICAL filesystem to the replica management system. @param source: URL (should be file:// or local path) of local file @param target: Optional param containing ?resource=myresource query This will upload the file to a specified iRODS resource or group. ''' #TODO: Make sure that the source URL is a local/file:// URL complete_path = saga.Url(source).get_path() # extract the path from the LogicalFile object, excluding # the filename destination_path=self._url.get_path()[0:string.rfind( self._url.get_path(), "/")+1] try: #var to hold our command result, placed here to keep in scope returncode = out = 0 # note we're uploading self._logger.debug("Beginning upload operation " +\ "will register file in logical dir: %s" % destination_path) # the query holds our target resource query = saga.Url(target).get_query() # list of args we will generate arg_list = "" # parse flags + generate args if flags: if flags & saga.namespace.OVERWRITE: arg_list += "-f " # was no resource selected? if query==None: self._logger.debug("Attempting to upload to default resource") returncode, out, _ = self.shell.run_sync("iput %s %s %s" % (arg_list, complete_path, destination_path)) # resource was selected, have to parse it and supply to iput -R else: #TODO: Verify correctness resource = query.split("=")[1] self._logger.debug("Attempting to upload to query-specified resource %s" % resource) returncode, out, _ = self.shell.run_sync("iput -R %s %s %s %s" % (resource, arg_list, complete_path, destination_path)) # check our result if returncode != 0: raise saga.NoSuccess ("Could not upload file %s, errorcode %s: %s"\ % (complete_path, str(returncode), out)) except Exception, ex: # couldn't upload for unspecificed reason raise saga.NoSuccess._log (self._logger, "Couldn't upload file: %s" % ex) return @SYNC_CALL def download (self, name, source, flags) : '''Downloads a file from the REMOTE REPLICA FILESYSTEM to a local directory. @param target: param containing a local path/filename to save the file to @param source: Optional param containing a remote replica to retrieve the file from (not evaluated, yet) ''' target = name #TODO: Make sure that the target URL is a local/file:// URL # extract the path from the LogicalFile object, excluding # the filename logical_path=self._url.get_path() # fill in our local path if one was specified local_path = "" if target: local_path = saga.Url(target).get_path() try: #var to hold our command result, placed here to keep in scope returncode = out = _ = 0 #mark that this is experimental/may not be part of official API self._logger.debug("Beginning download operation " +\ "will download logical file: %s, specified local target is %s" % (logical_path, target) ) # was no local target selected? if target==None: self._logger.debug("Attempting to download file %s with iget to current local directory" % \ logical_path) self._logger.debug("Executing: iget %s" % logical_path) returncode, out, _ = self.shell.run_sync("iget %s" % \ (logical_path)) # local target selected else: self._logger.debug("Attempting to download file %s with iget to %s" % (logical_path, local_path)) self._logger.debug("Executing: iget %s %s" % (logical_path, local_path)) returncode, out, _ = self.shell.run_sync("iget %s %s " % (logical_path, local_path)) # check our result if returncode != 0: raise saga.NoSuccess ("Could not download file %s, errorcode %s: %s"\ % (logical_path, str(returncode), out)) except Exception, ex: # couldn't download for unspecificed reason raise saga.NoSuccess ("Couldn't download file. %s" % ex) return
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. import inspect from botocore.docs.utils import get_official_service_name from botocore.docs.method import document_custom_method from botocore.docs.method import document_model_driven_method from botocore.docs.method import get_instance_public_methods from botocore.docs.sharedexample import document_shared_examples from botocore.docs.example import ResponseExampleDocumenter from botocore.docs.params import ResponseParamsDocumenter from botocore.docs.utils import DocumentedShape from botocore.compat import OrderedDict class ClientDocumenter(object): def __init__(self, client, shared_examples=None): self._client = client self._shared_examples = shared_examples if self._shared_examples is None: self._shared_examples = {} self._service_name = self._client.meta.service_model.service_name def document_client(self, section): """Documents a client and its methods :param section: The section to write to. """ self._add_title(section) self._add_class_signature(section) client_methods = get_instance_public_methods(self._client) self._add_client_intro(section, client_methods) self._add_client_methods(section, client_methods) def _add_title(self, section): section.style.h2('Client') def _add_client_intro(self, section, client_methods): section = section.add_new_section('intro') # Write out the top level description for the client. official_service_name = get_official_service_name( self._client.meta.service_model) section.write( 'A low-level client representing %s' % official_service_name) section.style.new_line() section.include_doc_string(self._client.meta.service_model.documentation) # Write out the client example instantiation. self._add_client_creation_example(section) # List out all of the possible client methods. section.style.new_line() section.write('These are the available methods:') section.style.new_line() class_name = self._client.__class__.__name__ for method_name in sorted(client_methods): section.style.li(':py:meth:`~%s.Client.%s`' % ( class_name, method_name)) def _add_class_signature(self, section): section.style.start_sphinx_py_class( class_name='%s.Client' % self._client.__class__.__name__) def _add_client_creation_example(self, section): section.style.start_codeblock() section.style.new_line() section.write( 'client = session.create_client(\'{service}\')'.format( service=self._service_name) ) section.style.end_codeblock() def _add_client_methods(self, section, client_methods): section = section.add_new_section('methods') for method_name in sorted(client_methods): self._add_client_method( section, method_name, client_methods[method_name]) def _add_client_method(self, section, method_name, method): section = section.add_new_section(method_name) if self._is_custom_method(method_name): self._add_custom_method(section, method_name, method) else: self._add_model_driven_method(section, method_name) def _is_custom_method(self, method_name): return method_name not in self._client.meta.method_to_api_mapping def _add_custom_method(self, section, method_name, method): document_custom_method(section, method_name, method) def _add_method_exceptions_list(self, section, operation_model): error_section = section.add_new_section('exceptions') error_section.style.new_line() error_section.style.bold('Exceptions') error_section.style.new_line() client_name = self._client.__class__.__name__ for error in operation_model.error_shapes: class_name = '%s.Client.exceptions.%s' % (client_name, error.name) error_section.style.li(':py:class:`%s`' % class_name) def _add_model_driven_method(self, section, method_name): service_model = self._client.meta.service_model operation_name = self._client.meta.method_to_api_mapping[method_name] operation_model = service_model.operation_model(operation_name) example_prefix = 'response = client.%s' % method_name document_model_driven_method( section, method_name, operation_model, event_emitter=self._client.meta.events, method_description=operation_model.documentation, example_prefix=example_prefix, ) # Add any modeled exceptions if operation_model.error_shapes: self._add_method_exceptions_list(section, operation_model) # Add the shared examples shared_examples = self._shared_examples.get(operation_name) if shared_examples: document_shared_examples( section, operation_model, example_prefix, shared_examples) class ClientExceptionsDocumenter(object): _USER_GUIDE_LINK = ( 'https://boto3.amazonaws.com/' 'v1/documentation/api/latest/guide/error-handling.html' ) _GENERIC_ERROR_SHAPE = DocumentedShape( name='Error', type_name='structure', documentation=( 'Normalized access to common exception attributes.' ), members=OrderedDict([ ('Code', DocumentedShape( name='Code', type_name='string', documentation=( 'An identifier specifying the exception type.' ), )), ('Message', DocumentedShape( name='Message', type_name='string', documentation=( 'A descriptive message explaining why the exception ' 'occured.' ), )), ]), ) def __init__(self, client): self._client = client self._service_name = self._client.meta.service_model.service_name def document_exceptions(self, section): self._add_title(section) self._add_overview(section) self._add_exceptions_list(section) self._add_exception_classes(section) def _add_title(self, section): section.style.h2('Client Exceptions') def _add_overview(self, section): section.style.new_line() section.write( 'Client exceptions are available on a client instance ' 'via the ``exceptions`` property. For more detailed instructions ' 'and examples on the exact usage of client exceptions, see the ' 'error handling ' ) section.style.external_link( title='user guide', link=self._USER_GUIDE_LINK, ) section.write('.') section.style.new_line() def _exception_class_name(self, shape): cls_name = self._client.__class__.__name__ return '%s.Client.exceptions.%s' % (cls_name, shape.name) def _add_exceptions_list(self, section): error_shapes = self._client.meta.service_model.error_shapes if not error_shapes: section.style.new_line() section.write('This client has no modeled exception classes.') section.style.new_line() return section.style.new_line() section.write('The available client exceptions are:') section.style.new_line() for shape in error_shapes: class_name = self._exception_class_name(shape) section.style.li(':py:class:`%s`' % class_name) def _add_exception_classes(self, section): for shape in self._client.meta.service_model.error_shapes: self._add_exception_class(section, shape) def _add_exception_class(self, section, shape): class_section = section.add_new_section(shape.name) class_name = self._exception_class_name(shape) class_section.style.start_sphinx_py_class(class_name=class_name) self._add_top_level_documentation(class_section, shape) self._add_exception_catch_example(class_section, shape) self._add_response_attr(class_section, shape) class_section.style.end_sphinx_py_class() def _add_top_level_documentation(self, section, shape): if shape.documentation: section.style.new_line() section.include_doc_string(shape.documentation) section.style.new_line() def _add_exception_catch_example(self, section, shape): section.style.new_line() section.style.bold('Example') section.style.start_codeblock() section.write('try:') section.style.indent() section.style.new_line() section.write('...') section.style.dedent() section.style.new_line() section.write('except client.exceptions.%s as e:' % shape.name) section.style.indent() section.style.new_line() section.write('print(e.response)') section.style.dedent() section.style.end_codeblock() def _add_response_attr(self, section, shape): response_section = section.add_new_section('response') response_section.style.start_sphinx_py_attr('response') self._add_response_attr_description(response_section) self._add_response_example(response_section, shape) self._add_response_params(response_section, shape) response_section.style.end_sphinx_py_attr() def _add_response_attr_description(self, section): section.style.new_line() section.include_doc_string( 'The parsed error response. All exceptions have a top level ' '``Error`` key that provides normalized access to common ' 'exception atrributes. All other keys are specific to this ' 'service or exception class.' ) section.style.new_line() def _add_response_example(self, section, shape): example_section = section.add_new_section('syntax') example_section.style.new_line() example_section.style.bold('Syntax') example_section.style.new_paragraph() documenter = ResponseExampleDocumenter( service_name=self._service_name, operation_name=None, event_emitter=self._client.meta.events, ) documenter.document_example( example_section, shape, include=[self._GENERIC_ERROR_SHAPE], ) def _add_response_params(self, section, shape): params_section = section.add_new_section('Structure') params_section.style.new_line() params_section.style.bold('Structure') params_section.style.new_paragraph() documenter = ResponseParamsDocumenter( service_name=self._service_name, operation_name=None, event_emitter=self._client.meta.events, ) documenter.document_params( params_section, shape, include=[self._GENERIC_ERROR_SHAPE], )
from util import memoize, run_search_function from util import INFINITY import time ######################################## ########## SUMMARY OF CHANGES ########## ######################################## # # basic_evaluate has been modified to return # -INFINITY instead of -1000 to make it consistent # with the other evaluation functions. # # minimax has been implemeted using recusrsion # and the helper function minimax_rec # which accepts all the same parameters as minimax # with the addition of max_node, which is set # to true/false depending on whether the # current node is a max/min node. # # new_evaluate has been implemented using the # various functions available in the ConnectFourBoard # class. # # A completely new addition is streak_evaluate # which is the evaluation function used when # the players are playing for the longest # streak. The longest streak game mode is # selected when the streak (NEW ADDITION TO # ConnectFourBoard CLASS) is set to > 7. # The variable streak has a default value 4, # and dtermines the length of a streak # required to win. When a ConnectFourBoard # class object is created without any # explicit arguments, the game is the # traditional Connect4 game. If explicitly # specified, the game a becomes a more general # Connectk. Both new_evaluate and streak_evaluate # takes into consideration the value of streak # and adjusts evaluations accordingly. # ######################################## def basic_evaluate(board): """ The original focused-evaluate function from the lab. The original is kept because the lab expects the code in the lab to be modified. """ if board.is_game_over(): # If the game has been won, we know that it must have been # won or ended by the previous move. # The previous move was made by our opponent. # Therefore, we can't have won, so return -INFINITY. # (note that this causes a tie to be treated like a loss) score = -INFINITY else: score = board.longest_chain(board.get_current_player_id()) * 10 # Prefer having your pieces in the center of the board. for row in range(6): for col in range(7): if board.get_cell(row, col) == board.get_current_player_id(): score -= abs(3-col) elif board.get_cell(row, col) == board.get_other_player_id(): score += abs(3-col) return score def get_all_next_moves(board): """ Return a generator of all moves that the current player could take from this position """ from connectfour import InvalidMoveException for i in xrange(board.board_width): try: yield (i, board.do_move(i)) except InvalidMoveException: pass def is_terminal(depth, board): """ Generic terminal state check, true when maximum depth is reached or the game has ended. """ return depth <= 0 or board.is_game_over() ######################################## # # minimax depends entirely on the recursion # defined by minimax_rec which takes all the same # parameters as minimax with the addition of # max_node, which is true/false depending on whether # the node is a max/min node. # # minimax_rec also returns a structure instead # of only a column number. The structure is of the # form [(EVALUATION, DEPTH, COLUMN), NODES_EXPANDED], # where EVALUATION corresponds to the best evaluation # found among the children, DEPTH corresponds # to the depth from which the evaluation was made, # and COLUMN corresponds to the move resulting in # EVALUATION. NODES_EXPANDED, as the name suggests, # is the number of nodes expanded by the particular # node. # # minimax outputs the EXECUTION TIME and NODES # EXPANDED before returning the required column number. # ######################################## def minimax(board, depth, eval_fn = basic_evaluate, get_next_moves_fn = get_all_next_moves, is_terminal_fn = is_terminal, verbose = True): """ Do a minimax search to the specified depth on the specified board. board -- the ConnectFourBoard instance to evaluate depth -- the depth of the search tree (measured in maximum distance from a leaf to the root) eval_fn -- (optional) the evaluation function to use to give a value to a leaf of the tree; see "focused_evaluate" in the lab for an example Returns an integer, the column number of the column that the search determines you should add a token to """ start = time.clock() [(evaluation, depth_searched, column), total_nodes_expanded] = minimax_rec(board, depth, eval_fn, get_next_moves_fn, is_terminal_fn, 1) stop = time.clock() print 'Nodes expanded: ', total_nodes_expanded print 'Execution time: ', (stop - start) return column raise NotImplementedError def minimax_rec(board, depth, eval_fn, get_next_moves_fn, is_terminal_fn, max_node): from copy import deepcopy ######################################## # # The current node is terminal if either # the desired search depth is reached or # the game is over. # # If the desired search depth has been reached # then return the evaluation of the game # state. Otherwise, return -INFINITY or # INFINITY depending on whether the node # is a max or min node. The reasoning is as follows: # If a game over is detected in a max node then the # game must have been finished by the min player, else # the game must have been finished by the max player. # Since evaluation is always done from the perspective # of the max player, this makes sense. # ######################################## if is_terminal_fn(depth, board): if depth <= 0: return [(eval_fn(board), depth, -1), 0] elif max_node == 1: return [(-INFINITY, -depth, -1), 0] else: return [(INFINITY, depth, -1), 0] ######################################## # # The moves generator is stored in moves. # # The rest is fairly straightforward. If # max_node is set then the maximum evaluation # is returned, else the minimum. Note that in # cases of ties, they are broken by the depth # at which the evaluation is obtained. depth is # highest at the root and gradually decreases # to zero at the leaves. So when sorted, the # evaluation obtained higher up the tree occurs # later and that obtained the deepest appears # first. The max node selects the rightmost # alternative and the min node selects the leftmost # alternative after sorting. Thus, on closer # inspection, max node will always try to finish # off the game the earliest and the min node # will try to delay the finish the longest. # If there is still a tie max node will select # rightmost alternative and min node # the leftmost. # # Note how max_node is reset to 0 by a max # node and set to 1 by a min node. This # conveys the context to each children and # enables them to take the appropriate actions. # ######################################## moves = get_next_moves_fn(board) if max_node == 1: ######################################## # MAX NODE. ######################################## evaluations = [] total_nodes_expanded = 0 for move in moves: [(evaluation, depth_searched, column), nodes_expanded] = minimax_rec(deepcopy(move[1]), depth - 1, eval_fn, get_next_moves_fn, is_terminal_fn, 0) evaluations.append((evaluation, depth_searched, move[0])) total_nodes_expanded += nodes_expanded + 1 evaluations.sort() return [evaluations[len(evaluations)-1], total_nodes_expanded] else: ######################################## # MIN NODE. ######################################## evaluations = [] total_nodes_expanded = 0 for move in moves: [(evaluation, depth_searched, column), nodes_expanded] = minimax_rec(deepcopy(move[1]), depth - 1, eval_fn, get_next_moves_fn, is_terminal_fn, 1) evaluations.append((evaluation, depth_searched, move[0])) total_nodes_expanded += nodes_expanded + 1 evaluations.sort() return [evaluations[0], total_nodes_expanded] raise NotImplementedError def rand_select(board): """ Pick a column by random """ import random moves = [move for move, new_board in get_all_next_moves(board)] return moves[random.randint(0, len(moves) - 1)] def new_evaluate(board): if board.is_game_over(): ######################################## # # If the game has been won, we know that it must have been # won or ended by the previous move. # The previous move was made by our opponent. # Therefore, we can't have won, so return -INFINITY. # (note that this causes a tie to be treated like a loss) # ######################################## score = -INFINITY else: ######################################## # # Prefer having your pieces in the center # of the board. This is a cardinal rule of # Connect4 and hence left to guide the # search during the initial stages of the # game. Note that upto this postion, the # function is identical to basic_evaluate. # However, new_evaluate is more informed # as it takes into consideration impending # threats, both from itself as well as the # opponent. The contribution to evaluation # from threats takes over the primary role # in the latter stages of the game. As then # acknowledging threats and countering them # is more important than playing to the middle. # # This evaluation is much more superior to # basic_evaluate as will be proved during # a head-to-head session between the two. This # strategy actually takes into account whether # current player played first or second and # chooses a strategy accordingly. These strategies # are independent and each can be used for # both the cases of playing first and second, to # beat basic_evaluate. # # The strategy used for playeing first is # less informed and hence more aggresive. # The strategy for playing second is more # informed and conservative. When put head # to head, the latter strategy beats the # former, as expected. # # Both have been kept because both are good # examples of evaluation functions. # # As already mentioned, this evaluation # function adapts itself for a ConnectK game. # ######################################## streak = board.get_streak() DIRECTION = [[(-1, 0), (1, 0)], [(0, -1), (0, 1)], [(-1, -1), (1, 1)], [(-1, 1), (1, -1)]] score = 0 for row in range(6): for col in range(7): if board.get_cell(row, col) == board.get_current_player_id(): score -= abs(3-col) elif board.get_cell(row, col) == board.get_other_player_id(): score += abs(3-col) current_player_threats = [] other_player_threats = [] if board.get_current_player_id() == 1: ######################################## # Strategy for playing first. ######################################## # # Takse into account only threats from # consecutive K-1 - streaks having open # ends. Aggresive and utilizes the fact # that the first player generally has the # upper-hand. # # Threats are stored as board positions # each player's threats exists. Separate # lists are maintained for the players. # ######################################## for row in range(6): for col in range(7): chains = [] if board.get_cell(row, col) != 0: chains.append((board._contig_vector_length(row, col, (-1, 0)) + 1 + board._contig_vector_length(row, col, (1, 0)), (1, 0))) chains.append((board._contig_vector_length(row, col, (0, -1)) + 1 + board._contig_vector_length(row, col, (0, 1)), (0, 1))) chains.append((board._contig_vector_length(row, col, (-1, -1)) + 1 + board._contig_vector_length(row, col, (1, 1)), (1, 1))) chains.append((board._contig_vector_length(row, col, (-1, 1)) + 1 + board._contig_vector_length(row, col, (1, -1)), (-1, 1))) for chain in chains: if chain[0] == streak - 1: cells = [] cells.extend(board._contig_vector_cells(row, col, (chain[1][0], chain[1][1]))) cells.extend(board._contig_vector_cells(row, col, (-chain[1][0], -chain[1][1]))) cells.append((row, col)) cells.sort() if board.get_cell(row, col) == board.get_current_player_id(): if 0 <= cells[0][0] - chain[1][0] < 6 and 0 <= cells[0][1] - chain[1][1] < 7: if board.get_cell(cells[0][0] - chain[1][0], cells[0][1] - chain[1][1]) == 0: current_player_threats.append((cells[0][0] - chain[1][0], cells[0][1] - chain[1][1])) if 0 <= cells[len(cells) - 1][0] + chain[1][0] < 6 and 0 <= cells[len(cells) - 1][1] + chain[1][1] < 7: if board.get_cell(cells[0][0] - chain[1][0], cells[0][1] - chain[1][1]) == 0: current_player_threats.append((cells[0][0] + chain[1][0], cells[0][1] + chain[1][1])) elif board.get_cell(row, col) == board.get_other_player_id(): if 0 <= cells[0][0] - chain[1][0] < 6 and 0 <= cells[0][1] - chain[1][1] < 7: if board.get_cell(cells[0][0] - chain[1][0], cells[0][1] - chain[1][1]) == 0: other_player_threats.append((cells[0][0] - chain[1][0], cells[0][1] - chain[1][1])) if 0 <= cells[len(cells) - 1][0] + chain[1][0] < 6 and 0 <= cells[len(cells) - 1][1] + chain[1][1] < 7: if board.get_cell(cells[0][0] - chain[1][0], cells[0][1] - chain[1][1]) == 0: other_player_threats.append((cells[0][0] + chain[1][0], cells[0][1] + chain[1][1])) else: ######################################## # Strategy for playing second. ######################################## # # Takes into account all threats, not # just consecutive K-1 - streaks. Considers # whether two smaller streaks can be combined # to finish the game. More informed and has an # advantage playing second since it can counter # better than the former strategy. # ######################################## for row in range(6): for col in range(7): if board.get_cell(row, col) == 0: for direction in DIRECTION: if 0 <= row + direction[0][0] <= 5 and 0 <= col + direction[0][1] <= 6: if board.get_cell(row + direction[0][0], col + direction[0][1]) != 0: first_extension = board._contig_vector_length(row + direction[0][0], col + direction[0][1], direction[0]) + 1 else: first_extension = 0 else: first_extension = 0 if 0 <= row + direction[1][0] <= 5 and 0 <= col + direction[1][1] <= 6: if board.get_cell(row + direction[1][0], col + direction[1][1]) != 0: second_extension = board._contig_vector_length(row + direction[1][0], col + direction[1][1], direction[1]) + 1 else: second_extension = 0 else: second_extension = 0 if first_extension >= streak - 1: if board.get_current_player_id() == board.get_cell(row + direction[0][0], col + direction[0][1]): current_player_threats.append((row, col)) else: other_player_threats.append((row, col)) if second_extension >= streak - 1: if board.get_current_player_id() == board.get_cell(row + direction[1][0], col + direction[1][1]): current_player_threats.append((row, col)) else: other_player_threats.append((row, col)) if first_extension > 0 and second_extension > 0: if board.get_cell(row + direction[0][0], col + direction[0][1]) == board.get_cell(row + direction[1][0], col + direction[1][1]) and first_extension + 1 + second_extension >= streak: if board.get_current_player_id() == board.get_cell(row + direction[0][0], col + direction[0][1]): current_player_threats.append((row, col)) else: other_player_threats.append((row, col)) ######################################## # # Convert each threat list to set as the # same threat may have been recorded from # multiple streaks. # # If there are no threats play to the # middle. # # not all threats are real though. If a # threat exists for a player in a column, # and another threat esists in the same # column below that for the same or the # other player then the former threat is # to realize before the latter. # # The lists of threats are accordingly # evaluated taking into consideration only # the real threats. # # Note that the reward and penalty from # threats is much greater than those for # playing to the middle. This ensures, # priority is given to threats, when they # arise. # ######################################## current_player_threats = set(current_player_threats) other_player_threats = set(other_player_threats) if len(current_player_threats) == 0 and len(other_player_threats) == 0: return score real_threats = [] for col in range(7): temp_threats = [] for threat in current_player_threats: if threat[1] == col: temp_threats.append(threat) for threat in other_player_threats: if threat[1] == col: temp_threats.append(threat) temp_threats.sort() if len(temp_threats) > 0: real_threats.append(temp_threats[len(temp_threats) - 1]) for threat in current_player_threats: if threat in real_threats: score += 40 for threat in other_player_threats: if threat in real_threats: score -= 40 return score raise NotImplementedError def streak_evaluate(board): ######################################## # # This evaluation function is used in the # longest streak game mode. Note that this # function does return a value of -INFINITY, # by default, when the game is over, as # the criteria for deciding a game over # does not determine the winner. The game # is over when each player has played 10 # pieces. The winner is the one with the # longest streak. # # This function is used in streak_player's # definition. # ######################################## # # It makes sense for rewards and penalties # to somewhat exclusively involve longets # streaks. # # However, it is still encourages to play # to the middle as doing so singnificantly # impedes the opponent's attempts to create # longer streaks. # # This is a balanced evaluation. When used # against itself, results in draws. # ######################################## if board.is_game_over(): if board.longest_chain(board.get_current_player_id()) - board.longest_chain(board.get_other_player_id()) < 0: return -INFINITY else: return INFINITY # If the game has been won, we know that it must have been # won or ended by the previous move. # The previous move was made by our opponent. # Therefore, we can't have won, so return -INFINITY. # (note that this causes a tie to be treated like a loss) score = -INFINITY score = (board.longest_chain(board.get_current_player_id()) * 10) - (board.longest_chain(board.get_other_player_id()) * 10) for row in range(6): for col in range(7): if board.get_cell(row, col) == board.get_current_player_id(): score -= abs(3-col) elif board.get_cell(row, col) == board.get_other_player_id(): score += abs(3-col) return score random_player = lambda board: rand_select(board) basic_player = lambda board: minimax(board, depth=4, eval_fn=basic_evaluate) new_player = lambda board: minimax(board, depth=4, eval_fn=new_evaluate) progressive_deepening_player = lambda board: run_search_function(board, search_fn=minimax, eval_fn=basic_evaluate)
#!/usr/bin/env python __author__ = 'waroquiers' import unittest from pymatgen.analysis.chemenv.utils.coordination_geometry_utils import Plane import numpy as np import itertools from pymatgen.util.testing import PymatgenTest class PlanesUtilsTest(PymatgenTest): def setUp(self): #Test of plane 4x + 2y - 4z + 3 = 0 (used in most test cases) self.expected_coefficients = np.array([4.0, 2.0, -4.0, 3.0], np.float) self.p1 = np.array([0.0, 0.0, 0.75]) self.p2 = np.array([-0.75, 0.0, 0.0]) self.p3 = np.array([0.0, -1.5, 0.0]) self.plane = Plane.from_3points(self.p1, self.p2, self.p3) def test_factors_abcd_normal_vector(self): factors = self.plane.coefficients / self.expected_coefficients self.assertArrayAlmostEqual([factors[0]]*4, [ff for ff in factors]) self.assertTrue(np.allclose([2.0/3.0, 1.0/3.0, -2.0/3.0], self.plane.normal_vector)) def test_from_npoints_plane(self): best_fits = ['least_square_distance', 'maximum_distance'] delta = 0.0001 for best_fit in best_fits: plane = Plane.from_npoints([self.p1, self.p2, self.p3], best_fit=best_fit) self.assertTrue(self.plane.is_same_plane_as(plane)) points = [np.array([5.1, 0.3, -2.3]), np.array([-2.0, 4.3, -6.3]), np.array([3.1, 2.3, -21.3]), np.array([-2, -0.5, 0.05]), np.array([11, 12, -13]), np.array([10, 8.3, -6.32])] plane = Plane.from_npoints(points, best_fit=best_fit) fit_error_plane = plane.fit_error(points, fit=best_fit) coeffs = [[1.0+delta, 1, 1, 1], [1, 1.0+delta, 1, 1], [1, 1, 1.0+delta, 1], [1, 1, 1, 1.0+delta], [1.0-delta, 1.0+delta, 1.0-delta, 1.0+delta]] for coeff in coeffs: plane_changed = Plane.from_coefficients(coeff[0]*plane.a, coeff[1]*plane.b, coeff[2]*plane.c, coeff[3]*plane.d) fit_error = plane_changed.fit_error(points, fit=best_fit) self.assertGreater(fit_error, fit_error_plane) coeff = [-2.1, -2.1, -2.1, -2.1] plane_not_changed = Plane.from_coefficients(coeff[0]*plane.a, coeff[1]*plane.b, coeff[2]*plane.c, coeff[3]*plane.d) fit_error = plane_not_changed.fit_error(points, fit=best_fit) self.assertAlmostEqual(fit_error, fit_error_plane) def test_is_in_plane(self): self.assertTrue(self.plane.is_in_plane(self.p1, 0.001)) self.assertTrue(self.plane.is_in_plane(self.p2, 0.001)) self.assertTrue(self.plane.is_in_plane(self.p3, 0.001)) self.assertFalse(self.plane.is_in_plane(np.zeros(3), 0.001)) self.assertTrue(self.plane.is_in_plane(np.array([1.0, 1.0, 2.25]), 0.001)) self.assertTrue(self.plane.is_in_plane(np.array([1.0, 1.0, 2.22]), 0.1)) self.assertFalse(self.plane.is_in_plane(np.array([1.0, 1.0, 2.22]), 0.001)) self.assertTrue(self.plane.is_in_plane(self.p1 + self.plane.normal_vector * 1.0, 1.000001)) self.assertFalse(self.plane.is_in_plane(self.p1 + self.plane.normal_vector * 1.00001, 1.0)) self.assertFalse(self.plane.is_in_plane(self.p1 + self.plane.normal_vector * 1.0, 0.999999)) self.assertTrue(self.plane.is_in_plane(self.plane.p1, 0.00001)) self.assertTrue(self.plane.is_in_plane(self.plane.p2, 0.00001)) self.assertTrue(self.plane.is_in_plane(self.plane.p3, 0.00001)) def test_normal_vector_is_normed(self): self.assertTrue(np.isclose(np.linalg.norm(self.plane.normal_vector), 1.0)) def test_orthonormal_vectors(self): ortho = self.plane.orthonormal_vectors() self.assertTrue(np.isclose(np.dot(ortho[0], self.plane.normal_vector), 0.0)) self.assertTrue(np.isclose(np.dot(ortho[1], self.plane.normal_vector), 0.0)) self.assertTrue(np.isclose(np.dot(ortho[2], self.plane.normal_vector), 1.0)) self.assertTrue(np.isclose(np.dot(ortho[0], ortho[1]), 0.0)) self.assertTrue(np.isclose(np.dot(ortho[1], ortho[2]), 0.0)) self.assertTrue(np.isclose(np.dot(ortho[2], ortho[0]), 0.0)) self.assertTrue(np.allclose(np.cross(ortho[0], ortho[1]), ortho[2])) self.assertTrue(np.allclose(np.cross(ortho[0], ortho[1]), self.plane.normal_vector)) self.assertTrue(np.allclose(np.cross(ortho[1], ortho[2]), ortho[0])) self.assertTrue(np.allclose(np.cross(ortho[2], ortho[0]), ortho[1])) self.assertFalse(np.allclose(np.cross(ortho[1], ortho[0]), ortho[2])) self.assertTrue(np.allclose(np.cross(ortho[0], ortho[1]), self.plane.normal_vector)) def test_plane_comparison(self): plane_test_1 = Plane.from_coefficients(4, 2, -4, 3) self.assertTrue(self.plane.is_same_plane_as(plane_test_1)) plane_test_2 = Plane.from_coefficients(-4, -2, 4, -3) self.assertTrue(self.plane.is_same_plane_as(plane_test_2)) plane_test_3 = Plane.from_coefficients(-12, -6, 12, -9) self.assertTrue(self.plane.is_same_plane_as(plane_test_3)) plane_test_4 = Plane.from_coefficients(3, 0, 2, 4) self.assertFalse(self.plane.is_same_plane_as(plane_test_4)) def test_plane_is_in_list_of_planes(self): plane_test_1 = Plane.from_coefficients(-8.1, 2, -4, 3) plane_test_2 = Plane.from_coefficients(0, -2, 4, 0) plane_test_3 = Plane.from_coefficients(-12, -6, 12, -9) plane_test_4 = Plane.from_coefficients(3, 0, 0, 4) plane_list = [plane_test_1, plane_test_2, plane_test_3, plane_test_4] self.assertTrue(self.plane.is_in_list(plane_list)) plane_list = [plane_test_1, plane_test_2, plane_test_4] self.assertFalse(self.plane.is_in_list(plane_list)) def test_plane_3_coefficients(self): plane_1 = Plane.from_coefficients(0, 2, -1, 3) self.assertTrue(plane_1.is_in_plane(plane_1.p1, 0.000001)) self.assertTrue(plane_1.is_in_plane(plane_1.p2, 0.000001)) self.assertTrue(plane_1.is_in_plane(plane_1.p3, 0.000001)) plane_2 = Plane.from_coefficients(12, 0, 2, -4) self.assertTrue(plane_2.is_in_plane(plane_2.p1, 0.000001)) self.assertTrue(plane_2.is_in_plane(plane_2.p2, 0.000001)) self.assertTrue(plane_2.is_in_plane(plane_2.p3, 0.000001)) plane_3 = Plane.from_coefficients(-8, 8, 0, 0) self.assertTrue(plane_3.is_in_plane(plane_3.p1, 0.000001)) self.assertTrue(plane_3.is_in_plane(plane_3.p2, 0.000001)) self.assertTrue(plane_3.is_in_plane(plane_3.p3, 0.000001)) def test_plane_2_coefficients(self): plane_1 = Plane.from_coefficients(-21, 0, 0, 3) self.assertTrue(plane_1.is_in_plane(plane_1.p1, 0.000001)) self.assertTrue(plane_1.is_in_plane(plane_1.p2, 0.000001)) self.assertTrue(plane_1.is_in_plane(plane_1.p3, 0.000001)) plane_2 = Plane.from_coefficients(0, 4, 0, -4) self.assertTrue(plane_2.is_in_plane(plane_2.p1, 0.000001)) self.assertTrue(plane_2.is_in_plane(plane_2.p2, 0.000001)) self.assertTrue(plane_2.is_in_plane(plane_2.p3, 0.000001)) plane_3 = Plane.from_coefficients(0, 0, 3, 1) self.assertTrue(plane_3.is_in_plane(plane_3.p1, 0.000001)) self.assertTrue(plane_3.is_in_plane(plane_3.p2, 0.000001)) self.assertTrue(plane_3.is_in_plane(plane_3.p3, 0.000001)) def test_indices_separate(self): #Test with the common test plane point_1 = np.array([0.0, 0.0, 0.0], np.float) point_2 = np.array([0.0, 0.0, 0.75], np.float) point_3 = np.array([-0.75, 0.0, 0.0], np.float) point_4 = np.array([1.0, 0.0, 0.0], np.float) point_5 = np.array([0.0, -1.5, 0.0], np.float) point_6 = np.array([10.0, 2.0, -20.0], np.float) point_7 = np.array([10.0, 10.0, 10.0], np.float) point_8 = np.array([100.0, 0.0, 0.0], np.float) plist = [point_1, point_2, point_3, point_4, point_5, point_6, point_7, point_8] sep = self.plane.indices_separate(plist, 0.000001) self.assertEqual(len(sep[0]), 0) self.assertEqual(len(sep[1]), 3) self.assertEqual(len(sep[2]), 5) self.assertTrue(np.allclose(sep[1], [1, 2, 4])) self.assertTrue(np.allclose(sep[2], [0, 3, 5, 6, 7])) sep = self.plane.indices_separate(plist, 10) self.assertEqual(len(sep[0]), 0) self.assertEqual(len(sep[1]), 6) self.assertEqual(len(sep[2]), 2) self.assertTrue(np.allclose(sep[1], [0, 1, 2, 3, 4, 6])) self.assertTrue(np.allclose(sep[2], [5, 7])) sep = self.plane.indices_separate(plist, 100000) self.assertEqual(len(sep[0]), 0) self.assertEqual(len(sep[1]), 8) self.assertEqual(len(sep[2]), 0) #Test with 2 coeff facets (Normal vector = [1, 0, 0] or [0, 1, 0] or [0, 0, 1]) #Plane x-2=0 (perpendicular to x) plane = Plane.from_coefficients(-4, 0, 0, 8) sep = plane.indices_separate(plist, 0.00001) self.assertEqual(sep[0], [0, 1, 2, 3, 4]) self.assertEqual(sep[1], []) self.assertEqual(sep[2], [5, 6, 7]) sep = plane.indices_separate(plist, 1.0) self.assertEqual(sep[0], [0, 1, 2, 4]) self.assertEqual(sep[1], [3]) self.assertEqual(sep[2], [5, 6, 7]) #Plane 2y+1=0 (perpendicular to y) plane = Plane.from_coefficients(0, 2, 0, 1) sep = plane.indices_separate(plist, 0.00001) self.assertEqual(sep[0], [4]) self.assertEqual(sep[1], []) self.assertEqual(sep[2], [0, 1, 2, 3, 5, 6, 7]) sep = plane.indices_separate(plist, 1.0) self.assertEqual(sep[0], []) self.assertEqual(sep[1], [0, 1, 2, 3, 4, 7]) self.assertEqual(sep[2], [5, 6]) #Plane 4z-3=0 (perpendicular to z) plane = Plane.from_coefficients(0, 0, -4, 3) sep = plane.indices_separate(plist, 0.00001) self.assertEqual(sep[0], [0, 2, 3, 4, 5, 7]) self.assertEqual(sep[1], [1]) self.assertEqual(sep[2], [6]) sep = plane.indices_separate(plist, 0.75) self.assertEqual(sep[0], [5]) self.assertEqual(sep[1], [0, 1, 2, 3, 4, 7]) self.assertEqual(sep[2], [6]) #Test with 3 coeff facets (Normal vector = [0, a, b] or [a, 0, b] or [a, b, 0]) #Plane 2y-z+4=0 plane = Plane.from_coefficients(0, 2, -1, 0) sep = plane.indices_separate(plist, 0.00001) self.assertEqual(sep[0], [1, 4]) self.assertEqual(sep[1], [0, 2, 3, 7]) self.assertEqual(sep[2], [5, 6]) sep = plane.indices_separate(plist, 0.75) self.assertEqual(sep[0], [4]) self.assertEqual(sep[1], [0, 1, 2, 3, 7]) self.assertEqual(sep[2], [5, 6]) #Plane 2y-z+4=0 plane = Plane.from_coefficients(4, 0, -2, -20) sep = plane.indices_separate(plist, 0.00001) self.assertEqual(sep[0], [0, 1, 2, 3, 4]) self.assertEqual(sep[1], [6]) self.assertEqual(sep[2], [5, 7]) #Plane 2y-z+4=0 plane = Plane.from_coefficients(-2, 9, 0, 2) sep = plane.indices_separate(plist, 0.00001) self.assertEqual(sep[0], [0, 1, 2, 6]) self.assertEqual(sep[1], [3, 5]) self.assertEqual(sep[2], [4, 7]) def test_projections(self): #Projections of points that are already on the plane expected_projected_points = [self.p1, self.p2, self.p3, self.plane.p1, self.plane.p2, self.plane.p3] projected_points = self.plane.projectionpoints(expected_projected_points) projected_2d = self.plane.project_and_to2dim(expected_projected_points, 'mean') for ii, pp in enumerate(expected_projected_points): self.assertTrue(np.allclose(pp, projected_points[ii])) for i1, i2 in itertools.combinations(list(range(len(expected_projected_points))), 2): self.assertTrue(np.isclose(np.linalg.norm(expected_projected_points[i1]-expected_projected_points[i2]), np.linalg.norm(projected_2d[i1]-projected_2d[i2]))) #Projections of random points (check on distances between the 3D points and the 2D points) points_to_project = [np.array([5.1, 0.3, -2.3]), np.array([-2.0, 4.3, -6.3]), np.array([3.1, 2.3, -21.3]), np.array([-2, -0.5, 0.05]), np.array([11, 12, -13]), np.array([10, 8.3, -6.32])] projected_points = self.plane.projectionpoints(points_to_project) meanpoint = np.array([np.mean([pp[ii] for pp in points_to_project]) for ii in range(3)]) projected_2d = self.plane.project_and_to2dim(points_to_project, 'mean') projected_2d_bis = self.plane.project_and_to2dim(points_to_project, meanpoint) for ii, pp in enumerate(projected_2d): self.assertTrue(np.allclose(pp, projected_2d_bis[ii])) for i1, i2 in itertools.combinations(list(range(len(projected_points))), 2): self.assertTrue(np.isclose(np.linalg.norm(projected_points[i1]-projected_points[i2]), np.linalg.norm(projected_2d[i1]-projected_2d[i2]))) for ii, pp in enumerate(points_to_project): projected_2d = self.plane.project_and_to2dim([pp], pp) self.assertTrue(np.allclose(projected_2d[0], 0.0)) #Check some specific projections points = [np.zeros(3, np.float), np.array([10, 10, 10], np.float), np.array([1.2, 2.3, 3.4], np.float), np.array([-1, -2, -3], np.float), np.array([-1, 1, -1], np.float)] projected_points = self.plane.projectionpoints(points) expected_projected_points = [np.array([-0.33333333, -0.16666667, 0.33333333]), np.array([7.44444444, 8.72222222, 12.55555556]), np.array([1.33333333, 2.36666667, 3.26666667]), np.array([-1.77777778, -2.38888889, -2.22222222]), np.array([-1.55555556, 0.72222222, -0.44444444])] for ii, pp in enumerate(projected_points): self.assertTrue(np.allclose(pp, expected_projected_points[ii])) self.assertTrue(self.plane.is_in_plane(pp, 0.0000001)) projected_2d_points_000 = self.plane.project_and_to2dim(points, [0.0, 0.0, 0.0]) projected_2d_points_mean = self.plane.project_and_to2dim(points, 'mean') for i1, i2 in itertools.combinations(list(range(len(projected_2d_points_000))), 2): norm_000 = np.linalg.norm(projected_2d_points_000[i1]-projected_2d_points_000[i2]) norm_mean = np.linalg.norm(projected_2d_points_mean[i1]-projected_2d_points_mean[i2]) norm_xyz_projected = np.linalg.norm(projected_points[i1]-projected_points[i2]) self.assertTrue(np.isclose(norm_000, norm_mean)) self.assertTrue(np.isclose(norm_000, norm_xyz_projected)) if __name__ == "__main__": unittest.main()
# -*- coding: utf-8 -*- # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Integration tests for the iam command.""" from __future__ import absolute_import from collections import defaultdict import json from gslib.exception import CommandException from gslib.iamhelpers import BindingsToDict from gslib.iamhelpers import BindingStringToTuple as bstt from gslib.iamhelpers import BindingsTuple from gslib.iamhelpers import DiffBindings from gslib.iamhelpers import IsEqualBindings from gslib.iamhelpers import PatchBindings import gslib.tests.testcase as testcase from gslib.tests.testcase.integration_testcase import SkipForS3 from gslib.tests.testcase.integration_testcase import SkipForXML from gslib.tests.util import SetBotoConfigForTest from gslib.third_party.storage_apitools import storage_v1_messages as apitools_messages from gslib.util import Retry bvle = apitools_messages.Policy.BindingsValueListEntry # Feature iam_bucket_roles must be turned on in bigstore dev config for setting # the new IAM policies on buckets. IAM_BUCKET_READ_ROLE_ABBREV = 'legacyBucketReader' IAM_BUCKET_READ_ROLE = 'roles/storage.%s' % IAM_BUCKET_READ_ROLE_ABBREV # GCS IAM does not currently support new object-level roles. IAM_OBJECT_READ_ROLE = 'roles/storage.legacyObjectReader' def gen_binding(role, members=None): """Generate an IAM Policy object dictionary. Generates Python dictionary representation of a storage_v1_messages.Policy object with a single storage_v1_messages.Policy.BindingsValueListEntry. Args: role: An IAM policy role (e.g. "roles/storage.objectViewer"). Fully specified in BindingsValueListEntry. members: A list of members (e.g. ["user:[email protected]"]). If None, bind to ["allUsers"]. Fully specified in BindingsValueListEntry. Returns: A Python dict representation of an IAM Policy object. """ if members is None: members = ['allUsers'] return [ { 'members': members, 'role': role, } ] class TestIamIntegration(testcase.GsUtilIntegrationTestCase): """Superclass for iam integration test cases.""" def assertEqualsPoliciesString(self, a, b): """Asserts two serialized policy bindings are equal.""" expected = [ bvle( members=binding_dict['members'], role=binding_dict['role']) for binding_dict in json.loads(a)['bindings']] result = [ bvle( members=binding_dict['members'], role=binding_dict['role']) for binding_dict in json.loads(b)['bindings']] self.assertTrue(IsEqualBindings(expected, result)) @SkipForS3('Tests use GS IAM model.') @SkipForXML('XML IAM control is not supported.') class TestIamHelpers(testcase.GsUtilUnitTestCase): """Unit tests for iam command helper.""" def test_convert_bindings_simple(self): """Tests that Policy.bindings lists are converted to dicts properly.""" self.assertEquals(BindingsToDict([]), defaultdict(set)) expected = defaultdict(set, {'x': set(['y'])}) self.assertEquals( BindingsToDict([bvle(role='x', members=['y'])]), expected) def test_convert_bindings_duplicates(self): """Test that role and member duplication are converted correctly.""" expected = defaultdict(set, {'x': set(['y', 'z'])}) duplicate_roles = [ bvle(role='x', members=['y']), bvle(role='x', members=['z'])] duplicate_members = [ bvle(role='x', members=['z', 'y']), bvle(role='x', members=['z'])] self.assertEquals(BindingsToDict(duplicate_roles), expected) self.assertEquals(BindingsToDict(duplicate_members), expected) def test_equality_bindings_literal(self): """Tests an easy case of identical bindings.""" bindings = [bvle(role='x', members=['y'])] self.assertTrue(IsEqualBindings([], [])) self.assertTrue(IsEqualBindings(bindings, bindings)) def test_equality_bindings_extra_roles(self): """Tests bindings equality when duplicate roles are added.""" bindings = [bvle(role='x', members=['x', 'y'])] bindings2 = bindings * 2 bindings3 = [ bvle(role='x', members=['y']), bvle(role='x', members=['x']), ] self.assertTrue(IsEqualBindings(bindings, bindings2)) self.assertTrue(IsEqualBindings(bindings, bindings3)) def test_diff_bindings_add_role(self): """Tests simple grant behavior of Policy.bindings diff.""" expected = [bvle(role='x', members=['y'])] (granted, removed) = DiffBindings([], expected) self.assertEquals(granted.bindings, expected) self.assertEquals(removed.bindings, []) def test_diff_bindings_drop_role(self): """Tests simple remove behavior of Policy.bindings diff.""" expected = [bvle(role='x', members=['y'])] (granted, removed) = DiffBindings(expected, []) self.assertEquals(granted.bindings, []) self.assertEquals(removed.bindings, expected) def test_diff_bindings_swap_role(self): """Tests expected behavior of switching a role.""" old = [bvle(role='x', members=['y'])] new = [bvle(role='a', members=['b'])] (granted, removed) = DiffBindings(old, new) self.assertEquals(granted.bindings, new) self.assertEquals(removed.bindings, old) def test_diff_bindings_add_member(self): """Tests expected behavior of adding a member to a role.""" old = [bvle(role='x', members=['y'])] new = [bvle(role='x', members=['z', 'y'])] expected = [bvle(role='x', members=['z'])] (granted, removed) = DiffBindings(old, new) self.assertEquals(granted.bindings, expected) self.assertEquals(removed.bindings, []) def test_diff_bindings_drop_member(self): """Tests expected behavior of dropping a member from a role.""" old = [bvle(role='x', members=['z', 'y'])] new = [bvle(role='x', members=['y'])] expected = [bvle(role='x', members=['z'])] (granted, removed) = DiffBindings(old, new) self.assertEquals(granted.bindings, []) self.assertEquals(removed.bindings, expected) def test_diff_bindings_swap_member(self): """Tests expected behavior of switching a member in a role.""" old = [bvle(role='x', members=['z'])] new = [bvle(role='x', members=['y'])] (granted, removed) = DiffBindings(old, new) self.assertEquals(granted.bindings, new) self.assertEquals(removed.bindings, old) def test_patch_bindings_grant(self): """Tests patching a grant binding.""" base = [ bvle(role='a', members=['user:[email protected]']), bvle(role='b', members=['user:[email protected]']), bvle(role='c', members=['user:[email protected]']), ] diff = [ bvle(role='d', members=['user:[email protected]']), ] expected = base + diff res = PatchBindings(base, BindingsTuple(True, diff)) self.assertTrue(IsEqualBindings(res, expected)) def test_patch_bindings_remove(self): """Tests patching a remove binding.""" base = [ bvle(members=['user:[email protected]'], role='a'), bvle(members=['user:[email protected]'], role='b'), bvle(members=['user:[email protected]'], role='c'), ] diff = [ bvle(members=['user:[email protected]'], role='a'), ] expected = [ bvle(members=['user:[email protected]'], role='b'), bvle(members=['user:[email protected]'], role='c'), ] res = PatchBindings(base, BindingsTuple(False, diff)) self.assertTrue(IsEqualBindings(res, expected)) def test_patch_bindings_remove_all(self): """Tests removing all roles from a member.""" base = [ bvle(members=['user:[email protected]'], role='a'), bvle(members=['user:[email protected]'], role='b'), bvle(members=['user:[email protected]'], role='c'), ] diff = [ bvle(members=['user:[email protected]'], role=''), ] res = PatchBindings(base, BindingsTuple(False, diff)) self.assertEquals(res, []) diff = [ bvle(members=['user:[email protected]'], role='a'), bvle(members=['user:[email protected]'], role='b'), bvle(members=['user:[email protected]'], role='c'), ] res = PatchBindings(base, BindingsTuple(False, diff)) self.assertEquals(res, []) def test_patch_bindings_multiple_users(self): """Tests expected behavior when multiple users exist.""" expected = [ bvle(members=['user:[email protected]'], role='b'), ] base = [ bvle(members=['user:[email protected]'], role='a'), bvle(members=['user:[email protected]', 'user:[email protected]'], role='b'), bvle(members=['user:[email protected]'], role='c'), ] diff = [ bvle(members=['user:[email protected]'], role='a'), bvle(members=['user:[email protected]'], role='b'), bvle(members=['user:[email protected]'], role='c'), ] res = PatchBindings(base, BindingsTuple(False, diff)) self.assertTrue(IsEqualBindings(res, expected)) def test_patch_bindings_grant_all_users(self): """Tests a public member grant.""" base = [ bvle(role='a', members=['user:[email protected]']), bvle(role='b', members=['user:[email protected]']), bvle(role='c', members=['user:[email protected]']), ] diff = [ bvle(role='a', members=['allUsers']), ] expected = [ bvle(role='a', members=['allUsers', 'user:[email protected]']), bvle(role='b', members=['user:[email protected]']), bvle(role='c', members=['user:[email protected]']), ] res = PatchBindings(base, BindingsTuple(True, diff)) self.assertTrue(IsEqualBindings(res, expected)) def test_patch_bindings_public_member_overwrite(self): """Tests public member vs. public member interaction.""" base = [ bvle(role='a', members=['allUsers']), ] diff = [ bvle(role='a', members=['allAuthenticatedUsers']), ] res = PatchBindings(base, BindingsTuple(True, diff)) self.assertTrue(IsEqualBindings(res, base + diff)) def test_valid_public_member_single_role(self): """Tests parsing single role.""" (_, bindings) = bstt(True, 'allUsers:admin') self.assertEquals(len(bindings), 1) self.assertIn( bvle(members=['allUsers'], role='roles/storage.admin'), bindings) def test_grant_no_role_error(self): """Tests that an error is raised when no role is specified for a grant.""" with self.assertRaises(CommandException): bstt(True, 'allUsers') with self.assertRaises(CommandException): bstt(True, 'user:[email protected]') with self.assertRaises(CommandException): bstt(True, 'user:[email protected]:') def test_remove_all_roles(self): """Tests parsing a -d allUsers or -d user:[email protected] request.""" # Input specifies remove all roles from allUsers. (is_grant, bindings) = bstt(False, 'allUsers') self.assertEquals(len(bindings), 1) self.assertIn(bvle(members=['allUsers'], role=''), bindings) self.assertEquals((is_grant, bindings), bstt(False, 'allUsers:')) # Input specifies remove all roles from a user. (_, bindings) = bstt(False, 'user:[email protected]') self.assertEquals(len(bindings), 1) def test_valid_multiple_roles(self): """Tests parsing of multiple roles bound to one user.""" (_, bindings) = bstt(True, 'allUsers:a,b,c') self.assertEquals(len(bindings), 3) self.assertIn(bvle(members=['allUsers'], role='roles/storage.a'), bindings) self.assertIn(bvle(members=['allUsers'], role='roles/storage.b'), bindings) self.assertIn(bvle(members=['allUsers'], role='roles/storage.c'), bindings) def test_valid_member(self): """Tests member parsing.""" (_, bindings) = bstt(True, 'user:[email protected]:admin') self.assertEquals(len(bindings), 1) self.assertIn( bvle( members=['user:[email protected]'], role='roles/storage.admin'), bindings) def test_duplicate_roles(self): """Tests that duplicate roles are ignored.""" (_, bindings) = bstt(True, 'allUsers:a,a') self.assertEquals(len(bindings), 1) self.assertIn(bvle(members=['allUsers'], role='roles/storage.a'), bindings) def test_invalid_input(self): """Tests invalid input handling.""" with self.assertRaises(CommandException): bstt(True, 'non_valid_public_member:role') with self.assertRaises(CommandException): bstt(True, 'non_valid_type:id:role') with self.assertRaises(CommandException): bstt(True, 'user:r') with self.assertRaises(CommandException): bstt(True, 'projectViewer:123424:admin') def test_invalid_n_args(self): """Tests invalid input due to too many colons.""" with self.assertRaises(CommandException): bstt(True, 'allUsers:some_id:some_role') with self.assertRaises(CommandException): bstt(True, 'user:[email protected]:r:nonsense') @SkipForS3('Tests use GS IAM model.') @SkipForXML('XML IAM control is not supported.') class TestIamCh(TestIamIntegration): """Integration tests for iam ch command.""" def setUp(self): super(TestIamCh, self).setUp() self.bucket = self.CreateBucket() self.bucket2 = self.CreateBucket() self.object = self.CreateObject(bucket_uri=self.bucket, contents='foo') self.object2 = self.CreateObject(bucket_uri=self.bucket, contents='bar') self.bucket_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.object_iam_string = self.RunGsUtil( ['iam', 'get', self.object.uri], return_stdout=True) self.object2_iam_string = self.RunGsUtil( ['iam', 'get', self.object2.uri], return_stdout=True) self.user = 'user:[email protected]' self.user2 = 'user:[email protected]' def test_patch_no_role(self): """Tests expected failure if no bindings are listed.""" stderr = self.RunGsUtil( ['iam', 'ch', self.bucket.uri], return_stderr=True, expected_status=1) self.assertIn('CommandException', stderr) def test_patch_single_grant_single_bucket(self): """Tests granting single role.""" self.assertHasNo( self.bucket_iam_string, self.user, IAM_BUCKET_READ_ROLE) self.RunGsUtil( ['iam', 'ch', '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri]) bucket_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.assertHas(bucket_iam_string, self.user, IAM_BUCKET_READ_ROLE) def test_patch_repeated_grant(self): """Granting multiple times for the same member will have no effect.""" self.RunGsUtil( ['iam', 'ch', '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri]) self.RunGsUtil( ['iam', 'ch', '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri]) bucket_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.assertHas(bucket_iam_string, self.user, IAM_BUCKET_READ_ROLE) def test_patch_single_remove_single_bucket(self): """Tests removing a single role.""" self.RunGsUtil( ['iam', 'ch', '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri]) self.RunGsUtil( ['iam', 'ch', '-d', '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri]) bucket_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.assertHasNo( bucket_iam_string, self.user, IAM_BUCKET_READ_ROLE) def test_patch_null_remove(self): """Removing a non-existent binding will have no effect.""" self.RunGsUtil( ['iam', 'ch', '-d', '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri]) bucket_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.assertHasNo( bucket_iam_string, self.user, IAM_BUCKET_READ_ROLE) self.assertEqualsPoliciesString(bucket_iam_string, self.bucket_iam_string) def test_patch_mixed_grant_remove_single_bucket(self): """Tests that mixing grant and remove requests will succeed.""" self.RunGsUtil( ['iam', 'ch', '%s:%s' % (self.user2, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri]) self.RunGsUtil( ['iam', 'ch', '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), '-d', '%s:%s' % (self.user2, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri]) bucket_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.assertHas(bucket_iam_string, self.user, IAM_BUCKET_READ_ROLE) self.assertHasNo( bucket_iam_string, self.user2, IAM_BUCKET_READ_ROLE) def test_patch_public_grant_single_bucket(self): """Test public grant request interacts properly with existing members.""" self.RunGsUtil( ['iam', 'ch', '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri]) self.RunGsUtil(['iam', 'ch', 'allUsers:%s' % IAM_BUCKET_READ_ROLE_ABBREV, self.bucket.uri]) bucket_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.assertHas(bucket_iam_string, 'allUsers', IAM_BUCKET_READ_ROLE) self.assertHas( bucket_iam_string, self.user, IAM_BUCKET_READ_ROLE) def test_patch_remove_all_roles(self): """Remove with no roles specified will remove member from all bindings.""" self.RunGsUtil( ['iam', 'ch', '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri]) self.RunGsUtil(['iam', 'ch', '-d', self.user, self.bucket.uri]) bucket_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.assertHasNo( bucket_iam_string, self.user, IAM_BUCKET_READ_ROLE) def test_patch_single_object(self): """Tests object IAM patch behavior.""" self.assertHasNo( self.object_iam_string, self.user, IAM_OBJECT_READ_ROLE) self.RunGsUtil( ['iam', 'ch', '%s:legacyObjectReader' % self.user, self.object.uri]) object_iam_string = self.RunGsUtil( ['iam', 'get', self.object.uri], return_stdout=True) self.assertHas( object_iam_string, self.user, IAM_OBJECT_READ_ROLE) def test_patch_multithreaded_single_object(self): """Tests the edge-case behavior of multithreaded execution.""" self.assertHasNo( self.object_iam_string, self.user, IAM_OBJECT_READ_ROLE) self.RunGsUtil( ['-m', 'iam', 'ch', '%s:legacyObjectReader' % self.user, self.object.uri]) object_iam_string = self.RunGsUtil( ['iam', 'get', self.object.uri], return_stdout=True) self.assertHas( object_iam_string, self.user, IAM_OBJECT_READ_ROLE) def test_patch_invalid_input(self): """Tests that listing bindings after a bucket will throw an error.""" stderr = self.RunGsUtil( ['iam', 'ch', '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri, '%s:%s' % (self.user2, IAM_BUCKET_READ_ROLE_ABBREV)], return_stderr=True, expected_status=1) self.assertIn('CommandException', stderr) bucket_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.assertHas(bucket_iam_string, self.user, IAM_BUCKET_READ_ROLE) self.assertHasNo( bucket_iam_string, self.user2, IAM_BUCKET_READ_ROLE) def test_patch_multiple_objects(self): """Tests IAM patch against multiple objects.""" self.RunGsUtil( ['iam', 'ch', '-r', '%s:legacyObjectReader' % self.user, self.bucket.uri]) object_iam_string = self.RunGsUtil( ['iam', 'get', self.object.uri], return_stdout=True) object2_iam_string = self.RunGsUtil( ['iam', 'get', self.object2.uri], return_stdout=True) self.assertHas( object_iam_string, self.user, IAM_OBJECT_READ_ROLE) self.assertHas( object2_iam_string, self.user, IAM_OBJECT_READ_ROLE) def test_patch_multithreaded_multiple_objects(self): """Tests multithreaded behavior against multiple objects.""" self.RunGsUtil( ['-m', 'iam', 'ch', '-r', '%s:legacyObjectReader' % self.user, self.bucket.uri]) object_iam_string = self.RunGsUtil( ['iam', 'get', self.object.uri], return_stdout=True) object2_iam_string = self.RunGsUtil( ['iam', 'get', self.object2.uri], return_stdout=True) self.assertHas( object_iam_string, self.user, IAM_OBJECT_READ_ROLE) self.assertHas( object2_iam_string, self.user, IAM_OBJECT_READ_ROLE) def test_patch_error(self): """See TestIamSet.test_set_error.""" stderr = self.RunGsUtil( ['iam', 'ch', '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri, 'gs://%s' % self.nonexistent_bucket_name, self.bucket2.uri], return_stderr=True, expected_status=1) self.assertIn('BucketNotFoundException', stderr) bucket_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) bucket2_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket2.uri], return_stdout=True) self.assertHas(bucket_iam_string, self.user, IAM_BUCKET_READ_ROLE) self.assertEqualsPoliciesString(bucket2_iam_string, self.bucket_iam_string) def test_patch_force_error(self): """See TestIamSet.test_set_force_error.""" stderr = self.RunGsUtil( ['iam', 'ch', '-f', '%s:%s' % (self.user, IAM_BUCKET_READ_ROLE_ABBREV), self.bucket.uri, 'gs://%s' % self.nonexistent_bucket_name, self.bucket2.uri], return_stderr=True, expected_status=1) self.assertIn('CommandException', stderr) bucket_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) bucket2_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket2.uri], return_stdout=True) self.assertHas(bucket_iam_string, self.user, IAM_BUCKET_READ_ROLE) self.assertHas(bucket2_iam_string, self.user, IAM_BUCKET_READ_ROLE) def test_patch_multithreaded_error(self): """See TestIamSet.test_set_multithreaded_error.""" stderr = self.RunGsUtil( ['-m', 'iam', 'ch', '-r', '%s:legacyObjectReader' % self.user, 'gs://%s' % self.nonexistent_bucket_name, self.bucket.uri], return_stderr=True, expected_status=1) self.assertIn('BucketNotFoundException', stderr) object_iam_string = self.RunGsUtil( ['iam', 'get', self.object.uri], return_stdout=True) object2_iam_string = self.RunGsUtil( ['iam', 'get', self.object2.uri], return_stdout=True) self.assertEqualsPoliciesString(self.object_iam_string, object_iam_string) self.assertEqualsPoliciesString(self.object_iam_string, object2_iam_string) def test_assert_has(self): test_policy = { 'bindings': [ {'members': ['allUsers'], 'role': 'roles/storage.admin'}, {'members': ['user:[email protected]', 'serviceAccount:[email protected]'], 'role': IAM_BUCKET_READ_ROLE} ] } self.assertHas(json.dumps(test_policy), 'allUsers', 'roles/storage.admin') self.assertHas( json.dumps(test_policy), 'user:[email protected]', IAM_BUCKET_READ_ROLE) self.assertHasNo( json.dumps(test_policy), 'allUsers', IAM_BUCKET_READ_ROLE) self.assertHasNo( json.dumps(test_policy), 'user:[email protected]', 'roles/storage.admin') def assertHas(self, policy, member, role): """Asserts a member has permission for role. Given an IAM policy, check if the specified member is bound to the specified role. Does not check group inheritence -- that is, if checking against the [{'member': ['allUsers'], 'role': X}] policy, this function will still raise an exception when testing for any member other than 'allUsers' against role X. This function does not invoke the TestIamPolicy endpoints to smartly check IAM policy resolution. This function is simply to assert the expected IAM policy is returned, not whether or not the IAM policy is being invoked as expected. Args: policy: Policy object as formatted by IamCommand._GetIam() member: A member string (e.g. 'user:[email protected]'). role: A fully specified role (e.g. 'roles/storage.admin') Raises: AssertionError if member is not bound to role. """ policy = json.loads(policy) bindings = dict((p['role'], p) for p in policy.get('bindings', [])) if role in bindings: if member in bindings[role]['members']: return raise AssertionError('Member \'%s\' does not have permission \'%s\' in ' 'policy %s' % (member, role, policy)) def assertHasNo(self, policy, member, role): """Functions as logical compliment of TestIamCh.assertHas().""" try: self.assertHas(policy, member, role) except AssertionError: pass else: raise AssertionError('Member \'%s\' has permission \'%s\' in ' 'policy %s' % (member, role, policy)) @SkipForS3('Tests use GS IAM model.') @SkipForXML('XML IAM control is not supported.') class TestIamSet(TestIamIntegration): """Integration tests for iam set command.""" def _patch_binding(self, policy, role, new_policy): """Returns a patched Python object representation of a Policy. Given replaces the original role:members binding in policy with new_policy. Args: policy: Python dict representation of a Policy instance. role: An IAM policy role (e.g. "roles/storage.objectViewer"). Fully specified in BindingsValueListEntry. new_policy: A Python dict representation of a Policy instance, with a single BindingsValueListEntry entry. Returns: A Python dict representation of the patched IAM Policy object. """ bindings = [ b for b in policy.get('bindings', []) if b.get('role', '') != role] bindings.extend(new_policy) policy = dict(policy) policy['bindings'] = bindings return policy # TODO(iam-beta): Replace gen_binding, _patch_binding with generators from # iamhelpers. def setUp(self): super(TestIamSet, self).setUp() self.public_bucket_read_binding = gen_binding(IAM_BUCKET_READ_ROLE) self.public_object_read_binding = gen_binding(IAM_OBJECT_READ_ROLE) self.bucket = self.CreateBucket() self.versioned_bucket = self.CreateVersionedBucket() self.bucket_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.old_bucket_iam_path = self.CreateTempFile( contents=self.bucket_iam_string) self.new_bucket_iam_policy = self._patch_binding( json.loads(self.bucket_iam_string), IAM_BUCKET_READ_ROLE, self.public_bucket_read_binding) self.new_bucket_iam_path = self.CreateTempFile( contents=json.dumps(self.new_bucket_iam_policy)) # Create a temporary object to get the IAM policy. tmp_object = self.CreateObject(contents='foobar') self.object_iam_string = self.RunGsUtil( ['iam', 'get', tmp_object.uri], return_stdout=True) self.old_object_iam_path = self.CreateTempFile( contents=self.object_iam_string) self.new_object_iam_policy = self._patch_binding( json.loads(self.object_iam_string), IAM_OBJECT_READ_ROLE, self.public_object_read_binding) self.new_object_iam_path = self.CreateTempFile( contents=json.dumps(self.new_object_iam_policy)) def test_seek_ahead_iam(self): """Ensures that the seek-ahead iterator is being used with iam commands.""" gsutil_object = self.CreateObject( bucket_uri=self.bucket, contents='foobar') # This forces the seek-ahead iterator to be utilized. with SetBotoConfigForTest([('GSUtil', 'task_estimation_threshold', '1'), ('GSUtil', 'task_estimation_force', 'True')]): stderr = self.RunGsUtil( ['-m', 'iam', 'set', self.new_object_iam_path, gsutil_object.uri], return_stderr=True) self.assertIn('Estimated work for this command: objects: 1\n', stderr) def test_set_invalid_iam_bucket(self): """Ensures invalid content returns error on input check.""" inpath = self.CreateTempFile(contents='badIam') stderr = self.RunGsUtil(['iam', 'set', inpath, self.bucket.uri], return_stderr=True, expected_status=1) self.assertIn('ArgumentException', stderr) # Tests that setting with a non-existent file will also return error. stderr = self.RunGsUtil( ['iam', 'set', 'nonexistent/path', self.bucket.uri], return_stderr=True, expected_status=1) self.assertIn('ArgumentException', stderr) def test_get_invalid_bucket(self): """Ensures that invalid bucket names returns an error.""" stderr = self.RunGsUtil(['iam', 'get', self.nonexistent_bucket_name], return_stderr=True, expected_status=1) self.assertIn('CommandException', stderr) stderr = self.RunGsUtil(['iam', 'get', 'gs://%s' % self.nonexistent_bucket_name], return_stderr=True, expected_status=1) self.assertIn('BucketNotFoundException', stderr) # N.B.: The call to wildcard_iterator.WildCardIterator here will invoke # ListBucket, which only promises eventual consistency. We use @Retry here # to mitigate errors due to this. @Retry(AssertionError, tries=3, timeout_secs=1) def _Check(): # pylint: disable=invalid-name # There are at least two buckets in the project # due to TestIamSet.setUp(). stderr = self.RunGsUtil(['iam', 'get', 'gs://*'], return_stderr=True, expected_status=1) self.assertIn('CommandException', stderr) _Check() def test_set_valid_iam_bucket(self): """Tests setting a valid IAM on a bucket.""" self.RunGsUtil( ['iam', 'set', '-e', '', self.new_bucket_iam_path, self.bucket.uri]) set_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.RunGsUtil( ['iam', 'set', '-e', '', self.old_bucket_iam_path, self.bucket.uri]) reset_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.assertEqualsPoliciesString(self.bucket_iam_string, reset_iam_string) self.assertIn( self.public_bucket_read_binding[0], json.loads(set_iam_string)['bindings']) def test_set_blank_etag(self): """Tests setting blank etag behaves appropriately.""" self.RunGsUtil( ['iam', 'set', '-e', '', self.new_bucket_iam_path, self.bucket.uri]) set_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.RunGsUtil( ['iam', 'set', '-e', json.loads(set_iam_string)['etag'], self.old_bucket_iam_path, self.bucket.uri]) reset_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.assertEqualsPoliciesString(self.bucket_iam_string, reset_iam_string) self.assertIn( self.public_bucket_read_binding[0], json.loads(set_iam_string)['bindings']) def test_set_valid_etag(self): """Tests setting valid etag behaves correctly.""" get_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.RunGsUtil( ['iam', 'set', '-e', json.loads(get_iam_string)['etag'], self.new_bucket_iam_path, self.bucket.uri]) set_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.RunGsUtil( ['iam', 'set', '-e', json.loads(set_iam_string)['etag'], self.old_bucket_iam_path, self.bucket.uri]) reset_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.assertEqualsPoliciesString(self.bucket_iam_string, reset_iam_string) self.assertIn( self.public_bucket_read_binding[0], json.loads(set_iam_string)['bindings']) def test_set_invalid_etag(self): """Tests setting an invalid etag format raises an error.""" self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) stderr = self.RunGsUtil( ['iam', 'set', '-e', 'some invalid etag', self.new_bucket_iam_path, self.bucket.uri], return_stderr=True, expected_status=1) self.assertIn('ArgumentException', stderr) def test_set_mismatched_etag(self): """Tests setting mismatched etag raises an error.""" get_iam_string = self.RunGsUtil( ['iam', 'get', self.bucket.uri], return_stdout=True) self.RunGsUtil( ['iam', 'set', '-e', json.loads(get_iam_string)['etag'], self.new_bucket_iam_path, self.bucket.uri]) stderr = self.RunGsUtil( ['iam', 'set', '-e', json.loads(get_iam_string)['etag'], self.new_bucket_iam_path, self.bucket.uri], return_stderr=True, expected_status=1) self.assertIn('PreconditionException', stderr) def _create_multiple_objects(self): """Creates two versioned objects and return references to all versions. Returns: A four-tuple (a, b, a*, b*) of storage_uri.BucketStorageUri instances. """ old_gsutil_object = self.CreateObject( bucket_uri=self.versioned_bucket, contents='foo') old_gsutil_object2 = self.CreateObject( bucket_uri=self.versioned_bucket, contents='bar') gsutil_object = self.CreateObject( bucket_uri=self.versioned_bucket, object_name=old_gsutil_object.object_name, contents='new_foo') gsutil_object2 = self.CreateObject( bucket_uri=self.versioned_bucket, object_name=old_gsutil_object2.object_name, contents='new_bar') return (old_gsutil_object, old_gsutil_object2, gsutil_object, gsutil_object2) def test_set_valid_iam_multiple_objects(self): """Tests setting a valid IAM on multiple objects.""" (old_gsutil_object, old_gsutil_object2, gsutil_object, gsutil_object2) = self._create_multiple_objects() # Set IAM policy on newest versions of all objects. self.RunGsUtil(['iam', 'set', '-r', self.new_object_iam_path, self.versioned_bucket.uri]) set_iam_string = self.RunGsUtil( ['iam', 'get', gsutil_object.uri], return_stdout=True) set_iam_string2 = self.RunGsUtil( ['iam', 'get', gsutil_object2.uri], return_stdout=True) self.assertEqualsPoliciesString(set_iam_string, set_iam_string2) self.assertIn( self.public_object_read_binding[0], json.loads(set_iam_string)['bindings']) # Check that old versions are not affected by the set IAM call. iam_string_old = self.RunGsUtil( ['iam', 'get', old_gsutil_object.version_specific_uri], return_stdout=True) iam_string_old2 = self.RunGsUtil( ['iam', 'get', old_gsutil_object2.version_specific_uri], return_stdout=True) self.assertEqualsPoliciesString(iam_string_old, iam_string_old2) self.assertEqualsPoliciesString(self.object_iam_string, iam_string_old) def test_set_valid_iam_multithreaded_multiple_objects(self): """Tests setting a valid IAM on multiple objects.""" (old_gsutil_object, old_gsutil_object2, gsutil_object, gsutil_object2) = self._create_multiple_objects() # Set IAM policy on newest versions of all objects. self.RunGsUtil(['-m', 'iam', 'set', '-r', self.new_object_iam_path, self.versioned_bucket.uri]) set_iam_string = self.RunGsUtil( ['iam', 'get', gsutil_object.uri], return_stdout=True) set_iam_string2 = self.RunGsUtil( ['iam', 'get', gsutil_object2.uri], return_stdout=True) self.assertEqualsPoliciesString(set_iam_string, set_iam_string2) self.assertIn( self.public_object_read_binding[0], json.loads(set_iam_string)['bindings']) # Check that old versions are not affected by the set IAM call. iam_string_old = self.RunGsUtil( ['iam', 'get', old_gsutil_object.version_specific_uri], return_stdout=True) iam_string_old2 = self.RunGsUtil( ['iam', 'get', old_gsutil_object2.version_specific_uri], return_stdout=True) self.assertEqualsPoliciesString(iam_string_old, iam_string_old2) self.assertEqualsPoliciesString(self.object_iam_string, iam_string_old) def test_set_valid_iam_multiple_objects_all_versions(self): """Tests set IAM policy on all versions of all objects.""" (old_gsutil_object, old_gsutil_object2, gsutil_object, gsutil_object2) = self._create_multiple_objects() self.RunGsUtil(['iam', 'set', '-ra', self.new_object_iam_path, self.versioned_bucket.uri]) set_iam_string = self.RunGsUtil( ['iam', 'get', gsutil_object.version_specific_uri], return_stdout=True) set_iam_string2 = self.RunGsUtil( ['iam', 'get', gsutil_object2.version_specific_uri], return_stdout=True) set_iam_string_old = self.RunGsUtil( ['iam', 'get', old_gsutil_object.version_specific_uri], return_stdout=True) set_iam_string_old2 = self.RunGsUtil( ['iam', 'get', old_gsutil_object2.version_specific_uri], return_stdout=True) self.assertEqualsPoliciesString(set_iam_string, set_iam_string2) self.assertEqualsPoliciesString(set_iam_string, set_iam_string_old) self.assertEqualsPoliciesString(set_iam_string, set_iam_string_old2) self.assertIn( self.public_object_read_binding[0], json.loads(set_iam_string)['bindings']) def test_set_error(self): """Tests fail-fast behavior of iam set. We initialize two buckets (bucket, bucket2) and attempt to set both along with a third, non-existent bucket in between, self.nonexistent_bucket_name. We want to ensure 1.) Bucket "bucket" IAM policy has been set appropriately, 2.) Bucket self.nonexistent_bucket_name has caused an error, and 3.) gsutil has exited and "bucket2"'s IAM policy is unaltered. """ bucket = self.CreateBucket() bucket2 = self.CreateBucket() stderr = self.RunGsUtil(['iam', 'set', '-e', '', self.new_bucket_iam_path, bucket.uri, 'gs://%s' % self.nonexistent_bucket_name, bucket2.uri], return_stderr=True, expected_status=1) # The program has exited due to a bucket lookup 404. self.assertIn('BucketNotFoundException', stderr) set_iam_string = self.RunGsUtil( ['iam', 'get', bucket.uri], return_stdout=True) set_iam_string2 = self.RunGsUtil( ['iam', 'get', bucket2.uri], return_stdout=True) # The IAM policy has been set on Bucket "bucket". self.assertIn( self.public_bucket_read_binding[0], json.loads(set_iam_string)['bindings']) # The IAM policy for Bucket "bucket2" remains unchanged. self.assertEqualsPoliciesString(self.bucket_iam_string, set_iam_string2) def test_set_force_error(self): """Tests ignoring failure behavior of iam set. Similar to TestIamSet.test_set_error, except here we want to ensure 1.) Bucket "bucket" IAM policy has been set appropriately, 2.) Bucket self.nonexistent_bucket_name has caused an error, BUT 3.) gsutil has continued and "bucket2"'s IAM policy has been set as well. """ bucket = self.CreateBucket() bucket2 = self.CreateBucket() stderr = self.RunGsUtil(['iam', 'set', '-f', self.new_bucket_iam_path, bucket.uri, 'gs://%s' % self.nonexistent_bucket_name, bucket2.uri], return_stderr=True, expected_status=1) # The program asserts that an error has occured (due to 404). self.assertIn('CommandException', stderr) set_iam_string = self.RunGsUtil( ['iam', 'get', bucket.uri], return_stdout=True) set_iam_string2 = self.RunGsUtil( ['iam', 'get', bucket2.uri], return_stdout=True) # The IAM policy has been set appropriately on Bucket "bucket". self.assertIn( self.public_bucket_read_binding[0], json.loads(set_iam_string)['bindings']) # The IAM policy has also been set on Bucket "bucket2". self.assertEqualsPoliciesString(set_iam_string, set_iam_string2) def test_set_multithreaded_error(self): """Tests fail-fast behavior of multithreaded iam set. This is testing gsutil iam set with the -m and -r flags present in invocation. N.B.: Currently, (-m, -r) behaves identically to (-m, -fr) and (-fr,). However, (-m, -fr) and (-fr,) behavior is not as expected due to name_expansion.NameExpansionIterator.next raising problematic e.g. 404 or 403 errors. More details on this issue can be found in comments in commands.iam.IamCommand._SetIam. Thus, the following command gsutil -m iam set -fr <object_policy> gs://bad_bucket gs://good_bucket will NOT set policies on objects in gs://good_bucket due to an error when iterating over gs://bad_bucket. """ gsutil_object = self.CreateObject(bucket_uri=self.bucket, contents='foobar') gsutil_object2 = self.CreateObject( bucket_uri=self.bucket, contents='foobar') stderr = self.RunGsUtil(['-m', 'iam', 'set', '-r', self.new_object_iam_path, 'gs://%s' % self.nonexistent_bucket_name, self.bucket.uri], return_stderr=True, expected_status=1) self.assertIn('BucketNotFoundException', stderr) set_iam_string = self.RunGsUtil( ['iam', 'get', gsutil_object.uri], return_stdout=True) set_iam_string2 = self.RunGsUtil( ['iam', 'get', gsutil_object2.uri], return_stdout=True) self.assertEqualsPoliciesString(set_iam_string, set_iam_string2) self.assertEqualsPoliciesString(self.object_iam_string, set_iam_string) def test_set_valid_iam_single_unversioned_object(self): """Tests setting a valid IAM on an object.""" gsutil_object = self.CreateObject(bucket_uri=self.bucket, contents='foobar') lookup_uri = gsutil_object.uri self.RunGsUtil(['iam', 'set', self.new_object_iam_path, lookup_uri]) set_iam_string = self.RunGsUtil( ['iam', 'get', lookup_uri], return_stdout=True) self.RunGsUtil( ['iam', 'set', '-e', json.loads(set_iam_string)['etag'], self.old_object_iam_path, lookup_uri]) reset_iam_string = self.RunGsUtil( ['iam', 'get', lookup_uri], return_stdout=True) self.assertEqualsPoliciesString(self.object_iam_string, reset_iam_string) self.assertIn( self.public_object_read_binding[0], json.loads(set_iam_string)['bindings']) def test_set_valid_iam_single_versioned_object(self): """Tests setting a valid IAM on a versioned object.""" gsutil_object = self.CreateObject(bucket_uri=self.bucket, contents='foobar') lookup_uri = gsutil_object.version_specific_uri self.RunGsUtil(['iam', 'set', self.new_object_iam_path, lookup_uri]) set_iam_string = self.RunGsUtil( ['iam', 'get', lookup_uri], return_stdout=True) self.RunGsUtil( ['iam', 'set', '-e', json.loads(set_iam_string)['etag'], self.old_object_iam_path, lookup_uri]) reset_iam_string = self.RunGsUtil( ['iam', 'get', lookup_uri], return_stdout=True) self.assertEqualsPoliciesString(self.object_iam_string, reset_iam_string) self.assertIn( self.public_object_read_binding[0], json.loads(set_iam_string)['bindings']) def test_set_valid_iam_multithreaded_single_object(self): """Tests setting a valid IAM on a single object with multithreading.""" gsutil_object = self.CreateObject(bucket_uri=self.bucket, contents='foobar') lookup_uri = gsutil_object.version_specific_uri self.RunGsUtil( ['-m', 'iam', 'set', '-e', '', self.new_object_iam_path, lookup_uri]) set_iam_string = self.RunGsUtil( ['iam', 'get', lookup_uri], return_stdout=True) self.RunGsUtil( ['-m', 'iam', 'set', '-e', '', self.old_object_iam_path, lookup_uri]) reset_iam_string = self.RunGsUtil( ['iam', 'get', lookup_uri], return_stdout=True) self.assertEqualsPoliciesString(self.object_iam_string, reset_iam_string) self.assertIn( self.public_object_read_binding[0], json.loads(set_iam_string)['bindings']) # Test multithreading on single object, specified with wildcards. lookup_uri = '%s*' % self.bucket.uri self.RunGsUtil( ['-m', 'iam', 'set', '-e', '', self.new_object_iam_path, lookup_uri]) set_iam_string = self.RunGsUtil( ['iam', 'get', lookup_uri], return_stdout=True) self.RunGsUtil( ['-m', 'iam', 'set', '-e', '', self.old_object_iam_path, lookup_uri]) reset_iam_string = self.RunGsUtil( ['iam', 'get', lookup_uri], return_stdout=True) self.assertEqualsPoliciesString(self.object_iam_string, reset_iam_string) self.assertIn( self.public_object_read_binding[0], json.loads(set_iam_string)['bindings'])
#!/usr/bin/env python """A vtctld webdriver test.""" import logging import os from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from selenium.common.exceptions import NoSuchElementException import unittest from vtproto import vttest_pb2 from vttest import environment as vttest_environment from vttest import local_database import environment import utils def setUpModule(): try: if utils.options.xvfb: try: # This will be killed automatically by utils.kill_sub_processes() utils.run_bg(['Xvfb', ':15', '-ac']) os.environ['DISPLAY'] = ':15' except OSError as err: # Despite running in background, utils.run_bg() will throw immediately # if the Xvfb binary is not found. logging.error( "Can't start Xvfb (will try local DISPLAY instead): %s", err) except: tearDownModule() raise def tearDownModule(): utils.required_teardown() if utils.options.skip_teardown: return utils.remove_tmp_files() utils.kill_sub_processes() class TestVtctldWeb(unittest.TestCase): @classmethod def setUpClass(cls): """Set up two keyspaces: one unsharded, one with two shards.""" topology = vttest_pb2.VTTestTopology() topology.cells.append('test') topology.cells.append('test2') keyspace = topology.keyspaces.add(name='test_keyspace') keyspace.replica_count = 2 keyspace.rdonly_count = 2 keyspace.shards.add(name='-80') keyspace.shards.add(name='80-') keyspace2 = topology.keyspaces.add(name='test_keyspace2') keyspace2.shards.add(name='0') keyspace2.replica_count = 2 keyspace2.rdonly_count = 1 cls.driver = environment.create_webdriver() port = environment.reserve_ports(1) vttest_environment.base_port = port environment.reset_mysql_flavor() cls.db = local_database.LocalDatabase( topology, os.path.join(environment.vttop, 'test/vttest_schema'), False, None, web_dir=os.path.join(environment.vttop, 'web/vtctld'), default_schema_dir=os.path.join( environment.vttop, 'test/vttest_schema/default'), web_dir2=os.path.join(environment.vttop, 'web/vtctld2/app')) cls.db.setup() cls.vtctld_addr = 'http://localhost:%d' % cls.db.config()['port'] utils.pause('Paused test after vtcombo was started.\n' 'For manual testing, connect to vtctld: %s' % cls.vtctld_addr) @classmethod def tearDownClass(cls): cls.db.teardown() cls.driver.quit() def _get_keyspaces(self): """Get list of all present keyspaces.""" content = self.driver.find_element_by_id('content') # TODO(thompsonja) find better way to get keyspace name keyspaces = content.find_elements_by_tag_name('md-card') return [ks.find_element_by_tag_name('h2').text for ks in keyspaces] def _get_keyspace_element(self, keyspace_name): """Get a specific keyspace element given a keyspace name.""" return self.driver.find_element_by_id('%s-card' % keyspace_name) def _get_shards(self, keyspace_name): shard_grid = self.driver.find_element_by_id( '%s-shards-list' % keyspace_name) return shard_grid.text.split('\n') def _get_serving_shards(self, keyspace_name): serving_shards = self.driver.find_element_by_id( '%s-serving-list' % keyspace_name) return serving_shards.text.split('\n') def _get_inactive_shards(self, keyspace_name): inactive_shards = self.driver.find_element_by_id( '%s-inactive-list' % keyspace_name) return inactive_shards.text.split('\n') def _get_shard_element(self, keyspace_name, shard_name): return self._get_keyspace_element(keyspace_name).find_element_by_link_text( shard_name) def _get_tablet_names(self): tablet_elements = ( self.driver.find_element_by_id('tablets').find_elements_by_tag_name( 'md-card')) tablet_titles = [ x.find_element_by_tag_name('md-toolbar').text.split('\n')[0] for x in tablet_elements] return dict( [(x.split(' ')[0], x.split(' ')[1][1:-1]) for x in tablet_titles]) def _get_shard_record_keyspace_shard(self): return self.driver.find_element_by_id('keyspace-shard').text def _get_shard_record_master_tablet(self): return self.driver.find_element_by_id('master-tablet').text def _check_tablet_types(self, tablet_types, expected_counts): for expected_type, count in expected_counts.iteritems(): self.assertEquals(count, len([x for x in tablet_types if x == expected_type])) def _check_shard_overview( self, keyspace_name, shard_name, expected_tablet_types): logging.info('Checking %s/%s', keyspace_name, shard_name) self._get_shard_element(keyspace_name, shard_name).click() self.assertEquals(self._get_shard_record_keyspace_shard(), '%s/%s' % (keyspace_name, shard_name)) master = self._get_shard_record_master_tablet() logging.info('master tablet is %s', master) shard_tablets = self._get_tablet_names() self.assertEquals(shard_tablets[master], 'master') self._check_tablet_types(shard_tablets.values(), expected_tablet_types) self.driver.back() def _get_dropdown_options(self, group): status_content = self.driver.find_element_by_tag_name('vt-status') dropdown = status_content.find_element_by_id(group) return [op.text for op in dropdown.find_elements_by_tag_name('option')] def _get_dropdown_selection(self, group): status_content = self.driver.find_element_by_tag_name('vt-status') dropdown = status_content.find_element_by_id(group) return dropdown.find_element_by_tag_name('label').text def _change_dropdown_option(self, dropdown_id, dropdown_value): status_content = self.driver.find_element_by_tag_name('vt-status') dropdown = status_content.find_element_by_id(dropdown_id) dropdown.click() options = dropdown.find_elements_by_tag_name('li') for op in options: if op.text == dropdown_value: logging.info('dropdown %s: option %s clicked', dropdown_id, op.text) op.click() break def _check_dropdowns(self, keyspaces, selected_keyspace, cells, selected_cell, types, selected_type, metrics, selected_metric): """Checking that all dropdowns have the correct options and selection.""" keyspace_options = self._get_dropdown_options('keyspace') keyspace_selected = self._get_dropdown_selection('keyspace') logging.info('Keyspace options: %s Keyspace selected: %s', ', '.join(keyspace_options), keyspace_selected) self.assertListEqual(keyspaces, keyspace_options) self.assertEqual(selected_keyspace, keyspace_selected) cell_options = self._get_dropdown_options('cell') cell_selected = self._get_dropdown_selection('cell') logging.info('Cell options: %s Cell Selected: %s', ', '.join(cell_options), cell_selected) self.assertListEqual(cells, cell_options) self.assertEqual(selected_cell, cell_selected) type_options = self._get_dropdown_options('type') type_selected = self._get_dropdown_selection('type') logging.info('Type options: %s Type Selected: %s', ', '.join(cell_options), cell_selected) self.assertListEqual(types, type_options) self.assertEqual(selected_type, type_selected) metric_options = self._get_dropdown_options('metric') metric_selected = self._get_dropdown_selection('metric') logging.info('metric options: %s metric Selected: %s', ', '.join(metric_options), metric_selected) self.assertListEqual(metrics, metric_options) self.assertEqual(selected_metric, metric_selected) def _check_heatmaps(self, selected_keyspace): """Checking that the view has the correct number of heatmaps drawn.""" status_content = self.driver.find_element_by_tag_name('vt-status') keyspaces = status_content.find_elements_by_tag_name('vt-heatmap') logging.info('Number of keyspaces found: %d', len(keyspaces)) if selected_keyspace == 'all': available_keyspaces = self._get_dropdown_options('keyspace') self.assertEqual(len(keyspaces), len(available_keyspaces)-1) for ks in keyspaces: heading = ks.find_element_by_id('keyspaceName') logging.info('Keyspace name: %s', heading.text) try: ks.find_element_by_id(heading.text) except NoSuchElementException: self.fail('Cannot get keyspace') self.assertIn(heading.text, available_keyspaces) else: self.assertEquals(len(keyspaces), 1) heading = keyspaces[0].find_element_by_id('keyspaceName') logging.info('Keyspace name: %s', heading.text) try: keyspaces[0].find_element_by_id(heading.text) except NoSuchElementException: self.fail('Cannot get keyspace') self.assertEquals(heading.text, selected_keyspace) def _check_new_view( self, keyspaces, selected_keyspace, cells, selected_cell, types, selected_type, metrics, selected_metric): """Checking the dropdowns and heatmaps for each newly routed view.""" logging.info('Testing realtime stats view') self._check_dropdowns(keyspaces, selected_keyspace, cells, selected_cell, types, selected_type, metrics, selected_metric) self._check_heatmaps(selected_keyspace) # Navigation def _navigate_to_dashboard(self): logging.info('Fetching main vtctld page: %s', self.vtctld_addr) self.driver.get('%s/app2' % self.vtctld_addr) wait = WebDriverWait(self.driver, 10) wait.until(expected_conditions.visibility_of_element_located( (By.ID, 'test_keyspace'))) def _navigate_to_keyspace_view(self): self._navigate_to_dashboard() dashboard_content = self.driver.find_element_by_tag_name('vt-dashboard') keyspace_cards = dashboard_content.find_elements_by_class_name('vt-card') self.assertEqual(2, len(keyspace_cards)) first_keyspace_card = keyspace_cards[0] shard_stats = first_keyspace_card.find_element_by_tag_name('md-list') shard_stats.click() wait = WebDriverWait(self.driver, 10) wait.until(expected_conditions.visibility_of_element_located( (By.CLASS_NAME, 'vt-card'))) def _navigate_to_shard_view(self): self._navigate_to_keyspace_view() keyspace_content = self.driver.find_element_by_tag_name('vt-keyspace-view') shard_cards = keyspace_content.find_elements_by_class_name( 'vt-serving-shard') self.assertEqual(2, len(shard_cards)) first_shard_card = shard_cards[0] first_shard_card.click() wait = WebDriverWait(self.driver, 10) wait.until(expected_conditions.visibility_of_element_located( (By.ID, '1'))) # Get Elements def _get_dashboard_keyspaces(self): """Get list of all present keyspaces.""" wait = WebDriverWait(self.driver, 10) wait.until(expected_conditions.visibility_of_element_located( (By.TAG_NAME, 'vt-dashboard'))) dashboard_content = self.driver.find_element_by_tag_name('vt-dashboard') return [ks.text for ks in dashboard_content.find_elements_by_class_name('vt-keyspace-card')] def _get_dashboard_shards(self): """Get list of all present shards.""" wait = WebDriverWait(self.driver, 10) wait.until(expected_conditions.visibility_of_element_located( (By.TAG_NAME, 'vt-dashboard'))) dashboard_content = self.driver.find_element_by_tag_name('vt-dashboard') return [sh.text for sh in dashboard_content.find_elements_by_class_name('vt-shard-stats')] def _get_keyspace_shards(self): wait = WebDriverWait(self.driver, 10) wait.until(expected_conditions.visibility_of_element_located( (By.TAG_NAME, 'vt-keyspace-view'))) keyspace_content = self.driver.find_element_by_tag_name('vt-keyspace-view') return [sh.text for sh in keyspace_content.find_elements_by_class_name('vt-serving-shard')] def _get_shard_tablets(self): wait = WebDriverWait(self.driver, 10) wait.until(expected_conditions.visibility_of_element_located( (By.TAG_NAME, 'vt-shard-view'))) shard_content = self.driver.find_element_by_tag_name('vt-shard-view') # Ignore Header row. tablet_types = [] tablet_uids = [] table_rows = shard_content.find_elements_by_tag_name('tr')[1:] for row in table_rows: columns = row.find_elements_by_tag_name('td') tablet_types.append( columns[1].find_element_by_class_name('ui-cell-data').text) tablet_uids.append( columns[3].find_element_by_class_name('ui-cell-data').text) return (tablet_types, tablet_uids) def _get_first_option(self, dashboard_content): dashboard_menu = dashboard_content.find_element_by_class_name('vt-menu') dashboard_menu.click() first_option = dashboard_content.find_element_by_class_name( 'ui-menuitem-text') return first_option def _get_dialog_cmd(self, dialog): dialog_command = [ cmd.text for cmd in dialog.find_elements_by_class_name('vt-sheet')] return dialog_command def _toggle_dialog_checkbox(self, dialog, index): ping_tablets_checkbox = dialog.find_elements_by_class_name( 'md-checkbox-inner-container')[index] ping_tablets_checkbox.click() def _get_validate_resp(self, dialog): validate = dialog.find_element_by_id('vt-action') validate.click() validate_response = dialog.find_element_by_class_name('vt-resp').text return validate_response def _close_dialog(self, dialog): dismiss = dialog.find_element_by_id('vt-dismiss') dismiss.click() def test_old_keyspace_overview(self): logging.info('Testing old keyspace overview') logging.info('Fetching main vtctld page: %s', self.vtctld_addr) self.driver.get(self.vtctld_addr) keyspace_names = self._get_keyspaces() logging.info('Keyspaces: %s', ', '.join(keyspace_names)) self.assertListEqual(['test_keyspace', 'test_keyspace2'], keyspace_names) test_keyspace_serving_shards = self._get_serving_shards('test_keyspace') logging.info( 'Serving Shards in test_keyspace: %s', ', '.join( test_keyspace_serving_shards)) self.assertListEqual(test_keyspace_serving_shards, ['-80', '80-']) test_keyspace2_serving_shards = self._get_serving_shards('test_keyspace2') logging.info( 'Serving Shards in test_keyspace2: %s', ', '.join( test_keyspace2_serving_shards)) self.assertListEqual(test_keyspace2_serving_shards, ['0']) with self.assertRaises(NoSuchElementException): self._get_inactive_shards('test_keyspace') logging.info( 'Inactive Shards in test_keyspace: %s', ', '.join([])) with self.assertRaises(NoSuchElementException): self._get_inactive_shards('test_keyspace2') logging.info( 'Inactive Shards in test_keyspace2: %s', ', '.join([])) def test_old_shard_overview(self): logging.info('Testing old shard overview') logging.info('Fetching main vtctld page: %s', self.vtctld_addr) self.driver.get(self.vtctld_addr) self._check_shard_overview( 'test_keyspace', '-80', {'master': 1, 'replica': 1, 'rdonly': 2}) self._check_shard_overview( 'test_keyspace', '80-', {'master': 1, 'replica': 1, 'rdonly': 2}) self._check_shard_overview( 'test_keyspace2', '0', {'master': 1, 'replica': 1, 'rdonly': 1}) def test_dashboard(self): logging.info('Testing dashboard view') self._navigate_to_dashboard() keyspace_names = self._get_dashboard_keyspaces() shard_names = self._get_dashboard_shards() logging.info('Keyspaces: %s', ', '.join(keyspace_names)) logging.info('Shards: %s', ', '.join(shard_names)) self.assertListEqual(['test_keyspace', 'test_keyspace2'], keyspace_names) self.assertListEqual(['2 Shards', '1 Shards'], shard_names) def test_dashboard_validate(self): self._navigate_to_dashboard() dashboard_content = self.driver.find_element_by_tag_name('vt-dashboard') first_menu_option = self._get_first_option(dashboard_content) logging.info('First option of Dashboard menu: %s', first_menu_option.text) self.assertEqual('Validate', first_menu_option.text) first_menu_option.click() dialog = dashboard_content.find_element_by_tag_name('vt-dialog') dialog_command = self._get_dialog_cmd(dialog) logging.info('Validate command: %s', ', '.join(dialog_command)) self.assertEqual(1, len(dialog_command)) self.assertListEqual(['Validate'], dialog_command) # Validate Dialog Checkbox is working self._toggle_dialog_checkbox(dialog, 0) dialog_command = self._get_dialog_cmd(dialog) logging.info('Validate command: %s', ', '.join(dialog_command)) self.assertEqual(2, len(dialog_command)) self.assertEqual('-ping-tablets', dialog_command[1]) # Validate succeeded validate_response = self._get_validate_resp(dialog) logging.info('Validate command response: %s', validate_response) self._close_dialog(dialog) def test_create_keyspace(self): self._navigate_to_dashboard() dashboard_content = self.driver.find_element_by_tag_name('vt-dashboard') dialog = dashboard_content.find_element_by_tag_name('vt-dialog') # Create Keyspace Dialog command responds to name. add_button = dashboard_content.find_element_by_class_name('add-button') add_button.click() input_fields = [md_input.find_element_by_tag_name('input') for md_input in dialog.find_elements_by_tag_name('md-input')] keyspace_name_field = input_fields[0] sharding_col_name_field = input_fields[1] keyspace_name_field.send_keys('test_keyspace3') dialog_command = [ cmd.text for cmd in dialog.find_elements_by_class_name('vt-sheet')] logging.info('Create keyspace command: %s', ', '.join(dialog_command)) self.assertEqual(2, len(dialog_command)) self.assertListEqual(['CreateKeyspace', 'test_keyspace3'], dialog_command) # Create Keyspace autopopulates sharding_column type sharding_col_name_field.send_keys('test_id') dialog_command = [ cmd.text for cmd in dialog.find_elements_by_class_name('vt-sheet')] logging.info('Create keyspace command: %s', ', '.join(dialog_command)) self.assertEqual(4, len(dialog_command)) self.assertListEqual(['CreateKeyspace', '-sharding_column_name=test_id', '-sharding_column_type=UINT64', 'test_keyspace3'], dialog_command) # Dropdown works dropdown = dialog.find_element_by_tag_name('p-dropdown') dropdown.click() options = dropdown.find_elements_by_tag_name('li') options[1].click() dialog_command = [ cmd.text for cmd in dialog.find_elements_by_class_name('vt-sheet')] logging.info('Create keyspace command: %s', ', '.join(dialog_command)) self.assertEqual(4, len(dialog_command)) self.assertListEqual(['CreateKeyspace', '-sharding_column_name=test_id', '-sharding_column_type=BYTES', 'test_keyspace3'], dialog_command) create = dialog.find_element_by_id('vt-action') create.click() dismiss = dialog.find_element_by_id('vt-dismiss') dismiss.click() keyspace_names = self._get_dashboard_keyspaces() logging.info('Keyspaces: %s', ', '.join(keyspace_names)) self.assertListEqual( ['test_keyspace', 'test_keyspace2', 'test_keyspace3'], keyspace_names) test_keyspace3 = dashboard_content.find_elements_by_class_name('vt-card')[2] test_keyspace3.find_element_by_class_name('vt-menu').click() options = test_keyspace3.find_elements_by_tag_name('li') delete = options[1] delete.click() delete = dialog.find_element_by_id('vt-action') delete.click() dismiss = dialog.find_element_by_id('vt-dismiss') dismiss.click() keyspace_names = self._get_dashboard_keyspaces() logging.info('Keyspaces: %s', ', '.join(keyspace_names)) self.assertListEqual(['test_keyspace', 'test_keyspace2'], keyspace_names) def test_keyspace_view(self): self._navigate_to_keyspace_view() logging.info('Navigating to keyspace view') self._navigate_to_keyspace_view() logging.info('Testing keyspace view') shard_names = self._get_keyspace_shards() logging.info('Shards in first keyspace: %s', ', '.join(shard_names)) self.assertListEqual(['-80', '80-'], shard_names) def test_shard_view(self): self._navigate_to_shard_view() logging.info('Navigating to shard view') self._navigate_to_shard_view() logging.info('Testing shard view') tablet_types, tablet_uids = self._get_shard_tablets() logging.info('Tablets types in first shard in first keyspace: %s', ', '.join(tablet_types)) logging.info('Tablets uids in first shard in first keyspace: %s', ', '.join(tablet_uids)) self.assertSetEqual( set(['master', 'replica', 'rdonly', 'rdonly', 'replica', 'replica', 'rdonly', 'rdonly']), set(tablet_types)) self.assertSetEqual( set(['1', '2', '3', '4', '5', '6', '7', '8']), set(tablet_uids)) def test_realtime_stats(self): logging.info('Testing realtime stats view') # Navigate to the status page from initial app. # TODO(thompsonja): Fix this once direct navigation works (going to status # page directly should display correctly) self.driver.get('%s/app2' % self.vtctld_addr) status_button = self.driver.find_element_by_partial_link_text('Status') status_button.click() wait = WebDriverWait(self.driver, 10) wait.until(expected_conditions.visibility_of_element_located( (By.TAG_NAME, 'vt-status'))) test_cases = [ (None, None, 'all', 'all', 'all'), ('type', 'REPLICA', 'all', 'all', 'REPLICA'), ('cell', 'test2', 'all', 'test2', 'REPLICA'), ('keyspace', 'test_keyspace', 'test_keyspace', 'test2', 'REPLICA'), ('cell', 'all', 'test_keyspace', 'all', 'REPLICA'), ('type', 'all', 'test_keyspace', 'all', 'all'), ('cell', 'test2', 'test_keyspace', 'test2', 'all'), ('keyspace', 'all', 'all', 'test2', 'all'), ] for (dropdown_id, dropdown_val, keyspace, cell, tablet_type) in test_cases: logging.info('Routing to new %s-%s-%s view', keyspace, cell, tablet_type) if dropdown_id and dropdown_val: self._change_dropdown_option(dropdown_id, dropdown_val) tablet_type_options = ['all', 'MASTER', 'REPLICA', 'RDONLY'] if cell == 'test2': tablet_type_options = ['all', 'REPLICA', 'RDONLY'] self._check_new_view(keyspaces=['all', 'test_keyspace', 'test_keyspace2'], selected_keyspace=keyspace, cells=['all', 'test', 'test2'], selected_cell=cell, types=tablet_type_options, selected_type=tablet_type, metrics=['lag', 'qps', 'health'], selected_metric='health' ) def add_test_options(parser): parser.add_option( '--no-xvfb', action='store_false', dest='xvfb', default=True, help='Use local DISPLAY instead of headless Xvfb mode.') if __name__ == '__main__': utils.main(test_options=add_test_options)
# -*- coding: utf-8 -*- """ S3 Synchronization @copyright: 2011-13 (c) Sahana Software Foundation @license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import sys import urllib, urllib2 import datetime import time try: from lxml import etree except ImportError: print >> sys.stderr, "ERROR: lxml module needed for XML handling" raise try: import json # try stdlib (Python 2.6) except ImportError: try: import simplejson as json # try external module except: import gluon.contrib.simplejson as json # fallback to pure-Python module from gluon import * from gluon.storage import Storage from s3rest import S3Method from s3import import S3ImportItem from s3resource import S3URLQuery DEBUG = False if DEBUG: print >> sys.stderr, "S3SYNC: DEBUG MODE" def _debug(m): print >> sys.stderr, m else: _debug = lambda m: None # ============================================================================= class S3Sync(S3Method): """ Synchronization Handler """ # ------------------------------------------------------------------------- def __init__(self): """ Constructor """ S3Method.__init__(self) self.log = S3SyncLog() # ------------------------------------------------------------------------- def apply_method(self, r, **attr): """ RESTful method handler (repository/sync, repository/register) @param r: the S3Request instance @param attr: controller attributes for the request """ output = dict() if r.method == "sync": if r.http == "GET": # Incoming pull output = self.__send(r, **attr) elif r.http in ("PUT", "POST"): # Incoming push output = self.__receive(r, **attr) else: r.error(405, current.manager.ERROR.BAD_METHOD) elif r.name == "repository" and r.method == "register": if r.http == "GET": # Incoming registration request output = self.__register(r, **attr) else: r.error(405, current.manager.ERROR.BAD_METHOD) else: r.error(405, current.manager.ERROR.BAD_METHOD) return output # ------------------------------------------------------------------------- def get_status(self): """ Read the current sync status """ table = current.s3db.sync_status row = current.db().select(table.ALL, limitby=(0, 1)).first() if not row: row = Storage() return row # ------------------------------------------------------------------------- def set_status(self, **attr): """ Update the current sync status """ table = current.s3db.sync_status data = Storage([(k, attr[k]) for k in attr if k in table.fields]) data.update(timestmp = datetime.datetime.utcnow()) row = current.db().select(table._id, limitby=(0, 1)).first() if row: row.update_record(**data) else: table.insert(**data) row = data return row # ------------------------------------------------------------------------- def __get_config(self): """ Read the sync settings, avoid repeated DB lookups """ if not hasattr(self, "config"): table = current.s3db.sync_config row = current.db().select(table.ALL, limitby=(0, 1)).first() self.config = row return self.config # ------------------------------------------------------------------------- def synchronize(self, repository): """ Synchronize with a repository @param repository: the repository Row @return: True if successful, False if there was an error """ _debug("S3Sync.synchronize(%s)" % repository.url) log = self.log if not repository.url: message = "No URL set for repository" log.write(repository_id=repository.id, resource_name=None, transmission=None, mode=None, action="connect", remote=False, result=self.log.FATAL, message=message) return False ttable = current.s3db.sync_task query = (ttable.repository_id == repository.id) & \ (ttable.deleted != True) tasks = current.db(query).select() connector = S3SyncRepository.factory(repository) error = connector.login() if error: log.write(repository_id=repository.id, resource_name=None, transmission=log.OUT, mode=None, action="login", remote=True, result=log.FATAL, message=error) return False success = True for task in tasks: # Pull mtime = None if task.mode in (1, 3): error, mtime = connector.pull(task, onconflict=self.onconflict) if error: success = False _debug("S3Sync.synchronize: %s PULL error: %s" % (task.resource_name, error)) continue if mtime is not None: task.update_record(last_pull=mtime) # Push mtime = None if task.mode in (2, 3): error, mtime = connector.push(task) if error: success = False _debug("S3Sync.synchronize: %s PUSH error: %s" % (task.resource_name, error)) continue if mtime is not None: task.update_record(last_push=mtime) _debug("S3Sync.synchronize: %s done" % task.resource_name) return success # ------------------------------------------------------------------------- def __register(self, r, **attr): """ Respond to an incoming registration request @param r: the S3Request @param attr: the controller attributes """ log = self.log result = log.SUCCESS message = "registration successful" repository_id = None config = self.__get_config() if "repository" in r.vars: ruid = r.vars["repository"] db = current.db rtable = current.s3db.sync_repository row = db(rtable.uuid == ruid).select(limitby=(0, 1)).first() if row: repository_id = row.id if not row.accept_push and current.auth.s3_has_role("ADMIN"): row.update_record(accept_push=True) else: if current.auth.s3_has_role("ADMIN"): accept_push = True else: accept_push = False repository_id = rtable.insert(name=ruid, uuid=ruid, accept_push=accept_push) if not repository_id: result = log.ERROR message = "registration failed" else: result = log.ERROR message = "no repository identifier specified" if result == log.SUCCESS: output = current.xml.json_message(message=message, sender="%s" % config.uuid) else: output = current.xml.json_message(False, 400, message=message, sender="%s" % config.uuid) # Set content type header headers = current.response.headers headers["Content-Type"] = "application/json" # Log the operation log.write(repository_id=repository_id, resource_name=log.NONE, transmission=log.IN, mode=log.PUSH, action="register repository", result=result, message=message) return output # ------------------------------------------------------------------------- def __send(self, r, **attr): """ Respond to an incoming pull @param r: the S3Request @param attr: the controller attributes """ _debug("S3Sync.__send") resource = r.resource # Identify the requesting repository repository_id = None if "repository" in r.vars: db = current.db s3db = current.s3db ruid = r.vars["repository"] rtable = s3db.sync_repository ttable = s3db.sync_task left = ttable.on((rtable.id == ttable.repository_id) & \ (ttable.resource_name == resource.tablename)) row = db(rtable.uuid == ruid).select(rtable.id, ttable.id, left=left, limitby=(0, 1)).first() if row: repository_id = row[rtable.id] task_id = row[ttable.id] # Additional export parameters _vars = r.get_vars start = _vars.get("start", None) if start is not None: try: start = int(start) except ValueError: start = None limit = _vars.get("limit", None) if limit is not None: try: limit = int(limit) except ValueError: limit = None msince = _vars.get("msince", None) if msince is not None: tfmt = current.xml.ISOFORMAT try: (y, m, d, hh, mm, ss, t0, t1, t2) = \ time.strptime(msince, tfmt) msince = datetime.datetime(y, m, d, hh, mm, ss) except ValueError: msince = None # Sync filters from peer filters = {} for k, v in _vars.items(): if k[0] == "[" and "]" in k: tablename, urlvar = k[1:].split("]", 1) if urlvar: if not tablename or tablename == "~": tablename = resource.tablename f = filters.get(tablename, {}) u = f.get(urlvar, None) if u: u = "%s&%s" % (u, v) else: u = v f[urlvar] = u filters[tablename] = f if not filters: filters = None # Export the resource output = resource.export_xml(start=start, limit=limit, filters=filters, msince=msince) count = resource.results # Set content type header headers = current.response.headers headers["Content-Type"] = "text/xml" # Log the operation log = self.log log.write(repository_id=repository_id, resource_name=r.resource.tablename, transmission=log.IN, mode=log.PULL, result=log.SUCCESS, message="data sent to peer (%s records)" % count) return output # ------------------------------------------------------------------------- def __receive(self, r, **attr): """ Respond to an incoming push @param r: the S3Request @param attr: the controller attributes """ _debug("S3Sync.__receive") s3db = current.s3db db = current.db # Identify the sending repository repository = Storage(id=None) if "repository" in r.vars: ruid = r.vars["repository"] rtable = s3db.sync_repository row = db(rtable.uuid == ruid).select(limitby=(0, 1)).first() if row: repository = row if not repository.id or \ not repository.accept_push: r.error(403, current.manager.ERROR.NOT_PERMITTED) # Get strategy and policy default_update_policy = S3ImportItem.POLICY.NEWER default_conflict_policy = S3ImportItem.POLICY.MASTER ttable = s3db.sync_task query = (ttable.repository_id == repository.id) & \ (ttable.resource_name == r.tablename) & \ (ttable.deleted != True) task = db(query).select(limitby=(0, 1)).first() last_sync = None if task: strategy = task.strategy update_policy = task.update_policy or default_update_policy conflict_policy = task.conflict_policy or default_conflict_policy if update_policy not in ("THIS", "OTHER"): last_sync = task.last_pull else: policies = S3ImportItem.POLICY p = r.get_vars.get("update_policy", None) values = {"THIS": "OTHER", "OTHER": "THIS"} switch = lambda p: p in values and values[p] or p if p and p in policies: p = switch(p) update_policy = policies[p] else: update_policy = default_update_policy p = r.get_vars.get("conflict_policy", None) if p and p in policies: p = switch(p) conflict_policy = policies[p] else: conflict_policy = default_conflict_policy msince = r.get_vars.get("msince", None) if msince is not None: tfmt = current.xml.ISOFORMAT try: (y, m, d, hh, mm, ss, t0, t1, t2) = \ time.strptime(msince, tfmt) last_sync = datetime.datetime(y, m, d, hh, mm, ss) except ValueError: last_sync = None s = r.get_vars.get("strategy", None) if s: s = str(s).split(",") methods = S3ImportItem.METHOD strategy = [method for method in methods.values() if method in s] else: strategy = ttable.strategy.default # Other parameters ignore_errors = True # Get the source source = r.read_body() # Import resource resource = r.resource onconflict = lambda item: self.onconflict(item, repository, resource) try: output = resource.import_xml(source, format="xml", ignore_errors=ignore_errors, strategy=strategy, update_policy=update_policy, conflict_policy=conflict_policy, last_sync=last_sync, onconflict=onconflict) except IOError: current.auth.permission.fail() except SyntaxError: e = sys.exc_info()[1] r.error(400, e) log = self.log if resource.error_tree is not None: # Validation error (log in any case) if ignore_errors: result = log.WARNING else: result = log.FATAL message = "%s" % resource.error for element in resource.error_tree.findall("resource"): error_msg = element.get("error", "unknown error") error_fields = element.findall("data[@error]") if error_fields: for field in error_fields: error_msg = field.get("error", "unknown error") if error_msg: msg = "(UID: %s) %s.%s=%s: %s" % \ (element.get("uuid", None), element.get("name", None), field.get("field", None), field.get("value", field.text), error_msg) message = "%s, %s" % (message, msg) else: msg = "(UID: %s) %s: %s" % \ (element.get("uuid", None), element.get("name", None), error_msg) message = "%s, %s" % (message, msg) else: result = log.SUCCESS message = "data received from peer" log.write(repository_id=repository.id, resource_name=resource.tablename, transmission=log.IN, mode=log.PUSH, result=result, message=message) return output # ------------------------------------------------------------------------- def onconflict(self, item, repository, resource): """ Automatic conflict resolution @param item: the conflicting import item @param repository: the repository the item comes from @param resource: the resource the item shall be imported to """ s3db = current.s3db tablename = resource.tablename resolver = s3db.get_config(tablename, "onconflict") _debug("Resolving conflict in %s" % resource.tablename) _debug("Repository: %s" % repository.name) _debug("Conflicting item: %s" % item) _debug("Method: %s" % item.method) if resolver: _debug("Applying custom rule") resolver(item, repository, resource) if item.conflict: _debug("Do not accept") else: _debug("Accept per custom rule") else: _debug("Applying default rule") ttable = s3db.sync_task policies = S3ImportItem.POLICY query = (ttable.repository_id == repository.id) & \ (ttable.resource_name == tablename) & \ (ttable.deleted != True) task = current.db(query).select(limitby=(0, 1)).first() if task and item.original: original = item.original conflict_policy = task.conflict_policy if conflict_policy == policies.OTHER: # Always accept _debug("Accept by default") item.conflict = False elif conflict_policy == policies.NEWER: # Accept if newer xml = current.xml if xml.MTIME in original and \ xml.as_utc(original[xml.MTIME]) <= item.mtime: _debug("Accept because newer") item.conflict = False else: _debug("Do not accept") elif conflict_policy == policies.MASTER: # Accept if master if current.xml.MCI in original and \ original.mci == 0 or item.mci == 1: _debug("Accept because master") item.conflict = False else: _debug("Do not accept") else: # Never accept _debug("Do not accept") pass else: # No rule - accept always _debug("Accept because no rule found") item.conflict = False # ------------------------------------------------------------------------- @staticmethod def get_filters(task_id): """ Get all filters for a synchronization task @param task_id: the task ID @return: a dict of dicts like {tablename: {url_var: value}} """ db = current.db s3db = current.s3db ftable = s3db.sync_resource_filter query = (ftable.task_id == task_id) & \ (ftable.deleted != True) rows = db(query).select(ftable.tablename, ftable.filter_string) filters = {} for row in rows: tablename = row.tablename if tablename in filters: filters[tablename] = "%s&%s" % (filters[tablename], row.filter_string) else: filters[tablename] = row.filter_string parse_url = S3URLQuery.parse_url for tablename in filters: filters[tablename] = parse_url(filters[tablename]) return filters # ============================================================================= class S3SyncLog(S3Method): """ Synchronization Logger """ TABLENAME = "sync_log" SUCCESS = "success" WARNING = "warning" ERROR = "error" FATAL = "fatal" IN = "incoming" OUT = "outgoing" PULL = "pull" PUSH = "push" NONE = "none" # ------------------------------------------------------------------------- def apply_method(self, r, **attr): """ RESTful method handler @param r: the S3Request instance @param attr: controller attributes for the request """ output = dict() resource = r.resource if resource.tablename == "sync_log": return resource.crud.select(r, **attr) elif resource.tablename == "sync_repository": # READ for sync log for this repository pass else: if r.interactive: # READ for sync log for this resource here = "%s.%s" % (r.controller, r.function) sync_log = current.s3db[self.TABLENAME] sync_log.resource_name.readable = False query = (sync_log.resource_name == resource.tablename) r = r.factory(prefix="sync", name="log", args=[]) s3 = current.response.s3 s3.filter = query s3.prep = None s3.postp = None s3.actions = [ dict(label=str(current.T("Details")), _class="action-btn", url=URL(c="sync", f="log", args=["[id]"], vars={"return":here})) ] output = r(subtitle=None, rheader=self.rheader) else: r.error(501, current.manager.ERROR.BAD_FORMAT) return output # ------------------------------------------------------------------------- @classmethod def write(cls, repository_id=None, resource_name=None, transmission=None, mode=None, action=None, result=None, remote=False, message=None): """ Writes a new entry to the log @param repository_id: the repository record ID @param resource_name: the resource name @param transmission: transmission mode (IN, OUT or None) @param mode: synchronization mode (PULL, PUSH or None) @param action: action taken to resolve errors (if any) @param result: the result of the transaction (SUCCESS, WARNING, ERROR or FATAL) @param remote: boolean, True if this is a remote error @param message: clear text message """ if result not in (cls.SUCCESS, cls.WARNING, cls.ERROR, cls.FATAL): result = cls.SUCCESS if transmission not in (cls.IN, cls.OUT): transmission = cls.NONE if mode not in (cls.PULL, cls.PUSH): mode = cls.NONE mode = "%s/%s" % (mode, transmission) if not action: action = cls.NONE now = datetime.datetime.utcnow() entry = Storage(timestmp=now, repository_id=repository_id, resource_name=resource_name, mode=mode, action=action, result=result, remote=remote, message=message) table = current.s3db[cls.TABLENAME] table.insert(**entry) return # ------------------------------------------------------------------------- @staticmethod def rheader(r, **attr): if r.id is None: return DIV(current.T("Showing latest entries first")) else: return None # ============================================================================= class S3SyncRepository(object): """ Synchronization API connector base class The base class handles Sahana Eden's Sync API, whilst other repository types may be handled by subclasses. Subclasses must implement (override) the following methods: register() - register at the peer site login() - login to the peer site pull(task) - pull data for a task push(task) - push data for a task """ # ------------------------------------------------------------------------- @staticmethod def factory(repository): """ Factory method to generate an instance of the appropriate subclass of the API for the repository @param repository: the repository record """ # Available connectors connectors = { "eden": S3SyncRepository, "ccrm": S3SyncCiviCRM, } api = repository.apitype if api in connectors: return connectors[api](repository) else: raise NotImplementedError # ------------------------------------------------------------------------- def __init__(self, repository): """ Constructor @param sync: the calling S3Sync instance @param repository: the repository record """ self.log = S3SyncLog self.id = repository.id self.name = repository.name self.url = repository.url self.username = repository.username self.password = repository.password self.site_key = repository.site_key self.proxy = repository.proxy # ------------------------------------------------------------------------- def get_config(self): """ Read the sync settings, avoid repeated DB lookups """ if not hasattr(self, "config"): table = current.s3db.sync_config row = current.db().select(table.ALL, limitby=(0, 1)).first() self.config = row return self.config # ------------------------------------------------------------------------- def register(self): """ Register at the repository """ if not self.url: return True _debug("S3SyncRepository.register(%s)" % (self.url)) # Construct the URL config = self.get_config() url = "%s/sync/repository/register.xml?repository=%s" % \ (self.url, config.uuid) _debug("...send to URL %s" % url) # Generate the request req = urllib2.Request(url=url) handlers = [] # Proxy handling proxy = self.proxy or config.proxy or None if proxy: proxy_handler = urllib2.ProxyHandler({"http": proxy}) handlers.append(proxy_handler) # Authentication username = self.username password = self.password if username and password: import base64 base64string = base64.encodestring('%s:%s' % (username, password))[:-1] req.add_header("Authorization", "Basic %s" % base64string) passwd_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() passwd_manager.add_password(realm=None, uri=url, user=username, passwd=password) auth_handler = urllib2.HTTPBasicAuthHandler(passwd_manager) handlers.append(auth_handler) # Install all handlers if handlers: opener = urllib2.build_opener(*handlers) urllib2.install_opener(opener) # Execute the request log = self.log success = True remote = False try: f = urllib2.urlopen(req) except urllib2.HTTPError, e: result = log.FATAL remote = True # Peer error code = e.code message = e.read() success = False try: message_json = json.loads(message) message = message_json.get("message", message) except: pass except: result = log.FATAL code = 400 message = sys.exc_info()[1] success = False else: ruid = None message = f.read() try: message_json = json.loads(message) message = message_json.get("message", message) ruid = message_json.get("sender", None) except: message = "registration successful" result = log.SUCCESS if ruid is not None: db = current.db rtable = current.s3db.sync_repository try: db(rtable.id == self.id).update(uuid=ruid) except: pass # Log the operation log.write(repository_id=self.id, transmission=log.OUT, mode=log.PUSH, action="request registration", remote=remote, result=result, message=message) return success # ------------------------------------------------------------------------- def login(self): """ Login to the repository """ # Sahana Eden uses HTTP Basic Auth, no login required return None # ------------------------------------------------------------------------- def pull(self, task, onconflict=None): """ Outgoing pull @param task: the task (sync_task Row) """ xml = current.xml config = self.get_config() resource_name = task.resource_name _debug("S3SyncRepository.pull(%s, %s)" % (self.url, resource_name)) # Construct the URL url = "%s/sync/sync.xml?resource=%s&repository=%s" % \ (self.url, resource_name, config.uuid) last_pull = task.last_pull if last_pull and task.update_policy not in ("THIS", "OTHER"): url += "&msince=%s" % xml.encode_iso_datetime(last_pull) url += "&include_deleted=True" # Send sync filters to peer filters = current.sync.get_filters(task.id) filter_string = None resource_name = task.resource_name for tablename in filters: prefix = "~" if not tablename or tablename == resource_name \ else tablename for k, v in filters[tablename].items(): urlfilter = "[%s]%s=%s" % (prefix, k, v) url += "&%s" % urlfilter _debug("...pull from URL %s" % url) # Figure out the protocol from the URL url_split = url.split("://", 1) if len(url_split) == 2: protocol, path = url_split else: protocol, path = "http", None # Create the request req = urllib2.Request(url=url) handlers = [] # Proxy handling proxy = self.proxy or config.proxy or None if proxy: _debug("using proxy=%s" % proxy) proxy_handler = urllib2.ProxyHandler({protocol: proxy}) handlers.append(proxy_handler) # Authentication handling username = self.username password = self.password if username and password: # Send auth data unsolicitedly (the only way with Eden instances): import base64 base64string = base64.encodestring('%s:%s' % (username, password))[:-1] req.add_header("Authorization", "Basic %s" % base64string) # Just in case the peer does not accept that, add a 401 handler: passwd_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() passwd_manager.add_password(realm=None, uri=url, user=username, passwd=password) auth_handler = urllib2.HTTPBasicAuthHandler(passwd_manager) handlers.append(auth_handler) # Install all handlers if handlers: opener = urllib2.build_opener(*handlers) urllib2.install_opener(opener) # Execute the request remote = False output = None response = None log = self.log try: f = urllib2.urlopen(req) except urllib2.HTTPError, e: result = log.ERROR remote = True # Peer error code = e.code message = e.read() try: # Sahana-Eden would send a JSON message, # try to extract the actual error message: message_json = json.loads(message) message = message_json.get("message", message) except: pass # Prefix as peer error and strip XML markup from the message # @todo: better method to do this? message = "<message>%s</message>" % message try: markup = etree.XML(message) message = markup.xpath(".//text()") if message: message = " ".join(message) else: message = "" except etree.XMLSyntaxError: pass output = xml.json_message(False, code, message, tree=None) except: result = log.FATAL code = 400 message = sys.exc_info()[1] output = xml.json_message(False, code, message) else: result = log.SUCCESS response = f # Process the response mtime = None if response: # Get import strategy and update policy strategy = task.strategy update_policy = task.update_policy conflict_policy = task.conflict_policy success = True message = "" # Import the data resource = current.s3db.resource(resource_name) onconflict = lambda item: onconflict(item, self, resource) count = 0 try: success = resource.import_xml( response, ignore_errors=True, strategy=strategy, update_policy=update_policy, conflict_policy=conflict_policy, last_sync=last_pull, onconflict=onconflict) count = resource.import_count except IOError, e: result = log.FATAL message = "%s" % e output = xml.json_message(False, 400, message) mtime = resource.mtime # Log all validation errors if resource.error_tree is not None: result = log.WARNING message = "%s" % resource.error for element in resource.error_tree.findall("resource"): for field in element.findall("data[@error]"): error_msg = field.get("error", None) if error_msg: msg = "(UID: %s) %s.%s=%s: %s" % \ (element.get("uuid", None), element.get("name", None), field.get("field", None), field.get("value", field.text), field.get("error", None)) message = "%s, %s" % (message, msg) # Check for failure if not success: result = log.FATAL if not message: error = current.manager.error message = "%s" % error output = xml.json_message(False, 400, message) mtime = None # ...or report success elif not message: message = "data imported successfully (%s records)" % count elif result == log.SUCCESS: # No data received from peer result = log.ERROR remote = True message = "no data received from peer" # Log the operation log.write(repository_id=self.id, resource_name=task.resource_name, transmission=log.OUT, mode=log.PULL, action=None, remote=remote, result=result, message=message) _debug("S3SyncRepository.pull import %s: %s" % (result, message)) return (output, mtime) # ------------------------------------------------------------------------- def push(self, task): """ Outgoing push @param task: the sync_task Row """ xml = current.xml config = self.get_config() resource_name = task.resource_name _debug("S3SyncRepository.push(%s, %s)" % (self.url, resource_name)) # Construct the URL url = "%s/sync/sync.xml?resource=%s&repository=%s" % \ (self.url, resource_name, config.uuid) strategy = task.strategy if strategy: url += "&strategy=%s" % ",".join(strategy) update_policy = task.update_policy if update_policy: url += "&update_policy=%s" % update_policy conflict_policy = task.conflict_policy if conflict_policy: url += "&conflict_policy=%s" % conflict_policy last_push = task.last_push if last_push and update_policy not in ("THIS", "OTHER"): url += "&msince=%s" % xml.encode_iso_datetime(last_push) else: last_push = None _debug("...push to URL %s" % url) # Define the resource resource = current.s3db.resource(resource_name, include_deleted=True) # Apply sync filters for this task filters = current.sync.get_filters(task.id) # Export the resource as S3XML data = resource.export_xml(filters=filters, msince=last_push) count = resource.results or 0 mtime = resource.muntil # Transmit the data via HTTP remote = False output = None log = self.log if data and count: # Find the protocol url_split = url.split("://", 1) if len(url_split) == 2: protocol, path = url_split else: protocol, path = "http", None # Generate the request import urllib2 req = urllib2.Request(url=url, data=data) req.add_header('Content-Type', "text/xml") handlers = [] # Proxy handling proxy = self.proxy or config.proxy or None if proxy: _debug("using proxy=%s" % proxy) proxy_handler = urllib2.ProxyHandler({protocol: proxy}) handlers.append(proxy_handler) # Authentication username = self.username password = self.password if username and password: # send auth credentials unsolicitedly import base64 base64string = base64.encodestring('%s:%s' % (username, password))[:-1] req.add_header("Authorization", "Basic %s" % base64string) # Just in case the peer does not accept that # => add a 401 handler: passwd_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() passwd_manager.add_password(realm=None, uri=url, user=username, passwd=password) auth_handler = urllib2.HTTPBasicAuthHandler(passwd_manager) handlers.append(auth_handler) # Install all handlers if handlers: opener = urllib2.build_opener(*handlers) urllib2.install_opener(opener) # Execute the request try: f = urllib2.urlopen(req) except urllib2.HTTPError, e: result = log.FATAL remote = True # Peer error code = e.code message = e.read() try: # Sahana-Eden sends a JSON message, # try to extract the actual error message: message_json = json.loads(message) message = message_json.get("message", message) except: pass output = xml.json_message(False, code, message) except: result = log.FATAL code = 400 message = sys.exc_info()[1] output = xml.json_message(False, code, message) else: result = log.SUCCESS message = "data sent successfully (%s records)" % count else: # No data to send result = log.WARNING message = "No data to send" # Log the operation log.write(repository_id=self.id, resource_name=task.resource_name, transmission=log.OUT, mode=log.PUSH, action=None, remote=remote, result=result, message=message) if output is not None: mtime = None return (output, mtime) # ============================================================================= class S3SyncCiviCRM(S3SyncRepository): """ CiviCRM REST-API connector @status: experimental """ # Resource map RESOURCE = { "pr_person": { "q": "civicrm/contact", "contact_type": "Individual" }, } # ------------------------------------------------------------------------- def register(self): """ Register at the repository """ # CiviCRM does not support via-web peer registration return True # ------------------------------------------------------------------------- def login(self): """ Login to the repository """ _debug("S3SyncCiviCRM.login()") request = { "q": "civicrm/login", "name": self.username, "pass": self.password, } response, error = self.send(**request) if error: _debug("S3SyncCiviCRM.login FAILURE: %s" % error) return error api_key = response.findall("//api_key") if len(api_key): self.api_key = api_key[0].text else: error = "No API Key returned by CiviCRM" _debug("S3SyncCiviCRM.login FAILURE: %s" % error) return error PHPSESSID = response.findall("//PHPSESSID") if len(PHPSESSID): self.PHPSESSID = PHPSESSID[0].text else: error = "No PHPSESSID returned by CiviCRM" _debug("S3SyncCiviCRM.login FAILURE: %s" % error) return error _debug("S3SyncCiviCRM.login SUCCESS") return None # ------------------------------------------------------------------------- def pull(self, task, onconflict=None): """ Pull updates from this repository @param task: the task Row @param onconflict: synchronization conflict resolver """ xml = current.xml log = self.log resource_name = task.resource_name _debug("S3SyncCiviCRM.pull(%s, %s)" % (self.url, resource_name)) mtime = None message = "" remote = False # Construct the request if resource_name not in self.RESOURCE: result = log.FATAL message = "Resource type %s currently not supported for CiviCRM synchronization" % \ resource_name output = xml.json_message(False, 400, message) else: args = Storage(self.RESOURCE[resource_name]) args["q"] += "/get" tree, error = self.send(method="GET", **args) if error: result = log.FATAL remote = True message = error output = xml.json_message(False, 400, error) elif len(tree.getroot()): result = log.SUCCESS remote = False # Get import strategy and update policy strategy = task.strategy update_policy = task.update_policy conflict_policy = task.conflict_policy # Import stylesheet folder = current.request.folder import os stylesheet = os.path.join(folder, "static", "formats", "ccrm", "import.xsl") # Host name of the peer, # used by the import stylesheet import urlparse hostname = urlparse.urlsplit(self.url).hostname # Import the data resource = current.s3db.resource(resource_name) onconflict = lambda item: onconflict(item, self, resource) count = 0 success = True try: success = resource.import_xml(tree, stylesheet=stylesheet, ignore_errors=True, strategy=strategy, update_policy=update_policy, conflict_policy=conflict_policy, last_sync=task.last_pull, onconflict=onconflict, site=hostname) count = resource.import_count except IOError, e: result = log.FATAL message = "%s" % e output = xml.json_message(False, 400, message) mtime = resource.mtime # Log all validation errors if resource.error_tree is not None: result = log.WARNING message = "%s" % resource.error for element in resource.error_tree.findall("resource"): for field in element.findall("data[@error]"): error_msg = field.get("error", None) if error_msg: msg = "(UID: %s) %s.%s=%s: %s" % \ (element.get("uuid", None), element.get("name", None), field.get("field", None), field.get("value", field.text), field.get("error", None)) message = "%s, %s" % (message, msg) # Check for failure if not success: result = log.FATAL if not message: error = current.manager.error message = "%s" % error output = xml.json_message(False, 400, message) mtime = None # ...or report success elif not message: message = "data imported successfully (%s records)" % count output = None else: # No data received from peer result = log.ERROR remote = True message = "no data received from peer" output = None # Log the operation log.write(repository_id=self.id, resource_name=resource_name, transmission=log.OUT, mode=log.PULL, action=None, remote=remote, result=result, message=message) _debug("S3SyncCiviCRM.pull import %s: %s" % (result, message)) return (output, mtime) # ------------------------------------------------------------------------- def push(self, task): """ Push data for a task @param task: the task Row """ xml = current.xml log = self.log resource_name = task.resource_name _debug("S3SyncCiviCRM.push(%s, %s)" % (self.url, resource_name)) result = log.FATAL remote = False message = "Push to CiviCRM currently not supported" output = xml.json_message(False, 400, message) # Log the operation log.write(repository_id=self.id, resource_name=resource_name, transmission=log.OUT, mode=log.PUSH, action=None, remote=remote, result=result, message=message) _debug("S3SyncCiviCRM.push export %s: %s" % (result, message)) return(output, None) # ------------------------------------------------------------------------- def send(self, method="GET", **args): config = self.get_config() # Authentication args = Storage(args) if hasattr(self, "PHPSESSID") and self.PHPSESSID: args["PHPSESSID"] = self.PHPSESSID if hasattr(self, "api_key") and self.api_key: args["api_key"] = self.api_key if hasattr(self, "site_key") and self.site_key: args["key"] = self.site_key # Create the request url = self.url + "?" + urllib.urlencode(args) req = urllib2.Request(url=url) handlers = [] # Proxy handling proxy = self.proxy or config.proxy or None if proxy: _debug("using proxy=%s" % proxy) proxy_handler = urllib2.ProxyHandler({protocol: proxy}) handlers.append(proxy_handler) # Install all handlers if handlers: opener = urllib2.build_opener(*handlers) urllib2.install_opener(opener) # Execute the request response = None message = None try: if method == "POST": f = urllib2.urlopen(req, data="") else: f = urllib2.urlopen(req) except urllib2.HTTPError, e: message = e.read() else: # Parse the response tree = current.xml.parse(f) root = tree.getroot() #print current.xml.tostring(tree, pretty_print=True) is_error = root.xpath("//ResultSet[1]/Result[1]/is_error") if len(is_error) and int(is_error[0].text): error = root.xpath("//ResultSet[1]/Result[1]/error_message") if len(error): message = error[0].text else: message = "Unknown error" else: response = tree return response, message # End =========================================================================
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Generic Node base class for all workers that run on hosts.""" import inspect import os import random from oslo_concurrency import processutils from oslo_config import cfg from oslo_db import exception as db_exc from oslo_log import log as logging import oslo_messaging as messaging from oslo_service import loopingcall from oslo_service import service from oslo_utils import importutils import osprofiler.notifier from osprofiler import profiler import osprofiler.web from cinder import context from cinder import exception from cinder.i18n import _, _LE, _LI, _LW from cinder import objects from cinder.objects import base as objects_base from cinder import rpc from cinder import version from cinder.wsgi import common as wsgi_common from cinder.wsgi import eventlet_server as wsgi LOG = logging.getLogger(__name__) service_opts = [ cfg.IntOpt('report_interval', default=10, help='Interval, in seconds, between nodes reporting state ' 'to datastore'), cfg.IntOpt('periodic_interval', default=60, help='Interval, in seconds, between running periodic tasks'), cfg.IntOpt('periodic_fuzzy_delay', default=60, help='Range, in seconds, to randomly delay when starting the' ' periodic task scheduler to reduce stampeding.' ' (Disable by setting to 0)'), cfg.StrOpt('osapi_volume_listen', default="0.0.0.0", help='IP address on which OpenStack Volume API listens'), cfg.IntOpt('osapi_volume_listen_port', default=8776, min=1, max=65535, help='Port on which OpenStack Volume API listens'), cfg.IntOpt('osapi_volume_workers', help='Number of workers for OpenStack Volume API service. ' 'The default is equal to the number of CPUs available.'), ] profiler_opts = [ cfg.BoolOpt("profiler_enabled", default=False, help=_('If False fully disable profiling feature.')), cfg.BoolOpt("trace_sqlalchemy", default=False, help=_("If False doesn't trace SQL requests.")) ] CONF = cfg.CONF CONF.register_opts(service_opts) CONF.register_opts(profiler_opts, group="profiler") def setup_profiler(binary, host): if CONF.profiler.profiler_enabled: _notifier = osprofiler.notifier.create( "Messaging", messaging, context.get_admin_context().to_dict(), rpc.TRANSPORT, "cinder", binary, host) osprofiler.notifier.set(_notifier) LOG.warning( _LW("OSProfiler is enabled.\nIt means that person who knows " "any of hmac_keys that are specified in " "/etc/cinder/api-paste.ini can trace his requests. \n" "In real life only operator can read this file so there " "is no security issue. Note that even if person can " "trigger profiler, only admin user can retrieve trace " "information.\n" "To disable OSprofiler set in cinder.conf:\n" "[profiler]\nenabled=false")) else: osprofiler.web.disable() class Service(service.Service): """Service object for binaries running on hosts. A service takes a manager and enables rpc by listening to queues based on topic. It also periodically runs tasks on the manager and reports it state to the database services table. """ def __init__(self, host, binary, topic, manager, report_interval=None, periodic_interval=None, periodic_fuzzy_delay=None, service_name=None, *args, **kwargs): super(Service, self).__init__() if not rpc.initialized(): rpc.init(CONF) self.host = host self.binary = binary self.topic = topic self.manager_class_name = manager manager_class = importutils.import_class(self.manager_class_name) manager_class = profiler.trace_cls("rpc")(manager_class) self.manager = manager_class(host=self.host, service_name=service_name, *args, **kwargs) self.report_interval = report_interval self.periodic_interval = periodic_interval self.periodic_fuzzy_delay = periodic_fuzzy_delay self.basic_config_check() self.saved_args, self.saved_kwargs = args, kwargs self.timers = [] setup_profiler(binary, host) self.rpcserver = None def start(self): version_string = version.version_string() LOG.info(_LI('Starting %(topic)s node (version %(version_string)s)'), {'topic': self.topic, 'version_string': version_string}) self.model_disconnected = False self.manager.init_host() ctxt = context.get_admin_context() try: service_ref = objects.Service.get_by_args( ctxt, self.host, self.binary) self.service_id = service_ref.id except exception.NotFound: self._create_service_ref(ctxt) LOG.debug("Creating RPC server for service %s", self.topic) target = messaging.Target(topic=self.topic, server=self.host) endpoints = [self.manager] endpoints.extend(self.manager.additional_endpoints) serializer = objects_base.CinderObjectSerializer() self.rpcserver = rpc.get_server(target, endpoints, serializer) self.rpcserver.start() self.manager.init_host_with_rpc() if self.report_interval: pulse = loopingcall.FixedIntervalLoopingCall( self.report_state) pulse.start(interval=self.report_interval, initial_delay=self.report_interval) self.timers.append(pulse) if self.periodic_interval: if self.periodic_fuzzy_delay: initial_delay = random.randint(0, self.periodic_fuzzy_delay) else: initial_delay = None periodic = loopingcall.FixedIntervalLoopingCall( self.periodic_tasks) periodic.start(interval=self.periodic_interval, initial_delay=initial_delay) self.timers.append(periodic) def basic_config_check(self): """Perform basic config checks before starting service.""" # Make sure report interval is less than service down time if self.report_interval: if CONF.service_down_time <= self.report_interval: new_down_time = int(self.report_interval * 2.5) LOG.warning( _LW("Report interval must be less than service down " "time. Current config service_down_time: " "%(service_down_time)s, report_interval for this: " "service is: %(report_interval)s. Setting global " "service_down_time to: %(new_down_time)s"), {'service_down_time': CONF.service_down_time, 'report_interval': self.report_interval, 'new_down_time': new_down_time}) CONF.set_override('service_down_time', new_down_time) def _create_service_ref(self, context): zone = CONF.storage_availability_zone kwargs = {'host': self.host, 'binary': self.binary, 'topic': self.topic, 'report_count': 0, 'availability_zone': zone} service_ref = objects.Service(context=context, **kwargs) service_ref.create() self.service_id = service_ref.id def __getattr__(self, key): manager = self.__dict__.get('manager', None) return getattr(manager, key) @classmethod def create(cls, host=None, binary=None, topic=None, manager=None, report_interval=None, periodic_interval=None, periodic_fuzzy_delay=None, service_name=None): """Instantiates class and passes back application object. :param host: defaults to CONF.host :param binary: defaults to basename of executable :param topic: defaults to bin_name - 'cinder-' part :param manager: defaults to CONF.<topic>_manager :param report_interval: defaults to CONF.report_interval :param periodic_interval: defaults to CONF.periodic_interval :param periodic_fuzzy_delay: defaults to CONF.periodic_fuzzy_delay """ if not host: host = CONF.host if not binary: binary = os.path.basename(inspect.stack()[-1][1]) if not topic: topic = binary if not manager: subtopic = topic.rpartition('cinder-')[2] manager = CONF.get('%s_manager' % subtopic, None) if report_interval is None: report_interval = CONF.report_interval if periodic_interval is None: periodic_interval = CONF.periodic_interval if periodic_fuzzy_delay is None: periodic_fuzzy_delay = CONF.periodic_fuzzy_delay service_obj = cls(host, binary, topic, manager, report_interval=report_interval, periodic_interval=periodic_interval, periodic_fuzzy_delay=periodic_fuzzy_delay, service_name=service_name) return service_obj def kill(self): """Destroy the service object in the datastore.""" self.stop() try: service_ref = objects.Service.get_by_id( context.get_admin_context(), self.service_id) service_ref.destroy() except exception.NotFound: LOG.warning(_LW('Service killed that has no database entry')) def stop(self): # Try to shut the connection down, but if we get any sort of # errors, go ahead and ignore them.. as we're shutting down anyway try: self.rpcserver.stop() except Exception: pass for x in self.timers: try: x.stop() except Exception: pass self.timers = [] super(Service, self).stop() def wait(self): for x in self.timers: try: x.wait() except Exception: pass if self.rpcserver: self.rpcserver.wait() def periodic_tasks(self, raise_on_error=False): """Tasks to be run at a periodic interval.""" ctxt = context.get_admin_context() self.manager.periodic_tasks(ctxt, raise_on_error=raise_on_error) def report_state(self): """Update the state of this service in the datastore.""" if not self.manager.is_working(): # NOTE(dulek): If manager reports a problem we're not sending # heartbeats - to indicate that service is actually down. LOG.error(_LE('Manager for service %(binary)s %(host)s is ' 'reporting problems, not sending heartbeat. ' 'Service will appear "down".'), {'binary': self.binary, 'host': self.host}) return ctxt = context.get_admin_context() zone = CONF.storage_availability_zone try: try: service_ref = objects.Service.get_by_id(ctxt, self.service_id) except exception.NotFound: LOG.debug('The service database object disappeared, ' 'recreating it.') self._create_service_ref(ctxt) service_ref = objects.Service.get_by_id(ctxt, self.service_id) service_ref.report_count += 1 if zone != service_ref.availability_zone: service_ref.availability_zone = zone service_ref.save() # TODO(termie): make this pattern be more elegant. if getattr(self, 'model_disconnected', False): self.model_disconnected = False LOG.error(_LE('Recovered model server connection!')) except db_exc.DBConnectionError: if not getattr(self, 'model_disconnected', False): self.model_disconnected = True LOG.exception(_LE('model server went away')) # NOTE(jsbryant) Other DB errors can happen in HA configurations. # such errors shouldn't kill this thread, so we handle them here. except db_exc.DBError: if not getattr(self, 'model_disconnected', False): self.model_disconnected = True LOG.exception(_LE('DBError encountered: ')) except Exception: if not getattr(self, 'model_disconnected', False): self.model_disconnected = True LOG.exception(_LE('Exception encountered: ')) class WSGIService(service.ServiceBase): """Provides ability to launch API from a 'paste' configuration.""" def __init__(self, name, loader=None): """Initialize, but do not start the WSGI server. :param name: The name of the WSGI server given to the loader. :param loader: Loads the WSGI application using the given name. :returns: None """ self.name = name self.manager = self._get_manager() self.loader = loader or wsgi_common.Loader() self.app = self.loader.load_app(name) self.host = getattr(CONF, '%s_listen' % name, "0.0.0.0") self.port = getattr(CONF, '%s_listen_port' % name, 0) self.workers = (getattr(CONF, '%s_workers' % name, None) or processutils.get_worker_count()) if self.workers and self.workers < 1: worker_name = '%s_workers' % name msg = (_("%(worker_name)s value of %(workers)d is invalid, " "must be greater than 0.") % {'worker_name': worker_name, 'workers': self.workers}) raise exception.InvalidInput(msg) setup_profiler(name, self.host) self.server = wsgi.Server(name, self.app, host=self.host, port=self.port) def _get_manager(self): """Initialize a Manager object appropriate for this service. Use the service name to look up a Manager subclass from the configuration and initialize an instance. If no class name is configured, just return None. :returns: a Manager instance, or None. """ fl = '%s_manager' % self.name if fl not in CONF: return None manager_class_name = CONF.get(fl, None) if not manager_class_name: return None manager_class = importutils.import_class(manager_class_name) return manager_class() def start(self): """Start serving this service using loaded configuration. Also, retrieve updated port number in case '0' was passed in, which indicates a random port should be used. :returns: None """ if self.manager: self.manager.init_host() self.server.start() self.port = self.server.port def stop(self): """Stop serving this API. :returns: None """ self.server.stop() def wait(self): """Wait for the service to stop serving this API. :returns: None """ self.server.wait() def reset(self): """Reset server greenpool size to default. :returns: None """ self.server.reset() def process_launcher(): return service.ProcessLauncher(CONF) # NOTE(vish): the global launcher is to maintain the existing # functionality of calling service.serve + # service.wait _launcher = None def serve(server, workers=None): global _launcher if _launcher: raise RuntimeError(_('serve() can only be called once')) _launcher = service.launch(CONF, server, workers=workers) def wait(): LOG.debug('Full set of CONF:') for flag in CONF: flag_get = CONF.get(flag, None) # hide flag contents from log if contains a password # should use secret flag when switch over to openstack-common if ("_password" in flag or "_key" in flag or (flag == "sql_connection" and ("mysql:" in flag_get or "postgresql:" in flag_get))): LOG.debug('%s : FLAG SET ', flag) else: LOG.debug('%(flag)s : %(flag_get)s', {'flag': flag, 'flag_get': flag_get}) try: _launcher.wait() except KeyboardInterrupt: _launcher.stop() rpc.cleanup() class Launcher(object): def __init__(self): self.launch_service = serve self.wait = wait def get_launcher(): # Note(lpetrut): ProcessLauncher uses green pipes which fail on Windows # due to missing support of non-blocking I/O pipes. For this reason, the # service must be spawned differently on Windows, using the ServiceLauncher # class instead. if os.name == 'nt': return Launcher() else: return process_launcher()
#!/usr/bin/python # # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Burnin program """ import sys import optparse import time import socket import urllib import random import string # pylint: disable=W0402 from itertools import izip, islice, cycle from cStringIO import StringIO from operator import or_ from ganeti import opcodes from ganeti import constants from ganeti import cli from ganeti import errors from ganeti import utils from ganeti import hypervisor from ganeti import compat from ganeti import pathutils from ganeti.confd import client as confd_client from ganeti.runtime import (GetClient) USAGE = ("\tburnin -o OS_NAME [options...] instance_name ...") MAX_RETRIES = 3 LOG_HEADERS = { 0: "- ", 1: "* ", 2: "", } #: Disk templates supporting a single node _SINGLE_NODE_DISK_TEMPLATES = compat.UniqueFrozenset([ constants.DT_DISKLESS, constants.DT_PLAIN, constants.DT_FILE, constants.DT_SHARED_FILE, constants.DT_EXT, constants.DT_RBD, constants.DT_GLUSTER ]) _SUPPORTED_DISK_TEMPLATES = compat.UniqueFrozenset([ constants.DT_DISKLESS, constants.DT_DRBD8, constants.DT_EXT, constants.DT_FILE, constants.DT_PLAIN, constants.DT_RBD, constants.DT_SHARED_FILE, constants.DT_GLUSTER ]) #: Disk templates for which import/export is tested _IMPEXP_DISK_TEMPLATES = (_SUPPORTED_DISK_TEMPLATES - frozenset([ constants.DT_DISKLESS, constants.DT_FILE, constants.DT_SHARED_FILE, constants.DT_GLUSTER ])) class InstanceDown(Exception): """The checked instance was not up""" class BurninFailure(Exception): """Failure detected during burning""" def Usage(): """Shows program usage information and exits the program.""" print >> sys.stderr, "Usage:" print >> sys.stderr, USAGE sys.exit(2) def Log(msg, *args, **kwargs): """Simple function that prints out its argument. """ if args: msg = msg % args indent = kwargs.get("indent", 0) sys.stdout.write("%*s%s%s\n" % (2 * indent, "", LOG_HEADERS.get(indent, " "), msg)) sys.stdout.flush() def Err(msg, exit_code=1): """Simple error logging that prints to stderr. """ sys.stderr.write(msg + "\n") sys.stderr.flush() sys.exit(exit_code) def RandomString(size=8, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) class SimpleOpener(urllib.FancyURLopener): """A simple url opener""" # pylint: disable=W0221 def prompt_user_passwd(self, host, realm, clear_cache=0): """No-interaction version of prompt_user_passwd.""" # we follow parent class' API # pylint: disable=W0613 return None, None def http_error_default(self, url, fp, errcode, errmsg, headers): """Custom error handling""" # make sure sockets are not left in CLOSE_WAIT, this is similar # but with a different exception to the BasicURLOpener class _ = fp.read() # throw away data fp.close() raise InstanceDown("HTTP error returned: code %s, msg %s" % (errcode, errmsg)) OPTIONS = [ cli.cli_option("-o", "--os", dest="os", default=None, help="OS to use during burnin", metavar="<OS>", completion_suggest=cli.OPT_COMPL_ONE_OS), cli.HYPERVISOR_OPT, cli.OSPARAMS_OPT, cli.cli_option("--disk-size", dest="disk_size", help="Disk size (determines disk count)", default="1G", type="string", metavar="<size,size,...>", completion_suggest=("512M 1G 4G 1G,256M" " 4G,1G,1G 10G").split()), cli.cli_option("--disk-growth", dest="disk_growth", help="Disk growth", default="128m", type="string", metavar="<size,size,...>"), cli.cli_option("--mem-size", dest="mem_size", help="Memory size", default=None, type="unit", metavar="<size>", completion_suggest=("128M 256M 512M 1G 4G 8G" " 12G 16G").split()), cli.cli_option("--maxmem-size", dest="maxmem_size", help="Max Memory size", default=256, type="unit", metavar="<size>", completion_suggest=("128M 256M 512M 1G 4G 8G" " 12G 16G").split()), cli.cli_option("--minmem-size", dest="minmem_size", help="Min Memory size", default=128, type="unit", metavar="<size>", completion_suggest=("128M 256M 512M 1G 4G 8G" " 12G 16G").split()), cli.cli_option("--vcpu-count", dest="vcpu_count", help="VCPU count", default=3, type="unit", metavar="<count>", completion_suggest=("1 2 3 4").split()), cli.DEBUG_OPT, cli.VERBOSE_OPT, cli.NOIPCHECK_OPT, cli.NONAMECHECK_OPT, cli.EARLY_RELEASE_OPT, cli.cli_option("--no-replace1", dest="do_replace1", help="Skip disk replacement with the same secondary", action="store_false", default=True), cli.cli_option("--no-replace2", dest="do_replace2", help="Skip disk replacement with a different secondary", action="store_false", default=True), cli.cli_option("--no-failover", dest="do_failover", help="Skip instance failovers", action="store_false", default=True), cli.cli_option("--no-migrate", dest="do_migrate", help="Skip instance live migration", action="store_false", default=True), cli.cli_option("--no-move", dest="do_move", help="Skip instance moves", action="store_false", default=True), cli.cli_option("--no-importexport", dest="do_importexport", help="Skip instance export/import", action="store_false", default=True), cli.cli_option("--no-startstop", dest="do_startstop", help="Skip instance stop/start", action="store_false", default=True), cli.cli_option("--no-reinstall", dest="do_reinstall", help="Skip instance reinstall", action="store_false", default=True), cli.cli_option("--no-reboot", dest="do_reboot", help="Skip instance reboot", action="store_false", default=True), cli.cli_option("--no-renamesame", dest="do_renamesame", help="Skip instance rename to same name", action="store_false", default=True), cli.cli_option("--reboot-types", dest="reboot_types", help="Specify the reboot types", default=None), cli.cli_option("--no-activate-disks", dest="do_activate_disks", help="Skip disk activation/deactivation", action="store_false", default=True), cli.cli_option("--no-add-disks", dest="do_addremove_disks", help="Skip disk addition/removal", action="store_false", default=True), cli.cli_option("--no-add-nics", dest="do_addremove_nics", help="Skip NIC addition/removal", action="store_false", default=True), cli.cli_option("--no-nics", dest="nics", help="No network interfaces", action="store_const", const=[], default=[{}]), cli.cli_option("--no-confd", dest="do_confd_tests", help="Skip confd queries", action="store_false", default=True), cli.cli_option("--rename", dest="rename", default=None, help=("Give one unused instance name which is taken" " to start the renaming sequence"), metavar="<instance_name>"), cli.cli_option("-t", "--disk-template", dest="disk_template", choices=list(_SUPPORTED_DISK_TEMPLATES), default=constants.DT_DRBD8, help=("Disk template (default %s, otherwise one of %s)" % (constants.DT_DRBD8, utils.CommaJoin(_SUPPORTED_DISK_TEMPLATES)))), cli.cli_option("-n", "--nodes", dest="nodes", default="", help=("Comma separated list of nodes to perform" " the burnin on (defaults to all nodes)"), completion_suggest=cli.OPT_COMPL_MANY_NODES), cli.cli_option("-I", "--iallocator", dest="iallocator", default=None, type="string", help=("Perform the allocation using an iallocator" " instead of fixed node spread (node restrictions no" " longer apply, therefore -n/--nodes must not be" " used"), completion_suggest=cli.OPT_COMPL_ONE_IALLOCATOR), cli.cli_option("-p", "--parallel", default=False, action="store_true", dest="parallel", help=("Enable parallelization of some operations in" " order to speed burnin or to test granular locking")), cli.cli_option("--net-timeout", default=15, type="int", dest="net_timeout", help=("The instance check network timeout in seconds" " (defaults to 15 seconds)"), completion_suggest="15 60 300 900".split()), cli.cli_option("-C", "--http-check", default=False, action="store_true", dest="http_check", help=("Enable checking of instance status via http," " looking for /hostname.txt that should contain the" " name of the instance")), cli.cli_option("-K", "--keep-instances", default=False, action="store_true", dest="keep_instances", help=("Leave instances on the cluster after burnin," " for investigation in case of errors or simply" " to use them")), cli.REASON_OPT, ] # Mainly used for bash completion ARGUMENTS = [cli.ArgInstance(min=1)] def _DoCheckInstances(fn): """Decorator for checking instances. """ def wrapper(self, *args, **kwargs): val = fn(self, *args, **kwargs) for instance in self.instances: self._CheckInstanceAlive(instance) # pylint: disable=W0212 return val return wrapper def _DoBatch(retry): """Decorator for possible batch operations. Must come after the _DoCheckInstances decorator (if any). @param retry: whether this is a retryable batch, will be passed to StartBatch """ def wrap(fn): def batched(self, *args, **kwargs): self.StartBatch(retry) val = fn(self, *args, **kwargs) self.CommitQueue() return val return batched return wrap class FeedbackAccumulator(object): """Feedback accumulator class.""" _feed_buf = StringIO() opts = None def ClearFeedbackBuf(self): """Clear the feedback buffer.""" self._feed_buf.truncate(0) def GetFeedbackBuf(self): """Return the contents of the buffer.""" return self._feed_buf.getvalue() def Feedback(self, msg): """Acumulate feedback in our buffer.""" formatted_msg = "%s %s" % (time.ctime(utils.MergeTime(msg[0])), msg[2]) self._feed_buf.write(formatted_msg + "\n") if self.opts.verbose: Log(formatted_msg, indent=3) class JobHandler(FeedbackAccumulator): """Class for handling Ganeti jobs.""" queued_ops = [] queue_retry = False def __init__(self): self.cl = cli.GetClient() def MaybeRetry(self, retry_count, msg, fn, *args): """Possibly retry a given function execution. @type retry_count: int @param retry_count: retry counter: - 0: non-retryable action - 1: last retry for a retryable action - MAX_RETRIES: original try for a retryable action @type msg: str @param msg: the kind of the operation @type fn: callable @param fn: the function to be called """ try: val = fn(*args) if retry_count > 0 and retry_count < MAX_RETRIES: Log("Idempotent %s succeeded after %d retries", msg, MAX_RETRIES - retry_count) return val except Exception, err: # pylint: disable=W0703 if retry_count == 0: Log("Non-idempotent %s failed, aborting", msg) raise elif retry_count == 1: Log("Idempotent %s repeated failure, aborting", msg) raise else: Log("Idempotent %s failed, retry #%d/%d: %s", msg, MAX_RETRIES - retry_count + 1, MAX_RETRIES, err) self.MaybeRetry(retry_count - 1, msg, fn, *args) def _ExecOp(self, *ops): """Execute one or more opcodes and manage the exec buffer. @return: if only opcode has been passed, we return its result; otherwise we return the list of results """ job_id = cli.SendJob(ops, cl=self.cl) results = cli.PollJob(job_id, cl=self.cl, feedback_fn=self.Feedback) if len(ops) == 1: return results[0] else: return results def ExecOp(self, retry, *ops): """Execute one or more opcodes and manage the exec buffer. @return: if only opcode has been passed, we return its result; otherwise we return the list of results """ if retry: rval = MAX_RETRIES else: rval = 0 cli.SetGenericOpcodeOpts(ops, self.opts) return self.MaybeRetry(rval, "opcode", self._ExecOp, *ops) def ExecOrQueue(self, name, ops, post_process=None): """Execute an opcode and manage the exec buffer.""" if self.opts.parallel: cli.SetGenericOpcodeOpts(ops, self.opts) self.queued_ops.append((ops, name, post_process)) else: val = self.ExecOp(self.queue_retry, *ops) if post_process is not None: post_process() return val def StartBatch(self, retry): """Start a new batch of jobs. @param retry: whether this is a retryable batch """ self.queued_ops = [] self.queue_retry = retry def CommitQueue(self): """Execute all submitted opcodes in case of parallel burnin""" if not self.opts.parallel or not self.queued_ops: return if self.queue_retry: rval = MAX_RETRIES else: rval = 0 try: results = self.MaybeRetry(rval, "jobset", self.ExecJobSet, self.queued_ops) finally: self.queued_ops = [] return results def ExecJobSet(self, jobs): """Execute a set of jobs and return once all are done. The method will return the list of results, if all jobs are successful. Otherwise, OpExecError will be raised from within cli.py. """ self.ClearFeedbackBuf() jex = cli.JobExecutor(cl=self.cl, feedback_fn=self.Feedback) for ops, name, _ in jobs: jex.QueueJob(name, *ops) try: results = jex.GetResults() except Exception, err: # pylint: disable=W0703 Log("Jobs failed: %s", err) raise BurninFailure() fail = False val = [] for (_, name, post_process), (success, result) in zip(jobs, results): if success: if post_process: try: post_process() except Exception, err: # pylint: disable=W0703 Log("Post process call for job %s failed: %s", name, err) fail = True val.append(result) else: fail = True if fail: raise BurninFailure() return val class Burner(JobHandler): """Burner class.""" def __init__(self): """Constructor.""" super(Burner, self).__init__() self.url_opener = SimpleOpener() self.nodes = [] self.instances = [] self.to_rem = [] self.disk_count = self.disk_growth = self.disk_size = None self.hvp = self.bep = None self.ParseOptions() self.disk_nodes = {} self.instance_nodes = {} self.GetState() self.confd_reply = None def ParseOptions(self): """Parses the command line options. In case of command line errors, it will show the usage and exit the program. """ parser = optparse.OptionParser(usage="\n%s" % USAGE, version=("%%prog (ganeti) %s" % constants.RELEASE_VERSION), option_list=OPTIONS) options, args = parser.parse_args() if len(args) < 1 or options.os is None: Usage() if options.mem_size: options.maxmem_size = options.mem_size options.minmem_size = options.mem_size elif options.minmem_size > options.maxmem_size: Err("Maximum memory lower than minimum memory") if options.disk_template not in _SUPPORTED_DISK_TEMPLATES: Err("Unknown or unsupported disk template '%s'" % options.disk_template) if options.disk_template == constants.DT_DISKLESS: disk_size = disk_growth = [] options.do_addremove_disks = False else: disk_size = [utils.ParseUnit(v) for v in options.disk_size.split(",")] disk_growth = [utils.ParseUnit(v) for v in options.disk_growth.split(",")] if len(disk_growth) != len(disk_size): Err("Wrong disk sizes/growth combination") if ((disk_size and options.disk_template == constants.DT_DISKLESS) or (not disk_size and options.disk_template != constants.DT_DISKLESS)): Err("Wrong disk count/disk template combination") self.disk_size = disk_size self.disk_growth = disk_growth self.disk_count = len(disk_size) if options.nodes and options.iallocator: Err("Give either the nodes option or the iallocator option, not both") if options.http_check and not options.name_check: Err("Can't enable HTTP checks without name checks") self.opts = options self.instances = args self.bep = { constants.BE_MINMEM: options.minmem_size, constants.BE_MAXMEM: options.maxmem_size, constants.BE_VCPUS: options.vcpu_count, } self.hypervisor = None self.hvp = {} if options.hypervisor: self.hypervisor, self.hvp = options.hypervisor if options.reboot_types is None: options.reboot_types = constants.REBOOT_TYPES else: options.reboot_types = options.reboot_types.split(",") rt_diff = set(options.reboot_types).difference(constants.REBOOT_TYPES) if rt_diff: Err("Invalid reboot types specified: %s" % utils.CommaJoin(rt_diff)) socket.setdefaulttimeout(options.net_timeout) def GetState(self): """Read the cluster state from the master daemon.""" if self.opts.nodes: names = self.opts.nodes.split(",") else: names = [] try: qcl = GetClient() result = qcl.QueryNodes(names, ["name", "offline", "drained"], False) except errors.GenericError, err: err_code, msg = cli.FormatError(err) Err(msg, exit_code=err_code) finally: qcl.Close() self.nodes = [data[0] for data in result if not (data[1] or data[2])] op_diagnose = opcodes.OpOsDiagnose(output_fields=["name", "variants", "hidden"], names=[]) result = self.ExecOp(True, op_diagnose) if not result: Err("Can't get the OS list") found = False for (name, variants, _) in result: if self.opts.os in cli.CalculateOSNames(name, variants): found = True break if not found: Err("OS '%s' not found" % self.opts.os) cluster_info = self.cl.QueryClusterInfo() self.cluster_info = cluster_info if not self.cluster_info: Err("Can't get cluster info") default_nic_params = self.cluster_info["nicparams"][constants.PP_DEFAULT] self.cluster_default_nicparams = default_nic_params if self.hypervisor is None: self.hypervisor = self.cluster_info["default_hypervisor"] self.hv_can_migrate = \ hypervisor.GetHypervisorClass(self.hypervisor).CAN_MIGRATE def FindMatchingDisk(self, instance): """Find a disk whose nodes match the instance's disk nodes.""" instance_nodes = self.instance_nodes[instance] for disk, disk_nodes in self.disk_nodes.iteritems(): if instance_nodes == disk_nodes: # Erase that disk from the dictionary so that we don't pick it again. del self.disk_nodes[disk] return disk Err("Couldn't find matching detached disk for instance %s" % instance) @_DoCheckInstances @_DoBatch(False) def BurnCreateInstances(self): """Create the given instances. """ self.to_rem = [] mytor = izip(cycle(self.nodes), islice(cycle(self.nodes), 1, None), self.instances) Log("Creating instances") for pnode, snode, instance in mytor: Log("instance %s", instance, indent=1) if self.opts.iallocator: pnode = snode = None msg = "with iallocator %s" % self.opts.iallocator elif self.opts.disk_template not in constants.DTS_INT_MIRROR: snode = None msg = "on %s" % pnode else: msg = "on %s, %s" % (pnode, snode) Log(msg, indent=2) op = opcodes.OpInstanceCreate(instance_name=instance, disks=[{"size": size} for size in self.disk_size], disk_template=self.opts.disk_template, nics=self.opts.nics, mode=constants.INSTANCE_CREATE, os_type=self.opts.os, pnode=pnode, snode=snode, start=True, ip_check=self.opts.ip_check, name_check=self.opts.name_check, wait_for_sync=True, file_driver="loop", file_storage_dir=None, iallocator=self.opts.iallocator, beparams=self.bep, hvparams=self.hvp, hypervisor=self.hypervisor, osparams=self.opts.osparams, ) # NB the i=instance default param is needed here so the lambda captures # the variable. See https://docs.python.org/2/faq/programming.html#id11 rm_inst = lambda i=instance: self.to_rem.append(i) # pylint: disable=C0322 self.ExecOrQueue(instance, [op], post_process=rm_inst) @_DoBatch(False) def BurnModifyRuntimeMemory(self): """Alter the runtime memory.""" Log("Setting instance runtime memory") for instance in self.instances: Log("instance %s", instance, indent=1) tgt_mem = self.bep[constants.BE_MINMEM] op = opcodes.OpInstanceSetParams(instance_name=instance, runtime_mem=tgt_mem) Log("Set memory to %s MB", tgt_mem, indent=2) self.ExecOrQueue(instance, [op]) @_DoBatch(False) def BurnGrowDisks(self): """Grow both the os and the swap disks by the requested amount, if any.""" Log("Growing disks") for instance in self.instances: Log("instance %s", instance, indent=1) for idx, growth in enumerate(self.disk_growth): if growth > 0: op = opcodes.OpInstanceGrowDisk(instance_name=instance, disk=idx, amount=growth, wait_for_sync=True, ignore_ipolicy=True) Log("increase disk/%s by %s MB", idx, growth, indent=2) self.ExecOrQueue(instance, [op]) @_DoBatch(True) def BurnReplaceDisks1D8(self): """Replace disks on primary and secondary for drbd8.""" Log("Replacing disks on the same nodes") early_release = self.opts.early_release for instance in self.instances: Log("instance %s", instance, indent=1) ops = [] for mode in constants.REPLACE_DISK_SEC, constants.REPLACE_DISK_PRI: op = opcodes.OpInstanceReplaceDisks(instance_name=instance, mode=mode, disks=list(range(self.disk_count)), early_release=early_release) Log("run %s", mode, indent=2) ops.append(op) self.ExecOrQueue(instance, ops) @_DoBatch(True) def BurnReplaceDisks2(self): """Replace secondary node.""" Log("Changing the secondary node") mode = constants.REPLACE_DISK_CHG mytor = izip(islice(cycle(self.nodes), 2, None), self.instances) for tnode, instance in mytor: Log("instance %s", instance, indent=1) if self.opts.iallocator: tnode = None msg = "with iallocator %s" % self.opts.iallocator else: msg = tnode op = opcodes.OpInstanceReplaceDisks(instance_name=instance, mode=mode, remote_node=tnode, iallocator=self.opts.iallocator, disks=[], early_release=self.opts.early_release) Log("run %s %s", mode, msg, indent=2) self.ExecOrQueue(instance, [op]) @_DoCheckInstances @_DoBatch(False) def BurnFailover(self): """Failover the instances.""" Log("Failing over instances") for instance in self.instances: Log("instance %s", instance, indent=1) op = opcodes.OpInstanceFailover(instance_name=instance, ignore_consistency=False) self.ExecOrQueue(instance, [op]) @_DoCheckInstances @_DoBatch(False) def BurnMove(self): """Move the instances.""" Log("Moving instances") mytor = izip(islice(cycle(self.nodes), 1, None), self.instances) for tnode, instance in mytor: Log("instance %s", instance, indent=1) op = opcodes.OpInstanceMove(instance_name=instance, target_node=tnode) self.ExecOrQueue(instance, [op]) @_DoBatch(False) def BurnMigrate(self): """Migrate the instances.""" Log("Migrating instances") for instance in self.instances: Log("instance %s", instance, indent=1) op1 = opcodes.OpInstanceMigrate(instance_name=instance, mode=None, cleanup=False) op2 = opcodes.OpInstanceMigrate(instance_name=instance, mode=None, cleanup=True) Log("migration and migration cleanup", indent=2) self.ExecOrQueue(instance, [op1, op2]) @_DoCheckInstances @_DoBatch(False) def BurnImportExport(self): """Export the instance, delete it, and import it back. """ Log("Exporting and re-importing instances") mytor = izip(cycle(self.nodes), islice(cycle(self.nodes), 1, None), islice(cycle(self.nodes), 2, None), self.instances) qcl = GetClient() for pnode, snode, enode, instance in mytor: Log("instance %s", instance, indent=1) # read the full name of the instance (full_name, ) = qcl.QueryInstances([instance], ["name"], False)[0] if self.opts.iallocator: pnode = snode = None import_log_msg = ("import from %s" " with iallocator %s" % (enode, self.opts.iallocator)) elif self.opts.disk_template not in constants.DTS_INT_MIRROR: snode = None import_log_msg = ("import from %s to %s" % (enode, pnode)) else: import_log_msg = ("import from %s to %s, %s" % (enode, pnode, snode)) exp_op = opcodes.OpBackupExport(instance_name=instance, target_node=enode, mode=constants.EXPORT_MODE_LOCAL, shutdown=True) rem_op = opcodes.OpInstanceRemove(instance_name=instance, ignore_failures=True) imp_dir = utils.PathJoin(pathutils.EXPORT_DIR, full_name) imp_op = opcodes.OpInstanceCreate(instance_name=instance, disks=[{"size": size} for size in self.disk_size], disk_template=self.opts.disk_template, nics=self.opts.nics, mode=constants.INSTANCE_IMPORT, src_node=enode, src_path=imp_dir, pnode=pnode, snode=snode, start=True, ip_check=self.opts.ip_check, name_check=self.opts.name_check, wait_for_sync=True, file_storage_dir=None, file_driver="loop", iallocator=self.opts.iallocator, beparams=self.bep, hvparams=self.hvp, osparams=self.opts.osparams, ) erem_op = opcodes.OpBackupRemove(instance_name=instance) Log("export to node %s", enode, indent=2) Log("remove instance", indent=2) Log(import_log_msg, indent=2) Log("remove export", indent=2) self.ExecOrQueue(instance, [exp_op, rem_op, imp_op, erem_op]) qcl.Close() @staticmethod def StopInstanceOp(instance): """Stop given instance.""" return opcodes.OpInstanceShutdown(instance_name=instance) @staticmethod def StartInstanceOp(instance): """Start given instance.""" return opcodes.OpInstanceStartup(instance_name=instance, force=False) @staticmethod def RenameInstanceOp(instance, instance_new, name_check, ip_check): """Rename instance.""" return opcodes.OpInstanceRename(instance_name=instance, new_name=instance_new, name_check=name_check, ip_check=ip_check) @_DoCheckInstances @_DoBatch(True) def BurnStopStart(self): """Stop/start the instances.""" Log("Stopping and starting instances") for instance in self.instances: Log("instance %s", instance, indent=1) op1 = self.StopInstanceOp(instance) op2 = self.StartInstanceOp(instance) self.ExecOrQueue(instance, [op1, op2]) @_DoBatch(False) def BurnRemove(self): """Remove the instances.""" Log("Removing instances") for instance in self.to_rem: Log("instance %s", instance, indent=1) op = opcodes.OpInstanceRemove(instance_name=instance, ignore_failures=True) self.ExecOrQueue(instance, [op]) def BurnRename(self, name_check, ip_check): """Rename the instances. Note that this function will not execute in parallel, since we only have one target for rename. """ Log("Renaming instances") rename = self.opts.rename for instance in self.instances: Log("instance %s", instance, indent=1) op_stop1 = self.StopInstanceOp(instance) op_stop2 = self.StopInstanceOp(rename) op_rename1 = self.RenameInstanceOp(instance, rename, name_check, ip_check) op_rename2 = self.RenameInstanceOp(rename, instance, name_check, ip_check) op_start1 = self.StartInstanceOp(rename) op_start2 = self.StartInstanceOp(instance) self.ExecOp(False, op_stop1, op_rename1, op_start1) self._CheckInstanceAlive(rename) self.ExecOp(False, op_stop2, op_rename2, op_start2) self._CheckInstanceAlive(instance) @_DoCheckInstances @_DoBatch(True) def BurnReinstall(self): """Reinstall the instances.""" Log("Reinstalling instances") for instance in self.instances: Log("instance %s", instance, indent=1) op1 = self.StopInstanceOp(instance) op2 = opcodes.OpInstanceReinstall(instance_name=instance) Log("reinstall without passing the OS", indent=2) op3 = opcodes.OpInstanceReinstall(instance_name=instance, os_type=self.opts.os) Log("reinstall specifying the OS", indent=2) op4 = self.StartInstanceOp(instance) self.ExecOrQueue(instance, [op1, op2, op3, op4]) @_DoCheckInstances @_DoBatch(True) def BurnReboot(self): """Reboot the instances.""" Log("Rebooting instances") for instance in self.instances: Log("instance %s", instance, indent=1) ops = [] for reboot_type in self.opts.reboot_types: op = opcodes.OpInstanceReboot(instance_name=instance, reboot_type=reboot_type, ignore_secondaries=False) Log("reboot with type '%s'", reboot_type, indent=2) ops.append(op) self.ExecOrQueue(instance, ops) @_DoCheckInstances @_DoBatch(True) def BurnRenameSame(self, name_check, ip_check): """Rename the instances to their own name.""" Log("Renaming the instances to their own name") for instance in self.instances: Log("instance %s", instance, indent=1) op1 = self.StopInstanceOp(instance) op2 = self.RenameInstanceOp(instance, instance, name_check, ip_check) Log("rename to the same name", indent=2) op4 = self.StartInstanceOp(instance) self.ExecOrQueue(instance, [op1, op2, op4]) @_DoCheckInstances @_DoBatch(True) def BurnActivateDisks(self): """Activate and deactivate disks of the instances.""" Log("Activating/deactivating disks") for instance in self.instances: Log("instance %s", instance, indent=1) op_start = self.StartInstanceOp(instance) op_act = opcodes.OpInstanceActivateDisks(instance_name=instance) op_deact = opcodes.OpInstanceDeactivateDisks(instance_name=instance) op_stop = self.StopInstanceOp(instance) Log("activate disks when online", indent=2) Log("activate disks when offline", indent=2) Log("deactivate disks (when offline)", indent=2) self.ExecOrQueue(instance, [op_act, op_stop, op_act, op_deact, op_start]) @_DoBatch(False) def BurnAddRemoveNICs(self): """Add, change and remove an extra NIC for the instances.""" Log("Adding and removing NICs") for instance in self.instances: Log("instance %s", instance, indent=1) op_add = opcodes.OpInstanceSetParams( instance_name=instance, nics=[(constants.DDM_ADD, {})]) op_chg = opcodes.OpInstanceSetParams( instance_name=instance, nics=[(constants.DDM_MODIFY, -1, {"mac": constants.VALUE_GENERATE})]) op_rem = opcodes.OpInstanceSetParams( instance_name=instance, nics=[(constants.DDM_REMOVE, {})]) Log("adding a NIC", indent=2) Log("changing a NIC", indent=2) Log("removing last NIC", indent=2) self.ExecOrQueue(instance, [op_add, op_chg, op_rem]) def ConfdCallback(self, reply): """Callback for confd queries""" if reply.type == confd_client.UPCALL_REPLY: if reply.server_reply.status != constants.CONFD_REPL_STATUS_OK: Err("Query %s gave non-ok status %s: %s" % (reply.orig_request, reply.server_reply.status, reply.server_reply)) if reply.orig_request.type == constants.CONFD_REQ_PING: Log("Ping: OK", indent=1) elif reply.orig_request.type == constants.CONFD_REQ_CLUSTER_MASTER: if reply.server_reply.answer == self.cluster_info["master"]: Log("Master: OK", indent=1) else: Err("Master: wrong: %s" % reply.server_reply.answer) elif reply.orig_request.type == constants.CONFD_REQ_NODE_ROLE_BYNAME: if reply.server_reply.answer == constants.CONFD_NODE_ROLE_MASTER: Log("Node role for master: OK", indent=1) else: Err("Node role for master: wrong: %s" % reply.server_reply.answer) elif reply.orig_request.type == constants.CONFD_REQ_INSTANCE_DISKS: self.confd_reply = reply.server_reply.answer def DoConfdRequestReply(self, req): self.confd_counting_callback.RegisterQuery(req.rsalt) self.confd_client.SendRequest(req, async=False) while not self.confd_counting_callback.AllAnswered(): if not self.confd_client.ReceiveReply(): Err("Did not receive all expected confd replies") break def BurnConfd(self): """Run confd queries for our instances. The following confd queries are tested: - CONFD_REQ_PING: simple ping - CONFD_REQ_CLUSTER_MASTER: cluster master - CONFD_REQ_NODE_ROLE_BYNAME: node role, for the master """ Log("Checking confd results") filter_callback = confd_client.ConfdFilterCallback(self.ConfdCallback) counting_callback = confd_client.ConfdCountingCallback(filter_callback) self.confd_counting_callback = counting_callback self.confd_client = confd_client.GetConfdClient(counting_callback) req = confd_client.ConfdClientRequest(type=constants.CONFD_REQ_PING) self.DoConfdRequestReply(req) req = confd_client.ConfdClientRequest( type=constants.CONFD_REQ_CLUSTER_MASTER) self.DoConfdRequestReply(req) req = confd_client.ConfdClientRequest( type=constants.CONFD_REQ_NODE_ROLE_BYNAME, query=self.cluster_info["master"]) self.DoConfdRequestReply(req) @_DoCheckInstances @_DoBatch(False) def BurnAddDisks(self): """Add an extra disk to every instance and then detach it.""" Log("Adding and detaching disks") # Instantiate a Confd client filter_callback = confd_client.ConfdFilterCallback(self.ConfdCallback) counting_callback = confd_client.ConfdCountingCallback(filter_callback) self.confd_counting_callback = counting_callback self.confd_client = confd_client.GetConfdClient(counting_callback) # Iterate all instances, start them, add a disk with a unique name and # detach it. Do all disk operations with hotplugging (if possible). for instance in self.instances: Log("instance %s", instance, indent=1) # Fetch disk info for an instance from the confd. The result of the query # will be stored in the confd_reply attribute of Burner. req = (confd_client.ConfdClientRequest( type=constants.CONFD_REQ_INSTANCE_DISKS, query=instance)) self.DoConfdRequestReply(req) disk_name = RandomString() nodes = [set(disk["nodes"]) for disk in self.confd_reply] nodes = reduce(or_, nodes) self.instance_nodes[instance] = nodes self.disk_nodes[disk_name] = nodes op_stop = self.StopInstanceOp(instance) op_add = opcodes.OpInstanceSetParams( instance_name=instance, hotplug_if_possible=True, disks=[(constants.DDM_ADD, {"size": self.disk_size[0], "name": disk_name})]) op_detach = opcodes.OpInstanceSetParams( instance_name=instance, hotplug_if_possible=True, disks=[(constants.DDM_DETACH, {})]) op_start = self.StartInstanceOp(instance) Log("adding a disk with name %s" % disk_name, indent=2) Log("detaching last disk", indent=2) self.ExecOrQueue(instance, [op_start, op_add, op_detach, op_stop, op_start]) @_DoCheckInstances @_DoBatch(False) def BurnRemoveDisks(self): """Attach a previously detached disk to an instance and then remove it.""" Log("Attaching and removing disks") # Iterate all instances in random order, attach the detached disks, remove # them and then restart the instances. Do all disk operation with # hotplugging (if possible). instances_copy = list(self.instances) random.shuffle(instances_copy) for instance in instances_copy: Log("instance %s", instance, indent=1) disk_name = self.FindMatchingDisk(instance) op_attach = opcodes.OpInstanceSetParams( instance_name=instance, hotplug_if_possible=True, disks=[(constants.DDM_ATTACH, {"name": disk_name})]) op_rem = opcodes.OpInstanceSetParams( instance_name=instance, hotplug_if_possible=True, disks=[(constants.DDM_REMOVE, {})]) op_stop = self.StopInstanceOp(instance) op_start = self.StartInstanceOp(instance) Log("attaching a disk with name %s" % disk_name, indent=2) Log("removing last disk", indent=2) self.ExecOrQueue(instance, [op_attach, op_rem, op_stop, op_start]) # Disk nodes are useful only for this test. del self.disk_nodes del self.instance_nodes def _CheckInstanceAlive(self, instance): """Check if an instance is alive by doing http checks. This will try to retrieve the url on the instance /hostname.txt and check that it contains the hostname of the instance. In case we get ECONNREFUSED, we retry up to the net timeout seconds, for any other error we abort. """ if not self.opts.http_check: return end_time = time.time() + self.opts.net_timeout url = None while time.time() < end_time and url is None: try: url = self.url_opener.open("http://%s/hostname.txt" % instance) except IOError: # here we can have connection refused, no route to host, etc. time.sleep(1) if url is None: raise InstanceDown(instance, "Cannot contact instance") hostname = url.read().strip() url.close() if hostname != instance: raise InstanceDown(instance, ("Hostname mismatch, expected %s, got %s" % (instance, hostname))) def BurninCluster(self): """Test a cluster intensively. This will create instances and then start/stop/failover them. It is safe for existing instances but could impact performance. """ Log("Testing global parameters") if (len(self.nodes) == 1 and self.opts.disk_template not in _SINGLE_NODE_DISK_TEMPLATES): Err("When one node is available/selected the disk template must" " be one of %s" % utils.CommaJoin(_SINGLE_NODE_DISK_TEMPLATES)) has_err = True try: self.BurnCreateInstances() if self.opts.do_startstop: self.BurnStopStart() if self.bep[constants.BE_MINMEM] < self.bep[constants.BE_MAXMEM]: self.BurnModifyRuntimeMemory() if self.opts.do_replace1 and \ self.opts.disk_template in constants.DTS_INT_MIRROR: self.BurnReplaceDisks1D8() if (self.opts.do_replace2 and len(self.nodes) > 2 and self.opts.disk_template in constants.DTS_INT_MIRROR): self.BurnReplaceDisks2() if (self.opts.disk_template in constants.DTS_GROWABLE and compat.any(n > 0 for n in self.disk_growth)): self.BurnGrowDisks() if self.opts.do_failover and \ self.opts.disk_template in constants.DTS_MIRRORED: self.BurnFailover() if self.opts.do_migrate: if self.opts.disk_template not in constants.DTS_MIRRORED: Log("Skipping migration (disk template %s does not support it)", self.opts.disk_template) elif not self.hv_can_migrate: Log("Skipping migration (hypervisor %s does not support it)", self.hypervisor) else: self.BurnMigrate() if (self.opts.do_move and len(self.nodes) > 1 and self.opts.disk_template in [constants.DT_PLAIN, constants.DT_FILE]): self.BurnMove() if (self.opts.do_importexport and self.opts.disk_template in _IMPEXP_DISK_TEMPLATES): self.BurnImportExport() if self.opts.do_reinstall: self.BurnReinstall() if self.opts.do_reboot: self.BurnReboot() if self.opts.do_renamesame: self.BurnRenameSame(self.opts.name_check, self.opts.ip_check) if self.opts.do_confd_tests: self.BurnConfd() default_nic_mode = self.cluster_default_nicparams[constants.NIC_MODE] # Don't add/remove nics in routed mode, as we would need an ip to add # them with if self.opts.do_addremove_nics: if default_nic_mode == constants.NIC_MODE_BRIDGED: self.BurnAddRemoveNICs() else: Log("Skipping nic add/remove as the cluster is not in bridged mode") if self.opts.do_activate_disks: self.BurnActivateDisks() if self.opts.do_addremove_disks: self.BurnAddDisks() self.BurnRemoveDisks() if self.opts.rename: self.BurnRename(self.opts.name_check, self.opts.ip_check) has_err = False finally: if has_err: Log("Error detected: opcode buffer follows:\n\n") Log(self.GetFeedbackBuf()) Log("\n\n") if not self.opts.keep_instances: try: self.BurnRemove() except Exception, err: # pylint: disable=W0703 if has_err: # already detected errors, so errors in removal # are quite expected Log("Note: error detected during instance remove: %s", err) else: # non-expected error raise return constants.EXIT_SUCCESS def Main(): """Main function. """ utils.SetupLogging(pathutils.LOG_BURNIN, sys.argv[0], debug=False, stderr_logging=True) return Burner().BurninCluster()
import json from datetime import datetime, timedelta from django.conf import settings from django.core.cache import cache from django.core.urlresolvers import reverse import mock from cache_nuggets.lib import Token from nose.tools import eq_, ok_ from test_utils import RequestFactory import amo import mkt.regions from amo.tests import ESTestCase from mkt.access.models import GroupUser from mkt.api.models import Access, generate from mkt.api.tests.test_oauth import RestOAuth, RestOAuthClient from mkt.constants.features import FeatureProfile from mkt.reviewers.models import AdditionalReview, QUEUE_TARAKO from mkt.reviewers.utils import AppsReviewing from mkt.site.fixtures import fixture from mkt.tags.models import Tag from mkt.webapps.models import Webapp from mkt.users.models import UserProfile class TestReviewing(RestOAuth): fixtures = fixture('user_2519', 'webapp_337141') def setUp(self): super(TestReviewing, self).setUp() self.list_url = reverse('reviewing-list') self.user = UserProfile.objects.get(pk=2519) self.req = RequestFactory().get('/') self.req.user = self.user def test_verbs(self): self._allowed_verbs(self.list_url, ('get')) def test_not_allowed(self): eq_(self.anon.get(self.list_url).status_code, 403) def test_still_not_allowed(self): eq_(self.client.get(self.list_url).status_code, 403) def add_perms(self): self.grant_permission(self.user, 'Apps:Review') def test_allowed(self): self.add_perms() res = self.client.get(self.list_url) eq_(res.status_code, 200, res.content) data = json.loads(res.content) eq_(data['objects'], []) def test_some(self): self.add_perms() # This feels rather brittle. cache.set('%s:review_viewing:%s' % (settings.CACHE_PREFIX, 337141), 2519, 50 * 2) AppsReviewing(self.req).add(337141) res = self.client.get(self.list_url) data = json.loads(res.content) eq_(data['objects'][0]['resource_uri'], reverse('app-detail', kwargs={'pk': 337141})) class TestApiReviewer(RestOAuth, ESTestCase): fixtures = fixture('webapp_337141', 'user_2519') def setUp(self): super(TestApiReviewer, self).setUp() self.user = UserProfile.objects.get(pk=2519) self.profile = self.user self.profile.update(read_dev_agreement=datetime.now()) self.grant_permission(self.profile, 'Apps:Review') self.access = Access.objects.create( key='test_oauth_key', secret=generate(), user=self.user) self.url = reverse('reviewers-search-api') self.webapp = Webapp.objects.get(pk=337141) self.webapp.update(status=amo.STATUS_PENDING) self.refresh('webapp') def test_fields(self): res = self.client.get(self.url) eq_(res.status_code, 200) obj = res.json['objects'][0] self.assertSetEqual(obj.keys(), ['device_types', 'id', 'is_escalated', 'is_packaged', 'latest_version', 'name', 'premium_type', 'price', 'slug', 'status']) eq_(obj['latest_version']['status'], 4) def test_anonymous_access(self): res = self.anon.get(self.url) eq_(res.status_code, 403) def test_non_reviewer_access(self): GroupUser.objects.filter(group__rules='Apps:Review', user=self.profile).delete() res = self.client.get(self.url) eq_(res.status_code, 403) def test_owner_still_non_reviewer_access(self): user = Webapp.objects.get(pk=337141).authors.all()[0] access = Access.objects.create( key='test_oauth_key_owner', secret=generate(), user=user) client = RestOAuthClient(access) res = client.get(self.url) eq_(res.status_code, 403) def test_status(self): res = self.client.get(self.url) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) res = self.client.get(self.url, {'status': 'pending'}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) res = self.client.get(self.url, {'status': 'rejected'}) eq_(res.status_code, 200) objs = res.json['objects'] eq_(len(objs), 0) self.webapp.update(status=amo.STATUS_REJECTED) self.refresh('webapp') res = self.client.get(self.url, {'status': 'rejected'}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) self.webapp.update(status=amo.STATUS_PUBLIC) self.refresh('webapp') res = self.client.get(self.url, {'status': 'public'}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) res = self.client.get(self.url, {'status': 'any'}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) res = self.client.get(self.url, {'status': 'vindaloo'}) eq_(res.status_code, 400) error = res.json['detail'] eq_(error.keys(), ['status']) def test_is_escalated(self): res = self.client.get(self.url, {'is_escalated': True}) eq_(res.status_code, 200) objs = res.json['objects'] eq_(len(objs), 0) res = self.client.get(self.url, {'is_escalated': False}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) res = self.client.get(self.url, {'is_escalated': None}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) def test_is_tarako(self): Tag(tag_text='tarako').save_tag(self.webapp) self.webapp.save() self.refresh() res = self.client.get(self.url, {'is_tarako': True}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) res = self.client.get(self.url, {'is_tarako': False}) eq_(res.status_code, 200) objs = res.json['objects'] eq_(len(objs), 0) res = self.client.get(self.url, {'is_tarako': None}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) def test_has_editors_comment(self): res = self.client.get(self.url, {'has_editor_comment': True}) eq_(res.status_code, 200) objs = res.json['objects'] eq_(len(objs), 0) res = self.client.get(self.url, {'has_editor_comment': False}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) res = self.client.get(self.url, {'has_editor_comment': None}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) def test_has_info_request(self): res = self.client.get(self.url, {'has_info_request': True}) eq_(res.status_code, 200) objs = res.json['objects'] eq_(len(objs), 0) res = self.client.get(self.url, {'has_info_request': False}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) res = self.client.get(self.url, {'has_info_request': None}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) def test_addon_type(self): res = self.client.get(self.url, {'type': 'app'}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) res = self.client.get(self.url, {'type': 'vindaloo'}) eq_(res.status_code, 400) error = res.json['detail'] eq_(error.keys(), ['type']) def test_no_region_filtering(self): self.webapp.addonexcludedregion.create(region=mkt.regions.BR.id) self.webapp.save() self.refresh('webapp') res = self.client.get(self.url, {'region': 'br'}) eq_(res.status_code, 200) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) def test_no_feature_profile_filtering(self): feature_profile = FeatureProfile().to_signature() qs = {'q': 'something', 'pro': feature_profile, 'dev': 'firefoxos'} # Enable an app feature that doesn't match one in our profile. self.webapp.addondevicetype_set.create(device_type=amo.DEVICE_GAIA.id) self.webapp.latest_version.features.update(has_pay=True) self.webapp.save() self.refresh('webapp') res = self.client.get(self.url, qs) eq_(res.status_code, 200) eq_(len(res.json['objects']), 1) obj = res.json['objects'][0] eq_(obj['slug'], self.webapp.app_slug) def test_no_flash_filtering(self): self.webapp.addondevicetype_set.create(device_type=amo.DEVICE_GAIA.id) self.webapp.latest_version.all_files[0].update(uses_flash=True) self.webapp.save() self.refresh('webapp') res = self.client.get(self.url, {'dev': 'firefoxos'}) eq_(res.status_code, 200) eq_(len(res.json['objects']), 1) def test_no_premium_filtering(self): self.webapp.addondevicetype_set.create( device_type=amo.DEVICE_MOBILE.id) self.webapp.update(premium_type=amo.ADDON_PREMIUM) self.refresh('webapp') res = self.client.get(self.url, {'dev': 'android', 'device': 'mobile'}) eq_(res.status_code, 200) eq_(len(res.json['objects']), 1) class TestApproveRegion(RestOAuth): fixtures = fixture('user_2519', 'webapp_337141') def url(self, **kwargs): kw = {'pk': '337141', 'region': 'cn'} kw.update(kwargs) return reverse('approve-region', kwargs=kw) def test_verbs(self): self.grant_permission(self.profile, 'Apps:ReviewRegionCN') self._allowed_verbs(self.url(), ['post']) def test_anon(self): res = self.anon.post(self.url()) eq_(res.status_code, 403) def test_bad_webapp(self): self.grant_permission(self.profile, 'Apps:ReviewRegionCN') res = self.client.post(self.url(pk='999')) eq_(res.status_code, 404) def test_webapp_not_pending_in_region(self): self.grant_permission(self.profile, 'Apps:ReviewRegionCN') res = self.client.post(self.url()) eq_(res.status_code, 404) def test_good_but_no_permission(self): res = self.client.post(self.url()) eq_(res.status_code, 403) def test_good_webapp_but_wrong_region_permission(self): self.grant_permission(self.profile, 'Apps:ReviewRegionBR') app = Webapp.objects.get(id=337141) app.geodata.set_status('cn', amo.STATUS_PENDING, save=True) res = self.client.post(self.url()) eq_(res.status_code, 403) def test_good_webapp_but_wrong_region_queue(self): self.grant_permission(self.profile, 'Apps:ReviewRegionCN') app = Webapp.objects.get(id=337141) app.geodata.set_status('cn', amo.STATUS_PENDING, save=True) res = self.client.post(self.url(region='br')) eq_(res.status_code, 403) def test_good_rejected(self): self.grant_permission(self.profile, 'Apps:ReviewRegionCN') app = Webapp.objects.get(id=337141) app.geodata.set_status('cn', amo.STATUS_PENDING, save=True) app.geodata.set_nominated_date('cn', save=True) res = self.client.post(self.url()) eq_(res.status_code, 200) obj = json.loads(res.content) eq_(obj['approved'], False) eq_(app.geodata.reload().get_status('cn'), amo.STATUS_REJECTED) def test_good_approved(self): self.grant_permission(self.profile, 'Apps:ReviewRegionCN') app = Webapp.objects.get(id=337141) app.geodata.set_status('cn', amo.STATUS_PENDING, save=True) app.geodata.set_nominated_date('cn', save=True) res = self.client.post(self.url(), data=json.dumps({'approve': '1'})) eq_(res.status_code, 200) obj = json.loads(res.content) eq_(obj['approved'], True) eq_(app.geodata.reload().get_status('cn'), amo.STATUS_PUBLIC) class TestGenerateToken(RestOAuth): fixtures = fixture('user_2519', 'webapp_337141') def setUp(self): super(TestGenerateToken, self).setUp() self.app = Webapp.objects.get(pk=337141) self.url = reverse('generate-reviewer-token', args=[self.app.app_slug]) self.user = UserProfile.objects.get(pk=2519) self.req = RequestFactory().get('/') self.req.user = self.user def test_verbs(self): self._allowed_verbs(self.url, ('post')) def test_not_allowed(self): eq_(self.anon.post(self.url).status_code, 403) def test_still_not_allowed(self): eq_(self.client.post(self.url).status_code, 403) def test_token(self): self.grant_permission(self.user, 'Apps:Review') res = self.client.post(self.url) eq_(res.status_code, 200, res.content) data = json.loads(res.content) assert 'token' in data # Check data in token. assert Token.valid(data['token'], data={'app_id': self.app.id}) class TestUpdateAdditionalReview(RestOAuth): fixtures = fixture('user_2519', 'webapp_337141') def setUp(self): super(TestUpdateAdditionalReview, self).setUp() self.grant_permission(self.profile, 'Apps:ReviewTarako') self.app = Webapp.objects.get(pk=337141) self.review = self.app.additionalreview_set.create(queue='my-queue') self.get_object_patcher = mock.patch( 'mkt.reviewers.views.UpdateAdditionalReviewViewSet.get_object') self.get_object = self.get_object_patcher.start() self.get_object.return_value = self.review self.addCleanup(self.get_object_patcher.stop) def patch(self, data, pk=None): if pk is None: pk = self.review.pk return self.client.patch( reverse('additionalreview-detail', args=[pk]), data=json.dumps(data), content_type='application/json') def test_review_tarako_required(self): self.remove_permission(self.profile, 'Apps:ReviewTarako') response = self.patch({'passed': True}) eq_(response.status_code, 403) def test_404_with_invalid_id(self): self.get_object_patcher.stop() response = self.patch({'passed': True}, pk=self.review.pk + 1) eq_(response.status_code, 404) self.get_object_patcher.start() def test_post_review_task_called_when_passed(self): with mock.patch.object(self.review, 'execute_post_review_task') as \ execute_post_review_task: response = self.patch({'passed': True}) eq_(response.status_code, 200) ok_(execute_post_review_task.called) def test_post_review_task_called_when_failed(self): with mock.patch.object(self.review, 'execute_post_review_task') as \ execute_post_review_task: response = self.patch({'passed': False}) eq_(response.status_code, 200) ok_(execute_post_review_task.called) def test_no_changes_without_pass_or_fail(self): with mock.patch.object(self.review, 'execute_post_review_task') as \ execute_post_review_task: response = self.patch({}) eq_(response.status_code, 400) eq_(response.json, {'non_field_errors': ['passed must be a boolean value']}) ok_(not execute_post_review_task.called) def test_comment_is_not_required(self): with mock.patch.object(self.review, 'execute_post_review_task') as \ execute_post_review_task: response = self.patch({'passed': False}) eq_(response.status_code, 200) ok_(execute_post_review_task.called) def test_comment_can_be_set(self): with mock.patch.object(self.review, 'execute_post_review_task') as \ execute_post_review_task: response = self.patch({'passed': False, 'comment': 'no work'}) eq_(response.status_code, 200) eq_(self.review.reload().comment, 'no work') ok_(execute_post_review_task.called) def test_reviewer_gets_set_to_current_user(self): with mock.patch.object(self.review, 'execute_post_review_task') as \ execute_post_review_task: response = self.patch({'passed': False}) eq_(response.status_code, 200) eq_(self.review.reload().reviewer, self.profile) ok_(execute_post_review_task.called) def test_review_completed_gets_set(self): with mock.patch.object(self.review, 'execute_post_review_task') as \ execute_post_review_task: response = self.patch({'passed': False}) eq_(response.status_code, 200) ok_(self.review.reload().review_completed - datetime.now() < timedelta(seconds=1)) ok_(execute_post_review_task.called) def test_review_can_only_happen_once(self): self.review.update(passed=True) with mock.patch.object(self.review, 'execute_post_review_task') as \ execute_post_review_task: response = self.patch({'passed': False}) eq_(response.status_code, 400) eq_(response.json, {'non_field_errors': ['has already been reviewed']}) ok_(not execute_post_review_task.called) class TestCreateAdditionalReview(RestOAuth): fixtures = fixture('user_2519', 'webapp_337141') def setUp(self): super(TestCreateAdditionalReview, self).setUp() self.app = Webapp.objects.get(pk=337141) self.addon_user = self.app.addonuser_set.create(user=self.profile) def post(self, data): return self.client.post( reverse('additionalreviews'), data=json.dumps(data), content_type='application/json') def review_exists(self): return (AdditionalReview.objects .filter(queue=QUEUE_TARAKO, app_id=self.app.pk) .exists()) def test_review_can_be_created(self): ok_(not self.review_exists()) response = self.post({'queue': QUEUE_TARAKO, 'app': self.app.pk}) eq_(response.status_code, 201) ok_(self.review_exists()) def test_queue_must_be_tarako(self): ok_(not self.review_exists()) response = self.post({'queue': 'not-tarako', 'app': self.app.pk}) eq_(response.status_code, 400) eq_(response.json, {'queue': ['is not a valid choice']}) ok_(not self.review_exists()) def test_a_non_author_does_not_have_access(self): self.addon_user.delete() ok_(not self.review_exists()) response = self.post({'queue': QUEUE_TARAKO, 'app': self.app.pk}) eq_(response.status_code, 403) ok_(not self.review_exists()) def test_admin_has_access(self): self.grant_permission(self.profile, 'Apps:Edit') self.addon_user.delete() ok_(not self.review_exists()) response = self.post({'queue': QUEUE_TARAKO, 'app': self.app.pk}) eq_(response.status_code, 201) ok_(self.review_exists()) def test_passed_cannot_be_set(self): ok_(not self.review_exists()) response = self.post( {'queue': QUEUE_TARAKO, 'app': self.app.pk, 'passed': True}) eq_(response.status_code, 201) ok_(self.review_exists()) eq_(AdditionalReview.objects.get(app_id=self.app.pk).passed, None) def test_only_one_pending_review(self): AdditionalReview.objects.create(queue=QUEUE_TARAKO, app=self.app) self.app.update(status=amo.STATUS_PENDING) eq_(AdditionalReview.objects.filter(app=self.app).count(), 1) response = self.post({'queue': QUEUE_TARAKO, 'app': self.app.pk}) eq_(response.status_code, 400) eq_(response.json, {'app': ['has a pending review']}) eq_(AdditionalReview.objects.filter(app=self.app).count(), 1) def test_unknown_app_is_an_error(self): response = self.post({'queue': QUEUE_TARAKO, 'app': 123}) eq_(response.status_code, 400) eq_(response.json, {'app': ["Invalid pk '123' - object does not exist."]})
# -*- coding: utf-8 -*- ''' Manage glusterfs pool. ''' # Import python libs from __future__ import generators from __future__ import absolute_import import logging import socket # Import salt libs import salt.utils.cloud as suc from salt.exceptions import SaltCloudException log = logging.getLogger(__name__) RESULT_CODES = [ 'Peer {0} added successfully.', 'Probe on localhost not needed', 'Host {0} is already in the peer group', 'Host {0} is already part of another cluster', 'Volume on {0} conflicts with existing volumes', 'UUID of {0} is the same as local uuid', '{0} responded with "unknown peer". This could happen if {0} doesn\'t have localhost defined', 'Failed to add peer. Information on {0}\'s logs', 'Cluster quorum is not met. Changing peers is not allowed.', 'Failed to update list of missed snapshots from {0}', 'Conflict comparing list of snapshots from {0}', 'Peer is already being detached from cluster.'] def __virtual__(): ''' Only load this module if the gluster command exists ''' return 'glusterfs' if 'glusterfs.list_volumes' in __salt__ else False def peered(name): ''' Check if node is peered. name The remote host with which to peer. .. code-block:: yaml peer-cluster: glusterfs.peered: - name: two peer-clusters: glusterfs.peered: - names: - one - two - three - four ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} try: suc.check_name(name, 'a-zA-Z0-9._-') except SaltCloudException as e: ret['comment'] = 'Invalid characters in peer name.' ret['result'] = False return ret peers = __salt__['glusterfs.list_peers']() if peers: if name in peers or any([name in peers[x] for x in peers]): ret['result'] = True ret['comment'] = 'Host {0} already peered'.format(name) return ret result = __salt__['glusterfs.peer'](name) ret['comment'] = '' if 'exitval' in result: if int(result['exitval']) <= len(RESULT_CODES): ret['comment'] = RESULT_CODES[int(result['exitval'])].format(name) else: if 'comment' in result: ret['comment'] = result['comment'] newpeers = __salt__['glusterfs.list_peers']() # if newpeers was null, we know something didn't work. if newpeers and name in newpeers or newpeers and any([name in newpeers[x] for x in newpeers]): ret['result'] = True ret['changes'] = {'new': newpeers, 'old': peers} # In case the hostname doesn't have any periods in it elif name == socket.gethostname(): ret['result'] = True return ret # In case they have a hostname like "example.com" elif name == socket.gethostname().split('.')[0]: ret['result'] = True return ret elif 'on localhost not needed' in ret['comment']: ret['result'] = True ret['comment'] = 'Peering with localhost is not needed' else: ret['result'] = False return ret def created(name, bricks, stripe=False, replica=False, device_vg=False, transport='tcp', start=False, force=False): ''' Check if volume already exists name name of the volume .. code-block:: yaml myvolume: glusterfs.created: - bricks: - host1:/srv/gluster/drive1 - host2:/srv/gluster/drive2 Replicated Volume: glusterfs.created: - name: volume2 - bricks: - host1:/srv/gluster/drive2 - host2:/srv/gluster/drive3 - replica: 2 - start: True ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} volumes = __salt__['glusterfs.list_volumes']() if name in volumes: if start: if isinstance(__salt__['glusterfs.status'](name), dict): ret['result'] = True cmnt = 'Volume {0} already exists and is started.'.format(name) else: result = __salt__['glusterfs.start_volume'](name) if 'started' in result: ret['result'] = True cmnt = 'Volume {0} started.'.format(name) ret['changes'] = {'new': 'started', 'old': 'stopped'} else: ret['result'] = False cmnt = result else: ret['result'] = True cmnt = 'Volume {0} already exists.'.format(name) ret['comment'] = cmnt return ret elif __opts__['test']: if start and isinstance(__salt__['glusterfs.status'](name), dict): comment = 'Volume {0} will be created and started'.format(name) else: comment = 'Volume {0} will be created'.format(name) ret['comment'] = comment ret['result'] = None return ret if suc.check_name(name, 'a-zA-Z0-9._-'): ret['comment'] = 'Invalid characters in volume name.' ret['result'] = False return ret ret['comment'] = __salt__['glusterfs.create'](name, bricks, stripe, replica, device_vg, transport, start, force) old_volumes = volumes volumes = __salt__['glusterfs.list_volumes']() if name in volumes: ret['changes'] = {'new': volumes, 'old': old_volumes} ret['result'] = True return ret def started(name): ''' Check if volume has been started name name of the volume .. code-block:: yaml mycluster: glusterfs.started: [] ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} volumes = __salt__['glusterfs.list_volumes']() if name not in volumes: ret['result'] = False ret['comment'] = 'Volume {0} does not exist'.format(name) return ret if isinstance(__salt__['glusterfs.status'](name), dict): ret['comment'] = 'Volume {0} is already started'.format(name) ret['result'] = True return ret elif __opts__['test']: ret['comment'] = 'Volume {0} will be started'.format(name) ret['result'] = None return ret ret['comment'] = __salt__['glusterfs.start_volume'](name) if 'started' in ret['comment']: ret['result'] = True ret['change'] = {'new': 'started', 'old': 'stopped'} else: ret['result'] = False return ret def add_volume_bricks(name, bricks): ''' Add brick(s) to an existing volume name Volume name bricks List of bricks to add to the volume .. code-block:: yaml myvolume: glusterfs.add_volume_bricks: - bricks: - host1:/srv/gluster/drive1 - host2:/srv/gluster/drive2 Replicated Volume: glusterfs.add_volume_bricks: - name: volume2 - bricks: - host1:/srv/gluster/drive2 - host2:/srv/gluster/drive3 ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} current_bricks = __salt__['glusterfs.status'](name) if 'does not exist' in current_bricks: ret['result'] = False ret['comment'] = current_bricks return ret if 'is not started' in current_bricks: ret['result'] = False ret['comment'] = current_bricks return ret add_bricks = __salt__['glusterfs.add_volume_bricks'](name, bricks) ret['comment'] = add_bricks if 'bricks successfully added' in add_bricks: old_bricks = current_bricks new_bricks = __salt__['glusterfs.status'](name) ret['result'] = True ret['changes'] = {'new': list(new_bricks['bricks'].keys()), 'old': list( old_bricks['bricks'].keys())} return ret if 'Bricks already in volume' in add_bricks: ret['result'] = True return ret return ret
#------------------------------------------------------------------------------ # Copyright 2014 Esri # 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. #------------------------------------------------------------------------------ # # LLOSProfileGraphAttachments.py # # Takes a LLOS output FC and adds a profile graph as an attachment to each line import os, sys, traceback import pylab import arcpy inputFeatures = arcpy.GetParameterAsText(0) debug = False deleteme = [] scratchFolder = arcpy.env.scratchFolder scratchGDB = arcpy.env.scratchGDB #pylab.use('AGG') try: rawLOS = {} # Current: {<SourceOID> : [<TarIsVis>, [<observerD=0.0>,<observerZ>], # [<targetD>,<targetZ>], # [<segmentList>]]]} # # where # [<segment>] is [<visibilityCode>,[d0,...,dN],[z0,...,zN]] # Unique sight lines sightLineIDs = [] rows = arcpy.da.SearchCursor(inputFeatures,["SourceOID","OID@"]) for row in rows: thisID = row[0] if thisID not in sightLineIDs: sightLineIDs.append(thisID) del rows if debug == True: arcpy.AddMessage("sightLineIDs list: " + str(sightLineIDs)) arcpy.AddMessage("Found " + str(len(sightLineIDs)) + " unique sight line IDs ...") arcpy.AddField_management(inputFeatures,"pngname","TEXT") expression = '"profile" + str(!SourceOID!)' arcpy.CalculateField_management(inputFeatures,"pngname",expression, "PYTHON") # get visible and non-visible lines for each LLOS for currentID in sightLineIDs: whereclause = (""""SourceOID" = %s""" % currentID) tarIsViz = None rows = arcpy.da.SearchCursor(inputFeatures,["OID@","SHAPE@", "SourceOID", "TarIsVis","VisCode","ObsZ","TgtZ","OID_OBSERV","OID_TARGET"],whereclause) startX = None startY = None tgtD = 0.0 line = 0 segmentList = [] for row in rows: oid = row[0] geometry = row[1] sourceOID = row[2] targetIsViz = row[3] visibilityCode = row[4] obsD = 0.0 obsZ = row[5] tgtZ = row[6] obsID = row[7] tgtID = row[8] partNum = 0 point = 0 partCount = geometry.partCount if debug == True: arcpy.AddMessage("OID: " + str(oid)) # go through parts in the line for part in geometry: if debug == True: arcpy.AddMessage("Line: " + str(line) + " Part: " + str(partNum) + " PointCount: " + str(len(part))) segment = [] partD = [] partZ = [] for pnt in part: if (line == 0) and (partNum == 0) and (point == 0): # if it is the very first point in the LLOS startX = pnt.X startY = pnt.Y if debug == True: arcpy.AddMessage("startX,startY: " + str(startX) + "," + str(startY)) distFromStart = 0 partD.append(0.0) partZ.append(pnt.Z) else: # for all other points in the LLOS distFromStart = math.sqrt((pnt.X - startX)**2 + (pnt.Y - startY)**2) if distFromStart > tgtD: tgtD = distFromStart partD.append(distFromStart) partZ.append(pnt.Z) point += 1 if debug == True: arcpy.AddMessage("Adding parts to segment ...") segment = [visibilityCode,partD,partZ] #if debug == True: arcpy.AddMessage("\nsegment: " + str(segment) + "\n") partNum += 1 if debug == True: arcpy.AddMessage("Adding segment to segment list ...") segmentList.append(segment) line += 1 del rows rawLOS[currentID] = [targetIsViz,[obsD,obsZ,obsID],[tgtD,tgtZ,tgtID],segmentList] if debug == True: arcpy.AddMessage("rawLOS: " + str(rawLOS)) # build a graph for each LLOS graphLocationDict = {} arcpy.AddMessage("Building graphs for lines ...") #for llosID in rawLOS.keys(): #UPDATE for llosID in list(rawLOS.keys()): graphInputList = rawLOS[llosID] # get the values for the current llos # Current: {<SourceOID> : [<TarIsVis>, [<observerD=0.0>,<observerZ>], # [<segmentList0>,...,<segmentListN>]]} targetVisibility = graphInputList[0] observer = graphInputList[1] obsD = observer[0] obsZ = observer[1] obsID = observer[2] target = graphInputList[2] tgtD = target[0] tgtZ = target[1] tgtID = target[2] segmentList = graphInputList[3] arcpy.AddMessage("Building graph from observer " + str(obsID) + " to target " + str(tgtID) + " ..." ) # plot the line of sight pylab.plot([obsD,tgtD],[obsZ,tgtZ],'k--',linewidth=1) # plot the visible profile for segment in segmentList: if segment[0] == 1 and len(segment[1]) != 0: # for visible segments - plot in green pylab.plot(segment[1],segment[2],'g',linewidth=1) if segment[0] == 2 and len(segment[1]) != 0: # for non-visible segments - plot in red pylab.plot(segment[1],segment[2],'r',linewidth=1) # titles & labels if (targetVisibility == 1): pylab.title("Target " + str(tgtID) + " is VISIBLE to observer " + str(obsID)) else: pylab.title("Target " + str(tgtID) + " is NOT VISIBLE to observer " + str(obsID)) pylab.ylabel("Elevation above sea level") pylab.xlabel("Distance to target") pylab.grid(True) # save the graph to a PNG file in the scratch folder graphPath = os.path.join(scratchFolder,r"profile" + str(llosID) + r".png") if debug == True: arcpy.AddMessage("graphPath: " + str(graphPath)) pylab.savefig(graphPath, dpi=900) pylab.cla() # clear the graph??? graphLocationDict[llosID] = graphPath deleteme.append(graphPath) # TODO: start an update cursor arcpy.AddMessage("Enabling attachments ...") arcpy.EnableAttachments_management(inputFeatures) matchTable = os.path.join(scratchGDB,"matchTable") deleteme.append(matchTable) arcpy.AddMessage("Building match table ...") arcpy.GenerateAttachmentMatchTable_management(inputFeatures,scratchFolder,matchTable,"pngname","*.png","ABSOLUTE") arcpy.AddMessage("Attaching profile graphs to sightlines ...") inOIDField = arcpy.Describe(inputFeatures).OIDFieldName arcpy.AddAttachments_management(inputFeatures,inOIDField,matchTable,"MatchID","Filename") # cleanup arcpy.AddMessage("Removing scratch data ...") for ds in deleteme: if arcpy.Exists(ds): arcpy.Delete_management(ds) if debug == True: arcpy.AddMessage(str(ds)) # output arcpy.SetParameter(1,inputFeatures) except arcpy.ExecuteError: error = True # Get the tool error messages msgs = arcpy.GetMessages() arcpy.AddError(msgs) #print msgs #UPDATE print(msgs) except: # Get the traceback object error = True tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # Concatenate information together concerning the error into a message string pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1]) msgs = "ArcPy ERRORS:\n" + arcpy.GetMessages() + "\n" # Return python error messages for use in script tool or Python Window arcpy.AddError(pymsg) arcpy.AddError(msgs) # Print Python error messages for use in Python / Python Window #print pymsg + "\n" #UPDATE print(pymsg + "\n") #print msgs #UPDATE print(msgs)
####################################################################### # This file is part of Pyblosxom. # # Copyright (C) 2003-2011 by the Pyblosxom team. See AUTHORS. # # Pyblosxom is distributed under the MIT license. See the file # LICENSE for distribution details. ####################################################################### """ This module contains the base class for all the Entry classes. The EntryBase class is essentially the API for entries in Pyblosxom. Reading through the comments for this class will walk you through building your own EntryBase derivatives. This module also holds a generic generate_entry function which will generate a BaseEntry with data that you provide for it. """ import time import locale from Pyblosxom import tools BIGNUM = 2000000000 CONTENT_KEY = "body" DOESNOTEXIST = "THISKEYDOESNOTEXIST" DOESNOTEXIST2 = "THISKEYDOESNOTEXIST2" class EntryBase: """ EntryBase is the base class for all the Entry classes. Each instance of an Entry class represents a single entry in the weblog, whether it came from a file, or a database, or even somewhere off the InterWeeb. EntryBase derivatives are dict-like except for one key difference: when doing ``__getitem__`` on a nonexistent key, it returns None by default. For example: >>> entry = EntryBase('some fake request') >>> None == entry["some_nonexistent_key"] True """ def __init__(self, request): self._data = "" self._metadata = dict(tools.STANDARD_FILTERS) self._id = "" self._mtime = BIGNUM self._request = request def __repr__(self): """ Returns a friendly debug-able representation of self. Useful to know on what entry pyblosxom fails on you (though unlikely) :returns: Identifiable representation of object """ return "<Entry instance: %s>\n" % self.getId() def get_id(self): """ This should return an id that's unique enough for caching purposes. Override this. :returns: string id """ return self._id getId = tools.deprecated_function(get_id) def get_data(self): """ Returns the data string. This method should be overridden to provide from pulling the data from other places. Override this. :returns: the data as a string """ return str(self._data) getData = tools.deprecated_function(get_data) def set_data(self, data): """ Sets the data content for this entry. If you are not creating the entry, then you have no right to set the data of the entry. Doing so could be hazardous depending on what EntryBase subclass you're dealing with. Override this. :param data: the data """ self._data = data setData = tools.deprecated_function(set_data) def get_metadata(self, key, default=None): """ Returns a given piece of metadata. Override this. :param key: the key being sought :param default: the default to return if the key does not exist :return: either the default (if the key did not exist) or the value of the key in the metadata dict """ return self._metadata.get(key, default) getMetadata = tools.deprecated_function(get_metadata) def set_metadata(self, key, value): """ Sets a key/value pair in the metadata dict. Override this. :param key: the key string :param value: the value string """ self._metadata[key] = value setMetadata = tools.deprecated_function(set_metadata) def get_metadata_keys(self): """ Returns the list of keys for which we have values in our stored metadata. .. Note:: This list gets modified later downstream. If you cache your list of metadata keys, then this method should return a copy of that list and not the list itself lest it get adjusted. Override this. :returns: list of metadata keys """ return self._metadata.keys() getMetadataKeys = tools.deprecated_function(get_metadata_keys) def get_from_cache(self, entryid): """ Retrieves information from the cache that pertains to this specific entryid. This is a helper method--call this to get data from the cache. Do not override it. :param entryid: a unique key for the information you're retrieving :returns: dict with the values or None if there's nothing for that entryid """ cache = tools.get_cache(self._request) # cache.__getitem__ returns None if the id isn't there if cache.has_key(entryid): return cache[entryid] return None getFromCache = tools.deprecated_function(get_from_cache) def add_to_cache(self, entryid, data): """ Over-writes the cached dict for key entryid with the data dict. This is a helper method--call this to add data to the cache. Do not override it. :param entryid: a unique key for the information you're storing :param data: the data to store--this should probably be a dict """ mycache = tools.get_cache(self._request) if mycache: # This could be extended to cover all keys used by # set_time(), but this is the key most likely to turn # up in metadata. If #date is not blocked from caching # here, the templates will use the raw string value # from the user metadata, rather than the value # derived from mtime. if data.has_key('date'): data.pop('date') mycache[entryid] = data addToCache = tools.deprecated_function(add_to_cache) def set_time(self, timetuple): """ This takes in a given time tuple and sets all the magic metadata variables we have according to the items in the time tuple. :param timetuple: the timetuple to use to set the data with--this is the same thing as the mtime/atime portions of an os.stat. This time is expected to be local time, not UTC. """ self['timetuple'] = timetuple self._mtime = time.mktime(timetuple) gmtimetuple = time.gmtime(self._mtime) self['mtime'] = self._mtime self['ti'] = time.strftime('%H:%M', timetuple) self['mo'] = time.strftime('%b', timetuple) self['mo_num'] = time.strftime('%m', timetuple) self['da'] = time.strftime('%d', timetuple) self['dw'] = time.strftime('%A', timetuple) self['yr'] = time.strftime('%Y', timetuple) self['fulltime'] = time.strftime('%Y%m%d%H%M%S', timetuple) self['date'] = time.strftime('%a, %d %b %Y', timetuple) # YYYY-MM-DDThh:mm:ssZ self['w3cdate'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', gmtimetuple) # Temporarily disable the set locale, so RFC-compliant date is # really RFC-compliant: directives %a and %b are locale # dependent. Technically, we're after english locale, but # only 'C' locale is guaranteed to exist. loc = locale.getlocale(locale.LC_ALL) locale.setlocale(locale.LC_ALL, 'C') self['rfc822date'] = time.strftime('%a, %d %b %Y %H:%M GMT', \ gmtimetuple) # set the locale back locale.setlocale(locale.LC_ALL, loc) setTime = tools.deprecated_function(set_time) # everything below this point involves convenience functions # that work with the above functions. def __getitem__(self, key, default=None): """ Retrieves an item from this dict based on the key given. If the item does not exist, then we return the default. If the item is ``CONTENT_KEY``, it calls ``get_data``, otherwise it calls ``get_metadata``. Don't override this. .. Warning:: There's no reason to override this--override ``get_data`` and ``get_metadata`` instead. :param key: the key being sought :param default: the default to return if the key does not exist :returns: the value of ``get_metadata`` or ``get_data`` """ if key == CONTENT_KEY: return self.get_data() return self.get_metadata(key, default) def get(self, key, default=None): """ Retrieves an item from the internal dict based on the key given. All this does is turn aroun and call ``__getitem__``. .. Warning:: There's no reason to override this--override ``get_data`` and ``get_metadata`` instead. :param key: the key being sought :param default: the default to return if the key does not exist :returns: the value of ``get_metadata`` or ``get_data`` (through ``__getitem__``) """ return self.__getitem__(key, default) def __setitem__(self, key, value): """ Sets the metadata[key] to the given value. This uses ``set_data`` and ``set_metadata``. Don't override this. :param key: the given key name :param value: the given value """ if key == CONTENT_KEY: self.set_data(value) else: self.set_metadata(key, value) def update(self, newdict): """ Updates the contents in this entry with the contents in the dict. It does so by calling ``set_data`` and ``set_metadata``. .. Warning:: There's no reason to override this--override ``set_data`` and ``set_metadata`` instead. :param newdict: the dict we're updating this one with """ for mem in newdict.keys(): if mem == CONTENT_KEY: self.set_data(newdict[mem]) else: self.set_metadata(mem, newdict[mem]) def has_key(self, key): """ Returns whether a given key is in the metadata dict. If the key is the ``CONTENT_KEY``, then we automatically return true. .. Warning:: There's no reason to override this--override ``get_metadata`` instead. :param key: the key to check in the metadata dict for :returns: whether (True) or not (False) the key exists """ if key == CONTENT_KEY or key == CONTENT_KEY + "_escaped": return True value = self.get_metadata(key, DOESNOTEXIST) if value == DOESNOTEXIST: value = self.get_metadata(key, DOESNOTEXIST2) if value == DOESNOTEXIST2: return False return True def keys(self): """ Returns a list of the keys that can be accessed through ``__getitem__``. .. Warning:: There's no reason to override this--override ``get_metadata_keys`` instead. :returns: list of key names """ keys = self.get_metadata_keys() if CONTENT_KEY not in keys: keys.append(CONTENT_KEY) return keys def generate_entry(request, properties, data, mtime=None): """ Takes a properties dict and a data string and generates a generic entry using the data you provided. :param request: the Request object :param properties: the dict of properties for the entry :param data: the data content for the entry :param mtime: the mtime tuple (as given by ``time.localtime()``). if you pass in None, then we'll use localtime. """ entry = EntryBase(request) entry.update(properties) entry.set_data(data) if mtime: entry.set_time(mtime) else: entry.set_time(time.localtime()) return entry
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' Various kinds of input widgets and form controls. ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from ...core.enums import CalendarPosition from ...core.has_props import abstract from ...core.properties import ( Bool, ColorHex, Date, Dict, Either, Enum, Float, Int, Interval, List, PositiveInt, String, Tuple, ) from .widget import Widget #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'AutocompleteInput', 'ColorPicker', 'DatePicker', 'FileInput', 'InputWidget', 'MultiChoice', 'MultiSelect', 'PasswordInput', 'Select', 'Spinner', 'TextInput', 'TextAreaInput' ) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- @abstract class InputWidget(Widget): ''' Abstract base class for input widgets. ''' title = String(default="", help=""" Widget's label. """) @classmethod def coerce_value(cls, val): prop_obj = cls.lookup('value') if isinstance(prop_obj, Float): return float(val) elif isinstance(prop_obj, Int): return int(val) elif isinstance(prop_obj, String): return str(val) else: return val #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- class FileInput(Widget): ''' Present a file-chooser dialog to users and return the contents of the selected files. ''' value = Either(String, List(String), default='', readonly=True, help=''' The base64-enconded contents of the file or files that were loaded. If `mulitiple` is set to False (default), this value is a single string with the contents of the single file that was chosen. If `multiple` is True, this value is a list of strings, each containing the contents of one of the multiple files that were chosen. The sequence of files is given by the list of filenames (see below) ''') mime_type = Either(String, List(String), default='', readonly=True, help=''' The mime-type of the file or files that were loaded. If `mulitiple` is set to False (default), this value is a single string with the mime-type of the single file that was chosen. If `multiple` is True, this value is a list of strings, each containing the mime-type of one of the multiple files that were chosen. The sequence of files is given by the list of filename (see below) ''') filename = Either(String, List(String), default='', readonly=True, help=''' The name(s) of the file or files that were loaded. If `mulitiple` is set to False (default), this value is a single string with the name of the single file that was chosen. If `multiple` is True, this value is a list of strings, each containing the name of one of the multiple files that were chosen. This list provides the sequence of files for the respective lists in value and mime-type .. note:: The full file path is not included since browsers will not provide access to that information for security reasons. ''') accept = String(default="", help=""" Comma-separated list of standard HTML file input filters that restrict what files the user can pick from. Values can be: `<file extension>`: Specific file extension(s) (e.g: .gif, .jpg, .png, .doc) are pickable `audio/*`: all sound files are pickable `video/*`: all video files are pickable `image/*`: all image files are pickable `<media type>`: A valid `IANA Media Type`_, with no parameters. .. _IANA Media Type: https://www.iana.org/assignments/media-types/media-types.xhtml """) multiple = Bool(default=False, help=""" set multiple=False (default) for single file selection, set multiple=True if selection of more than one file at a time should be possible. """) class TextInput(InputWidget): ''' Single-line input widget. ''' value = String(default="", help=""" Initial or entered text value. Change events are triggered whenever <enter> is pressed. """) value_input = String(default="", help=""" Initial or current value. Change events are triggered whenever any update happens, i.e. on every keypress. """) placeholder = String(default="", help=""" Placeholder for empty input field. """) class TextAreaInput(TextInput): ''' Multi-line input widget. ''' cols = Int(default=20, help=""" Specifies the width of the text area (in average character width). Default: 20 """) rows = Int(default=2, help=""" Specifies the height of the text area (in lines). Default: 2 """) max_length = Int(default=500, help=""" Max count of characters in field """) class PasswordInput(TextInput): ''' Single-line password input widget. This widget hides the input value so that it is not visible in the browser. .. warning:: Secure transmission of the password to Bokeh server application code requires configuring the server for SSL (i.e. HTTPS) termination. ''' class AutocompleteInput(TextInput): ''' Single-line input widget with auto-completion. ''' completions = List(String, help=""" A list of completion strings. This will be used to guide the user upon typing the beginning of a desired value. """) min_characters = PositiveInt(default=2, help=""" The number of characters a user must type before completions are presented. """) class Select(InputWidget): ''' Single-select widget. ''' options = Either(List(Either(String, Tuple(Either(Int, String), String))), Dict(String, List(Either(String, Tuple(Either(Int, String), String)))), help=""" Available selection options. Options may be provided either as a list of possible string values, or as a list of tuples, each of the form ``(value, label)``. In the latter case, the visible widget text for each value will be corresponding given label. Option groupings can be provided by supplying a dictionary object whose values are in the aforementioned list format """) value = String(default="", help=""" Initial or selected value. """) class MultiSelect(InputWidget): ''' Multi-select widget. ''' options = List(Either(String, Tuple(String, String)), help=""" Available selection options. Options may be provided either as a list of possible string values, or as a list of tuples, each of the form ``(value, label)``. In the latter case, the visible widget text for each value will be corresponding given label. """) value = List(String, help=""" Initial or selected values. """) size = Int(default=4, help=""" The number of visible options in the dropdown list. (This uses the ``select`` HTML element's ``size`` attribute. Some browsers might not show less than 3 options.) """) class MultiChoice(InputWidget): ''' MultiChoice widget. ''' options = List(Either(String, Tuple(String, String)), help=""" Available selection options. Options may be provided either as a list of possible string values, or as a list of tuples, each of the form ``(value, label)``. In the latter case, the visible widget text for each value will be corresponding given label. """) value = List(String, help=""" Initial or selected values. """) delete_button = Bool(default=True, help=""" Whether to add a button to remove a selected option. """) max_items = Int(default=None, help=""" The maximum number of items that can be selected. """) option_limit = Int(default=None, help=""" The number of choices that will be rendered in the dropdown. """) placeholder = String(default=None, help=""" A string that is displayed if not item is added. """) solid = Bool(default=True, help=""" Specify whether the choices should be solidly filled.""") class DatePicker(InputWidget): ''' Calendar-based date picker widget. ''' value = Date(help=""" The initial or picked date. """) min_date = Date(default=None, help=""" Optional earliest allowable date. """) max_date = Date(default=None, help=""" Optional latest allowable date. """) disabled_dates = List(Either(Date, Tuple(Date, Date)), default=[], help=""" A list of dates of ``(start, end)`` date ranges to make unavailable for selection. All other dates will be avalable. .. note:: Only one of ``disabled_dates`` and ``enabled_dates`` should be specified. """) enabled_dates = List(Either(Date, Tuple(Date, Date)), default=[], help=""" A list of dates of ``(start, end)`` date ranges to make available for selection. All other dates will be unavailable. .. note:: Only one of ``disabled_dates`` and ``enabled_dates`` should be specified. """) position = Enum(CalendarPosition, default="auto", help=""" Where the calendar is rendered relative to the input when ``inline`` is False. """) inline = Bool(default=False, help=""" Whether the calendar sholud be displayed inline. """) class ColorPicker(InputWidget): ''' Color picker widget .. warning:: This widget as a limited support on *Internet Explorer* (it will be displayed as a simple text input). ''' color = ColorHex(default='#000000', help=""" The initial color of the picked color (named or hexadecimal) """) class Spinner(InputWidget): ''' Spinner widget for numerical inputs ''' value = Float(default=0, help=""" The initial value of the spinner """) step = Interval(Float, start=1e-16, end=float('inf'), default=1, help=""" The step added or subtracted to the current value """) low = Float(help=""" Optional lowest allowable value. """) high = Float(help=""" Optional highest allowable value. """) #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
# Copyright 2011 Fluidinfo 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. from jinja2.exceptions import TemplateNotFound from random import randrange from twisted.python import log from twisted.web import resource, http, server from twisted.web.resource import ErrorPage from twisted.web.static import File from txfluiddb.client import Endpoint, Namespace, Values from txfluiddb.http import HTTPError from lastpage.callback import Callback from lastpage.login import Login from lastpage.logout import Logout # Content we serve statically, if static files are not being served by some # other means (e.g., nginx). _staticFiles = { '/static/favicon.ico': 'static/favicon.ico', '/robots.txt': 'static/robots.txt', '/static/bullet.png': 'static/bullet.png', '/static/icon.png': 'static/icon.png', '/static/login.png': 'static/login.png', '/static/logo.png': 'static/logo.png', '/static/style.css': 'static/style.css', } def _requestId(): """ Make a (fairly) unique request id for matching up error pages with errors in our logs. @return: a random C{str} identifier. """ return ''.join([chr(ord('a') + randrange(0, 26)) for i in range(16)]) class LastPage(resource.Resource): """ Top-level resource for the lastpage.me service. @param conf: A L{config.Config} instance holding configuration settings. @param env: The Jinja2 C{Environment} to use for rendering. @param cookieDict: a C{dict} that maps cookies to OAuth token keys. @param oauthTokenDict: a C{dict} that maps OAuth token keys to tokens. """ allowedMethods = ('GET',) def __init__(self, conf, env, cookieDict, oauthTokenDict): resource.Resource.__init__(self) self._conf = conf self._env = env self._cookieDict = cookieDict self._oauthTokenDict = oauthTokenDict def getChild(self, what, request): """ Find and return a child resource. @param what: The thing (either a user name or an html page) wanted. @param request: A twisted.web HTTP C{Request}. """ # Serve static files. if self._conf.serve_static_files: path = request.path if path in _staticFiles: filename = _staticFiles[path] log.msg('Serving static path %s -> %s.' % (path, filename)) request.setResponseCode(http.OK) fileResource = File(filename) fileResource.isLeaf = True return fileResource # Serve .html requests. if what == '' or what.endswith('.html'): try: template = self._env.get_template(what or 'index.html') except TemplateNotFound: # There could in theory be a user whose name ends in .html, # so we'll just let this go through. pass else: self._template = template return self if what == '_login_': return Login(self._cookieDict, self._oauthTokenDict, self._conf) if what == '_logout_': return Logout(self._cookieDict, self._conf) if what == '_callback_': return Callback(self._cookieDict, self._oauthTokenDict, self._conf) log.msg('Request for path %s assumed to be a user URL lookup.' % request.path) # Serve normal user redirects. try: # Decode the path components into unicode. who = what.decode('utf-8') rest = u'-'.join([x.decode('utf-8') for x in request.postpath]) except UnicodeDecodeError: return ErrorPage(http.BAD_REQUEST, 'Bad URI UTF-8', 'Bad UTF-8') if rest: tag = u'%s/lastpage-%s' % (who, rest) else: tag = u'%s/lastpage' % who return LastPageOf(self._conf, self._env, who, tag) def render_GET(self, request): """ Handle a GET request. This is a request for a top-level HTML page like http://lastpage.me/tools.html @param request: A twisted.web HTTP C{Request}. """ cookie = request.getCookie(self._conf.cookie_name) print 'got cookie %r' % (cookie,) try: data = self._cookieDict[cookie] except: print 'missed on looking up cookie' username = None else: print 'found cookie' username = data[0]['screen_name'] # token = data[1] return str(self._template.render(user=username)) class LastPageOf(resource.Resource): """ A resource for a specific user of lastpage.me. This resource is used to handle requests for http://lastpage.me/username. @param conf: A L{config.Config} instance holding configuration settings. @param env: The Jinja2 C{Environment} to use for rendering. @param who: A C{unicode} username to redirect to, if possible. @param tag: The C{unicode} path name of the tag to query for. """ allowedMethods = ('GET',) isLeaf = True def __init__(self, conf, env, who, tag): resource.Resource.__init__(self) self._endpoint = Endpoint(baseURL=conf.fluidinfo_endpoint) self._env = env self._who = who self._tag = tag def render_GET(self, request): """ Handle a GET request. @param request: A twisted.web HTTP C{Request}. @return: the twisted.web constant C{server.NOT_DONE_YET} to indicate that the request processing is still underway. """ query = u'has %s' % self._tag d = Values().get(self._endpoint, query, tags=[u'fluiddb/about']) d.addCallback(self._finishHas, request) d.addErrback(self._hasErr, request) d.addErrback(log.err) return server.NOT_DONE_YET def _hasErr(self, fail, request): """ Handle an error in the GET on the user's tag. @param fail: the Twisted failure. @param request: A twisted.web HTTP C{Request}. """ fail.trap(HTTPError) errorClass = fail.value.response_headers.get('x-fluiddb-error-class') if errorClass: if errorClass[0] == 'TNonexistentTag': # A non-existent tag could be due to the user not existing # or the tag not existing. Find out which so we can be as # helpful as possible in the error message. d = Namespace(self._who).exists(self._endpoint) d.addCallback(self._testUserExists, request) d.addErrback(self._oops, request) d.addErrback(log.err) return d error = 'Fluidinfo error class %s.' % errorClass[0] else: error = ('No x-fluiddb-error-class in response headers! %r' % fail.value.response_headers) _id = _requestId() log.msg('Error: request %s: %s' % (_id, error)) log.err(fail) template = self._env.get_template('500.html') request.write(str(template.render(id=_id))) request.finish() def _finishHas(self, result, request): """ Handle the result of the 'has username/lastpage' /values query. We just figure out how many objects are tagged and route the results (if any) and the request to a more specific method. @param result: the result of the query. @param request: A twisted.web HTTP C{Request}. """ results = result['results']['id'] nResults = len(results) if nResults == 0: self._noObjectsTagged(request) elif nResults == 1: self._oneObjectTagged(results, request) else: self._multipleObjectsTagged(results, request) def _noObjectsTagged(self, request): """ The user's tag is not on any object, so we cannot redirect them. Instead, show an informative page to let them know what's up. @param request: A twisted.web HTTP C{Request}. """ template = self._env.get_template('no-pages-tagged.html') request.write(str(template.render(user=self._who, tag=self._tag))) request.setResponseCode(http.OK) request.finish() def _oneObjectTagged(self, results, request): """ The user's tag is only on one object, so we can redirect them, assuming the tag value looks like a URL. @param results: The C{dict} result from the /values call to get the fluiddb/about value of the user's tagged object. @param request: A twisted.web HTTP C{Request}. """ url = results.values()[0]['fluiddb/about']['value'] try: url = str(url) except UnicodeEncodeError: log.msg('Could not convert url %r to str.' % (url,)) # Display the offending URL in an ASCII representation of # the unicode value. url = '%r' % (url,) request.setResponseCode(http.OK) template = self._env.get_template('tag-not-a-url.html') request.write(str(template.render( user=self._who, tag=self._tag, about=url))) else: if url.startswith('http'): log.msg('Redirect: %s -> %s' % ( self._tag.encode('utf-8'), url)) request.setResponseCode(http.TEMPORARY_REDIRECT) request.redirect(url) else: request.setResponseCode(http.OK) template = self._env.get_template('tag-not-a-url.html') request.write(str(template.render( user=self._who, tag=self._tag, about=url))) request.finish() def _multipleObjectsTagged(self, results, request): """ The user's tag is on multiple objects, so we cannot redirect them, to just one URL. Instead we display the fluiddb/about values of the objects that are tagged. @param results: The C{dict} result from the /values call to get the fluiddb/about value of the user's tagged object. @param request: A twisted.web HTTP C{Request}. """ pages = [] for obj in results.values(): url = obj['fluiddb/about']['value'] try: url = str(url) except UnicodeEncodeError: log.msg('Tag URL %r could not be converted to str' % url) # Convert it to a string of some form, even though it's # not going to be a valid URL. We could UTF-8 and # %-encode here but I'm not sure it's worth the # trouble. So for now let's just display the Unicode. url = '%r' % (url,) else: if url.startswith('http'): url = '<a href="%s">%s</a>' % (url, url) pages.append(url) request.setResponseCode(http.OK) template = self._env.get_template('multiple-pages-tagged.html') request.write(str(template.render( user=self._who, tag=self._tag, pages=pages))) request.setResponseCode(http.OK) request.finish() def _testUserExists(self, exists, request): """ Produce an informative page to indicate that we can't help because either the user doesn't exist or the tag isn't present. @param exists: C{True} if the user exists, else C{False}. @param request: A twisted.web HTTP C{Request}. """ if exists: template = self._env.get_template('no-pages-tagged.html') else: template = self._env.get_template('no-user.html') request.write(str(template.render(user=self._who, tag=self._tag))) request.setResponseCode(http.OK) request.finish() def _oops(self, fail, request): """ Produce an internal server error page to indicate that we had a severed problem. @param fail: the Twisted failure. @param request: A twisted.web HTTP C{Request}. """ _id = _requestId() log.msg('Error: returning a 500 error. Request id = %s' % _id) log.err(fail) request.setResponseCode(http.INTERNAL_SERVER_ERROR) template = self._env.get_template('500.html') request.write(str(template.render(id=_id))) request.finish()
# -*- coding: utf-8 -*- import json import unittest import urlparse from pale import Endpoint from pale.arguments import (BaseArgument, BooleanArgument, JsonDictArgument, FloatArgument, IntegerArgument, ListArgument, ScopeArgument, StringArgument, StringListArgument, URLArgument) from pale.errors import ArgumentError class ArgumentTests(unittest.TestCase): def expect_valid_argument(self, arg_inst, value, expected): validated = arg_inst.validate(value, 'test item') self.assertEqual(validated, expected) def expect_invalid_argument(self, arg_inst, value): with self.assertRaises(ArgumentError): validated = arg_inst.validate(value, 'test item') def test_boolean_argument(self): required_bool_arg = BooleanArgument('test bool arg', required=True) self.expect_valid_argument(required_bool_arg, 'true', True) self.expect_valid_argument(required_bool_arg, 'TRUE', True) self.expect_valid_argument(required_bool_arg, 'True', True) self.expect_valid_argument(required_bool_arg, 'TrUe', True) self.expect_valid_argument(required_bool_arg, 'false', False) self.expect_valid_argument(required_bool_arg, 'FALSE', False) self.expect_valid_argument(required_bool_arg, 'False', False) self.expect_valid_argument(required_bool_arg, 'FaLSe', False) self.expect_invalid_argument(required_bool_arg, None) self.expect_invalid_argument(required_bool_arg, 'hello') # allow 0/1 integers, but not other ints self.expect_valid_argument(required_bool_arg, '0', False) self.expect_valid_argument(required_bool_arg, '1', True) self.expect_invalid_argument(required_bool_arg, '-241') self.expect_invalid_argument(required_bool_arg, '241') self.expect_invalid_argument(required_bool_arg, '0.0') self.expect_invalid_argument(required_bool_arg, '1.0') self.expect_invalid_argument(required_bool_arg, '1.234') optional_bool_arg = BooleanArgument('test arg', required=False) self.expect_valid_argument(optional_bool_arg, 'True', True) self.expect_valid_argument(optional_bool_arg, None, None) default_bool_arg = BooleanArgument('test arg', required=False, default=False) self.expect_valid_argument(default_bool_arg, None, False) # passing a value overrides the default self.expect_valid_argument(default_bool_arg, 'true', True) required_default_bool_arg = BooleanArgument('test arg', required=True, default=False) self.expect_valid_argument(required_default_bool_arg, None, False) self.expect_valid_argument(required_default_bool_arg, 'true', True) def test_string_argument(self): # damn near everything will probably come in as a string, so there's # only so much to test without regex matching required_string_arg = StringArgument('test string arg', required=True) self.expect_valid_argument(required_string_arg, 'hello, world', 'hello, world') self.expect_valid_argument(required_string_arg, '12345', '12345') self.expect_invalid_argument(required_string_arg, None) self.expect_invalid_argument(required_string_arg, '') optional_string_arg = StringArgument('test string arg', required=False) self.expect_valid_argument(optional_string_arg, 'hello, world', 'hello, world') self.expect_valid_argument(optional_string_arg, None, None) default_string_arg = StringArgument('test string arg', required=False, default="hello tests") self.expect_valid_argument(default_string_arg, 'hello, world', 'hello, world') self.expect_valid_argument(default_string_arg, None, 'hello tests') required_default_string_arg = StringArgument('test string arg', required=True, default="hello tests") self.expect_valid_argument(required_default_string_arg, 'hello, world', 'hello, world') self.expect_valid_argument(required_default_string_arg, None, 'hello tests') def test_url_argument(self): required_url_arg = URLArgument('test url arg', required=True) google_url = urlparse.urlparse('https://www.google.com/') ftp_url = urlparse.urlparse('ftp://www.google.com/') url_path = urlparse.urlparse('/foo/bar/baz') url_path_with_query = urlparse.urlparse('/foo/bar/baz?query=hi') url_path_with_fragment = urlparse.urlparse('/foo/bar/baz#hello') url_path_with_query_fragment = urlparse.urlparse( '/foo/bar/baz?query=hi#hello') self.expect_invalid_argument(required_url_arg, None) self.expect_invalid_argument(required_url_arg, '') self.expect_invalid_argument(required_url_arg, ftp_url.geturl()) self.expect_invalid_argument(required_url_arg, 'i am not a url') self.expect_invalid_argument(required_url_arg, url_path.geturl()) self.expect_valid_argument(required_url_arg, google_url.geturl(), google_url) optional_url_arg = URLArgument('test string arg', required=False) self.expect_valid_argument(optional_url_arg, None, None) self.expect_valid_argument(optional_url_arg, google_url.geturl(), google_url) url_path_arg = URLArgument('test string arg', path_only=True) self.expect_invalid_argument(url_path_arg, google_url.geturl()) self.expect_valid_argument(url_path_arg, url_path.geturl(), url_path) self.expect_valid_argument(url_path_arg, url_path_with_query.geturl(), url_path_with_query) self.expect_valid_argument(url_path_arg, url_path_with_fragment.geturl(), url_path_with_fragment) self.expect_valid_argument(url_path_arg, url_path_with_query_fragment.geturl(), url_path_with_query_fragment) def test_integer_argument(self): required_int_arg = IntegerArgument('test integer arg', required=True) self.expect_invalid_argument(required_int_arg, 'i am not an int') # single characters aren't accidentally converted to ascii values self.expect_invalid_argument(required_int_arg, 'Q') self.expect_invalid_argument(required_int_arg, None) self.expect_valid_argument(required_int_arg, '123', 123) # no floats self.expect_invalid_argument(required_int_arg, '123.45') self.expect_valid_argument(required_int_arg, '-159', -159) optional_int_arg = IntegerArgument('test integer arg') self.expect_invalid_argument(optional_int_arg, 'i am not an int') self.expect_valid_argument(optional_int_arg, None, None) self.expect_valid_argument(optional_int_arg, '75', 75) default_int_arg = IntegerArgument('test integer arg', default=42) self.expect_invalid_argument(default_int_arg, 'i am not an int') self.expect_valid_argument(default_int_arg, None, 42) self.expect_valid_argument(default_int_arg, '33', 33) default_required_int_arg = IntegerArgument('test integer arg', default=42, required=True) self.expect_invalid_argument(default_required_int_arg, 'i am not an int') self.expect_valid_argument(default_required_int_arg, None, 42) self.expect_valid_argument(default_required_int_arg, '33', 33) self.expect_valid_argument(default_required_int_arg, '0', 0) minimum_int_arg = IntegerArgument('test integer arg', min_value=9) self.expect_invalid_argument(minimum_int_arg, 'i am not an int') self.expect_invalid_argument(minimum_int_arg, 8) self.expect_invalid_argument(minimum_int_arg, -873) self.expect_valid_argument(minimum_int_arg, 9, 9) self.expect_valid_argument(minimum_int_arg, 31423, 31423) maximum_int_arg = IntegerArgument('test integer arg', max_value=9) self.expect_invalid_argument(maximum_int_arg, 'i am not an int') self.expect_invalid_argument(maximum_int_arg, 10) self.expect_invalid_argument(maximum_int_arg, 873) self.expect_valid_argument(maximum_int_arg, 9, 9) self.expect_valid_argument(maximum_int_arg, -31423, -31423) min_max_int_arg = IntegerArgument('test integer arg', min_value=0, max_value=9) self.expect_invalid_argument(min_max_int_arg, 'i am not an int') self.expect_invalid_argument(min_max_int_arg, 10) self.expect_invalid_argument(min_max_int_arg, 873) self.expect_invalid_argument(min_max_int_arg, -1) self.expect_invalid_argument(min_max_int_arg, -972151) self.expect_valid_argument(min_max_int_arg, 9, 9) self.expect_valid_argument(min_max_int_arg, 0, 0) self.expect_valid_argument(min_max_int_arg, 5, 5) def test_float_argument(self): required_float_arg = FloatArgument('test float arg', required=True) self.expect_invalid_argument(required_float_arg, 'i am not a float') # single characters aren't accidentally converted to ascii values self.expect_invalid_argument(required_float_arg, 'Q') self.expect_invalid_argument(required_float_arg, None) self.expect_valid_argument(required_float_arg, '123', 123.0) self.expect_valid_argument(required_float_arg, '123.45', 123.45) self.expect_valid_argument(required_float_arg, '-159', -159.0) optional_float_arg = FloatArgument('test float arg') self.expect_invalid_argument(optional_float_arg, 'i am not a float') self.expect_valid_argument(optional_float_arg, None, None) self.expect_valid_argument(optional_float_arg, '3.14159', 3.14159) default_float_arg = FloatArgument('test float arg', default=1.5) self.expect_invalid_argument(default_float_arg, 'i am not a float') self.expect_valid_argument(default_float_arg, None, 1.5) self.expect_valid_argument(default_float_arg, 42.245, 42.245) min_float_arg = FloatArgument('test float arg', min_value=0.2) self.expect_invalid_argument(min_float_arg, 'i am not a float') self.expect_invalid_argument(min_float_arg, '-1.589') self.expect_invalid_argument(min_float_arg, '0.1') self.expect_valid_argument(min_float_arg, '0.2', 0.2) self.expect_valid_argument(min_float_arg, '12.245', 12.245) max_float_arg = FloatArgument('test float arg', max_value=100.0) self.expect_invalid_argument(max_float_arg, 'i am not a float') self.expect_invalid_argument(max_float_arg, '158.9') self.expect_invalid_argument(max_float_arg, '100.1') self.expect_valid_argument(max_float_arg, '0.1', 0.1) self.expect_valid_argument(max_float_arg, '99.9', 99.9) self.expect_valid_argument(max_float_arg, '-102.245', -102.245) min_max_float_arg = FloatArgument('test float arg', min_value=0.0, max_value=1.0) self.expect_invalid_argument(min_max_float_arg, 'i am not a float') self.expect_invalid_argument(min_max_float_arg, '1.1') self.expect_invalid_argument(min_max_float_arg, '-102.245') self.expect_invalid_argument(min_max_float_arg, '99.9') self.expect_valid_argument(min_max_float_arg, '0.1', 0.1) self.expect_valid_argument(min_max_float_arg, '0.567235', 0.567235) self.expect_valid_argument(min_max_float_arg, '0', 0.0) self.expect_valid_argument(min_max_float_arg, '1', 1.0) def test_scope_argument(self): required_scope_arg = ScopeArgument('test scope arg', required=True) self.expect_invalid_argument(required_scope_arg, None) self.expect_valid_argument(required_scope_arg, "hello world", ['hello', 'world']) self.expect_valid_argument(required_scope_arg, "hello.world and.goodbye.mars", ['hello.world', 'and.goodbye.mars']) def test_string_list_argument(self): comma_separated_string_list = StringListArgument('test string list arg', separator=',', trim_whitespace=False, required=True) self.expect_invalid_argument(comma_separated_string_list, None) self.expect_valid_argument(comma_separated_string_list, "hello world", ['hello world']) self.expect_valid_argument(comma_separated_string_list, "hello,world", ['hello', 'world']) self.expect_valid_argument(comma_separated_string_list, "hello, world", ['hello', ' world']) # it can also handle querystring lists, in which case, it'll get a list # directly, rather than a value-separated string self.expect_valid_argument(comma_separated_string_list, ['hello', 'world'], ['hello', 'world']) self.expect_valid_argument(comma_separated_string_list, ['hello', ' world'], ['hello', ' world']) comma_separated_string_list.trim_whitespace = True self.expect_valid_argument(comma_separated_string_list, "hello, world", ['hello', 'world']) self.expect_valid_argument(comma_separated_string_list, ['hello', 'world'], ['hello', 'world']) self.expect_valid_argument(comma_separated_string_list, ['hello', ' world'], ['hello', 'world']) def test_list_argument(self): required_bool_list_arg = ListArgument('test list arg', required=True, item_type=BooleanArgument('Boolean items')) self.expect_invalid_argument(required_bool_list_arg, 'true') self.expect_valid_argument(required_bool_list_arg, ['true', 'True', '1', 'false'], [True, True, True, False]) self.expect_invalid_argument(required_bool_list_arg, ['true', 'True', '1', 'false', 'hello, world']) optional_list_arg = ListArgument('test list arg', item_type=StringArgument('a string')) self.expect_valid_argument(optional_list_arg, None, None) def test_dict_argument(self): # because sometimes you want to pass a json dictionary... required_dict_arg = JsonDictArgument('test dict arg', required=True, field_map={ 'foo': StringArgument("the thing's foo", required=True), 'count': IntegerArgument('why not have a count?', required=True), 'optionals': StringListArgument("more optional things") }) valid_dict = { 'foo': 'hello', 'count': 5 } expected_dict = { 'foo': 'hello', 'count': 5, 'optionals': None } self.expect_valid_argument(required_dict_arg, json.dumps(valid_dict), expected_dict) self.expect_invalid_argument(required_dict_arg, json.dumps({'foo': 'bar'})) self.expect_invalid_argument(required_dict_arg, 'this is not a json.') self.expect_invalid_argument(required_dict_arg, json.dumps({'foo': 'hi', 'count': 10, 'extra': 'something else'})) allow_extras_dict_arg = JsonDictArgument('test dict arg', required=True, allow_extra_fields=True, field_map={ 'foo': StringArgument("the thing's foo", required=True), 'count': IntegerArgument('why not have a count?', required=True), 'optionals': StringListArgument("more optional things") }) self.expect_valid_argument(allow_extras_dict_arg, json.dumps({ 'foo': 'hi', 'count': 10, 'extra': 'something else', 'optionals': ['hello', 'how are you'] }), { 'foo': 'hi', 'count': 10, 'extra': 'something else', 'optionals': ['hello', 'how are you'] })
""" It usually takes about 29,180 seconds (8 hours). """ import os import math import copy import cPickle as pickle import numpy as np from data import model from sklearn import mixture def discretize_elems_in_list(df, l, key): """ It converts categorical values to integer values, so you need to care when you use this function. """ for i, _ in enumerate(l): df[key][df[key]==l[i]]=i return df def scale_bignums_to_log2(df,targets): for i in range(len(targets)): for j in range(df.shape[0]): df[targets[i]].iloc[j]=int(math.log(1+df[targets[i]].iloc[j],2)) df.iloc[0] return df def discretize_elems(df, attacks): protocols = list(set(df['protocol_type'])) services = list(set(df['service'])) flags = list(set(df['flag'])) df = discretize_elems_in_list(df,attacks,'attack') df = discretize_elems_in_list(df,protocols,'protocol_type') df = discretize_elems_in_list(df,services,'service') df = discretize_elems_in_list(df,flags,'flag') scaled=['duration','src_bytes','dst_bytes','num_root','num_compromised', 'num_file_creations','count','srv_count','dst_host_count', 'dst_host_srv_count'] df = scale_bignums_to_log2(df,scaled) return df def generate_gmms(df, headers, n_initialization=10): """ Using BIC, AIC values may be required for future work """ gmms = [] # it is for normal data or abnormal data. """ Three elements for each protocol_type, and in each element, there is a container for each headers. """ for protocol_type in range(3): #0:udp, 1:icmp, 2:tcp df_for_protocol = df[ df['protocol_type']==protocol_type ] gmms_for_protocol = [] important_headers = ['dst_host_srv_count','logged_in','dst_bytes','dst_host_same_src_port_rate','srv_count','flag','protocol_type','src_bytes','count','service'] #ON THE KDD'99 DATASET: STATISTICAL ANALYSIS FOR FEATURE SELECTION for header_type in headers: # print header_type if header_type in ['protocol_type', 'attack', 'difficulty']: continue # pick the best clf which produces minimum bic among those four types data_to_fit = df_for_protocol[header_type] cov_types = ['spherical', 'tied', 'diag', 'full'] best_clf = None lowest_bic = np.infty if len(data_to_fit) != 0: # If there is no data, it become None type. for cov_type in cov_types: try : for n_comp in [3,4,5,6,7,8,9]: # gmm fitting clf = mixture.GMM(n_components=n_comp, covariance_type=cov_type, n_init=n_initialization) clf.fit(data_to_fit) bic = clf.bic(data_to_fit) if bic < lowest_bic: best_clf = clf lowest_bic = bic except : # print " Warning! " + header_type + " w/" + cov_type + " has an error." pass # print lowest_bic if lowest_bic > -3000 : if header_type in important_headers : # print " Warning! this value is too big but I will use anyway" pass else : best_clf = None gmms_for_protocol.append(best_clf) gmms.append(gmms_for_protocol) return gmms def construct_gmms(df, headers): # only select for normal data df_train = copy.deepcopy(df) df_train = df_train[(df_train["attack"] == model.attack_normal)] gmms_normal = generate_gmms(df_train, headers) # only select for abnormal data df_train = copy.deepcopy(df) df_train = df_train[(df_train["attack"] != model.attack_normal)] gmms_abnormal = generate_gmms(df_train, headers) gmms = [gmms_normal, gmms_abnormal] return gmms def get_header_data(): workpath = os.path.dirname(os.path.abspath(__file__)) headerfile = workpath + '/data/kddcup.names' headers, attacks = model.load_headers(headerfile) return headers, attacks def get_preprocessed_test_data(datasize=None, regenerate=False): df = None workpath = os.path.dirname(os.path.abspath(__file__)) if regenerate == False: with open(workpath+'/./df_test_plus.pkl','rb') as input: df_test_plus = pickle.load(input) with open(workpath+'/./df_test_21.pkl','rb') as input: df_test_21 = pickle.load(input) with open(workpath + '/./gmms_test_plus.pkl','rb') as input: gmm_test_plus = pickle.load(input) with open(workpath + '/./gmms_test_21.pkl','rb') as input: gmm_test_21 = pickle.load(input) return df_test_plus, df_test_21, gmm_test_plus, gmm_test_21 else : workpath = os.path.dirname(os.path.abspath(__file__)) datafile_plus = workpath + '/data/KDDTest+.txt' datafile_21 = workpath + '/data/KDDTest-21.txt' headers, attacks = get_header_data() print "preprocessing testing data plus..." df = model.load_dataframe(datafile_plus,headers,datasize=datasize) df_test_plus = discretize_elems(df, attacks) gmms_test_plus = construct_gmms(df_test_plus, headers) print "preprocessing testing data 21..." df = model.load_dataframe(datafile_21,headers,datasize=datasize) df_test_21 = discretize_elems(df, attacks) gmms_test_21 = construct_gmms(df_test_21, headers) print "save to file..." with open(workpath + '/./df_test_plus.pkl','wb') as output: pickle.dump(df_test_plus, output, -1) with open(workpath + '/./df_test_21.pkl','wb') as output: pickle.dump(df_test_21, output, -1) with open(workpath + '/./gmms_test_plus.pkl','wb') as output: pickle.dump(gmms_test_plus, output,-1) with open(workpath + '/./gmms_test_21.pkl','wb') as output: pickle.dump(gmms_test_21, output,-1) return df_test_plus, df_test_21, gmms_test_plus, gmms_test_21 def get_preprocessed_training_data(datasize=None, regenerate=False, withfull=False): df = None workpath = os.path.dirname(os.path.abspath(__file__)) if regenerate == False: with open(workpath+'/./df_training_20.pkl','rb') as input: df_training_20 = pickle.load(input) with open(workpath+'/./df_training_full.pkl','rb') as input: df_training_full = pickle.load(input) with open(workpath+'/./gmms_training_20.pkl','rb') as input: gmms_20 = pickle.load(input) with open(workpath+'/./gmms_training_full.pkl','rb') as input: gmms_full = pickle.load(input) return df_training_20, df_training_full, gmms_20, gmms_full else : workpath = os.path.dirname(os.path.abspath(__file__)) datafile_20 = workpath + '/data/KDDTrain+_20Percent.txt' datafile_full = workpath + '/data/KDDTrain+.txt' headers, attacks = get_header_data() df_training_full = None gmms_training_full = None print "preprocessing training data for 20 percent..." df = model.load_dataframe(datafile_20,headers,datasize=datasize) print "descretization..." df_training_20 = discretize_elems(df, attacks) print "gmm fitting..." gmms_training_20 = construct_gmms(df_training_20, headers) if withfull == True : print "preprocessing training data total..." df = model.load_dataframe(datafile_full,headers,datasize=datasize) print "descretization..." df_training_full = discretize_elems(df, attacks) print "gmm fitting..." gmms_training_full = construct_gmms(df_training_full, headers) else : print "without full data" print "save to file..." with open(workpath + '/./df_training_20.pkl','wb') as output: pickle.dump(df_training_20, output,-1) with open(workpath + '/./gmms_training_20.pkl','wb') as output: pickle.dump(gmms_training_20, output,-1) if withfull == True : with open(workpath + '/./df_training_full.pkl','wb') as output: pickle.dump(df_training_full, output,-1) with open(workpath + '/./gmms_training_full.pkl','wb') as output: pickle.dump(gmms_training_full, output,-1) return df_training_20, df_training_full, gmms_training_20, gmms_training_full if __name__ == '__main__': import sys import time if sys.version_info < (2, 7) or sys.version_info >= (3, 0): print ("Requires Python 2.7.x") exit() del sys print (__doc__) ############################################################################# # Generate pkl files datasize = None start = time.time() ############################################################################# print "preprocessing training data..." get_preprocessed_training_data(datasize,regenerate=True, withfull=False) ############################################################################# print "preprocessing test data..." get_preprocessed_test_data(datasize,regenerate=True) ############################################################################# elapsed = (time.time() - start) print "Preprocessing done (%s seconds)" % (elapsed)
# encoding: utf-8 """ Objects related to mouse click and hover actions on a shape or text. """ from __future__ import ( absolute_import, division, print_function, unicode_literals ) from .enum.action import PP_ACTION from .opc.constants import RELATIONSHIP_TYPE as RT from .shapes import Subshape from .util import lazyproperty class ActionSetting(Subshape): """ Properties that specify how a shape or text run reacts to mouse actions during a slide show. """ # Subshape superclass provides access to the Slide Part, which is needed # to access relationships. def __init__(self, xPr, parent, hover=False): super(ActionSetting, self).__init__(parent) # xPr is either a cNvPr or rPr element self._element = xPr # _hover determines use of `a:hlinkClick` or `a:hlinkHover` self._hover = hover @property def action(self): """ A member of the :ref:`PpActionType` enumeration, such as `PP_ACTION.HYPERLINK`, indicating the type of action that will result when the specified shape or text is clicked or the mouse pointer is positioned over the shape during a slide show. """ hlink = self._hlink if hlink is None: return PP_ACTION.NONE action_verb = hlink.action_verb if action_verb == 'hlinkshowjump': relative_target = hlink.action_fields['jump'] return { 'firstslide': PP_ACTION.FIRST_SLIDE, 'lastslide': PP_ACTION.LAST_SLIDE, 'lastslideviewed': PP_ACTION.LAST_SLIDE_VIEWED, 'nextslide': PP_ACTION.NEXT_SLIDE, 'previousslide': PP_ACTION.PREVIOUS_SLIDE, 'endshow': PP_ACTION.END_SHOW, }[relative_target] return { None: PP_ACTION.HYPERLINK, 'hlinksldjump': PP_ACTION.NAMED_SLIDE, 'hlinkpres': PP_ACTION.PLAY, 'hlinkfile': PP_ACTION.OPEN_FILE, 'customshow': PP_ACTION.NAMED_SLIDE_SHOW, 'ole': PP_ACTION.OLE_VERB, 'macro': PP_ACTION.RUN_MACRO, 'program': PP_ACTION.RUN_PROGRAM, }[action_verb] @lazyproperty def hyperlink(self): """ A |Hyperlink| object representing the hyperlink action defined on this click or hover mouse event. A |Hyperlink| object is always returned, even if no hyperlink or other click action is defined. """ return Hyperlink(self._element, self._parent, self._hover) @property def target_slide(self): """ A reference to the slide in this presentation that is the target of the slide jump action in this shape. Slide jump actions include `PP_ACTION.FIRST_SLIDE`, `LAST_SLIDE`, `NEXT_SLIDE`, `PREVIOUS_SLIDE`, and `NAMED_SLIDE`. Returns |None| for all other actions. In particular, the `LAST_SLIDE_VIEWED` action and the `PLAY` (start other presentation) actions are not supported. """ slide_jump_actions = ( PP_ACTION.FIRST_SLIDE, PP_ACTION.LAST_SLIDE, PP_ACTION.NEXT_SLIDE, PP_ACTION.PREVIOUS_SLIDE, PP_ACTION.NAMED_SLIDE, ) if self.action not in slide_jump_actions: return None if self.action == PP_ACTION.FIRST_SLIDE: return self._slides[0] elif self.action == PP_ACTION.LAST_SLIDE: return self._slides[-1] elif self.action == PP_ACTION.NEXT_SLIDE: next_slide_idx = self._slide_index + 1 if next_slide_idx >= len(self._slides): raise ValueError('no next slide') return self._slides[next_slide_idx] elif self.action == PP_ACTION.PREVIOUS_SLIDE: prev_slide_idx = self._slide_index - 1 if prev_slide_idx < 0: raise ValueError('no previous slide') return self._slides[prev_slide_idx] elif self.action == PP_ACTION.NAMED_SLIDE: rId = self._hlink.rId return self.part.related_parts[rId].slide @property def _hlink(self): """ Reference to the `a:hlinkClick` or `h:hlinkHover` element for this click action. Returns |None| if the element is not present. """ if self._hover: return self._element.hlinkHover return self._element.hlinkClick @lazyproperty def _slide(self): """ Reference to the slide containing the shape having this click action. """ return self.part.slide @lazyproperty def _slide_index(self): """ Position in the slide collection of the slide containing the shape having this click action. """ return self._slides.index(self._slide) @lazyproperty def _slides(self): """ Reference to the slide collection for this presentation. """ return self.part.package.presentation_part.presentation.slides class Hyperlink(Subshape): """ Represents a hyperlink action on a shape or text run. """ def __init__(self, xPr, parent, hover=False): super(Hyperlink, self).__init__(parent) # xPr is either a cNvPr or rPr element self._element = xPr # _hover determines use of `a:hlinkClick` or `a:hlinkHover` self._hover = hover @property def address(self): """ Read/write. The URL of the hyperlink. URL can be on http, https, mailto, or file scheme; others may work. Returns |None| if no hyperlink is defined, including when another action such as `RUN_MACRO` is defined on the object. Assigning |None| removes any action defined on the object, whether it is a hyperlink action or not. """ hlink = self._hlink # there's no URL if there's no click action if hlink is None: return None # a click action without a relationship has no URL rId = hlink.rId if not rId: return None return self.part.target_ref(rId) @address.setter def address(self, url): # implements all three of add, change, and remove hyperlink self._remove_hlink() if url: rId = self.part.relate_to(url, RT.HYPERLINK, is_external=True) hlink = self._get_or_add_hlink() hlink.rId = rId def _get_or_add_hlink(self): """ Get the `a:hlinkClick` or `a:hlinkHover` element for the Hyperlink object, depending on the value of `self._hover`. Create one if not present. """ if self._hover: return self._element.get_or_add_hlinkHover() return self._element.get_or_add_hlinkClick() @property def _hlink(self): """ Reference to the `a:hlinkClick` or `h:hlinkHover` element for this click action. Returns |None| if the element is not present. """ if self._hover: return self._element.hlinkHover return self._element.hlinkClick def _remove_hlink(self): """ Remove the a:hlinkClick or a:hlinkHover element, including dropping any relationship it might have. """ hlink = self._hlink if hlink is None: return rId = hlink.rId if rId: self.part.drop_rel(rId) self._element.remove(hlink)
# coding=utf-8 # Copyright 2020 The TF-Agents 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 # # https://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. # Lint as: python2, python3 r"""Train and Eval DQN. To run DQN on CartPole: ```bash tensorboard --logdir $HOME/tmp/dqn/gym/CartPole-v0/ --port 2223 & python tf_agents/agents/dqn/examples/v2/train_eval.py \ --root_dir=$HOME/tmp/dqn/gym/CartPole-v0/ \ --alsologtostderr ``` To run DQN-RNNs on MaskedCartPole: ```bash python tf_agents/agents/dqn/examples/v2/train_eval.py \ --root_dir=$HOME/tmp/dqn_rnn/gym/MaskedCartPole-v0/ \ --gin_param='train_eval.env_name="MaskedCartPole-v0"' \ --gin_param='train_eval.train_sequence_length=10' \ --alsologtostderr ``` """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import os import time from absl import app from absl import flags from absl import logging import gin from six.moves import range import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import from tf_agents.agents.dqn import dqn_agent from tf_agents.drivers import dynamic_step_driver from tf_agents.environments import suite_gym from tf_agents.environments import tf_py_environment from tf_agents.environments.examples import masked_cartpole # pylint: disable=unused-import from tf_agents.eval import metric_utils from tf_agents.keras_layers import dynamic_unroll_layer from tf_agents.metrics import tf_metrics from tf_agents.networks import sequential from tf_agents.policies import random_tf_policy from tf_agents.replay_buffers import tf_uniform_replay_buffer from tf_agents.utils import common flags.DEFINE_string('root_dir', os.getenv('TEST_UNDECLARED_OUTPUTS_DIR'), 'Root directory for writing logs/summaries/checkpoints.') flags.DEFINE_integer('num_iterations', 100000, 'Total number train/eval iterations to perform.') flags.DEFINE_multi_string('gin_file', None, 'Paths to the gin-config files.') flags.DEFINE_multi_string('gin_param', None, 'Gin binding parameters.') FLAGS = flags.FLAGS KERAS_LSTM_FUSED = 2 @gin.configurable def train_eval( root_dir, env_name='CartPole-v0', num_iterations=100000, train_sequence_length=1, # Params for QNetwork fc_layer_params=(100,), # Params for QRnnNetwork input_fc_layer_params=(50,), lstm_size=(20,), output_fc_layer_params=(20,), # Params for collect initial_collect_steps=1000, collect_steps_per_iteration=1, epsilon_greedy=0.1, replay_buffer_capacity=100000, # Params for target update target_update_tau=0.05, target_update_period=5, # Params for train train_steps_per_iteration=1, batch_size=64, learning_rate=1e-3, n_step_update=1, gamma=0.99, reward_scale_factor=1.0, gradient_clipping=None, use_tf_functions=True, # Params for eval num_eval_episodes=10, eval_interval=1000, # Params for checkpoints train_checkpoint_interval=10000, policy_checkpoint_interval=5000, rb_checkpoint_interval=20000, # Params for summaries and logging log_interval=1000, summary_interval=1000, summaries_flush_secs=10, debug_summaries=False, summarize_grads_and_vars=False, eval_metrics_callback=None): """A simple train and eval for DQN.""" root_dir = os.path.expanduser(root_dir) train_dir = os.path.join(root_dir, 'train') eval_dir = os.path.join(root_dir, 'eval') train_summary_writer = tf.compat.v2.summary.create_file_writer( train_dir, flush_millis=summaries_flush_secs * 1000) train_summary_writer.set_as_default() eval_summary_writer = tf.compat.v2.summary.create_file_writer( eval_dir, flush_millis=summaries_flush_secs * 1000) eval_metrics = [ tf_metrics.AverageReturnMetric(buffer_size=num_eval_episodes), tf_metrics.AverageEpisodeLengthMetric(buffer_size=num_eval_episodes) ] global_step = tf.compat.v1.train.get_or_create_global_step() with tf.compat.v2.summary.record_if( lambda: tf.math.equal(global_step % summary_interval, 0)): tf_env = tf_py_environment.TFPyEnvironment(suite_gym.load(env_name)) eval_tf_env = tf_py_environment.TFPyEnvironment(suite_gym.load(env_name)) if train_sequence_length != 1 and n_step_update != 1: raise NotImplementedError( 'train_eval does not currently support n-step updates with stateful ' 'networks (i.e., RNNs)') action_spec = tf_env.action_spec() num_actions = action_spec.maximum - action_spec.minimum + 1 if train_sequence_length > 1: q_net = create_recurrent_network( input_fc_layer_params, lstm_size, output_fc_layer_params, num_actions) else: q_net = create_feedforward_network(fc_layer_params, num_actions) train_sequence_length = n_step_update # TODO(b/127301657): Decay epsilon based on global step, cf. cl/188907839 tf_agent = dqn_agent.DqnAgent( tf_env.time_step_spec(), tf_env.action_spec(), q_network=q_net, epsilon_greedy=epsilon_greedy, n_step_update=n_step_update, target_update_tau=target_update_tau, target_update_period=target_update_period, optimizer=tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate), td_errors_loss_fn=common.element_wise_squared_loss, gamma=gamma, reward_scale_factor=reward_scale_factor, gradient_clipping=gradient_clipping, debug_summaries=debug_summaries, summarize_grads_and_vars=summarize_grads_and_vars, train_step_counter=global_step) tf_agent.initialize() train_metrics = [ tf_metrics.NumberOfEpisodes(), tf_metrics.EnvironmentSteps(), tf_metrics.AverageReturnMetric(), tf_metrics.AverageEpisodeLengthMetric(), ] eval_policy = tf_agent.policy collect_policy = tf_agent.collect_policy replay_buffer = tf_uniform_replay_buffer.TFUniformReplayBuffer( data_spec=tf_agent.collect_data_spec, batch_size=tf_env.batch_size, max_length=replay_buffer_capacity) collect_driver = dynamic_step_driver.DynamicStepDriver( tf_env, collect_policy, observers=[replay_buffer.add_batch] + train_metrics, num_steps=collect_steps_per_iteration) train_checkpointer = common.Checkpointer( ckpt_dir=train_dir, agent=tf_agent, global_step=global_step, metrics=metric_utils.MetricsGroup(train_metrics, 'train_metrics')) policy_checkpointer = common.Checkpointer( ckpt_dir=os.path.join(train_dir, 'policy'), policy=eval_policy, global_step=global_step) rb_checkpointer = common.Checkpointer( ckpt_dir=os.path.join(train_dir, 'replay_buffer'), max_to_keep=1, replay_buffer=replay_buffer) train_checkpointer.initialize_or_restore() rb_checkpointer.initialize_or_restore() if use_tf_functions: # To speed up collect use common.function. collect_driver.run = common.function(collect_driver.run) tf_agent.train = common.function(tf_agent.train) initial_collect_policy = random_tf_policy.RandomTFPolicy( tf_env.time_step_spec(), tf_env.action_spec()) # Collect initial replay data. logging.info( 'Initializing replay buffer by collecting experience for %d steps with ' 'a random policy.', initial_collect_steps) dynamic_step_driver.DynamicStepDriver( tf_env, initial_collect_policy, observers=[replay_buffer.add_batch] + train_metrics, num_steps=initial_collect_steps).run() results = metric_utils.eager_compute( eval_metrics, eval_tf_env, eval_policy, num_episodes=num_eval_episodes, train_step=global_step, summary_writer=eval_summary_writer, summary_prefix='Metrics', ) if eval_metrics_callback is not None: eval_metrics_callback(results, global_step.numpy()) metric_utils.log_metrics(eval_metrics) time_step = None policy_state = collect_policy.get_initial_state(tf_env.batch_size) timed_at_step = global_step.numpy() time_acc = 0 # Dataset generates trajectories with shape [Bx2x...] dataset = replay_buffer.as_dataset( num_parallel_calls=3, sample_batch_size=batch_size, num_steps=train_sequence_length + 1).prefetch(3) iterator = iter(dataset) def train_step(): experience, _ = next(iterator) return tf_agent.train(experience) if use_tf_functions: train_step = common.function(train_step) for _ in range(num_iterations): start_time = time.time() time_step, policy_state = collect_driver.run( time_step=time_step, policy_state=policy_state, ) for _ in range(train_steps_per_iteration): train_loss = train_step() time_acc += time.time() - start_time if global_step.numpy() % log_interval == 0: logging.info('step = %d, loss = %f', global_step.numpy(), train_loss.loss) steps_per_sec = (global_step.numpy() - timed_at_step) / time_acc logging.info('%.3f steps/sec', steps_per_sec) tf.compat.v2.summary.scalar( name='global_steps_per_sec', data=steps_per_sec, step=global_step) timed_at_step = global_step.numpy() time_acc = 0 for train_metric in train_metrics: train_metric.tf_summaries( train_step=global_step, step_metrics=train_metrics[:2]) if global_step.numpy() % train_checkpoint_interval == 0: train_checkpointer.save(global_step=global_step.numpy()) if global_step.numpy() % policy_checkpoint_interval == 0: policy_checkpointer.save(global_step=global_step.numpy()) if global_step.numpy() % rb_checkpoint_interval == 0: rb_checkpointer.save(global_step=global_step.numpy()) if global_step.numpy() % eval_interval == 0: results = metric_utils.eager_compute( eval_metrics, eval_tf_env, eval_policy, num_episodes=num_eval_episodes, train_step=global_step, summary_writer=eval_summary_writer, summary_prefix='Metrics', ) if eval_metrics_callback is not None: eval_metrics_callback(results, global_step.numpy()) metric_utils.log_metrics(eval_metrics) return train_loss logits = functools.partial( tf.keras.layers.Dense, activation=None, kernel_initializer=tf.random_uniform_initializer(minval=-0.03, maxval=0.03), bias_initializer=tf.constant_initializer(-0.2)) dense = functools.partial( tf.keras.layers.Dense, activation=tf.keras.activations.relu, kernel_initializer=tf.compat.v1.variance_scaling_initializer( scale=2.0, mode='fan_in', distribution='truncated_normal')) fused_lstm_cell = functools.partial( tf.keras.layers.LSTMCell, implementation=KERAS_LSTM_FUSED) def create_feedforward_network(fc_layer_units, num_actions): return sequential.Sequential( [dense(num_units) for num_units in fc_layer_units] + [logits(num_actions)]) def create_recurrent_network( input_fc_layer_units, lstm_size, output_fc_layer_units, num_actions): rnn_cell = tf.keras.layers.StackedRNNCells( [fused_lstm_cell(s) for s in lstm_size]) return sequential.Sequential( [dense(num_units) for num_units in input_fc_layer_units] + [dynamic_unroll_layer.DynamicUnroll(rnn_cell)] + [dense(num_units) for num_units in output_fc_layer_units] + [logits(num_actions)]) def main(_): logging.set_verbosity(logging.INFO) tf.compat.v1.enable_v2_behavior() gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_param) train_eval(FLAGS.root_dir, num_iterations=FLAGS.num_iterations) if __name__ == '__main__': flags.mark_flag_as_required('root_dir') app.run(main)
#!/usr/bin/python # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. ''' This script provides tools to map BattOrs to phones. Phones are identified by the following string: "Phone serial number" - Serial number of the phone. This can be obtained via 'adb devices' or 'usb-devices', and is not expected to change for a given phone. BattOrs are identified by the following two strings: "BattOr serial number" - Serial number of the BattOr. This can be obtained via 'usb-devices', and is not expected to change for a given BattOr. "BattOr path" - The path of the form '/dev/ttyUSB*' that is used to communicate with the BattOr (the battor_agent binary takes this BattOr path as a parameter). The BattOr path is frequently reassigned by the OS, most often when the device is disconnected and then reconnected. Thus, the BattOr path cannot be expected to be stable. In a typical application, the user will require the BattOr path for the BattOr that is plugged into a given phone. For instance, the user will be running tracing on a particular phone, and will need to know which BattOr path to use to communicate with the BattOr to get the corresponding power trace. Getting this mapping requires two steps: (1) determining the mapping between phone serial numbers and BattOr serial numbers, and (2) getting the BattOr path corresponding to a given BattOr serial number. For step (1), we generate a JSON file giving this mapping. This JSON file consists of a list of items of the following form: [{'phone': <phone serial 1>, 'battor': <battor serial 1>}, {'phone': <phone serial 2>, 'battor': <battor serial 2>}, ...] The default way to generate this JSON file is using the function GenerateSerialMapFile, which generates a mapping based on assuming that the system has two identical USB hubs connected to it, and the phone plugged into physical port number 1 on one hub corresponds to the BattOr plugged into physical port number 1 on the other hub, and similarly with physical port numbers 2, 3, etc. This generates the map file based on the structure at the time GenerateSerialMapFile called. Note that after the map file is generated, port numbers are no longer used; the user could move around the devices in the ports without affecting which phone goes with which BattOr. (Thus, if the user wanted to update the mapping to match the new port connections, the user would have to re-generate this file.) The script update_mapping.py will do this updating from the command line. If the user wanted to specify a custom mapping, the user could instead create the JSON file manually. (In this case, hubs would not be necessary and the physical ports connected would be irrelevant.) Step (2) is conducted through the function GetBattOrPathFromPhoneSerial, which takes a serial number mapping generated via step (1) and a phone serial number, then gets the corresponding BattOr serial number from the map and determines its BattOr path (e.g. /dev/ttyUSB0). Since BattOr paths can change if devices are connected and disconnected (even if connected or disconnected via the same port) this function should be called to determine the BattOr path every time before connecting to the BattOr. Note that if there is only one BattOr connected to the system, then GetBattOrPathFromPhoneSerial will always return that BattOr and will ignore the mapping file. Thus, if the user never has more than one BattOr connected to the system, the user will not need to generate mapping files. ''' import json import collections from battor import battor_error from devil.utils import find_usb_devices from devil.utils import usb_hubs def GetBattOrList(device_tree_map): return [x for x in find_usb_devices.GetTTYList() if IsBattOr(x, device_tree_map)] def IsBattOr(tty_string, device_tree_map): (bus, device) = find_usb_devices.GetBusDeviceFromTTY(tty_string) node = device_tree_map[bus].FindDeviceNumber(device) return '0403:6001' in node.desc def GetBattOrSerialNumbers(device_tree_map): for x in find_usb_devices.GetTTYList(): if IsBattOr(x, device_tree_map): (bus, device) = find_usb_devices.GetBusDeviceFromTTY(x) devnode = device_tree_map[bus].FindDeviceNumber(device) yield devnode.serial def ReadSerialMapFile(filename): """Reads JSON file giving phone-to-battor serial number map. Parses a JSON file consisting of a list of items of the following form: [{'phone': <phone serial 1>, 'battor': <battor serial 1>}, {'phone': <phone serial 2>, 'battor': <battor serial 2>}, ...] indicating which phone serial numbers should be matched with which BattOr serial numbers. Returns dictionary of the form: {<phone serial 1>: <BattOr serial 1>, <phone serial 2>: <BattOr serial 2>} Args: filename: Name of file to read. """ result = {} with open(filename, 'r') as infile: in_dict = json.load(infile) for x in in_dict: result[x['phone']] = x['battor'] return result def WriteSerialMapFile(filename, serial_map): """Writes a map of phone serial numbers to BattOr serial numbers to file. Writes a JSON file consisting of a list of items of the following form: [{'phone': <phone serial 1>, 'battor': <battor serial 1>}, {'phone': <phone serial 2>, 'battor': <battor serial 2>}, ...] indicating which phone serial numbers should be matched with which BattOr serial numbers. Mapping is based on the physical port numbers of the hubs that the BattOrs and phones are connected to. Args: filename: Name of file to write. serial_map: Serial map {phone: battor} """ result = [] for (phone, battor) in serial_map.iteritems(): result.append({'phone': phone, 'battor': battor}) with open(filename, 'w') as outfile: json.dump(result, outfile) def GenerateSerialMap(hub_types=None): """Generates a map of phone serial numbers to BattOr serial numbers. Generates a dict of: {<phone serial 1>: <battor serial 1>, <phone serial 2>: <battor serial 2>} indicating which phone serial numbers should be matched with which BattOr serial numbers. Mapping is based on the physical port numbers of the hubs that the BattOrs and phones are connected to. Args: hub_types: List of hub types to check for. If not specified, checks for all defined hub types. (see usb_hubs.py for details) """ if hub_types: hub_types = [usb_hubs.GetHubType(x) for x in hub_types] else: hub_types = usb_hubs.ALL_HUBS devtree = find_usb_devices.GetBusNumberToDeviceTreeMap() # List of serial numbers in the system that represent BattOrs. battor_serials = list(GetBattOrSerialNumbers(devtree)) # If there's only one BattOr in the system, then a serial number ma # is not necessary. if len(battor_serials) == 1: return {} # List of dictionaries, one for each hub, that maps the physical # port number to the serial number of that hub. For instance, in a 2 # hub system, this could return [{1:'ab', 2:'cd'}, {1:'jkl', 2:'xyz'}] # where 'ab' and 'cd' are the phone serial numbers and 'jkl' and 'xyz' # are the BattOr serial numbers. port_to_serial = find_usb_devices.GetAllPhysicalPortToSerialMaps( hub_types, device_tree_map=devtree) class serials(object): def __init__(self): self.phone = None self.battor = None # Map of {physical port number: [phone serial #, BattOr serial #]. This # map is populated by executing the code below. For instance, in the above # example, after the code below is executed, port_to_devices would equal # {1: ['ab', 'jkl'], 2: ['cd', 'xyz']} port_to_devices = collections.defaultdict(serials) for hub in port_to_serial: for (port, serial) in hub.iteritems(): if serial in battor_serials: if port_to_devices[port].battor is not None: raise battor_error.BattOrError('Multiple BattOrs on same port number') else: port_to_devices[port].battor = serial else: if port_to_devices[port].phone is not None: raise battor_error.BattOrError('Multiple phones on same port number') else: port_to_devices[port].phone = serial # Turn the port_to_devices map into a map of the form # {phone serial number: BattOr serial number}. result = {} for pair in port_to_devices.values(): if pair.phone is None: continue if pair.battor is None: raise battor_error.BattOrError( 'Phone detected with no corresponding BattOr') result[pair.phone] = pair.battor return result def GenerateSerialMapFile(filename, hub_types=None): """Generates a serial map file and writes it.""" WriteSerialMapFile(filename, GenerateSerialMap(hub_types)) def _PhoneToPathMap(serial, serial_map, devtree): """Maps phone serial number to TTY path, assuming serial map is provided.""" try: battor_serial = serial_map[serial] except KeyError: raise battor_error.BattOrError('Serial number not found in serial map.') for tree in devtree.values(): for node in tree.AllNodes(): if isinstance(node, find_usb_devices.USBDeviceNode): if node.serial == battor_serial: bus_device_to_tty = find_usb_devices.GetBusDeviceToTTYMap() bus_device = (node.bus_num, node.device_num) try: return bus_device_to_tty[bus_device] except KeyError: raise battor_error.BattOrError( 'Device with given serial number not a BattOr ' '(does not have TTY path)') def GetBattOrPathFromPhoneSerial(serial, serial_map=None, serial_map_file=None): """Gets the TTY path (e.g. '/dev/ttyUSB0') to communicate with the BattOr. (1) If serial_map is given, it is treated as a dictionary mapping phone serial numbers to BattOr serial numbers. This function will get the TTY path for the given BattOr serial number. (2) If serial_map_file is given, it is treated as the name of a phone-to-BattOr mapping file (generated with GenerateSerialMapFile) and this will be loaded and used as the dict to map port numbers to BattOr serial numbers. You can only give one of serial_map and serial_map_file. Args: serial: Serial number of phone connected on the same physical port that the BattOr is connected to. serial_map: Map of phone serial numbers to BattOr serial numbers, given as a dictionary. serial_map_file: Map of phone serial numbers to BattOr serial numbers, given as a file. hub_types: List of hub types to check for. Used only if serial_map_file is None. Returns: Device string used to communicate with device. Raises: ValueError: If serial number is not given. BattOrError: If BattOr not found or unexpected USB topology. """ # If there's only one BattOr connected to the system, just use that one. # This allows for use on, e.g., a developer's workstation with no hubs. devtree = find_usb_devices.GetBusNumberToDeviceTreeMap() all_battors = GetBattOrList(devtree) if len(all_battors) == 1: return '/dev/' + all_battors[0] if not serial: raise battor_error.BattOrError( 'Two or more BattOrs connected, no serial provided') if serial_map and serial_map_file: raise ValueError('Cannot specify both serial_map and serial_map_file') if serial_map_file: serial_map = ReadSerialMapFile(serial_map_file) tty_string = _PhoneToPathMap(serial, serial_map, devtree) if not tty_string: raise battor_error.BattOrError( 'No device with given serial number detected.') if IsBattOr(tty_string, devtree): return '/dev/' + tty_string else: raise battor_error.BattOrError( 'Device with given serial number is not a BattOr.') if __name__ == '__main__': # Main function for testing purposes print GenerateSerialMap()
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2018, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' Provide a base class for objects that can have declarative, typed, serializable properties. .. note:: These classes form part of the very low-level machinery that implements the Bokeh model and property system. It is unlikely that any of these classes or their methods will be applicable to any standard usage or to anyone who is not directly developing on Bokeh's own infrastructure. ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals import logging log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports import difflib import inspect from warnings import warn # External imports # Bokeh imports from ..util.future import with_metaclass from ..util.string import nice_join from .property.descriptor_factory import PropertyDescriptorFactory from .property.override import Override from .property.wrappers import PropertyValueContainer #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'abstract', 'accumulate_dict_from_superclasses', 'accumulate_from_superclasses', 'HasProps', 'MetaHasProps', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- def abstract(cls): ''' A decorator to mark abstract base classes derived from |HasProps|. ''' if not issubclass(cls, HasProps): raise TypeError("%s is not a subclass of HasProps" % cls.__name__) # running python with -OO will discard docstrings -> __doc__ is None if cls.__doc__ is not None: cls.__doc__ += _ABSTRACT_ADMONITION return cls class MetaHasProps(type): ''' Specialize the construction of |HasProps| classes. This class is a `metaclass`_ for |HasProps| that is responsible for creating and adding the |PropertyDescriptor| instances that delegate validation and serialization to |Property| attributes. .. _metaclass: https://docs.python.org/3/reference/datamodel.html#metaclasses ''' def __new__(meta_cls, class_name, bases, class_dict): ''' ''' names_with_refs = set() container_names = set() # Now handle all the Override overridden_defaults = {} for name, prop in class_dict.items(): if not isinstance(prop, Override): continue if prop.default_overridden: overridden_defaults[name] = prop.default for name, default in overridden_defaults.items(): del class_dict[name] generators = dict() for name, generator in class_dict.items(): if isinstance(generator, PropertyDescriptorFactory): generators[name] = generator elif isinstance(generator, type) and issubclass(generator, PropertyDescriptorFactory): # Support the user adding a property without using parens, # i.e. using just the Property subclass instead of an # instance of the subclass generators[name] = generator.autocreate() dataspecs = {} new_class_attrs = {} for name, generator in generators.items(): prop_descriptors = generator.make_descriptors(name) replaced_self = False for prop_descriptor in prop_descriptors: if prop_descriptor.name in generators: if generators[prop_descriptor.name] is generator: # a generator can replace itself, this is the # standard case like `foo = Int()` replaced_self = True prop_descriptor.add_prop_descriptor_to_class(class_name, new_class_attrs, names_with_refs, container_names, dataspecs) else: # if a generator tries to overwrite another # generator that's been explicitly provided, # use the prop that was manually provided # and ignore this one. pass else: prop_descriptor.add_prop_descriptor_to_class(class_name, new_class_attrs, names_with_refs, container_names, dataspecs) # if we won't overwrite ourselves anyway, delete the generator if not replaced_self: del class_dict[name] class_dict.update(new_class_attrs) class_dict["__properties__"] = set(new_class_attrs) class_dict["__properties_with_refs__"] = names_with_refs class_dict["__container_props__"] = container_names if len(overridden_defaults) > 0: class_dict["__overridden_defaults__"] = overridden_defaults if dataspecs: class_dict["__dataspecs__"] = dataspecs if "__example__" in class_dict: path = class_dict["__example__"] # running python with -OO will discard docstrings -> __doc__ is None if "__doc__" in class_dict and class_dict["__doc__"] is not None: class_dict["__doc__"] += _EXAMPLE_TEMPLATE % dict(path=path) return super(MetaHasProps, meta_cls).__new__(meta_cls, class_name, bases, class_dict) def __init__(cls, class_name, bases, nmspc): if class_name == 'HasProps': return # Check for improperly overriding a Property attribute. # Overriding makes no sense except through the Override # class which can be used to tweak the default. # Historically code also tried changing the Property's # type or changing from Property to non-Property: these # overrides are bad conceptually because the type of a # read-write property is invariant. cls_attrs = cls.__dict__.keys() # we do NOT want inherited attrs here for attr in cls_attrs: for base in bases: if issubclass(base, HasProps) and attr in base.properties(): warn(('Property "%s" in class %s was overridden by a class attribute ' + \ '"%s" in class %s; it never makes sense to do this. ' + \ 'Either %s.%s or %s.%s should be removed, or %s.%s should not ' + \ 'be a Property, or use Override(), depending on the intended effect.') % (attr, base.__name__, attr, class_name, base.__name__, attr, class_name, attr, base.__name__, attr), RuntimeWarning, stacklevel=2) if "__overridden_defaults__" in cls.__dict__: our_props = cls.properties() for key in cls.__dict__["__overridden_defaults__"].keys(): if key not in our_props: warn(('Override() of %s in class %s does not override anything.') % (key, class_name), RuntimeWarning, stacklevel=2) def accumulate_from_superclasses(cls, propname): ''' Traverse the class hierarchy and accumulate the special sets of names ``MetaHasProps`` stores on classes: Args: name (str) : name of the special attribute to collect. Typically meaningful values are: ``__container_props__``, ``__properties__``, ``__properties_with_refs__`` ''' cachename = "__cached_all" + propname # we MUST use cls.__dict__ NOT hasattr(). hasattr() would also look at base # classes, and the cache must be separate for each class if cachename not in cls.__dict__: s = set() for c in inspect.getmro(cls): if issubclass(c, HasProps) and hasattr(c, propname): base = getattr(c, propname) s.update(base) setattr(cls, cachename, s) return cls.__dict__[cachename] def accumulate_dict_from_superclasses(cls, propname): ''' Traverse the class hierarchy and accumulate the special dicts ``MetaHasProps`` stores on classes: Args: name (str) : name of the special attribute to collect. Typically meaningful values are: ``__dataspecs__``, ``__overridden_defaults__`` ''' cachename = "__cached_all" + propname # we MUST use cls.__dict__ NOT hasattr(). hasattr() would also look at base # classes, and the cache must be separate for each class if cachename not in cls.__dict__: d = dict() for c in inspect.getmro(cls): if issubclass(c, HasProps) and hasattr(c, propname): base = getattr(c, propname) for k,v in base.items(): if k not in d: d[k] = v setattr(cls, cachename, d) return cls.__dict__[cachename] class HasProps(with_metaclass(MetaHasProps, object)): ''' Base class for all class types that have Bokeh properties. ''' def __init__(self, **properties): ''' ''' super(HasProps, self).__init__() self._property_values = dict() self._unstable_default_values = dict() self._unstable_themed_values = dict() for name, value in properties.items(): setattr(self, name, value) def __setattr__(self, name, value): ''' Intercept attribute setting on HasProps in order to special case a few situations: * short circuit all property machinery for ``_private`` attributes * suggest similar attribute names on attribute errors Args: name (str) : the name of the attribute to set on this object value (obj) : the value to set Returns: None ''' # self.properties() below can be expensive so avoid it # if we're just setting a private underscore field if name.startswith("_"): super(HasProps, self).__setattr__(name, value) return props = sorted(self.properties()) descriptor = getattr(self.__class__, name, None) if name in props or (descriptor is not None and descriptor.fset is not None): super(HasProps, self).__setattr__(name, value) else: matches, text = difflib.get_close_matches(name.lower(), props), "similar" if not matches: matches, text = props, "possible" raise AttributeError("unexpected attribute '%s' to %s, %s attributes are %s" % (name, self.__class__.__name__, text, nice_join(matches))) def __str__(self): return "%s(...)" % self.__class__.__name__ __repr__ = __str__ def equals(self, other): ''' Structural equality of models. Args: other (HasProps) : the other instance to compare to Returns: True, if properties are structurally equal, otherwise False ''' # NOTE: don't try to use this to implement __eq__. Because then # you will be tempted to implement __hash__, which would interfere # with mutability of models. However, not implementing __hash__ # will make bokeh unusable in Python 3, where proper implementation # of __hash__ is required when implementing __eq__. if not isinstance(other, self.__class__): return False else: return self.properties_with_values() == other.properties_with_values() def set_from_json(self, name, json, models=None, setter=None): ''' Set a property value on this object from JSON. Args: name: (str) : name of the attribute to set json: (JSON-value) : value to set to the attribute to models (dict or None, optional) : Mapping of model ids to models (default: None) This is needed in cases where the attributes to update also have values that have references. setter(ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' if name in self.properties(): log.trace("Patching attribute %r of %r with %r", name, self, json) descriptor = self.lookup(name) descriptor.set_from_json(self, json, models, setter) else: log.warning("JSON had attr %r on obj %r, which is a client-only or invalid attribute that shouldn't have been sent", name, self) def update(self, **kwargs): ''' Updates the object's properties from the given keyword arguments. Returns: None Examples: The following are equivalent: .. code-block:: python from bokeh.models import Range1d r = Range1d # set properties individually: r.start = 10 r.end = 20 # update properties together: r.update(start=10, end=20) ''' for k,v in kwargs.items(): setattr(self, k, v) def update_from_json(self, json_attributes, models=None, setter=None): ''' Updates the object's properties from a JSON attributes dictionary. Args: json_attributes: (JSON-dict) : attributes and values to update models (dict or None, optional) : Mapping of model ids to models (default: None) This is needed in cases where the attributes to update also have values that have references. setter(ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' for k, v in json_attributes.items(): self.set_from_json(k, v, models, setter) @classmethod def lookup(cls, name): ''' Find the ``PropertyDescriptor`` for a Bokeh property on a class, given the property name. Args: name (str) : name of the property to search for Returns: PropertyDescriptor : descriptor for property named ``name`` ''' return getattr(cls, name) @classmethod def properties_with_refs(cls): ''' Collect the names of all properties on this class that also have references. This method *always* traverses the class hierarchy and includes properties defined on any parent classes. Returns: set[str] : names of properties that have references ''' return accumulate_from_superclasses(cls, "__properties_with_refs__") @classmethod def properties_containers(cls): ''' Collect the names of all container properties on this class. This method *always* traverses the class hierarchy and includes properties defined on any parent classes. Returns: set[str] : names of container properties ''' return accumulate_from_superclasses(cls, "__container_props__") @classmethod def properties(cls, with_bases=True): ''' Collect the names of properties on this class. This method *optionally* traverses the class hierarchy and includes properties defined on any parent classes. Args: with_bases (bool, optional) : Whether to include properties defined on parent classes in the results. (default: True) Returns: set[str] : property names ''' if with_bases: return accumulate_from_superclasses(cls, "__properties__") else: return set(cls.__properties__) @classmethod def dataspecs(cls): ''' Collect the names of all ``DataSpec`` properties on this class. This method *always* traverses the class hierarchy and includes properties defined on any parent classes. Returns: set[str] : names of DataSpec properties ''' return set(cls.dataspecs_with_props().keys()) @classmethod def dataspecs_with_props(cls): ''' Collect a dict mapping the names of all ``DataSpec`` properties on this class to the associated properties. This method *always* traverses the class hierarchy and includes properties defined on any parent classes. Returns: dict[str, DataSpec] : mapping of names and ``DataSpec`` properties ''' return accumulate_dict_from_superclasses(cls, "__dataspecs__") def properties_with_values(self, include_defaults=True): ''' Collect a dict mapping property names to their values. This method *always* traverses the class hierarchy and includes properties defined on any parent classes. Non-serializable properties are skipped and property values are in "serialized" format which may be slightly different from the values you would normally read from the properties; the intent of this method is to return the information needed to losslessly reconstitute the object instance. Args: include_defaults (bool, optional) : Whether to include properties that haven't been explicitly set since the object was created. (default: True) Returns: dict : mapping from property names to their values ''' return self.query_properties_with_values(lambda prop: prop.serialized, include_defaults) @classmethod def _overridden_defaults(cls): ''' Returns a dictionary of defaults that have been overridden. This is an implementation detail of Property. ''' return accumulate_dict_from_superclasses(cls, "__overridden_defaults__") def query_properties_with_values(self, query, include_defaults=True): ''' Query the properties values of |HasProps| instances with a predicate. Args: query (callable) : A callable that accepts property descriptors and returns True or False include_defaults (bool, optional) : Whether to include properties that have not been explicitly set by a user (default: True) Returns: dict : mapping of property names and values for matching properties ''' themed_keys = set() result = dict() if include_defaults: keys = self.properties() else: # TODO (bev) For now, include unstable default values. Things rely on Instances # always getting serialized, even defaults, and adding unstable defaults here # accomplishes that. Unmodified defaults for property value containers will be # weeded out below. keys = set(self._property_values.keys()) | set(self._unstable_default_values.keys()) if self.themed_values(): themed_keys = set(self.themed_values().keys()) keys |= themed_keys for key in keys: descriptor = self.lookup(key) if not query(descriptor): continue value = descriptor.serializable_value(self) if not include_defaults and key not in themed_keys: if isinstance(value, PropertyValueContainer) and key in self._unstable_default_values: continue result[key] = value return result def themed_values(self): ''' Get any theme-provided overrides. Results are returned as a dict from property name to value, or ``None`` if no theme overrides any values for this instance. Returns: dict or None ''' return getattr(self, '__themed_values__', None) def apply_theme(self, property_values): ''' Apply a set of theme values which will be used rather than defaults, but will not override application-set values. The passed-in dictionary may be kept around as-is and shared with other instances to save memory (so neither the caller nor the |HasProps| instance should modify it). Args: property_values (dict) : theme values to use in place of defaults Returns: None ''' old_dict = self.themed_values() # if the same theme is set again, it should reuse the same dict if old_dict is property_values: return removed = set() # we're doing a little song-and-dance to avoid storing __themed_values__ or # an empty dict, if there's no theme that applies to this HasProps instance. if old_dict is not None: removed.update(set(old_dict.keys())) added = set(property_values.keys()) old_values = dict() for k in added.union(removed): old_values[k] = getattr(self, k) if len(property_values) > 0: setattr(self, '__themed_values__', property_values) elif hasattr(self, '__themed_values__'): delattr(self, '__themed_values__') # Property container values might be cached even if unmodified. Invalidate # any cached values that are not modified at this point. for k, v in old_values.items(): if k in self._unstable_themed_values: del self._unstable_themed_values[k] # Emit any change notifications that result for k, v in old_values.items(): descriptor = self.lookup(k) descriptor.trigger_if_changed(self, v) def unapply_theme(self): ''' Remove any themed values and restore defaults. Returns: None ''' self.apply_theme(property_values=dict()) def _clone(self): ''' Duplicate a HasProps object. Values that are containers are shallow-copied. ''' return self.__class__(**self._property_values) #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- _ABSTRACT_ADMONITION = ''' .. note:: This is an abstract base class used to help organize the hierarchy of Bokeh model types. **It is not useful to instantiate on its own.** ''' _EXAMPLE_TEMPLATE = ''' Example ------- .. bokeh-plot:: ../%(path)s :source-position: below ''' #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
# Copyright 2015 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import itertools from oslo_config import cfg cells_opts = [ cfg.BoolOpt('enable', default=False, help=""" Enable cell functionality When this functionality is enabled, it lets you to scale an OpenStack Compute cloud in a more distributed fashion without having to use complicated technologies like database and message queue clustering. Cells are configured as a tree. The top-level cell should have a host that runs a nova-api service, but no nova-compute services. Each child cell should run all of the typical nova-* services in a regular Compute cloud except for nova-api. You can think of cells as a normal Compute deployment in that each cell has its own database server and message queue broker. Possible values: * True: Enables the feature * False: Disables the feature Services which consume this: * nova-api * nova-cells * nova-compute Related options: * name: A unique cell name must be given when this functionality is enabled. * cell_type: Cell type should be defined for all cells. """), cfg.StrOpt('topic', default='cells', help=""" Topic This is the message queue topic that cells nodes listen on. It is used when the cells service is started up to configure the queue, and whenever an RPC call to the scheduler is made. Possible values: * cells: This is the recommended and the default value. Services which consume this: * nova-cells Related options: * None """), cfg.StrOpt('manager', default='nova.cells.manager.CellsManager', help=""" DEPRECATED: Manager for cells The nova-cells manager class. This class defines RPC methods that the local cell may call. This class is NOT used for messages coming from other cells. That communication is driver-specific. Communication to other cells happens via the nova.cells.messaging module. The MessageRunner from that module will handle routing the message to the correct cell via the communication driver. Most methods below create 'targeted' (where we want to route a message to a specific cell) or 'broadcast' (where we want a message to go to multiple cells) messages. Scheduling requests get passed to the scheduler class. Possible values: * 'nova.cells.manager.CellsManager' is the only possible value for this option as of the Mitaka release Services which consume this: * nova-cells Related options: * None """, deprecated_for_removal=True ), cfg.StrOpt('name', default='nova', help=""" Name of the current cell This value must be unique for each cell. Name of a cell is used as its id, leaving this option unset or setting the same name for two or more cells may cause unexpected behaviour. Possible values: * Unique name string Services which consume this: * nova-cells Related options: * enabled: This option is meaningful only when cells service is enabled """), cfg.ListOpt('capabilities', default=['hypervisor=xenserver;kvm', 'os=linux;windows'], help=""" Cell capabilities List of arbitrary key=value pairs defining capabilities of the current cell to be sent to the parent cells. These capabilities are intended to be used in cells scheduler filters/weighers. Possible values: * key=value pairs list for example; ``hypervisor=xenserver;kvm,os=linux;windows`` Services which consume this: * nova-cells Related options: * None """), cfg.IntOpt('call_timeout', default=60, help=""" Call timeout Cell messaging module waits for response(s) to be put into the eventlet queue. This option defines the seconds waited for response from a call to a cell. Possible values: * Time in seconds. Services which consume this: * nova-cells Related options: * None """), cfg.FloatOpt('reserve_percent', default=10.0, help=""" Reserve percentage Percentage of cell capacity to hold in reserve, so the minimum amount of free resource is considered to be; min_free = total * (reserve_percent / 100.0) This option affects both memory and disk utilization. The primary purpose of this reserve is to ensure some space is available for users who want to resize their instance to be larger. Note that currently once the capacity expands into this reserve space this option is ignored. Possible values: * Float percentage value Services which consume this: * nova-cells Related options: * None """), cfg.StrOpt('cell_type', default='compute', choices=('api', 'compute'), help=""" Type of cell When cells feature is enabled the hosts in the OpenStack Compute cloud are partitioned into groups. Cells are configured as a tree. The top-level cell's cell_type must be set to ``api``. All other cells are defined as a ``compute cell`` by default. Possible values: * api: Cell type of top-level cell. * compute: Cell type of all child cells. (Default) Services which consume this: * nova-cells Related options: * compute_api_class: This option must be set to cells api driver for the top-level cell (nova.compute.cells_api.ComputeCellsAPI) * quota_driver: Disable quota checking for the child cells. (nova.quota.NoopQuotaDriver) """), cfg.IntOpt("mute_child_interval", default=300, help=""" Mute child interval Number of seconds after which a lack of capability and capacity update the child cell is to be treated as a mute cell. Then the child cell will be weighed as recommend highly that it be skipped. Possible values: * Time in seconds. Services which consume this: * nova-cells Related options: * None """), cfg.IntOpt('bandwidth_update_interval', default=600, help=""" Bandwidth update interval Seconds between bandwidth usage cache updates for cells. Possible values: * Time in seconds. Services which consume this: * nova-compute Related options: * None """), cfg.IntOpt('instance_update_sync_database_limit', default=100, help=""" Instance update sync database limit Number of instances to pull from the database at one time for a sync. If there are more instances to update the results will be paged through. Possible values: * Number of instances. Services which consume this: * nova-cells Related options: * None """), ] mute_weigher_opts = [ cfg.FloatOpt('mute_weight_multiplier', default=-10000.0, help=""" Mute weight multiplier Multiplier used to weigh mute children. Mute children cells are recommended to be skipped so their weight is multiplied by this negative value. Possible values: * Negative numeric number Services which consume this: * nova-cells Related options: * None """), ] ram_weigher_opts = [ cfg.FloatOpt('ram_weight_multiplier', default=10.0, help=""" Ram weight multiplier Multiplier used for weighing ram. Negative numbers indicate that Compute should stack VMs on one host instead of spreading out new VMs to more hosts in the cell. Possible values: * Numeric multiplier Services which consume this: * nova-cells Related options: * None """), ] weigher_opts = [ cfg.FloatOpt('offset_weight_multiplier', default=1.0, help=""" Offset weight multiplier Multiplier used to weigh offset weigher. Cells with higher weight_offsets in the DB will be preferred. The weight_offset is a property of a cell stored in the database. It can be used by a deployer to have scheduling decisions favor or disfavor cells based on the setting. Possible values: * Numeric multiplier Services which consume this: * nova-cells Related options: * None """), ] cell_manager_opts = [ cfg.StrOpt('driver', default='nova.cells.rpc_driver.CellsRPCDriver', help=""" Cells communication driver Driver for cell<->cell communication via RPC. This is used to setup the RPC consumers as well as to send a message to another cell. 'nova.cells.rpc_driver.CellsRPCDriver' starts up 2 separate servers for handling inter-cell communication via RPC. Possible values: * 'nova.cells.rpc_driver.CellsRPCDriver' is the default driver * Otherwise it should be the full Python path to the class to be used Services which consume this: * nova-cells Related options: * None """), cfg.IntOpt("instance_updated_at_threshold", default=3600, help=""" Instance updated at threshold Number of seconds after an instance was updated or deleted to continue to update cells. This option lets cells manager to only attempt to sync instances that have been updated recently. i.e., a threshold of 3600 means to only update instances that have modified in the last hour. Possible values: * Threshold in seconds Services which consume this: * nova-cells Related options: * This value is used with the ``instance_update_num_instances`` value in a periodic task run. """), cfg.IntOpt("instance_update_num_instances", default=1, help=""" Instance update num instances On every run of the periodic task, nova cells manager will attempt to sync instance_updated_at_threshold number of instances. When the manager gets the list of instances, it shuffles them so that multiple nova-cells services do not attempt to sync the same instances in lockstep. Possible values: * Positive integer number Services which consume this: * nova-cells Related options: * This value is used with the ``instance_updated_at_threshold`` value in a periodic task run. """) ] cell_messaging_opts = [ cfg.IntOpt('max_hop_count', default=10, help=""" Maximum hop count When processing a targeted message, if the local cell is not the target, a route is defined between neighbouring cells. And the message is processed across the whole routing path. This option defines the maximum hop counts until reaching the target. Possible values: * Positive integer value Services which consume this: * nova-cells Related options: * None """), cfg.StrOpt('scheduler', default='nova.cells.scheduler.CellsScheduler', help=""" Cells scheduler The class of the driver used by the cells scheduler. This should be the full Python path to the class to be used. If nothing is specified in this option, the CellsScheduler is used. Possible values: * 'nova.cells.scheduler.CellsScheduler' is the default option * Otherwise it should be the full Python path to the class to be used Services which consume this: * nova-cells Related options: * None """) ] cell_rpc_driver_opts = [ cfg.StrOpt('rpc_driver_queue_base', default='cells.intercell', help=""" RPC driver queue base When sending a message to another cell by JSON-ifying the message and making an RPC cast to 'process_message', a base queue is used. This option defines the base queue name to be used when communicating between cells. Various topics by message type will be appended to this. Possible values: * The base queue name to be used when communicating between cells. Services which consume this: * nova-cells Related options: * None """) ] cell_scheduler_opts = [ cfg.ListOpt('scheduler_filter_classes', default=['nova.cells.filters.all_filters'], help=""" Scheduler filter classes Filter classes the cells scheduler should use. An entry of "nova.cells.filters.all_filters" maps to all cells filters included with nova. As of the Mitaka release the following filter classes are available: Different cell filter: A scheduler hint of 'different_cell' with a value of a full cell name may be specified to route a build away from a particular cell. Image properties filter: Image metadata named 'hypervisor_version_requires' with a version specification may be specified to ensure the build goes to a cell which has hypervisors of the required version. If either the version requirement on the image or the hypervisor capability of the cell is not present, this filter returns without filtering out the cells. Target cell filter: A scheduler hint of 'target_cell' with a value of a full cell name may be specified to route a build to a particular cell. No error handling is done as there's no way to know whether the full path is a valid. As an admin user, you can also add a filter that directs builds to a particular cell. Possible values: * 'nova.cells.filters.all_filters' is the default option * Otherwise it should be the full Python path to the class to be used Services which consume this: * nova-cells Related options: * None """), cfg.ListOpt('scheduler_weight_classes', default=['nova.cells.weights.all_weighers'], help=""" Scheduler weight classes Weigher classes the cells scheduler should use. An entry of "nova.cells.weights.all_weighers" maps to all cell weighers included with nova. As of the Mitaka release the following weight classes are available: mute_child: Downgrades the likelihood of child cells being chosen for scheduling requests, which haven't sent capacity or capability updates in a while. Options include mute_weight_multiplier (multiplier for mute children; value should be negative). ram_by_instance_type: Select cells with the most RAM capacity for the instance type being requested. Because higher weights win, Compute returns the number of available units for the instance type requested. The ram_weight_multiplier option defaults to 10.0 that adds to the weight by a factor of 10. Use a negative number to stack VMs on one host instead of spreading out new VMs to more hosts in the cell. weight_offset: Allows modifying the database to weight a particular cell. The highest weight will be the first cell to be scheduled for launching an instance. When the weight_offset of a cell is set to 0, it is unlikely to be picked but it could be picked if other cells have a lower weight, like if they're full. And when the weight_offset is set to a very high value (for example, '999999999999999'), it is likely to be picked if another cell do not have a higher weight. Possible values: * 'nova.cells.weights.all_weighers' is the default option * Otherwise it should be the full Python path to the class to be used Services which consume this: * nova-cells Related options: * None """), cfg.IntOpt('scheduler_retries', default=10, help=""" Scheduler retries How many retries when no cells are available. Specifies how many times the scheduler tries to launch a new instance when no cells are available. Possible values: * Positive integer value Services which consume this: * nova-cells Related options: * This value is used with the ``scheduler_retry_delay`` value while retrying to find a suitable cell. """), cfg.IntOpt('scheduler_retry_delay', default=2, help=""" Scheduler retry delay Specifies the delay (in seconds) between scheduling retries when no cell can be found to place the new instance on. When the instance could not be scheduled to a cell after ``scheduler_retries`` in combination with ``scheduler_retry_delay``, then the scheduling of the instance failed. Possible values: * Time in seconds. Services which consume this: * nova-cells Related options: * This value is used with the ``scheduler_retries`` value while retrying to find a suitable cell. """) ] cell_state_manager_opts = [ cfg.IntOpt('db_check_interval', default=60, help=""" DB check interval Cell state manager updates cell status for all cells from the DB only after this particular interval time is passed. Otherwise cached status are used. If this value is 0 or negative all cell status are updated from the DB whenever a state is needed. Possible values: * Interval time, in seconds. Services which consume this: * nova-cells Related options: * None """), cfg.StrOpt('cells_config', help=""" Optional cells configuration Configuration file from which to read cells configuration. If given, overrides reading cells from the database. Cells store all inter-cell communication data, including user names and passwords, in the database. Because the cells data is not updated very frequently, use this option to specify a JSON file to store cells data. With this configuration, the database is no longer consulted when reloading the cells data. The file must have columns present in the Cell model (excluding common database fields and the id column). You must specify the queue connection information through a transport_url field, instead of username, password, and so on. The transport_url has the following form: rabbit://USERNAME:PASSWORD@HOSTNAME:PORT/VIRTUAL_HOST Possible values: The scheme can be either qpid or rabbit, the following sample shows this optional configuration: { "parent": { "name": "parent", "api_url": "http://api.example.com:8774", "transport_url": "rabbit://rabbit.example.com", "weight_offset": 0.0, "weight_scale": 1.0, "is_parent": true }, "cell1": { "name": "cell1", "api_url": "http://api.example.com:8774", "transport_url": "rabbit://rabbit1.example.com", "weight_offset": 0.0, "weight_scale": 1.0, "is_parent": false }, "cell2": { "name": "cell2", "api_url": "http://api.example.com:8774", "transport_url": "rabbit://rabbit2.example.com", "weight_offset": 0.0, "weight_scale": 1.0, "is_parent": false } } Services which consume this: * nova-cells Related options: * None """) ] ALL_CELLS_OPTS = list(itertools.chain( cells_opts, mute_weigher_opts, ram_weigher_opts, weigher_opts, cell_manager_opts, cell_messaging_opts, cell_rpc_driver_opts, cell_scheduler_opts, cell_state_manager_opts )) def register_opts(conf): conf.register_opts(ALL_CELLS_OPTS, group="cells") def list_opts(): return {'cells': ALL_CELLS_OPTS}
# Copyright 2013-2016 DataStax, 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. try: import unittest2 as unittest except ImportError: import unittest # noqa import mock import logging from cassandra.cqlengine.connection import get_session, get_cluster from cassandra.cqlengine import CQLEngineException from cassandra.cqlengine import management from cassandra.cqlengine.management import _get_table_metadata, sync_table, drop_table, sync_type from cassandra.cqlengine.models import Model from cassandra.cqlengine import columns from tests.integration import PROTOCOL_VERSION, greaterthancass20, MockLoggingHandler, CASSANDRA_VERSION from tests.integration.cqlengine.base import BaseCassEngTestCase from tests.integration.cqlengine.query.test_queryset import TestModel from cassandra.cqlengine.usertype import UserType from tests.integration.cqlengine import DEFAULT_KEYSPACE class KeyspaceManagementTest(BaseCassEngTestCase): def test_create_drop_succeeeds(self): cluster = get_cluster() keyspace_ss = 'test_ks_ss' self.assertNotIn(keyspace_ss, cluster.metadata.keyspaces) management.create_keyspace_simple(keyspace_ss, 2) self.assertIn(keyspace_ss, cluster.metadata.keyspaces) management.drop_keyspace(keyspace_ss) self.assertNotIn(keyspace_ss, cluster.metadata.keyspaces) keyspace_nts = 'test_ks_nts' self.assertNotIn(keyspace_nts, cluster.metadata.keyspaces) management.create_keyspace_network_topology(keyspace_nts, {'dc1': 1}) self.assertIn(keyspace_nts, cluster.metadata.keyspaces) management.drop_keyspace(keyspace_nts) self.assertNotIn(keyspace_nts, cluster.metadata.keyspaces) class DropTableTest(BaseCassEngTestCase): def test_multiple_deletes_dont_fail(self): sync_table(TestModel) drop_table(TestModel) drop_table(TestModel) class LowercaseKeyModel(Model): first_key = columns.Integer(primary_key=True) second_key = columns.Integer(primary_key=True) some_data = columns.Text() class CapitalizedKeyModel(Model): firstKey = columns.Integer(primary_key=True) secondKey = columns.Integer(primary_key=True) someData = columns.Text() class PrimaryKeysOnlyModel(Model): __table_name__ = "primary_keys_only" __options__ = {'compaction': {'class': 'LeveledCompactionStrategy'}} first_key = columns.Integer(primary_key=True) second_key = columns.Integer(primary_key=True) class PrimaryKeysModelChanged(Model): __table_name__ = "primary_keys_only" __options__ = {'compaction': {'class': 'LeveledCompactionStrategy'}} new_first_key = columns.Integer(primary_key=True) second_key = columns.Integer(primary_key=True) class PrimaryKeysModelTypeChanged(Model): __table_name__ = "primary_keys_only" __options__ = {'compaction': {'class': 'LeveledCompactionStrategy'}} first_key = columns.Float(primary_key=True) second_key = columns.Integer(primary_key=True) class PrimaryKeysRemovedPk(Model): __table_name__ = "primary_keys_only" __options__ = {'compaction': {'class': 'LeveledCompactionStrategy'}} second_key = columns.Integer(primary_key=True) class PrimaryKeysAddedClusteringKey(Model): __table_name__ = "primary_keys_only" __options__ = {'compaction': {'class': 'LeveledCompactionStrategy'}} new_first_key = columns.Float(primary_key=True) second_key = columns.Integer(primary_key=True) class CapitalizedKeyTest(BaseCassEngTestCase): def test_table_definition(self): """ Tests that creating a table with capitalized column names succeeds """ sync_table(LowercaseKeyModel) sync_table(CapitalizedKeyModel) drop_table(LowercaseKeyModel) drop_table(CapitalizedKeyModel) class FirstModel(Model): __table_name__ = 'first_model' first_key = columns.UUID(primary_key=True) second_key = columns.UUID() third_key = columns.Text() class SecondModel(Model): __table_name__ = 'first_model' first_key = columns.UUID(primary_key=True) second_key = columns.UUID() third_key = columns.Text() fourth_key = columns.Text() class ThirdModel(Model): __table_name__ = 'first_model' first_key = columns.UUID(primary_key=True) second_key = columns.UUID() third_key = columns.Text() # removed fourth key, but it should stay in the DB blah = columns.Map(columns.Text, columns.Text) class FourthModel(Model): __table_name__ = 'first_model' first_key = columns.UUID(primary_key=True) second_key = columns.UUID() third_key = columns.Text() # renamed model field, but map to existing column renamed = columns.Map(columns.Text, columns.Text, db_field='blah') class AddColumnTest(BaseCassEngTestCase): def setUp(self): drop_table(FirstModel) def test_add_column(self): sync_table(FirstModel) meta_columns = _get_table_metadata(FirstModel).columns self.assertEqual(set(meta_columns), set(FirstModel._columns)) sync_table(SecondModel) meta_columns = _get_table_metadata(FirstModel).columns self.assertEqual(set(meta_columns), set(SecondModel._columns)) sync_table(ThirdModel) meta_columns = _get_table_metadata(FirstModel).columns self.assertEqual(len(meta_columns), 5) self.assertEqual(len(ThirdModel._columns), 4) self.assertIn('fourth_key', meta_columns) self.assertNotIn('fourth_key', ThirdModel._columns) self.assertIn('blah', ThirdModel._columns) self.assertIn('blah', meta_columns) sync_table(FourthModel) meta_columns = _get_table_metadata(FirstModel).columns self.assertEqual(len(meta_columns), 5) self.assertEqual(len(ThirdModel._columns), 4) self.assertIn('fourth_key', meta_columns) self.assertNotIn('fourth_key', FourthModel._columns) self.assertIn('renamed', FourthModel._columns) self.assertNotIn('renamed', meta_columns) self.assertIn('blah', meta_columns) class ModelWithTableProperties(Model): __options__ = {'bloom_filter_fp_chance': '0.76328', 'comment': 'TxfguvBdzwROQALmQBOziRMbkqVGFjqcJfVhwGR', 'gc_grace_seconds': '2063', 'read_repair_chance': '0.17985', 'dclocal_read_repair_chance': '0.50811'} key = columns.UUID(primary_key=True) class TablePropertiesTests(BaseCassEngTestCase): def setUp(self): drop_table(ModelWithTableProperties) def test_set_table_properties(self): sync_table(ModelWithTableProperties) expected = {'bloom_filter_fp_chance': 0.76328, 'comment': 'TxfguvBdzwROQALmQBOziRMbkqVGFjqcJfVhwGR', 'gc_grace_seconds': 2063, 'read_repair_chance': 0.17985, # For some reason 'dclocal_read_repair_chance' in CQL is called # just 'local_read_repair_chance' in the schema table. # Source: https://issues.apache.org/jira/browse/CASSANDRA-6717 # TODO: due to a bug in the native driver i'm not seeing the local read repair chance show up # 'local_read_repair_chance': 0.50811, } options = management._get_table_metadata(ModelWithTableProperties).options self.assertEqual(dict([(k, options.get(k)) for k in expected.keys()]), expected) def test_table_property_update(self): ModelWithTableProperties.__options__['bloom_filter_fp_chance'] = 0.66778 ModelWithTableProperties.__options__['comment'] = 'xirAkRWZVVvsmzRvXamiEcQkshkUIDINVJZgLYSdnGHweiBrAiJdLJkVohdRy' ModelWithTableProperties.__options__['gc_grace_seconds'] = 96362 ModelWithTableProperties.__options__['read_repair_chance'] = 0.2989 ModelWithTableProperties.__options__['dclocal_read_repair_chance'] = 0.12732 sync_table(ModelWithTableProperties) table_options = management._get_table_metadata(ModelWithTableProperties).options self.assertDictContainsSubset(ModelWithTableProperties.__options__, table_options) def test_bogus_option_update(self): sync_table(ModelWithTableProperties) option = 'no way will this ever be an option' try: ModelWithTableProperties.__options__[option] = 'what was I thinking?' self.assertRaisesRegexp(KeyError, "Invalid table option.*%s.*" % option, sync_table, ModelWithTableProperties) finally: ModelWithTableProperties.__options__.pop(option, None) class SyncTableTests(BaseCassEngTestCase): def setUp(self): drop_table(PrimaryKeysOnlyModel) def test_sync_table_works_with_primary_keys_only_tables(self): sync_table(PrimaryKeysOnlyModel) # blows up with DoesNotExist if table does not exist table_meta = management._get_table_metadata(PrimaryKeysOnlyModel) self.assertIn('LeveledCompactionStrategy', table_meta.as_cql_query()) PrimaryKeysOnlyModel.__options__['compaction']['class'] = 'SizeTieredCompactionStrategy' sync_table(PrimaryKeysOnlyModel) table_meta = management._get_table_metadata(PrimaryKeysOnlyModel) self.assertIn('SizeTieredCompactionStrategy', table_meta.as_cql_query()) def test_primary_key_validation(self): """ Test to ensure that changes to primary keys throw CQLEngineExceptions @since 3.2 @jira_ticket PYTHON-532 @expected_result Attempts to modify primary keys throw an exception @test_category object_mapper """ sync_table(PrimaryKeysOnlyModel) self.assertRaises(CQLEngineException, sync_table, PrimaryKeysModelChanged) self.assertRaises(CQLEngineException, sync_table, PrimaryKeysAddedClusteringKey) self.assertRaises(CQLEngineException, sync_table, PrimaryKeysRemovedPk) class IndexModel(Model): __table_name__ = 'index_model' first_key = columns.UUID(primary_key=True) second_key = columns.Text(index=True) class IndexCaseSensitiveModel(Model): __table_name__ = 'IndexModel' __table_name_case_sensitive__ = True first_key = columns.UUID(primary_key=True) second_key = columns.Text(index=True) class BaseInconsistent(Model): __table_name__ = 'inconsistent' first_key = columns.UUID(primary_key=True) second_key = columns.Integer(index=True) third_key = columns.Integer(index=True) class ChangedInconsistent(Model): __table_name__ = 'inconsistent' __table_name_case_sensitive__ = True first_key = columns.UUID(primary_key=True) second_key = columns.Text(index=True) class BaseInconsistentType(UserType): __type_name__ = 'type_inconsistent' age = columns.Integer() name = columns.Text() class ChangedInconsistentType(UserType): __type_name__ = 'type_inconsistent' age = columns.Integer() name = columns.Integer() class InconsistentTable(BaseCassEngTestCase): def setUp(self): drop_table(IndexModel) def test_sync_warnings(self): """ Test to insure when inconsistent changes are made to a table, or type as part of a sync call that the proper logging messages are surfaced @since 3.2 @jira_ticket PYTHON-260 @expected_result warnings are logged @test_category object_mapper """ mock_handler = MockLoggingHandler() logger = logging.getLogger(management.__name__) logger.addHandler(mock_handler) sync_table(BaseInconsistent) sync_table(ChangedInconsistent) self.assertTrue('differing from the model type' in mock_handler.messages.get('warning')[0]) if CASSANDRA_VERSION >= '2.1': sync_type(DEFAULT_KEYSPACE, BaseInconsistentType) mock_handler.reset() sync_type(DEFAULT_KEYSPACE, ChangedInconsistentType) self.assertTrue('differing from the model user type' in mock_handler.messages.get('warning')[0]) logger.removeHandler(mock_handler) class TestIndexSetModel(Model): partition = columns.UUID(primary_key=True) int_set = columns.Set(columns.Integer, index=True) int_list = columns.List(columns.Integer, index=True) text_map = columns.Map(columns.Text, columns.DateTime, index=True) mixed_tuple = columns.Tuple(columns.Text, columns.Integer, columns.Text, index=True) class IndexTests(BaseCassEngTestCase): def setUp(self): drop_table(IndexModel) drop_table(IndexCaseSensitiveModel) def test_sync_index(self): """ Tests the default table creation, and ensures the table_name is created and surfaced correctly in the table metadata @since 3.1 @jira_ticket PYTHON-337 @expected_result table_name is lower case @test_category object_mapper """ sync_table(IndexModel) table_meta = management._get_table_metadata(IndexModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'second_key')) # index already exists sync_table(IndexModel) table_meta = management._get_table_metadata(IndexModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'second_key')) def test_sync_index_case_sensitive(self): """ Tests the default table creation, and ensures the table_name is created correctly and surfaced correctly in table metadata @since 3.1 @jira_ticket PYTHON-337 @expected_result table_name is lower case @test_category object_mapper """ sync_table(IndexCaseSensitiveModel) table_meta = management._get_table_metadata(IndexCaseSensitiveModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'second_key')) # index already exists sync_table(IndexCaseSensitiveModel) table_meta = management._get_table_metadata(IndexCaseSensitiveModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'second_key')) @greaterthancass20 def test_sync_indexed_set(self): """ Tests that models that have container types with indices can be synced. @since 3.2 @jira_ticket PYTHON-533 @expected_result table_sync should complete without a server error. @test_category object_mapper """ sync_table(TestIndexSetModel) table_meta = management._get_table_metadata(TestIndexSetModel) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'int_set')) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'int_list')) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'text_map')) self.assertIsNotNone(management._get_index_name_by_column(table_meta, 'mixed_tuple')) class NonModelFailureTest(BaseCassEngTestCase): class FakeModel(object): pass def test_failure(self): with self.assertRaises(CQLEngineException): sync_table(self.FakeModel) class StaticColumnTests(BaseCassEngTestCase): def test_static_columns(self): if PROTOCOL_VERSION < 2: raise unittest.SkipTest("Native protocol 2+ required, currently using: {0}".format(PROTOCOL_VERSION)) class StaticModel(Model): id = columns.Integer(primary_key=True) c = columns.Integer(primary_key=True) name = columns.Text(static=True) drop_table(StaticModel) session = get_session() with mock.patch.object(session, "execute", wraps=session.execute) as m: sync_table(StaticModel) self.assertGreater(m.call_count, 0) statement = m.call_args[0][0].query_string self.assertIn('"name" text static', statement) # if we sync again, we should not apply an alter w/ a static sync_table(StaticModel) with mock.patch.object(session, "execute", wraps=session.execute) as m2: sync_table(StaticModel) self.assertEqual(len(m2.call_args_list), 0)
import urllib.request from bs4 import BeautifulSoup from time import sleep, time import pickle import queue import threading import math HYPER_EXPANSION_LIMIT = 2 # How many levels of links is it allowed to follow HYPER_DEFAULT_LINK = "https://en.wikipedia.org/wiki/Vitamin_A" HYPER_DEFAULT_SEARCH = "Vitamin A" HYPER_DEFAULT_THREAD_TIMEOUT = 100 alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_=+{}[]'\\./,<>?:\";'1234567890 " status = "" parsedLinks = [] parsedLinksCount = 0 q = queue.Queue threads = [] threads2 = [] times = [] currentThreadsActive = 0 def getGeneratorLen(gen): count = 0 for i in gen: count += 1 return count def find_all(a_str, sub): start = 0 while True: start = a_str.find(sub, start) if start == -1: return yield start start += len(sub) # use start += 1 to find overlapping matches def getNextStringIndexFromIndex(string, searchstring, index): for i in range(index, len(string)): # print("[DEBUG] Iterating " + str(i) + "/" + str(len(string))) if str(string[i]) == str(searchstring): return i return -1 def getMainInformation(text, searchString): final = "" if searchString not in text: return 0 else: for string in searchString.split(" "): position = 1 indexies = find_all(text, string) for index in indexies: # print("[DEBUG : MAIN INFO] Interating through index " + str(position) + "/" + str(getGeneratorLen(indexies))) sentanceEnd = getNextStringIndexFromIndex(text, ".", index) final += text[index:sentanceEnd] final += "\n" position += 1 return final def summarise(link, word): word = str(word.upper()) print("Parsing " + link) try: with urllib.request.urlopen(link) as source: # Parse Wikipedia Page http = source.read() soup = BeautifulSoup(http, 'html.parser') except ValueError: # print(link + " is not a valid link!") return -1 # Inform user # print("Parsed " + soup.title.string) # print("Getting paragraph text...") paragraph = soup.p.getText().upper() # print("Retrived text") # print("Retriving important information...") if word not in paragraph: # print("Error, search string " + word + " has no occurance, trying non-plural form") if word not in paragraph: # print("Non-Plural valid") final = getMainInformation(paragraph, word[:-1]) return final else: # print("Plural invalid") final = 0 else: final = getMainInformation(paragraph, word) if (final != 0): return final def getWebsiteExists(link): try: urllib.request.urlopen(link) except: # print(link + " is not a valid link!") return -1 return 0 parsedInformation = {} def getLinkInfo(aElement, betweenTag, word): global currentThreadsActive global status startTime = time() if aElement.string != "None": try: if len(betweenTag.split(" ")) > 1 or word == betweenTag: return else: parseLink = aElement.get("href") if str(parseLink) == "None": # print("Passing due to missing href") return if parseLink[0:6] == "/wiki/": parseLink = "https://en.wikipedia.org" + parseLink # print("Link not formatted correctly, correcting to " + parseLink) if ( "File:" in parseLink or "Main_Page" in parseLink or parseLink == "https://wikimediafoundation.org/"): # print("Continuing due to file or main page") return if any(parseLink in str(s) for s in parsedLinks): # print("Passing due to already parsed " + betweenTag) return parsedLinks.append(parseLink) if getWebsiteExists(parseLink) == -1: return else: parsedInformation[betweenTag.upper()] = summarise(parseLink, betweenTag) endtime = time() timeSpent = math.floor((endtime - startTime) * currentThreadsActive - 1) times.append(timeSpent) if len(times) > 10: del times[0] totalTimeSpent = 0 for t in times: totalTimeSpent += t averageTimeSpent = math.floor(totalTimeSpent / len(times)) status = str(math.floor(averageTimeSpent / 60)) + "m Remaining" currentThreadsActive -= 1 del threads[threads.find(threading.current_thread())] except AttributeError: return else: return def readLinks(link, word): global threads global currentThreadsActive print("Parsing links to level " + str(HYPER_EXPANSION_LIMIT) + "...") checkedLinks = 0 with urllib.request.urlopen(link) as source: # Parse Wikipedia Page HTTP = source.read() SOUP = BeautifulSoup(HTTP, 'html.parser') threadtimes = [] linkCount = len(SOUP.find_all("a")) for aElement in SOUP.find_all("a"): print("\n") print("Creating thread " + str(checkedLinks) + "/" + str(linkCount)) betweenTag = aElement.getText() checkedLinks += 1 threads.append(threading.Thread(target=getLinkInfo, args=(aElement, betweenTag, word))) currentThreadsActive += 1 print("Starting Threads") for thread in threads: thread.start() threadtimes.append(math.floor(time())) print("Waiting for thread completion") sleep(1) for i in range(0, len(threads) - 1): threads[i].join() print("Parsed " + str(parsedLinksCount) + " links, check " + str(checkedLinks)) sleep(3) # print(parsedInformation) pickle.dump(parsedInformation, open("save.p", "wb")) def go(action): global parsedInformation readLink = False if action == "PARSE": link = input("What do you want me to parse?\n") word = input("What do you want me to learn about?\n") parsedInformation[word.upper()] = summarise(link, word) readLink = True elif action == "PARSEN": link = input("What do you want me to parse?\n") word = input("What do you want me to learn about?\n") parsedInformation[word.upper()] = summarise(link, word) elif action == "TEST": link = HYPER_DEFAULT_LINK word = HYPER_DEFAULT_SEARCH parsedInformation[word.upper()] = summarise(link, word) readLink = True elif action == "LOAD": parsedInformation = pickle.load(open("save.p", "rb")) if action == "SAVE": pickle.dump(parsedInformation, open("save.p", "wb")) if readLink: # noinspection PyUnboundLocalVariable,PyUnboundLocalVariable readLinks(link, word) def getParsedInformation(): return parsedInformation def listParsedInformation(slow=False): # print("Learnt topics:") keys = parsedInformation.keys() for key in keys: print(key) if slow: sleep(0.5) def searchParsedInformation(text): keys = parsedInformation.keys() for key in keys: if text in key or key in text: print(key) def queryParsedInformation(text): keys = parsedInformation.keys() for key in keys: try: print(parsedInformation[key]) if text in parsedInformation[key]: print("Term found in " + key) except: continue def getInformation(key): return parsedInformation[key] def filter(): global parsedInformation newList = {} keys = parsedInformation.keys() for key in keys: delete = False for letter in key: if letter not in alphabet: # print(key + " is not english") delete = True if type(parsedInformation[key]) != str: delete = True if not delete: newList[key] = parsedInformation[key] parsedInformation = newList def selfExpand(initialLink, word): global currentThreadsActive print("Expanding on " + initialLink) sleep(1) summarise(initialLink, word) with urllib.request.urlopen(initialLink) as source: # Parse Wikipedia Page HTTP = source.read() SOUP = BeautifulSoup(HTTP, 'html.parser') title = SOUP.find("div", {"id": "firstHeading"}) for aElement in SOUP.find_all("a"): betweenTag = aElement.getText() threads2.append(threading.Thread(target=getLinkInfo, args=(aElement, betweenTag, title))) currentThreadsActive += 1 sleep(1) for thread in threads2: thread.start() thread.join() print("Threads done") for aElement in SOUP.find_all("a"): if getWebsiteExists(aElement.get("href")) > 0: print("Valid link " + str(aElement.get("href")) + " found, recursing.") selfExpand(str(aElement.get("href")), aElement.getText) """ GET Gets the information from a key LIST Lists all of the keys Extra Args SLOW Prints the entries slower GO [COMMAND] Executes one of the opening commands: Test Tests the program on one of the default sites Parse Parses a specific link Load Loads the save file Save Saves to save file QUIT Exits info stream SEARCH [STRING] Searches the keys for a string QUERY [STRING] Searches keys and text bodies for a string FILTER Takes all the non-english keys out LEARN Start the background load process THREADS Lists the threads """ def takeAction(action): global threads global currentThreadsActive if action[0] == "GET": values = "" for item in action: if item != "GET": values += item values += " " values = values[:-1] try: return "Information on " + values + ":\n" + str(parsedInformation[values]) except KeyError: return "Error, no such item " + values elif action[0] == "LIST": print("Listing " + str(len(parsedInformation)) + " entries") try: if action[1] == "SLOW": if True: listParsedInformation(True) else: return else: listParsedInformation() except IndexError: listParsedInformation() elif action[0] == "GO": try: go(action[1]) except IndexError: return "Not enough arguments" elif action[0] == "QUIT": return elif action[0] == "SEARCH": try: action[2] == action[2] except IndexError: hasArgument = False else: hasArgument = True if hasArgument: searchParsedInformation(action[1]) else: try: searchParsedInformation(action[1]) except IndexError: return "Error! you must specify a search string" elif action[0] == "QUERY": try: action[2] == action[2] except IndexError: hasArgument = False else: hasArgument = True if hasArgument: queryParsedInformation(action[1]) else: try: queryParsedInformation(action[1]) except IndexError: return "Error! you must specify a query string" elif action[0] == "FILTER": filter() elif action[0] == "PRINT": return parsedInformation elif action[0] == "LEARN": threads.append(threading.Thread(target=selfExpand, args=(HYPER_DEFAULT_LINK, HYPER_DEFAULT_SEARCH))) currentThreadsActive += 1 elif action[0] == "THREADS": if (len(threads) + len(threads2) > 15): print("There are " + str(len(threads2) + len(threads)) + " threads, display? y/n") if (input("").upper() == "y"): print("First Threads") for thread in threads: print(thread) sleep(0.3) print("Level two threads") for thread in threads2: print(thread) sleep(0.3) elif action[0] == "STATUS": print(status) else: return "Error, not valid command" sleep(0.2) def main(): print(parsedInformation) print("Initiating info loop") while True: for thread in threads: if not thread.isAlive(): try: thread.start() except RuntimeError: continue action = input("What should I do?\n") action = action.upper() action = action.split(" ") print(takeAction(action)) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- # # Copyright (C)2005-2010 Edgewall Software # Copyright (C) 2005 Christopher Lenz <[email protected]> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. # # Author: Christopher Lenz <[email protected]> import errno import os import re import weakref from genshi.builder import tag from trac.config import ConfigurationError, ListOption from trac.core import Component, TracError, implements from trac.db.api import ConnectionBase, IDatabaseConnector from trac.db.util import ConnectionWrapper, IterableCursor from trac.env import ISystemInfoProvider from trac.util import get_pkginfo, getuser, lazy from trac.util.translation import _, tag_ _like_escape_re = re.compile(r'([/_%])') _glob_escape_re = re.compile(r'[*?\[]') try: import pysqlite2.dbapi2 as sqlite except ImportError: import sqlite3 as sqlite sqlite_version = sqlite.sqlite_version_info sqlite_version_string = sqlite.sqlite_version pysqlite_version = sqlite.version_info pysqlite_version_string = get_pkginfo(sqlite).get('version', '%d.%d.%s' % pysqlite_version) min_sqlite_version = (3, 0, 0) min_pysqlite_version = (2, 4, 1) # version provided by Python 2.6 class PyFormatCursor(sqlite.Cursor): def _rollback_on_error(self, function, *args, **kwargs): try: return function(self, *args, **kwargs) except sqlite.DatabaseError: self.cnx.rollback() raise def execute(self, sql, args=None): if args: sql = sql % (('?',) * len(args)) return self._rollback_on_error(sqlite.Cursor.execute, sql, args or []) def executemany(self, sql, args): if not args: return sql = sql % (('?',) * len(args[0])) return self._rollback_on_error(sqlite.Cursor.executemany, sql, args) # EagerCursor taken from the example in pysqlite's repository: # # http://code.google.com/p/pysqlite/source/browse/misc/eager.py # # Only change is to subclass it from PyFormatCursor instead of # sqlite.Cursor. class EagerCursor(PyFormatCursor): def __init__(self, con): PyFormatCursor.__init__(self, con) self.rows = [] self.pos = 0 def execute(self, *args): result = PyFormatCursor.execute(self, *args) self.rows = PyFormatCursor.fetchall(self) self.pos = 0 return result def fetchone(self): try: row = self.rows[self.pos] except IndexError: return None else: self.pos += 1 return row def fetchmany(self, num=None): if num is None: num = self.arraysize result = self.rows[self.pos:self.pos + num] self.pos += num return result def fetchall(self): result = self.rows[self.pos:] self.pos = len(self.rows) return result # Mapping from "abstract" SQL types to DB-specific types _type_map = { 'int': 'integer', 'int64': 'integer', } def _to_sql(table): sql = ["CREATE TABLE %s (" % table.name] coldefs = [] for column in table.columns: ctype = column.type.lower() ctype = _type_map.get(ctype, ctype) if column.auto_increment: ctype = "integer PRIMARY KEY" elif len(table.key) == 1 and column.name in table.key: ctype += " PRIMARY KEY" coldefs.append(" %s %s" % (column.name, ctype)) if len(table.key) > 1: coldefs.append(" UNIQUE (%s)" % ','.join(table.key)) sql.append(',\n'.join(coldefs) + '\n);') yield '\n'.join(sql) for index in table.indices: unique = 'UNIQUE' if index.unique else '' yield "CREATE %s INDEX %s_%s_idx ON %s (%s);" % (unique, table.name, '_'.join(index.columns), table.name, ','.join(index.columns)) class SQLiteConnector(Component): """Database connector for SQLite. Database URLs should be of the form: {{{ sqlite:path/to/trac.db }}} """ implements(IDatabaseConnector, ISystemInfoProvider) required = False extensions = ListOption('sqlite', 'extensions', doc="""Paths to [https://sqlite.org/loadext.html sqlite extensions]. The paths may be absolute or relative to the Trac environment. (''since 0.12'') """) memory_cnx = None def __init__(self): self.error = None # ISystemInfoProvider methods def get_system_info(self): if self.required: yield 'SQLite', sqlite_version_string yield 'pysqlite', pysqlite_version_string # IDatabaseConnector methods def get_supported_schemes(self): if sqlite_version < min_sqlite_version: self.error = _("SQLite version is %(version)s. Minimum required " "version is %(min_version)s.", version=sqlite_version_string, min_version='%d.%d.%d' % min_sqlite_version) elif pysqlite_version < min_pysqlite_version: self.error = _("Need at least PySqlite %(version)s or higher", version='%d.%d.%d' % min_pysqlite_version) elif (2, 5, 2) <= pysqlite_version < (2, 5, 5): self.error = _("PySqlite 2.5.2 - 2.5.4 break Trac, please use " "2.5.5 or higher") yield 'sqlite', -1 if self.error else 1 def get_connection(self, path, log=None, params={}): self.required = True params['extensions'] = self._extensions if path == ':memory:': if not self.memory_cnx: self.memory_cnx = SQLiteConnection(path, log, params) return self.memory_cnx else: return SQLiteConnection(path, log, params) def get_exceptions(self): return sqlite def init_db(self, path, schema=None, log=None, params={}): if path != ':memory:': # make the directory to hold the database if os.path.exists(path): raise TracError(_("Database already exists at %(path)s", path=path)) dir = os.path.dirname(path) if not os.path.exists(dir): os.makedirs(dir) if isinstance(path, unicode): # needed with 2.4.0 path = path.encode('utf-8') # this direct connect will create the database if needed cnx = sqlite.connect(path, isolation_level=None, timeout=int(params.get('timeout', 10000))) cursor = cnx.cursor() _set_journal_mode(cursor, params.get('journal_mode')) _set_synchronous(cursor, params.get('synchronous')) cnx.isolation_level = 'DEFERRED' else: cnx = self.get_connection(path, log, params) cursor = cnx.cursor() if schema is None: from trac.db_default import schema for table in schema: for stmt in self.to_sql(table): cursor.execute(stmt) cursor.close() cnx.commit() def destroy_db(self, path, log=None, params={}): if path != ':memory:': if not os.path.isabs(path): path = os.path.join(self.env.path, path) try: os.remove(path) except OSError as e: if e.errno != errno.ENOENT: raise def to_sql(self, table): return _to_sql(table) def alter_column_types(self, table, columns): """Yield SQL statements altering the type of one or more columns of a table. Type changes are specified as a `columns` dict mapping column names to `(from, to)` SQL type tuples. """ for name, (from_, to) in sorted(columns.iteritems()): if _type_map.get(to, to) != _type_map.get(from_, from_): raise NotImplementedError("Conversion from %s to %s is not " "implemented" % (from_, to)) return () def backup(self, dest_file): """Simple SQLite-specific backup of the database. @param dest_file: Destination file basename """ import shutil db_str = self.config.get('trac', 'database') try: db_str = db_str[:db_str.index('?')] except ValueError: pass db_name = os.path.join(self.env.path, db_str[7:]) shutil.copy(db_name, dest_file) if not os.path.exists(dest_file): raise TracError(_("No destination file created")) return dest_file @lazy def _extensions(self): _extensions = [] for extpath in self.extensions: if not os.path.isabs(extpath): extpath = os.path.join(self.env.path, extpath) _extensions.append(extpath) return _extensions class SQLiteConnection(ConnectionBase, ConnectionWrapper): """Connection wrapper for SQLite.""" __slots__ = ['_active_cursors', '_eager'] poolable = sqlite_version >= (3, 3, 8) and pysqlite_version >= (2, 5, 0) def __init__(self, path, log=None, params={}): self.cnx = None if path != ':memory:': if not os.access(path, os.F_OK): raise ConfigurationError(_('Database "%(path)s" not found.', path=path)) dbdir = os.path.dirname(path) if not os.access(path, os.R_OK + os.W_OK) or \ not os.access(dbdir, os.R_OK + os.W_OK): raise ConfigurationError(tag_( "The user %(user)s requires read _and_ write permissions " "to the database file %(path)s and the directory it is " "located in.", user=tag.code(getuser()), path=tag.code(path))) self._active_cursors = weakref.WeakKeyDictionary() timeout = int(params.get('timeout', 10.0)) self._eager = params.get('cursor', 'eager') == 'eager' # eager is default, can be turned off by specifying ?cursor= if isinstance(path, unicode): # needed with 2.4.0 path = path.encode('utf-8') cnx = sqlite.connect(path, detect_types=sqlite.PARSE_DECLTYPES, isolation_level=None, check_same_thread=sqlite_version < (3, 3, 1), timeout=timeout) # load extensions extensions = params.get('extensions', []) if len(extensions) > 0: cnx.enable_load_extension(True) for ext in extensions: cnx.load_extension(ext) cnx.enable_load_extension(False) cursor = cnx.cursor() _set_journal_mode(cursor, params.get('journal_mode')) _set_synchronous(cursor, params.get('synchronous')) cursor.close() cnx.isolation_level = 'DEFERRED' ConnectionWrapper.__init__(self, cnx, log) def cursor(self): cursor = self.cnx.cursor((PyFormatCursor, EagerCursor)[self._eager]) self._active_cursors[cursor] = True cursor.cnx = self return IterableCursor(cursor, self.log) def rollback(self): for cursor in self._active_cursors.keys(): cursor.close() self.cnx.rollback() def cast(self, column, type): if sqlite_version >= (3, 2, 3): return 'CAST(%s AS %s)' % (column, _type_map.get(type, type)) elif type == 'int': # hack to force older SQLite versions to convert column to an int return '1*' + column else: return column def concat(self, *args): return '||'.join(args) def drop_table(self, table): cursor = self.cursor() if sqlite_version < (3, 7, 6): # SQLite versions at least between 3.6.21 and 3.7.5 have a # buggy behavior with DROP TABLE IF EXISTS (#12298) try: cursor.execute("DROP TABLE " + self.quote(table)) except sqlite.OperationalError: # "no such table" pass else: cursor.execute("DROP TABLE IF EXISTS " + self.quote(table)) def get_column_names(self, table): cursor = self.cnx.cursor() rows = cursor.execute("PRAGMA table_info(%s)" % self.quote(table)) return [row[1] for row in rows] def get_last_id(self, cursor, table, column='id'): return cursor.lastrowid def get_table_names(self): rows = self.execute(""" SELECT name FROM sqlite_master WHERE type='table' """) return [row[0] for row in rows] def like(self): if sqlite_version >= (3, 1, 0): return "LIKE %s ESCAPE '/'" else: return 'LIKE %s' def like_escape(self, text): if sqlite_version >= (3, 1, 0): return _like_escape_re.sub(r'/\1', text) else: return text def prefix_match(self): return 'GLOB %s' def prefix_match_value(self, prefix): return _glob_escape_re.sub(lambda m: '[%s]' % m.group(0), prefix) + '*' def quote(self, identifier): return _quote(identifier) def reset_tables(self): cursor = self.cursor() table_names = self.get_table_names() for name in table_names: cursor.execute("DELETE FROM %s" % name) return table_names def update_sequence(self, cursor, table, column='id'): # SQLite handles sequence updates automagically # http://www.sqlite.org/autoinc.html pass def _quote(identifier): return "`%s`" % identifier.replace('`', '``') def _set_journal_mode(cursor, value): if not value: return value = value.upper() if value == 'OFF': raise TracError(_("PRAGMA journal_mode `%(value)s` cannot be used " "in SQLite", value=value)) cursor.execute('PRAGMA journal_mode = %s' % _quote(value)) row = cursor.fetchone() if not row: raise TracError(_("PRAGMA journal_mode isn't supported by SQLite " "%(version)s", version=sqlite_version_string)) if (row[0] or '').upper() != value: raise TracError(_("PRAGMA journal_mode `%(value)s` isn't supported " "by SQLite %(version)s", value=value, version=sqlite_version_string)) def _set_synchronous(cursor, value): if not value: return if value.isdigit(): value = str(int(value)) cursor.execute('PRAGMA synchronous = %s' % _quote(value))
import os from collections import namedtuple from collections.abc import Sequence from urllib.parse import urlparse, urlunparse import ipaddress import markdown from mkdocs import utils, theme, plugins from mkdocs.config.base import Config, ValidationError class BaseConfigOption: def __init__(self): self.warnings = [] self.default = None def is_required(self): return False def validate(self, value): return self.run_validation(value) def reset_warnings(self): self.warnings = [] def pre_validation(self, config, key_name): """ Before all options are validated, perform a pre-validation process. The pre-validation process method should be implemented by subclasses. """ def run_validation(self, value): """ Perform validation for a value. The run_validation method should be implemented by subclasses. """ return value def post_validation(self, config, key_name): """ After all options have passed validation, perform a post-validation process to do any additional changes dependant on other config values. The post-validation process method should be implemented by subclasses. """ class SubConfig(BaseConfigOption, Config): def __init__(self, *config_options): BaseConfigOption.__init__(self) Config.__init__(self, config_options) self.default = {} def validate(self, value): self.load_dict(value) return self.run_validation(value) def run_validation(self, value): Config.validate(self) return self class ConfigItems(BaseConfigOption): """ Config Items Option Validates a list of mappings that all must match the same set of options. """ def __init__(self, *config_options, **kwargs): BaseConfigOption.__init__(self) self.item_config = SubConfig(*config_options) self.required = kwargs.get('required', False) def __repr__(self): return f'{self.__class__.__name__}: {self.item_config}' def run_validation(self, value): if value is None: if self.required: raise ValidationError("Required configuration not provided.") else: return () if not isinstance(value, Sequence): raise ValidationError(f'Expected a sequence of mappings, but a ' f'{type(value)} was given.') return [self.item_config.validate(item) for item in value] class OptionallyRequired(BaseConfigOption): """ A subclass of BaseConfigOption that adds support for default values and required values. It is a base class for config options. """ def __init__(self, default=None, required=False): super().__init__() self.default = default self.required = required def is_required(self): return self.required def validate(self, value): """ Perform some initial validation. If the option is empty (None) and isn't required, leave it as such. If it is empty but has a default, use that. Finally, call the run_validation method on the subclass unless. """ if value is None: if self.default is not None: if hasattr(self.default, 'copy'): # ensure no mutable values are assigned value = self.default.copy() else: value = self.default elif not self.required: return elif self.required: raise ValidationError("Required configuration not provided.") return self.run_validation(value) class Type(OptionallyRequired): """ Type Config Option Validate the type of a config option against a given Python type. """ def __init__(self, type_, length=None, **kwargs): super().__init__(**kwargs) self._type = type_ self.length = length def run_validation(self, value): if not isinstance(value, self._type): msg = f"Expected type: {self._type} but received: {type(value)}" elif self.length is not None and len(value) != self.length: msg = ("Expected type: {0} with length {2} but received: {1} with " "length {3}").format(self._type, value, self.length, len(value)) else: return value raise ValidationError(msg) class Choice(OptionallyRequired): """ Choice Config Option Validate the config option against a strict set of values. """ def __init__(self, choices, **kwargs): super().__init__(**kwargs) try: length = len(choices) except TypeError: length = 0 if not length or isinstance(choices, str): raise ValueError(f'Expected iterable of choices, got {choices}') self.choices = choices def run_validation(self, value): if value not in self.choices: msg = f"Expected one of: {self.choices} but received: {value}" else: return value raise ValidationError(msg) class Deprecated(BaseConfigOption): """ Deprecated Config Option Raises a warning as the option is deprecated. Uses `message` for the warning. If `move_to` is set to the name of a new config option, the value is moved to the new option on pre_validation. If `option_type` is set to a ConfigOption instance, then the value is validated against that type. """ def __init__(self, moved_to=None, message='', option_type=None): super().__init__() self.default = None self.moved_to = moved_to self.message = message or ( 'The configuration option {} has been deprecated and ' 'will be removed in a future release of MkDocs.' ) self.option = option_type or BaseConfigOption() self.warnings = self.option.warnings def pre_validation(self, config, key_name): self.option.pre_validation(config, key_name) if config.get(key_name) is not None: self.warnings.append(self.message.format(key_name)) if self.moved_to is not None: if '.' not in self.moved_to: target = config target_key = self.moved_to else: move_to, target_key = self.moved_to.rsplit('.', 1) target = config for key in move_to.split('.'): target = target.setdefault(key, {}) if not isinstance(target, dict): # We can't move it for the user return target[target_key] = config.pop(key_name) def validate(self, value): return self.option.validate(value) def post_validation(self, config, key_name): self.option.post_validation(config, key_name) def reset_warnings(self): self.option.reset_warnings() self.warnings = self.option.warnings class IpAddress(OptionallyRequired): """ IpAddress Config Option Validate that an IP address is in an apprioriate format """ def run_validation(self, value): try: host, port = value.rsplit(':', 1) except Exception: raise ValidationError("Must be a string of format 'IP:PORT'") if host != 'localhost': try: # Validate and normalize IP Address host = str(ipaddress.ip_address(host)) except ValueError as e: raise ValidationError(e) try: port = int(port) except Exception: raise ValidationError(f"'{port}' is not a valid port") class Address(namedtuple('Address', 'host port')): def __str__(self): return f'{self.host}:{self.port}' return Address(host, port) def post_validation(self, config, key_name): host = config[key_name].host if key_name == 'dev_addr' and host in ['0.0.0.0', '::']: self.warnings.append( ("The use of the IP address '{}' suggests a production environment " "or the use of a proxy to connect to the MkDocs server. However, " "the MkDocs' server is intended for local development purposes only. " "Please use a third party production-ready server instead.").format(host) ) class URL(OptionallyRequired): """ URL Config Option Validate a URL by requiring a scheme is present. """ def __init__(self, default='', required=False, is_dir=False): self.is_dir = is_dir super().__init__(default, required) def pre_validation(self, config, key_name): # TODO: replace this with an error in a future release (1.3?) user_defined_keys = sum([list(x.keys()) for x in config.user_configs], []) if key_name == 'site_url' and key_name not in user_defined_keys: self.warnings.append( 'This option is now required. Set to a valid URL or ' 'an empty string to avoid an error in a future release.' ) def run_validation(self, value): if value == '': return value try: parsed_url = urlparse(value) except (AttributeError, TypeError): raise ValidationError("Unable to parse the URL.") if parsed_url.scheme: if self.is_dir and not parsed_url.path.endswith('/'): parsed_url = parsed_url._replace(path=f'{parsed_url.path}/') return urlunparse(parsed_url) raise ValidationError( "The URL isn't valid, it should include the http:// (scheme)") def post_validation(self, config, key_name): if key_name == 'site_url': if config[key_name] in ['', None] and config['use_directory_urls']: config['use_directory_urls'] = False self.warnings.append( "The 'use_directory_urls' option has been disabled because " "'site_url' contains an empty value. Either define a valid " "URL for 'site_url' or set 'use_directory_urls' to False." ) class RepoURL(URL): """ Repo URL Config Option A small extension to the URL config that sets the repo_name and edit_uri, based on the url if they haven't already been provided. """ def post_validation(self, config, key_name): repo_host = urlparse(config['repo_url']).netloc.lower() edit_uri = config.get('edit_uri') # derive repo_name from repo_url if unset if config['repo_url'] is not None and config.get('repo_name') is None: if repo_host == 'github.com': config['repo_name'] = 'GitHub' elif repo_host == 'bitbucket.org': config['repo_name'] = 'Bitbucket' elif repo_host == 'gitlab.com': config['repo_name'] = 'GitLab' else: config['repo_name'] = repo_host.split('.')[0].title() # derive edit_uri from repo_name if unset if config['repo_url'] is not None and edit_uri is None: if repo_host == 'github.com' or repo_host == 'gitlab.com': edit_uri = 'edit/master/docs/' elif repo_host == 'bitbucket.org': edit_uri = 'src/default/docs/' else: edit_uri = '' # ensure a well-formed edit_uri if edit_uri: if not edit_uri.startswith(('?', '#')) \ and not config['repo_url'].endswith('/'): config['repo_url'] += '/' if not edit_uri.endswith('/'): edit_uri += '/' config['edit_uri'] = edit_uri class FilesystemObject(Type): """ Base class for options that point to filesystem objects. """ def __init__(self, exists=False, **kwargs): super().__init__(type_=str, **kwargs) self.exists = exists self.config_dir = None def pre_validation(self, config, key_name): self.config_dir = os.path.dirname(config.config_file_path) if config.config_file_path else None def run_validation(self, value): value = super().run_validation(value) if self.config_dir and not os.path.isabs(value): value = os.path.join(self.config_dir, value) if self.exists and not self.existence_test(value): raise ValidationError(f"The path {value} isn't an existing {self.name}.") value = os.path.abspath(value) assert isinstance(value, str) return value class Dir(FilesystemObject): """ Dir Config Option Validate a path to a directory, optionally verifying that it exists. """ existence_test = staticmethod(os.path.isdir) name = 'directory' def post_validation(self, config, key_name): if config.config_file_path is None: return # Validate that the dir is not the parent dir of the config file. if os.path.dirname(config.config_file_path) == config[key_name]: raise ValidationError( ("The '{0}' should not be the parent directory of the config " "file. Use a child directory instead so that the '{0}' " "is a sibling of the config file.").format(key_name)) class File(FilesystemObject): """ File Config Option Validate a path to a file, optionally verifying that it exists. """ existence_test = staticmethod(os.path.isfile) name = 'file' class SiteDir(Dir): """ SiteDir Config Option Validates the site_dir and docs_dir directories do not contain each other. """ def post_validation(self, config, key_name): super().post_validation(config, key_name) # Validate that the docs_dir and site_dir don't contain the # other as this will lead to copying back and forth on each # and eventually make a deep nested mess. if (config['docs_dir'] + os.sep).startswith(config['site_dir'].rstrip(os.sep) + os.sep): raise ValidationError( ("The 'docs_dir' should not be within the 'site_dir' as this " "can mean the source files are overwritten by the output or " "it will be deleted if --clean is passed to mkdocs build." "(site_dir: '{}', docs_dir: '{}')" ).format(config['site_dir'], config['docs_dir'])) elif (config['site_dir'] + os.sep).startswith(config['docs_dir'].rstrip(os.sep) + os.sep): raise ValidationError( ("The 'site_dir' should not be within the 'docs_dir' as this " "leads to the build directory being copied into itself and " "duplicate nested files in the 'site_dir'." "(site_dir: '{}', docs_dir: '{}')" ).format(config['site_dir'], config['docs_dir'])) class Theme(BaseConfigOption): """ Theme Config Option Validate that the theme exists and build Theme instance. """ def __init__(self, default=None): super().__init__() self.default = default def validate(self, value): if value is None and self.default is not None: value = {'name': self.default} if isinstance(value, str): value = {'name': value} themes = utils.get_theme_names() if isinstance(value, dict): if 'name' in value: if value['name'] is None or value['name'] in themes: return value raise ValidationError( f"Unrecognised theme name: '{value['name']}'. " f"The available installed themes are: {', '.join(themes)}" ) raise ValidationError("No theme name set.") raise ValidationError(f'Invalid type "{type(value)}". Expected a string or key/value pairs.') def post_validation(self, config, key_name): theme_config = config[key_name] if not theme_config['name'] and 'custom_dir' not in theme_config: raise ValidationError("At least one of 'theme.name' or 'theme.custom_dir' must be defined.") # Ensure custom_dir is an absolute path if 'custom_dir' in theme_config and not os.path.isabs(theme_config['custom_dir']): config_dir = os.path.dirname(config.config_file_path) theme_config['custom_dir'] = os.path.join(config_dir, theme_config['custom_dir']) if 'custom_dir' in theme_config and not os.path.isdir(theme_config['custom_dir']): raise ValidationError("The path set in {name}.custom_dir ('{path}') does not exist.". format(path=theme_config['custom_dir'], name=key_name)) if 'locale' in theme_config and not isinstance(theme_config['locale'], str): raise ValidationError("'{name}.locale' must be a string.".format(name=theme_config['name'])) config[key_name] = theme.Theme(**theme_config) class Nav(OptionallyRequired): """ Nav Config Option Validate the Nav config. Automatically add all markdown files if empty. """ def __init__(self, **kwargs): super().__init__(**kwargs) self.file_match = utils.is_markdown_file def run_validation(self, value): if not isinstance(value, list): raise ValidationError(f"Expected a list, got {type(value)}") if len(value) == 0: return config_types = {type(item) for item in value} if config_types.issubset({str, dict}): return value raise ValidationError("Invalid pages config. {} {}".format( config_types, {str, dict} )) def post_validation(self, config, key_name): # TODO: remove this when `pages` config setting is fully deprecated. if key_name == 'pages' and config['pages'] is not None: if config['nav'] is None: # copy `pages` config to new 'nav' config setting config['nav'] = config['pages'] warning = ("The 'pages' configuration option has been deprecated and will " "be removed in a future release of MkDocs. Use 'nav' instead.") self.warnings.append(warning) class Private(OptionallyRequired): """ Private Config Option A config option only for internal use. Raises an error if set by the user. """ def run_validation(self, value): raise ValidationError('For internal use only.') class MarkdownExtensions(OptionallyRequired): """ Markdown Extensions Config Option A list or dict of extensions. Each list item may contain either a string or a one item dict. A string must be a valid Markdown extension name with no config options defined. The key of a dict item must be a valid Markdown extension name and the value must be a dict of config options for that extension. Extension configs are set on the private setting passed to `configkey`. The `builtins` keyword accepts a list of extensions which cannot be overriden by the user. However, builtins can be duplicated to define config options for them if desired. """ def __init__(self, builtins=None, configkey='mdx_configs', **kwargs): super().__init__(**kwargs) self.builtins = builtins or [] self.configkey = configkey self.configdata = {} def validate_ext_cfg(self, ext, cfg): if not isinstance(ext, str): raise ValidationError(f"'{ext}' is not a valid Markdown Extension name.") if not cfg: return if not isinstance(cfg, dict): raise ValidationError(f"Invalid config options for Markdown Extension '{ext}'.") self.configdata[ext] = cfg def run_validation(self, value): if not isinstance(value, (list, tuple, dict)): raise ValidationError('Invalid Markdown Extensions configuration') extensions = [] if isinstance(value, dict): for ext, cfg in value.items(): self.validate_ext_cfg(ext, cfg) extensions.append(ext) else: for item in value: if isinstance(item, dict): if len(item) > 1: raise ValidationError('Invalid Markdown Extensions configuration') ext, cfg = item.popitem() self.validate_ext_cfg(ext, cfg) extensions.append(ext) elif isinstance(item, str): extensions.append(item) else: raise ValidationError('Invalid Markdown Extensions configuration') extensions = utils.reduce_list(self.builtins + extensions) # Confirm that Markdown considers extensions to be valid try: markdown.Markdown(extensions=extensions, extension_configs=self.configdata) except Exception as e: raise ValidationError(e.args[0]) return extensions def post_validation(self, config, key_name): config[self.configkey] = self.configdata class Plugins(OptionallyRequired): """ Plugins config option. A list or dict of plugins. If a plugin defines config options those are used when initializing the plugin class. """ def __init__(self, **kwargs): super().__init__(**kwargs) self.installed_plugins = plugins.get_plugins() self.config_file_path = None def pre_validation(self, config, key_name): self.config_file_path = config.config_file_path def run_validation(self, value): if not isinstance(value, (list, tuple, dict)): raise ValidationError('Invalid Plugins configuration. Expected a list or dict.') plgins = plugins.PluginCollection() if isinstance(value, dict): for name, cfg in value.items(): plgins[name] = self.load_plugin(name, cfg) else: for item in value: if isinstance(item, dict): if len(item) > 1: raise ValidationError('Invalid Plugins configuration') name, cfg = item.popitem() item = name else: cfg = {} plgins[item] = self.load_plugin(item, cfg) return plgins def load_plugin(self, name, config): if not isinstance(name, str): raise ValidationError(f"'{name}' is not a valid plugin name.") if name not in self.installed_plugins: raise ValidationError(f'The "{name}" plugin is not installed') config = config or {} # Users may define a null (None) config if not isinstance(config, dict): raise ValidationError(f"Invalid config options for the '{name}' plugin.") Plugin = self.installed_plugins[name].load() if not issubclass(Plugin, plugins.BasePlugin): raise ValidationError('{}.{} must be a subclass of {}.{}'.format( Plugin.__module__, Plugin.__name__, plugins.BasePlugin.__module__, plugins.BasePlugin.__name__)) plugin = Plugin() errors, warnings = plugin.load_config(config, self.config_file_path) self.warnings.extend(warnings) errors_message = '\n'.join( f"Plugin '{name}' value: '{x}'. Error: {y}" for x, y in errors ) if errors_message: raise ValidationError(errors_message) return plugin
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base.page import Page class FlowRevisionList(ListResource): def __init__(self, version, sid): """ Initialize the FlowRevisionList :param Version version: Version that contains the resource :param sid: The unique string that identifies the resource :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionList """ super(FlowRevisionList, self).__init__(version) # Path Solution self._solution = {'sid': sid, } self._uri = '/Flows/{sid}/Revisions'.format(**self._solution) def stream(self, limit=None, page_size=None): """ Streams FlowRevisionInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param int limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param int page_size: Number of records to fetch per request, when not set will use the default value of 50 records. If no page_size is defined but a limit is defined, stream() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results :rtype: list[twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance] """ limits = self._version.read_limits(limit, page_size) page = self.page(page_size=limits['page_size'], ) return self._version.stream(page, limits['limit']) def list(self, limit=None, page_size=None): """ Lists FlowRevisionInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param int limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param int page_size: Number of records to fetch per request, when not set will use the default value of 50 records. If no page_size is defined but a limit is defined, list() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results :rtype: list[twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance] """ return list(self.stream(limit=limit, page_size=page_size, )) def page(self, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of FlowRevisionInstance records from the API. Request is executed immediately :param str page_token: PageToken provided by the API :param int page_number: Page Number, this value is simply for client state :param int page_size: Number of records to return, defaults to 50 :returns: Page of FlowRevisionInstance :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage """ data = values.of({'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) response = self._version.page(method='GET', uri=self._uri, params=data, ) return FlowRevisionPage(self._version, response, self._solution) def get_page(self, target_url): """ Retrieve a specific page of FlowRevisionInstance records from the API. Request is executed immediately :param str target_url: API-generated URL for the requested results page :returns: Page of FlowRevisionInstance :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage """ response = self._version.domain.twilio.request( 'GET', target_url, ) return FlowRevisionPage(self._version, response, self._solution) def get(self, revision): """ Constructs a FlowRevisionContext :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision` :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext """ return FlowRevisionContext(self._version, sid=self._solution['sid'], revision=revision, ) def __call__(self, revision): """ Constructs a FlowRevisionContext :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision` :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext """ return FlowRevisionContext(self._version, sid=self._solution['sid'], revision=revision, ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Studio.V2.FlowRevisionList>' class FlowRevisionPage(Page): def __init__(self, version, response, solution): """ Initialize the FlowRevisionPage :param Version version: Version that contains the resource :param Response response: Response from the API :param sid: The unique string that identifies the resource :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionPage """ super(FlowRevisionPage, self).__init__(version, response) # Path Solution self._solution = solution def get_instance(self, payload): """ Build an instance of FlowRevisionInstance :param dict payload: Payload response from the API :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance """ return FlowRevisionInstance(self._version, payload, sid=self._solution['sid'], ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Studio.V2.FlowRevisionPage>' class FlowRevisionContext(InstanceContext): def __init__(self, version, sid, revision): """ Initialize the FlowRevisionContext :param Version version: Version that contains the resource :param sid: The SID that identifies the resource to fetch :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision` :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext """ super(FlowRevisionContext, self).__init__(version) # Path Solution self._solution = {'sid': sid, 'revision': revision, } self._uri = '/Flows/{sid}/Revisions/{revision}'.format(**self._solution) def fetch(self): """ Fetch the FlowRevisionInstance :returns: The fetched FlowRevisionInstance :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance """ payload = self._version.fetch(method='GET', uri=self._uri, ) return FlowRevisionInstance( self._version, payload, sid=self._solution['sid'], revision=self._solution['revision'], ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) return '<Twilio.Studio.V2.FlowRevisionContext {}>'.format(context) class FlowRevisionInstance(InstanceResource): class Status(object): DRAFT = "draft" PUBLISHED = "published" def __init__(self, version, payload, sid, revision=None): """ Initialize the FlowRevisionInstance :returns: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance """ super(FlowRevisionInstance, self).__init__(version) # Marshaled Properties self._properties = { 'sid': payload.get('sid'), 'account_sid': payload.get('account_sid'), 'friendly_name': payload.get('friendly_name'), 'definition': payload.get('definition'), 'status': payload.get('status'), 'revision': deserialize.integer(payload.get('revision')), 'commit_message': payload.get('commit_message'), 'valid': payload.get('valid'), 'errors': payload.get('errors'), 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), 'url': payload.get('url'), } # Context self._context = None self._solution = {'sid': sid, 'revision': revision or self._properties['revision'], } @property def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: FlowRevisionContext for this FlowRevisionInstance :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionContext """ if self._context is None: self._context = FlowRevisionContext( self._version, sid=self._solution['sid'], revision=self._solution['revision'], ) return self._context @property def sid(self): """ :returns: The unique string that identifies the resource :rtype: unicode """ return self._properties['sid'] @property def account_sid(self): """ :returns: The SID of the Account that created the resource :rtype: unicode """ return self._properties['account_sid'] @property def friendly_name(self): """ :returns: The string that you assigned to describe the Flow :rtype: unicode """ return self._properties['friendly_name'] @property def definition(self): """ :returns: JSON representation of flow definition :rtype: dict """ return self._properties['definition'] @property def status(self): """ :returns: The status of the Flow :rtype: FlowRevisionInstance.Status """ return self._properties['status'] @property def revision(self): """ :returns: The latest revision number of the Flow's definition :rtype: unicode """ return self._properties['revision'] @property def commit_message(self): """ :returns: Description of change made in the revision :rtype: unicode """ return self._properties['commit_message'] @property def valid(self): """ :returns: Boolean if the flow definition is valid :rtype: bool """ return self._properties['valid'] @property def errors(self): """ :returns: List of error in the flow definition :rtype: list[dict] """ return self._properties['errors'] @property def date_created(self): """ :returns: The ISO 8601 date and time in GMT when the resource was created :rtype: datetime """ return self._properties['date_created'] @property def date_updated(self): """ :returns: The ISO 8601 date and time in GMT when the resource was last updated :rtype: datetime """ return self._properties['date_updated'] @property def url(self): """ :returns: The absolute URL of the resource :rtype: unicode """ return self._properties['url'] def fetch(self): """ Fetch the FlowRevisionInstance :returns: The fetched FlowRevisionInstance :rtype: twilio.rest.studio.v2.flow.flow_revision.FlowRevisionInstance """ return self._proxy.fetch() def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) return '<Twilio.Studio.V2.FlowRevisionInstance {}>'.format(context)
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Part of the Keras training engine related to Python generators of array data. """ # pylint: disable=protected-access from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import math import numpy as np from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.ops import iterator_ops from tensorflow.python.eager import context from tensorflow.python.framework import errors from tensorflow.python.keras import backend from tensorflow.python.keras import callbacks as cbks from tensorflow.python.keras.engine import training_utils from tensorflow.python.keras.utils import data_utils from tensorflow.python.keras.utils import generic_utils from tensorflow.python.keras.utils.mode_keys import ModeKeys from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import nest def model_iteration(model, data, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, validation_freq=1, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=False, initial_epoch=0, mode=ModeKeys.TRAIN, batch_size=None, steps_name='steps', **kwargs): """Loop function for arrays of data with modes TRAIN/TEST/PREDICT. Arguments: model: Keras Model instance. data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or `(x, y)` or `(x, y, sample_weights)`) or a generator or `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset. steps_per_epoch: Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. Ignored with the default value of `None`. epochs: Number of times to iterate over the data. verbose: 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. Note that the progress bar is not particularly useful when logged to a file, so verbose=2 is recommended when not running interactively (eg, in a production environment). callbacks: List of callbacks to be called during training. validation_data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or `(x, y)` or `(x, y, sample_weights)`) or a generator or `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset. validation_steps: Total number of steps (batches of samples) before declaring validation finished. validation_freq: Only relevant if validation data is provided. Integer or `collections.Container` instance (e.g. list, tuple, etc.). If an integer, specifies how many training epochs to run before a new validation run is performed, e.g. `validation_freq=2` runs validation every 2 epochs. If a Container, specifies the epochs on which to run validation, e.g. `validation_freq=[1, 2, 10]` runs validation at the end of the 1st, 2nd, and 10th epochs. class_weight: Dictionary mapping class indices to a weight for the class. max_queue_size: Integer. Maximum size for the generator queue. If unspecified, `max_queue_size` will default to 10. workers: Integer. Maximum number of processes to spin up when using process-based threading. If unspecified, `workers` will default to 1. If 0, will execute the generator on the main thread. use_multiprocessing: Boolean. If `True`, use process-based threading. If unspecified, `use_multiprocessing` will default to `False`. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes. shuffle: Boolean. Whether to shuffle the order of the batches at the beginning of each epoch. Only used with instances of `Sequence` (`keras.utils.Sequence`). Has no effect when `steps_per_epoch` is not `None`. initial_epoch: Epoch at which to start training (useful for resuming a previous training run). mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT. batch_size: Integer batch size or None if unknown. Will only be used if `data` is in NumPy/Tensor format. steps_name: The string name of the steps argument, either `steps`, `validation_steps`, or `steps_per_epoch`. Only used for error message formatting. **kwargs: Additional arguments for backwards compatibility. `steps` is accepted as an alias for `steps_per_epoch`. Returns: - In TRAIN mode: `History` object. - In TEST mode: Evaluation metrics. - In PREDICT mode: Outputs of the Model called on inputs. Raises: ValueError: in case of invalid arguments. """ if 'steps' in kwargs: steps_per_epoch = kwargs['steps'] # Determine the number of steps per epoch and whether we should reset the # dataset at the end of each epoch. reset_dataset_after_each_epoch = False original_dataset = None is_dataset = isinstance(data, (dataset_ops.DatasetV2, dataset_ops.DatasetV1)) if is_dataset: original_dataset = data if steps_per_epoch is None: reset_dataset_after_each_epoch = True steps_per_epoch = training_utils.infer_steps_for_dataset( data, steps_per_epoch, epochs=epochs, steps_name=steps_name) # Convert to a format that supports `next(generator)`. generator, steps_per_epoch = convert_to_generator_like( data, steps_per_epoch=steps_per_epoch, batch_size=batch_size, epochs=epochs - initial_epoch, shuffle=shuffle) do_validation = validation_data is not None is_sequence = isinstance(generator, data_utils.Sequence) _validate_arguments(is_sequence, is_dataset, use_multiprocessing, workers, steps_per_epoch, validation_data, validation_steps, mode, kwargs) batch_function = _make_execution_function( model, mode, class_weight=class_weight) # Create the queue for the generator. enqueuer = None if not is_dataset: generator, enqueuer = _make_enqueued_generator( generator, workers=workers, use_multiprocessing=use_multiprocessing, max_queue_size=max_queue_size, shuffle=shuffle) num_samples_or_steps, use_steps = _get_num_samples_or_steps( data, steps_per_epoch) count_mode = 'steps' if use_steps else 'samples' callbacks = cbks.configure_callbacks( callbacks, model, do_validation=do_validation, epochs=epochs, steps_per_epoch=steps_per_epoch, batch_size=batch_size, samples=num_samples_or_steps, verbose=0, # Handle ProgBar as part of Callbacks once hooks are ready. mode=mode) # TODO(omalleyt): Handle ProgBar as part of Callbacks once hooks are ready. progbar = training_utils.get_progbar(model, count_mode) progbar.params = callbacks.params progbar.params['verbose'] = verbose if mode == ModeKeys.PREDICT: aggregator = training_utils.OutputsAggregator(True, steps_per_epoch) else: aggregator = training_utils.MetricsAggregator(True, steps_per_epoch) should_set_learning_phase = context.executing_eagerly() and model.run_eagerly if should_set_learning_phase: learning_phase_scope = backend.eager_learning_phase_scope( 1 if mode == ModeKeys.TRAIN else 0) learning_phase_scope.__enter__() callbacks.model.stop_training = False callbacks._call_begin_hook(mode) progbar.on_train_begin() initial_epoch = model._maybe_load_initial_epoch_from_ckpt(initial_epoch, mode) for epoch in range(initial_epoch, epochs): if callbacks.model.stop_training: break # Setup work for each epoch. model.reset_metrics() epoch_logs = {} if mode == ModeKeys.TRAIN: callbacks.on_epoch_begin(epoch, epoch_logs) progbar.on_epoch_begin(epoch, epoch_logs) if steps_per_epoch is None: # Loop over dataset until `OutOfRangeError` is raised. target_steps = np.inf else: # Loop over dataset for the specified number of steps. target_steps = steps_per_epoch step = 0 while step < target_steps: batch_data = _get_next_batch(generator, mode) if batch_data is None: if is_dataset: # The dataset passed by the user ran out of batches. # Now we know the cardinality of the dataset. # If steps_per_epoch was specified, then running out of data is # unexpected, so we stop training and inform the user. if steps_per_epoch: callbacks.model.stop_training = True logging.warning( 'Your dataset ran out of data; interrupting training. ' 'Make sure that your dataset can generate at least ' '`%s * epochs` batches (in this case, %d batches). ' 'You may need to use the repeat() function when ' 'building your dataset.' % (steps_name, steps_per_epoch * epochs)) elif step > 0: steps_per_epoch = step aggregator.num_samples_or_steps = steps_per_epoch if mode == ModeKeys.TRAIN: progbar.params['steps'] = steps_per_epoch progbar.progbar.target = steps_per_epoch else: # We ran out of batches while the user passed an iterator (legacy). callbacks.model.stop_training = True logging.warning( 'Your dataset iterator ran out of data; ' 'interrupting training. Make sure that your iterator ' 'can generate at least `%s * epochs` ' 'batches (in this case, %d batches). You may need to' 'use the repeat() function when building your ' 'dataset.' % (steps_name, steps_per_epoch * epochs)) break # `batch_size` used for validation data if validation # data is NumPy/EagerTensors. batch_size = int(nest.flatten(batch_data)[0].shape[0]) # Callbacks batch begin. batch_logs = {'batch': step, 'size': batch_size} callbacks._call_batch_hook(mode, 'begin', step, batch_logs) progbar.on_batch_begin(step, batch_logs) is_deferred = not model._is_compiled batch_outs = batch_function(*batch_data) if not isinstance(batch_outs, list): batch_outs = [batch_outs] if step == 0: aggregator.create(batch_outs) if is_deferred: # Set callbacks params. We do this here when model is compiled only # in the first iteration of this loop (deferred build scenario). cbks.set_callback_parameters( callbacks, model, do_validation=do_validation, batch_size=batch_size, epochs=epochs, steps_per_epoch=steps_per_epoch, samples=num_samples_or_steps, verbose=verbose, mode=mode) progbar.params = callbacks.params progbar.params['verbose'] = verbose # Aggregate results. aggregator.aggregate(batch_outs) # Callbacks batch end. batch_logs = cbks.make_logs(model, batch_logs, batch_outs, mode) callbacks._call_batch_hook(mode, 'end', step, batch_logs) progbar.on_batch_end(step, batch_logs) step += 1 if callbacks.model.stop_training: break aggregator.finalize() results = aggregator.results epoch_logs = cbks.make_logs(model, epoch_logs, results, mode) if len(results) == 1: results = results[0] # Run the test loop every epoch during training. if (do_validation and training_utils.should_run_validation(validation_freq, epoch) and not callbacks.model.stop_training): val_results = model_iteration( model, validation_data, steps_per_epoch=validation_steps, batch_size=batch_size, class_weight=class_weight, workers=workers, use_multiprocessing=use_multiprocessing, max_queue_size=max_queue_size, callbacks=callbacks, verbose=0, mode=ModeKeys.TEST, steps_name='validation_steps') if not isinstance(val_results, list): val_results = [val_results] epoch_logs = cbks.make_logs( model, epoch_logs, val_results, mode, prefix='val_') if mode == ModeKeys.TRAIN: # Epochs only apply to `fit`. callbacks.on_epoch_end(epoch, epoch_logs) progbar.on_epoch_end(epoch, epoch_logs) # Recreate dataset iterator for the next epoch. if reset_dataset_after_each_epoch and epoch < epochs - 1: generator = dataset_ops.make_one_shot_iterator(original_dataset) callbacks._call_end_hook(mode) if enqueuer is not None: enqueuer.stop() if should_set_learning_phase: learning_phase_scope.__exit__(None, None, None) if mode == ModeKeys.TRAIN: return model.history return results # Maintain compatibility with the existing names. fit_generator = functools.partial(model_iteration, mode=ModeKeys.TRAIN) evaluate_generator = functools.partial( model_iteration, mode=ModeKeys.TEST, shuffle=False) predict_generator = functools.partial( model_iteration, mode=ModeKeys.PREDICT, shuffle=False) def _get_next_batch(generator, mode): """Retrieves the next batch of input data.""" try: generator_output = next(generator) except (StopIteration, errors.OutOfRangeError): return None if not isinstance(generator_output, tuple): if mode == ModeKeys.PREDICT: # Always wrap in a tuple. return (generator_output,) else: raise ValueError('Output of generator should be ' 'a tuple `(x, y, sample_weight)` ' 'or `(x, y)`. Found: ' + str(generator_output)) if len(generator_output) < 1 or len(generator_output) > 3: raise ValueError('Output of generator should be ' 'a tuple `(x, y, sample_weight)` ' 'or `(x, y)` or (x,). Found: ' + str(generator_output)) return generator_output def _validate_arguments(is_sequence, is_dataset, use_multiprocessing, workers, steps_per_epoch, validation_data, validation_steps, mode, kwargs): """Raises errors if arguments are invalid. Arguments: is_sequence: Boolean, whether data is a `keras.utils.data_utils.Sequence` instance. is_dataset: Boolean, whether data is a dataset instance. use_multiprocessing: Boolean. If `True`, use process-based threading. If unspecified, `use_multiprocessing` will default to `False`. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes. workers: Integer. Maximum number of processes to spin up when using process-based threading. If unspecified, `workers` will default to 1. If 0, will execute the generator on the main thread. steps_per_epoch: Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. Ignored with the default value of `None`. validation_data: Either a tuple of NumPy/Tensor inputs (i.e. `(x,)` or `(x, y)` or `(x, y, sample_weights)`) or a generator or `keras.utils.data_utils.Sequence` object or Eager Iterator or Dataset. validation_steps: Total number of steps (batches of samples) before declaring validation finished. mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT. kwargs: Additional arguments for backwards compatibility. Raises: ValueError: If `steps_per_epoch` or `validation_steps` are not passed for data types that require them, or if unrecognized keyword arguments are passed. """ if not is_sequence and use_multiprocessing and workers > 1: logging.warning( UserWarning('Using a generator with `use_multiprocessing=True`' ' and multiple workers may duplicate your data.' ' Please consider using the `keras.utils.Sequence`' ' class.')) if steps_per_epoch is None and not is_dataset: arg_name = 'steps_per_epoch' if mode == ModeKeys.TRAIN else 'steps' raise ValueError('Please specify the number of steps via the ' '`{}` argument.'.format(arg_name)) val_gen = ( data_utils.is_generator_or_sequence(validation_data) or isinstance(validation_data, iterator_ops.IteratorV2)) if (val_gen and not isinstance(validation_data, data_utils.Sequence) and not validation_steps): raise ValueError('Please specify the `validation_steps` argument.') if any(k != 'steps' for k in kwargs): raise ValueError('Invalid arguments passed: {}'.format( [k for k in kwargs if k != 'steps'])) def convert_to_generator_like(data, batch_size=None, steps_per_epoch=None, epochs=1, shuffle=False): """Make a generator out of NumPy or EagerTensor inputs. Arguments: data: Either a generator or `keras.utils.data_utils.Sequence` object or `Dataset`, `Iterator`, or a {1,2,3}-tuple of NumPy arrays or EagerTensors. If a tuple, the elements represent `(x, y, sample_weights)` and may be `None` or `[None]`. batch_size: Used when creating a generator out of tuples of NumPy arrays or EagerTensors. steps_per_epoch: Steps of the generator to run each epoch. If `None` the number of steps will be read from the data (for `keras.utils.data_utils.Sequence` types). epochs: Total number of epochs to run. shuffle: Whether the data should be shuffled. Returns: - Generator, `keras.utils.data_utils.Sequence`, or `Iterator`. Raises: - ValueError: If `batch_size` is not provided for NumPy or EagerTensor inputs. """ if isinstance(data, tuple): # Scrub `Nones` that might have been passed for `targets`, `sample_weights`. data = tuple( ele for ele in data if not all(e is None for e in nest.flatten(ele))) if data_utils.is_generator_or_sequence(data) or isinstance( data, iterator_ops.IteratorV2): if isinstance(data, data_utils.Sequence): if steps_per_epoch is None: steps_per_epoch = len(data) return data, steps_per_epoch if isinstance(data, dataset_ops.DatasetV2): return dataset_ops.make_one_shot_iterator(data), steps_per_epoch # Create generator from NumPy or EagerTensor Input. num_samples = int(nest.flatten(data)[0].shape[0]) if batch_size is None: raise ValueError('You must specify `batch_size`') steps_per_epoch = int(math.ceil(num_samples / batch_size)) def _gen(data): """Makes a generator out of a structure of NumPy/EagerTensors.""" index_array = np.arange(num_samples) for _ in range(epochs): if shuffle: np.random.shuffle(index_array) batches = generic_utils.make_batches(num_samples, batch_size) for (batch_start, batch_end) in batches: batch_ids = index_array[batch_start:batch_end] flat_batch_data = training_utils.slice_arrays( nest.flatten(data), batch_ids, contiguous=(not shuffle)) yield nest.pack_sequence_as(data, flat_batch_data) return _gen(data), steps_per_epoch def _make_enqueued_generator(generator, workers=1, use_multiprocessing=False, max_queue_size=10, shuffle=False): """Create a buffered queue of next elements of the generator.""" is_sequence = isinstance(generator, data_utils.Sequence) enqueuer = None if workers > 0: if is_sequence: enqueuer = data_utils.OrderedEnqueuer( generator, use_multiprocessing=use_multiprocessing, shuffle=shuffle) else: enqueuer = data_utils.GeneratorEnqueuer( generator, use_multiprocessing=use_multiprocessing) enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: if is_sequence: output_generator = data_utils.iter_sequence_infinite(generator) else: output_generator = generator return output_generator, enqueuer def _make_execution_function(model, mode, class_weight=None): """Makes function to run one step of model execution.""" if mode == ModeKeys.TRAIN: f = functools.partial(model.train_on_batch, class_weight=class_weight) elif mode == ModeKeys.TEST: f = model.test_on_batch else: # Match signature of other modes to allow # 1, 2, or 3-tuples from generator def predict_on_batch(x, y=None, sample_weights=None): # pylint: disable=unused-argument return model.predict_on_batch(x) f = predict_on_batch # Maintain stateful metrics across batch-level calls. if mode != ModeKeys.PREDICT: f = functools.partial(f, reset_metrics=False) return f def _get_num_samples_or_steps(data, steps_per_epoch): """Returns number of samples or steps, and whether to use steps count mode.""" flat_inputs = nest.flatten(data) if hasattr(flat_inputs[0], 'shape'): return int(flat_inputs[0].shape[0]), False return steps_per_epoch, True class GeneratorOrSequenceTrainingLoop(training_utils.TrainingLoop): """Generator-like. Input is Python generator, or Sequence object. The difference between this class and `GeneratorLikeTrainingFunction` is that this class only handles inputs that with x, y and sample_weight fused into one param. """ def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0., validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_freq=1, max_queue_size=10, workers=1, use_multiprocessing=False): model._validate_or_infer_batch_size(batch_size, steps_per_epoch, x) training_utils.check_generator_arguments( y, sample_weight, validation_split=validation_split) return fit_generator( model, x, steps_per_epoch=steps_per_epoch, epochs=epochs, verbose=verbose, callbacks=callbacks, validation_data=validation_data, validation_steps=validation_steps, validation_freq=validation_freq, class_weight=class_weight, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, shuffle=shuffle, initial_epoch=initial_epoch, steps_name='steps_per_epoch') def evaluate(self, model, x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False): model._validate_or_infer_batch_size(batch_size, steps, x) training_utils.check_generator_arguments(y, sample_weight) return evaluate_generator( model, x, steps=steps, verbose=verbose, callbacks=callbacks, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing) def predict(self, model, x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False): model._validate_or_infer_batch_size(batch_size, steps, x) return predict_generator( model, x, steps=steps, verbose=verbose, callbacks=callbacks, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing) class EagerDatasetOrIteratorTrainingLoop(training_utils.TrainingLoop): """A non-distributed Dataset or iterator in eager execution.""" def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0., validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_freq=1, **kwargs): model._validate_or_infer_batch_size(batch_size, steps_per_epoch, x) # Make sure that y, sample_weights, validation_split are not passed. training_utils.validate_dataset_input(x, y, sample_weight, validation_split) if (isinstance(x, (dataset_ops.DatasetV1, dataset_ops.DatasetV2)) and shuffle): training_utils.verify_dataset_shuffled(x) return fit_generator( model, x, steps_per_epoch=steps_per_epoch, epochs=epochs, verbose=verbose, callbacks=callbacks, validation_data=validation_data, validation_steps=validation_steps, validation_freq=validation_freq, class_weight=class_weight, workers=0, shuffle=shuffle, initial_epoch=initial_epoch, steps_name='steps_per_epoch') def evaluate(self, model, x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None, callbacks=None, **kwargs): model._validate_or_infer_batch_size(batch_size, steps, x) # Make sure that y, sample_weights, validation_split are not passed. training_utils.validate_dataset_input(x, y, sample_weight) return evaluate_generator( model, x, steps=steps, verbose=verbose, workers=0, callbacks=callbacks) def predict(self, model, x, batch_size=None, verbose=0, steps=None, callbacks=None, **kwargs): model._validate_or_infer_batch_size(batch_size, steps, x) return predict_generator( model, x, steps=steps, verbose=verbose, workers=0, callbacks=callbacks) class GeneratorLikeTrainingLoop(training_utils.TrainingLoop): """TrainingLoop that handle inputs like python generator. This is the default handler for most of the input data types, includes symbolic tensors or Numpy array-like, Datasets and iterators in graph mode (since they generate symbolic tensors). This Function is used to handle model with `run_eagerly` = True. """ def fit(self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0., validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_freq=1, **kwargs): batch_size = model._validate_or_infer_batch_size(batch_size, steps_per_epoch, x) x, y, sample_weights = model._standardize_user_data( x, y, sample_weight=sample_weight, class_weight=class_weight, batch_size=batch_size, check_steps=True, steps_name='steps_per_epoch', steps=steps_per_epoch, validation_split=validation_split, shuffle=shuffle) if validation_data: validation_data = model._prepare_validation_data(validation_data, batch_size, validation_steps) elif validation_split and 0. < validation_split < 1.: (x, y, sample_weights, val_x, val_y, val_sample_weights) = model._split_training_and_validation_data( x, y, sample_weights, validation_split) validation_data = (val_x, val_y, val_sample_weights) else: if validation_steps: raise ValueError('`validation_steps` should not be specified if ' '`validation_data` is None.') return fit_generator( model, (x, y, sample_weights), steps_per_epoch=steps_per_epoch, batch_size=batch_size, epochs=epochs, verbose=verbose, callbacks=callbacks, validation_data=validation_data, validation_steps=validation_steps, validation_freq=validation_freq, workers=0, shuffle=shuffle, initial_epoch=initial_epoch, steps_name='steps_per_epoch') def evaluate(self, model, x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None, callbacks=None, **kwargs): batch_size = model._validate_or_infer_batch_size(batch_size, steps, x) x, y, sample_weights = model._standardize_user_data( x, y, sample_weight=sample_weight, batch_size=batch_size, check_steps=True, steps_name='steps', steps=steps) return evaluate_generator( model, (x, y, sample_weights), steps=steps, batch_size=batch_size, verbose=verbose, workers=0, callbacks=callbacks) def predict(self, model, x, batch_size=None, verbose=0, steps=None, callbacks=None, **kwargs): batch_size = model._validate_or_infer_batch_size(batch_size, steps, x) x, _, _ = model._standardize_user_data( x, check_steps=True, steps_name='steps', steps=steps) return predict_generator( model, x, steps=steps, batch_size=batch_size, verbose=verbose, workers=0, callbacks=callbacks)
# test_multibytecodec_support.py # Common Unittest Routines for CJK codecs # import codecs import os import re import sys import unittest from httplib import HTTPException from test import test_support from StringIO import StringIO class TestBase: encoding = '' # codec name codec = None # codec tuple (with 4 elements) tstring = '' # string to test StreamReader codectests = None # must set. codec test tuple roundtriptest = 1 # set if roundtrip is possible with unicode has_iso10646 = 0 # set if this encoding contains whole iso10646 map xmlcharnametest = None # string to test xmlcharrefreplace unmappedunicode = u'\udeee' # a unicode codepoint that is not mapped. def setUp(self): if self.codec is None: self.codec = codecs.lookup(self.encoding) self.encode = self.codec.encode self.decode = self.codec.decode self.reader = self.codec.streamreader self.writer = self.codec.streamwriter self.incrementalencoder = self.codec.incrementalencoder self.incrementaldecoder = self.codec.incrementaldecoder def test_chunkcoding(self): for native, utf8 in zip(*[StringIO(f).readlines() for f in self.tstring]): u = self.decode(native)[0] self.assertEqual(u, utf8.decode('utf-8')) if self.roundtriptest: self.assertEqual(native, self.encode(u)[0]) def test_errorhandle(self): for source, scheme, expected in self.codectests: if isinstance(source, bytes): func = self.decode else: func = self.encode if expected: result = func(source, scheme)[0] if func is self.decode: self.assertTrue(type(result) is unicode, type(result)) self.assertEqual(result, expected, '%r.decode(%r, %r)=%r != %r' % (source, self.encoding, scheme, result, expected)) else: self.assertTrue(type(result) is bytes, type(result)) self.assertEqual(result, expected, '%r.encode(%r, %r)=%r != %r' % (source, self.encoding, scheme, result, expected)) else: self.assertRaises(UnicodeError, func, source, scheme) def test_xmlcharrefreplace(self): if self.has_iso10646: self.skipTest('encoding contains full ISO 10646 map') s = u"\u0b13\u0b23\u0b60 nd eggs" self.assertEqual( self.encode(s, "xmlcharrefreplace")[0], "&#2835;&#2851;&#2912; nd eggs" ) def test_customreplace_encode(self): if self.has_iso10646: self.skipTest('encoding contains full ISO 10646 map') from htmlentitydefs import codepoint2name def xmlcharnamereplace(exc): if not isinstance(exc, UnicodeEncodeError): raise TypeError("don't know how to handle %r" % exc) l = [] for c in exc.object[exc.start:exc.end]: if ord(c) in codepoint2name: l.append(u"&%s;" % codepoint2name[ord(c)]) else: l.append(u"&#%d;" % ord(c)) return (u"".join(l), exc.end) codecs.register_error("test.xmlcharnamereplace", xmlcharnamereplace) if self.xmlcharnametest: sin, sout = self.xmlcharnametest else: sin = u"\xab\u211c\xbb = \u2329\u1234\u232a" sout = "&laquo;&real;&raquo; = &lang;&#4660;&rang;" self.assertEqual(self.encode(sin, "test.xmlcharnamereplace")[0], sout) def test_callback_wrong_objects(self): def myreplace(exc): return (ret, exc.end) codecs.register_error("test.cjktest", myreplace) for ret in ([1, 2, 3], [], None, object(), 'string', ''): self.assertRaises(TypeError, self.encode, self.unmappedunicode, 'test.cjktest') def test_callback_long_index(self): def myreplace(exc): return (u'x', long(exc.end)) codecs.register_error("test.cjktest", myreplace) self.assertEqual(self.encode(u'abcd' + self.unmappedunicode + u'efgh', 'test.cjktest'), ('abcdxefgh', 9)) def myreplace(exc): return (u'x', sys.maxint + 1) codecs.register_error("test.cjktest", myreplace) self.assertRaises((IndexError, OverflowError), self.encode, self.unmappedunicode, 'test.cjktest') def test_callback_None_index(self): def myreplace(exc): return (u'x', None) codecs.register_error("test.cjktest", myreplace) self.assertRaises(TypeError, self.encode, self.unmappedunicode, 'test.cjktest') def test_callback_backward_index(self): def myreplace(exc): if myreplace.limit > 0: myreplace.limit -= 1 return (u'REPLACED', 0) else: return (u'TERMINAL', exc.end) myreplace.limit = 3 codecs.register_error("test.cjktest", myreplace) self.assertEqual(self.encode(u'abcd' + self.unmappedunicode + u'efgh', 'test.cjktest'), ('abcdREPLACEDabcdREPLACEDabcdREPLACEDabcdTERMINALefgh', 9)) def test_callback_forward_index(self): def myreplace(exc): return (u'REPLACED', exc.end + 2) codecs.register_error("test.cjktest", myreplace) self.assertEqual(self.encode(u'abcd' + self.unmappedunicode + u'efgh', 'test.cjktest'), ('abcdREPLACEDgh', 9)) def test_callback_index_outofbound(self): def myreplace(exc): return (u'TERM', 100) codecs.register_error("test.cjktest", myreplace) self.assertRaises(IndexError, self.encode, self.unmappedunicode, 'test.cjktest') def test_incrementalencoder(self): UTF8Reader = codecs.getreader('utf-8') for sizehint in [None] + range(1, 33) + \ [64, 128, 256, 512, 1024]: istream = UTF8Reader(StringIO(self.tstring[1])) ostream = StringIO() encoder = self.incrementalencoder() while 1: if sizehint is not None: data = istream.read(sizehint) else: data = istream.read() if not data: break e = encoder.encode(data) ostream.write(e) self.assertEqual(ostream.getvalue(), self.tstring[0]) def test_incrementaldecoder(self): UTF8Writer = codecs.getwriter('utf-8') for sizehint in [None, -1] + range(1, 33) + \ [64, 128, 256, 512, 1024]: istream = StringIO(self.tstring[0]) ostream = UTF8Writer(StringIO()) decoder = self.incrementaldecoder() while 1: data = istream.read(sizehint) if not data: break else: u = decoder.decode(data) ostream.write(u) self.assertEqual(ostream.getvalue(), self.tstring[1]) def test_incrementalencoder_error_callback(self): inv = self.unmappedunicode e = self.incrementalencoder() self.assertRaises(UnicodeEncodeError, e.encode, inv, True) e.errors = 'ignore' self.assertEqual(e.encode(inv, True), '') e.reset() def tempreplace(exc): return (u'called', exc.end) codecs.register_error('test.incremental_error_callback', tempreplace) e.errors = 'test.incremental_error_callback' self.assertEqual(e.encode(inv, True), 'called') # again e.errors = 'ignore' self.assertEqual(e.encode(inv, True), '') def test_streamreader(self): UTF8Writer = codecs.getwriter('utf-8') for name in ["read", "readline", "readlines"]: for sizehint in [None, -1] + range(1, 33) + \ [64, 128, 256, 512, 1024]: istream = self.reader(StringIO(self.tstring[0])) ostream = UTF8Writer(StringIO()) func = getattr(istream, name) while 1: data = func(sizehint) if not data: break if name == "readlines": ostream.writelines(data) else: ostream.write(data) self.assertEqual(ostream.getvalue(), self.tstring[1]) def test_streamwriter(self): readfuncs = ('read', 'readline', 'readlines') UTF8Reader = codecs.getreader('utf-8') for name in readfuncs: for sizehint in [None] + range(1, 33) + \ [64, 128, 256, 512, 1024]: istream = UTF8Reader(StringIO(self.tstring[1])) ostream = self.writer(StringIO()) func = getattr(istream, name) while 1: if sizehint is not None: data = func(sizehint) else: data = func() if not data: break if name == "readlines": ostream.writelines(data) else: ostream.write(data) self.assertEqual(ostream.getvalue(), self.tstring[0]) class TestBase_Mapping(unittest.TestCase): pass_enctest = [] pass_dectest = [] supmaps = [] codectests = [] def __init__(self, *args, **kw): unittest.TestCase.__init__(self, *args, **kw) try: self.open_mapping_file().close() # test it to report the error early except (IOError, HTTPException): self.skipTest("Could not retrieve "+self.mapfileurl) def open_mapping_file(self): return test_support.open_urlresource(self.mapfileurl) def test_mapping_file(self): if self.mapfileurl.endswith('.xml'): self._test_mapping_file_ucm() else: self._test_mapping_file_plain() def _test_mapping_file_plain(self): _unichr = lambda c: eval("u'\\U%08x'" % int(c, 16)) unichrs = lambda s: u''.join(_unichr(c) for c in s.split('+')) urt_wa = {} with self.open_mapping_file() as f: for line in f: if not line: break data = line.split('#')[0].strip().split() if len(data) != 2: continue csetval = eval(data[0]) if csetval <= 0x7F: csetch = chr(csetval & 0xff) elif csetval >= 0x1000000: csetch = chr(csetval >> 24) + chr((csetval >> 16) & 0xff) + \ chr((csetval >> 8) & 0xff) + chr(csetval & 0xff) elif csetval >= 0x10000: csetch = chr(csetval >> 16) + \ chr((csetval >> 8) & 0xff) + chr(csetval & 0xff) elif csetval >= 0x100: csetch = chr(csetval >> 8) + chr(csetval & 0xff) else: continue unich = unichrs(data[1]) if unich == u'\ufffd' or unich in urt_wa: continue urt_wa[unich] = csetch self._testpoint(csetch, unich) def _test_mapping_file_ucm(self): with self.open_mapping_file() as f: ucmdata = f.read() uc = re.findall('<a u="([A-F0-9]{4})" b="([0-9A-F ]+)"/>', ucmdata) for uni, coded in uc: unich = unichr(int(uni, 16)) codech = ''.join(chr(int(c, 16)) for c in coded.split()) self._testpoint(codech, unich) def test_mapping_supplemental(self): for mapping in self.supmaps: self._testpoint(*mapping) def _testpoint(self, csetch, unich): if (csetch, unich) not in self.pass_enctest: try: self.assertEqual(unich.encode(self.encoding), csetch) except UnicodeError, exc: self.fail('Encoding failed while testing %s -> %s: %s' % ( repr(unich), repr(csetch), exc.reason)) if (csetch, unich) not in self.pass_dectest: try: self.assertEqual(csetch.decode(self.encoding), unich) except UnicodeError, exc: self.fail('Decoding failed while testing %s -> %s: %s' % ( repr(csetch), repr(unich), exc.reason)) def test_errorhandle(self): for source, scheme, expected in self.codectests: if isinstance(source, bytes): func = source.decode else: func = source.encode if expected: if isinstance(source, bytes): result = func(self.encoding, scheme) self.assertTrue(type(result) is unicode, type(result)) self.assertEqual(result, expected, '%r.decode(%r, %r)=%r != %r' % (source, self.encoding, scheme, result, expected)) else: result = func(self.encoding, scheme) self.assertTrue(type(result) is bytes, type(result)) self.assertEqual(result, expected, '%r.encode(%r, %r)=%r != %r' % (source, self.encoding, scheme, result, expected)) else: self.assertRaises(UnicodeError, func, self.encoding, scheme) def load_teststring(name): dir = test_support.findfile('cjkencodings') with open(os.path.join(dir, name + '.txt'), 'rb') as f: encoded = f.read() with open(os.path.join(dir, name + '-utf8.txt'), 'rb') as f: utf8 = f.read() return encoded, utf8
""" Note: ntlm3 was obtained from here: https://github.com/trustrachel/python-ntlm3 """ import datetime import urllib2 from urlparse import urlparse, urlunparse try: import arcpy arcpyFound = True except: arcpyFound = False try: from ntlm3 import HTTPNtlmAuthHandler hasNTLM = True except: hasNTLM = False from .._abstract import abstract _defaultTokenExpiration = 5 #Minutes import warnings warnings.filterwarnings("ignore", category=UserWarning, module='urllib2') ######################################################################## class LDAPSecurityHandler(abstract.BaseSecurityHandler): """ This Security Handler handles LDAP based security. """ _jar = None _handler = None _certificatefile = None _keyfile = None _token = "" _proxy_url = None _proxy_port = None _org_url = None _url = None _surl = None _referer_url = None _parsed_org_url = None _portal_username = None _method = "HANDLER" _login_username = None _username = None _password = None #---------------------------------------------------------------------- def __init__(self, org_url, username, password, proxy_url=None, proxy_port=None, referer_url=None): """Constructor""" self._login_username = username self._password = password self._proxy_url = proxy_url self._proxy_port = proxy_port self._initURL(org_url=org_url, referer_url=referer_url) self.loadusername() _is_portal = None #---------------------------------------------------------------------- @property def is_portal(self): if self._is_portal is None: self.check_portal() return self._is_portal def check_portal(self): from ..manageorg import Administration admin = Administration(url=self._org_url, securityHandler=self) portal = admin.portals.portalSelf self._is_portal = portal.isPortal #---------------------------------------------------------------------- @property def method(self): """get the security handler type""" return self._method #---------------------------------------------------------------------- def _initURL(self, org_url, referer_url): """ sets proper URLs for AGOL """ if org_url is not None and org_url != '': if not org_url.startswith('http://') and not org_url.startswith('https://'): org_url = 'https://' + org_url self._org_url = org_url if self._org_url.lower().find('/sharing/rest') > -1: self._url = self._org_url else: self._url = self._org_url + "/sharing/rest" if self._url.startswith('http://'): self._surl = self._url.replace('http://', 'https://') else: self._surl = self._url parsed_url = urlparse(self._org_url) self._parsed_org_url = urlunparse((parsed_url[0],parsed_url[1],"","","",""))#added 7/15/2015 if referer_url is None: self._referer_url = parsed_url.netloc #---------------------------------------------------------------------- @property def org_url(self): """gets the org_url""" return self._org_url #---------------------------------------------------------------------- @property def referer_url(self): """gets the referer url""" return self._referer_url #---------------------------------------------------------------------- @property def token(self): """gets the token""" return self._token #---------------------------------------------------------------------- @property def username(self): """gets/sets the username""" return self._username #---------------------------------------------------------------------- @username.setter def username(self, value): """gets/sets the username""" if isinstance(value, str): self._username = value self._handler = None #---------------------------------------------------------------------- @property def password(self): """gets/sets the current password""" return self._password #---------------------------------------------------------------------- @password.setter def password(self, value): """gets/sets the current password""" if isinstance(value, str): self._password = value self._handler = None #---------------------------------------------------------------------- @property def handler(self): """returns the handler""" if self._handler is None: passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, self._parsed_org_url, self._login_username, self.password) self._handler = urllib2.HTTPBasicAuthHandler(passman) return self._handler #---------------------------------------------------------------------- @property def cookiejar(self): """gets the cookiejar""" if self._jar is None: from cookielib import CookieJar self._jar = CookieJar() return self._jar def loadusername(self): if self._username is None: from ..manageorg import Administration admin = Administration(url=self._org_url, securityHandler=self, proxy_url=self._proxy_url, proxy_port=self._proxy_port) portal = admin.portals.portalSelf if 'username' in portal.user: self._username = portal.user['username'] else: self._username = self._login_username del portal, admin #---------------------------------------------------------------------- @property def proxy_url(self): """gets the proxy url""" return self._proxy_url #---------------------------------------------------------------------- @proxy_url.setter def proxy_url(self, value): """ sets the proxy_url """ self._proxy_url = value #---------------------------------------------------------------------- @property def proxy_port(self): """ gets the proxy port """ return self._proxy_port #---------------------------------------------------------------------- @proxy_port.setter def proxy_port(self, value): """ sets the proxy port """ if isinstance(value, int): self._proxy_port = value #---------------------------------------------------------------------- def portalServerHandler(self, serverUrl, username=None): """ returns a handler to access a federated server serverUrl - url to the server. Example: https://server.site.com/arcgis username - the portal site username. if None is passed, it obtains it from the portal properties Outout: returns a PortalServerSecurityHandler object Usage: >>> # access the administration site >>> serverUrl="https://mysite.site.com/arcgis" >>> newSH = sh.portalServerHandler(serverUrl=serverUrl, username=None) >>> agsAdmin = AGSAdministration(url=serverUrl, securityHandler=newSH) >>> print agsAdmin.info >>> # access a secure service from portal handler >>> msUrl = "https://mysite.site.com:6443/arcgis/rest/services/SampleWorldCities/MapServer" >>> ms = arcrest.ags.MapService(url=msUrl, securityHandler=newSH) >>> print ms.mapName """ from ..manageorg import Administration admin = Administration(url=self._org_url, securityHandler=self, proxy_url=self._proxy_url, proxy_port=self._proxy_port) token_url = admin.tokenURL if username is None: username = self._login_username ptsh = PortalTokenSecurityHandler(username=username, password=self._password, org_url=self._org_url, token_url=token_url, proxy_url=self._proxy_url, proxy_port=self._proxy_port, jar=self.cookiejar, handler=self.handler) pssh = PortalServerSecurityHandler(tokenHandler=ptsh, serverUrl=serverUrl, referer=self._referer_url, jar=self.cookiejar, handler=self.handler) return pssh ######################################################################## class NTLMSecurityHandler(LDAPSecurityHandler): """performs NTLM/Kerberos security handling""" def __init__(self, org_url, username, password, proxy_url=None, proxy_port=None, referer_url=None): self._login_username = username self._password = password self._proxy_url = proxy_url self._proxy_port = proxy_port self._initURL(org_url=org_url, referer_url=referer_url) self.loadusername() #---------------------------------------------------------------------- @property def handler(self): """gets the security handler for the class""" if hasNTLM: if self._handler is None: passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, self._parsed_org_url, self._login_username, self._password) self._handler = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) return self._handler else: raise Exception("Missing Ntlm python package.") #---------------------------------------------------------------------- @property def cookiejar(self): """gets the cookiejar""" if self._jar is None: from cookielib import CookieJar self._jar = CookieJar() return self._jar ######################################################################## class PKISecurityHandler(abstract.BaseSecurityHandler): """ This Security Handler handles PKI based security """ _jar = None _handler = None _certificatefile = None _keyfile = None _token = "" _proxy_url = None _proxy_port = None _org_url = None _parsed_org_url = None _url = None _surl = None _referer_url = None _method = "HANDLER" #---------------------------------------------------------------------- def __init__(self, org_url, keyfile, certificatefile, proxy_url=None, proxy_port=None, referer_url=None): """Constructor""" self._keyfile = keyfile self._certificatefile = certificatefile self._proxy_url = proxy_url self._proxy_port = proxy_port self._initURL(org_url=org_url, referer_url=referer_url) #---------------------------------------------------------------------- @property def method(self): """get the security handler type""" return self._method #---------------------------------------------------------------------- def _initURL(self, org_url, referer_url): """ sets proper URLs for AGOL """ if org_url is not None and org_url != '': if not org_url.startswith('http://') and not org_url.startswith('https://'): org_url = 'https://' + org_url self._org_url = org_url if self._org_url.lower().find('/sharing/rest') > -1: self._url = self._org_url else: self._url = self._org_url + "/sharing/rest" if self._url.startswith('http://'): self._surl = self._url.replace('http://', 'https://') else: self._surl = self._url parsed_url = urlparse(self._org_url) self._parsed_org_url = urlunparse((parsed_url[0],parsed_url[1],"","","","")) if referer_url is None: parsed_org = urlparse(self._org_url) self._referer_url = parsed_org.netloc _is_portal = None #---------------------------------------------------------------------- @property def is_portal(self): if self._is_portal is None: self.check_portal() return self._is_portal def check_portal(self): from ..manageorg import Administration admin = Administration(url=self._org_url, securityHandler=self) portal = admin.portals.portalSelf self._is_portal = portal.isPortal #---------------------------------------------------------------------- @property def org_url(self): """gets the org_url""" return self._org_url #---------------------------------------------------------------------- @property def referer_url(self): """gets the referer url""" return self._referer_url #---------------------------------------------------------------------- @property def token(self): """gets the token""" return self._token #---------------------------------------------------------------------- @property def handler(self): """returns the handler""" if self._handler is None: self._handler = self.HTTPSClientAuthHandler(key=self._keyfile, cert=self._certificatefile) return self._handler #---------------------------------------------------------------------- @property def certificate(self): """gets/sets the certificate file""" return self._certificatefile #---------------------------------------------------------------------- @certificate.setter def certificate(self, value): """gets/sets the certificate file""" import os if os.path.isfile(value): self._certificatefile = value #---------------------------------------------------------------------- @property def key_file(self): """returns the key file""" return self._keyfile #---------------------------------------------------------------------- @key_file.setter def key_file(self, value): """gets/sets the certificate file""" import os if os.path.isfile(value): self._keyfile = value #---------------------------------------------------------------------- @property def cookiejar(self): """gets the cookiejar""" if self._jar is None: from cookielib import CookieJar self._jar = CookieJar() return self._jar #---------------------------------------------------------------------- @property def proxy_url(self): """gets the proxy url""" return self._proxy_url #---------------------------------------------------------------------- @proxy_url.setter def proxy_url(self, value): """ sets the proxy_url """ self._proxy_url = value #---------------------------------------------------------------------- @property def proxy_port(self): """ gets the proxy port """ return self._proxy_port #---------------------------------------------------------------------- @proxy_port.setter def proxy_port(self, value): """ sets the proxy port """ if isinstance(value, int): self._proxy_port = value #---------------------------------------------------------------------- class HTTPSClientAuthHandler(urllib2.HTTPSHandler): import httplib def __init__(self, key, cert): urllib2.HTTPSHandler.__init__(self) self.key = key self.cert = cert def https_open(self, req): #Rather than pass in a reference to a connection class, we pass in # a reference to a function which, for all intents and purposes, # will behave as a constructor return self.do_open(self.getConnection, req) def getConnection(self, host, timeout=300): return self.httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert, timeout=timeout) ######################################################################## class PortalServerSecurityHandler(abstract.BaseSecurityHandler): """ This service is designed to allow users manage a server from a Portal site credentials. This means a user can get an ArcGIS Server Token from a Portal login to manage and use secure services. It is not designed for users to create this object through code, but rather it is generated by the system. """ _method = "TOKEN" _tokenHandler = None _serverUrl = None _referer = None _parsed_org_url = None _token = None _handler = None _jar = None # def __init__(self, tokenHandler, serverUrl, referer, handler=None, jar = None): """Constructor""" if isinstance(tokenHandler, PortalTokenSecurityHandler): self._portalTokenHandler = tokenHandler elif isinstance(tokenHandler, ArcGISTokenSecurityHandler): self._tokenHandler = tokenHandler else: raise AttributeError("Invalid token handler") self._handler = handler self._jar = jar self._initURL(serverUrl=serverUrl) #---------------------------------------------------------------------- def _initURL(self, serverUrl=None): """ sets proper URLs for AGOL """ self._serverUrl = serverUrl parsed_url = urlparse(self._serverUrl) self._parsed_org_url = urlunparse((parsed_url[0],parsed_url[1],"","","","")) self._referer = parsed_url.netloc #---------------------------------------------------------------------- @property def token(self): """gets the AGS server token""" return self._portalTokenHandler.servertoken(serverURL=self._serverUrl, referer=self._referer) #---------------------------------------------------------------------- @property def method(self): """returns the handler method""" return self._method # @property def serverUrl(self): """gets/sets the server url""" return self._serverUrl # @serverUrl.setter def serverUrl(self, value): """gets/sets the server url""" if value.lower() != self._serverUrl.lower(): self._serverUrl = value # @property def referer(self): """gets/sets the referer object""" return self._referer #---------------------------------------------------------------------- @property def cookiejar(self): """gets the cookiejar""" return self._jar @cookiejar.setter def cookiejar(self, value): """gets/sets a cookiejar""" if value is not None: self._jar = value @property def handler(self): """gets/sets a handler""" return self._handler @handler.setter def handler(self, value): """gets/sets a handler""" if value is not None: self._handler = value @referer.setter def referer(self, value): """gets/sets the referer object""" if value is not None and \ self._referer is not None and \ self._referer.lower() != value.lower(): self._referer = value #---------------------------------------------------------------------- @property def is_portal(self): return False ######################################################################## class OAuthSecurityHandler(abstract.BaseSecurityHandler): """Handles AGOL OAuth Security Inputs: client_id - OAuth client key secret_id - OAuth secret key org_url - The url of that ArcGIS Organization. This url is composed on the machine name and the instance name of the portal. For example: http://myportal.mycompany.com/portal for a Portal for ArcGIS Server instance. - http://www.arcgis.com for ArcGIS Online - http://myOnlineOrg.maps.arcgis.com for ArcGIS Online, but the unique url for your org token_url - optional - url to where the token is obtained proxy_url - optional - proxy url as a string proxy_port - optional - proxy port as integer Output: OAuthSecurityHandler Class Object """ _token = None _default_token_url = "https://www.arcgis.com/sharing/rest/oauth2/token/" _token_url = "https://www.arcgis.com/sharing/rest/oauth2/token/" _client_id = None _secret_id = None _token_created_on = None _token_expires_on = None _expires_in = None _proxy_url = None _proxy_port = None _method = "OAUTH" #---------------------------------------------------------------------- def __init__(self, client_id, secret_id, org_url,token_url=None, proxy_url=None, proxy_port=None): """Constructor""" self._client_id = client_id self._secret_id = secret_id self._token_url = token_url self._org_url = org_url self._proxy_port = proxy_port self._proxy_url = proxy_url self._token_expires_on = datetime.datetime.now() + datetime.timedelta(seconds=_defaultTokenExpiration) self._initURL(token_url=token_url) #---------------------------------------------------------------------- def _initURL(self, org_url=None, token_url=None, referer_url=None): """ sets proper URLs for AGOL """ if org_url is not None and org_url != '': if not org_url.startswith('http://') and not org_url.startswith('https://'): org_url = 'http://' + org_url self._org_url = org_url if not self._org_url.startswith('http://') and not self._org_url.startswith('https://'): self._org_url = 'http://' + self._org_url if self._org_url.lower().find('/sharing/rest') > -1: self._url = self._org_url else: self._url = self._org_url + "/sharing/rest" if self._url.startswith('http://'): self._surl = self._url.replace('http://', 'https://') else: self._surl = self._url if token_url is None: self._token_url = self._surl + "/oauth2/token" else: self._token_url = token_url if referer_url is None: if not self._org_url.startswith('http://'): self._referer_url = self._org_url.replace('http://', 'https://') else: self._referer_url = self._org_url else: self._referer_url = referer_url _is_portal = None #---------------------------------------------------------------------- @property def is_portal(self): if self._is_portal is None: self.check_portal() return self._is_portal def check_portal(self): from ..manageorg import Administration admin = Administration(url=self._org_url, securityHandler=self) portal = admin.portals.portalSelf self._is_portal = portal.isPortal #---------------------------------------------------------------------- @property def method(self): """returns the handler method""" return self._method #---------------------------------------------------------------------- @property def proxy_url(self): """gets the proxy url""" return self._proxy_url #---------------------------------------------------------------------- @proxy_url.setter def proxy_url(self, value): """ sets the proxy_url """ self._proxy_url = value #---------------------------------------------------------------------- @property def proxy_port(self): """ gets the proxy port """ return self._proxy_port #---------------------------------------------------------------------- @proxy_port.setter def proxy_port(self, value): """ sets the proxy port """ if isinstance(value, int): self._proxy_port = value #---------------------------------------------------------------------- @property def org_url(self): """ gets/sets the organization URL """ return self._org_url #---------------------------------------------------------------------- @property def referer_url(self): """ returns when the token was generated """ return self._referer_url #---------------------------------------------------------------------- @property def token(self): """ obtains a token from the site """ if self._token is None or \ datetime.datetime.now() >= self._token_expires_on: self._generateForOAuthSecurity(self._client_id, self._secret_id, self._token_url) return self._token #---------------------------------------------------------------------- @property def client_id(self): """ returns the client id """ return self._client_id #---------------------------------------------------------------------- @client_id.setter def client_id(self, value): """ sets the client id for oauth """ self._token = None self._client_id = value #---------------------------------------------------------------------- @property def secret_id(self): """ returns ***** for secret id """ return "*****" #---------------------------------------------------------------------- @secret_id.setter def secret_id(self, value): """ sets the secret id """ self._token = None self._secret_id = value #---------------------------------------------------------------------- @property def token_url(self): """ returns the token url """ return self._token_url #---------------------------------------------------------------------- @token_url.setter def token_url(self, value): """ sets the token url """ self._token = None self._token_url = value #---------------------------------------------------------------------- def resetTokenURLToDefault(self): """ resets the token url to the default url """ self._token = None self._token_url = self._default_token_url #---------------------------------------------------------------------- @property def tokenExperationDate(self): """ returns when the token is not valid """ return self._token_expires_on #---------------------------------------------------------------------- @property def tokenObtainedDate(self): """ returns when the token was generated """ return self._token_created_on #---------------------------------------------------------------------- def _generateForOAuthSecurity(self, client_id, secret_id, token_url=None): """ generates a token based on the OAuth security model """ grant_type="client_credentials" if token_url is None: token_url = "https://www.arcgis.com/sharing/rest/oauth2/token" params = { "client_id" : client_id, "client_secret" : secret_id, "grant_type":grant_type, "f" : "json" } token = self._do_post(url=token_url, param_dict=params, securityHandler=None, proxy_port=self._proxy_port, proxy_url=self._proxy_url) if 'access_token' in token: self._token = token['access_token'] self._expires_in = token['expires_in'] self._token_created_on = datetime.datetime.now() self._token_expires_on = self._token_created_on + datetime.timedelta(seconds=int(token['expires_in'])) else: self._token = None self._expires_in = None self._token_created_on = None self._token_expires_on = None #self._token_expires_on = None ######################################################################## class ArcGISTokenSecurityHandler(abstract.BaseSecurityHandler): """ handles ArcGIS Maps Token Base Security """ _method = "TOKEN" _token = None _surl = None _org_url =None _url = None _referer_url = None _username = None _token_expires_on = None _expires_in = None _proxy_url = None _proxy_port = None _server_token = None _server_token_expires_on = None _server_token_created_on = None _server_expires_in = None _server_url = None _token_url = None #---------------------------------------------------------------------- def __init__(self,proxy_url=None, proxy_port=None): """Constructor""" if arcpyFound == False: self._message = "ArcPy not available" self._valid = False else: self._proxy_port = proxy_port self._proxy_url = proxy_url self._token_expires_on = None self._initURL() #---------------------------------------------------------------------- def _initURL(self): """ sets proper URLs for AGOL """ token = self._getTokenArcMap() if 'error' in token: self._valid = False self._message = token['error'] else: self._valid = True self._message = "Token Generated" self._org_url = arcpy.GetActivePortalURL() if self._org_url.lower().find('/sharing/rest') > -1: self._url = self._org_url else: self._url = self._org_url + "/sharing/rest" if self._url.startswith('http://'): self._surl = self._url.replace('http://', 'https://') else: self._surl = self._url url = '{}/portals/self'.format( self._url) parameters = { 'f': 'json' } portal_info = self._do_post(url=url, param_dict=parameters, securityHandler=self, proxy_port=self._proxy_port, proxy_url=self._proxy_url) if 'user' in portal_info: if 'username' in portal_info['user']: self._username = portal_info['user'] results = self._do_get(url= self._surl + '/portals/info', param_dict={'f':'json'}, header=None, proxy_port=self._proxy_port, proxy_url=self._proxy_url) if 'authInfo' in results and 'tokenServicesUrl' in results['authInfo']: self._token_url = results['authInfo']['tokenServicesUrl'] else: self._token_url = self._surl + '/generateToken' _is_portal = None #---------------------------------------------------------------------- @property def is_portal(self): if self._is_portal is None: self.check_portal() return self._is_portal def check_portal(self): from ..manageorg import Administration admin = Administration(url=self._org_url, securityHandler=self) portal = admin.portals.portalSelf self._is_portal = portal.isPortal #---------------------------------------------------------------------- @property def method(self): """returns the handler method""" return self._method #---------------------------------------------------------------------- @property def org_url(self): """ gets/sets the organization URL """ return self._org_url #---------------------------------------------------------------------- @property def proxy_url(self): """gets the proxy url""" return self._proxy_url #---------------------------------------------------------------------- @proxy_url.setter def proxy_url(self, value): """ sets the proxy_url """ self._proxy_url = value #---------------------------------------------------------------------- @property def proxy_port(self): """ gets the proxy port """ return self._proxy_port #---------------------------------------------------------------------- @proxy_port.setter def proxy_port(self, value): """ sets the proxy port """ if isinstance(value, int): self._proxy_port = value #---------------------------------------------------------------------- @property def username(self): """ returns the username """ return self._username #---------------------------------------------------------------------- @property def tokenExperationDate(self): """ returns when the token is not valid """ return self._token_expires_on #---------------------------------------------------------------------- @property def referer_url(self): """ returns when the token was generated """ return self._referer_url #---------------------------------------------------------------------- @property def token(self): """ returns the token for the site """ if self._token is None or \ datetime.datetime.now() >= self._token_expires_on: result = self._getTokenArcMap() if 'error' in result: self._valid = False self._message = result else: self._valid = True self._message = "Token Generated" return self._token #---------------------------------------------------------------------- def _getTokenArcMap(self): token_response = arcpy.GetSigninToken() if token_response and 'token' in token_response: self._token = token_response['token'] self._expires_in = token_response['expires'] self._token_expires_on = datetime.datetime.fromtimestamp(token_response['expires'] /1000) - \ datetime.timedelta(seconds=1) self._referer_url = token_response['referer'] return self._token #{'token': u'', 'expires': 1434040404L, 'referer': u'http://www.esri.com/AGO/A4901C34-4DDA-4B63-8D7A-E5906A85D17C'} else: return {"error": "No valid token, please log in ArcMap"} #---------------------------------------------------------------------- def servertoken(self,serverURL,referer): """ returns the server token for the server """ if self._server_token is None or self._server_token_expires_on is None or \ datetime.datetime.now() >= self._server_token_expires_on or \ self._server_url != serverURL: self._server_url = serverURL result = self._generateForServerTokenSecurity(serverURL=serverURL, token=self.token) if 'error' in result: self._valid = False self._message = result else: self._valid = True self._message = "Server Token Generated" return self._server_token #---------------------------------------------------------------------- def _generateForServerTokenSecurity(self, serverURL, token, expiration=None): """ generates a token for a feature service """ query_dict = {'serverURL':serverURL, 'token': token, 'expiration':str(_defaultTokenExpiration), 'f': 'json', 'request':'getToken'} if expiration is not None: query_dict['expiration'] = expiration server_token = self._do_post(url=self._token_url, param_dict=query_dict, securityHandler=None, proxy_port=self._proxy_port, proxy_url=self._proxy_url) if 'error' in server_token: self._server_token = None self._server_token_created_on = None self._server_token_expires_on = None self._server_expires_in = None return server_token else: self._server_token = server_token['token'] self._server_token_created_on = datetime.datetime.now() self._server_token_expires_on = datetime.datetime.fromtimestamp(server_token['expires'] /1000) - \ datetime.timedelta(seconds=1) self._server_expires_in = (self._server_token_expires_on - self._server_token_created_on).total_seconds() return server_token['token'] ######################################################################## class AGOLTokenSecurityHandler(abstract.BaseSecurityHandler): """ handles ArcGIS Online Token Base Security username - required - username to access AGOL services password - required - password for username above org_url - The url of that ArcGIS Organization. This url is composed on the machine name and the instance name of the portal. For example: http://myportal.mycompany.com/portal for a Portal for ArcGIS Server instance. - http://www.arcgis.com for ArcGIS Online - http://myOnlineOrg.maps.arcgis.com for ArcGIS Online, but the unique url for your org token_url - optional - if URL is different than default AGOL token url, then enter it here for AGOL token service. proxy_url - optional - if proxy is required to access internet, the IP goes here. proxy_post - optional - if proxy is used and it's not port 90 enter it here. """ _token = None _surl = None _org_url ="http://www.arcgis.com" _url = "https://www.arcgis.com/sharing/rest" _parsed_org_url = "http://www.arcgis.com" _referer_url = None _method = "TOKEN" _username = None _password = None _token_url = None _default_token_url = 'https://arcgis.com/sharing/rest/generateToken' _token_created_on = None _token_expires_on = None _expires_in = None _proxy_url = None _proxy_port = None #---------------------------------------------------------------------- def __init__(self, username, password, org_url ="https://www.arcgis.com", token_url=None, proxy_url=None, proxy_port=None): """Constructor""" self._username = username self._password = password self._token_url = token_url self._org_url = org_url self._proxy_port = proxy_port self._proxy_url = proxy_url self._token_expires_on = datetime.datetime.now() + datetime.timedelta(seconds=_defaultTokenExpiration) self._initURL(org_url=org_url,token_url=token_url) #---------------------------------------------------------------------- def _initURL(self, org_url=None, token_url=None, referer_url=None): """ sets proper URLs for AGOL """ if org_url is not None and org_url != '': if not org_url.startswith('http://') and not org_url.startswith('https://'): org_url = 'http://' + org_url self._org_url = org_url if not self._org_url.startswith('http://') and not self._org_url.startswith('https://'): self._org_url = 'http://' + self._org_url if self._org_url.lower().find('/sharing/rest') > -1: self._url = self._org_url else: self._url = self._org_url + "/sharing/rest" if self._url.startswith('http://'): self._surl = self._url.replace('http://', 'https://') else: self._surl = self._url if token_url is None: results = self._do_get(url= self._surl + '/info', param_dict={'f':'json'}, header=None, proxy_port=self._proxy_port, proxy_url=self._proxy_url) if 'authInfo' in results and 'tokenServicesUrl' in results['authInfo']: self._token_url = results['authInfo']['tokenServicesUrl'] else: self._token_url = self._surl + '/generateToken' else: self._token_url = token_url parsed_url = urlparse(self._org_url) self._parsed_org_url = urlunparse((parsed_url[0],parsed_url[1],"","","","")) if referer_url is None: self._referer_url = parsed_url.netloc #if referer_url is None or \ #referer_url.lower().find('www.arcgis.com') > -1: #self._referer_url = "arcgis.com" #else: #self._referer_url = referer_url _is_portal = None #---------------------------------------------------------------------- @property def is_portal(self): if self._is_portal is None: self.check_portal() return self._is_portal def check_portal(self): from ..manageorg import Administration admin = Administration(url=self._org_url, securityHandler=self) portal = admin.portals.portalSelf self._is_portal = portal.isPortal #---------------------------------------------------------------------- def __getRefererUrl(self, url=None): """ gets the referer url for the token handler """ if url is None: url = "http://www.arcgis.com/sharing/rest/portals/self" params = { "f" : "json", "token" : self.token } val = self._do_get(url=url, param_dict=params, proxy_url=self._proxy_url, proxy_port=self._proxy_port) self._referer_url = "arcgis.com"#"http://%s.%s" % (val['urlKey'], val['customBaseUrl']) self._token = None return self._referer_url #---------------------------------------------------------------------- @property def method(self): """returns the handler method""" return self._method #---------------------------------------------------------------------- @property def org_url(self): """ gets/sets the organization URL """ return self._org_url #---------------------------------------------------------------------- @org_url.setter def org_url(self, value): """ gets/sets the organization URL """ if value is not None: self._org_url = value #---------------------------------------------------------------------- @property def proxy_url(self): """gets the proxy url""" return self._proxy_url #---------------------------------------------------------------------- @proxy_url.setter def proxy_url(self, value): """ sets the proxy_url """ self._proxy_url = value #---------------------------------------------------------------------- @property def proxy_port(self): """ gets the proxy port """ return self._proxy_port #---------------------------------------------------------------------- @proxy_port.setter def proxy_port(self, value): """ sets the proxy port """ if isinstance(value, int): self._proxy_port = value #---------------------------------------------------------------------- @property def username(self): """ returns the username """ return self._username #---------------------------------------------------------------------- @username.setter def username(self, username): """ sets the username """ self._token = None self._username = username #---------------------------------------------------------------------- @property def password(self): """ returns **** for the password """ return "****" #---------------------------------------------------------------------- @password.setter def password(self, value): """ sets the password """ self._token = None self._password = value #---------------------------------------------------------------------- @property def token_url(self): """ returns the token url """ if self._token_url is None: return self._default_token_url return self._token_url #---------------------------------------------------------------------- @token_url.setter def token_url(self, value): """ sets the token url """ self._token = None self._token_url = value #---------------------------------------------------------------------- def resetTokenURLToDefault(self): """ resets the token url to the default url """ self._token = None self._token_url = self._default_token_url #---------------------------------------------------------------------- @property def tokenExperationDate(self): """ returns when the token is not valid """ return self._token_expires_on #---------------------------------------------------------------------- @property def tokenObtainedDate(self): """ returns when the token was generated """ return self._token_created_on #---------------------------------------------------------------------- @property def referer_url(self): """ returns when the token was generated """ return self._referer_url #---------------------------------------------------------------------- @property def token(self): """ returns the token for the site """ if self._token is None or \ datetime.datetime.now() >= self._token_expires_on: result = self._generateForTokenSecurity(username=self._username, password=self._password, referer=self._referer_url, tokenUrl=self._token_url) if 'error' in result: self._valid = False self._message = result else: self._valid = True self._message = "Token Generated" return self._token #---------------------------------------------------------------------- def _generateForTokenSecurity(self, username, password, referer=None, tokenUrl=None, expiration=None, proxy_url=None, proxy_port=None): """ generates a token for a feature service """ if referer is None: referer = self._referer_url if tokenUrl is None: tokenUrl = self._token_url query_dict = {'username': self._username, 'password': self._password, 'expiration': str(_defaultTokenExpiration), 'referer': referer, 'f': 'json'} if expiration is not None: query_dict['expiration'] = str(expiration) self._token_created_on = datetime.datetime.now() token = self._do_post(url=tokenUrl, param_dict=query_dict, securityHandler=None, proxy_port=self._proxy_port, proxy_url=self._proxy_url) if 'error' in token: self._token = None return token self._token_expires_on = datetime.datetime.fromtimestamp(token['expires'] /1000) - \ datetime.timedelta(seconds=1) #if token['expires'] > 86400: #seconds = 86400 #else: #seconds = int(token['expires']) #self._token_expires_on = self._token_created_on + \ #datetime.timedelta(seconds=seconds) if "token" not in token: self._token = None return None else: httpPrefix = self._url if token['ssl'] == True: httpPrefix = self._surl self._token = token['token'] return token['token'], httpPrefix ######################################################################### class AGSTokenSecurityHandler(abstract.BaseSecurityHandler): """ handles ArcGIS Server Security username - required - person accessing server password - required - login credential token_url - required - URL to generate a token on server proxy_url - optional - IP of proxy proxy_port - optional - port of the proxy server """ _method = "TOKEN" _token = None _username = None _password = None _token_url = None _token_created_on = None _token_expires_on = None _expires_in = None _proxy_url = None _proxy_port = None _default_token_url = None _referer_url = None _org_url = None #---------------------------------------------------------------------- def __init__(self, username, password, org_url=None, token_url=None, proxy_url=None, proxy_port=None): """Constructor""" self._username = username self._password = password self._token_url = token_url self._org_url = org_url self._proxy_port = proxy_port self._proxy_url = proxy_url self._token_expires_on = datetime.datetime.now() + datetime.timedelta(seconds=_defaultTokenExpiration) if token_url is None and \ not org_url is None: params = {"f":"json"} parts = urlparse(org_url) p = parts.path[1:].strip().split('/')[0] url = "%s://%s/%s/rest/info" % (parts.scheme, parts.netloc, p) result = self._do_get(url=url, param_dict=params, securityHandler=None, proxy_url=proxy_url, proxy_port=proxy_port) if 'authInfo' in result and \ 'tokenServicesUrl' in result['authInfo']: self._token_url = result['authInfo']['tokenServicesUrl'] else: raise Exception("Cannot determine the token url, please pass that parameter.") #---------------------------------------------------------------------- @property def method(self): """returns the handler method""" return self._method #---------------------------------------------------------------------- @property def proxy_url(self): """gets the proxy url""" return self._proxy_url #---------------------------------------------------------------------- @proxy_url.setter def proxy_url(self, value): """ sets the proxy_url """ self._proxy_url = value #---------------------------------------------------------------------- @property def proxy_port(self): """ gets the proxy port """ return self._proxy_port #---------------------------------------------------------------------- @proxy_port.setter def proxy_port(self, value): """ sets the proxy port """ if isinstance(value, int): self._proxy_port = value #---------------------------------------------------------------------- @property def username(self): """ returns the username """ return self._username #---------------------------------------------------------------------- @username.setter def username(self, username): """ sets the username """ self._token = None self._username = username #---------------------------------------------------------------------- @property def password(self): """ returns **** for the password """ return "****" #---------------------------------------------------------------------- @password.setter def password(self, value): """ sets the password """ self._token = None self._password = value #---------------------------------------------------------------------- @property def token_url(self): """ returns the token url """ return self._token_url #---------------------------------------------------------------------- @token_url.setter def token_url(self, value): """ sets the token url """ self._token = None self._token_url = value #---------------------------------------------------------------------- @property def tokenExperationDate(self): """ returns when the token is not valid """ return self._token_expires_on #---------------------------------------------------------------------- @property def tokenObtainedDate(self): """ returns when the token was generated """ return self._token_created_on #---------------------------------------------------------------------- @property def token(self): """ returns the token for the site """ if self._token is None or \ datetime.datetime.now() >= self._token_expires_on: self._generateForTokenSecurity(username=self._username, password=self._password, tokenUrl=self._token_url) return self._token #---------------------------------------------------------------------- @property def referer_url(self): """ returns when the token was generated """ return self._referer_url #---------------------------------------------------------------------- def _generateForTokenSecurity(self, username, password, tokenUrl, expiration=None): """ generates a token for a feature service """ query_dict = {'username': username, 'password': password, 'expiration': str(_defaultTokenExpiration), 'client': 'requestip', 'f': 'json'} if expiration is not None: query_dict['expiration'] = expiration token = self._do_post(url=tokenUrl, param_dict=query_dict, securityHandler=None, proxy_port=self._proxy_port, proxy_url=self._proxy_url) if "token" not in token: self._token = None self._token_created_on = None self._token_expires_on = None self._expires_in = None return None else: self._token = token['token'] self._token_created_on = datetime.datetime.now() #if token['expires'] > 86400: #seconds = 86400 #else: #seconds = int(token['expires']) #self._token_expires_on = self._token_created_on + datetime.timedelta(seconds=seconds) self._token_expires_on = datetime.datetime.fromtimestamp(int(token['expires']) /1000) - datetime.timedelta(seconds=1) self._expires_in = (self._token_expires_on - self._token_created_on).total_seconds() return token['token'] ######################################################################## class PortalTokenSecurityHandler(abstract.BaseSecurityHandler): """ Handles connection to a Portal Site Inputs: username - name of the user password - password for user org_url - The url of that ArcGIS Organization. This url is composed on the machine name and the instance name of the portal. For example: http://myportal.mycompany.com/portal for a Portal for ArcGIS Server instance. - http://www.arcgis.com for ArcGIS Online - http://myOnlineOrg.maps.arcgis.com for ArcGIS Online, but the unique url for your org proxy_url - URL of the proxy proxy_port - proxy port """ _token = None _server_token = None _server_token_expires_on = None _server_token_created_on = None _server_expires_in = None _server_url = None _org_url = None _url = None _surl = None _parsed_org_url = None _username = None _password = None _proxy_port = None _proxy_url = None _token_url = None _token_created_on = None _token_expires_on = None _expires_in = None _method = "TOKEN" #Added for testing _handler = None _jar = None def __init__(self, username, password, org_url, token_url=None, proxy_url=None, proxy_port=None, handler=None, jar=None): """Constructor""" self._org_url = org_url self._username = username self._password = password self._token_url = token_url self._proxy_port = proxy_port self._proxy_url = proxy_url self._token_expires_on = datetime.datetime.now() + datetime.timedelta(seconds=_defaultTokenExpiration) self._jar = jar self._handler = handler self._initURL(org_url=org_url, token_url=token_url, referer_url=None) #---------------------------------------------------------------------- def _initURL(self, org_url=None, token_url=None, referer_url=None): """ sets proper URLs for AGOL """ if org_url is not None and org_url != '': if not org_url.startswith('http://') and not org_url.startswith('https://'): org_url = 'http://' + org_url self._org_url = org_url if not self._org_url.startswith('http://') and not self._org_url.startswith('https://'): self._org_url = 'http://' + self._org_url if self._org_url.lower().find('/sharing/rest') > -1: self._url = self._org_url self._org_url = str(self._org_url).replace('/sharing/rest','') else: self._url = self._org_url + "/sharing/rest" if self._url.startswith('http://'): self._surl = self._url.replace('http://', 'https://') else: self._surl = self._url if token_url is None: results = self._do_get(url= self._surl + '/portals/info', param_dict={'f':'json'}, securityHandler=None, header=None, proxy_port=self._proxy_port, proxy_url=self._proxy_url) if 'authInfo' in results and 'tokenServicesUrl' in results['authInfo']: self._token_url = results['authInfo']['tokenServicesUrl'] else: self._token_url = self._surl + '/generateToken' else: self._token_url = token_url parsed_url = urlparse(self._org_url) self._parsed_org_url = urlunparse((parsed_url[0],parsed_url[1],"","","","")) if referer_url is None: self._referer_url = parsed_url.netloc _is_portal = None #---------------------------------------------------------------------- @property def is_portal(self): if self._is_portal is None: self.check_portal() return self._is_portal #---------------------------------------------------------------------- def check_portal(self): from ..manageorg import Administration admin = Administration(url=self._org_url, securityHandler=self) portal = admin.portals.portalSelf self._is_portal = portal.isPortal #---------------------------------------------------------------------- @property def method(self): """returns the handler method""" return self._method #---------------------------------------------------------------------- @property def org_url(self): """ gets/sets the organization URL """ return self._org_url #---------------------------------------------------------------------- @property def proxy_url(self): """gets the proxy url""" return self._proxy_url #---------------------------------------------------------------------- @proxy_url.setter def proxy_url(self, value): """ sets the proxy_url """ self._proxy_url = value #---------------------------------------------------------------------- @property def proxy_port(self): """ gets the proxy port """ return self._proxy_port #---------------------------------------------------------------------- @proxy_port.setter def proxy_port(self, value): """ sets the proxy port """ if isinstance(value, int): self._proxy_port = value #---------------------------------------------------------------------- @property def username(self): """ returns the username """ return self._username #---------------------------------------------------------------------- @username.setter def username(self, username): """ sets the username """ self._token = None self._username = username #---------------------------------------------------------------------- @property def password(self): """ returns **** for the password """ return "****" #---------------------------------------------------------------------- @password.setter def password(self, value): """ sets the password """ self._token = None self._password = value #---------------------------------------------------------------------- @property def token_url(self): """ returns the token url """ return self._token_url #---------------------------------------------------------------------- @token_url.setter def token_url(self, value): """ sets the token url """ self._token = None self._token_url = value #---------------------------------------------------------------------- @property def tokenExperationDate(self): """ returns when the token is not valid """ return self._token_expires_on #---------------------------------------------------------------------- @property def tokenObtainedDate(self): """ returns when the token was generated """ return self._token_created_on #---------------------------------------------------------------------- @property def referer_url(self): """ returns when the token was generated """ return self._referer_url #---------------------------------------------------------------------- @property def token(self): """ returns the token for the site """ if self._token is None or \ datetime.datetime.now() >= self._token_expires_on: result = self._generateForTokenSecurity(username=self._username, password=self._password, tokenUrl=self._token_url) if 'error' in result: self._valid = False self._message = result else: self._valid = True self._message = "Token Generated" return self._token #---------------------------------------------------------------------- @property def cookiejar(self): """gets the cookiejar""" return self._jar #---------------------------------------------------------------------- @cookiejar.setter def cookiejar(self, value): """gets/sets a cookiejar""" if value is not None: self._jar = value #---------------------------------------------------------------------- @property def handler(self): """gets/sets a handler""" return self._handler #---------------------------------------------------------------------- @handler.setter def handler(self, value): """gets/sets a handler""" if value is not None: self._handler = value #---------------------------------------------------------------------- def servertoken(self,serverURL,referer): """ returns the server token for the server """ if self._server_token is None or self._server_token_expires_on is None or \ datetime.datetime.now() >= self._server_token_expires_on or \ self._server_url != serverURL: self._server_url = serverURL result = self._generateForServerTokenSecurity(serverURL=serverURL, token=self.token, tokenUrl=self._token_url, referer=referer) if 'error' in result: self._valid = False self._message = result else: self._valid = True self._message = "Server Token Generated" return self._server_token #---------------------------------------------------------------------- def _generateForServerTokenSecurity(self, serverURL, token, tokenUrl, referer, expiration=None ): """ generates a token for a feature service """ query_dict = {'serverURL':serverURL, 'token': token, 'expiration':str(_defaultTokenExpiration), 'f': 'json', 'request':'getToken', 'referer':referer} if expiration is not None: query_dict['expiration'] = expiration secHandler = None if self.cookiejar is not None: secHandler = self if secHandler is not None: secHandler._method = "HANDLER" server_token = self._do_post(url=tokenUrl, param_dict=query_dict, securityHandler=secHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url) if self.cookiejar is not None: if secHandler is not None: secHandler._method = "TOKEN" if 'error' in server_token: self._server_token = None self._server_token_created_on = None self._server_token_expires_on = None self._server_expires_in = None return server_token else: self._server_token = server_token['token'] self._server_token_created_on = datetime.datetime.now() self._server_token_expires_on = datetime.datetime.fromtimestamp(server_token['expires'] /1000) - \ datetime.timedelta(seconds=1) self._server_expires_in = (self._server_token_expires_on - self._server_token_created_on).total_seconds() return server_token['token'] #---------------------------------------------------------------------- def _generateForTokenSecurity(self, username, password, tokenUrl, expiration=None): """ generates a token for a feature service """ query_dict = {'username': username, 'password': password, 'expiration':str(_defaultTokenExpiration), 'client': 'requestip', 'f': 'json'} if expiration is not None: query_dict['expiration'] = expiration secHandler = None if self.cookiejar is not None: secHandler = self if secHandler is not None: secHandler._method = "HANDLER" token = self._do_post(url=tokenUrl, param_dict=query_dict, securityHandler=secHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url) if self.cookiejar is not None: if secHandler is not None: secHandler._method = "TOKEN" if 'error' in token: self._token = None self._token_created_on = None self._token_expires_on = None self._expires_in = None return token elif 'status' in token: self._token = None self._token_created_on = None self._token_expires_on = None self._expires_in = None #print token['message'] return token else: self._token = token['token'] self._token_created_on = datetime.datetime.now() self._token_expires_on = datetime.datetime.fromtimestamp(token['expires'] /1000) - \ datetime.timedelta(seconds=1) self._expires_in = (self._token_expires_on - self._token_created_on).total_seconds() return token['token'] #---------------------------------------------------------------------- def portalServerHandler(self, serverUrl, username=None): """ returns a handler to access a federated server serverUrl - url to the server. Example: https://server.site.com/arcgis username - the portal site username. if None is passed, it obtains it from the portal properties Outout: returns a PortalServerSecurityHandler object Usage: >>> # access the administration site >>> serverUrl="https://mysite.site.com/arcgis" >>> newSH = sh.portalServerHandler(serverUrl=serverUrl, username=None) >>> agsAdmin = AGSAdministration(url=serverUrl, securityHandler=newSH) >>> print agsAdmin.info >>> # access a secure service from portal handler >>> msUrl = "https://mysite.site.com:6443/arcgis/rest/services/SampleWorldCities/MapServer" >>> ms = arcrest.ags.MapService(url=msUrl, securityHandler=newSH) >>> print ms.mapName """ pssh = PortalServerSecurityHandler(tokenHandler=self, serverUrl=serverUrl, referer=self._referer_url) return pssh
""" Tools for working with streams. """ from collections import deque from zlib import decompressobj from zlib import MAX_WBITS __all__ = ("BufferedIStream", "FilteredIStream", "FilteredOStream", "GzippedIStream") class _StreamAdaptor(object): """ Abstract base class for a stream adaptor. """ def __init__(self, stream): """ Initialize this object. The adaptor assumes responsibility for closing the stream when the adaptor's close() method is called or when exiting a context block. """ self._stream = stream return def close(self): """ Close the adaptor and its stream. """ try: self._stream.close() except AttributeError: # no close() pass return class _IStreamAdaptor(_StreamAdaptor): """ Abstract base class for an input stream adaptor. This can be used to make an input stream compatible with the Reader stream protocol. """ def __next__(self): """ Return the next line of text from a stream. """ raise NotImplementedError def __iter__(self): """ Return an iterator for this stream. """ return self class BufferedIStream(_IStreamAdaptor): """ Add buffering to an input stream. The buffered stream can be rewound to lines previously retrieved via the next() method. """ def __init__(self, stream, buflen=1): """ Initialize this object. """ super(BufferedIStream, self).__init__(stream) self._buffer = deque(maxlen=buflen) while len(self._buffer) < buflen: # Fill the buffer one record at a time. try: self._buffer.append(next(self._stream)) except StopIteration: # stream is exhausted # Don't raise StopIteration until self.next() is called with an # exhausted buffer. break self._bufpos = 0 # always points to the current record return def __next__(self): """ Return the next line of text. If the stream has been rewound this will return the first buffered line, otherwise the next line from the input stream. """ try: line = self._buffer[self._bufpos] self._bufpos += 1 except IndexError: # At the end of the buffer so get a new line. line = next(self._stream) self._buffer.append(line) # pops _buffer[0] return line def rewind(self, count=None): """ Rewind the buffer. By default rewind to the beginning of the buffer. """ self._bufpos = 0 if count is None else max(0, self._bufpos - count) return def close(self): """ Close the adaptor and its stream. """ super(BufferedIStream, self).close() self._buffer.clear() self._bufpos = 0 return class FilteredIStream(_IStreamAdaptor): """ Add filtering to an input stream. Stream filters are applied before the stream input is parsed by the Reader; this can be faster than using Reader filters. A filter is a callable object that accepts a line from the stream's next() method and performs one of the following actions: 1. Return None to reject the line (it will not be passed to the reader). 2. Return the line as is. 3. Return a new/modified line. 4. Raise StopIteration to signal the end of input. """ def __init__(self, stream): """ Initialize this object. """ super(FilteredIStream, self).__init__(stream) self._filters = [] return def filter(self, *callbacks): """ Add filters to this stream or clear all filters (default). """ if not callbacks: self._filters = [] else: self._filters.extend(callbacks) return def __next__(self): """ Return the next filtered line from the stream. """ # Recursion would simplify this, but would fail for any combination of # filters that rejected more than 1000 consecutive lines (the Python # recursion limit). line = None while line is None: # Repeat until a line passes all filters. line = next(self._stream) for callback in self._filters: # Apply each filter in order. Stop as soon as the line fails # a filter. line = callback(line) if line is None: break return line class GzippedIStream(_IStreamAdaptor): """ Add gzip/zlib decompression to a text input stream. Unlike the Python gzip module, this will work with streaming data, e.g. a urlopen() stream. """ read_size = 1024 # bytes; adjust to maximize performance def __init__(self, stream): """ Initialize this object. The input stream must implement a read() method that returns a user- specified number of bytes, e.g. any file-like object. """ super(GzippedIStream, self).__init__(stream) self._decode = decompressobj(MAX_WBITS + 32).decompress self._buffer = b"" return def __next__(self): """ Return the next line of text. """ def read(): """ Retrieve decompressed data from the stream. """ # The block size is based on the compressed data; the returned data # size may be different. data = self._stream.read(self.read_size) if not data: # Check for EOF before decoding because the decoded value will # be an empty string if data does not contain a complete # encoded sequence. return False self._buffer += self._decode(data) return True endl = "\n".encode() while True: # Find the end of the next complete line. try: pos = self._buffer.index(endl) + len(endl) # include \n except ValueError: # \n not found # Keep going as long as the stream is still good, otherwise # this is the last line (the newline is missing). if read(): continue pos = len(self._buffer) break if not self._buffer: raise StopIteration line = self._buffer[:pos].decode() self._buffer = self._buffer[pos:] return line class _OStreamAdaptor(_StreamAdaptor): """ Abstract base class for an output stream adaptor. This can be used to make an output stream compatible with the Writer stream protocol. """ def write(self, line): """ Write a line of text to the stream. """ raise NotImplementedError class FilteredOStream(_OStreamAdaptor): """ Add filtering to an output stream. Stream filters are applied to the text output after it has been generated by the Writer. This can be used, for example, to apply low-level text formatting. A filter is a callable object that accepts a line of text and performs one of the following actions: 1. Return None to reject the line (it will not be written to the stream). 2. Return the line as is. 3. Return a new/modified line. """ def __init__(self, stream): """ Initialize this object. """ super(FilteredOStream, self).__init__(stream) self._filters = [] return def filter(self, *callbacks): """ Add filters to this stream or clear all filters (default). """ if not callbacks: self._filters = [] else: self._filters.extend(callbacks) return def write(self, line): """ Write a filtered line to the stream. """ for callback in self._filters: # Apply each filter to the line. line = callback(line) if line is None: return self._stream.write(line) return
from __future__ import print_function from __future__ import absolute_import from builtins import next from builtins import str from builtins import range from past.builtins import basestring import tensorflow as tf import numpy as np import os import shutil import time from .layers import * from .classes import * flags = tf.app.flags FLAGS = flags.FLAGS logging = tf.logging flags.DEFINE_float('gpu_mem', 1.0, "Fraction of gpu memory to be used.") flags.DEFINE_float('reg', 1e-8, "weight on the regularizer") flags.DEFINE_string('project', 'tfs', "top level directory which contains summaries, saved models.") flags.DEFINE_string('name', 'unamed_run', "top level directory which contains summaries, saved models.") flags.DEFINE_string('base_path', '/home/girish.varma/', "top level directory which contains summaries, saved models.") flags.DEFINE_integer("B", 100, "batch size") flags.DEFINE_float("rate", 0.001, "learning rate") flags.DEFINE_bool("new", False, "Delete the previous run with same name and start new.") flags.DEFINE_integer("threads", 8, "threads") flags.DEFINE_boolean('load', False, "Load model") allow_soft_placement = True log_device_placement = False def training_loop(ctrl, model, test = False): if FLAGS.load and 'saver' in ctrl.keys(): ctrl['saver'].restore(ctrl['sess'], tf.train.latest_checkpoint(FLAGS.base_path + FLAGS.project+ '/model/' +FLAGS.name)) step = 0 try: start = time.time() while not ctrl['coord'].should_stop(): try: summ, step = model.train(ctrl['sess']) if 'writer' in ctrl.keys(): ctrl['writer'].add_summary(summ, step*FLAGS.B) if step % 10 == 0: if 'writer' in ctrl.keys(): ctrl['writer'].flush() if step % 10 == 0 and test: summ = model.validate(ctrl['sess']) if 'writer' in ctrl.keys(): ctrl['writer'].add_summary(summ, step*FLAGS.B) ctrl['writer'].flush() if 'saver' in ctrl.keys(): ctrl['saver'].save(ctrl['sess'], FLAGS.base_path + FLAGS.project+ '/model/' +FLAGS.name, global_step = step) end = time.time() - start print('time for 10 steps ', end, '. Samples seen ', step *FLAGS.B) start = time.time() except tf.errors.DataLossError as err: print(err.message) except tf.errors.OutOfRangeError: print('Training done') if 'saver' in ctrl.keys(): ctrl['saver'].save(ctrl['sess'], FLAGS.base_path + 'model/' + FLAGS.name, global_step = step) finally: ctrl['coord'].request_stop() if 'saver' in ctrl.keys(): ctrl['saver'].save(ctrl['sess'], FLAGS.base_path + "model/" + FLAGS.name, global_step = step) ctrl['coord'].join(ctrl['threads']) ctrl['sess'].close() def find_class_by_name(name, modules): """Searches the provided modules for the named class and returns it.""" modules = [getattr(module, name, None) for module in modules] return next(a for a in modules if a) def create_folders(): if not os.path.exists(FLAGS.base_path + FLAGS.project): os.makedirs(FLAGS.base_path + FLAGS.project) if not os.path.exists(FLAGS.base_path + FLAGS.project + '/model'): os.makedirs(FLAGS.base_path + FLAGS.project + '/model') if not os.path.exists(FLAGS.base_path + FLAGS.project + '/summary'): os.makedirs(FLAGS.base_path + FLAGS.project + '/summary') if not os.path.exists(FLAGS.base_path + FLAGS.project+ '/model/' +FLAGS.name ): os.makedirs(FLAGS.base_path + FLAGS.project+ '/model/' +FLAGS.name ) if not os.path.exists(FLAGS.base_path + FLAGS.project+ '/summary/' +FLAGS.name ): os.makedirs(FLAGS.base_path + FLAGS.project+ '/summary/' +FLAGS.name ) model_path = FLAGS.base_path + FLAGS.project+ '/model/' +FLAGS.name summary_path = FLAGS.base_path + FLAGS.project+ '/summary/' +FLAGS.name if os.path.exists(model_path) and not FLAGS.load: shutil.rmtree(model_path) if os.path.exists(summary_path) and not FLAGS.load: shutil.rmtree(summary_path) if not os.path.exists(model_path): os.makedirs(model_path) if not os.path.exists(summary_path): os.makedirs(summary_path) def session(): config = tf.ConfigProto(allow_soft_placement=allow_soft_placement,log_device_placement=log_device_placement) config.gpu_options.per_process_gpu_memory_fraction=FLAGS.gpu_mem # don't hog all vRAM config.gpu_options.allow_growth=True sess = tf.Session(config=config) return sess def init_tf(writer = False, saver = False, coord = False): create_folders() sess = session() output = {'sess': sess} init = tf.global_variables_initializer() sess.run(init) sess.run(tf.local_variables_initializer()) if writer: output['writer'] = tf.summary.FileWriter(FLAGS.base_path + FLAGS.project+ '/summary/' +FLAGS.name, sess.graph) if saver: output['saver'] = tf.train.Saver(var_list= tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)) if coord: output['coord'] = coord = tf.train.Coordinator() output['threads'] = tf.train.start_queue_runners(sess=sess, coord=coord) return output def shape(x): return x.get_shape().as_list() def match(y, y_pred, name = 'match'): with tf.variable_scope(name): accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_pred,1), tf.argmax(y,1)), tf.float32)) return accuracy def softmax_cross_entropy(y, y_pred, name = 'softmax_cross_entropy'): return tf.losses.softmax_cross_entropy(y, y_pred) def classify(y, y_pred, y_val = None, y_pred_val = None, **kwargs): loss = kwargs.get('loss', softmax_cross_entropy) acc = kwargs.get('acc', match) with tf.variable_scope('train_loss_acc'): train_loss = loss(y, y_pred) train_acc = acc(y, y_pred) train_reg = sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)) total_train_loss = train_loss + FLAGS.reg*train_reg train_summary = [ tf.summary.scalar('loss', train_loss), tf.summary.scalar('accuracy', train_acc), tf.summary.scalar('regularizer', train_reg), tf.summary.scalar('total_loss', total_train_loss) ] optimizer, rate, global_step = minimize(total_train_loss, **kwargs) train_summary += [tf.summary.scalar('learning_rate', rate)] valid_summary = [] if y_val != None: with tf.variable_scope('valid_loss_acc'): valid_loss = loss(y_val, y_pred_val) valid_acc = acc(y_val, y_pred_val) valid_summary += [ tf.summary.scalar('loss', valid_loss), tf.summary.scalar('accuracy', valid_acc) ] model_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) for i in model_vars: valid_summary += [tf.summary.histogram(i.op.name, i)] return optimizer, tf.summary.merge(train_summary), tf.summary.merge(valid_summary), global_step def minimize(loss_tensor, **kwargs): algo = kwargs.get('algo', 'adam') rate = kwargs.get('rate', 0.01) name = kwargs.get('name', 'optimizer') grad_clip = kwargs.get('grad_clip', 1.0) global_step = tf.Variable(0, trainable=False, name="global_step") learning_rate = tf.train.exponential_decay( rate, global_step * FLAGS.B, kwargs.get('learning_rate_decay_examples', 4000000), kwargs.get('learning_rate_decay', 0.95), staircase=True) with tf.variable_scope(name): optimizer = None if algo == 'adam': optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) elif algo == 'sgd': optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) elif algo == 'momentum': optimizer = tf.train.MomentumOptimizer(learning_rate, kwargs.get('momentum', None)) gvs = optimizer.compute_gradients(loss_tensor) if grad_clip != 0. : gvs = [(tf.clip_by_value(grad, -grad_clip, grad_clip), var) for grad, var in gvs] train_op = optimizer.apply_gradients(gvs, global_step = global_step) return train_op, learning_rate, global_step def sequential(x, net, defaults = {}, name = '', reuse = None, var = {}, layers = {}): layers = dict(list(layers.items()) + list(predefined_layers.items())) y = x logging.info('Building Sequential Network : %s', name) with tf.variable_scope(name, reuse = reuse): for i in range(len(net)): ltype = net[i][0] lcfg = net[i][1] if len(net[i]) == 2 else {} lname = lcfg.get('name', ltype + str(i)) ldefs = defaults.get(ltype, {}) lcfg = dict(list(ldefs.items()) + list(lcfg.items())) for k, v in list(lcfg.items()): if isinstance(v, basestring) and v[0] == '$': # print var, v lcfg[k] = var[v[1:]] y = layers[ltype](y, lname, **lcfg) logging.info('\t %s \t %s', lname, y.get_shape().as_list()) return y
#!/usr/bin/python3 # # Copyright (C) 2010, 2011, 2012 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Script for testing ganeti.backend""" import os import sys import unittest from ganeti import utils from ganeti import opcodes from ganeti import opcodes_base from ganeti import ht from ganeti import constants from ganeti import errors from ganeti import compat import testutils class TestOpcodes(unittest.TestCase): def test(self): self.assertRaises(ValueError, opcodes.OpCode.LoadOpCode, None) self.assertRaises(ValueError, opcodes.OpCode.LoadOpCode, "") self.assertRaises(ValueError, opcodes.OpCode.LoadOpCode, {}) self.assertRaises(ValueError, opcodes.OpCode.LoadOpCode, {"OP_ID": ""}) for cls in opcodes.OP_MAPPING.values(): self.assertTrue(cls.OP_ID.startswith("OP_")) self.assertTrue(len(cls.OP_ID) > 3) self.assertEqual(cls.OP_ID, cls.OP_ID.upper()) self.assertEqual(cls.OP_ID, opcodes_base._NameToId(cls.__name__)) self.assertFalse( compat.any(cls.OP_ID.startswith(prefix) for prefix in opcodes_base.SUMMARY_PREFIX.keys())) self.assertTrue(callable(cls.OP_RESULT), msg=("%s should have a result check" % cls.OP_ID)) self.assertRaises(TypeError, cls, unsupported_parameter="some value") args = [ # No variables {}, # Variables supported by all opcodes {"dry_run": False, "debug_level": 0, }, # All variables dict([(name, []) for name in cls.GetAllSlots()]) ] for i in args: op = cls(**i) self.assertEqual(op.OP_ID, cls.OP_ID) self._checkSummary(op) # Try a restore state = op.__getstate__() self.assertTrue(isinstance(state, dict)) restored = opcodes.OpCode.LoadOpCode(state) self.assertTrue(isinstance(restored, cls)) self._checkSummary(restored) for name in ["x_y_z", "hello_world"]: assert name not in cls.GetAllSlots() for value in [None, True, False, [], "Hello World"]: self.assertRaises(AttributeError, setattr, op, name, value) def _checkSummary(self, op): summary = op.Summary() if hasattr(op, "OP_DSC_FIELD"): self.assertTrue(("OP_%s" % summary).startswith("%s(" % op.OP_ID)) self.assertTrue(summary.endswith(")")) else: self.assertEqual("OP_%s" % summary, op.OP_ID) def testSummary(self): class OpTest(opcodes.OpCode): OP_DSC_FIELD = "data" OP_PARAMS = [ ("data", ht.NoDefault, ht.TString, None), ] self.assertEqual(OpTest(data="").Summary(), "TEST()") self.assertEqual(OpTest(data="Hello World").Summary(), "TEST(Hello World)") self.assertEqual(OpTest(data="node1.example.com").Summary(), "TEST(node1.example.com)") def testSummaryFormatter(self): class OpTest(opcodes.OpCode): OP_DSC_FIELD = "data" OP_DSC_FORMATTER = lambda _, v: "a" OP_PARAMS = [ ("data", ht.NoDefault, ht.TString, None), ] self.assertEqual(OpTest(data="").Summary(), "TEST(a)") self.assertEqual(OpTest(data="b").Summary(), "TEST(a)") def testTinySummary(self): self.assertFalse( utils.FindDuplicates(opcodes_base.SUMMARY_PREFIX.values())) self.assertTrue(compat.all(prefix.endswith("_") and supplement.endswith("_") for (prefix, supplement) in opcodes_base.SUMMARY_PREFIX.items())) self.assertEqual(opcodes.OpClusterPostInit().TinySummary(), "C_POST_INIT") self.assertEqual(opcodes.OpNodeRemove().TinySummary(), "N_REMOVE") self.assertEqual(opcodes.OpInstanceMigrate().TinySummary(), "I_MIGRATE") self.assertEqual(opcodes.OpTestJqueue().TinySummary(), "TEST_JQUEUE") def testListSummary(self): class OpTest(opcodes.OpCode): OP_DSC_FIELD = "data" OP_PARAMS = [ ("data", ht.NoDefault, ht.TList, None), ] self.assertEqual(OpTest(data=["a", "b", "c"]).Summary(), "TEST(a,b,c)") self.assertEqual(OpTest(data=["a", None, "c"]).Summary(), "TEST(a,None,c)") self.assertEqual(OpTest(data=[1, 2, 3, 4]).Summary(), "TEST(1,2,3,4)") def testOpId(self): self.assertFalse(utils.FindDuplicates(cls.OP_ID for cls in opcodes._GetOpList())) self.assertEqual(len(opcodes._GetOpList()), len(opcodes.OP_MAPPING)) def testParams(self): supported_by_all = set(["debug_level", "dry_run", "priority"]) self.assertTrue(opcodes_base.BaseOpCode not in opcodes.OP_MAPPING.values()) self.assertTrue(opcodes.OpCode not in opcodes.OP_MAPPING.values()) for cls in list(opcodes.OP_MAPPING.values()) + [opcodes.OpCode]: all_slots = cls.GetAllSlots() self.assertEqual(len(set(all_slots) & supported_by_all), 3, msg=("Opcode %s doesn't support all base" " parameters (%r)" % (cls.OP_ID, supported_by_all))) # All opcodes must have OP_PARAMS self.assertTrue(hasattr(cls, "OP_PARAMS"), msg="%s doesn't have OP_PARAMS" % cls.OP_ID) param_names = [name for (name, _, _, _) in cls.GetAllParams()] self.assertEqual(all_slots, param_names) # Without inheritance self.assertEqual(cls.__slots__, [name for (name, _, _, _) in cls.OP_PARAMS]) # This won't work if parameters are converted to a dictionary duplicates = utils.FindDuplicates(param_names) self.assertFalse(duplicates, msg=("Found duplicate parameters %r in %s" % (duplicates, cls.OP_ID))) # Check parameter definitions for attr_name, aval, test, doc in cls.GetAllParams(): self.assertTrue(attr_name) self.assertTrue(callable(test), msg=("Invalid type check for %s.%s" % (cls.OP_ID, attr_name))) self.assertTrue(doc is None or isinstance(doc, str)) if callable(aval): default_value = aval() self.assertFalse(callable(default_value), msg=("Default value of %s.%s returned by function" " is callable" % (cls.OP_ID, attr_name))) else: default_value = aval if aval is not ht.NoDefault and aval is not None: self.assertTrue(test(default_value), msg=("Default value of %s.%s does not verify" % (cls.OP_ID, attr_name))) # If any parameter has documentation, all others need to have it as well has_doc = [doc is not None for (_, _, _, doc) in cls.OP_PARAMS] self.assertTrue(not compat.any(has_doc) or compat.all(has_doc), msg="%s does not document all parameters" % cls) def testValidateNoModification(self): class OpTest(opcodes.OpCode): OP_PARAMS = [ ("nodef", None, ht.TString, None), ("wdef", "default", ht.TMaybeString, None), ("number", 0, ht.TInt, None), ("notype", None, ht.TAny, None), ] # Missing required parameter "nodef" op = OpTest() before = op.__getstate__() self.assertRaises(errors.OpPrereqError, op.Validate, False) self.assertTrue(op.nodef is None) self.assertEqual(op.wdef, "default") self.assertEqual(op.number, 0) self.assertTrue(op.notype is None) self.assertEqual(op.__getstate__(), before, msg="Opcode was modified") # Required parameter "nodef" is provided op = OpTest(nodef="foo") before = op.__getstate__() op.Validate(False) self.assertEqual(op.__getstate__(), before, msg="Opcode was modified") self.assertEqual(op.nodef, "foo") self.assertEqual(op.wdef, "default") self.assertEqual(op.number, 0) self.assertTrue(op.notype is None) # Missing required parameter "nodef" op = OpTest(wdef="hello", number=999) before = op.__getstate__() self.assertRaises(errors.OpPrereqError, op.Validate, False) self.assertTrue(op.nodef is None) self.assertTrue(op.notype is None) self.assertEqual(op.__getstate__(), before, msg="Opcode was modified") # Wrong type for "nodef" op = OpTest(nodef=987) before = op.__getstate__() self.assertRaises(errors.OpPrereqError, op.Validate, False) self.assertEqual(op.nodef, 987) self.assertTrue(op.notype is None) self.assertEqual(op.__getstate__(), before, msg="Opcode was modified") # Testing different types for "notype" op = OpTest(nodef="foo", notype=[1, 2, 3]) before = op.__getstate__() op.Validate(False) self.assertEqual(op.nodef, "foo") self.assertEqual(op.notype, [1, 2, 3]) self.assertEqual(op.__getstate__(), before, msg="Opcode was modified") op = OpTest(nodef="foo", notype="Hello World") before = op.__getstate__() op.Validate(False) self.assertEqual(op.nodef, "foo") self.assertEqual(op.notype, "Hello World") self.assertEqual(op.__getstate__(), before, msg="Opcode was modified") def testValidateSetDefaults(self): class OpTest(opcodes.OpCode): OP_PARAMS = [ ("value1", "default", ht.TMaybeString, None), ("value2", "result", ht.TMaybeString, None), ] op = OpTest() op.Validate(True) self.assertEqual(op.value1, "default") self.assertEqual(op.value2, "result") self.assertTrue(op.dry_run is None) self.assertTrue(op.debug_level is None) self.assertEqual(op.priority, constants.OP_PRIO_DEFAULT) op = OpTest(value1="hello", value2="world", debug_level=123) op.Validate(True) self.assertEqual(op.value1, "hello") self.assertEqual(op.value2, "world") self.assertEqual(op.debug_level, 123) def testOpInstanceMultiAlloc(self): inst = dict([(name, []) for name in opcodes.OpInstanceCreate.GetAllSlots()]) inst_op = opcodes.OpInstanceCreate(**inst) inst_state = inst_op.__getstate__() multialloc = opcodes.OpInstanceMultiAlloc(instances=[inst_op]) state = multialloc.__getstate__() self.assertEqual(state["instances"], [inst_state]) loaded_multialloc = opcodes.OpCode.LoadOpCode(state) (loaded_inst,) = loaded_multialloc.instances self.assertNotEqual(loaded_inst, inst_op) self.assertEqual(loaded_inst.__getstate__(), inst_state) class TestOpcodeDepends(unittest.TestCase): def test(self): check_relative = opcodes_base.BuildJobDepCheck(True) check_norelative = opcodes_base.TNoRelativeJobDependencies for fn in [check_relative, check_norelative]: self.assertTrue(fn(None)) self.assertTrue(fn([])) self.assertTrue(fn([(1, [])])) self.assertTrue(fn([(719833, [])])) self.assertTrue(fn([("24879", [])])) self.assertTrue(fn([(2028, [constants.JOB_STATUS_ERROR])])) self.assertTrue(fn([ (2028, [constants.JOB_STATUS_ERROR]), (18750, []), (5063, [constants.JOB_STATUS_SUCCESS, constants.JOB_STATUS_ERROR]), ])) self.assertFalse(fn(1)) self.assertFalse(fn([(9, )])) self.assertFalse(fn([(15194, constants.JOB_STATUS_ERROR)])) for i in [ [(-1, [])], [(-27740, [constants.JOB_STATUS_CANCELED, constants.JOB_STATUS_ERROR]), (-1, [constants.JOB_STATUS_ERROR]), (9921, [])], ]: self.assertTrue(check_relative(i)) self.assertFalse(check_norelative(i)) class TestResultChecks(unittest.TestCase): def testJobIdList(self): for i in [[], [(False, "error")], [(False, "")], [(True, 123), (True, "999")]]: self.assertTrue(ht.TJobIdList(i)) for i in ["", [("x", 1)], [[], []], [[False, "", None], [True, 123]]]: self.assertFalse(ht.TJobIdList(i)) def testJobIdListOnly(self): self.assertTrue(ht.TJobIdListOnly({ constants.JOB_IDS_KEY: [], })) self.assertTrue(ht.TJobIdListOnly({ constants.JOB_IDS_KEY: [(True, "9282")], })) self.assertFalse(ht.TJobIdListOnly({ "x": None, })) self.assertFalse(ht.TJobIdListOnly({ constants.JOB_IDS_KEY: [], "x": None, })) self.assertFalse(ht.TJobIdListOnly({ constants.JOB_IDS_KEY: [("foo", "bar")], })) self.assertFalse(ht.TJobIdListOnly({ constants.JOB_IDS_KEY: [("one", "two", "three")], })) class TestOpInstanceSetParams(unittest.TestCase): def _GenericTests(self, fn): self.assertTrue(fn([])) self.assertTrue(fn([(constants.DDM_ADD, {})])) self.assertTrue(fn([(constants.DDM_ATTACH, {})])) self.assertTrue(fn([(constants.DDM_REMOVE, {})])) self.assertTrue(fn([(constants.DDM_DETACH, {})])) for i in [0, 1, 2, 3, 9, 10, 1024]: self.assertTrue(fn([(i, {})])) self.assertFalse(fn(None)) self.assertFalse(fn({})) self.assertFalse(fn("")) self.assertFalse(fn(0)) self.assertFalse(fn([(-100, {})])) self.assertFalse(fn([(constants.DDM_ADD, 2, 3)])) self.assertFalse(fn([[constants.DDM_ADD]])) def testNicModifications(self): fn = ht.TSetParamsMods(ht.TINicParams) self._GenericTests(fn) for param in constants.INIC_PARAMS: self.assertTrue(fn([[constants.DDM_ADD, {param: None}]])) self.assertTrue(fn([[constants.DDM_ADD, {param: param}]])) def testDiskModifications(self): fn = ht.TSetParamsMods(ht.TIDiskParams) self._GenericTests(fn) for param in constants.IDISK_PARAMS: self.assertTrue(fn([[constants.DDM_ADD, {param: 0}]])) self.assertTrue(fn([[constants.DDM_ADD, {param: param}]])) self.assertTrue(fn([[constants.DDM_ATTACH, {param: param}]])) if __name__ == "__main__": testutils.GanetiTestProgram()
#!/usr/bin/python2 """ dynamicEndpoints.py: make cjdns reliably connect to remote nodes with dynamic IP addresses, identified by a DNS name. Requires a config file with a section for each dynamic-IP node, like this: [lhjs0njqtvh1z4p2922bbyp2mksmyzf5lb63kvs3ppy78y1dj130.k] hostname: verge.info.tm port: 6324 password: ns6vn00hw0buhrtc4wbk8sv230 The section name (in square brackets) is the public key of the node. Then the hostname, port, and peering password for the node are given. By default, this program looks up the current Internet IP of each node defined in the config file, and add that node at that IP to the local cjdns instance. Unless the --noWait option is given, or the $nowait environment variable is true, the program then continues running, waiting for cjdns to log messages about those peers being unresponsive and updating the peers' Internet IP addresses as needed. If cjdns dies while the program is monitoring for messages, the program will hang indefinitely. Requires that the $HOME/.cjdnsadmin file be correctly set up. See cjdnsadminmaker.py if that is not the case. """ # You may redistribute this program 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 cjdnsadmin.cjdnsadmin import connectWithAdminInfo; from cjdnsadmin.publicToIp6 import PublicToIp6_convert; from cjdnsadmin.bencode import * import sys import socket, re import select import time import os import logging import argparse import ConfigParser # This holds a regex that matches the message we get from the roiuter when it # sees an unresponsive peer. IS_UNRESPONSIVE = re.compile( "Pinging unresponsive peer \\[(.*\\.k)\\] lag \\[.*\\]") # Make sure that it works assert(IS_UNRESPONSIVE.match("Pinging unresponsive peer " + "[6fmmn3qurcjg6d8hplq1rrcsspfhvm1900s13f3p5bv2bb4f4mm0.k] lag [207147]")) # What file and line do these messages come from? TODO: don't depend so tightly # on the other end of the codebase. Use the API to watch peers. MESSAGE_FILE = "InterfaceController.c" MESSAGE_LINE = 252 class Node(object): """ Represents a remote peer. A remoter peer has: - A hostname to repeatedly look up - A port to connect to - A password to connect with - A public key to authenticate the remote peer with - A last known Internet IP address. """ __slots__ = ("host","port","password","key","lastAddr") def __init__(self,host,port,password,key): self.host = host self.port = port self.password = password self.key = key self.lastAddr = None class DynamicEndpointWatcher(object): """ Encapsulates all the stuff we need to actually keep an eye on our remote nodes and see if they change IPs. When a node with a dynamic IP is unresponsive, we look up its IP address and tell cjdns to go connect to it. """ def __init__(self, cjdns, configuration): """ Set up a new DynamicEndpointWatcher operating on the given CJDNS admin connection, using the specified ConfigParser parsed configuration. """ # Keep the cjdns admin connection self.cjdns = cjdns # Holds a dict from public key string to Node object for the remote # peer, for all known nodes. self.nodes = dict() # Holds a dict from public key to Node object for those nodes which are # unresponsive. self.unresponsive = dict() # Holds a cjdns log message subscription to messages about unresponsive # nodes. Note that this points specifically to a source line number in # the cjdns C code and is thus going to break whenever anyone touches # that file. TODO: check node responsiveness through the API. self.sub = self.cjdns.AdminLog_subscribe(MESSAGE_LINE, MESSAGE_FILE, 'DEBUG') # Add nodes from the given ConfigParser parser. for section in configuration.sections(): # Each section is named with a node key, and contains a # hostname, port, and password. peerHostname = configuration.get(section, "hostname") peerPort = configuration.get(section, "port") peerPassword = configuration.get(section, "password") # Add the node self.addNode(peerHostname, peerPort, peerPassword, section) if self.sub['error'] == 'none': # We successfully subscribed to messages. Add all the nodes we're # supposed to watch. for node in self.nodes.values(): self.lookup(node) logging.info("{} peers added!".format(len(self.nodes))) else: logging.error(self.sub) def run(self): """ Run forever, monitoring the peers we are responsible for. """ logging.info("Watching for unresponsive peers") # Watch for any messages from our log message subscription. self.recieve(self.sub['txid']) def addNode(self, host, port, password, key): """ Add a new remote peer with the given hostname, port, password, and public key. Does not automatically try to connect to the remote node. """ self.nodes[key] = Node(host, port, password, key) def lookup(self, node): """ Look up the current IP address for the given Node object, and tell the cjdns router to try to connect to it. """ try: # Use AF_INET here to make sure we don't get an IPv6 address and try # to connect to it when the cjdns UDPInterface is using only IPv4. # TODO: Make cjdns bind its UDPInterface to IPv6 as well as IPv4. for info in socket.getaddrinfo(node.host,node.port, socket.AF_INET,socket.SOCK_DGRAM): # For every IP address the node has in DNS, with the port we # wanted attached... # Save the address we get in a field in the node. sockaddr = info[-1] node.lastAddr = sockaddr # Grab the IP:port string sockaddr = sockaddr[0] + ":" + str(sockaddr[1]) # Announce we are going to connect logging.info("Connecting to {} at {}".format( PublicToIp6_convert(node.key), sockaddr)) # Tell CJDNS to begin a UDPInterface connection to the given # IP:port, with the given public key and password. Always use # the 0th UDPInterface, which is the default. reply = self.cjdns.UDPInterface_beginConnection( password=node.password, publicKey=node.key, address=sockaddr) if reply["error"] != "none": # The router didn't like our request. Complain. logging.error( "Router refuses to connect to remote peer. {}".format( reply["error"])) # Maybe try the next address? break # Mark this node as no longer unresponsive try: del self.unresponsive[node.key] except KeyError: pass # Don't try any more addresses. Stop after the first. return except socket.gaierror as e: # The lookup failed at the OS level. Did we put in a bad hostname? logging.error("Could not resolve DNS name {}: {}".format( node.host, e)) # If we get here, we found no addresses that worked. logging.error("No working addresses found for node {}".format( PublicToIp6_convert(node.key))) def doLog(self, message): """ Process a log line from cjdns to see if it indicates that a peer we are responsible for is unresponsive. """ logging.debug(message) # Short-circuit messages that start with the wrong l;etter and can't # possibly match. if message[0]!='P': return; # Test plausible messages against the regex p = IS_UNRESPONSIVE.match(message) # If they don't match, ignore them. if not p: return # Otherwise, get the key of the unresponsive node from the regex match # group. downKey = p.group(1) # And get the nodfe for that key node = self.nodes.get(downKey,None) if not node: # Complain we aren't responsible for that node. logging.warning("Unmonitored neighbor {} is down".format( PublicToIp6_convert(downKey))) return # Otherwise, announce we are doing our job. logging.warning("Monitored neighbor {} is down.".format( PublicToIp6_convert(downKey))) # If we are responsible for it, register it as unresponsive. self.unresponsive[downKey] = node # Go get its address and try reconnecting. self.lookup(node) def recieve(self, txid): """ Loop forever porcessing messages from the cjdns router. Takes a txid pointing to the subscription to such messages. """ while True: # Repeatedly get and process log messages. self.doLog(self.cjdns.getMessage(txid)["message"]) def main(argv): """ Run the program. """ # Set up logging. See the logging module docs. logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.INFO) # Parse command-line arguments. Make sure to give our docstring as program # help. parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("configFile", type=argparse.FileType("r"), help="configuration file of hosts to read") parser.add_argument("--noWait", action="store_true", help="look up dynamic peers once and exit") # Parse all the command-line arguments options = parser.parse_args(argv[1:]) # Now we can load the config file. It is now required. # Maker a new parser to parse the config file parsedConfig = ConfigParser.SafeConfigParser() # Be case sensitive parsedConfig.optionxform = str # Read the config from the file parsedConfig.readfp(options.configFile) # Connect to the router cjdns = connectWithAdminInfo() # Make a new watcher on that connection, with the config from the config # file. This automatically looks up all the peers and tries to connect to # them once. watcher = DynamicEndpointWatcher(cjdns, parsedConfig) if options.noWait or os.environ.get('nowait', False): # We're not supposed to wait. Quit while we're ahead sys.exit(0) else: # Monitor for unresponsive nodes. This will loop until cjdns restarts, # at which point it will keep looping but won't actually work anymore. watcher.run() if __name__ == "__main__": # Run our main method sys.exit(main(sys.argv))
""" Helper functions for writing to terminals and files. """ import sys, os, unicodedata import py py3k = sys.version_info[0] >= 3 py33 = sys.version_info >= (3, 3) from py.builtin import text, bytes win32_and_ctypes = False colorama = None if sys.platform == "win32": try: import colorama except ImportError: try: import ctypes win32_and_ctypes = True except ImportError: pass def _getdimensions(): if py33: import shutil size = shutil.get_terminal_size() return size.lines, size.columns else: import termios, fcntl, struct call = fcntl.ioctl(1, termios.TIOCGWINSZ, "\000" * 8) height, width = struct.unpack("hhhh", call)[:2] return height, width def get_terminal_width(): width = 0 try: _, width = _getdimensions() except py.builtin._sysex: raise except: # pass to fallback below pass if width == 0: # FALLBACK: # * some exception happened # * or this is emacs terminal which reports (0,0) width = int(os.environ.get('COLUMNS', 80)) # XXX the windows getdimensions may be bogus, let's sanify a bit if width < 40: width = 80 return width terminal_width = get_terminal_width() char_width = { 'A': 1, # "Ambiguous" 'F': 2, # Fullwidth 'H': 1, # Halfwidth 'N': 1, # Neutral 'Na': 1, # Narrow 'W': 2, # Wide } def get_line_width(text): text = unicodedata.normalize('NFC', text) return sum(char_width.get(unicodedata.east_asian_width(c), 1) for c in text) # XXX unify with _escaped func below def ansi_print(text, esc, file=None, newline=True, flush=False): if file is None: file = sys.stderr text = text.rstrip() if esc and not isinstance(esc, tuple): esc = (esc,) if esc and sys.platform != "win32" and file.isatty(): text = (''.join(['\x1b[%sm' % cod for cod in esc]) + text + '\x1b[0m') # ANSI color code "reset" if newline: text += '\n' if esc and win32_and_ctypes and file.isatty(): if 1 in esc: bold = True esc = tuple([x for x in esc if x != 1]) else: bold = False esctable = {() : FOREGROUND_WHITE, # normal (31,): FOREGROUND_RED, # red (32,): FOREGROUND_GREEN, # green (33,): FOREGROUND_GREEN|FOREGROUND_RED, # yellow (34,): FOREGROUND_BLUE, # blue (35,): FOREGROUND_BLUE|FOREGROUND_RED, # purple (36,): FOREGROUND_BLUE|FOREGROUND_GREEN, # cyan (37,): FOREGROUND_WHITE, # white (39,): FOREGROUND_WHITE, # reset } attr = esctable.get(esc, FOREGROUND_WHITE) if bold: attr |= FOREGROUND_INTENSITY STD_OUTPUT_HANDLE = -11 STD_ERROR_HANDLE = -12 if file is sys.stderr: handle = GetStdHandle(STD_ERROR_HANDLE) else: handle = GetStdHandle(STD_OUTPUT_HANDLE) oldcolors = GetConsoleInfo(handle).wAttributes attr |= (oldcolors & 0x0f0) SetConsoleTextAttribute(handle, attr) while len(text) > 32768: file.write(text[:32768]) text = text[32768:] if text: file.write(text) SetConsoleTextAttribute(handle, oldcolors) else: file.write(text) if flush: file.flush() def should_do_markup(file): if os.environ.get('PY_COLORS') == '1': return True if os.environ.get('PY_COLORS') == '0': return False if 'NO_COLOR' in os.environ: return False return hasattr(file, 'isatty') and file.isatty() \ and os.environ.get('TERM') != 'dumb' \ and not (sys.platform.startswith('java') and os._name == 'nt') class TerminalWriter(object): _esctable = dict(black=30, red=31, green=32, yellow=33, blue=34, purple=35, cyan=36, white=37, Black=40, Red=41, Green=42, Yellow=43, Blue=44, Purple=45, Cyan=46, White=47, bold=1, light=2, blink=5, invert=7) # XXX deprecate stringio argument def __init__(self, file=None, stringio=False, encoding=None): if file is None: if stringio: self.stringio = file = py.io.TextIO() else: from sys import stdout as file elif py.builtin.callable(file) and not ( hasattr(file, "write") and hasattr(file, "flush")): file = WriteFile(file, encoding=encoding) if hasattr(file, "isatty") and file.isatty() and colorama: file = colorama.AnsiToWin32(file).stream self.encoding = encoding or getattr(file, 'encoding', "utf-8") self._file = file self.hasmarkup = should_do_markup(file) self._lastlen = 0 self._chars_on_current_line = 0 self._width_of_current_line = 0 @property def fullwidth(self): if hasattr(self, '_terminal_width'): return self._terminal_width return get_terminal_width() @fullwidth.setter def fullwidth(self, value): self._terminal_width = value @property def chars_on_current_line(self): """Return the number of characters written so far in the current line. Please note that this count does not produce correct results after a reline() call, see #164. .. versionadded:: 1.5.0 :rtype: int """ return self._chars_on_current_line @property def width_of_current_line(self): """Return an estimate of the width so far in the current line. .. versionadded:: 1.6.0 :rtype: int """ return self._width_of_current_line def _escaped(self, text, esc): if esc and self.hasmarkup: text = (''.join(['\x1b[%sm' % cod for cod in esc]) + text +'\x1b[0m') return text def markup(self, text, **kw): esc = [] for name in kw: if name not in self._esctable: raise ValueError("unknown markup: %r" %(name,)) if kw[name]: esc.append(self._esctable[name]) return self._escaped(text, tuple(esc)) def sep(self, sepchar, title=None, fullwidth=None, **kw): if fullwidth is None: fullwidth = self.fullwidth # the goal is to have the line be as long as possible # under the condition that len(line) <= fullwidth if sys.platform == "win32": # if we print in the last column on windows we are on a # new line but there is no way to verify/neutralize this # (we may not know the exact line width) # so let's be defensive to avoid empty lines in the output fullwidth -= 1 if title is not None: # we want 2 + 2*len(fill) + len(title) <= fullwidth # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth # 2*len(sepchar)*N <= fullwidth - len(title) - 2 # N <= (fullwidth - len(title) - 2) // (2*len(sepchar)) N = max((fullwidth - len(title) - 2) // (2*len(sepchar)), 1) fill = sepchar * N line = "%s %s %s" % (fill, title, fill) else: # we want len(sepchar)*N <= fullwidth # i.e. N <= fullwidth // len(sepchar) line = sepchar * (fullwidth // len(sepchar)) # in some situations there is room for an extra sepchar at the right, # in particular if we consider that with a sepchar like "_ " the # trailing space is not important at the end of the line if len(line) + len(sepchar.rstrip()) <= fullwidth: line += sepchar.rstrip() self.line(line, **kw) def write(self, msg, **kw): if msg: if not isinstance(msg, (bytes, text)): msg = text(msg) self._update_chars_on_current_line(msg) if self.hasmarkup and kw: markupmsg = self.markup(msg, **kw) else: markupmsg = msg write_out(self._file, markupmsg) def _update_chars_on_current_line(self, text_or_bytes): newline = b'\n' if isinstance(text_or_bytes, bytes) else '\n' current_line = text_or_bytes.rsplit(newline, 1)[-1] if isinstance(current_line, bytes): current_line = current_line.decode('utf-8', errors='replace') if newline in text_or_bytes: self._chars_on_current_line = len(current_line) self._width_of_current_line = get_line_width(current_line) else: self._chars_on_current_line += len(current_line) self._width_of_current_line += get_line_width(current_line) def line(self, s='', **kw): self.write(s, **kw) self._checkfill(s) self.write('\n') def reline(self, line, **kw): if not self.hasmarkup: raise ValueError("cannot use rewrite-line without terminal") self.write(line, **kw) self._checkfill(line) self.write('\r') self._lastlen = len(line) def _checkfill(self, line): diff2last = self._lastlen - len(line) if diff2last > 0: self.write(" " * diff2last) class Win32ConsoleWriter(TerminalWriter): def write(self, msg, **kw): if msg: if not isinstance(msg, (bytes, text)): msg = text(msg) self._update_chars_on_current_line(msg) oldcolors = None if self.hasmarkup and kw: handle = GetStdHandle(STD_OUTPUT_HANDLE) oldcolors = GetConsoleInfo(handle).wAttributes default_bg = oldcolors & 0x00F0 attr = default_bg if kw.pop('bold', False): attr |= FOREGROUND_INTENSITY if kw.pop('red', False): attr |= FOREGROUND_RED elif kw.pop('blue', False): attr |= FOREGROUND_BLUE elif kw.pop('green', False): attr |= FOREGROUND_GREEN elif kw.pop('yellow', False): attr |= FOREGROUND_GREEN|FOREGROUND_RED else: attr |= oldcolors & 0x0007 SetConsoleTextAttribute(handle, attr) write_out(self._file, msg) if oldcolors: SetConsoleTextAttribute(handle, oldcolors) class WriteFile(object): def __init__(self, writemethod, encoding=None): self.encoding = encoding self._writemethod = writemethod def write(self, data): if self.encoding: data = data.encode(self.encoding, "replace") self._writemethod(data) def flush(self): return if win32_and_ctypes: TerminalWriter = Win32ConsoleWriter import ctypes from ctypes import wintypes # ctypes access to the Windows console STD_OUTPUT_HANDLE = -11 STD_ERROR_HANDLE = -12 FOREGROUND_BLACK = 0x0000 # black text FOREGROUND_BLUE = 0x0001 # text color contains blue. FOREGROUND_GREEN = 0x0002 # text color contains green. FOREGROUND_RED = 0x0004 # text color contains red. FOREGROUND_WHITE = 0x0007 FOREGROUND_INTENSITY = 0x0008 # text color is intensified. BACKGROUND_BLACK = 0x0000 # background color black BACKGROUND_BLUE = 0x0010 # background color contains blue. BACKGROUND_GREEN = 0x0020 # background color contains green. BACKGROUND_RED = 0x0040 # background color contains red. BACKGROUND_WHITE = 0x0070 BACKGROUND_INTENSITY = 0x0080 # background color is intensified. SHORT = ctypes.c_short class COORD(ctypes.Structure): _fields_ = [('X', SHORT), ('Y', SHORT)] class SMALL_RECT(ctypes.Structure): _fields_ = [('Left', SHORT), ('Top', SHORT), ('Right', SHORT), ('Bottom', SHORT)] class CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure): _fields_ = [('dwSize', COORD), ('dwCursorPosition', COORD), ('wAttributes', wintypes.WORD), ('srWindow', SMALL_RECT), ('dwMaximumWindowSize', COORD)] _GetStdHandle = ctypes.windll.kernel32.GetStdHandle _GetStdHandle.argtypes = [wintypes.DWORD] _GetStdHandle.restype = wintypes.HANDLE def GetStdHandle(kind): return _GetStdHandle(kind) SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute SetConsoleTextAttribute.argtypes = [wintypes.HANDLE, wintypes.WORD] SetConsoleTextAttribute.restype = wintypes.BOOL _GetConsoleScreenBufferInfo = \ ctypes.windll.kernel32.GetConsoleScreenBufferInfo _GetConsoleScreenBufferInfo.argtypes = [wintypes.HANDLE, ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO)] _GetConsoleScreenBufferInfo.restype = wintypes.BOOL def GetConsoleInfo(handle): info = CONSOLE_SCREEN_BUFFER_INFO() _GetConsoleScreenBufferInfo(handle, ctypes.byref(info)) return info def _getdimensions(): handle = GetStdHandle(STD_OUTPUT_HANDLE) info = GetConsoleInfo(handle) # Substract one from the width, otherwise the cursor wraps # and the ending \n causes an empty line to display. return info.dwSize.Y, info.dwSize.X - 1 def write_out(fil, msg): # XXX sometimes "msg" is of type bytes, sometimes text which # complicates the situation. Should we try to enforce unicode? try: # on py27 and above writing out to sys.stdout with an encoding # should usually work for unicode messages (if the encoding is # capable of it) fil.write(msg) except UnicodeEncodeError: # on py26 it might not work because stdout expects bytes if fil.encoding: try: fil.write(msg.encode(fil.encoding)) except UnicodeEncodeError: # it might still fail if the encoding is not capable pass else: fil.flush() return # fallback: escape all unicode characters msg = msg.encode("unicode-escape").decode("ascii") fil.write(msg) fil.flush()
# Copyright 2014 Open Source Robotics Foundation, 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. from __future__ import print_function import os import re import sys from multiprocessing import cpu_count from catkin_tools.common import wide_log def add_context_args(parser): """Add common workspace and profile args to an argparse parser. :param parser: The python argparse parser object (or subparser) :type parser: ArgumentParser """ add = parser.add_argument add_workspace_arg(parser) add('--profile', default=None, help='The name of a config profile to use (default: active profile)') def add_workspace_arg(parser): """Add common workspace arg to an argparse parser. :param parser: The python argparse parser object (or subparser) :type parser: ArgumentParser """ add = parser.add_argument add('--workspace', '-w', default=None, help='The path to the catkin_tools workspace or a directory contained within it (default: ".")') def add_cmake_and_make_and_catkin_make_args(parser): """Add common make and cmake args to an argparse parser. :param parser: The python argparse parser object (or subparser) :type parser: ArgumentParser """ add = parser.add_argument add('--parallel-jobs', '--parallel', '-p', default=None, help='Maximum number of packages which could be built in parallel (default is cpu count)') add = parser.add_mutually_exclusive_group().add_argument add('--cmake-args', metavar='ARG', dest='cmake_args', nargs='+', required=False, type=str, default=None, help='Arbitrary arguments which are passes to CMake. ' 'It collects all of following arguments until a "--" is read.') add('--no-cmake-args', dest='cmake_args', action='store_const', const='A', default=None, help='Pass no additional arguments to CMake.') add = parser.add_mutually_exclusive_group().add_argument add('--make-args', metavar='ARG', dest='make_args', nargs='+', required=False, type=str, default=None, help='Arbitrary arguments which are passes to make.' 'It collects all of following arguments until a "--" is read.') add('--no-make-args', dest='make_args', action='store_const', const=[], default=None, help='Pass no additional arguments to make (does not affect --catkin-make-args).') add = parser.add_mutually_exclusive_group().add_argument add('--catkin-make-args', metavar='ARG', dest='catkin_make_args', nargs='+', required=False, type=str, default=None, help='Arbitrary arguments which are passes to make but only for catkin packages.' 'It collects all of following arguments until a "--" is read.') add('--no-catkin-make-args', dest='catkin_make_args', action='store_const', const=[], default=None, help='Pass no additional arguments to make for catkin packages (does not affect --make-args).') def _extract_cmake_and_make_arguments(args, extract_catkin_make): """Extract arguments which are meant to be passed to CMake and GNU Make through the catkin_tools command line interface. :param args: system arguments from which special arguments need to be extracted :type args: list :returns: tuple of separate args, cmake_args, make args, and catkin make args :rtype: tuple """ cmake_args = [] make_args = [] catkin_make_args = [] arg_types = {} if '--no-cmake-args' not in args: arg_types['--cmake-args'] = cmake_args if '--no-make-args' not in args: arg_types['--make-args'] = make_args if extract_catkin_make and '--no-catkin_make_args' not in args: arg_types['--catkin-make-args'] = catkin_make_args # Determine where each arg type starts # Map from arg indices to arg types arg_indexes = {} for arg_type in arg_types.keys(): if arg_type in args: arg_indexes[args.index(arg_type)] = arg_type def split_arguments(args, splitter_name): if splitter_name not in args: return args, None start_index = args.index(splitter_name) end_index = args.index('--', start_index + 1) if '--' in args else None if end_index: return args[0:index] + args[end_index + 1:], args[index + 1:end_index] else: return args[0:index], args[index + 1:] for index in reversed(sorted(arg_indexes.keys())): arg_type = arg_indexes[index] args, specific_args = split_arguments(args, arg_type) arg_types[arg_type].extend(specific_args) # classify -D* and -G* arguments as cmake specific arguments if '--cmake-args' in arg_types: implicit_cmake_args = [a for a in args if a.startswith('-D') or a.startswith('-G')] args = [a for a in args if a not in implicit_cmake_args] cmake_args = implicit_cmake_args + cmake_args if '--no-cmake-args' not in args and len(cmake_args) == 0: cmake_args = None if '--no-make-args' not in args and len(make_args) == 0: make_args = None if extract_catkin_make and '--no-catkin_make_args' not in args and len(catkin_make_args) == 0: catkin_make_args = None return args, cmake_args, make_args, catkin_make_args def extract_cmake_and_make_and_catkin_make_arguments(args): """Extracts cmake, make, and catkin specific make arguments from given system arguments :param args: system arguments from which special arguments need to be extracted :type args: list :returns: tuple of separate args, cmake_args, make args, and catkin make args :rtype: tuple """ return _extract_cmake_and_make_arguments(args, extract_catkin_make=True) def extract_cmake_and_make_arguments(args): """Extracts cmake and make arguments from the given system arguments :param args: system arguments from which special arguments need to be extracted :type args: list :returns: tuple of separate args, cmake_args, and make_args :rtype: tuple """ args, cmake_args, make_args, _ = _extract_cmake_and_make_arguments(args, extract_catkin_make=False) return args, cmake_args, make_args def extract_jobs_flags(mflags): """Extracts make job flags from a list of other make flags, i.e. -j8 -l8 :param mflags: string of space separated make arguments :type mflags: str :returns: space separated list of make jobs flags :rtype: str """ regex = r'(?:^|\s)(-?(?:j|l)(?:\s*[0-9]+|\s|$))' + \ r'|' + \ r'(?:^|\s)((?:--)?(?:jobs|load-average)(?:(?:=|\s+)[0-9]+|(?:\s|$)))' matches = re.findall(regex, mflags) or [] matches = [m[0] or m[1] for m in matches] return ' '.join([m.strip() for m in matches]) if matches else None def handle_make_arguments(input_make_args, force_single_threaded_when_running_tests=False): """Special handling for make arguments. If force_single_threaded_when_running_tests is True, jobs flags are replaced with -j1, because tests cannot handle parallelization. If no job flags are present and there are none in the MAKEFLAGS environment variable, then make flags are set to the cpu_count, e.g. -j4 -l4. :param input_make_args: list of make arguments to be handled :type input_make_args: list :param force_single_threaded_when_running_tests: self explanatory :type force_single_threaded_when_running_tests: bool :returns: copied list of make arguments, potentially with some modifications :rtype: list """ make_args = list(input_make_args) if force_single_threaded_when_running_tests: # force single threaded execution when running test since rostest does not support multiple parallel runs run_tests = [a for a in make_args if a.startswith('run_tests')] if run_tests: wide_log('Forcing "-j1" for running unit tests.') make_args.append('-j1') # If no -j/--jobs/-l/--load-average flags are in make_args if not extract_jobs_flags(' '.join(make_args)): # If -j/--jobs/-l/--load-average are in MAKEFLAGS if 'MAKEFLAGS' in os.environ and extract_jobs_flags(os.environ['MAKEFLAGS']): # Do not extend make arguments, let MAKEFLAGS set things pass else: # Else extend the make_arguments to include some jobs flags # Use the number of CPU cores try: jobs = cpu_count() make_args.append('-j{0}'.format(jobs)) make_args.append('-l{0}'.format(jobs)) except NotImplementedError: # If the number of cores cannot be determined, do not extend args pass return make_args def argument_preprocessor(args): """Perform processing of argument patterns which are not captured by argparse, before being passed to argparse :param args: system arguments from which special arguments need to be extracted :type args: list :returns: a tuple contianing a list of the arguments which can be handled by argparse and a dict of the extra arguments which this function has extracted :rtype: tuple """ # CMake/make pass-through flags collect dashed options. They require special # handling or argparse will complain about unrecognized options. # NOTE: http://bugs.python.org/issue9334 args = sys.argv[1:] if args is None else args extract_make_args = extract_cmake_and_make_and_catkin_make_arguments args, cmake_args, make_args, catkin_make_args = extract_make_args(args) # Extract make jobs flags. jobs_flags = extract_jobs_flags(' '.join(args)) or [] if jobs_flags: args = re.sub(jobs_flags, '', ' '.join(args)).split() jobs_flags = jobs_flags.split() extras = { 'cmake_args': cmake_args, 'make_args': make_args + jobs_flags if make_args else jobs_flags if jobs_flags else make_args, 'catkin_make_args': catkin_make_args, } return args, extras